问:
Angular/SignalR Error: Failed to complete negotiation with the server
Using SignalR for my server and Angular for my client... When I run my client I receive these errors:

```<code>zone.js:2969 OPTIONS https://localhost:27967/chat/negotiate 0 ()

Utils.js:148 Error: Failed to complete negotiation with the server: Error

Utils.js:148 Error: Failed to start the connection: Error
</code>```

I am guessing it is something with CORS... I am trying to implement a simple chat application. I am using the latest verison of SignalR:

Here is the github that contains the code for the tutorial I am following.
SignalR Chat Tutorial

Here is my startup

```<code>    using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace signalrChat
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins("http://localhost:4200");
            }));

            services.AddSignalR();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("CorsPolicy");

            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("/chat");
            });
        }
    }
}
</code>```

And here is my client:

```<code>    import { Component, OnInit } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  private hubConnection: HubConnection;

  nick = '';
  message = '';
  messages: string[] = [];

  ngOnInit() {
    this.nick = window.prompt('Your name:', 'John');

    this.hubConnection = new HubConnectionBuilder().withUrl('https://localhost:27967/chat').build();

    this.hubConnection
    .start()
    .then(() => console.log("Connection Started!"))
    .catch(err => console.log("Error while establishing a connection :( "));

    this.hubConnection.on('sendToAll', (nick: string, receiveMessage: string) => {
      const text = `${nick}: ${receiveMessage}`;
      this.messages.push(text);
    })
  }

  public sendMessage(): void {
    this.hubConnection
    .invoke('sendToAll', this.nick, this.message)
    .catch(err => console.log(err));
  }

}
</code>```

I assume it may be something with cors. Thank you!

EDIT: I just recreated the signalr implementation in visual studio and it worked. I believe I chose the wrong settings on start up.

答:
I faced the slimier issue and I fixed it by adding

```<code>skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
</code>```

in client-side as @Caims mentioned. But I don't think this is the correct solution and feel more like a hack .
What you have to do is adding AllowCredentials in server side. Anyway when it's coming to Azure you can't relay on that fix. So no need enable WSS only in client side.

Here is my ConfigureServices method:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
        builder
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials()
        .WithOrigins("http://localhost:4200");
    }));

    services.AddSignalR();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
</code>```

This is my Configure method:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("CorsPolicy");
    app.UseSignalR(routes =>
    {
        routes.MapHub<NotifyHub>("/notify");
    });

    app.UseMvc();
}
</code>```

And finally this is how I connected from client-side:

```<code>const connection = new signalR.HubConnectionBuilder()
      .configureLogging(signalR.LogLevel.Debug)
      .withUrl("http://localhost:5000/notify", {
        //skipNegotiation: true,
        //transport: signalR.HttpTransportType.WebSockets
      }).build();

connection.start().then(function () {
    console.log('Connected!');
}).catch(function (err) {
    return console.error(err.toString());
});

connection.on("BroadcastMessage", (type: string, payload: string) => {
    this.msgs.push({ severity: type, summary: payload });
});
</code>```

Body:
Using SignalR for my server and Angular for my client... When I run my client I receive these errors:

zone.js:2969 OPTIONS https://localhost:27967/chat/negotiate 0 ()

Utils.js:148 Error: Failed to complete negotiation with the server: Error

Utils.js:148 Error: Failed to start the connection: Error

I am guessing it is something with CORS... I am trying to implement a simple chat application. I am using the latest verison of SignalR:

Here is the github that contains the code for the tutorial I am following.
SignalR Chat Tutorial

Here is my startup

    using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace signalrChat
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins("http://localhost:4200");
            }));

            services.AddSignalR();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("CorsPolicy");

            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("/chat");
            });
        }
    }
}

And here is my client:

    import { Component, OnInit } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  private hubConnection: HubConnection;

  nick = '';
  message = '';
  messages: string[] = [];

  ngOnInit() {
    this.nick = window.prompt('Your name:', 'John');

    this.hubConnection = new HubConnectionBuilder().withUrl('https://localhost:27967/chat').build();

    this.hubConnection
    .start()
    .then(() => console.log("Connection Started!"))
    .catch(err => console.log("Error while establishing a connection :( "));

    this.hubConnection.on('sendToAll', (nick: string, receiveMessage: string) => {
      const text = `${nick}: ${receiveMessage}`;
      this.messages.push(text);
    })
  }

  public sendMessage(): void {
    this.hubConnection
    .invoke('sendToAll', this.nick, this.message)
    .catch(err => console.log(err));
  }

}

I assume it may be something with cors. Thank you!

EDIT: I just recreated the signalr implementation in visual studio and it worked. I believe I chose the wrong settings on start up.

Body:
I faced the slimier issue and I fixed it by adding

skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets

in client-side as @Caims mentioned. But I don't think this is the correct solution and feel more like a hack .
What you have to do is adding AllowCredentials in server side. Anyway when it's coming to Azure you can't relay on that fix. So no need enable WSS only in client side.

Here is my ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
        builder
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials()
        .WithOrigins("http://localhost:4200");
    }));

    services.AddSignalR();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

This is my Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("CorsPolicy");
    app.UseSignalR(routes =>
    {
        routes.MapHub<NotifyHub>("/notify");
    });

    app.UseMvc();
}

And finally this is how I connected from client-side:

const connection = new signalR.HubConnectionBuilder()
      .configureLogging(signalR.LogLevel.Debug)
      .withUrl("http://localhost:5000/notify", {
        //skipNegotiation: true,
        //transport: signalR.HttpTransportType.WebSockets
      }).build();

connection.start().then(function () {
    console.log('Connected!');
}).catch(function (err) {
    return console.error(err.toString());
});

connection.on("BroadcastMessage", (type: string, payload: string) => {
    this.msgs.push({ severity: type, summary: payload });
});


来源: stackexchange

问:
HTML, open link click anywhere on page
I  have code for clickable background that I want to use but when I click on background its always open. How to make this code to work one per day BUT at most easiest way possible... with cookie or something else. I really need help with this. Thanks!</p>

```<code><body onclick="location.href='test.html';">
</code>```

答:
If you want to restrict the user to open the link only once per day. You can do something like this:</p>

```<code><body onclick="openLink()">

<script>
function openLink() {
  var today = new Date();
  var dd = String(today.getDate()).padStart(2, '0');
  var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
  var yyyy = today.getFullYear();

  today = mm + '/' + dd + '/' + yyyy;

  // As date object returns time as well. Which we dont need. So we remove that.

  if(localStorage.getItem('date') == today) {
    alert('come back tomorrow');
  } else {
    localStorage.setItem('date', today);
    location.href='test.html';
  }
}
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Title: HTML, open link click anywhere on page

Body:
If you want to restrict the user to open the link only once per day. You can do something like this:

<body onclick="openLink()">

<script>
function openLink() {
  var today = new Date();
  var dd = String(today.getDate()).padStart(2, '0');
  var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
  var yyyy = today.getFullYear();

  today = mm + '/' + dd + '/' + yyyy;

  // As date object returns time as well. Which we dont need. So we remove that.

  if(localStorage.getItem('date') == today) {
    alert('come back tomorrow');
  } else {
    localStorage.setItem('date', today);
    location.href='test.html';
  }
}
</script>


问:
How exactly CSS works?
Currently, I am stack with CSS. I can't understand how exactly CSS works.
If I want to apply "border: 1px solid red" to a CSS parent element then it is only applied to parent element but not other elements (children) that inside this parent. But If I apply "color: red" then the color property is applied to every single child inside the parent (Including parent itself).

Example-1:

```<code><div class="parent">
    Inside parent class
    <div class="child">Inside child class 1</div>
    <div class="child">Inside child class 2</div>
</div>
</code>```

```<code>.parent {
  border: 1px solid red;
}
</code>```

Example-2:

```<code><div class="parent">
    Inside parent class
    <div class="child">Inside child class 1</div>
    <div class="child">Inside child class 2</div>
</div>
</code>```

```<code>.parent {
  color: red;
}
</code>```

why example-1 works for the parent element, not for children.
Example-2 works fine what I expected.

答:
The reason behind this is with CSS property inheritance. All HTML elements have a default set of values for all CSS properties.

The color property is typically set to "inherit", therefore, child elements will inherit the parent element values for this property unless the child element explicitly has set the property to another value.

The border property on the other hand does not have "inherit" as it's default behavior therefore does not inherit parent values unless you have specifically set it too.

Hope this helps!

Title: How exactly CSS works?

Body:
Currently, I am stack with CSS. I can't understand how exactly CSS works.
If I want to apply "border: 1px solid red" to a CSS parent element then it is only applied to parent element but not other elements (children) that inside this parent. But If I apply "color: red" then the color property is applied to every single child inside the parent (Including parent itself).

Example-1:

    Inside parent class

Inside child class 1

Inside child class 2

.parent {
  border: 1px solid red;
}

Example-2:

    Inside parent class

Inside child class 1

Inside child class 2

.parent {
  color: red;
}

why example-1 works for the parent element, not for children.
Example-2 works fine what I expected.


问:
Finding roots of a non linear expression when multiplied with a linear expression
Here is a simple polynomial equation:

```<code>b^2 + 2b + 1 = 0
</code>```

I could easily solve this as:

```<code>import numpy as np
from scipy.optimize import fsolve

eq = lambda b : np.power(b,2) + 2*b + 1
fsolve(eq, np.linspace(0,1,2))
</code>```

Similarly I could solve any equation, that has finite number of terms. But how do I solve an equation with infinite number of terms which is given as :

The above equation could be written as :

```<code>5 = (1 - l) * (5.5 + 4.0*l + 4*l^2 + 6*l^3 + 5*l^4 + 5*l^5 + 5*l^6 + 5*l^7 + 5*l^8 + 5*l^9 + 5*l^10   )
</code>```

when n goes from 1 to 10. But I want to solve this for sufficiently large value of n such that LHS ~= RHS.

I know the values of LHS and G1 -> Ginf but cannot understand how could I compute the value of lambda here.

I tried looking at numpy polynomial functions but could not find a function that is relevant here.

答:
The following glosses over the fact that I do not 100% understand the coefficient notation G_t:t+n (what kind of dependency is that supposed to indicate exactly?)

Obviously, the solution will depend on coefficients. If as your example suggests, the coefficients are all equal above some index n_0 then your r.h.s. expression is a telescoping sum and equal to G_t:1 + sum_1^n_0 [G_t:n - G_t:n+1] l^n`. Be sure to note that this sum is finite, so you know how to proceed from here.

One caveat: you must have |l| < 1 otherwise the series does not converge and the r.h.s. is undefined, although some kind of continuation argument may be possible.

Body:
Here is a simple polynomial equation:

b^2 + 2b + 1 = 0

I could easily solve this as:

import numpy as np
from scipy.optimize import fsolve

eq = lambda b : np.power(b,2) + 2*b + 1
fsolve(eq, np.linspace(0,1,2))

Similarly I could solve any equation, that has finite number of terms. But how do I solve an equation with infinite number of terms which is given as :

The above equation could be written as :

5 = (1 - l) * (5.5 + 4.0*l + 4*l^2 + 6*l^3 + 5*l^4 + 5*l^5 + 5*l^6 + 5*l^7 + 5*l^8 + 5*l^9 + 5*l^10   )

when n goes from 1 to 10. But I want to solve this for sufficiently large value of n such that LHS ~= RHS.

I know the values of LHS and G1 -> Ginf but cannot understand how could I compute the value of lambda here.

I tried looking at numpy polynomial functions but could not find a function that is relevant here.


问:
How to use describe keypsaces; command in jupyter notebook
I am reading Cassandra database data in Jupiter notebook. In Cassandra we can use this with command "describe keyspaces;".

Suppose, once I am Jupyter is connected Cassandra and I dont want to use Cassandra, want to input Cassandra commands through Jupyter notebook, how to achieve describe keyspaces in order to know the keyspaces

Tried entering describe keyspaces; command

```<code>from cassandra.cluster import Cluster
cluster = Cluster(['127.0.0.1'])  # provide contact points and port
session = cluster.connect('fiirstkeyspace')
rows = session.execute('select * from books_by_author limit 5 ;')
for row in rows:
    print(row)
</code>```

In the above code, I know I have a keyspace called 'fiirstkeyspace'

however,I want to know all the keyspaces in Cassandra through Jupyter notebook.

```<code>show keyspaces;
  File "<ipython-input-62-dd2f479cd0fc>", line 1
    show keyspaces;
                 ^
SyntaxError: invalid syntax

describe keyspaces;
 File "<ipython-input-67-21f5033a29b3>", line 1
    describe keyspaces;
                     ^
SyntaxError: invalid syntax
</code>```

答:
describe keyspaces, etc. are commands that are implemented in cqlsh - they aren't real CQL commands.  In Python you can get all this information via Metadata class, that hides implementation details, as schema for system tables could differ between versions.

The code for getting names of all keyspaces is quite simple (cluster is the name of object that you created to connect to Cassandra cluster):

cluster.metadata.keyspaces.keys()
```

And then you can fetch data about individual keyspaces from cluster.metadata.keyspaces map.

Body:
I am reading Cassandra database data in Jupiter notebook. In Cassandra we can use this with command "describe keyspaces;".

Suppose, once I am Jupyter is connected Cassandra and I dont want to use Cassandra, want to input Cassandra commands through Jupyter notebook, how to achieve describe keyspaces in order to know the keyspaces

Tried entering describe keyspaces; command

from cassandra.cluster import Cluster
cluster = Cluster(['127.0.0.1'])  # provide contact points and port
session = cluster.connect('fiirstkeyspace')
rows = session.execute('select * from books_by_author limit 5 ;')
for row in rows:
    print(row)

In the above code, I know I have a keyspace called 'fiirstkeyspace'

however,I want to know all the keyspaces in Cassandra through Jupyter notebook.

show keyspaces;
  File "<ipython-input-62-dd2f479cd0fc>", line 1
    show keyspaces;
                 ^
SyntaxError: invalid syntax

describe keyspaces;
 File "<ipython-input-67-21f5033a29b3>", line 1
    describe keyspaces;
                     ^
SyntaxError: invalid syntax

Body:
describe keyspaces, etc. are commands that are implemented in cqlsh - they aren't real CQL commands.  In Python you can get all this information via Metadata class, that hides implementation details, as schema for system tables could differ between versions.

The code for getting names of all keyspaces is quite simple (cluster is the name of object that you created to connect to Cassandra cluster):

cluster.metadata.keyspaces.keys()

And then you can fetch data about individual keyspaces from cluster.metadata.keyspaces map.


答:
Different CSS properties have different inheritance and cascade rules. You need to see the CSS specification to see how each one behaves.

In your case, you're asking why border is not inherited by child elements but color is:

The CSS specification for border states that it is not inherited: https://www.w3.org/TR/css-backgrounds-3/#the-border-color

The CSS specification for color states that it is inherited: https://www.w3.org/TR/css-color-3/#foreground

Web developers and designers eventually familiarise themselves with each property and just memorize which properties are inherited and which are not.

But generally speaking (as a rule-of-thumb): if a rule affects the layout of an element (e.g. a box's dimensions, including padding, width/height, margin, position, etc) then it won't be inherited, and properties that only affect text (like color, font-family, font-weight, etc) are inherited. The edge-cases are in other properties like background-image, opacity and filter where you need to consult the spec to be sure.

Title: How exactly CSS works?


问:
Unable to read the data from kafka topics using spark streaming
I am trying to read the data from the kafka topic using the spark streaming. I am able to produce the message into the kafka topic, but whilereading the data from topic using spark streaming i am getting error message as given below:

```<code>ERROR ReceiverTracker: Deregistered receiver for stream 0: Error starting receiver 0 - java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String
</code>```

below is the code:

```<code>from pyspark import SparkConf, SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import pprint

conf= SparkConf().setAppName(“streaming test”).setMaster(“yarn-client”)
sc=SparkContext(conf=conf)
ssc=StreamingContext(sc,10)

topic = “newone”
broker = {“metadata.broker.list”: “URL”}
direct = KafkaUtils.createStream(ssc,broker,“test”,{topic:1})

direct.pprint()
ssc.start()
ssc.awaitTermination()
</code>```

答:
Output Operations on DStreams

print() - Prints the first ten elements of every batch of data in a
  DStream on the driver node running the streaming application. This is
  useful for development and debugging. Python API This is called
  pprint() in the Python API.

java.util.Hashmap is coming in the message i.e. InputDStream[ConsumerRecord[K, V]]   you want to print that, while and hence java.lang.ClassCastException

you have to parse the message and print it like this...

```<code> direct.transform(...).map(lambda ...)
</code>```

examples here :tests.py

Body:
I am trying to read the data from the kafka topic using the spark streaming. I am able to produce the message into the kafka topic, but whilereading the data from topic using spark streaming i am getting error message as given below:

ERROR ReceiverTracker: Deregistered receiver for stream 0: Error starting receiver 0 - java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String

below is the code:

from pyspark import SparkConf, SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import pprint

conf= SparkConf().setAppName(“streaming test”).setMaster(“yarn-client”)
sc=SparkContext(conf=conf)
ssc=StreamingContext(sc,10)

topic = “newone”
broker = {“metadata.broker.list”: “URL”}
direct = KafkaUtils.createStream(ssc,broker,“test”,{topic:1})

direct.pprint()
ssc.start()
ssc.awaitTermination()

Body:
Output Operations on DStreams

print() - Prints the first ten elements of every batch of data in a
  DStream on the driver node running the streaming application. This is
  useful for development and debugging. Python API This is called
  pprint() in the Python API.

java.util.Hashmap is coming in the message i.e. InputDStream[ConsumerRecord[K, V]]   you want to print that, while and hence java.lang.ClassCastException

you have to parse the message and print it like this...

 direct.transform(...).map(lambda ...)

examples here :tests.py


问:
Beautiful Soup output not very readable
I have created a twitter scraper using the Beautiful Soup library. I have successfully managed to retrieve the Bio and the top tweet of a given user using their user name. The only issue I am having is that the output is a bit weird as the output is extracted from HTML code it contains many empty lines.

I have tried using prettify but all that returns is an empty line. I have also tried using pprint.pprint.

I am new to python and can't think of any other way to make the output of my script any neater

Any help would be greatly appreciated.

Below is my script:

```<code>import requests
from bs4 import BeautifulSoup
import pprint

q = "https://twitter.com"

def find_bio(username):
    c = format("https://twitter.com"+"/" + username)
    r = requests.get(c)
    s = BeautifulSoup(r.text, "html.parser")

    return s.find("div", class_="ProfileHeaderCard").text

def find_toptweet(username):
    c = format("https://twitter.com"+"/" + username)
    r = requests.get(c)
    s = BeautifulSoup(r.text, "html.parser")

    return s.find("div", class_="content").text

if __name__ == "__main__":
    username = input('enter username: ')
    bio = find_bio(username)
    tweet = find_toptweet(username)
    print("Bio--------------------------------------------------------------")
    pprint.pprint(bio)
    print("End of Bio-------------------------------------------------------")
    print('top tweet')
    pprint.pprint(tweet)
</code>```

Output below

```<code>enter username: altifali4
Bio--------------------------------------------------------------------------------------
('\n'
 '\n'
 'Altif Ali\n'
 '\n'
 '\n'
 '\n'
 '@AltifAli4\n'
 '\n'
 '\n'
 'People, by and large, are good people\n'
 '\n'
 'UoH\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
' \n'
 '    instagram.com/altif.ali\n'
 '  \n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Joined August 2018\n'
 '\n'
 '\n'
 '\n'
 '    Born 1999\n'
 '\n'
 '\n'
 '\n')
End of Bio---------------------------------------------------------------- ----------------------
top tweet
('\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Lowkey\u200f\xa0@Lowkey0nline\n'
 '\n'
 'May 22\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'More\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Copy link to Tweet\n'
 '\n'
 '\n'
 'Embed Tweet\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Power concedes nothing without demand. Without demand power concedes '
 'nothing.\n')

Process finished with exit code 0
</code>```

答:
Try replacing your if statement with the following one:

```<code>if __name__ == "__main__":
    username = input('enter username: ')
    bio = find_bio(username).replace("\n","")
    tweet = find_toptweet(username).replace("\n","")
    print("Bio--------------------------------------------------------------")
    print(bio)
    print("End of Bio-------------------------------------------------------")
    print('top tweet')
    print(tweet)
</code>```

hope this helps

Title: Beautiful Soup output not very readable

Body:
I have created a twitter scraper using the Beautiful Soup library. I have successfully managed to retrieve the Bio and the top tweet of a given user using their user name. The only issue I am having is that the output is a bit weird as the output is extracted from HTML code it contains many empty lines.

I have tried using prettify but all that returns is an empty line. I have also tried using pprint.pprint.

I am new to python and can't think of any other way to make the output of my script any neater

Any help would be greatly appreciated.

Below is my script:

import requests
from bs4 import BeautifulSoup
import pprint

q = "https://twitter.com"

def find_bio(username):
    c = format("https://twitter.com"+"/" + username)
    r = requests.get(c)
    s = BeautifulSoup(r.text, "html.parser")

    return s.find("div", class_="ProfileHeaderCard").text

def find_toptweet(username):
    c = format("https://twitter.com"+"/" + username)
    r = requests.get(c)
    s = BeautifulSoup(r.text, "html.parser")

    return s.find("div", class_="content").text

if __name__ == "__main__":
    username = input('enter username: ')
    bio = find_bio(username)
    tweet = find_toptweet(username)
    print("Bio--------------------------------------------------------------")
    pprint.pprint(bio)
    print("End of Bio-------------------------------------------------------")
    print('top tweet')
    pprint.pprint(tweet)

Output below

enter username: altifali4
Bio--------------------------------------------------------------------------------------
('\n'
 '\n'
 'Altif Ali\n'
 '\n'
 '\n'
 '\n'
 '@AltifAli4\n'
 '\n'
 '\n'
 'People, by and large, are good people\n'
 '\n'
 'UoH\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
' \n'
 '    instagram.com/altif.ali\n'
 '  \n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Joined August 2018\n'
 '\n'
 '\n'
 '\n'
 '    Born 1999\n'
 '\n'
 '\n'
 '\n')
End of Bio---------------------------------------------------------------- ----------------------
top tweet
('\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Lowkey\u200f\xa0@Lowkey0nline\n'
 '\n'
 'May 22\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'More\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Copy link to Tweet\n'
 '\n'
 '\n'
 'Embed Tweet\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 '\n'
 'Power concedes nothing without demand. Without demand power concedes '
 'nothing.\n')

Process finished with exit code 0

Body:
Try replacing your if statement with the following one:

if __name__ == "__main__":
    username = input('enter username: ')
    bio = find_bio(username).replace("\n","")
    tweet = find_toptweet(username).replace("\n","")
    print("Bio--------------------------------------------------------------")
    print(bio)
    print("End of Bio-------------------------------------------------------")
    print('top tweet')
    print(tweet)

hope this helps


问:
CreateAtAction returns "No route matches the supplied values" in ASP.Net Web API
I have the following Put Method to update my Item::

```<code>[HttpPut]
[Route("items")]
public async Task<IActionResult> UpdateProduct([FromBody] CatalogItem productToUpdate)
{
       var catalogItem = await _catalogContext.CatalogItems.SingleOrDefaultAsync(i => i.Id == productToUpdate.Id);
       if (catalogItem == null) return NotFound(new { Message = $"Item with id {productToUpdate.Id} not found." });

       catalogItem = productToUpdate;
       _catalogContext.CatalogItems.Update(catalogItem);
       await _catalogContext.SaveChangesAsync();

       return CreatedAtAction(nameof(GetItemById), new { id = productToUpdate.Id }, productToUpdate);
}
</code>```

And the following GetItemBy Id Action:

```<code>[HttpGet]
[Route("items/{id:int}")]
public async Task<IActionResult> GetItemById(int id)
{
       if (id <= 0)
       {
           return BadRequest();
       }
       var item = await _catalogContext.CatalogItems.SingleOrDefaultAsync(c => c.Id == id);
       if (item != null)
       {

           return Ok(item);
       }
       return NotFound();
}
</code>```

When I call the Update action via swagger with this object:

```<code>{
  "id": 42,
  "name": "TestProduct",
  "description": "this is a test",
  "price": 12.55,
  "imageFileName": null,
  "imagePath": null,
  "catalogTypeId": 1,
  "catalogBrandId": 2
}
</code>```

I get this error:

An unhandled exception was thrown by the application. catalogapi  |
  System.InvalidOperationException: No route matches the supplied
  values.

The item is updated in the database, but the error occurs when CreatedAtAction is executed. I have the same problem in my POST action. I tried to use CreatedAtRoute and even tried it without the third parameter productToUpdate. I can call the GetItemById (/api/Catalog/items/42) without any problem...

Is there anything I am missing here?

答: Does the get work? If so, change the route on the put to the same as the get.</p>

Body:
I have the following Put Method to update my Item::

[HttpPut]
[Route("items")]
public async Task<IActionResult> UpdateProduct([FromBody] CatalogItem productToUpdate)
{
       var catalogItem = await _catalogContext.CatalogItems.SingleOrDefaultAsync(i => i.Id == productToUpdate.Id);
       if (catalogItem == null) return NotFound(new { Message = $"Item with id {productToUpdate.Id} not found." });

       catalogItem = productToUpdate;
       _catalogContext.CatalogItems.Update(catalogItem);
       await _catalogContext.SaveChangesAsync();

       return CreatedAtAction(nameof(GetItemById), new { id = productToUpdate.Id }, productToUpdate);
}

And the following GetItemBy Id Action:

[HttpGet]
[Route("items/{id:int}")]
public async Task<IActionResult> GetItemById(int id)
{
       if (id <= 0)
       {
           return BadRequest();
       }
       var item = await _catalogContext.CatalogItems.SingleOrDefaultAsync(c => c.Id == id);
       if (item != null)
       {

           return Ok(item);
       }
       return NotFound();
}

When I call the Update action via swagger with this object:

{
  "id": 42,
  "name": "TestProduct",
  "description": "this is a test",
  "price": 12.55,
  "imageFileName": null,
  "imagePath": null,
  "catalogTypeId": 1,
  "catalogBrandId": 2
}

I get this error:

An unhandled exception was thrown by the application. catalogapi  |
  System.InvalidOperationException: No route matches the supplied
  values.

The item is updated in the database, but the error occurs when CreatedAtAction is executed. I have the same problem in my POST action. I tried to use CreatedAtRoute and even tried it without the third parameter productToUpdate. I can call the GetItemById (/api/Catalog/items/42) without any problem...

Is there anything I am missing here?


问:
How to create a Column that defaults to a ListView as fallback if the content widgets are too large?
I have some widgets that I want to display on a screen.

If the screen is large enough, the widgets should be centered on it like this:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [...],
)
```

<p>On small screens, I don't want the <code>Column</code> to overflow (black & yellow stripes) but instead, let the user scroll through them, as if they were in a <code>ListView</code>, like this:</p>

<pre class="lang-dart prettyprint-override"><code>ListView(
  children: [...],
)
</code>```

If I knew the dimensions of the widgets beforehand, I could change the layout to one of the above in a LayoutBuilder based on the incoming constraints.
However, I don't know how their dimensions, so is there any easy way to achieve this on the widget layer?

答: You can wrap your column with a SingheChildScrollView and it should work for you.</p>

Body:
I have some widgets that I want to display on a screen.

If the screen is large enough, the widgets should be centered on it like this:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [...],
)

On small screens, I don't want the Column to overflow (black & yellow stripes) but instead, let the user scroll through them, as if they were in a ListView, like this:

ListView(
  children: [...],
)

If I knew the dimensions of the widgets beforehand, I could change the layout to one of the above in a LayoutBuilder based on the incoming constraints.
However, I don't know how their dimensions, so is there any easy way to achieve this on the widget layer?


问:
Rounding problem in Java. Why am i not getting the expected results in this case?
I have a plugin that i made for Minecraft. It is used for massive ender dragon fights to divide the EXP fairly among everybody, based on the damage dealt.

It works but there's a hiccup that makes the equation miss experience.

Here's the code:

```<code>private void divideExpAmongstPlayersBasedOnDamageDealt(int exp, Map<Player, Double> damageMap) {
    double totalDamageDealt = 0.0d;

    for (Double value : damageMap.values()) {
        totalDamageDealt += value;
    }

    while (exp > 0 && !damageMap.isEmpty()) {
        Player maxHitterInList = Collections.max(damageMap.entrySet(),
                Comparator.comparingDouble(Map.Entry::getValue)).getKey();

        double damageShare = damageMap.get(maxHitterInList) / totalDamageDealt;
        int expShare = (int) Math.round(exp * damageShare);

        if (expShare == 0)
            break;

        if (maxHitterInList.isOnline()) {
            sendPlayerMessage(maxHitterInList, damageShare, expShare);
            maxHitterInList.giveExp(expShare);
        }

        exp -= expShare;

        damageMap.remove(maxHitterInList);
    }
}
</code>```

It finds the max hitter, awards them their share of EXP and removes them from the list, until there is no more EXP left to give.

The problem is that it misses points, forcing me to add && !damageMap.isEmpty() to the while condition to avoid exceptions.. It prints the percentages accurately always (the sum adds up to 100).

Im thinking it has to do with the Math.round function, although i am in the dark as how to debug this. When i do the calculations by hand they work out.

Example (this literally happened): A mob grants 10 exp. Player1 did 57% of damage, Player2 did 43%. The percentage values get printed correctly, yet Player1 receives 6 EXP and Player2 receives 2?? Last time i checked 0.57 * 10 equals 5.7 = 6 and 0.43 * 10 equals 4.3 = 4.

What am i missing? Does it have to do with the round function or the way doubles work?

Thanks

答:
This is not a rounding issue but you are using the wrong value in your calculation.

You wrote "Last time i checked 0.57 * 10 equals 5.7 = 6 and 0.43 * 10 equals 4.3 = 4" but the formula you use is

```<code>int expShare = (int) Math.round(exp * damageShare);
</code>```

and you update exp for each iteration of the loop

```<code>exp -= expShare;
</code>```

which means for your second player exp is for 4 and not 10 as you assumed in your example so the real calculation is 0.43 * 2 which rounded is 2

So you need to separate between the variable used in the condition for the while and the one used in the calculation.

Body:
I have a plugin that i made for Minecraft. It is used for massive ender dragon fights to divide the EXP fairly among everybody, based on the damage dealt.

It works but there's a hiccup that makes the equation miss experience.

Here's the code:

private void divideExpAmongstPlayersBasedOnDamageDealt(int exp, Map<Player, Double> damageMap) {
    double totalDamageDealt = 0.0d;

    for (Double value : damageMap.values()) {
        totalDamageDealt += value;
    }

    while (exp > 0 && !damageMap.isEmpty()) {
        Player maxHitterInList = Collections.max(damageMap.entrySet(),
                Comparator.comparingDouble(Map.Entry::getValue)).getKey();

        double damageShare = damageMap.get(maxHitterInList) / totalDamageDealt;
        int expShare = (int) Math.round(exp * damageShare);

        if (expShare == 0)
            break;

        if (maxHitterInList.isOnline()) {
            sendPlayerMessage(maxHitterInList, damageShare, expShare);
            maxHitterInList.giveExp(expShare);
        }

        exp -= expShare;

        damageMap.remove(maxHitterInList);
    }
}

It finds the max hitter, awards them their share of EXP and removes them from the list, until there is no more EXP left to give.

The problem is that it misses points, forcing me to add && !damageMap.isEmpty() to the while condition to avoid exceptions.. It prints the percentages accurately always (the sum adds up to 100).

Im thinking it has to do with the Math.round function, although i am in the dark as how to debug this. When i do the calculations by hand they work out.

Example (this literally happened): A mob grants 10 exp. Player1 did 57% of damage, Player2 did 43%. The percentage values get printed correctly, yet Player1 receives 6 EXP and Player2 receives 2?? Last time i checked 0.57 * 10 equals 5.7 = 6 and 0.43 * 10 equals 4.3 = 4.

What am i missing? Does it have to do with the round function or the way doubles work?

Thanks

Body:
This is not a rounding issue but you are using the wrong value in your calculation.

You wrote "Last time i checked 0.57 * 10 equals 5.7 = 6 and 0.43 * 10 equals 4.3 = 4" but the formula you use is

int expShare = (int) Math.round(exp * damageShare);

and you update exp for each iteration of the loop

exp -= expShare;

which means for your second player exp is for 4 and not 10 as you assumed in your example so the real calculation is 0.43 * 2 which rounded is 2

So you need to separate between the variable used in the condition for the while and the one used in the calculation.


问:
How to allow circular relation with nullable: false?
I want to store who is the "creator" and "updater" of every record as a reference to the "User" table in my database. This applies to every table, including the "User" table itself. This is because it can happen that a record is created either by the user that is registering or by some other already existing user.

On the "User" table I have a DB trigger that fills the "creator" and "updater" fields to the same value as the newly generated "id" by default, hence I would like to use a NOT NULL constraint on my "creator" and "updater" column. Unfortunately, this results in the following error: "Circular relations detected: User -> User. To resolve this issue you need to set nullable: false somewhere in this dependency structure."

Is there a way for me to have a circular relation with a not null constraint using TypeORM?

答:
I was actually able to make it work. I'm going to share my solution in case anyone is looking for an answer.

Before I was trying to auto generate the "created_by" column in the following way:

```<code>@ManyToOne(type => User, { onUpdate: 'CASCADE', onDelete: 'CASCADE', nullable: false })
@JoinColumn({ name: 'created_by' })
creator: User
</code>```

All I had to do to make it work was to remove the nullable: false from there and move it to a new @Column field so that in total I would have:

```<code>@Column({ nullable: false })
created_by: number

@ManyToOne(type => User, { onUpdate: 'CASCADE', onDelete: 'CASCADE' })
@JoinColumn({ name: 'created_by' })
creator: User
</code>```

Body:
I was actually able to make it work. I'm going to share my solution in case anyone is looking for an answer.

Before I was trying to auto generate the "created_by" column in the following way:

@ManyToOne(type => User, { onUpdate: 'CASCADE', onDelete: 'CASCADE', nullable: false })
@JoinColumn({ name: 'created_by' })
creator: User

All I had to do to make it work was to remove the nullable: false from there and move it to a new @Column field so that in total I would have:

@Column({ nullable: false })
created_by: number

@ManyToOne(type => User, { onUpdate: 'CASCADE', onDelete: 'CASCADE' })
@JoinColumn({ name: 'created_by' })
creator: User


问:
difference between let inside and outside a lambda expression
Consider a module with the following procedures:

```<code>(define-module (test test)
  #:export     (proc1 proc2 proc3))

(define proc1
  (let ((module (current-module)))
    (lambda ()
      (format #t "~s\n" module))))

(define proc2
  (lambda ()
    (let ((module (current-module)))
      (format #t "~s\n" module))))

(define (proc3)
  (let ((module (current-module)))
    (format #t "~s\n" module)))
</code>```

I was under the impression that all these were equivalent, but they are not.

```<code>scheme@(guile-user)> (use-modules (test test))
scheme@(guile-user)> (proc1)
#<directory (test test) 562a062152d0>
$1 = #t
scheme@(guile-user)> (proc2)
#<directory (guile-user) 562a05b8bbd0>
$2 = #t
scheme@(guile-user)> (proc3)
#<directory (guile-user) 562a05b8bbd0>
$3 = #t
</code>```

Only in proc1 the module symbol inside the lambda expression is bound to the module were the procedure is defined.

Can somebody explain this? Does it mean I always have to use the first form, if I want to create a closure?

答:
Only proc1 prints the test module.

proc2 and proc3 are equivalent, they print the REPL module.

As well as executing proc1,2,3 try (current-module) in the REPL. It will make things clearer.

For proc1 (current-module) is executed at the time the procedure is defined, for proc2 and proc2 (current-module) is executed at the time the procedure is called.

Body:
Consider a module with the following procedures:

(define-module (test test)
  #:export     (proc1 proc2 proc3))

(define proc1
  (let ((module (current-module)))
    (lambda ()
      (format #t "~s\n" module))))

(define proc2
  (lambda ()
    (let ((module (current-module)))
      (format #t "~s\n" module))))

(define (proc3)
  (let ((module (current-module)))
    (format #t "~s\n" module)))

I was under the impression that all these were equivalent, but they are not.

scheme@(guile-user)> (use-modules (test test))
scheme@(guile-user)> (proc1)
#<directory (test test) 562a062152d0>
$1 = #t
scheme@(guile-user)> (proc2)
#<directory (guile-user) 562a05b8bbd0>
$2 = #t
scheme@(guile-user)> (proc3)
#<directory (guile-user) 562a05b8bbd0>
$3 = #t

Only in proc1 the module symbol inside the lambda expression is bound to the module were the procedure is defined.

Can somebody explain this? Does it mean I always have to use the first form, if I want to create a closure?


问:
How to clear MemoryCache in ASP.NET Core?
How to correctly clear IMemoryCache from ASP.NET Core?

I believe this class is missing Clear method, but anyway how to deal with it? In my project I'm caching DocumentRepository's methods for 24 hours where I'm getting lots of rows from database. But sometimes I can change the database, so I want to clear the IMemoryCache as it has got rubbish data.

答:
The cache class and interface don't have any methods for clearing neither ones to iterate over the keys, since it's not meant to be a list and in ASP.NET Core applications one usually use IDistributedCache interface as dependency, since it easier allows you to later change from a local memory cache to a distributed cache (such as memd or Redis).

Instead, if you want to invalidate a specific row, you should remove the cached entry via cache.Remove(myKey).

Of course, this requires you to know the key you want to invalidate. Typically you do that via events. Every time you update an entry in the database, you would fire up an event. This event will be caught by a background service and cause a cache invalidation.

Locally this can be done with any pub/sub library. In distributed scenarios you may want to use pub/sub features of the distributed cache (i.e. Redis).

In cases of lookup tables (where many values are affected), you can have a service refresh the cache (i.e. every 5 to 10 minutes via a background task using a scheduling library such as hangfire or quart.net).

Home work Questions

But one question you should ask yourself: Is it really a good idea to cache documents for 24 hours if they change frequently?

Does the loading of a single document takes so much time, that caching it 24 hours will be worth? Or are shorter times good enough (15, 30, 60 minutes)?


问:
What is the default height on Androids TabLayout
Seems like something that should be easy to find, but it's harder than I thought.
What is the default height on the TabLayout in DIPs?</p>

答:
its height is "?attr/tabIndicatorHeight"

E.g.
 you can use this value in an xml file for another view like:

```<code>android:layout_marginBottom="?attr/tabIndicatorHeight"
</code>```

And it will look  ok on all devices.

ContentLicense: CC BY-SA 3.0

Body:
its height is "?attr/tabIndicatorHeight"

E.g.
 you can use this value in an xml file for another view like:

android:layout_marginBottom="?attr/tabIndicatorHeight"

And it will look  ok on all devices.


问:
How to pass Laravel data into Vue root instance with Laravel Mix Setup
So I am using Laravel 5.5. I have a data coming from my Controller and I want to pass it to my root vue instance not the component.

So for example I have the Dashboard Controller which has a data of "users"

```<code>class DashboardController extends Controller {

    public function index(){

       $user = User::find(1);

       return view('index', compact('user'));

    }

}
</code>```

I am using Larave mix on my project setup. So my main js file is the app.js. That "$user" data I need to pass on the root Vue instance. Which is located in app.js

```<code>const app = new Vue({
    el: '#dashboard',

    data: {
        // I want all the data from my controller in here.
    },

});
</code>```

答:
I just solved this by placing a reference on the window Object in the  of my layout file, and then picking that reference up with a mixin that can be injected into any component.

TLDR SOLUTION

.env

```<code>GEODATA_URL="https://geo.some-domain.com"
</code>```

config/geodata.php

```<code><?php

return [
    'url' => env('GEODATA_URL')
];
</code>```

resources/views/layouts/root.blade.php

```<code><head>
    <script>
        window.geodataUrl = "{{ config('geodata.url') }}";
    </script>
</head>
</code>```

resources/js/components/mixins/geodataUrl.js

```<code>const geodataUrl = {
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
};

export default geodataUrl;
</code>```

usage

```<code><template>
    <div>
        <a :href="geodataUrl">YOLO</a>
    </div>
</template>

<script>
import geodataUrl from '../mixins/geodataUrl';

export default {
    name: 'v-foo',

    mixins: [geodataUrl],

    data() {
        return {};
    },

    computed: {},

    methods: {},
};
</script>
</code>```

END TLDR SOLUTION

If you want, you can use a global mixin instead by adding this to your app.js entrypoint:

```<code>Vue.mixin({
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
});
</code>```

I would not recommend using this pattern, however, for any sensitive data because it is sitting on the window Object.

I like this solution because it doesn't use any extra libraries, and the chain of code is very clear. It passes the grep test, in that you can search your code for "window.geodataUrl" and see everything you need to understand how and why the code is working.

That consideration is important if the code may live for a long time and another developer may come across it.

However, JavaScript::put([]) is in my opinion, a decent utility that can be worth having, but in the past I have disliked how it can be extremely difficult to debug if a problem happens, because you cannot see where in the codebase the data comes from.

Imagine you have some Vue code that is consuming window.chartData that came from JavaScript::put([ 'chartData' => $user->chartStuff ]). Depending on the number of references to chartData in your code base, it could take you a very long time to discover which PHP file was responsible for making window.chartData work, especially if you didn't write that code and the next person has no idea JavaScript::put() is being used.

In that case, I recommend putting a comment in the code like:

```<code>/* data comes from poop.php via JavaScript::put */
</code>```

Then the person can search the code for "JavaScript::put" and quickly find it. Keep in mind "the person" could be yourself in 6 months after you forget the implementation details.

It is always a good idea to use Vue component prop declarations like this:

```<code>props: {
    chartData: {
        type: Array,
        required: true,
    },
},
</code>```

My point is, if you use JavaScript::put(), then Vue cannot detect as easily if the component fails to receive the data. Vue must assume the data is there on the window Object at the moment in time it refers to it. Your best bet may be to instead create a GET endpoint and make a fetch call in your created/mounted lifecycle method.

I think it is important to have an explicit contract between Laravel and Vue when it comes to getting/setting data.

In the interest of helping you as much as possible by giving you options, here is an example of making a fetch call using ES6 syntax sugar:

routes/web.php

```<code>Route::get('/charts/{user}/coolchart', 'UserController@getChart')->name('user.chart');
</code>```

app/Http/Controllers/UserController.php

```<code>public function getChart(Request $request, User $user)
{
    // do stuff
    $data = $user->chart;

    return response()->json([
        'chartData' => $data,
    ]);
}
</code>```

Anywhere in Vue, especially a created lifecycle method:

```<code><?php

return [
    'url' => env('GEODATA_URL')
];
</code>```0

That example assumes your Vue component is a Mealy finite state machine, whereby the component can only be in one state at any given time, but it can freely switch between states.

I'd recommend using such states as computed props:

```<code><?php

return [
    'url' => env('GEODATA_URL')
];
</code>```1

With markup such as:

```<code><?php

return [
    'url' => env('GEODATA_URL')
];
</code>```2

Body:
So I am using Laravel 5.5. I have a data coming from my Controller and I want to pass it to my root vue instance not the component.

So for example I have the Dashboard Controller which has a data of "users"

class DashboardController extends Controller {

    public function index(){

       $user = User::find(1);

       return view('index', compact('user'));

    }

}

I am using Larave mix on my project setup. So my main js file is the app.js. That "$user" data I need to pass on the root Vue instance. Which is located in app.js

const app = new Vue({
    el: '#dashboard',

    data: {
        // I want all the data from my controller in here.
    },

});

Body:
I just solved this by placing a reference on the window Object in the <head> of my layout file, and then picking that reference up with a mixin that can be injected into any component.

TLDR SOLUTION

.env

GEODATA_URL="https://geo.some-domain.com"

config/geodata.php

<?php

return [
    'url' => env('GEODATA_URL')
];

resources/views/layouts/root.blade.php

<head>
    <script>
        window.geodataUrl = "{{ config('geodata.url') }}";
    </script>
</head>

resources/js/components/mixins/geodataUrl.js

const geodataUrl = {
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
};

export default geodataUrl;

usage

<template>
    <div>
        <a :href="geodataUrl">YOLO</a>
    </div>
</template>

<script>
import geodataUrl from '../mixins/geodataUrl';

export default {
    name: 'v-foo',

    mixins: [geodataUrl],

    data() {
        return {};
    },

    computed: {},

    methods: {},
};
</script>

END TLDR SOLUTION

If you want, you can use a global mixin instead by adding this to your app.js entrypoint:

Vue.mixin({
    data() {
        return {
            geodataUrl: window.geodataUrl,
        };
    },
});

I would not recommend using this pattern, however, for any sensitive data because it is sitting on the window Object.

I like this solution because it doesn't use any extra libraries, and the chain of code is very clear. It passes the grep test, in that you can search your code for "window.geodataUrl" and see everything you need to understand how and why the code is working.

That consideration is important if the code may live for a long time and another developer may come across it.

However, JavaScript::put([]) is in my opinion, a decent utility that can be worth having, but in the past I have disliked how it can be extremely difficult to debug if a problem happens, because you cannot see where in the codebase the data comes from.

Imagine you have some Vue code that is consuming window.chartData that came from JavaScript::put([ 'chartData' => $user->chartStuff ]). Depending on the number of references to chartData in your code base, it could take you a very long time to discover which PHP file was responsible for making window.chartData work, especially if you didn't write that code and the next person has no idea JavaScript::put() is being used.

In that case, I recommend putting a comment in the code like:

/* data comes from poop.php via JavaScript::put */

Then the person can search the code for "JavaScript::put" and quickly find it. Keep in mind "the person" could be yourself in 6 months after you forget the implementation details.

It is always a good idea to use Vue component prop declarations like this:

props: {
    chartData: {
        type: Array,
        required: true,
    },
},

My point is, if you use JavaScript::put(), then Vue cannot detect as easily if the component fails to receive the data. Vue must assume the data is there on the window Object at the moment in time it refers to it. Your best bet may be to instead create a GET endpoint and make a fetch call in your created/mounted lifecycle method.

I think it is important to have an explicit contract between Laravel and Vue when it comes to getting/setting data.

In the interest of helping you as much as possible by giving you options, here is an example of making a fetch call using ES6 syntax sugar:

routes/web.php

Route::get('/charts/{user}/coolchart', 'UserController@getChart')->name('user.chart');

app/Http/Controllers/UserController.php

public function getChart(Request $request, User $user)
{
    // do stuff
    $data = $user->chart;

    return response()->json([
        'chartData' => $data,
    ]);
}

Anywhere in Vue, especially a created lifecycle method:

created() {
    this.handleGetChart();
},

methods: {
    async handleGetChart() {
        try {
            this.state = LOADING;
            const { data } = await axios.get(`/charts/${this.user.id}/coolchart`);

            if (typeof data !== 'object') {
                throw new Error(`Unexpected server response. Expected object, got: ${data}`);
            }

            this.chartData = data.chartData;
            this.state = DATA_LOADED;
        } catch (err) {
            this.state = DATA_FAILED;
            throw new Error(`Problem getting chart data: ${err}`);
        }
    },
},

That example assumes your Vue component is a Mealy finite state machine, whereby the component can only be in one state at any given time, but it can freely switch between states.

I'd recommend using such states as computed props:

computed: {
    isLoading() { return (this.state === LOADING); },
    isDataLoaded() { return (this.state === DATA_LOADED); },
    isDataFailed() { return (this.state === DATA_FAILED); },
},

With markup such as:

<div v-show="isLoading">Loading...</div>
<v-baller-chart v-if="isDataLoaded" :data="chartData"></v-baller-chart>
<button v-show="isDataFailed" type="button" @click="handleGetChart">TRY AGAIN</button>


问:
How to extract numbers from a string and add to an array?
I want to convert this string:

```<code><5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>
</code>```

to an array with key value

I would really appreciate the help

I tried different xmlParse strategies but it is not exactly an xml.

```<code>$xml = new \SimpleXMLElement("<5>20825.24</5><7>0.0</ 7><8>0.0</8>");
</code>```

Response: String could not be parsed as XML

I expect an array like this:

```<code>[5=>20825.24,7=>0.0,8=>0.0]
</code>```

答:
If you want to match the digits in the opening tag with the digits in the closing tag, you could use a regex make use of a backreference to the first capturing group:

```<code><(\d+)>\h*\d+(?:\.\d+)?\h*</\h*\1>
</code>```

Explanation

< Match > char

(\d+)> Capture in group 1 matching 1+ digits and match >

\h* Match 0+ horizontal whitespace chars

\d+(?:\.\d+)? Match 1+ digits followed by an optional part to match a dot and 1+ digits

\h* Match 0+ horizontal whitespace chars

< Match <

/\h* Match \ followed by 0+ horizontal whitespace chars

\1> Match backreference to group 1 using \1 and match >

Regex demo | Php demo

For example:

```<code>$re = '~<(\d+)>\h*(\d+(?:\.\d+)?)\h*</\h*\1>~m';
$str = '<5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>';
preg_match_all($re, $str, $matches);
print_r(array_combine($matches[1], $matches[2]));
</code>```

Result

```<code>Array
(
    [5] => 20825.24
    [7] => 0.0
    [8] => 0.0
)
</code>```

Note that now the array keys are 5, 7 and 8. Keep in mind that if you might use different data, that arrays can not have duplicate keys.

Body:
I want to convert this string:

<5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>

to an array with key value

I would really appreciate the help

I tried different xmlParse strategies but it is not exactly an xml.

$xml = new \SimpleXMLElement("<5>20825.24</5><7>0.0</ 7><8>0.0</8>");

Response: String could not be parsed as XML

I expect an array like this:

[5=>20825.24,7=>0.0,8=>0.0]

Body:
If you want to match the digits in the opening tag with the digits in the closing tag, you could use a regex make use of a backreference to the first capturing group:

<(\d+)>\h*\d+(?:\.\d+)?\h*</\h*\1>

Explanation

< Match > char

(\d+)> Capture in group 1 matching 1+ digits and match >

\h* Match 0+ horizontal whitespace chars

\d+(?:\.\d+)? Match 1+ digits followed by an optional part to match a dot and 1+ digits

\h* Match 0+ horizontal whitespace chars

< Match <

/\h* Match \ followed by 0+ horizontal whitespace chars

\1> Match backreference to group 1 using \1 and match >

Regex demo | Php demo

For example:

$re = '~<(\d+)>\h*(\d+(?:\.\d+)?)\h*</\h*\1>~m';
$str = '<5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>';
preg_match_all($re, $str, $matches);
print_r(array_combine($matches[1], $matches[2]));

Result

Array
(
    [5] => 20825.24
    [7] => 0.0
    [8] => 0.0
)

Note that now the array keys are 5, 7 and 8. Keep in mind that if you might use different data, that arrays can not have duplicate keys.


问:
Firebase Database Rules - Get displayName
I added Firebase to my website and created a signup form.
When the user clicks the "signup" button it creates a user using "Firebase Authentication", then it updates the user's displayName, and finally adds some data about the user to the database:

```<code>firebase.auth().createUserWithEmailAndPassword(email, password).then(function () {

    profile = firebase.auth().currentUser;

    profile.updateProfile({
       displayName: "name-value"
    }).then(function() {

        // Update successful.

        firebase.database().ref("/users/" + profile.uid).set({
            data:{
                country: "country-value",
                city: "city-value"
            }
        });
    });
}).catch(function(error) {
    // Handle Errors here.
});
</code>```

Everything worked fine until I changed the database rules from:

```<code>{
    "rules": {
        ".read": true,
        ".write": true
        }
    }
}
</code>```

To:

```<code>{
    "rules": {
        "users": {
            ".read": true,
            "$user": {
                ".write": "auth.token.name !== null"
            }
        }
    }
}
</code>```

I used auth.token.name as it is written in the guide to check whether or not the user's displayName exists (I planned to make it check some more things about it later).
Somehow "firebase rules" 'thinks' that auth.token.name equals null, even though I set the displayName before. Why is it happening and what can I do to make it work?

Thanks in advance :)

答:
I had the same problem and figured out a better solution. Firebase has a feature called custom claims that is meant for the use case we have. You want to set some id on a Firebase Anonymous Auth User that is accessible from database security rules.

The high-level of the solution is to make a Cloud Function that uses the admin api to set a custom claim. You can't set custom claims from the client side.

Next, call the cloud function to update the custom claim then use Auth.auth().currentUser?.getIDTokenResult(forcingRefresh: true,... in order to retrieve the updated token which includes the custom claim. This step is critical because you need your custom claim to be sent as part of every request moving forward.

If anyone actually reads this I can type up a more detailed implementation example.

Body:
I added Firebase to my website and created a signup form.
When the user clicks the "signup" button it creates a user using "Firebase Authentication", then it updates the user's displayName, and finally adds some data about the user to the database:

firebase.auth().createUserWithEmailAndPassword(email, password).then(function () {

    profile = firebase.auth().currentUser;

    profile.updateProfile({
       displayName: "name-value"
    }).then(function() {

        // Update successful.

        firebase.database().ref("/users/" + profile.uid).set({
            data:{
                country: "country-value",
                city: "city-value"
            }
        });
    });
}).catch(function(error) {
    // Handle Errors here.
});

Everything worked fine until I changed the database rules from:

{
    "rules": {
        ".read": true,
        ".write": true
        }
    }
}

To:

{
    "rules": {
        "users": {
            ".read": true,
            "$user": {
                ".write": "auth.token.name !== null"
            }
        }
    }
}

I used auth.token.name as it is written in the guide to check whether or not the user's displayName exists (I planned to make it check some more things about it later).
Somehow "firebase rules" 'thinks' that auth.token.name equals null, even though I set the displayName before. Why is it happening and what can I do to make it work?

Thanks in advance :)


问:
Is it possible to call confirmation dialog from controller in codeigniterr?
I am using codeigniter of version 3. When I submit that form, i have to save the data of that form and a confirmation dialog with yes no option has to appear. If user clicks yes i have to redirect to a page and if use clicks to no i have to redirect to another page .How can i do that?
My View code:

```<code><form id="saveRenewFirm" action="<?php echo base_url() ?>firm/saveFirmInfo"  method="post" role="form">

                <div class="row">
                    <div class="col-25">
                    <label> Name of the firm:</label>
                    </div>
                     <div class="col-75">
                                <input type="text" id="firm_name" name="firm_name" value="<?php echo $firmDetail->firm_name; ?>"  <?php echo $status;?> style="width:50%;" />
                    </div>
                </div></p>
                    <div class="row">
                    <div class="col-25">

                        <label>Category :</label>
                        </div>
                    <div class="col-75">
                            <input type="text" name="category" id="category"  value="<?php echo $firmDetail->category; ?>" <?php echo $status;?> />
                        </div>
                </div>
                    <div class="row">
                    <div class="col-25">
                        <label>Phone no :</label>
                        </div>
                    <div class="col-75">
                            <input type="text" name="phone_no" id="phone_no"  value="<?php echo $firmDetail->phone; ?>" <?php echo $status;?> />
                    </div>
                    </div>

                <div class="row">
                    <div class="col-25">

                        <label>Address :</label></div><div class="col-75"><input type="text" name="address" style="width:400px;" id="address" value="<?php echo $firmDetail->address; ?>" <?php echo $status;?> />
                    </div>
                </div>
            <button  value="submit" name="action" type="submit"    class="button" >Submit</button>
                    <?php echo form_hidden('renew_id',$firmDetail->renew_id);?>
                </form>
</code>```

My controller:

```<code>   public function saveFirmInfo() {
    $this->setValidation();
    if($this->form_validation->run() == FALSE){

            $this->index();

    } else {
            $data = array(
                'firm_name' => $this->input->post('firm_name'),
                'category' => $this->input->post(category),
                'phone_no' => $this->input->post('phone_no'),
                'address' => $this->input->post('address'));

        $new_id = $this->renewed_firm_model->insert($data);

        if($new_id>0){
                $this->session->set_flashdata('success', 'Firm Detail submitted. Do you want to continue to payment?');
        }else {
                $this->session->set_flashdata('error', 'Error during processing, please try again...');

         }
         redirect('member/profile','refresh');
}
</code>```

I want to bring a confirmation dialog instead of flash message to continue for payment . If user clicks yes then i have to redirect to payment page and if user clicks no another page has to be opened.

答:
You can either do this 2 ways.

The first way, and the easiest given your current code would be to redirect to a page after the user submits the form that has a question and 2 options (yes or no).

The second way would be to submit the form via ajax and launch a modal on success function. This would be more intensive, and require substantial changes to your current save function.

Body:
I am using codeigniter of version 3. When I submit that form, i have to save the data of that form and a confirmation dialog with yes no option has to appear. If user clicks yes i have to redirect to a page and if use clicks to no i have to redirect to another page .How can i do that?
My View code:

<form id="saveRenewFirm" action="<?php echo base_url() ?>firm/saveFirmInfo"  method="post" role="form">

                     Name of the firm:

                                <input type="text" id="firm_name" name="firm_name" value="<?php echo $firmDetail->firm_name; ?>"  <?php echo $status;?> style="width:50%;" />

                        Category :

                            <input type="text" name="category" id="category"  value="<?php echo $firmDetail->category; ?>" <?php echo $status;?> />

                        Phone no :

                            <input type="text" name="phone_no" id="phone_no"  value="<?php echo $firmDetail->phone; ?>" <?php echo $status;?> />

                        Address :

<input type="text" name="address" style="width:400px;" id="address" value="<?php echo $firmDetail->address; ?>" <?php echo $status;?> />

            <button  value="submit" name="action" type="submit"    class="button" >Submit</button>
                    <?php echo form_hidden('renew_id',$firmDetail->renew_id);?>
                </form>

My controller:

   public function saveFirmInfo() {
    $this->setValidation();
    if($this->form_validation->run() == FALSE){

            $this->index();

    } else {
            $data = array(
                'firm_name' => $this->input->post('firm_name'),
                'category' => $this->input->post(category),
                'phone_no' => $this->input->post('phone_no'),
                'address' => $this->input->post('address'));

        $new_id = $this->renewed_firm_model->insert($data);

        if($new_id>0){
                $this->session->set_flashdata('success', 'Firm Detail submitted. Do you want to continue to payment?');
        }else {
                $this->session->set_flashdata('error', 'Error during processing, please try again...');

         }
         redirect('member/profile','refresh');
}

I want to bring a confirmation dialog instead of flash message to continue for payment . If user clicks yes then i have to redirect to payment page and if user clicks no another page has to be opened.


问:
How to build Lite app such as Twitter Lite or Facebook Lite
l'm currently working on a application for the Android os and it's using some features so that it can only work on android 5.0+. Ans it's also huge(31.23 MB currently). I read a post from Facebook Lite developpers who where explaining the advantage of using Lite app version and how they've built their own. I want to do the same for my app. But I don't know how to create the UI rendering engine as they've explained, the app must download on a 2G network using LTS protocol the app user interface represented like a DOM object. So, the problem is how to build the user interface from the DOM? From their post, we can understand that using a WebView isn't a good approach. Help me please. Most of our customers use 2G. Any help will ne appreciated.</p>

答:
your question is not as clear as it could be. But as I can understand, you need to know how to make an Android app that can parse XML data using DOM Parser isn't it ?
So, as I don't know what exactly your app is based of, I'm going to give a simple example of code. Maybe this can help you to adapt it with the logic of your project.

Suppose that you want to parse Users Data with DOM Parser in Android Studio, so you need to make an app like the exemple below:

Create a new Project in Android Studio and rename it MyParserApp

Swich in the Project View and locate src/main folder, Right Click to create a new directory and name it assets like thhis.

Then, right click on the assets folder and create a new Andoid Ressource File give it the name myusers.xml like this:

You can now open the file myusers.xml and code it like this:

```<code><?xml version="1.0" encoding="utf-8"?>

<users>

<user>

<name>Félix Maroy</name>

<fonction>CEO</fonction>

<city>Bukavu</city>

</user>

<user>

<name>Mbuyi Beya</name>

<fonction>Developer</fonction>

<city>Kinshasa</city>

</user>

<user>

<name>John Doe</name>

<fonction>Accountant</fonction>

<city>New York</city>

</user>

</users>
</code>```

Create a Layout Ressource File in src/layout and name it users_list.xml, Open it and code like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="17dp" />
    <TextView
        android:id="@+id/fonction"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_marginTop="7dp"
        android:textColor="#343434"
        android:textSize="14dp" />
    <TextView
        android:id="@+id/city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/fonction"
        android:layout_alignBottom="@+id/fonction"
        android:layout_alignParentRight="true"
        android:textColor="#343434"
        android:textSize="14dp" />
</RelativeLayout>
</code>```

It'll looks like this:

Then Code your activity_main.xml in src/layout like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/user_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dp" />
</LinearLayout>
</code>```

It'll looks like this:

And the last step is to code your MainActivity.java like this:

```<code>package com.mercipro.myparserapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try{
            ArrayList<HashMap<String, String>> userList = new ArrayList<>();
            ListView lv = (ListView) findViewById(R.id.user_list);
            InputStream istream = getAssets().open("myusers.xml");
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(istream);
            NodeList nList = doc.getElementsByTagName("user");
            for(int i =0;i<nList.getLength();i++){
                if(nList.item(0).getNodeType() == Node.ELEMENT_NODE){
                    HashMap<String,String> user = new HashMap<>();
                    Element elm = (Element)nList.item(i);
                    user.put("name", getNodeValue("name",elm));
                    user.put("fonction", getNodeValue("fonction",elm));
                    user.put("city", getNodeValue("city",elm));
                    userList.add(user);
                }
            }
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.users_list,new String[]{"name","fonction","city"}, new int[]{R.id.name, R.id.fonction, R.id.city});
            lv.setAdapter(adapter);
        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }
    protected String getNodeValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag);
        Node node = nodeList.item(0);
        if(node!=null){
            if(node.hasChildNodes()){
                Node child = node.getFirstChild();
                while (child!=null){
                    if(child.getNodeType() == Node.TEXT_NODE){
                        return  child.getNodeValue();
                    }
                }
            }
        }
        return "";
    }
}

</code>```

Now Run your app, the result will looks like this

Hope this will give you an idea on How to Parse XML using DOM Parser in Android Studio so that you can build Lite applications as you read somewhere (I never code a Lite app).

Body:
your question is not as clear as it could be. But as I can understand, you need to know how to make an Android app that can parse XML data using DOM Parser isn't it ?
So, as I don't know what exactly your app is based of, I'm going to give a simple example of code. Maybe this can help you to adapt it with the logic of your project.

Suppose that you want to parse Users Data with DOM Parser in Android Studio, so you need to make an app like the exemple below:

Create a new Project in Android Studio and rename it MyParserApp

Swich in the Project View and locate src/main folder, Right Click to create a new directory and name it assets like thhis.

Then, right click on the assets folder and create a new Andoid Ressource File give it the name myusers.xml like this:

You can now open the file myusers.xml and code it like this:

<?xml version="1.0" encoding="utf-8"?>

<users>

<user>

<name>Félix Maroy</name>

<fonction>CEO</fonction>

<city>Bukavu</city>

</user>

<user>

<name>Mbuyi Beya</name>

<fonction>Developer</fonction>

<city>Kinshasa</city>

</user>

<user>

<name>John Doe</name>

<fonction>Accountant</fonction>

<city>New York</city>

</user>

</users>

Create a Layout Ressource File in src/layout and name it users_list.xml, Open it and code like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="17dp" />
    <TextView
        android:id="@+id/fonction"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_marginTop="7dp"
        android:textColor="#343434"
        android:textSize="14dp" />
    <TextView
        android:id="@+id/city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/fonction"
        android:layout_alignBottom="@+id/fonction"
        android:layout_alignParentRight="true"
        android:textColor="#343434"
        android:textSize="14dp" />
</RelativeLayout>

It'll looks like this:

Then Code your activity_main.xml in src/layout like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/user_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dp" />
</LinearLayout>

It'll looks like this:

And the last step is to code your MainActivity.java like this:

package com.mercipro.myparserapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try{
            ArrayList<HashMap<String, String>> userList = new ArrayList<>();
            ListView lv = (ListView) findViewById(R.id.user_list);
            InputStream istream = getAssets().open("myusers.xml");
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(istream);
            NodeList nList = doc.getElementsByTagName("user");
            for(int i =0;i<nList.getLength();i++){
                if(nList.item(0).getNodeType() == Node.ELEMENT_NODE){
                    HashMap<String,String> user = new HashMap<>();
                    Element elm = (Element)nList.item(i);
                    user.put("name", getNodeValue("name",elm));
                    user.put("fonction", getNodeValue("fonction",elm));
                    user.put("city", getNodeValue("city",elm));
                    userList.add(user);
                }
            }
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.users_list,new String[]{"name","fonction","city"}, new int[]{R.id.name, R.id.fonction, R.id.city});
            lv.setAdapter(adapter);
        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }
    protected String getNodeValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag);
        Node node = nodeList.item(0);
        if(node!=null){
            if(node.hasChildNodes()){
                Node child = node.getFirstChild();
                while (child!=null){
                    if(child.getNodeType() == Node.TEXT_NODE){
                        return  child.getNodeValue();
                    }
                }
            }
        }
        return "";
    }
}

Now Run your app, the result will looks like this

Hope this will give you an idea on How to Parse XML using DOM Parser in Android Studio so that you can build Lite applications as you read somewhere (I never code a Lite app).


问:
HTTPClient Post Request with Headers and Body
I want to set the Content-Type and Authorization Headers using HttpClient and want to load the xml file for the body(request) and send Post request.

I have searched for combining both headers and body for Post request.

Setting up the Headers using HttpRequestMessage.

```<code>   HttpClient clientTest = new HttpClient();

   HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post,url);

   httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/vnd.citrix.sessionparams+xml");
   httpRequest.Headers.Authorization = new AuthenticationHeaderValue("CitrixAuth", "H4sIAAAAAAAEAK1X2Y6jyBL9lZLnEbnZt1J");
</code>```

Setting the xml body -

```<code>XDocument xml = XDocument.Load("RequestSession.xml");
</code>```

Converting to Document.ToString()

```<code>var httpContent = new StringContent(xml.Document.ToString(), Encoding.UTF8, "application/vnd.citrix.sessionstate+xml");
</code>```

Please help me with combining both headers and body for Post Request using HttpClient.

答:
I do not know if this is a valid request for the service you are calling, but to set headers and body and send a request it would look like this:

```<code>HttpClient clientTest = new HttpClient();

HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post,url);

httpRequest.Content = new StringContent(xml.Document.ToString(), Encoding.UTF8, "application/vnd.citrix.sessionstate+xml");
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("CitrixAuth", "H4sIAAAAAAAEAK1X2Y6jyBL9lZLnEbnZt1J");

var response = await clientTest.SendAsync(httpRequest);
</code>```

If you get a 400 Bad Request it because what you are sending is not appropriate for the API, not because of how you are sending it.

Body:
I want to set the Content-Type and Authorization Headers using HttpClient and want to load the xml file for the body(request) and send Post request.

I have searched for combining both headers and body for Post request.

Setting up the Headers using HttpRequestMessage.

   HttpClient clientTest = new HttpClient();

   HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post,url);

   httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/vnd.citrix.sessionparams+xml");
   httpRequest.Headers.Authorization = new AuthenticationHeaderValue("CitrixAuth", "H4sIAAAAAAAEAK1X2Y6jyBL9lZLnEbnZt1J");

Setting the xml body -

XDocument xml = XDocument.Load("RequestSession.xml");

Converting to Document.ToString()

var httpContent = new StringContent(xml.Document.ToString(), Encoding.UTF8, "application/vnd.citrix.sessionstate+xml");

Please help me with combining both headers and body for Post Request using HttpClient.

Body:
I do not know if this is a valid request for the service you are calling, but to set headers and body and send a request it would look like this:

HttpClient clientTest = new HttpClient();

HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post,url);

httpRequest.Content = new StringContent(xml.Document.ToString(), Encoding.UTF8, "application/vnd.citrix.sessionstate+xml");
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("CitrixAuth", "H4sIAAAAAAAEAK1X2Y6jyBL9lZLnEbnZt1J");

var response = await clientTest.SendAsync(httpRequest);

If you get a 400 Bad Request it because what you are sending is not appropriate for the API, not because of how you are sending it.


问:
how do I add template conditions in the ListView class?
I have a ListView class in views.py, I want to add a condition if the authenticated user displays another template

urls.py

```<code>from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import (
    PostListView,
)

urlpatterns = [
    path('', PostListView.as_view(), name='index'),
]
</code>```

Views.py

```<code>from django.shortcuts import render, get_object_or_404
from django.views.generic import (
    ListView,
)
from .models import Post
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

class PostListView(ListView):
    model = Post
    template_name = 'page/index.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 7

</code>```

i want to add

```<code>        if self.request.user.is_authenticated:
            template_name = 'page/index.html'
        else:
            template_name = 'page/home.html'
</code>```

Django 2.2.x

答:
You can override the get_template_names function [Django-doc]:

```<code>class PostListView(ListView):
    model = Post
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 7

    def <b>get_template_names</b>(self):
        if self.request.user.is_authenticated:
            return ['page/index.html']
        else:
            return ['page/home.html']</code>```

As the documentation says, this function:

Returns a list of template names to search for when rendering the template. The first template that is found will be used.

If template_name is specified, the default implementation will return a list containing template_name (if it is specified).

That being said, if you do not plan to render the list on your home.html page, it might be better to perform a redirect to another page, instead of just rendering a page. Otherwise, if you later want to add more content to your home.html page, you will each time need to update all the views that render this.

The basic implementation [GitHub] in the TemplateResponseMixin [Django-doc] is thus:

```<code>def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response() is overridden.
    """
    if self.template_name is None:
        raise ImproperlyConfigured(
            "TemplateResponseMixin requires either a definition of "
            "'template_name' or an implementation of 'get_template_names()'")
    else:
        return [self.template_name]</code>```

Body:
I have a ListView class in views.py, I want to add a condition if the authenticated user displays another template

urls.py

from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import (
    PostListView,
)

urlpatterns = [
    path('', PostListView.as_view(), name='index'),
]

Views.py

from django.shortcuts import render, get_object_or_404
from django.views.generic import (
    ListView,
)
from .models import Post
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

class PostListView(ListView):
    model = Post
    template_name = 'page/index.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 7

i want to add

        if self.request.user.is_authenticated:
            template_name = 'page/index.html'
        else:
            template_name = 'page/home.html'

Django 2.2.x

Body:
You can override the get_template_names function [Django-doc]:

class PostListView(ListView):
    model = Post
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 7

    def get_template_names(self):
        if self.request.user.is_authenticated:
            return ['page/index.html']
        else:
            return ['page/home.html']

As the documentation says, this function:

Returns a list of template names to search for when rendering the template. The first template that is found will be used.

If template_name is specified, the default implementation will return a list containing template_name (if it is specified).

That being said, if you do not plan to render the list on your home.html page, it might be better to perform a redirect to another page, instead of just rendering a page. Otherwise, if you later want to add more content to your home.html page, you will each time need to update all the views that render this.

The basic implementation [GitHub] in the TemplateResponseMixin [Django-doc] is thus:

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response() is overridden.
    """
    if self.template_name is None:
        raise ImproperlyConfigured(
            "TemplateResponseMixin requires either a definition of "
            "'template_name' or an implementation of 'get_template_names()'")
    else:
        return [self.template_name]


问:
How Recursion works in C
I am new to C and I'm reading about recursion, but I am totally confused.

The main part where I'm getting confused is how things get unwind when the exit condition is reached. I would like to know how during recursion values got pushed and popped from stack.

Also can anyone please give me a diagramatic  view of recursion?

Thanks...

答:
In C recursion is just like ordinary function calls.

When a function is called, the arguments, return address, and frame pointer (I forgot the order) are pushed on the stack.

In the called function, first the space for local variables is "pushed" on the stack.

if function returns something, put it in a certain register (depends on architecture, AFAIK)

undo step 2.

undo step 1.

So, with recursion steps 1 and 2 are performed a few times, then possibly 3 (maybe only once) and finally 4 and 5 are done (as many times as 1 and 2).

Title: How Recursion works in C