问:
How to handle streaming data using fetch?
I have used async for with great success in handling output streams from processes with node.js, but I'm struggling to get something that I was hoping could "just work" with the browser fetch API.

This works great to async'ly handle chunks of output streaming from a process:

```<code>for await (const out of proc.child.stdout) {
  ...
}
</code>```

(in an async function context here of course)

I tried to do something similar in a browser where I want to gain access to the data while it is being sent to me from the server.

```<code>for await (const chunk of (await fetch('/data.jsonl')).body) {
  console.log('got', chunk);
}
</code>```

This does not work in Chrome (Uncaught TypeError: (intermediate value).body is not async iterable).

For my use case this is not necessary, so I am simply using let data = await (await fetch(datapath)).text(); in my client code for now. This is analogous to the typical use of .json() instead of .text() on the awaited fetch, so no processing can begin until the entire response is received by the browser. This is not ideal for obvious reasons.

I was looking at Oboe.js (I think the relevant impl is somewhere near here) which pretty much deals with this but its internals are fairly ugly so it looks like that might be the only way to do this for now?

If async iteration isn't implemented (meaning async for cannot be used yet) isn't there another way to use the ReadableStream in a practical way?

答:
I believe the current state of affairs in mid 2020 is that async for does not work on the fetch body yet.

https://github.com/whatwg/streams/issues/778 This issue appears to have tracking bugs for browsers and none of them have the functionality implemented yet.

I don't currently know of another way to make use of the .body ReadableStream provided by fetch.

The standard way to do the task implicit in the question is to use a websocket.

Body:
I have used async for with great success in handling output streams from processes with node.js, but I'm struggling to get something that I was hoping could "just work" with the browser fetch API.

This works great to async'ly handle chunks of output streaming from a process:

for await (const out of proc.child.stdout) {
  ...
}

(in an async function context here of course)

I tried to do something similar in a browser where I want to gain access to the data while it is being sent to me from the server.

for await (const chunk of (await fetch('/data.jsonl')).body) {
  console.log('got', chunk);
}

This does not work in Chrome (Uncaught TypeError: (intermediate value).body is not async iterable).

For my use case this is not necessary, so I am simply using let data = await (await fetch(datapath)).text(); in my client code for now. This is analogous to the typical use of .json() instead of .text() on the awaited fetch, so no processing can begin until the entire response is received by the browser. This is not ideal for obvious reasons.

I was looking at Oboe.js (I think the relevant impl is somewhere near here) which pretty much deals with this but its internals are fairly ugly so it looks like that might be the only way to do this for now?

If async iteration isn't implemented (meaning async for cannot be used yet) isn't there another way to use the ReadableStream in a practical way?


来源: stackexchange

问:
How to wait in a continuous loop in servlet?
I am developing a servlet based application. One situation is that a client requests some data from a database which is sent back in the form of html. The client will modify this data and then sent it back to the server. Now the twist starts. There is not a single client. So multiple clients can request the same data. So what I am doing is that when the first client makes a request, this request is stored somewhere so that when the next user makes the same request he is denied the data.

Now suppose the first user gets the data and 2nd is denied. Now while the first user is on the html page which allows him to modify the data. I want to send continuous javascript async post requests at a fixed interval to inform the server that the client is active.

At the server side I need a thread or something which can keep waiting in a loop for the javascript async requests and if the request is not received within the fixed time then the thread removes the saved request so that future requests to the data will be accepted.

I have searched the entire day and looked at things like async servlets, ServletContext listener and scheduledExecutorservice. I dont want to use scheduledExecutorService as it is invoked at app startUp which I dont want to do since this specific situation is a minor part of the code and to handle it I dont want something running all the time. I need some background service which keeps running even after the server has returned requested data.

答:
Servlets won't fulfill your requirements, therefore you should use WebSockets.

As per my understanding, you are trying to push data from the server, therefore you need to a push architecture instead of pull architecture (Servlets are based upon pull architecture).

Java has native support of WebSockets

You can find several tutorials on how to use WebSockets in a Java Web Application.

Here is a link to a basic WebSockets Tutorial.

Hope this helps

ContentLicense: CC BY-SA 4.0


问:
When should I use curly braces for ES6 import?
It seems to be obvious, but I found myself a bit confused about when to use curly braces for importing a single module in ES6. For example, in the React-Native project I am working on, I have the following file and its content:

File initialState.js

```<code>var initialState = {
    todo: {
        todos: [
            {id: 1, task: 'Finish Coding', completed: false},
            {id: 2, task: 'Do Laundry', completed: false},
            {id: 2, task: 'Shopping Groceries', completed: false},
        ]
    }
};

export default initialState;
</code>```

In the TodoReducer.js, I have to import it without curly braces:

```<code>import initialState from './todoInitialState';
</code>```

If I enclose the initialState in curly braces, I get the following error for the following line of code:

Cannot read property todo of undefined

File TodoReducer.js:

```<code>export default function todos(state = initialState.todo, action) {
    // ...
}
</code>```

Similar errors also happen to my components with the curly braces. I was wondering when I should use curly braces for a single import, because obviously, when importing multiple component/modules, you have to enclose them in curly braces, which I know.

The Stack Overflow post at here does not answer my question, instead I am asking when I should or should not use curly braces for importing a single module, or I should never use curly braces for importing a single module in ES6 (this is apparently not the case, as I have seen single import with curly braces required).

答:
For a default export we do not use { } when we import.

For example,

File player.js

```<code>export default vx;
</code>```

File index.js

```<code>import vx from './player';
</code>```

File index.js

File player.js

If we want to import everything that we export then we use *:

Body:
It seems to be obvious, but I found myself a bit confused about when to use curly braces for importing a single module in ES6. For example, in the React-Native project I am working on, I have the following file and its content:

File initialState.js

var initialState = {
    todo: {
        todos: [
            {id: 1, task: 'Finish Coding', completed: false},
            {id: 2, task: 'Do Laundry', completed: false},
            {id: 2, task: 'Shopping Groceries', completed: false},
        ]
    }
};

export default initialState;

In the TodoReducer.js, I have to import it without curly braces:

import initialState from './todoInitialState';

If I enclose the initialState in curly braces, I get the following error for the following line of code:

Cannot read property todo of undefined

File TodoReducer.js:

export default function todos(state = initialState.todo, action) {
    // ...
}

Similar errors also happen to my components with the curly braces. I was wondering when I should use curly braces for a single import, because obviously, when importing multiple component/modules, you have to enclose them in curly braces, which I know.

The Stack Overflow post at here does not answer my question, instead I am asking when I should or should not use curly braces for importing a single module, or I should never use curly braces for importing a single module in ES6 (this is apparently not the case, as I have seen single import with curly braces required).

Body:
For a default export we do not use { } when we import.

For example,

File player.js

export default vx;

File index.js

import vx from './player';

File index.js

File player.js

If we want to import everything that we export then we use *:


问:
CSS: navbar items on top of each other?
in my page the navbar menu items show on top of each other.

Why?

Codepen:

https://codepen.io/ogonzales/pen/mdeNNLB

Code:

```<code><nav class="navbar navbar-expand-md navbar-light fixed-top" style="height: 70px;" id="top-navbar">
    <img src="" alt="Ministerios Elim" width="2%" height="50%"/>
    <a class="navbar-brand" href="" style="margin-right: 5%;"><span style="margin-left: 3%;">Ministerios Elim</span></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse"
        aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarCollapse">
        <ul>
            <li>
                <a href="/">Home</a>
            </li>
            {% for item in navigation.menu_items.all %}
                <li>
                    <a href="{{ item.link }}" class="nav-link" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a>
                </li>
            {% endfor %}
        </ul>
        <form class="form-inline ml-auto">
            <a href="" class="btn btn-outline-secondary">Ingresar</a>
            <a href="" class="btn btn-primary ml-2">Registro</a>
        </form>
    </div>
</nav>
</code>```

答:
This is the default behaviour of items inside an unordered list (ul), which are block elements. You need to make them inline-block if you want them to appear on one line.

For example, try adding this code to your CSS:

#navbarCollapse ul li {
  display: inline-block;
}
```

You will see that the items are no longer all underneath each other.

If the options still don't all appear on one line, you are probably having the problem (at least it looks to me like you would, from your codepen you have provided) that the width of your container is not large enough to fit all the elements in it.

Consider making this wider, or displaying less navigation options if design constraints and screen sizes don't allow any more.

Title: CSS: navbar items on top of each other?

Body:
in my page the navbar menu items show on top of each other.

Why?

Codepen:

https://codepen.io/ogonzales/pen/mdeNNLB

Code:

    Ministerios Elim
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse"
        aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Home

            {% for item in navigation.menu_items.all %}

                    {{ item.title }}

            {% endfor %}

        <form class="form-inline ml-auto">
            Ingresar
            Registro
        </form>

Body:
This is the default behaviour of items inside an unordered list (ul), which are block elements. You need to make them inline-block if you want them to appear on one line.

For example, try adding this code to your CSS:

#navbarCollapse ul li {
  display: inline-block;
}

You will see that the items are no longer all underneath each other.

If the options still don't all appear on one line, you are probably having the problem (at least it looks to me like you would, from your codepen you have provided) that the width of your container is not large enough to fit all the elements in it.

Consider making this wider, or displaying less navigation options if design constraints and screen sizes don't allow any more.


问:
How to get a horizontal picker for Swift UI?
Is there an existing solution to get a horizontal picker in Swift UI?

Example for Swift: https://github.com/akkyie/AKPickerView-Swift

答:
I ended up solving this using a horizontal scrollview, tap gestures, and state to track the selection.</p>

```<code>@State private var index

var body: some View {

        return ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(0..<self.items.count, id: \.self) { i in
                    Text("\(i)")
                        .foregroundColor(self.index == i ? .red : .black)
                        .frame(width: 20, height: 20)
                        .gesture(TapGesture().onEnded({ self.index = i }))
                }
            }
        }
        .frame(width: self.width, alignment: .leading)
}
</code>```

Body:
I ended up solving this using a horizontal scrollview, tap gestures, and state to track the selection.

@State private var index

var body: some View {

        return ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(0..<self.items.count, id: \.self) { i in
                    Text("\(i)")
                        .foregroundColor(self.index == i ? .red : .black)
                        .frame(width: 20, height: 20)
                        .gesture(TapGesture().onEnded({ self.index = i }))
                }
            }
        }
        .frame(width: self.width, alignment: .leading)
}


问:
How to create an array for storing x and y coordinates in Python
I am trying to read the description of a polygon from a file and compute the area of the polygon according to the description.

So far my approach:

```<code>#Function for computing area of a polygen
def polygonArea(A):
    n = len(A)  # of corners
    area = 0.0
    j = n - 1
    for i in range(n):
        area += (A[0][j] + A[0][i]) * (A[1][j] - A[1][i])
    area = abs(area) / 2.0

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""
    if fileContent > data and data == "(":
        data.join(fileContent)
        if data == "N":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file>temp:
                yb += temp
                A[1].append(yb) #Storing the value in y co ordinate of vector A
                A[0].append(xa) #Storing the value in x co ordinate of vector A
         if data == "W":
             data.join(fileContent)
             if data != ",":
                 print("Description is wrong!")
             if file > temp:
                 xa -= temp
                 A[1].append(yb)
                 A[0].append(xa)
        if data == "E":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa += temp
                A[1].append(yb)
                A[0].append(xa)
        if data == "S":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa -= temp
                A[1].append(yb)
                A[0].append(xa)

#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)
</code>```

答:
If you can get the coordinate of all the points going either clockwise or counter-clockwise, starting at any vertex, you can use this formula:

You can put that formula into a python program:

```<code>def polygon(x1,y1,x2,y2,x3,y3,x4,y4):
    area = abs(((x1*y2-y1*x2)+(x2*y3-y2*x3)+(x3*y4-y3*x4)+(x4*y1-y4*x1))/2)
    return area

print(polygon(4,4,4,0,0,0,0,4))
</code>```

Output:

```<code>16.0
</code>```

Body:
I am trying to read the description of a polygon from a file and compute the area of the polygon according to the description.

So far my approach:

#Function for computing area of a polygen
def polygonArea(A):
    n = len(A)  # of corners
    area = 0.0
    j = n - 1
    for i in range(n):
        area += (A[0][j] + A[0][i]) * (A[1][j] - A[1][i])
    area = abs(area) / 2.0

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""
    if fileContent > data and data == "(":
        data.join(fileContent)
        if data == "N":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file>temp:
                yb += temp
                A[1].append(yb) #Storing the value in y co ordinate of vector A
                A[0].append(xa) #Storing the value in x co ordinate of vector A
         if data == "W":
             data.join(fileContent)
             if data != ",":
                 print("Description is wrong!")
             if file > temp:
                 xa -= temp
                 A[1].append(yb)
                 A[0].append(xa)
        if data == "E":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa += temp
                A[1].append(yb)
                A[0].append(xa)
        if data == "S":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa -= temp
                A[1].append(yb)
                A[0].append(xa)

#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)

Body:
If you can get the coordinate of all the points going either clockwise or counter-clockwise, starting at any vertex, you can use this formula:

You can put that formula into a python program:

def polygon(x1,y1,x2,y2,x3,y3,x4,y4):
    area = abs(((x1*y2-y1*x2)+(x2*y3-y2*x3)+(x3*y4-y3*x4)+(x4*y1-y4*x1))/2)
    return area

print(polygon(4,4,4,0,0,0,0,4))

Output:

16.0


问:
Numpy outputting unicode from tostring()
```<code> if request.method == "POST":
    data = [[1,1]]
    data = sc.transform(data)
    rfc = RandomForestClassifier(n_estimators = 200)
    rfc.fit(X_train, y_train)
    my_prediction = rfc.predict(data)
    return my_prediction.tostring()
</code>```

Somehow the code outputs � �V�.

This is also returned in Flask so I don't know if that is part of the problem.

答:
I ended up converting the array to a list and then to a string with join. Don't know what caused this but it worked.</p>

```<code>  if request.method == "POST":
    genderquery = request.form['genderquery']
    agequery = request.form['agequery']
    data = [[genderquery,agequery]]
    data = sc.transform(data)
    rfc = RandomForestClassifier(n_estimators = 200)
    rfc.fit(X_train, y_train)
    my_prediction = rfc.predict(data)
    my_prediction = my_prediction.tolist()
    my_prediction = ''.join(my_prediction)
    print(my_prediction)
    return render_template('results.html',prediction = my_prediction, gender = genderquery.upper())
</code>```

Body:
 if request.method == "POST":
    data = [[1,1]]
    data = sc.transform(data)
    rfc = RandomForestClassifier(n_estimators = 200)
    rfc.fit(X_train, y_train)
    my_prediction = rfc.predict(data)
    return my_prediction.tostring()

Somehow the code outputs � �V�.

This is also returned in Flask so I don't know if that is part of the problem.

Body:
I ended up converting the array to a list and then to a string with join. Don't know what caused this but it worked.

  if request.method == "POST":
    genderquery = request.form['genderquery']
    agequery = request.form['agequery']
    data = [[genderquery,agequery]]
    data = sc.transform(data)
    rfc = RandomForestClassifier(n_estimators = 200)
    rfc.fit(X_train, y_train)
    my_prediction = rfc.predict(data)
    my_prediction = my_prediction.tolist()
    my_prediction = ''.join(my_prediction)
    print(my_prediction)
    return render_template('results.html',prediction = my_prediction, gender = genderquery.upper())


问:
Modifying list of related objects asynchronously yields unexpected results
I have a list of objects which can have one or more relationships to one another. I'd like to run through this list and compare each object to all other objects in the list, setting the relationships as I compare the objects. Because this comparison in real life is fairly complex and time consuming I'm trying to do this asynchronously.

I've quickly put together some sample code which illustrates the issue at hand in a fairly simple fashion.

```<code>class Program
    {
        private static readonly Word[] _words =
        {
            new Word("Beef"),
            new Word("Bull"),
            new Word("Space")
        };

        static void Main()
        {
            var tasks = new List<Task>();

            foreach (var word in _words)
            {
                tasks.Add(CheckRelationShipsAsnc(word));
            }

            Task.WhenAll(tasks);
        }

        static async Task CheckRelationShipsAsnc(Word leftWord)
        {
            await Task.Run(() =>
            {
                foreach (var rightWord in _words)
                {
                    if(leftWord.Text.First() == rightWord.Text.First())
                    {
                        leftWord.RelationShips.Add(rightWord);
                    }
                }
            });
        }
    }

    class Word
    {
        public string Text { get; }
        public List<Word> RelationShips { get; } = new List<Word>();

        public Word(string text)
        {
            if(string.IsNullOrEmpty(text)) throw new ArgumentException();
            Text = text;
        }

        public override string ToString()
        {
            return $"{Text} ({RelationShips.Count} relationships)";
        }
    }
</code>```

The expected result would be that "Space" has no relationships whereas the words "Bull" and "Beef" have one relationship to one another. What I get is all words have no relationsships at all. I'm having trouble understanding what exactly the problem is.

答:
You should make Main method async as well and await Task.WhenAll. Otherwise the result task for WhenAll will not run its execution. You can also simplify tasks creation using Linq

static async Task Main()
{
    var tasks = _words.Select(CheckRelationShipsAsync);
    await Task.WhenAll(tasks);
}
```

<p>You can also use <code>Wait()</code> or <code>WaitAll</code> method, which runs synchronously and blocks the current thread (so, it isn't a recommend approach). But it doesn't require to make <code>Main</code> method <code>async</code></p>

<pre class="lang-cs prettyprint-override"><code>var tasks = _words.Select(CheckRelationShipsAsync);
var task = Task.WhenAll(tasks);
task.Wait();
</code>```

or

static void  Main()
{
    var tasks = _words.Select(CheckRelationShipsAsync);
    Task.WaitAll(tasks.ToArray());
}
```

Second point is that when you check the relationships you haven't skip the word itself, and every word at the end has relationship with itself. You should add leftWord != rightWord condition inside foreach loop to get an expected result

The expected result would be that "Space" has no relationships whereas
  the words "Bull" and "Beef" have one relationship to one another.

Body:
I have a list of objects which can have one or more relationships to one another. I'd like to run through this list and compare each object to all other objects in the list, setting the relationships as I compare the objects. Because this comparison in real life is fairly complex and time consuming I'm trying to do this asynchronously.

I've quickly put together some sample code which illustrates the issue at hand in a fairly simple fashion.

class Program
    {
        private static readonly Word[] _words =
        {
            new Word("Beef"),
            new Word("Bull"),
            new Word("Space")
        };

        static void Main()
        {
            var tasks = new List<Task>();

            foreach (var word in _words)
            {
                tasks.Add(CheckRelationShipsAsnc(word));
            }

            Task.WhenAll(tasks);
        }

        static async Task CheckRelationShipsAsnc(Word leftWord)
        {
            await Task.Run(() =>
            {
                foreach (var rightWord in _words)
                {
                    if(leftWord.Text.First() == rightWord.Text.First())
                    {
                        leftWord.RelationShips.Add(rightWord);
                    }
                }
            });
        }
    }

    class Word
    {
        public string Text { get; }
        public List<Word> RelationShips { get; } = new List<Word>();

        public Word(string text)
        {
            if(string.IsNullOrEmpty(text)) throw new ArgumentException();
            Text = text;
        }

        public override string ToString()
        {
            return $"{Text} ({RelationShips.Count} relationships)";
        }
    }

The expected result would be that "Space" has no relationships whereas the words "Bull" and "Beef" have one relationship to one another. What I get is all words have no relationsships at all. I'm having trouble understanding what exactly the problem is.

Body:
You should make Main method async as well and await Task.WhenAll. Otherwise the result task for WhenAll will not run its execution. You can also simplify tasks creation using Linq

static async Task Main()
{
    var tasks = _words.Select(CheckRelationShipsAsync);
    await Task.WhenAll(tasks);
}

You can also use Wait() or WaitAll method, which runs synchronously and blocks the current thread (so, it isn't a recommend approach). But it doesn't require to make Main method async

var tasks = _words.Select(CheckRelationShipsAsync);
var task = Task.WhenAll(tasks);
task.Wait();

or

static void  Main()
{
    var tasks = _words.Select(CheckRelationShipsAsync);
    Task.WaitAll(tasks.ToArray());
}

Second point is that when you check the relationships you haven't skip the word itself, and every word at the end has relationship with itself. You should add leftWord != rightWord condition inside foreach loop to get an expected result

The expected result would be that "Space" has no relationships whereas
  the words "Bull" and "Beef" have one relationship to one another.


问:
C#: how to handle floats properly
In my code i write the following line:

```<code>return ((value / 120) * 1440).ToString();
</code>```

Now this returns me 0 when the value in value is less than Zero because it treats the result of (value / 120) as an integer where as i need C# to treat this result as float is there any way to achieve this?

Example:
If Value = 80

Then,
This function returns me 0 whereas i want this function to return me 960

答:
If you specifically want a single-precision float you can use 120.0f, or 120.0 for a double-precision (double).

You can read up on floating-point literals for more information.

ContentLicense: CC BY-SA 3.0

Title: C#: how to handle floats properly

Body:
In my code i write the following line:

return ((value / 120) * 1440).ToString();

Now this returns me 0 when the value in value is less than Zero because it treats the result of (value / 120) as an integer where as i need C# to treat this result as float is there any way to achieve this?

Example:
If Value = 80

Then,
This function returns me 0 whereas i want this function to return me 960


问:
Jekyll Kramdown preserve new lines
I need to find a way to make Kramdown preserve new lines in jekyll posts which are writen in markdown

for example this text:

```<code>Hello
darkness
my
old
firend
</code>```

is ouputed as:

Hellodarknessmyoldfriend

```

<p>and I want it to be:</p>

<pre class="lang-html prettyprint-override"><code><p>Hello<br/>darkness<br/>my<br/>old<br/>friend</p>
</code>```

How to config kramdown to do this ?

答:
In Markdown a linebreak is added with a backslash (\) at the end of the line in question.

Hello\
darkness\
my\
old\
friend
```

<p>Output:</p>

<pre class="lang-html prettyprint-override"><code><p>Hello<br/>darkness<br/>my<br/>old<br/>friend</p>
</code>```

Per the official Kramdown docs, you need two backslashes, but I tested this in one of my projects and it works as listed above.

If you're not trimming whitespace, you could use two spaces at the end of the line, but that's still something extra you'd need to add.

If you are looking for a way to add nothing at the end and have a line-return create a
 tag, there is no way to do this.

Title: Jekyll Kramdown preserve new lines

Body:
I need to find a way to make Kramdown preserve new lines in jekyll posts which are writen in markdown

for example this text:

Hello
darkness
my
old
firend

is ouputed as:

Hellodarknessmyoldfriend

and I want it to be:

Hello
darkness
my
old
friend

How to config kramdown to do this ?

Body:
In Markdown a linebreak is added with a backslash (\) at the end of the line in question.

Hello\
darkness\
my\
old\
friend

Output:

<p>Hello<br/>darkness<br/>my<br/>old<br/>friend</p>

Per the official Kramdown docs, you need two backslashes, but I tested this in one of my projects and it works as listed above.

If you're not trimming whitespace, you could use two spaces at the end of the line, but that's still something extra you'd need to add.

If you are looking for a way to add nothing at the end and have a line-return create a <br> tag, there is no way to do this.


问:
Error: element is not assignable to type string in react
The output that I was getting is with html tags; hence I used dangerouslySetInnerHTML to avoid that after which I am getting the error "Type '{ contents: Element; }' is not assignable to type 'string'."

My react code is as follows:

```<code>import * as React from 'react';
import { RouteComponentProps } from 'react-router';

interface FetchImageDataState {
imageList: ImageData[];
loading: boolean;
}

export class OurTeam extends React.Component<RouteComponentProps<{}>, FetchImageDataState> {
constructor() {
    super();
    this.state = { imageList: [], loading: true }; //initialize to default

    fetch('api/Home/ourTeam')
        .then(response => response.json() as Promise<ImageData[]>)
        .then(data => {
            this.setState({ imageList: data, loading: false });
        });
}

public render() {

    let contents = this.state.loading ? <p><em>Loading...</em></p> : this.renderImageTable(this.state.imageList);
    let body = { contents };
    return <div>
        <h1>Team</h1>

        <div dangerouslySetInnerHTML={{ __html: body }} />
            </div>;
}

private renderImageTable(imageList: ImageData[]) {
    return <div className='table'>
        {imageList.map(x =>
            <div key={x.byteData} >{[x]}</div>)
    }</div>;
}

}

export class ImageData {
byteData: string = "";
}
</code>```

Without usage of dangerouslySetInnerHTML the output of the code was desired text with html tags; and also the image tag was displayed instead of image. The detailed error is:
ERROR in [at-loader] ./ClientApp/components/OurTeam.tsx:41:18
    TS2322: Type '{ dangerouslySetInnerHTML: { __html: { contents: Element; }; }; }' is not assignable to type 'HTMLProps'.
  Types of property 'dangerouslySetInnerHTML' are incompatible.
    Type '{ __html: { contents: Element; }; }' is not assignable to type '{ __html: string; } | undefined'.
      Type '{ __html: { contents: Element; }; }' is not assignable to type '{ __html: string; }'.
        Types of property '__html' are incompatible.
          Type '{ contents: Element; }' is not assignable to type 'string'.

I am new to react, please help to resolve the issue.

答:
You seem to be compicating it more than it should be the below code should work fine. use a ternary operator to check if loading is true and render html or JSX based on that and also best to make the call when the component mounts

```<code>import React,{Fragment} from 'react';
export class OurTeam extends Component {
   constructor() {
    super();
    this.state = { imageList: [], loading: true }; //initialize to default

}

  componentDidMount(){
    fetch('api/Home/ourTeam')
        .then(response => response.json())
        .then(data => {
            this.setState({ imageList: data, loading: false });
        }).catch(err=>{
         console.log(err);
         }};
  }

 render() {
    return (<div>
        <h1>Team</h1>
      {this.state.loading ?
        <Fragment>
         <p><em>Loading...</em></p>
        </Fragment>
        :
       <Fragment>
        <div className='table'>
         this.state.imageList.map(x =>
             <div key={x.byteData} >{[x]}</div>)
           </div>
      </Fragment>});
}}}
</code>```

Body:
The output that I was getting is with html tags; hence I used dangerouslySetInnerHTML to avoid that after which I am getting the error "Type '{ contents: Element; }' is not assignable to type 'string'."

My react code is as follows:

import * as React from 'react';
import { RouteComponentProps } from 'react-router';

interface FetchImageDataState {
imageList: ImageData[];
loading: boolean;
}

export class OurTeam extends React.Component<RouteComponentProps<{}>, FetchImageDataState> {
constructor() {
    super();
    this.state = { imageList: [], loading: true }; //initialize to default

    fetch('api/Home/ourTeam')
        .then(response => response.json() as Promise<ImageData[]>)
        .then(data => {
            this.setState({ imageList: data, loading: false });
        });
}

public render() {

    let contents = this.state.loading ?
Loading...
 : this.renderImageTable(this.state.imageList);
    let body = { contents };
    return

Team

;
}

private renderImageTable(imageList: ImageData[]) {
    return

        {imageList.map(x =>

{[x]}
)
    }
;
}

}

export class ImageData {
byteData: string = "";
}

Without usage of dangerouslySetInnerHTML the output of the code was desired text with html tags; and also the image tag was displayed instead of image. The detailed error is:
ERROR in [at-loader] ./ClientApp/components/OurTeam.tsx:41:18
    TS2322: Type '{ dangerouslySetInnerHTML: { __html: { contents: Element; }; }; }' is not assignable to type 'HTMLProps'.
  Types of property 'dangerouslySetInnerHTML' are incompatible.
    Type '{ __html: { contents: Element; }; }' is not assignable to type '{ __html: string; } | undefined'.
      Type '{ __html: { contents: Element; }; }' is not assignable to type '{ __html: string; }'.
        Types of property '__html' are incompatible.
          Type '{ contents: Element; }' is not assignable to type 'string'.

I am new to react, please help to resolve the issue.

Body:
You seem to be compicating it more than it should be the below code should work fine. use a ternary operator to check if loading is true and render html or JSX based on that and also best to make the call when the component mounts

import React,{Fragment} from 'react';
export class OurTeam extends Component {
   constructor() {
    super();
    this.state = { imageList: [], loading: true }; //initialize to default

}

  componentDidMount(){
    fetch('api/Home/ourTeam')
        .then(response => response.json())
        .then(data => {
            this.setState({ imageList: data, loading: false });
        }).catch(err=>{
         console.log(err);
         }};
  }

 render() {
    return (<div>
        <h1>Team</h1>
      {this.state.loading ?
        <Fragment>
         <p><em>Loading...</em></p>
        </Fragment>
        :
       <Fragment>
        <div className='table'>
         this.state.imageList.map(x =>
             <div key={x.byteData} >{[x]}</div>)
           </div>
      </Fragment>});
}}}


问:
Using CodeCompare with git from WSL
I really like Devart's CodeCompare and its excellent integration with Visual Studio. However, these days I do development in VSCode under WSL2. VSCode has a pretty decent diff and merge tool but it cannot be compared to CodeCompare (no pun intended). I really want to use CodeCompare from VSCode (Devart please look into it - this is the most popular dev.environment these days) or just from the good ole Linux git CLI.</p>

答:
This is what I came up with. If someone has a better suggestion (this one is a little slow), please share it.
So, I added these lines to my ~/.gitconfig:</p>
```<code>[diff]
    tool = codecompare
    guitool = codecompare

[difftool "codecompare"]
    cmd = \"${ProgramFilesW64}/Devart/Code Compare/CodeCompare.exe\" /SC=git /ENVIRONMENT=standalone /W /T1="ours" /T2="theirs" \"$(wslpath -w $LOCAL)\" \"$(wslpath -w $REMOTE)\"
    renames = true

[merge]
    tool = codecompare
    guitool = codecompare

[mergetool "codecompare"]
    cmd = \"${ProgramFilesW64}/Devart/Code Compare/CodeMerge.exe\" /SC=git /ENVIRONMENT=standalone /MF=\"`wslpath -m $LOCAL`\" /TF=\"`wslpath -m $REMOTE`\" /BF=\"`wslpath -m $BASE`\" /RF=\"`wslpath -m $MERGED`\" /MT="ours-HEAD" /TT="theirs" /RT="result" /BT="base"
    trustExitCode = true

[mergetool]
    keepBackup = false
</code>```

Title: Using CodeCompare with git from WSL

Body:
This is what I came up with. If someone has a better suggestion (this one is a little slow), please share it.
So, I added these lines to my ~/.gitconfig:

[diff]
    tool = codecompare
    guitool = codecompare

[difftool "codecompare"]
    cmd = \"${ProgramFilesW64}/Devart/Code Compare/CodeCompare.exe\" /SC=git /ENVIRONMENT=standalone /W /T1="ours" /T2="theirs" \"$(wslpath -w $LOCAL)\" \"$(wslpath -w $REMOTE)\"
    renames = true

[merge]
    tool = codecompare
    guitool = codecompare

[mergetool "codecompare"]
    cmd = \"${ProgramFilesW64}/Devart/Code Compare/CodeMerge.exe\" /SC=git /ENVIRONMENT=standalone /MF=\"`wslpath -m $LOCAL`\" /TF=\"`wslpath -m $REMOTE`\" /BF=\"`wslpath -m $BASE`\" /RF=\"`wslpath -m $MERGED`\" /MT="ours-HEAD" /TT="theirs" /RT="result" /BT="base"
    trustExitCode = true

[mergetool]
    keepBackup = false


问:
Center button in MailChimp

Hello,

How can I center a MailChimp button? The button is centered on desktop, but is shifted right on mobile devices, see the picture. I have been trying playing around with some classes and id's but can not solve it really. Not all the CSS code is necessary I guess. Sorry, I know it is messy. (In the HTML I have HIDDEN... the API-key)

Here is the HTML:

```<code><!-- Begin Mailchimp Signup Form -->
<div id="mc_embed_signup">
<form id="mc-embedded-subscribe-form" class="validate" action="https://hotmail.us4.list-manage.com/subscribe/post? HIDDEN... " method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank">
<div id="mc_embed_signup_scroll">
<span class="text1">Ta del av vårt nyhetsbrev!</span>
<input id="mce-EMAIL" class="email" name="EMAIL" required="" type="email" value="" placeholder="Skriv din e-post här!" />
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input tabindex="-1" name=" HIDDEN...
    " type="text" value="" /></div>
<div class="clear">
   <center><input id="mc-embedded-subscribe" class="button2" name="subscribe" type="submit"
   value="Prenumerera" />
   </center>
</div>
</div>
</form></div>
<!--End mc_embed_signup-->
</code>```

Here are some CSS:

```<code>.button2 {
   display: inline-block;
   text-align: center;
  font-family: lora !important;
/*    vertical-align: bottom;*/
 /*  padding-bottom: 0px !important;*/
 margin:auto !important;
   height:34px !important;
 line-height :34px !important;
   padding: 5px 12px !important;
   border: 1px solid #aeb11b;
   border-radius: 8px;
   background: #f8fd27!important;
   background: -webkit-gradient(linear, left top, left bottom, from(#f8fd27), to(#aeb11b))!important;
   background: -moz-linear-gradient(top, #f8fd27, #aeb11b)!important;
   background: linear-gradient(to bottom, #f8fd27, #aeb11b)!important;
   -webkit-box-shadow: #8d1bb3 0px 0px 24px 0px!important;
   -moz-box-shadow: #8d1bb3 0px 0px 24px 0px!important;
   box-shadow: #8d1bb3 0px 0px 24px 0px!important;
   text-shadow: #ffff33 1px 1px 1px!important;
   font: normal normal bold 20px arial!important;
   color: #111111!important;
   text-decoration: none!important;
}

.button2:hover,
.button2:focus {
   border: 1px solid #f8fd27!important;[![enter image description here][1]][1]
   background: #ffff2f!important;
   background: -webkit-gradient(linear, left top, left bottom, from(#ffff2f), to(#d1d420))!important;
   background: -moz-linear-gradient(top, #ffff2f, #d1d420)!important;
   background: linear-gradient(to bottom, #ffff2f, #d1d420)!important;
   color: #111111!important;
}
.button2:active {
   background: #aeb11b!important;
   background: -webkit-gradient(linear, left top, left bottom, from(#aeb11b), to(#aeb11b))!important;
   background: -moz-linear-gradient(top, #aeb11b, #aeb11b)!important;
   background: linear-gradient(to bottom, #aeb11b, #aeb11b)!important;
}
.button2:after{
   content:  "\0000a0"!important;
   display: inline-block!important;
   height: 24px!important;
   width: 24px!important;
   line-height: 24px!important;
   margin: 0 -4px -6px 4px!important;
   position: relative!important;
   top: 0px!important;
   left: 0px!important;
   background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAEJUlEQVRIiaWVXWhURxTHf3P3Zjfq5mOzZE1q1RC1Eb+yxhbBB6lN+yD40BJRUGlAUKIIRTEVn3wzfbFQqiJVH4rFL2qRih8VYkWxtCUSimWLYDS1Jm52UzfG3N17786d6UOycVc3Ee3AwHyc+f/OOcOcEYBBkTbv3Xms/mx1feX0ynWlpaXNU3xTFgSnBiNKKTlijwzanh2zM3ZnaiB19vwX53sfxR4Vk0GMAVQ+qO1EW324NtyxsHbhx0siS8xZ5bPw+/worQAwhIHlWvQ87aE73i17k70/pOKpvUc+PXI/T0cBRj4AwNh+bvumurfqDi2rXRYESGQSDNlDZFUWpRUCgSEMAmaAUGmIyNQIz5xndPV3DSeSiW2HWw6fznNYFUSw5dyWz8tCZR3VU6uLhjtZ87RHMp3EGrLaj7Uc+zLndA7AhpMbNgWrgt9WlFYQLAm+NgBgMDOIIx1GnoxsPLnh5OlxwJpDa+orZ1Z2C58IVgYqKfOXvREgmUliSxvt6eHUw1TjxR0Xe81INIJZZXY42gkiYVAN4vf5EYjxgzPKZrBq5iqEGF27PXCb2GCsQNxVLkP2UG5abobNjoq5FRt9S9uXzimpKjkotTSkkriei5W18Pv8aDSe9njqPCVUGmLl2yupmVbDovAi+qw++q1+PO1hZS36RvpwPRepJFJJlKHml88p/843e/3sNl2iP8ptSCWxpU3KTuF4DhoNAu4P3cf1XOZXzcdn+FhcvZh7qXt0J7oZSA8UiEslkVoaylD9pivcZk96RXNqZS3iVhyAEqOEu6m7xK04bdE2TGGyLbqNx9Zjbj66WfS8Z3jNovGbxsdGwKjJ31gxYwWhQGjCy2x5p4VoJAqA4znsvbGX6/9cf8lOOapfNBxt8IQhCsrFqTWnaKxuRAiB1hpg0rHruez8eSfXHl4rAGipXdOW9kvVKFcSciKvGiutSGfTZGTmRQBm2k4nhF8UpOhA1wHCU8JF0yMQtC5spWl6EwAZmWHrT1u5+vfVl2y1qxOmLe0YBgWACz0XiooD7Fq2i2gkitYax3NovdzKlQdXihtLYmbGznRi8MGEinmet7/Xzr4V+4DRy113YR2XH1ye+FCGTsFO5jKdvxCYkwH2LN/D/pX7MYRBJpth/Y/rJ40UjSROg6Aeg02cIcDaiWybaprYvXz3ePk48ecJLvVcmswfcDjNcTaOVtMd1BHmDwRvVkZfbIph/qWRQ/T6AMHvPKGJPkw+QcH/7s/YzNfcAsQoADS/coel2Bh8iH5DYQ9I085XHM3F8hwAmt/4hSXcG4MEXktcMozFZg5ydGxFA+QDRt9zF3eYyxkMatE0oDBe4bXE4Swp1nKcW2Oei1x/8dNnfF6LwfvUM421+GgGFmAQQaPQJIAYHp2M8D2d9JJ8/tHn6/wHNkwY75YHNyEAAAAASUVORK5CYII=") no-repeat left center transparent!important;
   background-size: 100% 100%!important;
}

#mc-embedded-subscribe {
font-family:lato !important;
text-transform: none !important;
}

.validate {
text-transform: none !important;
font-family: helvetica;
font-weight:700 !important;
width: 100% !important;
text-align: center !important;
font-size: 19px !important;
line-height: 30px;
font-style: normal;
}

#mc-embedded-subscribe-form,
#mc_embed_signup {
padding: 0px 0px !important;
margin: 0px 0px !important;
}

.mc_embed_signup_scroll,
.mc-embedded-subscribe
.validate
.clear {
position: absolute;
padding: 0px 0px !important;
margin: 0px 0px !important;
left: 50%;
font-family: arial !important;
top: 10%;}

#mc_embed_signup  input.email {
 height:35px !important;
 width: 220px;
}
</code>```

答:
Your code snippet provided is working just fine.

Problem is that in your page, that you provided in comment, there is float: right declared on your button which I saw by inspecting that element:

```<code>input[type=submit], button, input[type=button] {
  border: none;
  text-transform: uppercase;
  margin: 10px 0px 0px;
  padding: 11px 20px;
  float: right;
  ...
}
</code>```

Removing it fixed the issue.

One more thing. Try not to use  tag as it is not supported by HTML5

Since you are using WordPress theme that is maybe not editable, add internal or inline style float: none to your HTML page:

Internal style:

```<code><head>
  <style>
    input[type=submit], button, input[type=button] {
     float: none;
    }
  </style>
</head>
</code>```

Inline style

```<code><input id="mc-embedded-subscribe" class="button2" name="subscribe" type="submit"
value="Prenumerera" style="float: none"/>
</code>```

To inspect an element:

Go to your website page

Right click on button

Left click on "Inspect element"

You will see HTML of your page and next to that CSS. Scroll down to see the code that I provided in my answer.

Title: Center button in MailChimp

Body:
Hello,

How can I center a MailChimp button? The button is centered on desktop, but is shifted right on mobile devices, see the picture. I have been trying playing around with some classes and id's but can not solve it really. Not all the CSS code is necessary I guess. Sorry, I know it is messy. (In the HTML I have HIDDEN... the API-key)

Here is the HTML:

<form id="mc-embedded-subscribe-form" class="validate" action="https://hotmail.us4.list-manage.com/subscribe/post? HIDDEN... " method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank">

Ta del av vårt nyhetsbrev!
<input id="mce-EMAIL" class="email" name="EMAIL" required="" type="email" value="" placeholder="Skriv din e-post här!" />

<input tabindex="-1" name=" HIDDEN...
    " type="text" value="" />

   <input id="mc-embedded-subscribe" class="button2" name="subscribe" type="submit"
   value="Prenumerera" />

</form>

Here are some CSS:

.button2 {
   display: inline-block;
   text-align: center;
  font-family: lora !important;
/*    vertical-align: bottom;*/
 /*  padding-bottom: 0px !important;*/
 margin:auto !important;
   height:34px !important;
 line-height :34px !important;
   padding: 5px 12px !important;
   border: 1px solid #aeb11b;
   border-radius: 8px;
   background: #f8fd27!important;
   background: -webkit-gradient(linear, left top, left bottom, from(#f8fd27), to(#aeb11b))!important;
   background: -moz-linear-gradient(top, #f8fd27, #aeb11b)!important;
   background: linear-gradient(to bottom, #f8fd27, #aeb11b)!important;
   -webkit-box-shadow: #8d1bb3 0px 0px 24px 0px!important;
   -moz-box-shadow: #8d1bb3 0px 0px 24px 0px!important;
   box-shadow: #8d1bb3 0px 0px 24px 0px!important;
   text-shadow: #ffff33 1px 1px 1px!important;
   font: normal normal bold 20px arial!important;
   color: #111111!important;
   text-decoration: none!important;
}

.button2:hover,
.button2:focus {
   border: 1px solid #f8fd27!important;[![enter image description here][1]][1]
   background: #ffff2f!important;
   background: -webkit-gradient(linear, left top, left bottom, from(#ffff2f), to(#d1d420))!important;
   background: -moz-linear-gradient(top, #ffff2f, #d1d420)!important;
   background: linear-gradient(to bottom, #ffff2f, #d1d420)!important;
   color: #111111!important;
}
.button2:active {
   background: #aeb11b!important;
   background: -webkit-gradient(linear, left top, left bottom, from(#aeb11b), to(#aeb11b))!important;
   background: -moz-linear-gradient(top, #aeb11b, #aeb11b)!important;
   background: linear-gradient(to bottom, #aeb11b, #aeb11b)!important;
}
.button2:after{
   content:  "\0000a0"!important;
   display: inline-block!important;
   height: 24px!important;
   width: 24px!important;
   line-height: 24px!important;
   margin: 0 -4px -6px 4px!important;
   position: relative!important;
   top: 0px!important;
   left: 0px!important;
   background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAEJUlEQVRIiaWVXWhURxTHf3P3Zjfq5mOzZE1q1RC1Eb+yxhbBB6lN+yD40BJRUGlAUKIIRTEVn3wzfbFQqiJVH4rFL2qRih8VYkWxtCUSimWLYDS1Jm52UzfG3N17786d6UOycVc3Ee3AwHyc+f/OOcOcEYBBkTbv3Xms/mx1feX0ynWlpaXNU3xTFgSnBiNKKTlijwzanh2zM3ZnaiB19vwX53sfxR4Vk0GMAVQ+qO1EW324NtyxsHbhx0siS8xZ5bPw+/worQAwhIHlWvQ87aE73i17k70/pOKpvUc+PXI/T0cBRj4AwNh+bvumurfqDi2rXRYESGQSDNlDZFUWpRUCgSEMAmaAUGmIyNQIz5xndPV3DSeSiW2HWw6fznNYFUSw5dyWz8tCZR3VU6uLhjtZ87RHMp3EGrLaj7Uc+zLndA7AhpMbNgWrgt9WlFYQLAm+NgBgMDOIIx1GnoxsPLnh5OlxwJpDa+orZ1Z2C58IVgYqKfOXvREgmUliSxvt6eHUw1TjxR0Xe81INIJZZXY42gkiYVAN4vf5EYjxgzPKZrBq5iqEGF27PXCb2GCsQNxVLkP2UG5abobNjoq5FRt9S9uXzimpKjkotTSkkriei5W18Pv8aDSe9njqPCVUGmLl2yupmVbDovAi+qw++q1+PO1hZS36RvpwPRepJFJJlKHml88p/843e/3sNl2iP8ptSCWxpU3KTuF4DhoNAu4P3cf1XOZXzcdn+FhcvZh7qXt0J7oZSA8UiEslkVoaylD9pivcZk96RXNqZS3iVhyAEqOEu6m7xK04bdE2TGGyLbqNx9Zjbj66WfS8Z3jNovGbxsdGwKjJ31gxYwWhQGjCy2x5p4VoJAqA4znsvbGX6/9cf8lOOapfNBxt8IQhCsrFqTWnaKxuRAiB1hpg0rHruez8eSfXHl4rAGipXdOW9kvVKFcSciKvGiutSGfTZGTmRQBm2k4nhF8UpOhA1wHCU8JF0yMQtC5spWl6EwAZmWHrT1u5+vfVl2y1qxOmLe0YBgWACz0XiooD7Fq2i2gkitYax3NovdzKlQdXihtLYmbGznRi8MGEinmet7/Xzr4V+4DRy113YR2XH1ye+FCGTsFO5jKdvxCYkwH2LN/D/pX7MYRBJpth/Y/rJ40UjSROg6Aeg02cIcDaiWybaprYvXz3ePk48ecJLvVcmswfcDjNcTaOVtMd1BHmDwRvVkZfbIph/qWRQ/T6AMHvPKGJPkw+QcH/7s/YzNfcAsQoADS/coel2Bh8iH5DYQ9I085XHM3F8hwAmt/4hSXcG4MEXktcMozFZg5ydGxFA+QDRt9zF3eYyxkMatE0oDBe4bXE4Swp1nKcW2Oei1x/8dNnfF6LwfvUM421+GgGFmAQQaPQJIAYHp2M8D2d9JJ8/tHn6/wHNkwY75YHNyEAAAAASUVORK5CYII=") no-repeat left center transparent!important;
   background-size: 100% 100%!important;
}

#mc-embedded-subscribe {
font-family:lato !important;
text-transform: none !important;
}

.validate {
text-transform: none !important;
font-family: helvetica;
font-weight:700 !important;
width: 100% !important;
text-align: center !important;
font-size: 19px !important;
line-height: 30px;
font-style: normal;
}

#mc-embedded-subscribe-form,
#mc_embed_signup {
padding: 0px 0px !important;
margin: 0px 0px !important;
}

.mc_embed_signup_scroll,
.mc-embedded-subscribe
.validate
.clear {
position: absolute;
padding: 0px 0px !important;
margin: 0px 0px !important;
left: 50%;
font-family: arial !important;
top: 10%;}

#mc_embed_signup  input.email {
 height:35px !important;
 width: 220px;
}

Body:
Your code snippet provided is working just fine.

Problem is that in your page, that you provided in comment, there is float: right declared on your button which I saw by inspecting that element:

input[type=submit], button, input[type=button] {
  border: none;
  text-transform: uppercase;
  margin: 10px 0px 0px;
  padding: 11px 20px;
  float: right;
  ...
}

Removing it fixed the issue.

One more thing. Try not to use <center> tag as it is not supported by HTML5

Since you are using WordPress theme that is maybe not editable, add internal or inline style float: none to your HTML page:

Internal style:

<head>
  <style>
    input[type=submit], button, input[type=button] {
     float: none;
    }
  </style>
</head>

Inline style

<input id="mc-embedded-subscribe" class="button2" name="subscribe" type="submit"
value="Prenumerera" style="float: none"/>

To inspect an element:

Go to your website page

Right click on button

Left click on "Inspect element"

You will see HTML of your page and next to that CSS. Scroll down to see the code that I provided in my answer.


问:
Jenkins, specifying JAVA_HOME
I installed openjdk-6-jdk on my ubuntu box using apt-get.

In system info jenkins is telling me Java.Home is /usr/lib/jvm/java-6-openjdk/jre

However when I specify that directory as JAVA_HOME in Jenkins : "configure system", it returns error message saying that directory does not look like a jdk directory.

it is also failing to pick up my maven install.

Am I missing something obvious ?

答:
I was facing the same issue and for me downgrading the JAVA_HOME from jdk12 was not the plausible option like said in the answer. So I did a trial and error experiment and I got the Jenkins running without even downgrading the version of JAVA_HOME.

Steps:

open configuration $ sudo vi /etc/init.d/jenkins

Comment following line:

```<code> #JAVA=`type -p java`
</code>```

Introduced the line mentioned below. (Note: Insert the specific path of JDK in your machine.)

```<code> JAVA=`type -p /usr/lib/jdk8/bin/java`
</code>```

Reload systemd manager configuration: $ sudo systemctl daemon-reload

Start Jenkins service: $ sudo systemctl start jenkins
```<code>● jenkins.service - LSB: Start Jenkins at boot time
   Loaded: loaded (/etc/init.d/jenkins; generated)
   Active: active (exited) since Sun 2020-05-31 21:05:30 CEST; 9min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 9055 ExecStart=/etc/init.d/jenkins start (code=exited, status=0/SUCCESS)
</code>```

Title: Jenkins, specifying JAVA_HOME

Body:
I was facing the same issue and for me downgrading the JAVA_HOME from jdk12 was not the plausible option like said in the answer. So I did a trial and error experiment and I got the Jenkins running without even downgrading the version of JAVA_HOME.

Steps:

open configuration $ sudo vi /etc/init.d/jenkins

Comment following line:

 #JAVA=`type -p java`

Introduced the line mentioned below. (Note: Insert the specific path of JDK in your machine.)

 JAVA=`type -p /usr/lib/jdk8/bin/java`

Reload systemd manager configuration: $ sudo systemctl daemon-reload

Start Jenkins service: $ sudo systemctl start jenkins

● jenkins.service - LSB: Start Jenkins at boot time
   Loaded: loaded (/etc/init.d/jenkins; generated)
   Active: active (exited) since Sun 2020-05-31 21:05:30 CEST; 9min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 9055 ExecStart=/etc/init.d/jenkins start (code=exited, status=0/SUCCESS)


问:
SQL PHP query multiple tables data
Noob alert here!
I'm trying to display some data on my php page from two tables but I don't know how to do it

```<code>db_bandas TABLE
banda_id | banda_name
    1    |  Rolling Beatles
    2    |  Linkin Bizkit

db_albuns TABLE
album_id | album_name | banda_id | album_ano
    1    |    Music   |    1     |  2000
    2    |   another  |    2     |  2014
    3    |  good one  |    1     |  2004
</code>```

What I want to show on the page is like :

```<code> 1  | Music    | Rolling Beatles | 2000
 2  | another  | Linkin Bizkit   | 2014
 3  | good one | Rolling Beatles | 2004
</code>```

I've tried the query like this

```<code>$sql = "SELECT db_albuns.album_nome AS album_nome, db_albuns.album_id AS album_id, db_albuns.album_ano AS album.ano, db_banda.banda_nome AS banda_nome FROM db_albuns,db_banda";

</code>```

答:
Your table name should be albums and columns name should be id, name, banda_id, ano. Your table name is albums, so I think there is no need to use prefix 'albums' for each column.

As well as another table name should be bandas and columns name should be id, name

And your query should be like this

```<code>$sql = "SELECT albums.id, albums.name, bandas.name, albums.ano
        FROM albums JOIN bandas
        on albums.banda_id = bandas.id";
</code>```

Title: SQL PHP query multiple tables data

Body:
Noob alert here!
I'm trying to display some data on my php page from two tables but I don't know how to do it

db_bandas TABLE
banda_id | banda_name
    1    |  Rolling Beatles
    2    |  Linkin Bizkit

db_albuns TABLE
album_id | album_name | banda_id | album_ano
    1    |    Music   |    1     |  2000
    2    |   another  |    2     |  2014
    3    |  good one  |    1     |  2004

What I want to show on the page is like :

 1  | Music    | Rolling Beatles | 2000
 2  | another  | Linkin Bizkit   | 2014
 3  | good one | Rolling Beatles | 2004

I've tried the query like this

$sql = "SELECT db_albuns.album_nome AS album_nome, db_albuns.album_id AS album_id, db_albuns.album_ano AS album.ano, db_banda.banda_nome AS banda_nome FROM db_albuns,db_banda";

Body:
Your table name should be albums and columns name should be id, name, banda_id, ano. Your table name is albums, so I think there is no need to use prefix 'albums' for each column.

As well as another table name should be bandas and columns name should be id, name

And your query should be like this

$sql = "SELECT albums.id, albums.name, bandas.name, albums.ano
        FROM albums JOIN bandas
        on albums.banda_id = bandas.id";


问:
Listing model coefficients in descending order
I have a dataset with both continuous and categorical variables. I am running regression to predict one of the variables based on the other variables in the dataset. After comparing the results of ridge, lasso and elastic-net regression, the lasso regression is the best model to proceed with.

I used the 'coef' function to extract the model's coefficients, however, the result is a very long list with over 800 variables (as some of my categorical variables have many levels). Is there a way I can quickly rank the coefficients from largest to smallest? This is a glmnet model output

Reproducible problem with example code:

```<code># Libraries Needed
library(caret)
library(glmnet)
library(mlbench)
library(psych)

# Data
data("BostonHousing")
data <- BostonHousing
str(data)

# Data Partition
set.seed(222)
ind <- sample(2, nrow(data), replace = T, prob = c(0.7, 0.3))
train <- data[ind==1,]
test <- data[ind==2,]

# Custom Control Parameters
custom <- trainControl(method = "repeatedcv",
                       number = 10,
                       repeats = 5,
                       verboseIter = T)

# Linear Model
set.seed(1234)
lm <- train(medv ~.,
            train,
            method='lm',
            trControl = custom)

# Results
lm$results
lm
summary(lm)
plot(lm$finalModel)

# Ridge Regression
set.seed(1234)
ridge <- train(medv ~.,
               train,
               method = 'glmnet',
               tuneGrid = expand.grid(alpha = 0,
                                      lambda = seq(0.0001, 1, length=5)),#try 5 values for lambda between 0.0001 and 1
                                      trControl=custom)
#increasing lambda = increasing penalty and vice versa
#increase lambda therefore will cause coefs to shrink

# Plot Results
plot(ridge)
plot(ridge$finalModel, xvar = "lambda", label = T)
plot(ridge$finalModel, xvar = 'dev', label=T)
plot(varImp(ridge, scale=T))

# Lasso Regression
set.seed(1234)
lasso <- train(medv ~.,
               train,
               method = 'glmnet',
               tuneGrid = expand.grid(alpha=1,
                                      lambda = seq(0.0001,1, length=5)),
               trControl = custom)

# Plot Results
plot(lasso)
lasso
plot(lasso$finalModel, xvar = 'lambda', label=T)
plot(lasso$finalModel, xvar = 'dev', label=T)
plot(varImp(lasso, scale=T))

# Elastic Net Regression
set.seed(1234)
en <- train(medv ~.,
            train,
            method = 'glmnet',
            tuneGrid = expand.grid(alpha = seq(0,1,length=10),
                                   lambda = seq(0.0001,1,length=5)),
            trControl = custom)

# Plot Results
plot(en)
plot(en$finalModel, xvar = 'lambda', label=T)
plot(en$finalModel, xvar = 'dev', label=T)
plot(varImp(en))

# Compare Models
model_list <- list(LinearModel = lm, Ridge = ridge, Lasso = lasso, ElasticNet=en)
res <- resamples(model_list)
summary(res)
bwplot(res)
xyplot(res, metric = 'RMSE')

# Best Model
en$bestTune
best <- en$finalModel
coef(best, s = en$bestTune$lambda)
</code>```

答:
For most models all you'd have to do would be:

```<code>sort(coef(model), decreasing=TRUE)
</code>```

Since you're using glmnet it's a little bit more complicated.  I'm going to replicate a minimal version of your example here (the other models, plots, etc. are not necessary in order for us to be able to reproduce your problem ...)

```<code>## Packages
library(caret)
library(glmnet)
library(mlbench) ## for BostonHousing data
# Data
data("BostonHousing")
data <- BostonHousing
# Data Partition
set.seed(222)
ind <- sample(2, nrow(data), replace = TRUE, prob = c(0.7, 0.3))
train <- data[ind==1,]
test <- data[ind==2,]
# Custom Control Parameters
custom <- trainControl(method = "repeatedcv",
                       number = 10,
                       repeats = 5,
                       verboseIter = TRUE)
# Elastic Net Regression
set.seed(1234)
en <- train(medv ~.,
            train,
            method = 'glmnet',
            tuneGrid = expand.grid(alpha = seq(0,1,length=10),
                                   lambda = seq(0.0001,1,length=5)),
            trControl = custom)
# Best Model
best <- en$finalModel
coefs <- coef(best, s = en$bestTune$lambda)
</code>```

(This could probably be made simpler: for example, do you really need the custom control parameters to show us the example?  This would be even simpler without using caret - just using `glmnet - but I was afraid I might leave something out.)

Once you've got the coefficients, sorting does appear to work, albeit with a message about possible inefficiency:

```<code>sort(coefs, decreasing=TRUE)
## <sparse>[ <logic> ] : .M.sub.i.logical() maybe inefficient
##  [1]  25.191049410   5.078589706   1.389548822   0.244605193   0.045600250
##  [6]   0.008840485   0.004372752  -0.012701593  -0.028337745  -0.162794401
## [11]  -0.335062819  -0.901475516  -1.395091095 -12.632336419
</code>```

sort(as.numeric(coefs)) also appears to work fine.

If you want to sort the entire matrix (i.e. keeping the values for all penalization levels), you can take advantage of the fact that the penalization doesn't change the rank-order of the parameters:

```<code>coeftab <-coef(best)
lastvals <- coeftab[,ncol(coeftab)]
coeftab_s <- coeftab[order(lastvals,decreasing=TRUE),]
## plot, leaving out the intercept
matplot(t(coeftab_s)[,-1],type="l")
</code>```

Body:
I have a dataset with both continuous and categorical variables. I am running regression to predict one of the variables based on the other variables in the dataset. After comparing the results of ridge, lasso and elastic-net regression, the lasso regression is the best model to proceed with.

I used the 'coef' function to extract the model's coefficients, however, the result is a very long list with over 800 variables (as some of my categorical variables have many levels). Is there a way I can quickly rank the coefficients from largest to smallest? This is a glmnet model output

Reproducible problem with example code:

# Libraries Needed
library(caret)
library(glmnet)
library(mlbench)
library(psych)

# Data
data("BostonHousing")
data <- BostonHousing
str(data)

# Data Partition
set.seed(222)
ind <- sample(2, nrow(data), replace = T, prob = c(0.7, 0.3))
train <- data[ind==1,]
test <- data[ind==2,]

# Custom Control Parameters
custom <- trainControl(method = "repeatedcv",
                       number = 10,
                       repeats = 5,
                       verboseIter = T)

# Linear Model
set.seed(1234)
lm <- train(medv ~.,
            train,
            method='lm',
            trControl = custom)

# Results
lm$results
lm
summary(lm)
plot(lm$finalModel)

# Ridge Regression
set.seed(1234)
ridge <- train(medv ~.,
               train,
               method = 'glmnet',
               tuneGrid = expand.grid(alpha = 0,
                                      lambda = seq(0.0001, 1, length=5)),#try 5 values for lambda between 0.0001 and 1
                                      trControl=custom)
#increasing lambda = increasing penalty and vice versa
#increase lambda therefore will cause coefs to shrink

# Plot Results
plot(ridge)
plot(ridge$finalModel, xvar = "lambda", label = T)
plot(ridge$finalModel, xvar = 'dev', label=T)
plot(varImp(ridge, scale=T))

# Lasso Regression
set.seed(1234)
lasso <- train(medv ~.,
               train,
               method = 'glmnet',
               tuneGrid = expand.grid(alpha=1,
                                      lambda = seq(0.0001,1, length=5)),
               trControl = custom)

# Plot Results
plot(lasso)
lasso
plot(lasso$finalModel, xvar = 'lambda', label=T)
plot(lasso$finalModel, xvar = 'dev', label=T)
plot(varImp(lasso, scale=T))

# Elastic Net Regression
set.seed(1234)
en <- train(medv ~.,
            train,
            method = 'glmnet',
            tuneGrid = expand.grid(alpha = seq(0,1,length=10),
                                   lambda = seq(0.0001,1,length=5)),
            trControl = custom)

# Plot Results
plot(en)
plot(en$finalModel, xvar = 'lambda', label=T)
plot(en$finalModel, xvar = 'dev', label=T)
plot(varImp(en))

# Compare Models
model_list <- list(LinearModel = lm, Ridge = ridge, Lasso = lasso, ElasticNet=en)
res <- resamples(model_list)
summary(res)
bwplot(res)
xyplot(res, metric = 'RMSE')

# Best Model
en$bestTune
best <- en$finalModel
coef(best, s = en$bestTune$lambda)

Body:
For most models all you'd have to do would be:

sort(coef(model), decreasing=TRUE)

Since you're using glmnet it's a little bit more complicated.  I'm going to replicate a minimal version of your example here (the other models, plots, etc. are not necessary in order for us to be able to reproduce your problem ...)

## Packages
library(caret)
library(glmnet)
library(mlbench) ## for BostonHousing data
# Data
data("BostonHousing")
data <- BostonHousing
# Data Partition
set.seed(222)
ind <- sample(2, nrow(data), replace = TRUE, prob = c(0.7, 0.3))
train <- data[ind==1,]
test <- data[ind==2,]
# Custom Control Parameters
custom <- trainControl(method = "repeatedcv",
                       number = 10,
                       repeats = 5,
                       verboseIter = TRUE)
# Elastic Net Regression
set.seed(1234)
en <- train(medv ~.,
            train,
            method = 'glmnet',
            tuneGrid = expand.grid(alpha = seq(0,1,length=10),
                                   lambda = seq(0.0001,1,length=5)),
            trControl = custom)
# Best Model
best <- en$finalModel
coefs <- coef(best, s = en$bestTune$lambda)

(This could probably be made simpler: for example, do you really need the custom control parameters to show us the example?  This would be even simpler without using caret - just using `glmnet - but I was afraid I might leave something out.)

Once you've got the coefficients, sorting does appear to work, albeit with a message about possible inefficiency:

sort(coefs, decreasing=TRUE)
## <sparse>[ <logic> ] : .M.sub.i.logical() maybe inefficient
##  [1]  25.191049410   5.078589706   1.389548822   0.244605193   0.045600250
##  [6]   0.008840485   0.004372752  -0.012701593  -0.028337745  -0.162794401
## [11]  -0.335062819  -0.901475516  -1.395091095 -12.632336419

sort(as.numeric(coefs)) also appears to work fine.

If you want to sort the entire matrix (i.e. keeping the values for all penalization levels), you can take advantage of the fact that the penalization doesn't change the rank-order of the parameters:

coeftab <-coef(best)
lastvals <- coeftab[,ncol(coeftab)]
coeftab_s <- coeftab[order(lastvals,decreasing=TRUE),]
## plot, leaving out the intercept
matplot(t(coeftab_s)[,-1],type="l")


问:
How can I compare two Git branches and only list the new commits in the feature/topic (second) branch
I have performed the steps below, but when I compare the develop branch with the feature branch I see two commit messages instead of only just 1 commit that I expect to see. One is the previous commit which is already in develop and the other us the latest commit I made in the feature branch.

I have pulled and merged the local develop branch from a remote branch

Then have created a new branch off of develop

Made changes and added those files and git commit -m "latest changes" in the feature branch

Performed git push to push the feature branch to the remote branch

When I compared develop to feature, I see two commits instead of just one (the one I created in the feature branch)

Why is this happening and how can I resolve this issue?

答:
Answer on your question: you may see difference between two branches by executing git log <parent_branch_name>..<your_feature_branch_name>, for instance git log develop..feature.

About your situation: As I see situation, the most likely reason for such behaviour is merging develop branch within your local repo. If while merging process (fyi pull operation is combination fetch and merge), merge did not process as fast-forward, then you got another state of develop branch, here could be merge commit, you are able to compare commits hashes.

In order to prevent such situations, you should use git pull --rebase command for pulling some local branch.

If you wanted to get latest changes before pushing your local feature branch to the remote server, you could also run git pull --rebase origin develop on your feature branch, then commit's tree will look like you just created your feature branch from develop and put all created commits on feature branch after parent's branch commits.

I hope, it will be helpful for you!


问:
How to Learn advanced concepts in developing Web Servers
I recently wrote a small C code which uses sockets to listen on a port. It simply echos back the request made to it by a browser. It creates a thread for daemon process and also for servicing new requests. I am doing it simply to learn more about webservers in general. I wanted to know what to do ahead?

I was planning to read the RFC for http. Many questions already answered on StackOverflow suggest going through open source webserver like apache or lighthttp, but I dont know how to start reading such open source projects?

答:
This is a really good book on HTTP. I recommend getting started with that then maybe the relevant RFC's. Also maybe check out the source of libcurl, a c library for http, https, ftp etc. Hope this helps :)

Also Tiny HTTPd is a small http server someone wrote for a school project, you can learn a lot from the source from that.
This is simple http client in c.


问:
The logic of nested loops in C
I am new to programming and I'm following the CS50 course. I'm trying to fully understand the logic behind nested loops in C. I think I've got it, but I'd like to be sure before I move on to the next set of problems. Here's the code (provided by the course). It creates a cube made of hashes. My explanations are below the code.

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n, j++)
    {
        printf("#");
    }
    printf("\n");
}

```

The first loop starts: It creates a new variable called i and sets it to 0. The command checks the new variable: If it is lesser than n (true), run it, starting the inside loop.

The inside loop also creates a new variable, j, sets it to 0, checks it and, if it is true (j < n), runs the code below and print a hash. Afterwards, the inside loop is incremented and this process occurs again until the inside loop condition is not met anymore. This will create a ROW of hashes if n is greater than 2.

The outer loop creates a new line, increments and the process starts all over again. It will run until the condition is false (i > n).

The next times the inside loop is accessed, the variable j is set to 0 again, that's why it is possible to print various rows in this program.

Is that correct? Thank you very much in advance!

答:
Yes, your explanation is spot on.

With a minor mistake:

It will run until the condition is false (i > n).

The condition is false when i >= n.

And what I assume it's a typo:

```<code>for (int j = 0; j < n, j++);
//                         ^
//                         |
</code>```

remove the ;

Title: The logic of nested loops in C

Body:
I am new to programming and I'm following the CS50 course. I'm trying to fully understand the logic behind nested loops in C. I think I've got it, but I'd like to be sure before I move on to the next set of problems. Here's the code (provided by the course). It creates a cube made of hashes. My explanations are below the code.

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n, j++)
    {
        printf("#");
    }
    printf("\n");
}

The first loop starts: It creates a new variable called i and sets it to 0. The command checks the new variable: If it is lesser than n (true), run it, starting the inside loop.

The inside loop also creates a new variable, j, sets it to 0, checks it and, if it is true (j < n), runs the code below and print a hash. Afterwards, the inside loop is incremented and this process occurs again until the inside loop condition is not met anymore. This will create a ROW of hashes if n is greater than 2.

The outer loop creates a new line, increments and the process starts all over again. It will run until the condition is false (i > n).

The next times the inside loop is accessed, the variable j is set to 0 again, that's why it is possible to print various rows in this program.

Is that correct? Thank you very much in advance!

Body:
Yes, your explanation is spot on.

With a minor mistake:

It will run until the condition is false (i > n).

The condition is false when i >= n.

And what I assume it's a typo:

for (int j = 0; j < n, j++);
//                         ^
//                         |

remove the ;


问:
Angular does not see variables values when using timer
I need to call the backend function in angular's component according to the timer.
I tried 2 options:

Option N1:

```<code>_api: Service;

constructor(api: Service){
 this._api = api;
    if (this.timeout != null) {
      clearTimeout(this.timeout);
    }

    this.timeout = setTimeout(() => {
        this.update();
    }, 20000);
}

update()
{
this._api.GetData()….
}
</code>```

The Result of this implementation does not run timer every N seconds, it calls update() function only once. But with this approach I can access the methods/properties of the this.api

OPTION N2:

```<code>_api: Service;

constructor(api: Service){
 this._api = api;
 setInterval(this.update, 2000);
}

update()
{
this._api.GetData()….
}
</code>```

And the result is: for some reason it can't see the methods/properties of this._api.
I checked whether I can see them if I don't use setInterval and it seems that the problem is caused by setInterval.

Please advise how to arrange timer work of some method in Angular?

答:
How about interval function provided by rxjs?

class Service {
  getData() {
    return rxjs.of( Array(Math.floor(Math.random() * 5)).fill(0).map((pr, index) => ({id: index})))
  }
}

class Component {
  constructor(service) {
    this.service = service;
    this.observable = null;
    this.ngOnInit = this.ngOnInit.bind(this);
  }

  ngOnInit() {
    this.observable = rxjs.interval(3000)
      .pipe(rxjs.operators.mergeMap(_ => this.service.getData()));

  }
}

const service = new Service();
const component = new Component(service);
component.ngOnInit();
component.observable.subscribe(values => {
  console.log(values)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script></code>```

Body:
I need to call the backend function in angular's component according to the timer.
I tried 2 options:

Option N1:

_api: Service;

constructor(api: Service){
 this._api = api;
    if (this.timeout != null) {
      clearTimeout(this.timeout);
    }

    this.timeout = setTimeout(() => {
        this.update();
    }, 20000);
}

update()
{
this._api.GetData()….
}

The Result of this implementation does not run timer every N seconds, it calls update() function only once. But with this approach I can access the methods/properties of the this.api

OPTION N2:

_api: Service;

constructor(api: Service){
 this._api = api;
 setInterval(this.update, 2000);
}

update()
{
this._api.GetData()….
}

And the result is: for some reason it can't see the methods/properties of this._api.
I checked whether I can see them if I don't use setInterval and it seems that the problem is caused by setInterval.

Please advise how to arrange timer work of some method in Angular?

Body:
How about interval function provided by rxjs?

class Service {
  getData() {
    return rxjs.of( Array(Math.floor(Math.random() * 5)).fill(0).map((pr, index) => ({id: index})))
  }
}

class Component {
  constructor(service) {
    this.service = service;
    this.observable = null;
    this.ngOnInit = this.ngOnInit.bind(this);
  }

  ngOnInit() {
    this.observable = rxjs.interval(3000)
      .pipe(rxjs.operators.mergeMap(_ => this.service.getData()));

  }
}

const service = new Service();
const component = new Component(service);
component.ngOnInit();
component.observable.subscribe(values => {
  console.log(values)
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>


问:
fetching data from django models
I am a newbie with Django. I created a table using Django models and inserted an object using the python shell. When I access the object using object id on Django template, I get the result as "{{obj.id}}-{{obj.content}}" rather than the actual data values.

The views.py file

```<code>from django.shortcuts import render
from django.http import HttpResponse, Http404
from .models import Tweet

# Create your views here.
def home_view(request, *args, **kwargs):
    return HttpResponse("<h1>Hello World!<h1>")

def tweet_detail_view(request, tweet_id, *args, **kwargs):
    try:
        obj = Tweet.objects.get(id = tweet_id)
    except:
        raise Http404
    return HttpResponse("<h1>Hello {{obj.id}} - {{obj.content}}</h1>")
</code>```

The models.py file

```<code>from django.db import models

# Create your models here.
class Tweet(models.Model):
    content = models.TextField(blank=True, null=True)
    image = models.FileField(upload_to='images/', blank=True, null=True)
</code>```

The urls.py file

```<code>from django.contrib import admin
from django.urls import path
from tweets import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home_view),
    path('tweet/<int:tweet_id>', views.tweet_detail_view),
]
</code>```

The Shell

```<code>(base) ankita@ankita-HP-Laptop-15-bs0xx:~/dev/trydjango/tweetme$ ./manage.py shell
Python 3.7.4 (default, Aug 13 2019, 20:35:49)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from tweets.models import Tweet

In [2]: obj = Tweet.objects.get(id = 1)

In [3]: obj
Out[3]: <Tweet: Tweet object (1)>

In [4]: obj.content
Out[4]: 'Hello World!'

In [5]: obj.id
Out[5]: 1
</code>```

The localhost page have only next text:

Hello {{obj.id}} - {{obj.content}}

答:
If you create template to render your page, this task is quite simple to achieve. So, why don/t you create template and render it using render?

hello_word.html

```<code><html>
    <body>
        <h1>Hello {{obj.id}} - {{obj.content}}</h1>
    </html>
</body>
</code>```

views.py

instead of HttpResponse:

```<code>return render(request, 'hello_world.html', {'obj': obj})
</code>```

I would say that this is a regular Django way to render templates.

Title: fetching data from django models

Body:
I am a newbie with Django. I created a table using Django models and inserted an object using the python shell. When I access the object using object id on Django template, I get the result as "{{obj.id}}-{{obj.content}}" rather than the actual data values.

The views.py file

from django.shortcuts import render
from django.http import HttpResponse, Http404
from .models import Tweet

# Create your views here.
def home_view(request, *args, **kwargs):
    return HttpResponse("
Hello World!
")

def tweet_detail_view(request, tweet_id, *args, **kwargs):
    try:
        obj = Tweet.objects.get(id = tweet_id)
    except:
        raise Http404
    return HttpResponse("
Hello {{obj.id}} - {{obj.content}}
")

The models.py file

from django.db import models

# Create your models here.
class Tweet(models.Model):
    content = models.TextField(blank=True, null=True)
    image = models.FileField(upload_to='images/', blank=True, null=True)

The urls.py file

from django.contrib import admin
from django.urls import path
from tweets import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home_view),
    path('tweet/<int:tweet_id>', views.tweet_detail_view),
]

The Shell

(base) ankita@ankita-HP-Laptop-15-bs0xx:~/dev/trydjango/tweetme$ ./manage.py shell
Python 3.7.4 (default, Aug 13 2019, 20:35:49)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from tweets.models import Tweet

In [2]: obj = Tweet.objects.get(id = 1)

In [3]: obj
Out[3]: <Tweet: Tweet object (1)>

In [4]: obj.content
Out[4]: 'Hello World!'

In [5]: obj.id
Out[5]: 1

The localhost page have only next text:

Hello {{obj.id}} - {{obj.content}}

Body:
If you create template to render your page, this task is quite simple to achieve. So, why don/t you create template and render it using render?

hello_word.html

<html>
    <body>
        <h1>Hello {{obj.id}} - {{obj.content}}</h1>
    </html>
</body>

views.py

instead of HttpResponse:

return render(request, 'hello_world.html', {'obj': obj})

I would say that this is a regular Django way to render templates.


问:
Python_Function for customdata hover in plotly lib
In the code below I tried to use customdata to make hovertemplate, but in this case on visualization it shows only data from the first row everywhere. I believe there should be function, but don't know how to implement it.

```<code>import plotly.express as px
import plotly.graph_objs as go
import pandas as pd

rows=[['501-600','15','122.58333','45.36667'],
      ['till 500','4','12.5','27.5'],
      ['more 1001','41','-115.53333','38.08'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)
df = df.astype({"data": int})

fig=px.scatter_geo(df,lon='longitude', lat='latitude',
                      color='bins',
                      opacity=0.5,
                      size='data',
                      projection="natural earth")

new_customdata = df.loc[:,('bins', 'data')]
fig.update_traces(go.Scattergeo(
customdata=new_customdata,
hovertemplate="<b>%{customdata[0]} </b><br><br>" + \
              "blablabla: %{customdata[1]: .3f}<extra></extra>"))

fig.show()
</code>```

答:
I believe this does what you're looking for:

```<code>rows=[['501-600','15','122.58333','45.36667'],
      ['till 500','4','12.5','27.5'],
      ['more 1001','41','-115.53333','38.08'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)
df = df.astype({"data": int})

fig = go.Figure(data=go.Scattergeo(
    lon = df['longitude'],
    lat = df['latitude'],
    mode = 'markers',
    marker_color = df.index,
    marker_size=df['data'],
    customdata = df,

    hovertemplate="<b>%{customdata[0]} </b><br><br>blablabla: %{customdata[1]: .3f}<extra></extra>"

))

fig.show()
</code>```

The result is (there's different hover text for each item):

Body:
In the code below I tried to use customdata to make hovertemplate, but in this case on visualization it shows only data from the first row everywhere. I believe there should be function, but don't know how to implement it.

import plotly.express as px
import plotly.graph_objs as go
import pandas as pd

rows=[['501-600','15','122.58333','45.36667'],
      ['till 500','4','12.5','27.5'],
      ['more 1001','41','-115.53333','38.08'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)
df = df.astype({"data": int})

fig=px.scatter_geo(df,lon='longitude', lat='latitude',
                      color='bins',
                      opacity=0.5,
                      size='data',
                      projection="natural earth")

new_customdata = df.loc[:,('bins', 'data')]
fig.update_traces(go.Scattergeo(
customdata=new_customdata,
hovertemplate="%{customdata[0]}

" + \
              "blablabla: %{customdata[1]: .3f}<extra></extra>"))

fig.show()

Body:
I believe this does what you're looking for:

rows=[['501-600','15','122.58333','45.36667'],
      ['till 500','4','12.5','27.5'],
      ['more 1001','41','-115.53333','38.08'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)
df = df.astype({"data": int})

fig = go.Figure(data=go.Scattergeo(
    lon = df['longitude'],
    lat = df['latitude'],
    mode = 'markers',
    marker_color = df.index,
    marker_size=df['data'],
    customdata = df,

    hovertemplate="<b>%{customdata[0]} </b><br><br>blablabla: %{customdata[1]: .3f}<extra></extra>"

))

fig.show()

The result is (there's different hover text for each item):


问:
Iframe video controls not clickable?
i am using that example : https://codepen.io/cyborgspaceviking/pen/BdWagp#code-area
but beside using gif files i am using videos and loading them into iframe.
But video controls not clickable.

This is my replacing html with img tag:

```<code>  <div class="resp-container">
            <iframe class="resp-iframe video" id="gif_tv_video" scrolling="no" frameborder="0" allowfullscreen="1"
              allow="autoplay; encrypted-media" src=""></iframe>
          </div>
</code>```

This is my codepen version link: https://codepen.io/affan-sheikh/pen/MWKggOe

答:
from the preview you've posted, it looks like the img is above the iframe.
Try adding pointer-events:none; to every element above to make it not-clickable.

Check here for more details

Title: Iframe video controls not clickable?

Body:
i am using that example : https://codepen.io/cyborgspaceviking/pen/BdWagp#code-area
but beside using gif files i am using videos and loading them into iframe.
But video controls not clickable.

This is my replacing html with img tag:

This is my codepen version link: https://codepen.io/affan-sheikh/pen/MWKggOe


问:
Use a "case when in" expression where the list values are in a single field?
I'm using SQL Server and would like to check if todays day name is in a list of values in a single field/column.

An example of the column "start_days" contents is:

```<code>'Monday','Tuesday','Sunday'
'Thursday'
'Friday','Sunday'
'Tuesday','Sunday'
'Tuesday','Wednesday','Thursday','Friday'
</code>```

The code I am trying to run on this is:

```<code>case
  when datename(weekday,getdate()) in (start_days) then 1
  else 0
end as today_flag
</code>```

And the result is 0 for every row.
Am I doing something wrong here or is it just not possible to use a single field as a list of values in the statement?

答:
As a starter: you should fix your data model and not store multiple values in a single column. Storing list of values in a database column basically defeats the purpopose of a relational database. Here is a related reading on that topic.

That said, here is one option using pattern matching:

```<code>case
  when ',' + start_days + ',' like '%,' + datename(weekday,getdate()) + ',%' then 1
  else 0
end as today_flag
</code>```

If you really have single quotes around values within the list, then we need to include them in the match:

```<code>case
  when ',' + start_days + ',' like '%,''' + datename(weekday,getdate()) + ''',%' then 1
  else 0
end as today_flag
</code>```

If the values always are weekdays, this can be simplified since there is no risk of overlapping values:

```<code>case
  when start_days like '%''' + datename(weekday,getdate()) + '''%' then 1
  else 0
end as today_flag
</code>```

Body:
I'm using SQL Server and would like to check if todays day name is in a list of values in a single field/column.

An example of the column "start_days" contents is:

'Monday','Tuesday','Sunday'
'Thursday'
'Friday','Sunday'
'Tuesday','Sunday'
'Tuesday','Wednesday','Thursday','Friday'

The code I am trying to run on this is:

case
  when datename(weekday,getdate()) in (start_days) then 1
  else 0
end as today_flag

And the result is 0 for every row.
Am I doing something wrong here or is it just not possible to use a single field as a list of values in the statement?

Body:
As a starter: you should fix your data model and not store multiple values in a single column. Storing list of values in a database column basically defeats the purpopose of a relational database. Here is a related reading on that topic.

That said, here is one option using pattern matching:

case
  when ',' + start_days + ',' like '%,' + datename(weekday,getdate()) + ',%' then 1
  else 0
end as today_flag

If you really have single quotes around values within the list, then we need to include them in the match:

case
  when ',' + start_days + ',' like '%,''' + datename(weekday,getdate()) + ''',%' then 1
  else 0
end as today_flag

If the values always are weekdays, this can be simplified since there is no risk of overlapping values:

case
  when start_days like '%''' + datename(weekday,getdate()) + '''%' then 1
  else 0
end as today_flag


问:
Pause and/or resume audio using Python on Linux
thank you for your attention! I want to pause and/or resume audio which is being played at the background using python, found this way, which uses pynput:

from pynput.keyboard import Controller, Key

c = Controller()
c.press(Key.media_play_pause)
```

But audio is still playing. Seems there are no errors, but it doesn't work.

答:
You might want to try using playerctl, a command line tool that you could use with

```<code>subprocess.call(("playerctl", "play-pause"))
</code>```

However, playerctl might not come preinstalled on your system, so you might have to

sudo apt install playerctl,

pacman -Syu playerctl,

sudo dnf install playerctl or

sudo zypper install playerctl

(depending on your distro)

This would not require pynput, but subprocess (import subprocess). If you don't care about style and security you could of course also use os.system("playerctl play-pause")

Body:
thank you for your attention! I want to pause and/or resume audio which is being played at the background using python, found this way, which uses pynput:

from pynput.keyboard import Controller, Key

c = Controller()
c.press(Key.media_play_pause)

But audio is still playing. Seems there are no errors, but it doesn't work.

Body:
You might want to try using playerctl, a command line tool that you could use with

subprocess.call(("playerctl", "play-pause"))

However, playerctl might not come preinstalled on your system, so you might have to

sudo apt install playerctl,

pacman -Syu playerctl,

sudo dnf install playerctl or

sudo zypper install playerctl

(depending on your distro)

This would not require pynput, but subprocess (import subprocess). If you don't care about style and security you could of course also use os.system("playerctl play-pause")


问:
django custom manager manytomany field add
My code for custom manager below:

```<code>class CustomManager(models.Manager):
    def create(self, **kwargs):
        obj, created = Group.objects.get_or_create(name='group1')
        kwargs.update({'groups': obj})
        return super(CustomManager, self).create(**kwargs)
</code>```

which creates TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead..

答:
As is specified, you can not directly pass a groups= in a create. You can use .set(…) [Django-doc] (or .add(…) [Django-doc]) for example, so:

```<code>class CustomManager(models.Manager):
    def create(self, **kwargs):
        object = super(CustomManager, self).create(**kwargs)
        group, __ = Group.objects.get_or_create(name='group1')
        object.groups<b>.set([group])</b>
        return object</code>```

Body:
My code for custom manager below:

class CustomManager(models.Manager):
    def create(self, **kwargs):
        obj, created = Group.objects.get_or_create(name='group1')
        kwargs.update({'groups': obj})
        return super(CustomManager, self).create(**kwargs)

which creates TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead..

Body:
As is specified, you can not directly pass a groups= in a create. You can use .set(…) [Django-doc] (or .add(…) [Django-doc]) for example, so:

class CustomManager(models.Manager):
    def create(self, **kwargs):
        object = super(CustomManager, self).create(**kwargs)
        group, __ = Group.objects.get_or_create(name='group1')
        object.groups.set([group])
        return object


问:
Combobox change value of other combobox
I have two comboboxes on an form. Each has the values Yes and No. What I want is when one is changed the other get the opposite (if the first is Yes the other is No).I need to do it with Javascript. I saw this question How to change "selected" value in combobox using JavaScript? but it is applied to only one combobox.

How can I do this?

LE:I need this example to be make with comboboxes. I can not use radio buttons

答:
Here is my own attempt working with yes/no values ..

html

```<code><select name="combo1" id="combo1">
    <option value="Yes">Yes</option>
    <option value="No">No</option>
</select>
<br /><br />
<select name="combo2" id="combo2">
    <option value="Yes">Yes</option>
    <option value="No">No</option>
</select>
</code>```

javascript

```<code>window.onload = function() { BindEvent(); }

function BindEvent()
{
    var c1 = document.getElementById ( 'combo1' );
    var c2= document.getElementById ( 'combo2' );

    c1.onchange = invert;
    c2.onchange = invert;

    c1.onchange(); //initialize
}

function invert() {
         var otherElem = document.getElementById( (this.id=='combo1')? 'combo2' : 'combo1');
         otherElem.value = (this.value=='Yes')?'No':'Yes';
    }
</code>```

demo http://jsfiddle.net/gaby/7Ujh2/

Title: Combobox change value of other combobox

Body:
Here is my own attempt working with yes/no values ..

html

<select name="combo1" id="combo1">
    <option value="Yes">Yes</option>
    <option value="No">No</option>
</select>
<br /><br />
<select name="combo2" id="combo2">
    <option value="Yes">Yes</option>
    <option value="No">No</option>
</select>

javascript

window.onload = function() { BindEvent(); }

function BindEvent()
{
    var c1 = document.getElementById ( 'combo1' );
    var c2= document.getElementById ( 'combo2' );

    c1.onchange = invert;
    c2.onchange = invert;

    c1.onchange(); //initialize
}

function invert() {
         var otherElem = document.getElementById( (this.id=='combo1')? 'combo2' : 'combo1');
         otherElem.value = (this.value=='Yes')?'No':'Yes';
    }

demo http://jsfiddle.net/gaby/7Ujh2/