问:
Problem in communicating using Socket in C#
I'm hoping I haven't missed something stupid.  I am working on an application that communicates between a number of hand-held window's mobile computers and a central server.  The current architecture only allows short messages (up to 4096 bytes), I am modifying the application to allow larger communications when necessary.  This code seems to work intermittently, depending on the server's speed and the network communication speed.  I need to find a way make the server's receiving code more solid.  It occasionally works perfectly, other times the hand-held throws the error "Unable to write data to the transport connection.  An existing connection was forcible closed by the remote host."

Hand-held transmitting code:

```<code>public bool SendMessage(NetworkStream ansStream, string asMessage)
{
    try
    {
        Byte[] wBytes = System.Text.Encoding.ASCII.GetBytes(asMessage.ToCharArray());
        ansStream.Write(wBytes, 0, wBytes.Length);
        return true;
    }
    catch (Exception E)
    {
        MessageBox.Show(E.Message, "Network Error");
        return false;
    }
}
</code>```

Server side receiving code:

```<code>public const int BUFFER_LENGTH = 4096;
public void ProcessMessage(object aClient)
{
    TcpClient wClient = (aClient as TcpClient);
    try
    {
        byte[] wBytes = new byte[BUFFER_LENGTH];
        StringBuilder wMessage = new StringBuilder();
        using (NetworkStream wNetStream = wClient.GetStream())
        {
            try
            {
                int wiRead = 0;
                int wiTotalBytes = 0;
                do
                {
                    wiRead = wNetStream.Read(wBytes, 0, wBytes.Length);
                    wMessage.AppendFormat("{0}", Encoding.ASCII.GetString(wBytes, 0, wiRead));
                    wiTotalBytes += wiRead;

                    // my attempt to ensure entire message is read
                    if (wNetStream.DataAvailable)
                    {
                        Thread.Sleep(1000);
                    }

                } while (wNetStream.DataAvailable);

                if (wiTotalBytes > 0)
                {
                    string wsAnswerFile = "";
                    string wsResult = DoBusinessProcess(wMessage.ToString(), out wsAnswerFile);
                    if (string.IsNullOrEmpty(wsAnswerFile))
                    {
                        wBytes = Encoding.ASCII.GetBytes(wsResult);
                        wNetStream.Write(wBytes, 0, wBytes.Length);
                    }
                    else
                    {
                        if (File.Exists(wsAnswerFile))
                        {
                            SendFile(wsAnswerFile, wNetStream);
                        }
                    }
                }
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message, "Network Error");
            }
            finally
            {
                if (wNetStream != null)
                {
                    wNetStream.Close();
                }
            }
        }
    }
}
</code>```

答:
When you are calling ProcessMessage and passing it a TCPClient, how are you initializing those TCPCLient connections? If you are doing it in a loop without multithreading then you may get results like the ones you've explained. Of course I can't be sure without knowing how you have your client listening loop setup.

Check out this link: http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server
 The second code snippet shows a listener loop that will start a new thread for each client. If you don't start a new thread for each client, if a new one is trying to connect while you are receiving data from the other one, it will say the server can't respond.

I hope this helps!

Body:
I'm hoping I haven't missed something stupid.  I am working on an application that communicates between a number of hand-held window's mobile computers and a central server.  The current architecture only allows short messages (up to 4096 bytes), I am modifying the application to allow larger communications when necessary.  This code seems to work intermittently, depending on the server's speed and the network communication speed.  I need to find a way make the server's receiving code more solid.  It occasionally works perfectly, other times the hand-held throws the error "Unable to write data to the transport connection.  An existing connection was forcible closed by the remote host."

Hand-held transmitting code:

public bool SendMessage(NetworkStream ansStream, string asMessage)
{
    try
    {
        Byte[] wBytes = System.Text.Encoding.ASCII.GetBytes(asMessage.ToCharArray());
        ansStream.Write(wBytes, 0, wBytes.Length);
        return true;
    }
    catch (Exception E)
    {
        MessageBox.Show(E.Message, "Network Error");
        return false;
    }
}

Server side receiving code:

public const int BUFFER_LENGTH = 4096;
public void ProcessMessage(object aClient)
{
    TcpClient wClient = (aClient as TcpClient);
    try
    {
        byte[] wBytes = new byte[BUFFER_LENGTH];
        StringBuilder wMessage = new StringBuilder();
        using (NetworkStream wNetStream = wClient.GetStream())
        {
            try
            {
                int wiRead = 0;
                int wiTotalBytes = 0;
                do
                {
                    wiRead = wNetStream.Read(wBytes, 0, wBytes.Length);
                    wMessage.AppendFormat("{0}", Encoding.ASCII.GetString(wBytes, 0, wiRead));
                    wiTotalBytes += wiRead;

                    // my attempt to ensure entire message is read
                    if (wNetStream.DataAvailable)
                    {
                        Thread.Sleep(1000);
                    }

                } while (wNetStream.DataAvailable);

                if (wiTotalBytes > 0)
                {
                    string wsAnswerFile = "";
                    string wsResult = DoBusinessProcess(wMessage.ToString(), out wsAnswerFile);
                    if (string.IsNullOrEmpty(wsAnswerFile))
                    {
                        wBytes = Encoding.ASCII.GetBytes(wsResult);
                        wNetStream.Write(wBytes, 0, wBytes.Length);
                    }
                    else
                    {
                        if (File.Exists(wsAnswerFile))
                        {
                            SendFile(wsAnswerFile, wNetStream);
                        }
                    }
                }
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message, "Network Error");
            }
            finally
            {
                if (wNetStream != null)
                {
                    wNetStream.Close();
                }
            }
        }
    }
}


来源: stackexchange

问:
Synthesis verilog with Yosys
I want to synthesis a vhdl design for ASIC standard cell libraries to find the circuits area requirement.
How can i do it for for Virtual Silicon (VST) standard cell library UMCL18G212T3 or UMC L180 0.18µm using Yosys?
Does Yosys support vhdl code or do i need to write it in verilog?</p>

答:
Via the Yosys webpage. It looks like only Verilog.

About

Yosys is a framework for Verilog RTL synthesis. It currently has
  extensive Verilog-2005 support and provides a basic set of synthesis
  algorithms for various application domains. Selected features and
  typical applications:

Also from the same page...

Example Usage

Yosys is controlled using synthesis scripts. For example, the
  following Yosys synthesis script reads a design (with the top module
  mytop) from the verilog file mydesign.v, synthesizes it to a
  gate-level netlist using the cell library in the Liberty file
  mycells.lib and writes the synthesized results as Verilog netlist to
  synth.v:

```<code>> # read design  read_verilog mydesign.v
>
> # elaborate design hierarchy hierarchy -check -top mytop
>
> # the high-level stuff proc; opt; fsm; opt; memory; opt
>
> # mapping to internal cell library techmap; opt
>
> # mapping flip-flops to mycells.lib dfflibmap -liberty mycells.lib
>
> # mapping logic to mycells.lib abc -liberty mycells.lib
>
> # cleanup clean
>
> # write synthesized design write_verilog synth.v
</code>```

ContentLicense: CC BY-SA 4.0

Title: Synthesis verilog with Yosys

Body:
Via the Yosys webpage. It looks like only Verilog.

About

Yosys is a framework for Verilog RTL synthesis. It currently has
  extensive Verilog-2005 support and provides a basic set of synthesis
  algorithms for various application domains. Selected features and
  typical applications:

Also from the same page...

Example Usage

Yosys is controlled using synthesis scripts. For example, the
  following Yosys synthesis script reads a design (with the top module
  mytop) from the verilog file mydesign.v, synthesizes it to a
  gate-level netlist using the cell library in the Liberty file
  mycells.lib and writes the synthesized results as Verilog netlist to
  synth.v:

> # read design  read_verilog mydesign.v
>
> # elaborate design hierarchy hierarchy -check -top mytop
>
> # the high-level stuff proc; opt; fsm; opt; memory; opt
>
> # mapping to internal cell library techmap; opt
>
> # mapping flip-flops to mycells.lib dfflibmap -liberty mycells.lib
>
> # mapping logic to mycells.lib abc -liberty mycells.lib
>
> # cleanup clean
>
> # write synthesized design write_verilog synth.v


问:
How can I ignore a relationship on table using Spring CrudRepository
I have two tables, Table A have several columns with item id, table B associated to Table as a many to one relations by foreign key A's item id, now I am using Spring CrudRepository trying to find all data in table A, I need all columns and all row but I dont want anything from table B because at this moment they are useless for me, is there any way that I can configure to let its ignore relationship when I use findall in CrudRepository to let it just return Pure Table A data?

I have a controller

```<code>@GetMapping
  public ResponseEntity<List<A>> findAll()
  {
     final List<A> aList = AService.findAll();

    final List<AResource> aResourceList = new ArrayList<>();

    for (final A a: aList)
    {
      aResourceList.add(new aResource(a));
    }
    return new ResponseEntity<>(aResourceList, HttpStatus.OK);
  }
</code>```

service

```<code>public List<A> findAll()
  {
    final List<A> aList = new ArrayList<>();

    aRepository.findAll().forEach(a -> aList.add(a));

    return aList;
  }
</code>```

then repository

```<code>public interface aRepository extends CrudRepository<A, long>
{
}
</code>```

so now if I ran this, it will grab A from table A and a list of B associated to each one of them, I would like to know is there an easy way to do this without writing my own query?

thanks

答:
<pre class="lang-java prettyprint-override"><code> @ManyToOne(fetch = FetchType.LAZY)
</code>```

Body:
I have two tables, Table A have several columns with item id, table B associated to Table as a many to one relations by foreign key A's item id, now I am using Spring CrudRepository trying to find all data in table A, I need all columns and all row but I dont want anything from table B because at this moment they are useless for me, is there any way that I can configure to let its ignore relationship when I use findall in CrudRepository to let it just return Pure Table A data?

I have a controller

@GetMapping
  public ResponseEntity<List> findAll()
  {
     final List aList = AService.findAll();

    final List<AResource> aResourceList = new ArrayList<>();

    for (final A a: aList)
    {
      aResourceList.add(new aResource(a));
    }
    return new ResponseEntity<>(aResourceList, HttpStatus.OK);
  }

service

public List findAll()
  {
    final List aList = new ArrayList<>();

    aRepository.findAll().forEach(a -> aList.add(a));

    return aList;
  }

then repository

public interface aRepository extends CrudRepository
{
}

so now if I ran this, it will grab A from table A and a list of B associated to each one of them, I would like to know is there an easy way to do this without writing my own query?

thanks

Body: @ManyToOne(fetch = FetchType.LAZY)


问:
get all results from couchbase full text search rest API with no limit
I want to get all the results from a full text search index in couchbase. However, the default limit is 10 results.

I am aware that I can customize the size to a specific number, but is it possible to set it such that I get all the results in one go?
Something like "size":"*" or "size":"all"

```<code>curl -u user:password -X POST -H "Content-Type: application/json" \
-d '{"query": {"query": "search_token"}, "size": 10}' \
http://1.2.3.4:8094/api/index/myindex/query
</code>```

答:
It doesn't look like there's an "all" option for size. Omitting size falls back to 10.

I tried using a really large number, and got an error message:

```<code>{
    "error": "rest_index: Query, indexName: ix_myindex, err: bleve: bleveMaxResultWindow exceeded, from: 0, size: 999999999, bleveMaxResultWindow: 10000",
    "request": {
        "query": {
            "query": "search_token"
        },
        "size": 999999999
    },
    "status": "fail"
}
</code>```

So, 10000 is the max you can ask for by default.

According to Couchbase ticket MB-17539, you can increase the maximum:

```<code>curl -XPUT -H "Content-type:application/json" http://<username>:<password>@<ip>:8094/api/managerOptions -d '{"bleveMaxResultWindow": "100000"}'
</code>```

I tried this, and it works. However, I don't see this endpoint in the documentation so it might change/become deprecated in the future.

But, I really have to wonder why you need this many results at once? Is paging not an option for you? (e.g. a body of {"query": {"query": "search_token"}, "size": 10, "from": 10}).

Body:
I want to get all the results from a full text search index in couchbase. However, the default limit is 10 results.

I am aware that I can customize the size to a specific number, but is it possible to set it such that I get all the results in one go?
Something like "size":"*" or "size":"all"

curl -u user:password -X POST -H "Content-Type: application/json" \
-d '{"query": {"query": "search_token"}, "size": 10}' \
http://1.2.3.4:8094/api/index/myindex/query

Body:
It doesn't look like there's an "all" option for size. Omitting size falls back to 10.

I tried using a really large number, and got an error message:

{
    "error": "rest_index: Query, indexName: ix_myindex, err: bleve: bleveMaxResultWindow exceeded, from: 0, size: 999999999, bleveMaxResultWindow: 10000",
    "request": {
        "query": {
            "query": "search_token"
        },
        "size": 999999999
    },
    "status": "fail"
}

So, 10000 is the max you can ask for by default.

According to Couchbase ticket MB-17539, you can increase the maximum:

curl -XPUT -H "Content-type:application/json" http://<username>:<password>@<ip>:8094/api/managerOptions -d '{"bleveMaxResultWindow": "100000"}'

I tried this, and it works. However, I don't see this endpoint in the documentation so it might change/become deprecated in the future.

But, I really have to wonder why you need this many results at once? Is paging not an option for you? (e.g. a body of {"query": {"query": "search_token"}, "size": 10, "from": 10}).


问:
How can I set data-content on hr:after in javascript?
I know you can add style to an element in javascript. E.g.

```<code>myElement.style.color = "red";
</code>```

But say I wanted to do the equivalent of

```<code>hr:after {
  content: "myRuntimeValue"
}
</code>```

How can I achieve that in javascript?

答:
You can do this indirectly via element attribute:

CSS

```<code>p#my-id::after {
    // set content to be the value of an attribute on the element p
    content: attr(data-value);
}
</code>```

JS

```<code>const element = document.getElementById('my-id');
element.setAttribute('data-value', 'myRuntimeValue');
</code>```

Body:
I know you can add style to an element in javascript. E.g.

myElement.style.color = "red";

But say I wanted to do the equivalent of

hr:after {
  content: "myRuntimeValue"
}

How can I achieve that in javascript?

Body:
You can do this indirectly via element attribute:

CSS

p#my-id::after {
    // set content to be the value of an attribute on the element p
    content: attr(data-value);
}

JS

const element = document.getElementById('my-id');
element.setAttribute('data-value', 'myRuntimeValue');


问:
Undefined express session in another route
I have login route in which I set a session for user username. When I post it through postman I get json result "thomas" and when I try to console.log it in route: user-data it says undefined. Can someone help me with this?

```<code>app.use(session({ secret: "thepolyglotdeveloper", cookie: { secure: true, maxAge: 60000 }, saveUninitialized: true, resave: true }));

app.post('/login', (req, res) => {
        req.session.username = 'thomas';
        res.json(req.session.username)
});

app.get('/user-data', (req, res) => {
    console.log(req.session.username) // Undefined
})
</code>```

答:
This is probably failing because postman doesn't save cookies between requests, so the cookie being "set" by postman isn't provided when you make the request to /user-data.

If you look at the response of the login POST in postman and provide it as a cookie in the GET request in postman, it should succeed.

Body:
I have login route in which I set a session for user username. When I post it through postman I get json result "thomas" and when I try to console.log it in route: user-data it says undefined. Can someone help me with this?

app.use(session({ secret: "thepolyglotdeveloper", cookie: { secure: true, maxAge: 60000 }, saveUninitialized: true, resave: true }));

app.post('/login', (req, res) => {
        req.session.username = 'thomas';
        res.json(req.session.username)
});

app.get('/user-data', (req, res) => {
    console.log(req.session.username) // Undefined
})


问:
Are morph targets in three.js gpu powered?
I have thousands of these shapes:

```<code>var someShape = new THREE.Shape( somePts );
var extrudedGeometry = new THREE.ExtrudeGeometry(someShape, {depth: 1, bevelEnabled: false});
var extrudedMesh = new THREE.Mesh(extrudedGeometry, new THREE.MeshPhongMaterial({color: getRandomColor(), transparent: true}));
</code>```

Each one of these shapes will morph into a different shape with the same amount of vertices. I was thinking of using morph targets, do they run on the gpu?

Is a morph target in three.js implemented behind the scenes as a vertex shader or if I'm trying to do this for thousands of objects should I create my own vertex shader?

答:
I was thinking of using morph targets, do they run on the gpu?

Yes, morph target animation is a form of vertex displacement which is implemented in the vertex shader. Most built-in materials like MeshPhongMaterial support it by including the respective shader chunks. As a user, you just have to set .morphTargets to true in order to notify the renderer that a specific material should use morph targets.

three.js R104

Body:
I have thousands of these shapes:

var someShape = new THREE.Shape( somePts );
var extrudedGeometry = new THREE.ExtrudeGeometry(someShape, {depth: 1, bevelEnabled: false});
var extrudedMesh = new THREE.Mesh(extrudedGeometry, new THREE.MeshPhongMaterial({color: getRandomColor(), transparent: true}));

Each one of these shapes will morph into a different shape with the same amount of vertices. I was thinking of using morph targets, do they run on the gpu?

Is a morph target in three.js implemented behind the scenes as a vertex shader or if I'm trying to do this for thousands of objects should I create my own vertex shader?


问:
how to handle xml data in javascript
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

```<code>$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })
</code>```

the returned xml data looks like:

```<code><DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...
</code>```

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

```<code>success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}
</code>```

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

答:
You are misusing the dataType parameter. It's not expected to be a MIME type. Instead, it should one of these: "xml", "html", "script", "json", "jsonp" or "text". In your case, "xml" (or omit it completely and jQuery will guess it for you):

http://api.jquery.com/jQuery.ajax/ (scroll down to "dataTypeString").

Update:

So far, it looks that your problem is that your server side script is crashing and you don't even have valid XML. Whatever, I've put together a small example in case it helps:

```<code>$.ajax({
    url: "/test.xml",
    type: "GET",
    async: false,
    dataType: "xml",
    data: {id: 43},
    success: function(data) {
        var output = "Usernames:\n";
        $(data).find("USERNAME").each(function(){
            output += "\n- " + $(this).text();
        });
        alert(output);
    },
    error: function(xhr, status, error){
        alert("error happens");
    }
})
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to handle xml data in javascript

Body:
I am newbie in javascript xml data handling. Currently, my ajax call to a server, and the server returns xml data, I don't know how to parse the xml data to get some values.

My ajax call:

$.ajax({
            url: 'http://localhost:8080/someinterface/the-id',
            type: 'GET',
            async: false,
            dataType: 'application/xml',
            data: {id: 43},
            success: function(data) {

                //handle the data

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })

the returned xml data looks like:

<DOCUMENT>
  <AGE>16</AGE>
  <USERNAME>default user</USERNAME>
  <SECURITYID>1111</SECURITYID>
...

how to parse the xml data to get for example "USERNAME" in my javascript ??

------------EDIT------------

I tried to use your proposed ways, but now I got error message:

XML Parsing Error: no element found Location: moz-nullprincipal:{120e8c1d-5174-4e94-9ebb-2bffda80b170} Line Number 1, Column 1:
^

and the ajax call result to the error function

-------------------PARTLY SOLVED------------------------

Finally, I found the reason is that my application is running on jetty server on localhost:8080, while my ajax is requesting xml data on tomcat server which is running on localhost:8085. Because of the domain port are different, I got the weired problem. Now, after I move my application to tomcat server and request tomcat server, I got the xml response successfully.

The ajax call goes to the success function, and I use

success: function(data){
           xmlDoc = $.parseXML(data);
            $xml = $(xmlDoc);
            $userName = $xml.find('USERNAME');
            var userName = $userName.text();
            alert('1');
            alert(userName);
}

I got alert('1') in my browser, BUT I do not get alert(userName) , I don't know why... So I put here "PARTLY SOLVED", so...why I do not get my userName alert..

Body:
You are misusing the dataType parameter. It's not expected to be a MIME type. Instead, it should one of these: "xml", "html", "script", "json", "jsonp" or "text". In your case, "xml" (or omit it completely and jQuery will guess it for you):

http://api.jquery.com/jQuery.ajax/ (scroll down to "dataTypeString").

Update:

So far, it looks that your problem is that your server side script is crashing and you don't even have valid XML. Whatever, I've put together a small example in case it helps:

$.ajax({
    url: "/test.xml",
    type: "GET",
    async: false,
    dataType: "xml",
    data: {id: 43},
    success: function(data) {
        var output = "Usernames:\n";
        $(data).find("USERNAME").each(function(){
            output += "\n- " + $(this).text();
        });
        alert(output);
    },
    error: function(xhr, status, error){
        alert("error happens");
    }
})


问:
What's wrong with this JSON file please?
.atom-live-server.json

What's wrong with this code please ? I cannot find the problem

答:
A JSON file can only have one root element. There you have two objects:

one from line 1 to 11,

another one from 13 to 15

Either separate them in two distinct files or create an object that contains both.


问:
NzNoAnimation Error using NzPicker (nz-year-picker)
When using NzPicker, I get the following error.

Adding an NzNoanimationModule is the same.

How do I fix it?

<nz-year-picker (ngModelChange)="onChange($event)" nzPlaceHolder="select year">
      </nz-year-picker>
```

```NzPickerComponent.html:81 ERROR TypeError: Object(...) is not a function
at NzNoAnimationDirective.push../node_modules/ng-zorro-antd/fesm5/ng-zorro-antd-core.js.NzNoAnimationDirective.updateClass (ng-zorro-antd-core.js:590)
at NzNoAnimationDirective.push../node_modules/ng-zorro-antd/fesm5/ng-zorro-antd-core.js.NzNoAnimationDirective.ngOnChanges (ng-zorro-antd-core.js:569)
at checkAndUpdateDirectiveInline (core.js:17976)
at checkAndUpdateNodeInline (core.js:26042)
at checkAndUpdateNode (core.js:26004)
at debugCheckAndUpdateNode (core.js:26638)
at debugCheckDirectivesFn (core.js:26598)
at Object.eval [as updateDirectives] (NzPickerComponent.html:81)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:26590)
at checkAndUpdateView (core.js:25986)
View_NzPickerComponent_10 @ NzPickerComponent.html:81
push../node_modules/@angular/core/fesm5/core.js.DebugContext_.logError @ core.js:26818
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:5615
(anonymous) @ core.js:23680
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
```

答: The cause was missing @angular/cdk/coercion.</p>

Body:
When using NzPicker, I get the following error.

Adding an NzNoanimationModule is the same.

How do I fix it?

<nz-year-picker (ngModelChange)="onChange($event)" nzPlaceHolder="select year">
      </nz-year-picker>

NzPickerComponent.html:81 ERROR TypeError: Object(...) is not a function
at NzNoAnimationDirective.push../node_modules/ng-zorro-antd/fesm5/ng-zorro-antd-core.js.NzNoAnimationDirective.updateClass (ng-zorro-antd-core.js:590)
at NzNoAnimationDirective.push../node_modules/ng-zorro-antd/fesm5/ng-zorro-antd-core.js.NzNoAnimationDirective.ngOnChanges (ng-zorro-antd-core.js:569)
at checkAndUpdateDirectiveInline (core.js:17976)
at checkAndUpdateNodeInline (core.js:26042)
at checkAndUpdateNode (core.js:26004)
at debugCheckAndUpdateNode (core.js:26638)
at debugCheckDirectivesFn (core.js:26598)
at Object.eval [as updateDirectives] (NzPickerComponent.html:81)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:26590)
at checkAndUpdateView (core.js:25986)
View_NzPickerComponent_10 @ NzPickerComponent.html:81
push../node_modules/@angular/core/fesm5/core.js.DebugContext_.logError @ core.js:26818
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:5615
(anonymous) @ core.js:23680
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150


问:
How to plot all R squares of a list of models in a single plot in R?
This is an example df. However my original df is much more big.

```<code>ind1 <- rnorm(99)
ind2 <- rnorm(99)
ind3 <- rnorm(99)
dep <- rnorm(99, mean=ind1)
df <- data.frame(dep, ind1, ind2, ind3)
</code>```

Following code is to run 3 models to each variables in the df.

```<code>ind <- c("ind1", "ind2", "ind3")
fmt <- c("dep ~ %s",
         "dep ~ poly(%s, 2, raw=TRUE)",
         "dep ~ poly(%s, 3, raw=TRUE)")
fo.strings <- c(outer(fmt, ind, sprintf))
outputs <- sapply(fo.strings, lm, data = df, simplify = FALSE)
</code>```

The outputs is a list of models (9 list in total).

I want to plot Rsquares of all models in the list in a single plot and
order them lowest to highest to compare them. It is quite complicated when they are in a list. It would be highly appreciated if someone help this out.

Thanks in advance!

答:
You extract the R squared with summary(model)$r.squared, and you can apply that function to the list. I'll use sapply here so the output is a named vector. Then there are many ways to plot it, you could use base R plot functions or ggplot, but an easy one is lattice::barchart:

```<code>rsq <- sapply(outputs, function(mod) summary(mod)$r.squared)
rsq <- sort(rsq)
lattice::barchart(rsq)
</code>```

Body:
This is an example df. However my original df is much more big.

ind1 <- rnorm(99)
ind2 <- rnorm(99)
ind3 <- rnorm(99)
dep <- rnorm(99, mean=ind1)
df <- data.frame(dep, ind1, ind2, ind3)

Following code is to run 3 models to each variables in the df.

ind <- c("ind1", "ind2", "ind3")
fmt <- c("dep ~ %s",
         "dep ~ poly(%s, 2, raw=TRUE)",
         "dep ~ poly(%s, 3, raw=TRUE)")
fo.strings <- c(outer(fmt, ind, sprintf))
outputs <- sapply(fo.strings, lm, data = df, simplify = FALSE)

The outputs is a list of models (9 list in total).

I want to plot Rsquares of all models in the list in a single plot and
order them lowest to highest to compare them. It is quite complicated when they are in a list. It would be highly appreciated if someone help this out.

Thanks in advance!

Body:
You extract the R squared with summary(model)$r.squared, and you can apply that function to the list. I'll use sapply here so the output is a named vector. Then there are many ways to plot it, you could use base R plot functions or ggplot, but an easy one is lattice::barchart:

rsq <- sapply(outputs, function(mod) summary(mod)$r.squared)
rsq <- sort(rsq)
lattice::barchart(rsq)


问:
What does this profiling result mean?
I opened a project (Visual C# - Windows Forms) and profiled it, and got the "hottest" methods. Now I can't understand the results because the hottest method is "collapsed methods without source". How can i understand what to fix if I can't see the method? What should i do?

Here is a pic so you can understand.

答:
If you read the screen carefully, you'll notice the following:

Collapsed methods without source. To view these methods, change the display option to show all methods.

So, try changing the display option to show all methods. That should fix your problem.

Once you know the methods, you'll need to go find them in your source code.

Title: What does this profiling result mean?


问:
how to do svg transform in percentage
I want to center the rect shape with something equivalent to
transform="translate(50% - 100,0)" for example:

```<code>    <svg width="100%" height="100%" viewbox="0 0 100% 100%">
        <g transform="translate(50% - 100,0)">
            <rect width="200" height="100" fill="rgb(0,0,255)" />
        </g>
    </svg>
</code>```

I can't find the right syntax.

答:
You can use an inner <svg> element to do the percentage part via its x attribute then the rest with the <g> element as you already have.

I'm not sure what you intend with the viewBox but percentage values are not valid there. Looks like you just don't need that at all.

<svg width="100%" height="100%">
    <svg x="50%" overflow="visible">
        <g transform="translate(-100,0)">
            <rect width="200" height="100" fill="rgb(0,0,255)" />
        </g>
    </svg>
</svg>```

Title: how to do svg transform in percentage

Body:
I want to center the rect shape with something equivalent to
transform="translate(50% - 100,0)" for example:

    <svg width="100%" height="100%" viewbox="0 0 100% 100%">
        <g transform="translate(50% - 100,0)">
            <rect width="200" height="100" fill="rgb(0,0,255)" />
        </g>
    </svg>

I can't find the right syntax.


问:
Running antlr4 parser for c++ on grammar file shows error 33: missing code generation template NonLocalAttrRefHeader
I am relatively new to ANTLR, I have a current project that needs to be merged from ANTLR3 (version 3.5) to ANTLR4. I have gone thru the book and tried the demo, this all works fine, but my own project gives me the following problem:

After converting a ANTRL3 project to ANTLR4 project (resolving all warnings and errors) I was able to build the lexer.h and lexer.cpp file but the following errors come up:
error(33):  missing code generation template NonLocalAttrRefHeader
error(33):  missing code generation template SetNonLocalAttrHeader
(about 50 times). I haven't been able to find any references of these templates anywhere. Is there anybody who can shed any light on these error messages? Because they don't say anything about line no's or reference any other code I'm completely in in the dark where to look.

I've set up a test environment, testing the demo g4 files. I have pulled the g4 file out of my (VS2017) project and tried it seperately using batch files.

Because of the lack of references I can't show the actual piece of code that is the cause. I have tried a partial parse, but I haven't been able to get any clues from that.

These errors are shown:
error(33):  missing code generation template NonLocalAttrRefHeader
error(33):  missing code generation template SetNonLocalAttrHeader

I've constructed a small example to demonstrate the problem:

```<code>/*
 * AMF Syntax definition for ANTLR.
 *
 */
grammar amf;

options {
    language = Cpp;
}

amf_group[amf::AmfGroup& amfGroup] locals [int jsonScope = 2]
    : statements=amf_statements (GROUPSEP WS? LINE_COMMENT? EOL? | EOF)
    {
        amfGroup.SetStatements(std::move($statements.stmts));
    }
    ;

amf_statements returns [amf::AmfStatements stmts]
    : ( WS? ( stmt=amf_statement { stmts.emplace_back(std::move($stmt.value)); } WS? EOL) )*
    ;

amf_statement returns [amf::AmfStatementPtr value]
    : (
        {$amf_group::jsonScope == 1}? jsonparent_statement
        | {$amf_group::jsonScope == 2}? jsonvalue_statement
       )
    {
        value = std::move(context.expression(0).value);
    }
    ;

jsonparent_statement returns [amf::AmfStatementPtr value] locals [int lineno=0]
    :
    (T_JSONPAR      { $lineno = $T_JSONPAR.line;} )  WS (arg=integer_const)
    {
        value = std::make_shared<amf::JSONParentStatement>($lineno, nullptr);
    }
    ;

jsonvalue_statement returns [amf::AmfStatementPtr value] locals [int lineno=0]
    : ( T_JSONVALUE { $lineno = $T_JSONVALUE.line; } ) WS (arg=integer_const) (WS fmt=integer_const)?
    {
        value = std::make_shared<amf::JSONValueStatement>($lineno, std::move(arg), std::move(fmt));
    }
    ;

integer_const returns [amf::AmfArgPtr value]
    : p='%' (
        (signed_int)
        {
            long num = std::stol($signed_int.text);
            value = std::make_shared<amf::AmfArg>(ARG_TYPE::ARG_INTEGER, num);
        }
        | signed_float
        {
            value = std::make_shared<amf::AmfArg>(ARG_TYPE::ARG_INTEGER, std::stof($signed_float.text));
        }
        )
    ;

signed_int
    : MINUS? INT;

signed_float
    : MINUS? FLOAT;

    T_JSONPAR       : 'JSONPAR' | 'JSONPARENT';
    T_JSONVALUE     : 'JSONVAL' | 'JSONVALUE';

    /* Special tokens */
    GROUPSEP        : '%%';

    MINUS           : '-';

INT : DIGIT+;

FLOAT
    : DIGIT+ '.' DIGIT* EXPONENT?
    | '.' DIGIT+ EXPONENT?
    | DIGIT+ EXPONENT
    ;

ID  : ('A'..'Z'|'_') ('A'..'Z'|'0'..'9'|'_')*
    ;

COMMENT
    : ('/*' .*? '*/') -> channel(HIDDEN)
    ;

LINE_COMMENT
    : ('//' ~('\n'|'\r')* '\r'?) -> channel(HIDDEN)
    ;

EOL : ('\r'? '\n');

QOUTED_STRING
    : '"$' ( ESC_SEQ | ~('\\'|'"') )* '"'
    ;

SIMPLE_STRING
    : '$' ~(' '|'\t'|'\r'|'\n')*
    ;

WS  : (' '|'\t')+;

fragment
DIGIT
    : '0'..'9'
    ;

fragment
EXPONENT
    : 'E' ('+'|'-')? ('0'..'9')+
    ;

fragment
ESC_SEQ
    : '\\' (
        'R'
        |'N'
        |'T'
        |'"'
        |'\''
        |'\\'
    )
    ;
</code>```

The error occurs as soon as I add the predicates for the amf_statement (in this case 4 times "missing code generation template for NonLocalAttrTefHeader)". I have tried changing the output language to Python or CSharp, but this doesn't help.

答:
After carefully looking at all the steps I stumbled on a small but critical difference in the batch command that executes the java command: I used a copy of my former antrl3 batch file that uses the java -jar option to execute the antlr-4.7.2-complete.jar instead of cp and executing the org.antlr.v4.Tool. All seems to go well, the command line options are displayed well, the syntax errors are all in place, until the actual lexer and parser code are created: then the error(33) is displayed, but only if dynamic scoping is used, otherwise all seems to go well.

Update: I thought I could proceed with my project, but this is only a partial solution: when I switched back to Cpp output, the errors returned. Standard output anf CSharp output is okay, as soon I attempt to generate Cpp output I receive the same errors, again when using dynamic scoping: lines 25 and 26. If I remove the predicates, the errors disappear.

So I'm still stuck with these errors, but only for C++.

Body:
I am relatively new to ANTLR, I have a current project that needs to be merged from ANTLR3 (version 3.5) to ANTLR4. I have gone thru the book and tried the demo, this all works fine, but my own project gives me the following problem:

After converting a ANTRL3 project to ANTLR4 project (resolving all warnings and errors) I was able to build the lexer.h and lexer.cpp file but the following errors come up:
error(33):  missing code generation template NonLocalAttrRefHeader
error(33):  missing code generation template SetNonLocalAttrHeader
(about 50 times). I haven't been able to find any references of these templates anywhere. Is there anybody who can shed any light on these error messages? Because they don't say anything about line no's or reference any other code I'm completely in in the dark where to look.

I've set up a test environment, testing the demo g4 files. I have pulled the g4 file out of my (VS2017) project and tried it seperately using batch files.

Because of the lack of references I can't show the actual piece of code that is the cause. I have tried a partial parse, but I haven't been able to get any clues from that.

These errors are shown:
error(33):  missing code generation template NonLocalAttrRefHeader
error(33):  missing code generation template SetNonLocalAttrHeader

I've constructed a small example to demonstrate the problem:

/*
 * AMF Syntax definition for ANTLR.
 *
 */
grammar amf;

options {
    language = Cpp;
}

amf_group[amf::AmfGroup& amfGroup] locals [int jsonScope = 2]
    : statements=amf_statements (GROUPSEP WS? LINE_COMMENT? EOL? | EOF)
    {
        amfGroup.SetStatements(std::move($statements.stmts));
    }
    ;

amf_statements returns [amf::AmfStatements stmts]
    : ( WS? ( stmt=amf_statement { stmts.emplace_back(std::move($stmt.value)); } WS? EOL) )*
    ;

amf_statement returns [amf::AmfStatementPtr value]
    : (
        {$amf_group::jsonScope == 1}? jsonparent_statement
        | {$amf_group::jsonScope == 2}? jsonvalue_statement
       )
    {
        value = std::move(context.expression(0).value);
    }
    ;

jsonparent_statement returns [amf::AmfStatementPtr value] locals [int lineno=0]
    :
    (T_JSONPAR      { $lineno = $T_JSONPAR.line;} )  WS (arg=integer_const)
    {
        value = std::make_shared<amf::JSONParentStatement>($lineno, nullptr);
    }
    ;

jsonvalue_statement returns [amf::AmfStatementPtr value] locals [int lineno=0]
    : ( T_JSONVALUE { $lineno = $T_JSONVALUE.line; } ) WS (arg=integer_const) (WS fmt=integer_const)?
    {
        value = std::make_shared<amf::JSONValueStatement>($lineno, std::move(arg), std::move(fmt));
    }
    ;

integer_const returns [amf::AmfArgPtr value]
    : p='%' (
        (signed_int)
        {
            long num = std::stol($signed_int.text);
            value = std::make_shared<amf::AmfArg>(ARG_TYPE::ARG_INTEGER, num);
        }
        | signed_float
        {
            value = std::make_shared<amf::AmfArg>(ARG_TYPE::ARG_INTEGER, std::stof($signed_float.text));
        }
        )
    ;

signed_int
    : MINUS? INT;

signed_float
    : MINUS? FLOAT;

    T_JSONPAR       : 'JSONPAR' | 'JSONPARENT';
    T_JSONVALUE     : 'JSONVAL' | 'JSONVALUE';

    /* Special tokens */
    GROUPSEP        : '%%';

    MINUS           : '-';

INT : DIGIT+;

FLOAT
    : DIGIT+ '.' DIGIT* EXPONENT?
    | '.' DIGIT+ EXPONENT?
    | DIGIT+ EXPONENT
    ;

ID  : ('A'..'Z'|'_') ('A'..'Z'|'0'..'9'|'_')*
    ;

COMMENT
    : ('/*' .*? '*/') -> channel(HIDDEN)
    ;

LINE_COMMENT
    : ('//' ~('\n'|'\r')* '\r'?) -> channel(HIDDEN)
    ;

EOL : ('\r'? '\n');

QOUTED_STRING
    : '"$' ( ESC_SEQ | ~('\\'|'"') )* '"'
    ;

SIMPLE_STRING
    : '$' ~(' '|'\t'|'\r'|'\n')*
    ;

WS  : (' '|'\t')+;

fragment
DIGIT
    : '0'..'9'
    ;

fragment
EXPONENT
    : 'E' ('+'|'-')? ('0'..'9')+
    ;

fragment
ESC_SEQ
    : '\\' (
        'R'
        |'N'
        |'T'
        |'"'
        |'\''
        |'\\'
    )
    ;

The error occurs as soon as I add the predicates for the amf_statement (in this case 4 times "missing code generation template for NonLocalAttrTefHeader)". I have tried changing the output language to Python or CSharp, but this doesn't help.


问:
How to align second line in a bullet-ed un-ordered list
I have a bullet-ed un-ordered list of ingredients on my recipe site.  I have some padding around the list so that it is displayed in the center of the page.  However, when I go to view the page on an iphone or a tablet (a device with a narrower screen), my bullet points are pushed to 2 lines and the second line is not in line with the first.

I believe this is due to the padding code I have around the list so that on a narrow screen, the bullets are still in the center of the page.  When the bullet point is too long that it has to go to 2 lines, the second line is pushed all the way to the left while the bullet is still centered.  I am looking to align the second line with the first (still centered on the page)

I have tried positioning it 'outside' the bullet point, however, because I have made my own bullet point with code this doesn't seem to work.

The code below is the code I have for the cellular device display of this issue.

```<code>    @media only screen and (max-width : 480px)
    { ul[data-rte-list] li>*:first-child::before  {
        content: "•";
        position: outside;
        line-height: 1.5em !important;
        top: 2px;
        padding-right: 10px;
        font-size: 22px;
        padding-left: 100px;
        color: #373737;
        opacity: .4;
    }

}
</code>```

This is exactly what the page looks like:

答:
Building on the answer by uom-pregorio, you can make the list item a flexbox container to have all the text truly aligned with the first line.

I also moved the ::before sudo element to the
 itself, so that it was not contained inside the , as we want them to sit next to each other as siblings.

div {
  width: 400px;
  margin: auto;
  background-color: #dadada;
}

ul {
  list-style: none;
  padding-left: 100px;
}

ul li {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: flex-start;
}

ul li::before {
  content: "•";
  line-height: 1.5em !important;
  padding-right: 10px;
  font-size: 22px;
  color: #373737;
  opacity: 0.4;
  width: content;
  margin: 0;
}

ul li>*:first-child {
  flex-grow:2;
  padding-top: 0.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <ul>
    <li>
      <span>1 can coconut milk</span>
    </li>
    <li>
      <span>1/4 cup date syrup (substitute maple syrup or honey)</span>
    </li>
    <li>
      <span>1 tsp vanilla</span>
    </li>
  </ul>
</div></code>```

See this site for more info: A Complete Guide to Flexbox

Body:
I have a bullet-ed un-ordered list of ingredients on my recipe site.  I have some padding around the list so that it is displayed in the center of the page.  However, when I go to view the page on an iphone or a tablet (a device with a narrower screen), my bullet points are pushed to 2 lines and the second line is not in line with the first.

I believe this is due to the padding code I have around the list so that on a narrow screen, the bullets are still in the center of the page.  When the bullet point is too long that it has to go to 2 lines, the second line is pushed all the way to the left while the bullet is still centered.  I am looking to align the second line with the first (still centered on the page)

I have tried positioning it 'outside' the bullet point, however, because I have made my own bullet point with code this doesn't seem to work.

The code below is the code I have for the cellular device display of this issue.

    @media only screen and (max-width : 480px)
    { ul[data-rte-list] li>*:first-child::before  {
        content: "•";
        position: outside;
        line-height: 1.5em !important;
        top: 2px;
        padding-right: 10px;
        font-size: 22px;
        padding-left: 100px;
        color: #373737;
        opacity: .4;
    }

}

This is exactly what the page looks like:

Body:
Building on the answer by uom-pregorio, you can make the list item a flexbox container to have all the text truly aligned with the first line.

I also moved the ::before sudo element to the <li> itself, so that it was not contained inside the <span>, as we want them to sit next to each other as siblings.

div {
  width: 400px;
  margin: auto;
  background-color: #dadada;
}

ul {
  list-style: none;
  padding-left: 100px;
}

ul li {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: flex-start;
}

ul li::before {
  content: "•";
  line-height: 1.5em !important;
  padding-right: 10px;
  font-size: 22px;
  color: #373737;
  opacity: 0.4;
  width: content;
  margin: 0;
}

ul li>*:first-child {
  flex-grow:2;
  padding-top: 0.5em;
}

<div>
  <ul>
    <li>
      <span>1 can coconut milk</span>
    </li>
    <li>
      <span>1/4 cup date syrup (substitute maple syrup or honey)</span>
    </li>
    <li>
      <span>1 tsp vanilla</span>
    </li>
  </ul>
</div>

See this site for more info: A Complete Guide to Flexbox


问:
Used SequentialFeatureSelector but does not improve the model accuracy
I am selecting features for building a churn prediction model. With the RandomForestClassifier, I got an accuracy of 0.9517 and it showed 16 features selected as part of this.

However, if I fit a model using the same list of 16 features with RandomForestClassifier separately, it shows an accuracy score of 0.8714, Why is there a huge difference in accuracy score although I used the same list of features selected by SequentialFeatureSelector?

[2019-01-28 17:51:16] Features: 16/16 -- score:
  0.9517879681082387[Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    3.6s remaining:    0.0s

```<code>rand_forest = RandomForestClassifier(bootstrap=True,
                class_weight=None, criterion='gini',
                max_depth=None, max_features='auto',
                max_leaf_nodes=None,
                min_impurity_decrease=0.0, min_impurity_split=None,
                min_samples_leaf=1, min_samples_split=2,
                min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=1,
                oob_score=False, random_state=None, verbose=0,
                warm_start=False)

SequentialFeatureSelector(clone_estimator=True, cv=0,
             estimator=rand_forest,
             floating=False, forward=True, k_features=16, n_jobs=1,
             pre_dispatch='2*n_jobs', scoring='accuracy', verbose=2)

xtr, xtst, ytr, ytst = train_test_split(x, y, random_state=5, test_size=0.2)

rfst = RandomForestClassifier(n_estimators=100)

rfstmodel = rfst.fit(xtr, ytr)

rfstmodel.score(xtst, ytst)

>>> 0.8714975845410629
</code>```

答:
Random Forest Classifiers don't just randomize the features, they also randomize the splits of those features, so even though your features are staying the same, your feature-splits are being randomly generated each time, which can introduce some variance into the model. For a more regularized model with on-average less variance, I recommend a Gradient Boosted Model, or better yet XGBoost.

Random Forest adds additional randomness to the model, while growing
  the trees. Instead of searching for the most important feature while
  splitting a node, it searches for the best feature among a random
  subset of features. This results in a wide diversity that generally
  results in a better model.

Therefore, in Random Forest, only a random subset of the features is
  taken into consideration by the algorithm for splitting a node. You
  can even make trees more random, by additionally using random
  thresholds for each feature rather than searching for the best
  possible thresholds (like a normal decision tree does).

Source: https://towardsdatascience.com/the-random-forest-algorithm-d457d499ffcd

Body:
I am selecting features for building a churn prediction model. With the RandomForestClassifier, I got an accuracy of 0.9517 and it showed 16 features selected as part of this.

However, if I fit a model using the same list of 16 features with RandomForestClassifier separately, it shows an accuracy score of 0.8714, Why is there a huge difference in accuracy score although I used the same list of features selected by SequentialFeatureSelector?

[2019-01-28 17:51:16] Features: 16/16 -- score:
  0.9517879681082387[Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    3.6s remaining:    0.0s

rand_forest = RandomForestClassifier(bootstrap=True,
                class_weight=None, criterion='gini',
                max_depth=None, max_features='auto',
                max_leaf_nodes=None,
                min_impurity_decrease=0.0, min_impurity_split=None,
                min_samples_leaf=1, min_samples_split=2,
                min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=1,
                oob_score=False, random_state=None, verbose=0,
                warm_start=False)

SequentialFeatureSelector(clone_estimator=True, cv=0,
             estimator=rand_forest,
             floating=False, forward=True, k_features=16, n_jobs=1,
             pre_dispatch='2*n_jobs', scoring='accuracy', verbose=2)

xtr, xtst, ytr, ytst = train_test_split(x, y, random_state=5, test_size=0.2)

rfst = RandomForestClassifier(n_estimators=100)

rfstmodel = rfst.fit(xtr, ytr)

rfstmodel.score(xtst, ytst)

>>> 0.8714975845410629


问:
Why are .innerHTML problems not an issue when using JQuery().html()?
I worked out any single instance of document.getElementById("MyID").innerHTML = "A value" in this Javascript World Clock guide causes Wordpress Admin not to load completely and breaks various areas of the Wordpress admin interface.

I solved it by replacing each instance with jQuery("#MyID").html("A value")) which appears to work fine. What is causing .innerHTML to fail miserably but not JQuery().html()?

答:
About the only difference between what you tried and what jQuery's html method might be doing is removing the content of the element before inserting the new content. So try removing the content first and if you are only inserting plain text, create and insert a text node instead of setting the innerHTML.

So:

```<code>function replaceContent(id, s) {
  var el = document.getElementById(id);
  if (el) {
    while (el.firstChild) {
      el.removeChild(el.firstChild);
    }
    el.appendChild(document.createTextNode(s));
  }
}
</code>```

Body:
About the only difference between what you tried and what jQuery's html method might be doing is removing the content of the element before inserting the new content. So try removing the content first and if you are only inserting plain text, create and insert a text node instead of setting the innerHTML.

So:

function replaceContent(id, s) {
  var el = document.getElementById(id);
  if (el) {
    while (el.firstChild) {
      el.removeChild(el.firstChild);
    }
    el.appendChild(document.createTextNode(s));
  }
}


问:
how to implement a sliverAppBar with a tabBar
the flutter document show a demo for SliverAppBar + TabBar + TabBarView with ListView use NestedScrollView, and it's a bit complex, so I wonder is there a simply and clear way to implement it. I tried this:

```<code>CustomScrollView
  slivers:
    SliverAPPBar
      bottom: TabBar
    TabBarView
      children: MyWidget(list or plain widget)
</code>```

got error:

flutter: The following assertion was thrown building Scrollable(axisDirection: right, physics:

  flutter: A RenderViewport expected a child of type RenderSliver but received a child of type _RenderExcludableScrollSemantics.

  flutter: RenderObjects expect specific types of children because they coordinate with their children during layout and paint. For example, a RenderSliver cannot be the child of a RenderBox because a RenderSliver does not understand the RenderBox layout protocol.

and

flutter: Another exception was thrown: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 3497 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.

HERE IS MY CODE:

```<code>import 'package:flutter/material.dart';

main(List<String> args) {
  runApp(MyScrollTabListApp());
}

class MyScrollTabListApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(title: "aa", home: MyScrollTabListHomePage());
  }
}

class MyScrollTabListHomePage extends StatefulWidget {
  @override
  MyScrollTabListHomePageState createState() {
    return new MyScrollTabListHomePageState();
  }
}

class MyScrollTabListHomePageState extends State<MyScrollTabListHomePage>
    with SingleTickerProviderStateMixin {
  final int _listItemCount = 300;
  final int _tabCount = 8;
  TabController _tabController;

  @override
  void initState() {
    _tabController = TabController(length: _tabCount, vsync: this);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 240.0,
            title: Text("Title"),
            pinned: true,
            bottom: TabBar(
              controller: _tabController,
              isScrollable: true,
              tabs: List<Tab>.generate(_tabCount, (int i) {
                return Tab(text: "TAB$i");
              }),
            ),
          ),
          TabBarView(
            controller: _tabController,
            children: List<Widget>.generate(_tabCount, (int i) {
              return Text('line $i');
            }),
          ),
        ],
      ),
    );
  }
}
</code>```

and for the official demo, it use struct like this

```<code>DefaultTabController
    NestedScrollView
      headerSliverBuilder
        SliverOverlapAbsorber
          handle
          SliverAppBar
        TabBarView
          CustomScrollView
            SliverOverlapInjector
              handle
              SliverPadding
</code>```

答:
Use NestedScrollView, here is the working code.

```<code>@override
Widget build(BuildContext context) {
  return Scaffold(
    body: DefaultTabController(
      length: 2,
      child: NestedScrollView(
        headerSliverBuilder: (context, value) {
          return [
            SliverAppBar(
              bottom: TabBar(
                tabs: [
                  Tab(icon: Icon(Icons.call), text: "Call"),
                  Tab(icon: Icon(Icons.message), text: "Message"),
                ],
              ),
            ),
          ];
        },
        body: TabBarView(
          children: [
            CallPage(),
            MessagePage(),
          ],
        ),
      ),
    ),
  );
}
</code>```

Body:
the flutter document show a demo for SliverAppBar + TabBar + TabBarView with ListView use NestedScrollView, and it's a bit complex, so I wonder is there a simply and clear way to implement it. I tried this:

CustomScrollView
  slivers:
    SliverAPPBar
      bottom: TabBar
    TabBarView
      children: MyWidget(list or plain widget)

got error:

flutter: The following assertion was thrown building Scrollable(axisDirection: right, physics:

  flutter: A RenderViewport expected a child of type RenderSliver but received a child of type _RenderExcludableScrollSemantics.

  flutter: RenderObjects expect specific types of children because they coordinate with their children during layout and paint. For example, a RenderSliver cannot be the child of a RenderBox because a RenderSliver does not understand the RenderBox layout protocol.

and

flutter: Another exception was thrown: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 3497 pos 14: 'owner._debugCurrentBuildTarget == this': is not true.

HERE IS MY CODE:

import 'package:flutter/material.dart';

main(List<String> args) {
  runApp(MyScrollTabListApp());
}

class MyScrollTabListApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(title: "aa", home: MyScrollTabListHomePage());
  }
}

class MyScrollTabListHomePage extends StatefulWidget {
  @override
  MyScrollTabListHomePageState createState() {
    return new MyScrollTabListHomePageState();
  }
}

class MyScrollTabListHomePageState extends State<MyScrollTabListHomePage>
    with SingleTickerProviderStateMixin {
  final int _listItemCount = 300;
  final int _tabCount = 8;
  TabController _tabController;

  @override
  void initState() {
    _tabController = TabController(length: _tabCount, vsync: this);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 240.0,
            title: Text("Title"),
            pinned: true,
            bottom: TabBar(
              controller: _tabController,
              isScrollable: true,
              tabs: List<Tab>.generate(_tabCount, (int i) {
                return Tab(text: "TAB$i");
              }),
            ),
          ),
          TabBarView(
            controller: _tabController,
            children: List<Widget>.generate(_tabCount, (int i) {
              return Text('line $i');
            }),
          ),
        ],
      ),
    );
  }
}

and for the official demo, it use struct like this

DefaultTabController
    NestedScrollView
      headerSliverBuilder
        SliverOverlapAbsorber
          handle
          SliverAppBar
        TabBarView
          CustomScrollView
            SliverOverlapInjector
              handle
              SliverPadding

Body:
Use NestedScrollView, here is the working code.

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: DefaultTabController(
      length: 2,
      child: NestedScrollView(
        headerSliverBuilder: (context, value) {
          return [
            SliverAppBar(
              bottom: TabBar(
                tabs: [
                  Tab(icon: Icon(Icons.call), text: "Call"),
                  Tab(icon: Icon(Icons.message), text: "Message"),
                ],
              ),
            ),
          ];
        },
        body: TabBarView(
          children: [
            CallPage(),
            MessagePage(),
          ],
        ),
      ),
    ),
  );
}


问:
SPFX with Angular - Not able to use service in component ts file
I have created a project using SharePoint SPFX framework and added necessary packages required for Angular (6.0 or 7.0) typescript. It seems Angular is working in my spfx webpart but when I am trying to create a service using Angular, I am not able to use the methods available in the service from component.ts file. Though no errors are being shown in the project, the method declared in the service is coming as undefined when I am trying to use in the component.ts file

app.service.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
export interface IDataService {
    getTitle(webUrl:string):string;
}
@Injectable()
export class SharePointService {
     constructor() {}
     public getTitle(webUrl:string):string {
       return webUrl;
     }
  }
</code>```

app.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import {IWebPartContext} from '@microsoft/sp-webpart-base';
import { IDataService } from './app.service';

@Component({
  selector: 'my-spfx-app',
  template: `<h3>Welcome to SPFx {{name}}!!</h3><p>{{serviceProp}}</p>`
})
export class AppComponent implements OnInit  {
    public name: string = '';
    public context:IWebPartContext;
    public serviceProp:string = "";
    constructor(private dataService: IDataService){
    }

   public  ngOnInit() {
        this.context= window["webPartContext"];
        this.name= this.context.pageContext.user.displayName;
        this.serviceProp = this.dataService.getTitle("Angular Service Testing");
    }
}
</code>```

Output

Welcome to SPFx User1

Data is not coming to serviceProp variable. Please help us

答:
You need to mark the class as the type instead of the interface

```<code>private dataService: SharePointService
</code>```

and don't forget to provide the service either in the root module or in the feature module that contains the component

```<code>`@Injectable({ provideIn: 'root' })`
</code>```

Body:
I have created a project using SharePoint SPFX framework and added necessary packages required for Angular (6.0 or 7.0) typescript. It seems Angular is working in my spfx webpart but when I am trying to create a service using Angular, I am not able to use the methods available in the service from component.ts file. Though no errors are being shown in the project, the method declared in the service is coming as undefined when I am trying to use in the component.ts file

app.service.ts

import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
export interface IDataService {
    getTitle(webUrl:string):string;
}
@Injectable()
export class SharePointService {
     constructor() {}
     public getTitle(webUrl:string):string {
       return webUrl;
     }
  }

app.component.ts

import { Component, OnInit } from '@angular/core';
import {IWebPartContext} from '@microsoft/sp-webpart-base';
import { IDataService } from './app.service';

@Component({
  selector: 'my-spfx-app',
  template: `<h3>Welcome to SPFx {{name}}!!</h3><p>{{serviceProp}}</p>`
})
export class AppComponent implements OnInit  {
    public name: string = '';
    public context:IWebPartContext;
    public serviceProp:string = "";
    constructor(private dataService: IDataService){
    }

   public  ngOnInit() {
        this.context= window["webPartContext"];
        this.name= this.context.pageContext.user.displayName;
        this.serviceProp = this.dataService.getTitle("Angular Service Testing");
    }
}

Output

Welcome to SPFx User1

Data is not coming to serviceProp variable. Please help us

Body:
You need to mark the class as the type instead of the interface

private dataService: SharePointService

and don't forget to provide the service either in the root module or in the feature module that contains the component

`@Injectable({ provideIn: 'root' })`


问:
why fork() return double zero if we use it first in a if or while
It's from my homework. In the code, there should be 2 processes, father and child. But in the code, there will be 2 zero, and will never get in the branch p1>0.
Here is a code. I use fork() and get double zero, it's confusing. I want to know how the fork() works in this code.

```<code>#include "stdio.h"
#include "unistd.h"
#include "signal.h"
int k1;
void func1(int signo){
    if (signo==SIGUSR2)
    {
        k1=0;
    }

}

int main(int argc, char const *argv[])
{
    int k,p1;
    while (p1=fork()==-1);//one time
    if (p1>0)
    {
        for (k = 1; k < 4; k++)
        {
            printf("parent:pid=%d\n",getpid());
            sleep(1);
        }
        kill(p1,12);
        wait(0);
        printf("OK!\n");
        exit(0);
    }
    else
    {
        signal(12,func1);
        k1=1;
        while (k1==1)
        {
            printf("I'm child\n");
            sleep(1);
        }
        printf("Child forced!\n");
        exit(0);

    }
    return 0;
}
</code>```

I want to know how fork() works in this code.

The output of the code is loop output: "I'm child". Output two lines per second.

However, in my opinion, there should output "parent:pid=%d", but the code won't get in the "p1>0" branch. it seems that fork() generates 2 processes but all of them have p1=0.

答:
The problem lies in operators precedence, == has higher precedence than = and thus while (p1=fork()==-1) is parsed as while (p1=(fork()==-1)). When You run this code fork succeeds and in both branches returns value different from -1. That's why in both, the child and the parent, p1 is equal to 0 (false).

You need to add extra parenthesis around assignment: while ((p1=fork())==-1).

Body:
It's from my homework. In the code, there should be 2 processes, father and child. But in the code, there will be 2 zero, and will never get in the branch p1>0.
Here is a code. I use fork() and get double zero, it's confusing. I want to know how the fork() works in this code.

#include "stdio.h"
#include "unistd.h"
#include "signal.h"
int k1;
void func1(int signo){
    if (signo==SIGUSR2)
    {
        k1=0;
    }

}

int main(int argc, char const *argv[])
{
    int k,p1;
    while (p1=fork()==-1);//one time
    if (p1>0)
    {
        for (k = 1; k < 4; k++)
        {
            printf("parent:pid=%d\n",getpid());
            sleep(1);
        }
        kill(p1,12);
        wait(0);
        printf("OK!\n");
        exit(0);
    }
    else
    {
        signal(12,func1);
        k1=1;
        while (k1==1)
        {
            printf("I'm child\n");
            sleep(1);
        }
        printf("Child forced!\n");
        exit(0);

    }
    return 0;
}

I want to know how fork() works in this code.

The output of the code is loop output: "I'm child". Output two lines per second.

However, in my opinion, there should output "parent:pid=%d", but the code won't get in the "p1>0" branch. it seems that fork() generates 2 processes but all of them have p1=0.


问:
creating a pending intent to start a non system app
I've read plenty of doc, but I still can't figure it out.

Are we allowed to start a 3rd party app(NON SYSTEM APP like as alarm, notification. etc) with a pending intent?

i.e.:

App1

create pending intent

start a non system app and send pending intent

App2

execute its own code

call pending intent to start App1

I haven't found 1 single example doing this. And according to the doc. you can pass a pending intent to a 3rd party app. It does not specify a system app

does it make sense?

答: Yes, you may launch anything you want with a PendingIntent. As long as the component you want to start is exported (publicly available).


问:
Question about type classes in Scala
Let there are classes Fruit, Orange, and Apple.

```<code>abstract class Fruit
class Orange extends Fruit
class Apple extends Fruit</code>```

Now I want to add write functionality to both types Orange and Apple. Using the type class pattern I can do the following:

```<code>trait Writer[T] {def write(t:T)}

implicit object AppleWriter extends Writer[Apple] {
   def write(a:Apple) {println("I am an apple!")}
}

implicit object OrangeWriter extends Writer[Orange] {
   def write(o:Orange) {println("I am an orange!")}
}

def write[T](t:T)(implicit w:Writer[T]){w.write(t)}</code>```

So for, so good but what if I want to define writeFruits ?

```<code>def writeFruits(fruits:List[Fruit]) {for (fruit <- fruits) write(fruit)}</code>```

I would like writeFruits to call either write[Apple] or write[Orange] for each fruit. I see that it does not work (and I know why) but maybe I can implement the writeFruits anyway.

Can I implement writeFruits somehow ?

答:
In the instance of covariant/contravariant types, you almost need to define your type class on the "base" type here:

```<code>implicit object FruitWriter extends Writer[Fruit] {
  def write(a : Fruit) = a match {
    case _ : Apple => println("I am an apple!")
    case _ : Orange => println("I am an orange")
  }
}
</code>```

You could also work on defining the type class with variance so that Writer[Fruit] could be used when you need a Writer[Apple].  It's unfortunate, but if you want to use OO polymorphism, you have to encode that into the functional aspects.

*strong text*Another option is to use an HList for write-fruits and do all the type-recursion yourself...

Assuming:

```<code>trait HList
object HNil extends HList
case class ::[A, Rest <: HList](head : A, tail : Rest)
</code>```

Then we can do something fun like:

```<code>implicit def nilWriter = new Writer[HNil] = { def write(o : HNil) = () }
implicit def hlistWriter[A, Rest](implicit aw : Writer[A], rw : Writer[Rest]) =
  new Writer[A :: Rest] {
  def write(o : (A :: Rest)) = {
    aw.write(o.head)
    rw.write(o.tail)
  }
}
</code>```

NOW

```<code>write( new Orange :: new Apple :: HNil)
</code>```

Note:  I have not tested this code, but the concept of recursively spanning types is sound.   I'm not actually recommending this approach.

Title: Question about type classes in Scala

Body:
Let there are classes Fruit, Orange, and Apple.

abstract class Fruit
class Orange extends Fruit
class Apple extends Fruit

Now I want to add write functionality to both types Orange and Apple. Using the type class pattern I can do the following:

trait Writer[T] {def write(t:T)}

implicit object AppleWriter extends Writer[Apple] {
   def write(a:Apple) {println("I am an apple!")}
}

implicit object OrangeWriter extends Writer[Orange] {
   def write(o:Orange) {println("I am an orange!")}
}

def write[T](t:T)(implicit w:Writer[T]){w.write(t)}

So for, so good but what if I want to define writeFruits ?

def writeFruits(fruits:List[Fruit]) {for (fruit <- fruits) write(fruit)}

I would like writeFruits to call either write[Apple] or write[Orange] for each fruit. I see that it does not work (and I know why) but maybe I can implement the writeFruits anyway.

Can I implement writeFruits somehow ?

Body:
In the instance of covariant/contravariant types, you almost need to define your type class on the "base" type here:

implicit object FruitWriter extends Writer[Fruit] {
  def write(a : Fruit) = a match {
    case _ : Apple => println("I am an apple!")
    case _ : Orange => println("I am an orange")
  }
}

You could also work on defining the type class with variance so that Writer[Fruit] could be used when you need a Writer[Apple].  It's unfortunate, but if you want to use OO polymorphism, you have to encode that into the functional aspects.

*strong text*Another option is to use an HList for write-fruits and do all the type-recursion yourself...

Assuming:

trait HList
object HNil extends HList
case class ::[A, Rest <: HList](head : A, tail : Rest)

Then we can do something fun like:

implicit def nilWriter = new Writer[HNil] = { def write(o : HNil) = () }
implicit def hlistWriter[A, Rest](implicit aw : Writer[A], rw : Writer[Rest]) =
  new Writer[A :: Rest] {
  def write(o : (A :: Rest)) = {
    aw.write(o.head)
    rw.write(o.tail)
  }
}

NOW

write( new Orange :: new Apple :: HNil)

Note:  I have not tested this code, but the concept of recursively spanning types is sound.   I'm not actually recommending this approach.


问:
How would I go about turning the characters in a word that a user inputs into an array that contains the letters in the word?
I am trying to code a hangman game in java. Using JOptionPane to ask the user for a word, how would I go about turning the characters in a word that a user inputs into an array that contains the letters in the word?</p>

答:
```<code>String[] arr = "foo".split("")
</code>```

Would return the array:

```<code>[ "f", "o", "o" ]
</code>```

Alternatively, this could be done with a for loop as such:

```<code>String s = "bar";
String[] arr = new String[s.length];
for (int i = 0; i < s.length; i++) {
    arr[i] = s.substring(i, i + 1);
}
</code>```

returning the output:

```<code>[ "b", "a", "r" ]
</code>```

Body:
String[] arr = "foo".split("")

Would return the array:

[ "f", "o", "o" ]

Alternatively, this could be done with a for loop as such:

String s = "bar";
String[] arr = new String[s.length];
for (int i = 0; i < s.length; i++) {
    arr[i] = s.substring(i, i + 1);
}

returning the output:

[ "b", "a", "r" ]


问:
How to change Highcharts xAxis formatting from yearly to monthly?
I have the following JSON Highcharts data:

```<code>"xAxis": {
      "type": "datetime",
      "dateTimeLabelFormats": {
        "month": "%b %y"
      },
      "labels": {
        "style": {
          "color": "#000000",
          "fontWeight": "normal",
          "font-size": "100%",
          "font-family": "sans-serif"
        }
      }
    },
</code>```

I want to split the xAxis into months but I am still getting the xAxis in years (2010, 2012, 2012 ...).

How do I change it to something like Jan 10, Feb 10, Mar 10... ?

答:
How highcharts appears to work is that it determines which time range to use (milliseconds, seconds, etc., all the way to years), and then checks THAT specific option for formatting.

So presumably your data is spread out far enough that it defaults to years, so to change the formatting it uses, you want to do "year": "%b %y".

Body:
I have the following JSON Highcharts data:

"xAxis": {
      "type": "datetime",
      "dateTimeLabelFormats": {
        "month": "%b %y"
      },
      "labels": {
        "style": {
          "color": "#000000",
          "fontWeight": "normal",
          "font-size": "100%",
          "font-family": "sans-serif"
        }
      }
    },

I want to split the xAxis into months but I am still getting the xAxis in years (2010, 2012, 2012 ...).

How do I change it to something like Jan 10, Feb 10, Mar 10... ?


问:
An array converting question
I have an array below,

```<code>var array = {
    "Id":[1,2,3],
    "Name":["one","two","five"],
    "row":[8,9,7]
}
</code>```

but I want to transform it into

```<code>var array2 =
{"data":
    [
    {"Id":1,"Name":"one","Row:8"},
    {"Id":2,"Name":"two","Row:9"},
    {"Id":3,"Name":"five","Row:7"},
    ]
}
</code>```

Is this possible?

答:
This should do it:</p>

```<code>// make sure the new object is initialized
var array2 = { data: [] };
// Count the number of items in array.Id and start iterating
for (var i=0,t=array.Id.length; i < t; i++) {
   // Note that array.Id = [1,2,3] does not result in corresponding keys
   // array.Id[0] corresponds to value 1!
   array2.data.push({
       Id: array.Id[i],
       Name: array.Name[i],
       Row: array.Row[i]
   });
}
</code>```

Title: An array converting question

Body:
I have an array below,

var array = {
    "Id":[1,2,3],
    "Name":["one","two","five"],
    "row":[8,9,7]
}

but I want to transform it into

var array2 =
{"data":
    [
    {"Id":1,"Name":"one","Row:8"},
    {"Id":2,"Name":"two","Row:9"},
    {"Id":3,"Name":"five","Row:7"},
    ]
}

Is this possible?

Body:
This should do it:

// make sure the new object is initialized
var array2 = { data: [] };
// Count the number of items in array.Id and start iterating
for (var i=0,t=array.Id.length; i < t; i++) {
   // Note that array.Id = [1,2,3] does not result in corresponding keys
   // array.Id[0] corresponds to value 1!
   array2.data.push({
       Id: array.Id[i],
       Name: array.Name[i],
       Row: array.Row[i]
   });
}


问:
Pandas isin() on column containing numbers separated by delimiters
I am trying to run an isin() on a column that contains multiple UID's that I would like to search for. I would like to search for the numbers separated by a delimiter (;).

I have provided an example of the dataframe.

```<code>import pandas as pd
import numpy as np

Data = {'UID': ['13', '234', '130', '1245', '1423', '321'],
        'Name': ['Bill', 'Bob', 'Joe', 'Tim', 'Rick', 'Mike'],
        'Score': ['1', '0', '0', '0', '1', '0'],
        'Friends_With': ['80', np.nan, '13;234', '1423;180;908', '130', '2345']}

df = pd.DataFrame(Data, columns= ['UID', 'Name', 'Score', 'Friends_With'])
</code>```

The "Friends_With" field contains the UID of each individual. I am able to search through the "Friends_With" of Bill, Rick and Mike because they only have one UID in their "Friends_With" field. However, I would like to look at the friends of Joe and Tim. Where Joe has 2 UID's in his "Friends_With" column and Mike has 3 UID's.

My end goal is, if an individual (Person1) with a "Score" of 0 is friends with another individual (Person2) with a "Score" of 1, I would like Person1's "Score" to be changed to 1 rather than 0.

Here is the code that I have tried, it works well for when there is only one UID in the "Friends_With" column.

```<code>df["Friendship Score"] = df["Friends_With"].isin(df["UID"])
</code>```

I am currently creating a new Boolean column because if I try something along the lines of the following I get a ValueError of, "The truth value of a Series is ambiguous."

```<code>if df["Friends_With"].isin(df["UID"]):
   df["Score"] = 1
</code>```

EDIT:
What would be the correct way to solve this problem when the dataset is millions of rows?

答:
Updated using dot with two for loops , notice this is o(nm) check

```<code>s=np.array([[y in x for y in df.UID ]for x  in df.Friends_With.fillna('No').str.split(';')]).dot(df.Score.astype(int))
df.loc[s==1,'Score']=s[s==1]
df
Out[201]:
    UID  Name Score  Friends_With
0    13  Bill     1            80
1   234   Bob     0           NaN
2   130   Joe     1        13;234
3  1245   Tim     1  1423;180;908
4  1423  Rick     1           130
5   321  Mike     0          2345
</code>```

Body:
I am trying to run an isin() on a column that contains multiple UID's that I would like to search for. I would like to search for the numbers separated by a delimiter (;).

I have provided an example of the dataframe.

import pandas as pd
import numpy as np

Data = {'UID': ['13', '234', '130', '1245', '1423', '321'],
        'Name': ['Bill', 'Bob', 'Joe', 'Tim', 'Rick', 'Mike'],
        'Score': ['1', '0', '0', '0', '1', '0'],
        'Friends_With': ['80', np.nan, '13;234', '1423;180;908', '130', '2345']}

df = pd.DataFrame(Data, columns= ['UID', 'Name', 'Score', 'Friends_With'])

The "Friends_With" field contains the UID of each individual. I am able to search through the "Friends_With" of Bill, Rick and Mike because they only have one UID in their "Friends_With" field. However, I would like to look at the friends of Joe and Tim. Where Joe has 2 UID's in his "Friends_With" column and Mike has 3 UID's.

My end goal is, if an individual (Person1) with a "Score" of 0 is friends with another individual (Person2) with a "Score" of 1, I would like Person1's "Score" to be changed to 1 rather than 0.

Here is the code that I have tried, it works well for when there is only one UID in the "Friends_With" column.

df["Friendship Score"] = df["Friends_With"].isin(df["UID"])

I am currently creating a new Boolean column because if I try something along the lines of the following I get a ValueError of, "The truth value of a Series is ambiguous."

if df["Friends_With"].isin(df["UID"]):
   df["Score"] = 1

EDIT:
What would be the correct way to solve this problem when the dataset is millions of rows?

Body:
Updated using dot with two for loops , notice this is o(nm) check

s=np.array([[y in x for y in df.UID ]for x  in df.Friends_With.fillna('No').str.split(';')]).dot(df.Score.astype(int))
df.loc[s==1,'Score']=s[s==1]
df
Out[201]:
    UID  Name Score  Friends_With
0    13  Bill     1            80
1   234   Bob     0           NaN
2   130   Joe     1        13;234
3  1245   Tim     1  1423;180;908
4  1423  Rick     1           130
5   321  Mike     0          2345


问:
How can I convert an image received through socket.io into an image in Unity?
I have a node.js server with socket.io communicating with a Unity application. A user can draw an image using Canvas on any browser and send it to other sockets (currently using toDataUrl). This sends an image in text which i can put into another browser and it will be able to represent it as an image.

The issue I am having is that I can't convert this so that it can appear on a SpriteRenderer in Unity.

I am able to get an image appearing through a regular URL using img.texture but currently the data isn't in a format that I understand how to work with.

How an image is sent through javascript:

photo: canvas.toDataURL()

Should I try using a different method to send the image other than toDataUrl?

An example of a string that I need to convert into a sprite renderer:
(Copy and paste the whole thing into a browser and a smiley face should appear)

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAcIAAAHCCAYAAAB8GMlFAAAJRklEQVR4nO3d0VEbSRcF4BOCQlAIZODJ4CcDk8GSwSqDJQOTwZIBk4HJADKADPQ/jFS4trBpIbV6NP19Vf3iKlMXmJpD3+k7SgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACACzEkeUzyuluPu38DgMXbJNn+Zm2aVQUAZzDk9yG4X0Oj2gCgujGfB+HYqDYAqO4tnwfha7PqAKCykiB8a1YdAFQ2RmsUgI4NcVgGgM5tYnwCgM4NmVqgb7s1xk4QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4FBDksckr7v1uPs3AFi8TZLtb9amWVUAcAZDfh+C+zU0qg0AqhvzeRCOjWoDgOre8nkQvjarDgAqKwnCt2bVAUBlY7RGAejYEIdlAOjcJsYnAOjckKkF+rZbY+wEAQAAAAAAAAAAZm+IT1MBoFP/xDgQAJ36ES+IAKBTJSHolYEALFZJCPo0FQAWqzQIfZoKAItUGoRjo/oAoKrSIBwa1QcA1axSHoQAsDhDykLwqVF9AFDVdTwfBKBjm5QF4V2j+gCgqruUBeGmUX0AUNWYsiC8blQfAFT1M0YnAOhY6ejEqlWBAFCLGUIAujbEDCEAHTNDCEDXNjFDCEDHzBAC0LUxZggB6JgZQgC6ZoYQgG5dxQwhAB0zOgFA1zYpC8L7NuUBQF0PMToBQMee48QoAB0rPSizblQfAFQzpCwE3xrVBwBV3cSJUQA6tomXbQPQsTFlQXjbqD4AqOo1TowC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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIBO/R8+u2EDBtiH6gAAAABJRU5ErkJggg==

Edit with all code currently:

public string url = "[encoded data, 20468 characters]";

```<code>  byte[] imageBytes = Convert.FromBase64String(url);
  Texture2D tex = new Texture2D(512, 512);
  tex.LoadImage( imageBytes );
  GetComponent<Renderer>().material.mainTexture = tex;
</code>```

答:
You'll need to convert it from Base64URL to regular Base64. Then, once you have the byte[] from using FromBase64String(base64);, you just need to create a Texture2D then LoadImage it into the texture:

```<code>byte[] imageBytes = FromBase64String(base64);
Texture2D tex = new Texture2D(512, 512);
tex.LoadImage(imageAsset.bytes);
GetComponent<Renderer>().material.mainTexture = tex;
</code>```

Body:
I have a node.js server with socket.io communicating with a Unity application. A user can draw an image using Canvas on any browser and send it to other sockets (currently using toDataUrl). This sends an image in text which i can put into another browser and it will be able to represent it as an image.

The issue I am having is that I can't convert this so that it can appear on a SpriteRenderer in Unity.

I am able to get an image appearing through a regular URL using img.texture but currently the data isn't in a format that I understand how to work with.

How an image is sent through javascript:

photo: canvas.toDataURL()

Should I try using a different method to send the image other than toDataUrl?

An example of a string that I need to convert into a sprite renderer:
(Copy and paste the whole thing into a browser and a smiley face should appear)

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAcIAAAHCCAYAAAB8GMlFAAAJRklEQVR4nO3d0VEbSRcF4BOCQlAIZODJ4CcDk8GSwSqDJQOTwZIBk4HJADKADPQ/jFS4trBpIbV6NP19Vf3iKlMXmJpD3+k7SgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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u8nT1/SPviOXY+/rH0bdr++5z1Av+Xw52tXu6/xT0439ycAAWZmnenzEh8yj+eKPa633e8AgBkYMp1AvYQ26hLWJk6CAszW/tnifewWT73uc5kHhAC6dhW7xWPXmGnXDcCFs1s8bD3FLCDAotktfhx+t9ECBejSOu8Hb+4ytQR72DkKPwA+NWRqq24yjW1c+i5yjPAD4ESuMgXlkCkoN3nfUY6Zx0sAxl1dw0m/cwA40CrvoTnkfZe5Xw95D9AxXw+9u93Xbv16NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIBO/R8+u2EDBtiH6gAAAABJRU5ErkJggg==

Edit with all code currently:

public string url = "[encoded data, 20468 characters]";

  byte[] imageBytes = Convert.FromBase64String(url);
  Texture2D tex = new Texture2D(512, 512);
  tex.LoadImage( imageBytes );
  GetComponent<Renderer>().material.mainTexture = tex;

Body:
You'll need to convert it from Base64URL to regular Base64. Then, once you have the byte[] from using FromBase64String(base64);, you just need to create a Texture2D then LoadImage it into the texture:

byte[] imageBytes = FromBase64String(base64);
Texture2D tex = new Texture2D(512, 512);
tex.LoadImage(imageAsset.bytes);
GetComponent<Renderer>().material.mainTexture = tex;


问:
How can I set data-content on hr:after in javascript?
I know you can add style to an element in javascript. E.g.

```<code>myElement.style.color = "red";
</code>```

But say I wanted to do the equivalent of

```<code>hr:after {
  content: "myRuntimeValue"
}
</code>```

How can I achieve that in javascript?

答:
:before and :after are not actual DOM-elements... so, you can't do anything with them from JS.

But you can create two classes, with different contents and styles, and toggle the class:

JsFiddle

document.getElementById('demo').addEventListener('click', function(){
  this.classList.remove('demo');
  this.classList.add('New-demo');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.demo:after {
  content: " myRuntimeValue";
  color: orange;
}
.New-demo:after {
  content: " Some New Bubu!";
  color: red;
}</code>```

Click Me!
```

With this trick, you can not only change the content, but add actual styles.

Body:
I know you can add style to an element in javascript. E.g.

myElement.style.color = "red";

But say I wanted to do the equivalent of

hr:after {
  content: "myRuntimeValue"
}

How can I achieve that in javascript?

Body:
:before and :after are not actual DOM-elements... so, you can't do anything with them from JS.

But you can create two classes, with different contents and styles, and toggle the class:

JsFiddle

document.getElementById('demo').addEventListener('click', function(){
  this.classList.remove('demo');
  this.classList.add('New-demo');
});

.demo:after {
  content: " myRuntimeValue";
  color: orange;
}
.New-demo:after {
  content: " Some New Bubu!";
  color: red;
}

<p id="demo" class="demo">Click Me!</p>

With this trick, you can not only change the content, but add actual styles.


问:
How can I dynamically add page breaks in jspdf, to prevent tables from breaking across two pages?
I am trying to create a web page that exports database information into a PDF, with tables that pull from a database with PHP and MySQL.

My tables have variable length, and can at times include more than one table, potentially up to 3+ tables.

In the case that the initial table would take up a large amount of space on a page, that the second table would break across to subsequent pages, how would I tell jspdf to go back to previous
 tag, and insert a -page break- before it? (i.e. if any row of table 2+ would break and move to the next page, move the entire table to the next page).

I've considered trying to crawl and count the
 tags to get a count, and trying to set an if-else statement to send the table to the next page, but I don't know how that would work for more than two tables.

```

答:
you should try jspdf autotable plugin.
https://github.com/simonbengtsson/jsPDF-AutoTable
and look at the examples for multiple tables</p>