问:
What is best practice of 'ThemeProvider' in styled-components?
I wanna know where <ThemeProvider/> should be placed in React app.

I'd come up with two solutions about it.

1, <ThemeProvider/> should be used 'Just Once' in top-root component
like index.js or App.js file created by 'create-react-app' tool.

2, <ThemeProvicer/> should be placed in 'Each root of React-component'
literally.

for clarification, I'll show you some example.
there is just two component, 'Red' and 'Blue'
 tag.

1, <ThemeProvider/> used 'Just Once'

```<code>// In './red.js'
import React from 'react'
import styled from "styled-components"

const Red = styled.div`background: ${props => props.theme.mainColor}`

export default function RedDiv() {
    return (
        //NOT using ThemeProvider
        <Red />
    )
}

</code>```

```<code>// In './blue.js'
......

const Blue = styled.div`background: ${props => props.theme.subColor}`

export default function BlueDiv() {
    return (
        <Blue />
    )
}

</code>```

```<code>// In './App.js'
import React, { Component } from 'react'
import { ThemeProvider } from "styled-components"
import myTheme from "./myTheme
import Red from "./red"
import Blue from "./blue"

export default class App extends Component {
    render() {
        return (
            //only used here just once
            <ThemeProvider theme={myTheme}>
                <>
                    <Red />
                    <Blue />
                </>
            </ThemeProvider>
        )
    }
}
</code>```

2, <ThemeProvider/> used 'Each root of React-component'

```<code>// In './red.js'
import React from 'react'
import styled, { ThemeProvider } from "styled-components"

const Red = styled.div`background: ${props => props.theme.mainColor} `

export default function RedDiv() {
    return (
        <ThemeProvider theme={myTheme}>
            <Red />
        </ThemeProvider>
    )
}

</code>```

```<code>// In './blue.js'
......

const Blue = styled.div`background: ${props => props.theme.mainColor}`

export default function BlueDiv() {
    return (
        <ThemeProvider theme={myTheme}>
            <Blue />
        </ThemeProvider>
    )
}

</code>```

```<code>// In './App.js'
import React, { Component } from 'react'
import Red from "./red"
import Blue from "./blue"

export default class App extends Component {
    render() {
        return (
            <>
                // <ThemeProvider/>  is not used
                <Red />
                <Blue />
            </>
        )
    }
}
</code>```

there is maybe some typo on the code above, but I hope that this example will convey my idea clearly.

答:
I use it only once, inside index.js.

Also a good place to add some global styles, if you need them. I use them for resetCSS (http://meyerweb.com/eric/tools/css/reset/) and some baseCSS rules like box-sizing etc.

index.js

```<code>import { createGlobalStyle, ThemeProvider } from 'styled-components';
import theme from './styles/theme';
import resetCSS from './styles/resetCSS';
import baseCSS from './styles/baseCSS';
import { BrowserRouter as Router} from "react-router-dom";

const GlobalStyle = createGlobalStyle`
  ${resetCSS}
  ${baseCSS}
`;

React.DOM.render(
  <React.Fragment>
    <GlobalStyle/>
    <Router>
      <ThemeProvider theme={theme}>
        <App/>
      </ThemeProvider>
    </Router>
  </React.Fragment>
  ,document.getElementById('root')
);
</code>```

Body:
I wanna know where <ThemeProvider/> should be placed in React app.

I'd come up with two solutions about it.

1, <ThemeProvider/> should be used 'Just Once' in top-root component
like index.js or App.js file created by 'create-react-app' tool.

2, <ThemeProvicer/> should be placed in 'Each root of React-component'
literally.

for clarification, I'll show you some example.
there is just two component, 'Red' and 'Blue'
 tag.

1, <ThemeProvider/> used 'Just Once'

// In './red.js'
import React from 'react'
import styled from "styled-components"

const Red = styled.div`background: ${props => props.theme.mainColor}`

export default function RedDiv() {
    return (
        //NOT using ThemeProvider
        <Red />
    )
}

// In './blue.js'
......

const Blue = styled.div`background: ${props => props.theme.subColor}`

export default function BlueDiv() {
    return (
        <Blue />
    )
}

// In './App.js'
import React, { Component } from 'react'
import { ThemeProvider } from "styled-components"
import myTheme from "./myTheme
import Red from "./red"
import Blue from "./blue"

export default class App extends Component {
    render() {
        return (
            //only used here just once
            <ThemeProvider theme={myTheme}>
                <>
                    <Red />
                    <Blue />
                </>
            </ThemeProvider>
        )
    }
}

2, <ThemeProvider/> used 'Each root of React-component'

// In './red.js'
import React from 'react'
import styled, { ThemeProvider } from "styled-components"

const Red = styled.div`background: ${props => props.theme.mainColor} `

export default function RedDiv() {
    return (
        <ThemeProvider theme={myTheme}>
            <Red />
        </ThemeProvider>
    )
}

// In './blue.js'
......

const Blue = styled.div`background: ${props => props.theme.mainColor}`

export default function BlueDiv() {
    return (
        <ThemeProvider theme={myTheme}>
            <Blue />
        </ThemeProvider>
    )
}

// In './App.js'
import React, { Component } from 'react'
import Red from "./red"
import Blue from "./blue"

export default class App extends Component {
    render() {
        return (
            <>
                // <ThemeProvider/>  is not used
                <Red />
                <Blue />
            </>
        )
    }
}

there is maybe some typo on the code above, but I hope that this example will convey my idea clearly.

Body:
I use it only once, inside index.js.

Also a good place to add some global styles, if you need them. I use them for resetCSS (http://meyerweb.com/eric/tools/css/reset/) and some baseCSS rules like box-sizing etc.

index.js

import { createGlobalStyle, ThemeProvider } from 'styled-components';
import theme from './styles/theme';
import resetCSS from './styles/resetCSS';
import baseCSS from './styles/baseCSS';
import { BrowserRouter as Router} from "react-router-dom";

const GlobalStyle = createGlobalStyle`
  ${resetCSS}
  ${baseCSS}
`;

React.DOM.render(
  <React.Fragment>
    <GlobalStyle/>
    <Router>
      <ThemeProvider theme={theme}>
        <App/>
      </ThemeProvider>
    </Router>
  </React.Fragment>
  ,document.getElementById('root')
);


来源: stackexchange

问:
Node npm error on windows looking for tools version
Im trying to use node and when i go to install the npm packages via 'npm install package.json'

I am currently using windows 8.1 as my os. It began when I started using redis but im not sure if it is because of redis.  The error I get is

MSBUILD : error MSB4132: The tools version "2.0" is unrecognized.
  Available tools versions are "4.0".

The full console print out is here

If anyone has come across this error and how to fix it would be greatly appreciated

答:
These  commands worked for me.

```<code> & npm --add-python-to-path='true' --debug install --global windows-build-tools
 & npm config set python "%USERPROFILE%\.windows-build-tools\python27\python.exe"
 & npm install -g windows-build-tools
 & npm install.
 & npm start.
</code>```

Solution found here

ContentLicense: CC BY-SA 3.0

Body:
These  commands worked for me.

 & npm --add-python-to-path='true' --debug install --global windows-build-tools
 & npm config set python "%USERPROFILE%\.windows-build-tools\python27\python.exe"
 & npm install -g windows-build-tools
 & npm install.
 & npm start.

Solution found here

ContentLicense: CC BY-SA 4.0


问:
How to find closer QGraphicsItem (in a QList) to the mouse x or the mouse y coords?
I'm trying to get which item is closer to the mouse coord.x or coord.y  I guess it is something like that, but don't get it after trying a lot. I got the mouse coordinates working it is just the part of the QList where I can't get it.</p>

```<code>void findcloser()
{
    QList<QGraphicsItem *> allitems = items();
    QList<QGraphicsItem *> alltypedos;
        foreach(auto item, allitems) {
        if(item->type() == chord::Type) {
           alltypedos.append(item);
        }
    }
    getcloser(alltypedos.begin(), alltypedos.end(), mouse.x);
    getcloser(alltypedos.begin(), alltypedos.end(), mouse.y);
}
</code>```

答:
The easiest way to calculate the distance between two points is to use QLineF class:

```<code>class GraphicsView: public QGraphicsView
{
    Q_OBJECT
public:
    GraphicsView(QWidget* parent=nullptr): QGraphicsView(parent){}

    virtual void mousePressEvent(QMouseEvent* event) override
    {
        // Take the position of the mouse in the scene coords
        QPointF const pos = mapToScene(event->pos());
        for(QGraphicsItem* item : scene()->items())
        {

            // Take the position of the items center
            QPointF itemPos = item->mapToScene(item->boundingRect().center());
            QLineF const distance(pos, itemPos);
            qDebug() << pos << itemPos << distance.length();
        }
        qDebug() << "---";
    }
};
</code>```

When you have the distance between an item and the mouse, it's just finding the lowest value:

```<code>virtual void mousePressEvent(QMouseEvent* event) override
{
    QPointF const pos = mapToScene(event->pos());
    QList<QGraphicsItem*> items = scene()->items();
    auto closest = std::min_element(items.begin(), items.end(), [pos](const QGraphicsItem* left, const QGraphicsItem* right)
    {
        QPointF const leftPos = left->mapToScene(left->boundingRect().center());
        QPointF const rightPos = right->mapToScene(right->boundingRect().center());
        QLineF const distanceLeft(pos, leftPos);
        QLineF const distanceRight(pos, rightPos);
        return distanceLeft.length() < distanceRight.length();
    });

    QGraphicsRectItem* item = dynamic_cast<QGraphicsRectItem*>(*closest);
    item->setBrush(Qt::red);
}
</code>```

Body:
I'm trying to get which item is closer to the mouse coord.x or coord.y  I guess it is something like that, but don't get it after trying a lot. I got the mouse coordinates working it is just the part of the QList where I can't get it.

void findcloser()
{
    QList<QGraphicsItem *> allitems = items();
    QList<QGraphicsItem *> alltypedos;
        foreach(auto item, allitems) {
        if(item->type() == chord::Type) {
           alltypedos.append(item);
        }
    }
    getcloser(alltypedos.begin(), alltypedos.end(), mouse.x);
    getcloser(alltypedos.begin(), alltypedos.end(), mouse.y);
}

Body:
The easiest way to calculate the distance between two points is to use QLineF class:

class GraphicsView: public QGraphicsView
{
    Q_OBJECT
public:
    GraphicsView(QWidget* parent=nullptr): QGraphicsView(parent){}

    virtual void mousePressEvent(QMouseEvent* event) override
    {
        // Take the position of the mouse in the scene coords
        QPointF const pos = mapToScene(event->pos());
        for(QGraphicsItem* item : scene()->items())
        {

            // Take the position of the items center
            QPointF itemPos = item->mapToScene(item->boundingRect().center());
            QLineF const distance(pos, itemPos);
            qDebug() << pos << itemPos << distance.length();
        }
        qDebug() << "---";
    }
};

When you have the distance between an item and the mouse, it's just finding the lowest value:

virtual void mousePressEvent(QMouseEvent* event) override
{
    QPointF const pos = mapToScene(event->pos());
    QList<QGraphicsItem*> items = scene()->items();
    auto closest = std::min_element(items.begin(), items.end(), [pos](const QGraphicsItem* left, const QGraphicsItem* right)
    {
        QPointF const leftPos = left->mapToScene(left->boundingRect().center());
        QPointF const rightPos = right->mapToScene(right->boundingRect().center());
        QLineF const distanceLeft(pos, leftPos);
        QLineF const distanceRight(pos, rightPos);
        return distanceLeft.length() < distanceRight.length();
    });

    QGraphicsRectItem* item = dynamic_cast<QGraphicsRectItem*>(*closest);
    item->setBrush(Qt::red);
}


问:
How to combine multiple Observable type arrays Observable<T[]>?
I'm running multiple queries on Firebase Firestore. They all (can) return an Observable. I would like to combine all Observable into ONE Observable.

I have tried different RxJS operators, like; combineLatest, forkJoin, concat, zip, merge and mergeMap. But I have not been able to achieve the desired result.

```<code>getPrivateBooksFromAuthors(authors): Observable<Book[]> {
    let bookRefs: Observable<Book[]>[] = [];
    authors.map(key => {
      bookRefs.push(this.afs.collection<Book>('books', ref =>
        ref.where('public', '==', false)
           .where('authors', 'array-contains', key)
        ).valueChanges())
    });
    return bookRefs[0]
}
</code>```

In the above piece of code I get all the private books from authors[0]. When I return concat(...bookRefs) or concat(bookRefs[0], bookRefs[1]), I still only get the books from authors[0]. I expect to get all the books from all the authors provided.

答:
@Doflamingo pointed us in the direction of forkJoin and @Llorenç gave a great code example with the map and reduce pipes to combine the Observables into one Observable. For me, the forkJoin failed if some authors didn't have Books. So I ended up going with combineLatest (which doesn't wait for all the Observables to be completed). This is my final code (all the credit goes to @Llorenç):

```<code>  mockBooks$(key): Observable<Book[]> {
    return this.afs.collection<Book>('books', ref =>
      ref.where('private', '==', true)
         .where('authors', 'array-contains', key)
      ).valueChanges()
    // return of([key + '-book1', key + '-book2', key + '-book3']);
  }

  getPrivateBooksFromAuthors(authors): Observable<Book[]> {
    let bookRefs: Observable<Book[]>[] = authors.map(key => this.mockBooks$(key));

     // return combineLatest(bookRefs).pipe(
     //     tap((books) => console.log('After forkJoin', books)),
     //     // You need this flattening operation!!
     //     map(books => books.reduce((acc, cur) => [...acc, ...cur], []) ));

     return combineLatest<Book[]>(bookRefs).pipe(
        map(arr => arr.reduce((acc, cur) => acc.concat(cur) ) ),
     )
  }
</code>```

I've commented out Llorenç's code, to show the difference. Thank you to both of you!

Body:
I'm running multiple queries on Firebase Firestore. They all (can) return an Observable. I would like to combine all Observable into ONE Observable.

I have tried different RxJS operators, like; combineLatest, forkJoin, concat, zip, merge and mergeMap. But I have not been able to achieve the desired result.

getPrivateBooksFromAuthors(authors): Observable<Book[]> {
    let bookRefs: Observable<Book[]>[] = [];
    authors.map(key => {
      bookRefs.push(this.afs.collection<Book>('books', ref =>
        ref.where('public', '==', false)
           .where('authors', 'array-contains', key)
        ).valueChanges())
    });
    return bookRefs[0]
}

In the above piece of code I get all the private books from authors[0]. When I return concat(...bookRefs) or concat(bookRefs[0], bookRefs[1]), I still only get the books from authors[0]. I expect to get all the books from all the authors provided.

Body:
@Doflamingo pointed us in the direction of forkJoin and @Llorenç gave a great code example with the map and reduce pipes to combine the Observables into one Observable. For me, the forkJoin failed if some authors didn't have Books. So I ended up going with combineLatest (which doesn't wait for all the Observables to be completed). This is my final code (all the credit goes to @Llorenç):

  mockBooks$(key): Observable<Book[]> {
    return this.afs.collection<Book>('books', ref =>
      ref.where('private', '==', true)
         .where('authors', 'array-contains', key)
      ).valueChanges()
    // return of([key + '-book1', key + '-book2', key + '-book3']);
  }

  getPrivateBooksFromAuthors(authors): Observable<Book[]> {
    let bookRefs: Observable<Book[]>[] = authors.map(key => this.mockBooks$(key));

     // return combineLatest(bookRefs).pipe(
     //     tap((books) => console.log('After forkJoin', books)),
     //     // You need this flattening operation!!
     //     map(books => books.reduce((acc, cur) => [...acc, ...cur], []) ));

     return combineLatest<Book[]>(bookRefs).pipe(
        map(arr => arr.reduce((acc, cur) => acc.concat(cur) ) ),
     )
  }

I've commented out Llorenç's code, to show the difference. Thank you to both of you!


问:
C# logic question
I have those boolean values:

```<code>bool test = false && true || true; // true
bool test1 = false && (true || true); // false
</code>```

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)

答:
In the first one && has precedence over || because you have not grouped explicitly.

In the second one, (...) lead to || being evaluated first.

Thus the differing results.

Title: C# logic question

Body:
I have those boolean values:

bool test = false && true || true; // true
bool test1 = false && (true || true); // false

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)


问:
Datatables issue with invalid JSON primitive draw
I have seen this question: Jquery Datatables Error: Invalid JSON primitive: draw

It could not help me solve the issue.

I am using Datatables, I get an error for the AJAX call. Here is the JS code:

```<code>function loadparttrackings() {
    // Call the datatable on the overview div and link back to server side
    $('#overviewFilteredPartTrackings').DataTable({
        "processing": true,
        "serverSide": true,
        "filter": true,
        "orderMulti": false,
        "ajax": {
            "url": window.applicationPath + "/Launches/GetFilteredPartTrackingRecords",
            "type": "POST",
            "data": function (d) {
                d.partNumber = $('#FilterPartNumber').val();
                d.segment = $('#FilterSegment').val();
                d.commodity = $('#FilterCommodity').val();
            }
        },
        // This is needed to hide the ID field and make it not searchable
        "columnDefs":
        [{
                "targets": [1],
                "visible": false,
                "searchable": false
        }],
        "columns": [

            {
                "render": function (data, type, full, meta) { return '<a class="btn btn-info" href="#" onclick=EditRecord("' + row.ID + '"); >Edit</a>'; }
            },
            // more columns omitted
    });
}
</code>```

The issue came up when I added the "type": "POST", to the AJAX part of the function. Now I get the error invalid json primitive draw.

Here is the code for the controller method:

```<code>[HttpPost]
    public ActionResult GetFilteredPartTrackingRecords(DataTableAjaxPostModel model, string partNumber, string commodity, string segment)
    {
        // Getting the data and such

        return Json(new
        {
            // this is what datatables wants sending back
            draw = model.draw,
            recordsTotal = 1000, // TODO CHANGE
            recordsFiltered = 1000, // TODO CHANGE
            data = result
        });
    }
</code>```

And here is the code for the model that I use:

```<code>public class DataTableAjaxPostModel
{
    // properties are not capital due to json mapping
    public int draw { get; set; }
    public int start { get; set; }
    public int length { get; set; }
    public List<Column> columns { get; set; }
    public Search search { get; set; }
    public List<Order> order { get; set; }
}

public class Column
{
    public string data { get; set; }
    public string name { get; set; }
    public bool searchable { get; set; }
    public bool orderable { get; set; }
    public Search search { get; set; }
}

public class Search
{
    public string value { get; set; }
    public string regex { get; set; }
}

public class Order
{
    public int column { get; set; }
    public string dir { get; set; }
}
</code>```

答:
I fixed it by doing the following:

remove the type: post from the ajax call.

```<code>"ajax": {
            "url": window.applicationPath + "/Launches/GetFilteredPartTrackingRecords",
            "data": function (d) {
                d.partNumber = $('#FilterPartNumber').val();
                d.segment = $('#FilterSegment').val();
                d.commodity = $('#FilterCommodity').val();
            }
        },
</code>```

Change the controller method to get

```<code>[HttpGet]
    public ActionResult GetFilteredPartTrackingRecords(DataTableAjaxPostModel model, string partNumber, string commodity, string segment)
</code>```

Change the JSON request behavior so I can return through GET

```<code>return Json(new
        {
            // this is what datatables wants sending back
            draw = model.draw,
            recordsTotal = 1000, // TODO CHANGE
            recordsFiltered = 1000, // TODO CHANGE
            data = result
        }, JsonRequestBehavior.AllowGet);
</code>```

I do not know if this is the best/ a good solution but this works for me.

Body:
I have seen this question: Jquery Datatables Error: Invalid JSON primitive: draw

It could not help me solve the issue.

I am using Datatables, I get an error for the AJAX call. Here is the JS code:

function loadparttrackings() {
    // Call the datatable on the overview div and link back to server side
    $('#overviewFilteredPartTrackings').DataTable({
        "processing": true,
        "serverSide": true,
        "filter": true,
        "orderMulti": false,
        "ajax": {
            "url": window.applicationPath + "/Launches/GetFilteredPartTrackingRecords",
            "type": "POST",
            "data": function (d) {
                d.partNumber = $('#FilterPartNumber').val();
                d.segment = $('#FilterSegment').val();
                d.commodity = $('#FilterCommodity').val();
            }
        },
        // This is needed to hide the ID field and make it not searchable
        "columnDefs":
        [{
                "targets": [1],
                "visible": false,
                "searchable": false
        }],
        "columns": [

            {
                "render": function (data, type, full, meta) { return 'Edit'; }
            },
            // more columns omitted
    });
}

The issue came up when I added the "type": "POST", to the AJAX part of the function. Now I get the error invalid json primitive draw.

Here is the code for the controller method:

[HttpPost]
    public ActionResult GetFilteredPartTrackingRecords(DataTableAjaxPostModel model, string partNumber, string commodity, string segment)
    {
        // Getting the data and such

        return Json(new
        {
            // this is what datatables wants sending back
            draw = model.draw,
            recordsTotal = 1000, // TODO CHANGE
            recordsFiltered = 1000, // TODO CHANGE
            data = result
        });
    }

And here is the code for the model that I use:

public class DataTableAjaxPostModel
{
    // properties are not capital due to json mapping
    public int draw { get; set; }
    public int start { get; set; }
    public int length { get; set; }
    public List<Column> columns { get; set; }
    public Search search { get; set; }
    public List<Order> order { get; set; }
}

public class Column
{
    public string data { get; set; }
    public string name { get; set; }
    public bool searchable { get; set; }
    public bool orderable { get; set; }
    public Search search { get; set; }
}

public class Search
{
    public string value { get; set; }
    public string regex { get; set; }
}

public class Order
{
    public int column { get; set; }
    public string dir { get; set; }
}

Body:
I fixed it by doing the following:

remove the type: post from the ajax call.

"ajax": {
            "url": window.applicationPath + "/Launches/GetFilteredPartTrackingRecords",
            "data": function (d) {
                d.partNumber = $('#FilterPartNumber').val();
                d.segment = $('#FilterSegment').val();
                d.commodity = $('#FilterCommodity').val();
            }
        },

Change the controller method to get

[HttpGet]
    public ActionResult GetFilteredPartTrackingRecords(DataTableAjaxPostModel model, string partNumber, string commodity, string segment)

Change the JSON request behavior so I can return through GET

return Json(new
        {
            // this is what datatables wants sending back
            draw = model.draw,
            recordsTotal = 1000, // TODO CHANGE
            recordsFiltered = 1000, // TODO CHANGE
            data = result
        }, JsonRequestBehavior.AllowGet);

I do not know if this is the best/ a good solution but this works for me.


问:
Swift Protocols causing Invalid Redeclaration and cluttering function table
TLDR: Using many Swift protocols in a large project is great for testing and SOLID coding, but I’m getting function clutter and invalid redeclaration clashes. What’s the best practice to avoid these problems in Swift while making heavy use of protocols?

Concretely, I want to use protocols to separate responsibilities from view classes such that they don’t need to know anything about the data models used to “decorate” them. But this is creating a lot of functions for my data model classes that are exposed throughout the app, and that are starting to clash with other protocols.

As an example, let’s say I want to set up my custom tableview cell from a certain data model in my project. Let’s call it MyDataModel. I create a decorating protocol like so:

```<code>protocol MyCellDecorator {
    var headingText: String?
    var descriptionText: String?
}
</code>```

And then my cell is like

```<code>class MyCell: UITableViewCell {
    @IBOutlet weak var headingLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!

    func setup(fromDecorator decorator: MyCellDecorator) {
        headingLabel.text = decorator.headingText
        descriptionLabel.text = decorator.descriptionText
    }
}
</code>```

Now all I need to do is provide an extension from my data model class implementing MyCellDecorator, providing headingText and descriptionText, and I can plug my data model object into setup(fromDecorator:).

```<code>extension MyDataClass: MyCellDecorator {
    var headingText: String {
        return “Some Heading“
    }
    var descriptionText: String {
        return “Some Description“
    }
}
</code>```

This makes the cell easy to test; it clearly separates responsibilities, MyCell and the UIViewController driving it now need to know nothing about MyDataModel..

BUT now MyDataModel has two extra properties, headingText, and descriptionText - available everywhere. But MyDataModel already extends 10 other decorator protocols for specific UI throughout my project, and it so happens that another protocol already defines headingText, so I get the compilation error “invalid redeclaration of ‘headingText’”.

With all of this headache, I decide to quit, go ahead and just pass MyDataModel into MyCell, it all compiles but I lose all the aforementioned advantages.

What are good ways, in such a big project as this, to score those sweet sweet protocol wins, without cluttering up my class’s function tables and having redeclaration clashes between different extensions?

答:
One struct-based way I've played with is this:

Instead of extending MyDataClass, I create a simple struct (which can be fileprivate to the view controller class, or not) that looks like:

```<code>struct MyDataClassCellDecorator: MyCellDecorator {
    var headingText: String? {
        return "Some heading with \(data.someText)"
    }

    var descriptionText: String? {
        return data.someOtherText
    }

    let data: MyDataClass
}
</code>```

This way MyCell can still use the protocol to decorate itself, MyDataClass doesn't need any extension at all, and in whatever access scope I want it I get a struct that does the decorating logic for MyDataClass + MyCellDecorator.

Body:
TLDR: Using many Swift protocols in a large project is great for testing and SOLID coding, but I’m getting function clutter and invalid redeclaration clashes. What’s the best practice to avoid these problems in Swift while making heavy use of protocols?

Concretely, I want to use protocols to separate responsibilities from view classes such that they don’t need to know anything about the data models used to “decorate” them. But this is creating a lot of functions for my data model classes that are exposed throughout the app, and that are starting to clash with other protocols.

As an example, let’s say I want to set up my custom tableview cell from a certain data model in my project. Let’s call it MyDataModel. I create a decorating protocol like so:

protocol MyCellDecorator {
    var headingText: String?
    var descriptionText: String?
}

And then my cell is like

class MyCell: UITableViewCell {
    @IBOutlet weak var headingLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!

    func setup(fromDecorator decorator: MyCellDecorator) {
        headingLabel.text = decorator.headingText
        descriptionLabel.text = decorator.descriptionText
    }
}

Now all I need to do is provide an extension from my data model class implementing MyCellDecorator, providing headingText and descriptionText, and I can plug my data model object into setup(fromDecorator:).

extension MyDataClass: MyCellDecorator {
    var headingText: String {
        return “Some Heading“
    }
    var descriptionText: String {
        return “Some Description“
    }
}

This makes the cell easy to test; it clearly separates responsibilities, MyCell and the UIViewController driving it now need to know nothing about MyDataModel..

BUT now MyDataModel has two extra properties, headingText, and descriptionText - available everywhere. But MyDataModel already extends 10 other decorator protocols for specific UI throughout my project, and it so happens that another protocol already defines headingText, so I get the compilation error “invalid redeclaration of ‘headingText’”.

With all of this headache, I decide to quit, go ahead and just pass MyDataModel into MyCell, it all compiles but I lose all the aforementioned advantages.

What are good ways, in such a big project as this, to score those sweet sweet protocol wins, without cluttering up my class’s function tables and having redeclaration clashes between different extensions?

Body:
One struct-based way I've played with is this:

Instead of extending MyDataClass, I create a simple struct (which can be fileprivate to the view controller class, or not) that looks like:

struct MyDataClassCellDecorator: MyCellDecorator {
    var headingText: String? {
        return "Some heading with \(data.someText)"
    }

    var descriptionText: String? {
        return data.someOtherText
    }

    let data: MyDataClass
}

This way MyCell can still use the protocol to decorate itself, MyDataClass doesn't need any extension at all, and in whatever access scope I want it I get a struct that does the decorating logic for MyDataClass + MyCellDecorator.


问:
How can I fill a listbox like this with data
What's the c# code to fill these listbox with datas (strings)

I saw this on https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

but there's no C# Code.

I want to have a listbox like in "Defining a Simple DataTemplate" on the link
https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

Picture from listbox   [1]: https://i.stack.imgur.com/K4HZS.png

```<code><ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=TaskName}" />
         <TextBlock Text="{Binding Path=Description}"/>
         <TextBlock Text="{Binding Path=Priority}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>
</code>```

答:
To do this, you will need to learn about MVVM pattern.
First, you need a class TODO in the model with properties for TaskName, Description and Priority.

```<code>public class Todo
{
    public string TaskName { get; set; }
    public string Description { get; set; }
    public int Priority { get; set; }
}
</code>```

Then, you will need a class to store the collection of TODO, your "myTodoList" in the xaml :

```<code>public class TodoViewModel
{
    public ObservableCollection<Todo> TodoList { get; } = new ObservableCollection<Todo>();

    public TodoViewModel()
    {
        TodoList.Add(new Todo { TaskName = "Todo1", Description = "Todo 1 Description", Priority = 1 });
        TodoList.Add(new Todo { TaskName = "Todo2", Description = "Todo 2 Description", Priority = 2 });
    }
}
</code>```

Then, you will need to set the datacontext in the code behind of the xaml :

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        this.DataContext = new TodoViewModel();
        InitializeComponent();
    }
}
</code>```

Finally, here is your XAML (I changed it a bit, you don't need things like "Path=") :

```<code><ListBox Width="400" Margin="10" ItemsSource="{Binding TodoList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding TaskName}" />
                    <TextBlock Text="{Binding Description}"/>
                    <TextBlock Text="{Binding Priority}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>
</code>```

And it should work well :)

Body:
What's the c# code to fill these listbox with datas (strings)

I saw this on https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

but there's no C# Code.

I want to have a listbox like in "Defining a Simple DataTemplate" on the link
https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

Picture from listbox   [1]: https://i.stack.imgur.com/K4HZS.png

<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=TaskName}" />
         <TextBlock Text="{Binding Path=Description}"/>
         <TextBlock Text="{Binding Path=Priority}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

Body:
To do this, you will need to learn about MVVM pattern.
First, you need a class TODO in the model with properties for TaskName, Description and Priority.

public class Todo
{
    public string TaskName { get; set; }
    public string Description { get; set; }
    public int Priority { get; set; }
}

Then, you will need a class to store the collection of TODO, your "myTodoList" in the xaml :

public class TodoViewModel
{
    public ObservableCollection<Todo> TodoList { get; } = new ObservableCollection<Todo>();

    public TodoViewModel()
    {
        TodoList.Add(new Todo { TaskName = "Todo1", Description = "Todo 1 Description", Priority = 1 });
        TodoList.Add(new Todo { TaskName = "Todo2", Description = "Todo 2 Description", Priority = 2 });
    }
}

Then, you will need to set the datacontext in the code behind of the xaml :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        this.DataContext = new TodoViewModel();
        InitializeComponent();
    }
}

Finally, here is your XAML (I changed it a bit, you don't need things like "Path=") :

<ListBox Width="400" Margin="10" ItemsSource="{Binding TodoList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding TaskName}" />
                    <TextBlock Text="{Binding Description}"/>
                    <TextBlock Text="{Binding Priority}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

And it should work well :)


问:
My application successfully deployed in Azure but I can't hit the URL
Deployment succesful in Azure but when I click on my URL I get an a 503 error?

This is a Linux OS Web app (App is Node/React) I think it might have something to do with the low CPU resources as I am on the free plan in Azure?

答:
When you browse to the app, it returns a HTTP "502 Bad Gateway" error or a HTTP "503 Service Unavailable" error.

This problem is often caused by application level issues, such as:

requests taking a long time

application using high memory/CPU

application crashing due to an exception.

Troubleshooting steps to solve "502 bad gateway" and "503 service unavailable" errors

Troubleshooting can be divided into three distinct tasks, in sequential order:

Observe and monitor application behavior

Collect data

Mitigate the issue

I would suggest you to go through these troubleshooting steps, it will help finding the right error.


问:
Is it ok to unit-test an abstract class by instantiating it as a mock object?
It has come to my attention that you can unit-test an abstract class by instantiating it as a mock object. Thereby you mock the abstract properties and methods, while being able to test the implemented ones.

However, I am accustomed to distinguish between the class to test and the injected dependencies to mock/stub. So, in this early stage of my new enlightenment I wonder if there are any pitfalls to this way of testing?? Any thoughts on this?

Regards,
Morten

答: An abstract class is by definition, abstract. There shouldn't be anything to test if it's truly abstract.</p>


问:
Android 9 Api 28 Notification not showing
I'm trying to show notification but it's not working for both Oreo and Pie version.

It's working in kitkat version.

I tried all the possible condition i can do, i don't know what else i'm missing here

Here is my code:

```<code>String idChannel = "my_channel_01";
        Intent mainIntent;
        mainIntent = new Intent(ChecklistOptionActivity.this, CashCountOptionActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);

        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationChannel mChannel = null;
        // The id of the channel.

        int importance = NotificationManager.IMPORTANCE_HIGH;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentTitle(context.getString(R.string.app_name))
                .setSmallIcon(R.drawable.bc_icon)
                .setContentIntent(pendingIntent)
                .setContentText("Test");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(idChannel, context.getString(R.string.app_name), importance);
            // Configure the notification channel.
            mChannel.setDescription("Test");
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);
        } else {
            builder.setContentTitle(context.getString(R.string.app_name))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setColor(ContextCompat.getColor(context, R.color.colorBlue))
                    .setVibrate(new long[]{100, 250})
                    .setLights(Color.YELLOW, 500, 5000)
                    .setAutoCancel(true);
        }
        mNotificationManager.notify(1, builder.build());
</code>```

答:
```<code>String channel_id = createNotificationChannel(context);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id);
</code>```

The below method is to generate a new channel_id.

```<code> public static String createNotificationChannel(Context context) {

                // NotificationChannels are required for Notifications on O (API 26) and above.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                    // The id of the channel.
                    String channelId = "Channel_id";

                    // The user-visible name of the channel.
                    CharSequence channelName = "Application_name";
                    // The user-visible description of the channel.
                    String channelDescription = "Application_name Alert";
                    int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
                    boolean channelEnableVibrate = true;
        //            int channelLockscreenVisibility = Notification.;

                    // Initializes NotificationChannel.
                    NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
                    notificationChannel.setDescription(channelDescription);
                    notificationChannel.enableVibration(channelEnableVibrate);
        //            notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);

                    // Adds NotificationChannel to system. Attempting to create an existing notification
                    // channel with its original values performs no operation, so it's safe to perform the
                    // below sequence.
                    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    assert notificationManager != null;
                    notificationManager.createNotificationChannel(notificationChannel);

                    return channelId;
                } else {
                    // Returns null for pre-O (26) devices.
                    return null;
                }
            }
</code>```

Here, you will get push notification using channel_id in your device which is consist 26+ SDK version.

Because, the NotificationCompat.Builder(context) method has been deprecated so that you will have to use an updated method NotificationCompat.Builder(context, channel_id) which has two parameters one is for context, the second one is for channel_id.

In the devices which has 26+ SDK version, you can create channel_id every time.

Body:
I'm trying to show notification but it's not working for both Oreo and Pie version.

It's working in kitkat version.

I tried all the possible condition i can do, i don't know what else i'm missing here

Here is my code:

String idChannel = "my_channel_01";
        Intent mainIntent;
        mainIntent = new Intent(ChecklistOptionActivity.this, CashCountOptionActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);

        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationChannel mChannel = null;
        // The id of the channel.

        int importance = NotificationManager.IMPORTANCE_HIGH;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentTitle(context.getString(R.string.app_name))
                .setSmallIcon(R.drawable.bc_icon)
                .setContentIntent(pendingIntent)
                .setContentText("Test");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(idChannel, context.getString(R.string.app_name), importance);
            // Configure the notification channel.
            mChannel.setDescription("Test");
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);
        } else {
            builder.setContentTitle(context.getString(R.string.app_name))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setColor(ContextCompat.getColor(context, R.color.colorBlue))
                    .setVibrate(new long[]{100, 250})
                    .setLights(Color.YELLOW, 500, 5000)
                    .setAutoCancel(true);
        }
        mNotificationManager.notify(1, builder.build());

Body:
String channel_id = createNotificationChannel(context);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id);

The below method is to generate a new channel_id.

 public static String createNotificationChannel(Context context) {

                // NotificationChannels are required for Notifications on O (API 26) and above.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                    // The id of the channel.
                    String channelId = "Channel_id";

                    // The user-visible name of the channel.
                    CharSequence channelName = "Application_name";
                    // The user-visible description of the channel.
                    String channelDescription = "Application_name Alert";
                    int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
                    boolean channelEnableVibrate = true;
        //            int channelLockscreenVisibility = Notification.;

                    // Initializes NotificationChannel.
                    NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
                    notificationChannel.setDescription(channelDescription);
                    notificationChannel.enableVibration(channelEnableVibrate);
        //            notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);

                    // Adds NotificationChannel to system. Attempting to create an existing notification
                    // channel with its original values performs no operation, so it's safe to perform the
                    // below sequence.
                    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    assert notificationManager != null;
                    notificationManager.createNotificationChannel(notificationChannel);

                    return channelId;
                } else {
                    // Returns null for pre-O (26) devices.
                    return null;
                }
            }

Here, you will get push notification using channel_id in your device which is consist 26+ SDK version.

Because, the NotificationCompat.Builder(context) method has been deprecated so that you will have to use an updated method NotificationCompat.Builder(context, channel_id) which has two parameters one is for context, the second one is for channel_id.

In the devices which has 26+ SDK version, you can create channel_id every time.


问:
Windows x64 RabbitMQ install error with Erlang environment var (ERLANG_HOME)
I'm ask/answering this question because it hung me up & it's likely someone else will have the same problem.

Install of RabbitMQ x64 v2.8.6 on Windows Server 2008 x64.

After Erlang install using default install location to C:\Program Files\erl5.9.2, I'm attempting to start the server via running the rabbitmq-service.bat. Fail:

```<code>Please either set ERLANG_HOME to point to your Erlang installation
or place the RabbitMQ server distribution in the Erlang lib folder.
</code>```

Problem is the .bat file does not have the correct subpath. with 5.9.2 (R15B02) version of erlang. My ERLANG_HOME directory is set correctly, but the script does not use it correctly for this version of Erlang, which, it appears to this Erlang noob to have a new subdirectory called "erts-5.9.2" which is causing the problems. Maybe someone intimate with these scripts can describe how to make this work correctly without the hack workaround I'm about to describe?

答:
Even I was this problem. The issue was the environment variable ERLANG_HOME=c:\Program Files\erl9.0 which was never existed.

I cross checked the path. The correct path was c:\Program Files\erl9.3.

After correcting the

ERLANG_HOME=c:\Program Files\erl9.3

the problem solved. So, definitely it is a path issue.

Body:
I'm ask/answering this question because it hung me up & it's likely someone else will have the same problem.

Install of RabbitMQ x64 v2.8.6 on Windows Server 2008 x64.

After Erlang install using default install location to C:\Program Files\erl5.9.2, I'm attempting to start the server via running the rabbitmq-service.bat. Fail:

Please either set ERLANG_HOME to point to your Erlang installation
or place the RabbitMQ server distribution in the Erlang lib folder.

Problem is the .bat file does not have the correct subpath. with 5.9.2 (R15B02) version of erlang. My ERLANG_HOME directory is set correctly, but the script does not use it correctly for this version of Erlang, which, it appears to this Erlang noob to have a new subdirectory called "erts-5.9.2" which is causing the problems. Maybe someone intimate with these scripts can describe how to make this work correctly without the hack workaround I'm about to describe?


问:
How to debug who is eating my touches in UIKit?
I can't figure out why tapping on text fields and buttons in my view is not working. I've checked all the obvious things like whether userInteractionEnabled is set to YES, whether a gesture recognizer is installed, and if there is an invisible view in the foreground.

Is there a best practice in iOS for tracing a touch from when it first appears to where it gets consumed?

UPDATE:

Both answers were helpful. During the course of my investigation I learned that if a subview is outside of its parent's bounds, even if the parent is not clipping subviews, the subview will not receive events. I printed out the chain of superviews from the text field that was not getting touches, and I saw that one of those views had a height of 0. I put in some constraints to stretch it out, and my problem was solved.

答:
You can debug that by using a symbolic breakpoint:

-[UIWindow sendEvent:] & po $arg3

Logs:

```<code><UITouchesEvent: 0x6000026fa6d0> timestamp: 179462 touches: {(
<UITouch: 0x7f84d6f10380> phase: Began tap count: 1 force: 0.000
window: <UIWindow: 0x7f84d6d0ad10; frame = (0 0; 375 812); autoresize = W+H;
gestureRecognizers = <NSArray: 0x600001aa8870>; layer = <UIWindowLayer: 0x6000014bd7e0>> view: <UIView: 0x7f84d6d0bff0; frame = (0 0; 375 812);
autoresize = W+H; layer = <CALayer: 0x6000014bdc60>> location in window: {165.66665649414062, 232.33332824707031} previous location in window:
{165.66665649414062, 232.33332824707031} location in view: {165.66665649414062,
232.33332824707031} previous location in view: {165.66665649414062,232.33332824707031}
)}
</code>```

Body:
You can debug that by using a symbolic breakpoint:

-[UIWindow sendEvent:] & po $arg3

Logs:

<UITouchesEvent: 0x6000026fa6d0> timestamp: 179462 touches: {(
<UITouch: 0x7f84d6f10380> phase: Began tap count: 1 force: 0.000
window: <UIWindow: 0x7f84d6d0ad10; frame = (0 0; 375 812); autoresize = W+H;
gestureRecognizers = <NSArray: 0x600001aa8870>; layer = <UIWindowLayer: 0x6000014bd7e0>> view: <UIView: 0x7f84d6d0bff0; frame = (0 0; 375 812);
autoresize = W+H; layer = <CALayer: 0x6000014bdc60>> location in window: {165.66665649414062, 232.33332824707031} previous location in window:
{165.66665649414062, 232.33332824707031} location in view: {165.66665649414062,
232.33332824707031} previous location in view: {165.66665649414062,232.33332824707031}
)}


问:
swiftmailer email error with multiple emails
I keep getting a fatal error message when getting multiple emails from firebase to php (passing data from firebase to HTML then to html to PHP)

Fatal error: Uncaught exception 'Swift_RfcComplianceException' with message 'Address in mailbox given [Person1@outlook.com,Person2@gmail.com] does not comply with RFC 2822, 3.6.2

I tried getting a single email from firebase and it worked perfectly, but multiple emails with any email addressed I used the same issue arise

```<code><?php

require '/Vendor/Mail/lib/swift_required.php';

// validation expected data exists if required later
if (!isset($_POST['agent_e'])  {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
}

$email_to = $_POST['agent_e']; // required
$headers .= "MIME-Version: 1.0\r\n";

$mailer   = Swift_Mailer::newInstance($transport);
$message  = Swift_Message::newInstance('')
    ->setSubject($subject)
    ->setFrom(array('mailer@outlook.com' => 'mailer'))
    ->setTo(array($email_to))
    ->setBody('<html>' .
' <body>' .
'  ' . // Embed the file
$messageBody .
'  ' .
' </body>' .
'</html>',
'text/html' // Mark the content-type as HTML
);

// Send the message
$result = $mailer->send($message);

</code>```

Emails from database example :

Error :

答:
i solved the problem with Splitting the emails i got from firebase to an array

as below code :

```<code>$email_to = str_replace(' ','',$email_to);
$email_to = (string) $email_to;
$email_to = explode(',',$email_to);
</code>```

Body:
I keep getting a fatal error message when getting multiple emails from firebase to php (passing data from firebase to HTML then to html to PHP)

Fatal error: Uncaught exception 'Swift_RfcComplianceException' with message 'Address in mailbox given [Person1@outlook.com,Person2@gmail.com] does not comply with RFC 2822, 3.6.2

I tried getting a single email from firebase and it worked perfectly, but multiple emails with any email addressed I used the same issue arise

<?php

require '/Vendor/Mail/lib/swift_required.php';

// validation expected data exists if required later
if (!isset($_POST['agent_e'])  {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
}

$email_to = $_POST['agent_e']; // required
$headers .= "MIME-Version: 1.0\r\n";

$mailer   = Swift_Mailer::newInstance($transport);
$message  = Swift_Message::newInstance('')
    ->setSubject($subject)
    ->setFrom(array('mailer@outlook.com' => 'mailer'))
    ->setTo(array($email_to))
    ->setBody('' .
' ' .
'  ' . // Embed the file
$messageBody .
'  ' .
' ' .
'',
'text/html' // Mark the content-type as HTML
);

// Send the message
$result = $mailer->send($message);

Emails from database example :

Error :

Body:
i solved the problem with Splitting the emails i got from firebase to an array

as below code :

$email_to = str_replace(' ','',$email_to);
$email_to = (string) $email_to;
$email_to = explode(',',$email_to);


问:
Objective-C and then what? Android, Windows 7, Blackberry
Question: what should one focus on when there is a strong need to develop Apps for multiple platforms? I spend all this time focusing on Obj-C, but that get's me no where with Android, Windows 7 or Blackberry.

At it stands, Objective-C isn't even the language that the iPhone ends up using. Obj-C is compiled for the iPhone. So there must be a way to write the Apps in a more global language and then have it compiled for the iPhone, Android and Blackberry...

Recommendations?

答: Perhaps you should look at MonoTouch/Mono For Android or Appcelerator Titanium if you want to write once and run on multiple mobile platforms.</p>


问:
xButton.setAttribute is not a function error
I have a function which formats elements in a JSON file to a table.

The table works fine, but now I am trying to implement a button on another column which deletes the said element from the file.

But when I did, it comes up with the error:
Uncaught (in promise) TypeError: xButton.setAttribute is not a function

Here is my code:

   async function table() {

    let response = await fetch('/tasks', {
     method: "GET",
     headers: {
     'Content-Type': 'application/json'
     }
    });

    let jsonPayload = await response.json();

    var table = document.getElementById("tableBody");

    tableBody.innerHTML = "";

    for(var i = jsonPayload.length - 1; i > -1; i--) {
      var row = tableBody.insertRow(0);

       var firstColumn = row.insertCell(0);
       var secondColumn = row.insertCell(1);
       var thirdColumn = row.insertCell(2);
       var fourthColumn = row.insertCell(3);

       var xButton = '<button>x</button>';
       xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);

     firstColumn.innerHTML = jsonPayload[i].id;
     secondColumn.innerHTML = jsonPayload[i].desc;

     thirdColumn.innerHTML = jsonPayload[i].importance;
     fourthColumn.innerHTML = xButton;

    }

   }```
</div>
</div>
</p>

<p>This is the code to delete an element
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//function which deletes a task.
   function deleteElement() {

   //Variable id is the number submitted in the input form to Delete tasks
      var id = document.getElementById("deleteId").value;

   //This is the url that is fetched with the variable id which deletes the function using the code from the backend.
   var url = "/tasks/"+id;

   //isNan checks whether id is not a number
   if (isNaN(id)) {
    //If it is not a number the error message is displayed.
    alert("The value inputted must be a number!");
    //Returns out of the function without proceeding
    return;
   }

   //Fetches /tasks, with the DELETE method
   fetch(url, {
    method: 'DELETE',
    headers: {
     'Content-Type': 'application/json'
    }
   });

   //display(); Calls the display function at the end to display the tasks again without the deleted url.
   display();
   }</code>```

The main issue is with the xButton, any help is appreciated.

答:
You need to create it with correct code. Also I suggest you to try out JQuery.</p>

```<code>var button = document.createElement("button");
button.innerHTML = "Do Something";

var body = document.getElementsByTagName("body")[0];
body.appendChild(button);

button.addEventListener ("click", function() {
  alert("test");
});
</code>```

Body:
I have a function which formats elements in a JSON file to a table.

The table works fine, but now I am trying to implement a button on another column which deletes the said element from the file.

But when I did, it comes up with the error:
Uncaught (in promise) TypeError: xButton.setAttribute is not a function

Here is my code:

   async function table() {

    let response = await fetch('/tasks', {
     method: "GET",
     headers: {
     'Content-Type': 'application/json'
     }
    });

    let jsonPayload = await response.json();

    var table = document.getElementById("tableBody");

    tableBody.innerHTML = "";

    for(var i = jsonPayload.length - 1; i > -1; i--) {
      var row = tableBody.insertRow(0);

       var firstColumn = row.insertCell(0);
       var secondColumn = row.insertCell(1);
       var thirdColumn = row.insertCell(2);
       var fourthColumn = row.insertCell(3);

       var xButton = '<button>x</button>';
       xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);

     firstColumn.innerHTML = jsonPayload[i].id;
     secondColumn.innerHTML = jsonPayload[i].desc;

     thirdColumn.innerHTML = jsonPayload[i].importance;
     fourthColumn.innerHTML = xButton;

    }

   }

This is the code to delete an element

//function which deletes a task.
   function deleteElement() {

   //Variable id is the number submitted in the input form to Delete tasks
      var id = document.getElementById("deleteId").value;

   //This is the url that is fetched with the variable id which deletes the function using the code from the backend.
   var url = "/tasks/"+id;

   //isNan checks whether id is not a number
   if (isNaN(id)) {
    //If it is not a number the error message is displayed.
    alert("The value inputted must be a number!");
    //Returns out of the function without proceeding
    return;
   }

   //Fetches /tasks, with the DELETE method
   fetch(url, {
    method: 'DELETE',
    headers: {
     'Content-Type': 'application/json'
    }
   });

   //display(); Calls the display function at the end to display the tasks again without the deleted url.
   display();
   }

The main issue is with the xButton, any help is appreciated.

Body:
You need to create it with correct code. Also I suggest you to try out JQuery.

var button = document.createElement("button");
button.innerHTML = "Do Something";

var body = document.getElementsByTagName("body")[0];
body.appendChild(button);

button.addEventListener ("click", function() {
  alert("test");
});


问:
NSURLErrorDomain Code=-1005 "The network connection was lost.", _kCFStreamErrorCodeKey=54

Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
  UserInfo={_kCFStreamErrorCodeKey=54, NSUnderlyingError=0x2834c47b0
  {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)"
  UserInfo={_kCFStreamErrorCodeKey=54, _kCFStreamErrorDomainKey=1}},
  _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<1>,
  _NSURLErrorRelatedURLSessionTaskErrorKey=(
      "LocalDataTask .<1>" ), NSLocalizedDescription=The network connection was lost.,
  NSErrorFailingURLStringKey=https://xxx.xxxx.com/xxxx/xxxxx,
  NSErrorFailingURLKey=https://xxx.xxxx.com/xxx/xxx,
  _kCFStreamErrorDomainKey=1} [-1005]

Got above error When I am firing api using AFNetworking. I have configured "App Transport Security setting" to allow arbitrary loads. Increased timeout interval of AFNetworking request serializer to 100 seconds. But none helped.

答:
If you are testing on simulator you might face this issue. I guess the simulator internally may not able to connect to the internet, so that is why it was not able to connect to the server. Try restarting the simulator and check .If it still doesn't work correctly then clear all the content and data for simulator from Hardware --> Erase All Content and Settings.

If you are checking in the real device please check the internet connection of the device.

If the internet connection is working fine then there is some configuration to be done at server end with 'Keep-Alive' value in configuration. I found the same solution at multiple references as below :

https://github.com/AFNetworking/AFNetworking/issues/2801

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

Hope this helps.


问:
POST Request with Form Data Only Working for Current Year
I'm attempting to send form data to get the information on bills for each year. Everything works as expected for 2019 however if I change the form data "ctl00$rilinContent$cbYear" to a prior year it just returns the default search page (which defaults to 2019 as the year) and thus gives no information to collect.

I attempted using "__EVENTTARGET" to change the year but didn't have any success, Thanks for any help you may be able to provide.

Sample Code

```<code>import requests

default_data = {'__EVENTTARGET': '',
            '__EVENTARGUMENT': '',
            '__LASTFOCUS': '',
            '__VIEWSTATE': 'PZZDS...', #(long string)
            '__VIEWSTATEGENERATOR': 'B3C16737',
            '__EVENTVALIDATION': 'kp03y...', #(long string)
            'ctl00$rilinContent$cbYear': '',
            'ctl00$rilinContent$txtReport': '',
            'ctl00$rilinContent$cbCommittee': '',
            'ctl00$rilinContent$comm': 'cbxIn',
            'ctl00$rilinContent$cbCategory': '',
            'ctl00$rilinContent$cbSponsor': '',
            'ctl00$rilinContent$cbxPrime': '',
            'ctl00$rilinContent$txtBills': '',
            'ctl00$rilinContent$cbxSortNumeric': '',
            'ctl00$rilinContent$txtBillFrom': '',
            'ctl00$rilinContent$txtBillTo': '',
            'ctl00$rilinContent$cbAction': '',
            'ctl00$rilinContent$cbxLastAction': '',
            'ctl00$rilinContent$cmdReport': 'Enter',
            'ctl00$rilinContent$hfQuery': ''}

url = "http://status.rilin.state.ri.us/"
data = default_data

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}

data['ctl00$rilinContent$cbYear'] = '2019'
data['ctl00$rilinContent$cbCategory'] = '307'

r = requests.post(url, data=data, headers=headers).text

# simple test
string = 'Legislative Status Report'
string in r
</code>```

答:
I think the page does an initial update via POST for year then subsequently for marriage. The following can be simplified I'm sure but seems to work</p>

```<code>import requests
from bs4 import BeautifulSoup as bs

default_data = {'__EVENTTARGET': '',
            '__EVENTARGUMENT': '',
            '__LASTFOCUS': '',
            '__VIEWSTATE': '',
            '__VIEWSTATEGENERATOR': 'B3C16737',
            '__EVENTVALIDATION': '',
            'ctl00$rilinContent$cbYear': '',
            'ctl00$rilinContent$txtReport': '',
            'ctl00$rilinContent$cbCommittee': '',
            'ctl00$rilinContent$comm': 'cbxIn',
            'ctl00$rilinContent$cbCategory': '',
            'ctl00$rilinContent$cbSponsor': '',
            'ctl00$rilinContent$cbxPrime': '',
            'ctl00$rilinContent$txtBills': '',
            'ctl00$rilinContent$cbxSortNumeric': '',
            'ctl00$rilinContent$txtBillFrom': '',
            'ctl00$rilinContent$txtBillTo': '',
            'ctl00$rilinContent$cbAction': '',
            'ctl00$rilinContent$cbxLastAction': '',
            'ctl00$rilinContent$cmdReport': '', #'Enter'
            'ctl00$rilinContent$hfQuery': ''}

url = "http://status.rilin.state.ri.us/"
data = default_data

headers = {
    'User-Agent': 'Mozilla/5.0',
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Content-Type' : 'application/x-www-form-urlencoded'
}

data['ctl00$rilinContent$cbYear'] = 2017

with requests.Session() as s:
    r = s.get(url)
    soup = bs(r.content, 'lxml')
    vs = soup.select_one('#__VIEWSTATE')['value']
    ev = soup.select_one('#__EVENTVALIDATION')['value']
    data['__VIEWSTATE'] = vs
    data['__EVENTVALIDATION'] = ev
    r = s.post(url, data=data, headers=headers)
    soup = bs(r.content, 'lxml')
    vs = soup.select_one('#__VIEWSTATE')['value']
    ev = soup.select_one('#__EVENTVALIDATION')['value']
    data['ctl00$rilinContent$cbCategory'] = 307
    data['__VIEWSTATE'] = vs
    data['__EVENTVALIDATION'] = ev
    data['ctl00$rilinContent$cmdReport'] = 'Enter'
    r = s.post(url, data=data, headers=headers)
    soup = bs(r.content, 'lxml')
    print(soup)
</code>```

Body:
I'm attempting to send form data to get the information on bills for each year. Everything works as expected for 2019 however if I change the form data "ctl00$rilinContent$cbYear" to a prior year it just returns the default search page (which defaults to 2019 as the year) and thus gives no information to collect.

I attempted using "__EVENTTARGET" to change the year but didn't have any success, Thanks for any help you may be able to provide.

Sample Code

import requests

default_data = {'__EVENTTARGET': '',
            '__EVENTARGUMENT': '',
            '__LASTFOCUS': '',
            '__VIEWSTATE': 'PZZDS...', #(long string)
            '__VIEWSTATEGENERATOR': 'B3C16737',
            '__EVENTVALIDATION': 'kp03y...', #(long string)
            'ctl00$rilinContent$cbYear': '',
            'ctl00$rilinContent$txtReport': '',
            'ctl00$rilinContent$cbCommittee': '',
            'ctl00$rilinContent$comm': 'cbxIn',
            'ctl00$rilinContent$cbCategory': '',
            'ctl00$rilinContent$cbSponsor': '',
            'ctl00$rilinContent$cbxPrime': '',
            'ctl00$rilinContent$txtBills': '',
            'ctl00$rilinContent$cbxSortNumeric': '',
            'ctl00$rilinContent$txtBillFrom': '',
            'ctl00$rilinContent$txtBillTo': '',
            'ctl00$rilinContent$cbAction': '',
            'ctl00$rilinContent$cbxLastAction': '',
            'ctl00$rilinContent$cmdReport': 'Enter',
            'ctl00$rilinContent$hfQuery': ''}

url = "http://status.rilin.state.ri.us/"
data = default_data

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}

data['ctl00$rilinContent$cbYear'] = '2019'
data['ctl00$rilinContent$cbCategory'] = '307'

r = requests.post(url, data=data, headers=headers).text

# simple test
string = 'Legislative Status Report'
string in r

Body:
I think the page does an initial update via POST for year then subsequently for marriage. The following can be simplified I'm sure but seems to work

import requests
from bs4 import BeautifulSoup as bs

default_data = {'__EVENTTARGET': '',
            '__EVENTARGUMENT': '',
            '__LASTFOCUS': '',
            '__VIEWSTATE': '',
            '__VIEWSTATEGENERATOR': 'B3C16737',
            '__EVENTVALIDATION': '',
            'ctl00$rilinContent$cbYear': '',
            'ctl00$rilinContent$txtReport': '',
            'ctl00$rilinContent$cbCommittee': '',
            'ctl00$rilinContent$comm': 'cbxIn',
            'ctl00$rilinContent$cbCategory': '',
            'ctl00$rilinContent$cbSponsor': '',
            'ctl00$rilinContent$cbxPrime': '',
            'ctl00$rilinContent$txtBills': '',
            'ctl00$rilinContent$cbxSortNumeric': '',
            'ctl00$rilinContent$txtBillFrom': '',
            'ctl00$rilinContent$txtBillTo': '',
            'ctl00$rilinContent$cbAction': '',
            'ctl00$rilinContent$cbxLastAction': '',
            'ctl00$rilinContent$cmdReport': '', #'Enter'
            'ctl00$rilinContent$hfQuery': ''}

url = "http://status.rilin.state.ri.us/"
data = default_data

headers = {
    'User-Agent': 'Mozilla/5.0',
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Content-Type' : 'application/x-www-form-urlencoded'
}

data['ctl00$rilinContent$cbYear'] = 2017

with requests.Session() as s:
    r = s.get(url)
    soup = bs(r.content, 'lxml')
    vs = soup.select_one('#__VIEWSTATE')['value']
    ev = soup.select_one('#__EVENTVALIDATION')['value']
    data['__VIEWSTATE'] = vs
    data['__EVENTVALIDATION'] = ev
    r = s.post(url, data=data, headers=headers)
    soup = bs(r.content, 'lxml')
    vs = soup.select_one('#__VIEWSTATE')['value']
    ev = soup.select_one('#__EVENTVALIDATION')['value']
    data['ctl00$rilinContent$cbCategory'] = 307
    data['__VIEWSTATE'] = vs
    data['__EVENTVALIDATION'] = ev
    data['ctl00$rilinContent$cmdReport'] = 'Enter'
    r = s.post(url, data=data, headers=headers)
    soup = bs(r.content, 'lxml')
    print(soup)


问:
Incorrect aggregation when using sorting
I use this query to get search hits and the count of hits across multiple indices:

```<code>/index1,index2/_search
{
  "query":{
    "query_string":{
      "query":"*"
    }
  },
  "aggs":{
    "group_by_index":{
      "terms":{
        "field":"_index",
        "min_doc_count":0
      }
    }
  },
  "post_filter":{
    "terms":{
      "_index":"index1"
    }
  },
  "sort":{
    "my_field":"asc"
  }
}
</code>```

The problem is if I sort on a field (my_field) that only exist in index1, the aggregation will only give me the hits count of index1, and not index2.

I thought the aggregation would work regardless of what sorting I have specified?

Using Elasticsearch 6.4

答: Solved it by using unmapped_type</p>

Body:
I use this query to get search hits and the count of hits across multiple indices:

/index1,index2/_search
{
  "query":{
    "query_string":{
      "query":"*"
    }
  },
  "aggs":{
    "group_by_index":{
      "terms":{
        "field":"_index",
        "min_doc_count":0
      }
    }
  },
  "post_filter":{
    "terms":{
      "_index":"index1"
    }
  },
  "sort":{
    "my_field":"asc"
  }
}

The problem is if I sort on a field (my_field) that only exist in index1, the aggregation will only give me the hits count of index1, and not index2.

I thought the aggregation would work regardless of what sorting I have specified?

Using Elasticsearch 6.4

Body: Solved it by using unmapped_type


问:
how to add Datepicker to a text box on custom dialogue box TinyMCE
I have a custom button and when i click i will get a custom dialogue box. till there every thing is fine, now i need a datetime picker in side that custom dialogue for that text box. i also not interested to use jqueryUI bundle for just datepicker can any once give me a better solution for this.

You can try at this fiddle https://jsfiddle.net/1qngde28/

```<code>
var dialogConfig =  {
  title: 'Date Picker Missing',
  body: {
    type: 'panel',
    items: [
      {
        type: 'input',
        name: 'title',
        label: 'Enter Title'
      },
      {
        type: 'input',
        name: 'DateTime',
        label: 'Datetime DD/MM/YYYY'
      }
    ]
  },
  buttons: [
    {
      type: 'cancel',
      name: 'closeButton',
      text: 'Cancel'
    },
    {
      type: 'submit',
      name: 'submitButton',
      text: 'Insert',
      primary: true
    }
  ],
  initialData: {
    title: '',
    DateTime: ''
  },
  onSubmit: function (api) {
    var data = api.getData();

    tinymce.activeEditor.execCommand('mceInsertContent', false, '<p>My ' + data.title +' at: <strong>' + data.DateTime + '</strong></p>');
    api.close();
  }
};

tinymce.init({
  selector: 'textarea.petMachine',
  toolbar: 'dialog-example-btn',
  setup: function (editor) {
    editor.ui.registry.addButton('dialog-example-btn', {
      text:'[Insert]',
      onAction: function () {
        editor.windowManager.open(dialogConfig)
      }
    })
  }
});

`````````````````````````

Date Picker on DateTime Text box.

Thanks in Advance.
</code>```

答:
I could able to do it using date range picker plugin from below URL
http://www.daterangepicker.com/

Here is the following code

```<code>//at Items /component declartion for form
{
   type: 'htmlpanel',
   html: '<input type="text" id="datepickerstart" class=" datepicker tox-textfield" readonly="readonly"></p>',
}

//at function

function _onAction() {

/* dialogue code here ..... */

                //Calling date picker
                $('.datepicker').daterangepicker({
                    singleDatePicker: true,
                    showDropdowns: true,
                    timePicker: true,
                    startDate: moment().startOf('hour')

                }, function (start, end, label) {
                    //alert($("#datepickerstart").val());
                });
            }

//at calling function of dialogue
editor.ui.registry.addMenuItem('xxxxxx', {
                text: 'xxxxxx',
                context: 'insert',
                onAction: _onAction
            });

// Include js and css of datepicker at where editor is been used which will automatically recognize the daterangepicker function.
</code>```

Body:
I have a custom button and when i click i will get a custom dialogue box. till there every thing is fine, now i need a datetime picker in side that custom dialogue for that text box. i also not interested to use jqueryUI bundle for just datepicker can any once give me a better solution for this.

You can try at this fiddle https://jsfiddle.net/1qngde28/

var dialogConfig =  {
  title: 'Date Picker Missing',
  body: {
    type: 'panel',
    items: [
      {
        type: 'input',
        name: 'title',
        label: 'Enter Title'
      },
      {
        type: 'input',
        name: 'DateTime',
        label: 'Datetime DD/MM/YYYY'
      }
    ]
  },
  buttons: [
    {
      type: 'cancel',
      name: 'closeButton',
      text: 'Cancel'
    },
    {
      type: 'submit',
      name: 'submitButton',
      text: 'Insert',
      primary: true
    }
  ],
  initialData: {
    title: '',
    DateTime: ''
  },
  onSubmit: function (api) {
    var data = api.getData();

    tinymce.activeEditor.execCommand('mceInsertContent', false, '
My ' + data.title +' at: ' + data.DateTime + '
');
    api.close();
  }
};

tinymce.init({
  selector: 'textarea.petMachine',
  toolbar: 'dialog-example-btn',
  setup: function (editor) {
    editor.ui.registry.addButton('dialog-example-btn', {
      text:'[Insert]',
      onAction: function () {
        editor.windowManager.open(dialogConfig)
      }
    })
  }
});

`````````````````````````

Date Picker on DateTime Text box.

Thanks in Advance.

Body:
I could able to do it using date range picker plugin from below URL
http://www.daterangepicker.com/

Here is the following code

//at Items /component declartion for form
{
   type: 'htmlpanel',
   html: '<input type="text" id="datepickerstart" class=" datepicker tox-textfield" readonly="readonly"></p>',
}

//at function

function _onAction() {

/* dialogue code here ..... */

                //Calling date picker
                $('.datepicker').daterangepicker({
                    singleDatePicker: true,
                    showDropdowns: true,
                    timePicker: true,
                    startDate: moment().startOf('hour')

                }, function (start, end, label) {
                    //alert($("#datepickerstart").val());
                });
            }

//at calling function of dialogue
editor.ui.registry.addMenuItem('xxxxxx', {
                text: 'xxxxxx',
                context: 'insert',
                onAction: _onAction
            });

// Include js and css of datepicker at where editor is been used which will automatically recognize the daterangepicker function.


问:
Using Horizontal Pod Autoscaling along with resource requests and limits
Say we have the following deployment:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  ...
spec:
  replicas: 2
  template:
    spec:
      containers:
        - image: ...
          ...
          resources:
            requests:
              cpu: 100m
              memory: 50Mi
            limits:
              cpu: 500m
              memory: 300Mi
</code>```

And we also create a HorizontalPodAutoscaler object which automatically scales up/down the number of pods based on CPU average utilization. I know that the HPA will compute the number of pods based on the resource requests, but what if I want the containers to be able to request more resources before scaling horizontally?

I have two questions:

1) Are resource limits even used by K8s when a HPA is defined?

2) Can I tell the HPA to scale based on resource limits rather than requests? Or as a means of implementing such a control, can I set the targetUtilization value to be more than 100%?

答:
Hi in deployment we have resources requests and limits. As per documentation here those parameters acts before HPA gets main role as autoscaler:

When you create a Pod, the Kubernetes scheduler selects a node for
  the Pod to run on. Each node has a maximum capacity for each of the
  resource types: the amount of CPU and memory it can provide for
  Pods.

Then the kubelet starts a Container of a Pod, it passes the CPU and memory limits to the container runtime.

If a Container exceeds its memory limit, it might be terminated. If it is restartable, the kubelet will restart it, as with any other type of runtime failure.

If a Container exceeds its memory request, it is likely that its Pod will be evicted whenever the node runs out of memory.

On the other hand:

The Horizontal Pod Autoscaler is implemented as a control loop, with a period controlled by the controller manager’s (with default value of 15 seconds).
  The controller manager queries the resource utilization against the metrics specified in each HorizontalPodAutoscaler definition.

Note:
Please note that if some of the pod’s containers do not have the relevant resource request set, CPU utilization for the pod will not be defined and the autoscaler will not take any action for that metric.

Hope this help

Body:
Say we have the following deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  ...
spec:
  replicas: 2
  template:
    spec:
      containers:
        - image: ...
          ...
          resources:
            requests:
              cpu: 100m
              memory: 50Mi
            limits:
              cpu: 500m
              memory: 300Mi

And we also create a HorizontalPodAutoscaler object which automatically scales up/down the number of pods based on CPU average utilization. I know that the HPA will compute the number of pods based on the resource requests, but what if I want the containers to be able to request more resources before scaling horizontally?

I have two questions:

1) Are resource limits even used by K8s when a HPA is defined?

2) Can I tell the HPA to scale based on resource limits rather than requests? Or as a means of implementing such a control, can I set the targetUtilization value to be more than 100%?


问:
windows phone best way to tombstone my list
I have a model with different properties, how can I save this on state and restore after resuming of application?</p>

答: Jeff Prosise has a great series of posts on Real-World Tombstoning in Silverlight for Windows Phone that should tell you everything you need to know about tombstoning, including what to save, how, and when.</p>


问:
Not able to publish website on Windows Azure using publish through VS2010
I am facing this problem when I try to publish my web application on Windows Azure via Visual Studio 2010. I am trying by right click on project and select publish and importing publish profile downloaded from Windows Azure platform.

I am getting this error:

Error 1 Web deployment task failed. (Could not connect to the remote computer ("waws-prod-am2-001.publish.azurewebsites.windows.net"). On the remote computer, make sure that Web Deploy is installed and that the required process ("Web Management Service") is started.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_DESTINATION_NOT_REACHABLE.)  0 0 MeraSungard

答:
I do not save the password in my publish profile. Even after checking and double checking the password from the portal and entering it when prompted, the publish failed. I knew the problem had something to do with the password because I could enter any bogus password and still get the same exact publish failed error.

What I did was click "Configure" on the publish tab of my project and click on "Validate Connection" on the "Connection" tab after entering the credentials again.

It was able to validate successfully and all subsequent publishes have been successful as well.


问:
Wrong position of dodged error bars when aes(group = ...) but not aes(fill/shape = ...)
Plotting error bars with position = "dodge" has caused me many headaches lately... Curiously, dodging them with the aesthetics shape or fill (which should not apply for error bars) seem to work well. However, dodging with aesthetics group places the bars in unexpected positions. I was wondering if this might be a ggplot2 bug.

I like placing custom error bars behind bar plots or boxplots. Sometimes I give special colors to different elements of my plots. For this reason, I often include aes() not in the ggplot() function, but in the geoms or stats.

Here is an example of "well placed" error bars:

library(ggplot2)
library(dplyr)

ToothGrowth %>%
  mutate(dose = factor(dose)) %>%
  ggplot(aes(dose, len)) +
  stat_boxplot(aes(fill = supp), geom = "errorbar", position = "dodge") +
  geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)
```

<p><img src="https://i.stack.imgur.com/nrZFe.png" alt="Plot1"></p>

<p>This produces the warning <code>Warning: Ignoring unknown aesthetics: fill</code>. Using <code>aes(shape = supp)</code> prints the same plot.</p>

<p>I would expect that same plot, but no warnings by exchanging fill/shape with "group" (<code>aes(group = supp)</code>). This produces no warnings, but a very unexpected result: </p>

<pre class="lang-r prettyprint-override"><code>ToothGrowth %>%
  mutate(dose = factor(dose)) %>%
  ggplot(aes(dose, len)) +
  stat_boxplot(aes(group = supp), geom = "errorbar", position = "dodge") +
  geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)
</code>```

Would someone have an explanation for this behavior? Shouldn't grouping with aes(group = ...) and aes(fill = ...) behave similarly on the dodge position?

答:
The code ignores  unknown aesthetics: fill

```<code>stat_boxplot(aes(fill = supp), geom = "errorbar", position = "dodge")
</code>```

Whereas the code considers the aesthetics group = supp and gives two errorbar each for OJ and VC.

```<code>stat_boxplot(aes(group = supp), geom = "errorbar", position = "dodge")
</code>```

Complete Code

```<code>library(ggplot2)
library(dplyr)

ToothGrowth %>%
  mutate(dose = factor(dose)) %>%
  ggplot(aes(dose, len)) +
  stat_boxplot(aes(fill = supp), geom = "errorbar", position = "dodge") +
  geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)

Warning: Ignoring unknown aesthetics: fill

ToothGrowth %>%
  mutate(dose = factor(dose)) %>%
  ggplot(aes(dose, len)) +
  stat_boxplot(aes(group = supp), geom = "errorbar", position = "dodge") +
  geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)
</code>```

Body:
Plotting error bars with position = "dodge" has caused me many headaches lately... Curiously, dodging them with the aesthetics shape or fill (which should not apply for error bars) seem to work well. However, dodging with aesthetics group places the bars in unexpected positions. I was wondering if this might be a ggplot2 bug.

I like placing custom error bars behind bar plots or boxplots. Sometimes I give special colors to different elements of my plots. For this reason, I often include aes() not in the ggplot() function, but in the geoms or stats.

Here is an example of "well placed" error bars:

library(ggplot2)
library(dplyr)

ToothGrowth %>%
  mutate(dose = factor(dose)) %>%
  ggplot(aes(dose, len)) +
  stat_boxplot(aes(fill = supp), geom = "errorbar", position = "dodge") +
  geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)

This produces the warning Warning: Ignoring unknown aesthetics: fill. Using aes(shape = supp) prints the same plot.

I would expect that same plot, but no warnings by exchanging fill/shape with "group" (aes(group = supp)). This produces no warnings, but a very unexpected result:

ToothGrowth %>%
  mutate(dose = factor(dose)) %>%
  ggplot(aes(dose, len)) +
  stat_boxplot(aes(group = supp), geom = "errorbar", position = "dodge") +
  geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)

Would someone have an explanation for this behavior? Shouldn't grouping with aes(group = ...) and aes(fill = ...) behave similarly on the dodge position?

Body:
The code ignores  unknown aesthetics: fill

stat_boxplot(aes(fill = supp), geom = "errorbar", position = "dodge")

Whereas the code considers the aesthetics group = supp and gives two errorbar each for OJ and VC.

stat_boxplot(aes(group = supp), geom = "errorbar", position = "dodge")

Complete Code

library(ggplot2)
library(dplyr)

ToothGrowth %>%
  mutate(dose = factor(dose)) %>%
  ggplot(aes(dose, len)) +
  stat_boxplot(aes(fill = supp), geom = "errorbar", position = "dodge") +
  geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)

Warning: Ignoring unknown aesthetics: fill

ToothGrowth %>%
  mutate(dose = factor(dose)) %>%
  ggplot(aes(dose, len)) +
  stat_boxplot(aes(group = supp), geom = "errorbar", position = "dodge") +
  geom_boxplot(aes(fill = supp), position = "dodge", coef = 0)


问:
Remove '_links' property from _embedded resources on zf-rest module
I'm using ZF2 with "zfcampus/zf-rest":"1.2.0" to return API results.

For a resource named Tag I receive the response below:

```<code>{
    "_links": {
        "self": {
            "href": "http://mydomain/article/tags"
        }
    },
    "_embedded": {
        "tags": [
            {
                "id": 1,
                "tag": "news",
                "isOfficial": true,
                "_links": {
                    "self": {
                        "href": "http://mydomain/article/tags"
                    }
                }
            }
        ]
    },
    "total_items": 1
}
</code>```

However, I would like to get rid of _links property under tags resource so I may have a cleaner output.

What I would like to achieve would look like this;

```<code>{
    "_links": {
        "self": {
            "href": "http://mydomain/article/tags"
        }
    },
    "_embedded": {
        "tags": [
            {
                "id": 1,
                "tag": "news",
                "isOfficial": true
            }
        ]
    },
    "total_items": 1
}
</code>```

How can I achieve this behavior?

Please mind that router for the endpoint is implemented as:

```<code>'api.rest.article.tags' => [
                'type'    => 'Segment',
                'options' => [
                    'route'    => '/article/tags',
                    'defaults' => [
                        'controller' => 'Api\V1\ArticleTag\Controller',
                    ],
                ],
            ],
</code>```

答:
When using ZF Hal you will get such a rendered result because self links are an essential part of the Hal-Json standard and your Tag is considered a Hal Resource and will be rendered as in your example above. You probably registered meta-data and a hydrator for this class and those are used for extracting the entity like that.

If you don't want to render the Tag as a Hal resource your solution could be as simple as removing the meta-data and hydrator for the class and simply implementing a JsonSerializable interface into your class and adding a jsonSerialize method that returns the desired result. The renderer will call jsonSerialize while rendering it instead...

When there is no Hydrator found and an object implements this JsonSerializable interface this is the fallback for extracting your object.

You can see that here in the extractEntity method:

```<code>if ($hydrator) {
    return $hydrator->extract($entity);
}
if ($entity instanceof JsonSerializable) {
    return $entity->jsonSerialize();
}
</code>```

Check this blog post on JsonSerializable: https://www.sitepoint.com/use-jsonserializable-interface/

Hope this will work for you, if not feel free to comment and I can see if I can suggest an alternative solution.

Body:
I'm using ZF2 with "zfcampus/zf-rest":"1.2.0" to return API results.

For a resource named Tag I receive the response below:

{
    "_links": {
        "self": {
            "href": "http://mydomain/article/tags"
        }
    },
    "_embedded": {
        "tags": [
            {
                "id": 1,
                "tag": "news",
                "isOfficial": true,
                "_links": {
                    "self": {
                        "href": "http://mydomain/article/tags"
                    }
                }
            }
        ]
    },
    "total_items": 1
}

However, I would like to get rid of _links property under tags resource so I may have a cleaner output.

What I would like to achieve would look like this;

{
    "_links": {
        "self": {
            "href": "http://mydomain/article/tags"
        }
    },
    "_embedded": {
        "tags": [
            {
                "id": 1,
                "tag": "news",
                "isOfficial": true
            }
        ]
    },
    "total_items": 1
}

How can I achieve this behavior?

Please mind that router for the endpoint is implemented as:

'api.rest.article.tags' => [
                'type'    => 'Segment',
                'options' => [
                    'route'    => '/article/tags',
                    'defaults' => [
                        'controller' => 'Api\V1\ArticleTag\Controller',
                    ],
                ],
            ],

Body:
When using ZF Hal you will get such a rendered result because self links are an essential part of the Hal-Json standard and your Tag is considered a Hal Resource and will be rendered as in your example above. You probably registered meta-data and a hydrator for this class and those are used for extracting the entity like that.

If you don't want to render the Tag as a Hal resource your solution could be as simple as removing the meta-data and hydrator for the class and simply implementing a JsonSerializable interface into your class and adding a jsonSerialize method that returns the desired result. The renderer will call jsonSerialize while rendering it instead...

When there is no Hydrator found and an object implements this JsonSerializable interface this is the fallback for extracting your object.

You can see that here in the extractEntity method:

if ($hydrator) {
    return $hydrator->extract($entity);
}
if ($entity instanceof JsonSerializable) {
    return $entity->jsonSerialize();
}

Check this blog post on JsonSerializable: https://www.sitepoint.com/use-jsonserializable-interface/

Hope this will work for you, if not feel free to comment and I can see if I can suggest an alternative solution.


问:
stop automatical convert to htmlentities?
I have a div id="ultimativegodemperorofalldivs"
It contains some Text like "such a cool & sexy div"

when I extract the InnerHTML with JS it converts the & to &
I really don't want this. I don't need it for URL's so it really should be a very simple &.
How to archive this?

Thx in Advance,
iceteea

答:
Instead of using innerHTML.you can use innerText

```<code>document.getElementById('ultimativegodemperorofalldivs').innerText
</code>```

Hope this helps!!!!

Body:
Instead of using innerHTML.you can use innerText

document.getElementById('ultimativegodemperorofalldivs').innerText

Hope this helps!!!!


问:
python converting a List of Tuples into a Dict with external keys
I have a list of tuples like this

```<code>[
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
]
</code>```

The result should be a list of dictionaries

```<code>[
{'id': 1, 'label': 'a'},
{'id': 2, 'label': 'b'},
{'id': 3, 'label': 'c'},
{'id': 4, 'label': 'd'},
{'id': 5, 'label': 'e'}
]
</code>```

I'm using python 3.6

The first value in every tuple is named as 'id' and the second value
in every tuple is named as 'label'.

I want to get the above result without using loop since the data will be huge.
Is there any built-in method to achieve my result?

答:
A simple comprehension will do:

```<code>l = [
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
]
results = [{"id" : id, "label": label} for id, label in l]
</code>```

If your data is too big you can use a generator (so it will be lazily evaluated):

```<code>    results = ({"id" : id, "label": label} for id, label in l)
</code>```

Or use map:

```<code>    results = map(lambda x: {"id" : x[0], "label": x[1]}, l)
</code>```

Body:
I have a list of tuples like this

[
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
]

The result should be a list of dictionaries

[
{'id': 1, 'label': 'a'},
{'id': 2, 'label': 'b'},
{'id': 3, 'label': 'c'},
{'id': 4, 'label': 'd'},
{'id': 5, 'label': 'e'}
]

I'm using python 3.6

The first value in every tuple is named as 'id' and the second value
in every tuple is named as 'label'.

I want to get the above result without using loop since the data will be huge.
Is there any built-in method to achieve my result?

Body:
A simple comprehension will do:

l = [
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d'),
(5,'e')
]
results = [{"id" : id, "label": label} for id, label in l]

If your data is too big you can use a generator (so it will be lazily evaluated):

    results = ({"id" : id, "label": label} for id, label in l)

Or use map:

    results = map(lambda x: {"id" : x[0], "label": x[1]}, l)


问:
Calling addEventListener or using onscroll handler?
I have two approaches making my element scroll on the window which both work but what are the two differences and which one is a better approach. Thanks!

First approach

```<code>window.onscroll = function() {rotate()};

function rotate(){
}
</code>```

Second approach

```<code>window.addEventListener('scroll', rotate);

function rotate(){
}
</code>```

答:
addEventListener:
The addEventListener() method attaches an event handler to the specified element.
It handles more than one Event.
For example:

```<code>document.getElementById("myBtn").addEventListener("click", function(){
  document.getElementById("demo").innerHTML = "Hello World";
});
</code>```

The onscroll event occurs when an element's scrollbar is being scrolled.
it handles only one event.

onscroll work try this link:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onscroll

Body:
I have two approaches making my element scroll on the window which both work but what are the two differences and which one is a better approach. Thanks!

First approach

window.onscroll = function() {rotate()};

function rotate(){
}

Second approach

window.addEventListener('scroll', rotate);

function rotate(){
}

Body:
addEventListener:
The addEventListener() method attaches an event handler to the specified element.
It handles more than one Event.
For example:

document.getElementById("myBtn").addEventListener("click", function(){
  document.getElementById("demo").innerHTML = "Hello World";
});

The onscroll event occurs when an element's scrollbar is being scrolled.
it handles only one event.

onscroll work try this link:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onscroll