问:
VueJS change font of specific row not all rows
Current code changes the font for all rows vs a specific row:

Vue.component('blog-post', {
  props: ['post'],
  template: `

 {{ post.title }}

      <button @click="$emit('enlarge-text')">Enlarge text</button>

  `,
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ],
    postFontSize : 1,
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}</code>```

  <blog-post v-for="post in posts" :post="post" :key="post.id" :style="{fontSize : postFontSize + 'em'}" @enlarge-text="postFontSize += 0.1"></blog-post>

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

<p>How can I just manipulate a specific row, one row, updating one row's font size vs all rows?</p>

<p>Tried the following but it did not work:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.component('blog-post', {
  props: ['post'],
  template: `
    <div class="blog-post row" :style="{fontSize : postFontSize + 'em'}" @enlarge-text="postFontSize += 0.1">
      <h3 class="cell">{{ post.title }}</h3>
      <button @click="$emit('enlarge-text')">Enlarge text</button>
      <div v-html="post.content" class="cell"></div>
    </div>
  `,
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ],
    postFontSize : 1,
  }
})</code>```

.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js"></script>

<div id="blog-post-demo">
  <blog-post v-for="post in posts" :post="post" :key="post.id"></blog-post>
</div></code>```

答:
The reason your first code snippet does not work is because you placed the postFontSize variable at its parent component. That's why all children component will share the same variable, meaning one changes in variable will affect every child.

To fix the problem, simply move all variables related to blog-post component into blog-post component (not in its parent component).

This includes postFontSize, @click method, and :style declaraction:

Vue.component('blog-post', {
  template: `

{{ post.title }}

      <button @click="enlargeText">Enlarge text</button>

  `,
  props: ['post'],
  data: function(){
    return {
      postFontSize: 1
    }
  },
  methods: {
    enlargeText: function(){
      this.postFontSize += 0.1;
    }
  }
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ]
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}</code>```

  <blog-post v-for="post in posts" :post="post" :key="post.id"></blog-post>

```

Body:
Current code changes the font for all rows vs a specific row:

Vue.component('blog-post', {
  props: ['post'],
  template: `

 {{ post.title }}

      <button @click="$emit('enlarge-text')">Enlarge text</button>

  `,
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ],
    postFontSize : 1,
  }
});

.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}

  <blog-post v-for="post in posts" :post="post" :key="post.id" :style="{fontSize : postFontSize + 'em'}" @enlarge-text="postFontSize += 0.1"></blog-post>

How can I just manipulate a specific row, one row, updating one row's font size vs all rows?

Tried the following but it did not work:

Vue.component('blog-post', {
  props: ['post'],
  template: `

{{ post.title }}

      <button @click="$emit('enlarge-text')">Enlarge text</button>

  `,
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ],
    postFontSize : 1,
  }
})

.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}

  <blog-post v-for="post in posts" :post="post" :key="post.id"></blog-post>

Body:
The reason your first code snippet does not work is because you placed the postFontSize variable at its parent component. That's why all children component will share the same variable, meaning one changes in variable will affect every child.

To fix the problem, simply move all variables related to blog-post component into blog-post component (not in its parent component).

This includes postFontSize, @click method, and :style declaraction:

Vue.component('blog-post', {
  template: `
    <div class="blog-post row" :style="{ fontSize: postFontSize + 'em' }">
      <h3 class="cell">{{ post.title }}</h3>
      <button @click="enlargeText">Enlarge text</button>
      <div v-html="post.content" class="cell"></div>
    </div>
  `,
  props: ['post'],
  data: function(){
    return {
      postFontSize: 1
    }
  },
  methods: {
    enlargeText: function(){
      this.postFontSize += 0.1;
    }
  }
});

new Vue({
  el   : '#blog-post-demo',
  data : {
    posts : [
      {id: 1, title : 'My Journey to Africa',    content : 'I am the post'},
      {id: 2, title : 'My Journey to America',   content : 'I am the post'},
      {id: 3, title : 'My Journey to Antartica', content : 'I am the post'},
      {id: 4, title : 'My Journey to Asia',      content : 'I am the post'},
    ]
  }
});

.row {
  background-color: cyan;
}

.cell {
  background-color: antiquewhite;
}

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js"></script>

<div id="blog-post-demo">
  <blog-post v-for="post in posts" :post="post" :key="post.id"></blog-post>
</div>


来源: stackexchange

问:
Problem with GetElementIds() to get current selection
I have a small code to extract current selection from revit but I get an error saying expected selection ,got list[elementId]

I also tried passing GetElementIds() as in the API but it says it takes excatly 1 argument(0 given)

```<code>import clr
import System
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI.Selection import *

clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)

clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager

# Import iron python packages
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)

app = __revit__.Application
doc = __revit__.ActiveUIDocument.Document

#get current selection from Document

from Autodesk.Revit.UI import Selection
from System.Collections.Generic import List as CL

sel = CL[ElementId]()
Selected=Selection.Selection.GetElementIds()
print(len(Selected))
</code>```

答:
the error in in this line of code:

```<code>Selected=Selection.Selection.GetElementIds()
</code>```

You need to add a link to the ui, then you can use it to get the selection:

```<code>ui = __revit__.ActiveUIDocument
Selected=ui.Selection.GetElementIds()
</code>```

Here is a full code that will fetch the users selection:

```<code>import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
app = __revit__.Application
doc = __revit__.ActiveUIDocument.Document
ui = __revit__.ActiveUIDocument

selectedElements = []
for elementId in ui.Selection.GetElementIds():
    selectedElements.Add(doc.GetElement(elementId))

for item in selectedElements:
    print item
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a small code to extract current selection from revit but I get an error saying expected selection ,got list[elementId]

I also tried passing GetElementIds() as in the API but it says it takes excatly 1 argument(0 given)

import clr
import System
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *

clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI.Selection import *

clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)

clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager

# Import iron python packages
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)

app = __revit__.Application
doc = __revit__.ActiveUIDocument.Document

#get current selection from Document

from Autodesk.Revit.UI import Selection
from System.Collections.Generic import List as CL

sel = CL[ElementId]()
Selected=Selection.Selection.GetElementIds()
print(len(Selected))

Body:
the error in in this line of code:

Selected=Selection.Selection.GetElementIds()

You need to add a link to the ui, then you can use it to get the selection:

ui = __revit__.ActiveUIDocument
Selected=ui.Selection.GetElementIds()

Here is a full code that will fetch the users selection:

import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
app = __revit__.Application
doc = __revit__.ActiveUIDocument.Document
ui = __revit__.ActiveUIDocument

selectedElements = []
for elementId in ui.Selection.GetElementIds():
    selectedElements.Add(doc.GetElement(elementId))

for item in selectedElements:
    print item


问:
AWS iot boto3 - how to get a certificate attached to a thing?
What is the best way to get a certificate arn attached to a thing? AWS documentation doesnt have a method to get the certificate attached to a particular thing.</p>

答: oops I found it. It is [list_thing_principals][1] https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iot.html#IoT.Client.list_thing_principals</p>


问:
set html text color and size using javascript
Suppose I have the following line of code in html, how to set the text color and size inside "MonitorInformation" DIV element in a programming way using Javascript in an easy way? Sorry for my stupid, I figured a long time but cannot figure out. :-(

```<code><div id="MonitorInformation">Connecting...wait</div>
</code>```

thanks in advance,
George

答:
```<code>const Monitorinfo = document.queryselector('MonitorInformation');

Monitorinfo.style.color = 'red';
Monitorinfo.style.fontSize = '20px';
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Suppose I have the following line of code in html, how to set the text color and size inside "MonitorInformation" DIV element in a programming way using Javascript in an easy way? Sorry for my stupid, I figured a long time but cannot figure out. :-(

Connecting...wait

thanks in advance,
George


问:
how to transcribe a long audio file in swift using ibm cloud?
I have a 10mb and split it into 4mb(frame size limit)  3 parts and then send 3 calls of:

```<code>                    speechToText.recognizeUsingWebSocket(audio: chunkData, settings: settings, callback: callback)
</code>```

but time stamps aren't consistent it gets reset to 0.0 for each call.
What's the proper way?

答: you are making three separate calls to the STT service, that is why the timestamps reset. You need to send the 10MBs within the same call.</p>

Body:
I have a 10mb and split it into 4mb(frame size limit)  3 parts and then send 3 calls of:

                    speechToText.recognizeUsingWebSocket(audio: chunkData, settings: settings, callback: callback)

but time stamps aren't consistent it gets reset to 0.0 for each call.
What's the proper way?


问:
Convert PHP variable to JQuery
Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery

View:

```<code><?php
    foreach ($muziek as $ms)
    {
        if ($ms->id == 2) {
            echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
            echo '</audio>';
        }
    }

    foreach ($muziek as $ms)
    {
        echo '<br>';
        echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
    }
?>
</div>

<script>
    $("input").click(function () {
       var test = $(this).attr("id");
       console.log(test);
       //Here needs to be the foreach muziek
    });
</script>
</code>```

Muziek variable:
This is how i fill the music variable

```<code>function getAllMuziek()
{
    $query = $this->db->get('muziek');
    $muziek = $query->result();

    return $muziek;
}
</code>```

Does someone has an idea or show me how this can be done?

答:
I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:

```<code>$.get( "base_url/your_controller/getAllMuziek" )
    .done(function( muziek ) {
        //Here needs to be the foreach muziek
        $.each(muziek, function( index, value ) {
            // whatever
        });
    });
</code>```

with a simple modification to your method getAllMuziek:

```<code>function getAllMuziek()
{
    $query = $this->db->get('muziek');
    $muziek = $query->result();

    header('Content-Type: application/json');
    echo json_encode($muziek);
}
</code>```

now when you make you ajax call you will get your result.

Title: Convert PHP variable to JQuery

Body:
Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery

View:

<?php
    foreach ($muziek as $ms)
    {
        if ($ms->id == 2) {
            echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
            echo '</audio>';
        }
    }

    foreach ($muziek as $ms)
    {
        echo '
';
        echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
    }
?>

Muziek variable:
This is how i fill the music variable

function getAllMuziek()
{
    $query = $this->db->get('muziek');
    $muziek = $query->result();

    return $muziek;
}

Does someone has an idea or show me how this can be done?

Body:
I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:

$.get( "base_url/your_controller/getAllMuziek" )
    .done(function( muziek ) {
        //Here needs to be the foreach muziek
        $.each(muziek, function( index, value ) {
            // whatever
        });
    });

with a simple modification to your method getAllMuziek:

function getAllMuziek()
{
    $query = $this->db->get('muziek');
    $muziek = $query->result();

    header('Content-Type: application/json');
    echo json_encode($muziek);
}

now when you make you ajax call you will get your result.


问:
AWS Kinesis sequence numbers
I have a kinesis consumer which is running from past 3 days..but still it didn't read the producer data

Producer put the data at sequence number -> 49593554362799306497476712297116585830001273292214763522

and consumer is reading at -> 49592407930728695436502186699740292765095159714163982338

Can anyone help me in understanding these sequence numbers ?

答: I suspect your consumer started reading at LATEST position after records have been already produced. Try changing it to TRIM_HORIZON. Check AWS docs for details: https://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html</p>

Title: AWS Kinesis sequence numbers


问:
Create shadow around a UIVisualEffectView without covering the whole view
Is it possible to create a shadow around a UIVisualView with UIBlurEffect without letting the UIVisualView get coloured by the shadow underneath?

I basically just want the shadow around the view but with this code the shadow will cover the whole view which darkens the whole view to much:

```<code>let borderPath = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 15, height: 15)).cgPath

shadowView.frame = view.bounds
shadowView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
shadowView.layer.shadowOpacity = 0.3
shadowView.layer.shadowRadius = 3.0
shadowView.backgroundColor = UIColor.clear

shadowView.layer.shadowPath = borderPath
shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
self.view.insertSubview(shadowView, at: 0)

let blurEffect = UIBlurEffect(style: .extraLight)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = view.bounds
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurView.clipsToBounds = true
blurView.layer.cornerRadius = 15
view.insertSubview(blurView, aboveSubview: shadowView)
</code>```

EDIT.

I need to achieve the same thing as in Apple's Maps application. Where the draggable favourite view both uses the UIVisualEffectView and a shadow around its top, without interfering with the UIVisualEffectView's background.

See example screenshots:

答:
I usually solve this kind of situation using composition of views. Instead of setting the shadow in the target view, I create a ShadowView and I put it behind the target view, both views with the same frame.

I've posted and example and code in this question.

An example of the result of this approach is the following:

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to create a shadow around a UIVisualView with UIBlurEffect without letting the UIVisualView get coloured by the shadow underneath?

I basically just want the shadow around the view but with this code the shadow will cover the whole view which darkens the whole view to much:

let borderPath = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 15, height: 15)).cgPath

shadowView.frame = view.bounds
shadowView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
shadowView.layer.shadowOpacity = 0.3
shadowView.layer.shadowRadius = 3.0
shadowView.backgroundColor = UIColor.clear

shadowView.layer.shadowPath = borderPath
shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
self.view.insertSubview(shadowView, at: 0)

let blurEffect = UIBlurEffect(style: .extraLight)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = view.bounds
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurView.clipsToBounds = true
blurView.layer.cornerRadius = 15
view.insertSubview(blurView, aboveSubview: shadowView)

EDIT.

I need to achieve the same thing as in Apple's Maps application. Where the draggable favourite view both uses the UIVisualEffectView and a shadow around its top, without interfering with the UIVisualEffectView's background.

See example screenshots:


问:
Why my jQuery ajax call is not successful
I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:

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

            alert(data);

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

I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.

I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.

Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?

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

Hi, I changed to use localhost request like:

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

                alert(data);

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

But I got the same error... more suggestions please... thank you.

答: Javascript is subject to the same origin policy. Your script running on localhost can't access COMPANY_DOMAIN.com.  </p>

Body:
I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:

$.ajax({
        url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
        type: 'GET',
        async: false,
        dataType: 'application/xml',
        data: {id: 43},
        success: function(data) {

            alert(data);

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

I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.

I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.

Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?

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

Hi, I changed to use localhost request like:

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

                alert(data);

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

But I got the same error... more suggestions please... thank you.


问:
Create a dictionary of generic variables in swift
I'm looking for a way to store a generics subclass in a dictionary but I'm having problems.

In the following example I'm trying to create a dictionary of objects that I know will subclass Entity<T>. I'm successfully storing single instances of my sub classes FloatEntity and StringEntity in an Entity type var but when I try to store the same in a dictionary of type Dictionary<String, Entity> I get an error.

class Entity<T> {
    var _value: T
    var value: T { get { return _value } set {_value = newValue}}

    init (defaultValue: T) {
        _value = defaultValue
    }
}

class FloatEntity: Entity<Float> {
}

class StringEntity: Entity<String> {
}

func run () {
    let variable1: Entity = FloatEntity (defaultValue: 1)
    let variable2: Entity = StringEntity (defaultValue: "")
    var dictionary: Dictionary<String, Entity> = [
        "One": FloatEntity (defaultValue: 1),
        "Two": StringEntity (defaultValue: ""),
    ]
    print (variable1)
    print (variable2)
    print (dictionary)
}
```

The error:

Cannot convert value of type 'FloatEntitiy' to expected dictionary value
  type 'Entity'

Can anyone advise on how I might go about using a dictionary to store generics like this?

答:
From what you've provided so far, this is not looking like a good use of a generic. If the idea is to store values in a dictionary where each value might be a string or might be a float, that sounds like more like an enum with associated values (this is playground code):

```<code>enum StringOrFloat {
    case string(String)
    case float(Float)
}
let v1 = StringOrFloat.string("meaning of life")
let v2 = StringOrFloat.float(42)
var d = Dictionary<String,StringOrFloat>()
d["hey"] = v1
d["ho"] = v2
</code>```

And here's a way of extracting a value:

```<code>if let val = d["hey"] {
    switch val {
    case .string(let s):
        print("it is a string, namely", s)
    case .float(let f):
        print("it is a float, namely", f)
    }
}
</code>```

Body:
I'm looking for a way to store a generics subclass in a dictionary but I'm having problems.

In the following example I'm trying to create a dictionary of objects that I know will subclass Entity<T>. I'm successfully storing single instances of my sub classes FloatEntity and StringEntity in an Entity type var but when I try to store the same in a dictionary of type Dictionary<String, Entity> I get an error.

class Entity<T> {
    var _value: T
    var value: T { get { return _value } set {_value = newValue}}

    init (defaultValue: T) {
        _value = defaultValue
    }
}

class FloatEntity: Entity<Float> {
}

class StringEntity: Entity<String> {
}

func run () {
    let variable1: Entity = FloatEntity (defaultValue: 1)
    let variable2: Entity = StringEntity (defaultValue: "")
    var dictionary: Dictionary<String, Entity> = [
        "One": FloatEntity (defaultValue: 1),
        "Two": StringEntity (defaultValue: ""),
    ]
    print (variable1)
    print (variable2)
    print (dictionary)
}

The error:

Cannot convert value of type 'FloatEntitiy' to expected dictionary value
  type 'Entity'

Can anyone advise on how I might go about using a dictionary to store generics like this?

Body:
From what you've provided so far, this is not looking like a good use of a generic. If the idea is to store values in a dictionary where each value might be a string or might be a float, that sounds like more like an enum with associated values (this is playground code):

enum StringOrFloat {
    case string(String)
    case float(Float)
}
let v1 = StringOrFloat.string("meaning of life")
let v2 = StringOrFloat.float(42)
var d = Dictionary<String,StringOrFloat>()
d["hey"] = v1
d["ho"] = v2

And here's a way of extracting a value:

if let val = d["hey"] {
    switch val {
    case .string(let s):
        print("it is a string, namely", s)
    case .float(let f):
        print("it is a float, namely", f)
    }
}


问:
Does the Filemaker API implement caching for _find requests or portalData requests?
I am rewriting an application which uses a Filemaker database.  Historically, a PHP script had a PHP SDK connection to Filemaker.  I am converting it to use the Filemaker 17 API.

During development I am creating a new record, and then displaying a list of records.  After creating a new record, the old system (using the PHP SDK) will display the updated list immediately.  The new system I'm developing will not.

After a few minutes, the new system (using the Filemaker 17 API) will show the correct list.  It seems to take 5-10 minutes.

All of this is happening through the use of portals.

I'm using the Symfony PHP framework.  I've tried clearing the Symfony cache.

I've also tried appending a UNIX timestamp to the _find URL of the API call.  It still returns me a list, but it's a stale list.

I'm using the 'cache-control: no-cache' cURL option, as well.

I've scoured the FM 17 API documentation, but can't find anything pertinent.

Is there a cache that the FM API implements?  If so, how do you disable that?

I expect the list to update immediately through the FM 17 API.

-- Updated --

If I manually update the record containing the portal data, the list returned from the API works instantly.  Is portal data cached?

答:
To ensure there is fresh data you could close the API session and start a new session.

When your code is done accessing the hosted database, use an HTTP
  DELETE method with the sessions URL specifying the name of the hosted
  database and the access token for the session. If your code does not
  log out of the database session, the access token becomes invalid when
  the FileMaker Data API session times out 15 minutes after the last
  call that specified the token.

https://fmhelp.filemaker.com/docs/17/en/dataapi/index.html#write-fm-data-api-calls_connect-database_log-out

Or as part of your find you could run a script in the script.pre-request as part of your _find that will refresh the portals on the layout.  E.g. using the "Refresh Portal" script step. The "caching" behaviour that you see may just be that the layout is not updating for that Data API session, and the layout needs updating.

You can run FileMaker scripts as part of the find request by including the
  script.prerequest, script.presort, and script parameters in the
  request body.

https://fmhelp.filemaker.com/docs/17/en/dataapi/index.html#perform-a-find-request

You could also do a find directly on the Events table using your Person Key.

Also as a final note, if there is some sort of uncommitted record somewhere, from an API script call that doesn't finish with a commit, or otherwise, then the data may not be showing in the portal yet.

(Note answer edited with fresh information)


问:
SQL Like or REGEXP filter results even when everything should be matched
this is what i have

```<code>SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
  AND product.field_sockel_value REGEXP '.*'
  AND product.field_artikel_value REGEXP '.*'
  AND product.field_leistung_value REGEXP '.*'
  AND product.field_licht_farbe_value REGEXP '.*'
  AND product.field_rubrik_value REGEXP '.*'
  AND product.field_artikelgruppe_value REGEXP '.*'
ORDER BY product.field_artikel_value
</code>```

Having these where-conditions I would assume that this gives the same results as:

```<code>SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
ORDER BY product.field_artikel_value
</code>```

But it does not. The first returns 494 rows and the last one gives 717. So there's missing a bunch of rows. When I use this query

```<code>SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
  AND product.field_artikel_value REGEXP '.*'
  AND product.field_leistung_value REGEXP '.*'
  AND product.field_rubrik_value REGEXP '.*'
  AND product.field_artikelgruppe_value REGEXP '.*'
ORDER BY product.field_artikel_value
</code>```

I also do get 717 rows. So… what could it be that makes those removed conditions so special? The columns are all of type longtext (because the cms does so) and have the exact same attributes.

BTW i noticed the same behavior when using LIKE instead of REGEXP.

答: Since you have a LEFT JOIN you also get lines where product.field_sockel_value or product.field_licht_farbe_value is NULL. These line got filtered in the WHERE clause

Body:
this is what i have

SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
  AND product.field_sockel_value REGEXP '.*'
  AND product.field_artikel_value REGEXP '.*'
  AND product.field_leistung_value REGEXP '.*'
  AND product.field_licht_farbe_value REGEXP '.*'
  AND product.field_rubrik_value REGEXP '.*'
  AND product.field_artikelgruppe_value REGEXP '.*'
ORDER BY product.field_artikel_value

Having these where-conditions I would assume that this gives the same results as:

SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
ORDER BY product.field_artikel_value

But it does not. The first returns 494 rows and the last one gives 717. So there's missing a bunch of rows. When I use this query

SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
  AND product.field_artikel_value REGEXP '.*'
  AND product.field_leistung_value REGEXP '.*'
  AND product.field_rubrik_value REGEXP '.*'
  AND product.field_artikelgruppe_value REGEXP '.*'
ORDER BY product.field_artikel_value

I also do get 717 rows. So… what could it be that makes those removed conditions so special? The columns are all of type longtext (because the cms does so) and have the exact same attributes.

BTW i noticed the same behavior when using LIKE instead of REGEXP.


问:
How to format an Array of Arrays of Object in JS
I want to formatting this Array in a computed property in VueJS, but I have one problem in the moment to access to newArray, all of elements in one only array

```<code>getNewArray(){
const newArray = []
const = this.data.map(item =>{
    for(let i in item){
       newArray.push(item.value)
  }
return newArray
})
}
</code>```

```<code>data:[
    [
    {idStatus: 2, value: '120'},
    {idStatus: 3, value: '130'},
    {idStatus: 4, value: '140'},
    {idStatus: 5, value: '150'}
    ],
    [
    {idStatus: 1, value: '160'},
    {idStatus: 2, value: '180'},
    {idStatus: 4, value: '10'},
    {idStatus: 5, value: '20'}
    ],
    [
    {idStatus: 3, value: '567'},
    {idStatus: 6, value: '234'},
    {idStatus: 9, value: '747'},
    {idStatus: 7, value: '789'}
    ],
    [
    {idStatus: 8, value: '340'},
    {idStatus: 5, value: '560'},
    {idStatus: 6, value: '120'},
    {idStatus: 2, value: '100'}
    ],
    [
    {idStatus: 1, value: '106'},
    {idStatus: 5, value: '345'},
    {idStatus: 7, value: '756'},
    {idStatus: 9, value: '946'}
    ]
    ]
</code>```

The result that I want to obtain is this

```<code>    data:[
    [120,130,140,150],
    [160,180,10,20],
    [567,234,747,789],
    [340,560,120,100],
    [106,345,756,946]
    ]
</code>```

答:
Use map:

const data = [[{idStatus:2,value:'120'},{idStatus:3,value:'130'},{idStatus:4,value:'140'},{idStatus:5,value:'150'}],[{idStatus:1,value:'160'},{idStatus:2,value:'180'},{idStatus:4,value:'10'},{idStatus:5,value:'20'}],[{idStatus:3,value:'567'},{idStatus:6,value:'234'},{idStatus:9,value:'747'},{idStatus:7,value:'789'}],[{idStatus:8,value:'340'},{idStatus:5,value:'560'},{idStatus:6,value:'120'},{idStatus:2,value:'100'}],[{idStatus:1,value:'106'},{idStatus:5,value:'345'},{idStatus:7,value:'756'},{idStatus:9,value:'946'}]];
const res = data.map(e => e.map(({ value }) => value));
console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Body:
I want to formatting this Array in a computed property in VueJS, but I have one problem in the moment to access to newArray, all of elements in one only array

getNewArray(){
const newArray = []
const = this.data.map(item =>{
    for(let i in item){
       newArray.push(item.value)
  }
return newArray
})
}

data:[
    [
    {idStatus: 2, value: '120'},
    {idStatus: 3, value: '130'},
    {idStatus: 4, value: '140'},
    {idStatus: 5, value: '150'}
    ],
    [
    {idStatus: 1, value: '160'},
    {idStatus: 2, value: '180'},
    {idStatus: 4, value: '10'},
    {idStatus: 5, value: '20'}
    ],
    [
    {idStatus: 3, value: '567'},
    {idStatus: 6, value: '234'},
    {idStatus: 9, value: '747'},
    {idStatus: 7, value: '789'}
    ],
    [
    {idStatus: 8, value: '340'},
    {idStatus: 5, value: '560'},
    {idStatus: 6, value: '120'},
    {idStatus: 2, value: '100'}
    ],
    [
    {idStatus: 1, value: '106'},
    {idStatus: 5, value: '345'},
    {idStatus: 7, value: '756'},
    {idStatus: 9, value: '946'}
    ]
    ]

The result that I want to obtain is this

    data:[
    [120,130,140,150],
    [160,180,10,20],
    [567,234,747,789],
    [340,560,120,100],
    [106,345,756,946]
    ]

Body:
Use map:

const data = [[{idStatus:2,value:'120'},{idStatus:3,value:'130'},{idStatus:4,value:'140'},{idStatus:5,value:'150'}],[{idStatus:1,value:'160'},{idStatus:2,value:'180'},{idStatus:4,value:'10'},{idStatus:5,value:'20'}],[{idStatus:3,value:'567'},{idStatus:6,value:'234'},{idStatus:9,value:'747'},{idStatus:7,value:'789'}],[{idStatus:8,value:'340'},{idStatus:5,value:'560'},{idStatus:6,value:'120'},{idStatus:2,value:'100'}],[{idStatus:1,value:'106'},{idStatus:5,value:'345'},{idStatus:7,value:'756'},{idStatus:9,value:'946'}]];
const res = data.map(e => e.map(({ value }) => value));
console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }


问:
How effective to override the default Threadpool executor for Spring webflux project?
I am new to Spring-Webflux.

I am running the below sample project in a 2 - core processor. My RESTful api will call to an external api and the external api response is less than 500ms.

When i using jMeter for load testing, can't achieve more than 15 TPS.

Am i missing something or anything wrong with the below design?

How effective it's to override the default Threadpool executor in Webflux project?

Thank you in advance.

Controller

```<code>public class LookupController {

    @Autowired
    private LookupService lookupService;

    @PostMapping(value = "/findOrder")
    public Mono findOrder(@RequestBody InputBean inputBean) {

        return lookupService.findOrder(inputBean)
                .map(resp -> ResponseEntity.ok(resp))
                .defaultIfEmpty(ResponseEntity.notFound().build());
    }
}
</code>```

Service

```<code>@Service
public class LookupService {

    @Autowired
    private RestWorker restWorker;

    public Mono findOrder(InputBean inputBean) {
        ..//Basic Validation
        ApiBean apiBean = restWorker.buildApiBean(inputBean);
        Mono responseStr = restWorker.callApi(apiBean);
        return responseStr.flatMap(resp -> {
            //Business Logic
            //Process the api response and create the corresponding Controller Response
            return Mono.just(controllerResponse);
        });
    }
}
</code>```

Helper

```<code>@Component
public class RestWorker {

    private Webclient webClient = null;

    @PostConstruct
    private void initWorker() {
        webClient = WebClient.builder()
                .baseUrl(httpUrl)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .defaultHeader(HttpHeaders.ACCEPT, "application/json")
                .defaultHeader(HttpHeaders.ACCEPT_CHARSET, "UTF-8")
                .build();
    }

    public ApiBean buildApiBean(InputBean inputBean) {
    // Create ApiBean based on the input bean + config values
    ....
        return apiBean;
    }

    public Mono callApi(ApiBean apiBean) {
        Mono responseMonoStr = null;
        try {
            responseMonoStr = webClient.post()
                    .uri(url_tibco)
                    .body(BodyInserters.fromObject(reqDoc))
                    .exchange()
                    .timeout(Duration.ofMillis(socketReadTimeout))
                    .flatMap(clientResponse -> {
                        System.out.println(Thread.currentThread().getName() + "Status Code : " + clientResponse.statusCode());
                        return clientResponse.bodyToMono(String.class);
                    });
        } catch (Exception exception) {
            return Mono.just("");
        }
    }
}
</code>```

答:
Brian Clozel,

Thank you so much. Non-blocking api is working based on event loop with small number of threads. But, when am sending some parallel requests it opens 2 different threads like reactor-http-nio-2, reactor-http-nio-3..

Why it opening different threads on each parallel request?

Body:
I am new to Spring-Webflux.

I am running the below sample project in a 2 - core processor. My RESTful api will call to an external api and the external api response is less than 500ms.

When i using jMeter for load testing, can't achieve more than 15 TPS.

Am i missing something or anything wrong with the below design?

How effective it's to override the default Threadpool executor in Webflux project?

Thank you in advance.

Controller

public class LookupController {

    @Autowired
    private LookupService lookupService;

    @PostMapping(value = "/findOrder")
    public Mono findOrder(@RequestBody InputBean inputBean) {

        return lookupService.findOrder(inputBean)
                .map(resp -> ResponseEntity.ok(resp))
                .defaultIfEmpty(ResponseEntity.notFound().build());
    }
}

Service

@Service
public class LookupService {

    @Autowired
    private RestWorker restWorker;

    public Mono findOrder(InputBean inputBean) {
        ..//Basic Validation
        ApiBean apiBean = restWorker.buildApiBean(inputBean);
        Mono responseStr = restWorker.callApi(apiBean);
        return responseStr.flatMap(resp -> {
            //Business Logic
            //Process the api response and create the corresponding Controller Response
            return Mono.just(controllerResponse);
        });
    }
}

Helper

@Component
public class RestWorker {

    private Webclient webClient = null;

    @PostConstruct
    private void initWorker() {
        webClient = WebClient.builder()
                .baseUrl(httpUrl)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .defaultHeader(HttpHeaders.ACCEPT, "application/json")
                .defaultHeader(HttpHeaders.ACCEPT_CHARSET, "UTF-8")
                .build();
    }

    public ApiBean buildApiBean(InputBean inputBean) {
    // Create ApiBean based on the input bean + config values
    ....
        return apiBean;
    }

    public Mono callApi(ApiBean apiBean) {
        Mono responseMonoStr = null;
        try {
            responseMonoStr = webClient.post()
                    .uri(url_tibco)
                    .body(BodyInserters.fromObject(reqDoc))
                    .exchange()
                    .timeout(Duration.ofMillis(socketReadTimeout))
                    .flatMap(clientResponse -> {
                        System.out.println(Thread.currentThread().getName() + "Status Code : " + clientResponse.statusCode());
                        return clientResponse.bodyToMono(String.class);
                    });
        } catch (Exception exception) {
            return Mono.just("");
        }
    }
}


问:
Is there any way to get the hashcode of an InputStream using Guava?
Is there a way to get the HashCode of an InputStream in Java,
I am trying to upload a picture using the
 from PrimeFaces, converting it into a HashCode and comparing it to another picture.

At the moment I'm trying this:

```<code>public void save(FileUploadEvent event) throws IOException {
        HashCode hashCode = null;
        HashCode hashCodeCompare = null;
        hashCode = Files.asByteSource(new File(event.toString())).hash(Hashing.murmur3_128(50));
        hashCodeCompare = Files.asByteSource(new File(FilePathOfFileToCompare)).hash(Hashing.murmur3_128(50));
        boolean hashTrueFalse;
        if(hashCode.equals(hashCodeCompare)) {
            System.out.println("true");
        } else{
            System.out.println("false");
        }

        try (InputStream input = event.getFile().getInputstream()) {
            String imageName = generateFileName() + "." + fileExtensions(event.getFile().getFileName());
            String imageLink = PICTURE_DESTINATION + "\\" + imageName;

            Picture picture = new Picture();
            picture.setPictureUrl(imageLink);
            pictureService.createOrUpdate(picture);

            personForm.getCurrentPersonDTO().setPictureDTO(pictureMapper.toDTO(picture));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

Is there any way to turn the InputStream into a hashcode?

答: I would suggest to use   Files.asByteSource(fileSource.getFile()).hash(hashFunction).padToLong()

Body:
Is there a way to get the HashCode of an InputStream in Java,
I am trying to upload a picture using the
 from PrimeFaces, converting it into a HashCode and comparing it to another picture.

At the moment I'm trying this:

public void save(FileUploadEvent event) throws IOException {
        HashCode hashCode = null;
        HashCode hashCodeCompare = null;
        hashCode = Files.asByteSource(new File(event.toString())).hash(Hashing.murmur3_128(50));
        hashCodeCompare = Files.asByteSource(new File(FilePathOfFileToCompare)).hash(Hashing.murmur3_128(50));
        boolean hashTrueFalse;
        if(hashCode.equals(hashCodeCompare)) {
            System.out.println("true");
        } else{
            System.out.println("false");
        }

        try (InputStream input = event.getFile().getInputstream()) {
            String imageName = generateFileName() + "." + fileExtensions(event.getFile().getFileName());
            String imageLink = PICTURE_DESTINATION + "\\" + imageName;

            Picture picture = new Picture();
            picture.setPictureUrl(imageLink);
            pictureService.createOrUpdate(picture);

            personForm.getCurrentPersonDTO().setPictureDTO(pictureMapper.toDTO(picture));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Is there any way to turn the InputStream into a hashcode?


答:
You should not use for .. in for array iteration #Ref

You can change your original code to this, by fixing following problems

You're pushing value to same newArray every-time whereas you have to create a new variable every-time inside map

You're not returning anything from your function

let data =[[{idStatus: 2, value: '120'},{idStatus: 3, value: '130'},{idStatus: 4, value: '140'},{idStatus: 5, value: '150'}],[{idStatus: 1, value: '160'},{idStatus: 2, value: '180'},{idStatus: 4, value: '10'},{idStatus: 5, value: '20'}],[{idStatus: 3, value: '567'},{idStatus: 6, value: '234'},{idStatus: 9, value: '747'},{idStatus: 7, value: '789'}],[{idStatus: 8, value: '340'},{idStatus: 5, value: '560'},{idStatus: 6, value: '120'},{idStatus: 2, value: '100'}],[{idStatus: 1, value: '106'},{idStatus: 5, value: '345'},{idStatus: 7, value: '756'},{idStatus: 9, value: '946'}]]

function getNewArray(){
const final = data.map(item =>{
    const newArray = []
    for(let i of item){
       newArray.push(i.value)
    }
    return newArray
})
return final
}

console.log(getNewArray())```
</div>
</div>
</p>

<p>You can use map twice</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let data = {data:[[{idStatus: 2, value: '120'},{idStatus: 3, value: '130'},{idStatus: 4, value: '140'},{idStatus: 5, value: '150'}],[{idStatus: 1, value: '160'},{idStatus: 2, value: '180'},{idStatus: 4, value: '10'},{idStatus: 5, value: '20'}],[{idStatus: 3, value: '567'},{idStatus: 6, value: '234'},{idStatus: 9, value: '747'},{idStatus: 7, value: '789'}],[{idStatus: 8, value: '340'},{idStatus: 5, value: '560'},{idStatus: 6, value: '120'},{idStatus: 2, value: '100'}],[{idStatus: 1, value: '106'},{idStatus: 5, value: '345'},{idStatus: 7, value: '756'},{idStatus: 9, value: '946'}]]}

function getNewArray(){
const final= data.data.map(val=> val.map(({value})=>value))
return final
}

console.log(getNewArray())</code>```

Title: How to format an Array of Arrays of Object in JS

Body:
You should not use for .. in for array iteration #Ref

You can change your original code to this, by fixing following problems

You're pushing value to same newArray every-time whereas you have to create a new variable every-time inside map

You're not returning anything from your function

let data =[[{idStatus: 2, value: '120'},{idStatus: 3, value: '130'},{idStatus: 4, value: '140'},{idStatus: 5, value: '150'}],[{idStatus: 1, value: '160'},{idStatus: 2, value: '180'},{idStatus: 4, value: '10'},{idStatus: 5, value: '20'}],[{idStatus: 3, value: '567'},{idStatus: 6, value: '234'},{idStatus: 9, value: '747'},{idStatus: 7, value: '789'}],[{idStatus: 8, value: '340'},{idStatus: 5, value: '560'},{idStatus: 6, value: '120'},{idStatus: 2, value: '100'}],[{idStatus: 1, value: '106'},{idStatus: 5, value: '345'},{idStatus: 7, value: '756'},{idStatus: 9, value: '946'}]]

function getNewArray(){
const final = data.map(item =>{
    const newArray = []
    for(let i of item){
       newArray.push(i.value)
    }
    return newArray
})
return final
}

console.log(getNewArray())

You can use map twice

let data = {data:[[{idStatus: 2, value: '120'},{idStatus: 3, value: '130'},{idStatus: 4, value: '140'},{idStatus: 5, value: '150'}],[{idStatus: 1, value: '160'},{idStatus: 2, value: '180'},{idStatus: 4, value: '10'},{idStatus: 5, value: '20'}],[{idStatus: 3, value: '567'},{idStatus: 6, value: '234'},{idStatus: 9, value: '747'},{idStatus: 7, value: '789'}],[{idStatus: 8, value: '340'},{idStatus: 5, value: '560'},{idStatus: 6, value: '120'},{idStatus: 2, value: '100'}],[{idStatus: 1, value: '106'},{idStatus: 5, value: '345'},{idStatus: 7, value: '756'},{idStatus: 9, value: '946'}]]}

function getNewArray(){
const final= data.data.map(val=> val.map(({value})=>value))
return final
}

console.log(getNewArray())


问:
Manage hundreds of classes without creating and destroying them?
I have a class A that works with hundreds or thousands of classes, each class has a method with some calculations, for example.
Class A has a method where it choose which class, of those hundreds or thousands, runs. And the method of class A runs many times in a short time.

The solution that I thought at the beginning was to have the classes already created in class A, to avoid having to create and destroy classes every time the event was executed and that the garbage collector consumes CPU. But this class A, as I say, is going to have hundreds or thousands of classes to run and having them all loaded is too high an expense in memory (I think).

My question is, can you think of an optimal way to work with hundreds or thousands of classes, which will run some of them every second, without having to create and destroy it in each execution of the method that works with them?

Edit:

First example: Create and save the classes and then use them, I think it would be a memory expense. But keep the garbage collector from working too much.

```<code>public class ClassA {

Class1 class1;
Class2 class2;

// ... more classes

Class100 class100;

public ClassA() {
    class1 = new Class1();

    // ... initializations

    class100 = new Class100();
}

public ChooseClass(int numberClass) {

    switch (numberClass) {
        case 1:
            class1.calculate();
            break;
        case 2:
            class2.run();
            break;

            // ... more cases, one for each class

        case 100:
            class100.method();
            break;
        default:
            break;
    }
}
</code>```

}

Second example: Creating the class when used, saves memory but the garbage collector consumes a lot of CPU.

```<code>public class ClassA {

public ChooseClass(int numberClass) {

    switch (numberClass) {
        case 1:
            Class1 class1 = new Class1();
            class1.calculate();
            break;
        case 2:
            Class2 Class2 = new Class2();
            class2.run();
            break;

            // ... more cases, one for each class

        case 100:
            Class100 class100 = new Class100();
            class100.method();
            break;
        default:
            break;
    }
}
</code>```

}

答:
The basic problem you face, when you start increasing the number of class instances is that they all need to be accounted and tracked during garbage collection operation, even if you never free those instances, the garbage collector still needs to track them.  There comes a point when the program spends more time performing garbage collection than actual work. We experienced this kind of performance problem with a binary search tree that ended up containing several millions of nodes that originally were class instances.

We were able to circumvent this by using List<T> of structs rather than classes. (The memory of a list is backed by an array, and for structs, the garbage collector only needs to track a single reference to this array). Now, instead of references to a class, we store indices to this list in order to access a desired instance of the struct.

In fact we also faced the problem (notice newer versions of the .NET framework do away with this limitation) that the backing array couldn't grow beyond 2GB even under 64-bits, so we split storage on several lists (256) and used a 32 bit index where 8 bits acted as a list selector and the remaining 24 bits served as an index into the list.

Of course it is convenient to build a class that abstracts all these details, and you need to be aware that when modifying the struct, you actually need to copy it to a local instance, modify it and then replace the original struct with a copy of the modified instance, otherwise your changes will occur in a temporal copy of the struct and not be reflected on your data collection. Also, there is a performance impact, that fortunately is paid-back once the collection is large enough, with extremely fast garbage collection cycles.

Here is some code (quite old), showing these ideas in place, and went from a server spending near 100% of CPU time, to around 15%, just by migrating our search tree to this approach.

```<code>public class SplitList<T> where T : struct {
      // A virtual list divided into several sublists, removing the 2GB capacity limit

      private List<T>[] _lists;
      private Queue<int> _free = new Queue<int>();
      private int _maxId = 0;
      private const int _hashingBits = 8;
      private const int _listSelector = 32 - _hashingBits;
      private const int _subIndexMask = (1 << _listSelector) - 1;

      public SplitList() {
         int listCount = 1 << _hashingBits;
         _lists = new List<T>[listCount];
         for( int i = 0; i < listCount; i++ )
            _lists[i] = new List<T>();
      }

      // Access a struct by index
      // Remember that this returns a local copy of the struct, so if changes are to be done,
      // the local copy must be copied to a local struct,  modify it, and then copy back the changes
      // to the list
      public T this[int idx] {
         get {
            return _lists[(idx >> _listSelector)][idx & _subIndexMask];
         }
         set {
            _lists[idx >> _listSelector][idx & _subIndexMask] = value ;
         }
      }

      // returns an index to a "new" struct inside the collection
      public int New() {

         int result;
         T newElement = new T();

         // are there any free indexes available?
         if( _free.Count > 0 ) {
            // yes, return a free index and initialize reused struct to default values
            result = _free.Dequeue();
            this[result] = newElement;
         } else {
            // no, grow the capacity
            result = ++_maxId;
            List<T> list = _lists[result >> _listSelector];
            list.Add(newElement);
         }
         return result;
      }

      // free an index and allow the struct slot to be reused.
      public void Free(int idx) {
         _free.Enqueue(idx);
      }

   }
</code>```

Here is a snippet of how our binary tree implementation ended up looking using this SplitList backing container class:

```<code> public class CLookupTree {

      public struct TreeNode {
         public int HashValue;
         public int LeftIdx;
         public int RightIdx;
         public int firstSpotIdx;
      }

      SplitList<TreeNode> _nodes;

      …

     private int RotateLeft(int idx) {
        // Performs a tree rotation to the left, here you can see how we need
        // to retrieve the struct to a local copy (thisNode), modify it, and
        // push back the modifications to the node storage list

        // Also note that we are working with indexes rather than references to
        // the nodes
        TreeNode thisNode = _nodes[idx];
        int result = thisNode.RightIdx;
        TreeNode rightNode = _nodes[result];
        thisNode.RightIdx = rightNode.LeftIdx;
        rightNode.LeftIdx = idx;
        _nodes[idx] = thisNode;
        _nodes[result] = rightNode;
        return result;
      }
   }
</code>```

Body:
I have a class A that works with hundreds or thousands of classes, each class has a method with some calculations, for example.
Class A has a method where it choose which class, of those hundreds or thousands, runs. And the method of class A runs many times in a short time.

The solution that I thought at the beginning was to have the classes already created in class A, to avoid having to create and destroy classes every time the event was executed and that the garbage collector consumes CPU. But this class A, as I say, is going to have hundreds or thousands of classes to run and having them all loaded is too high an expense in memory (I think).

My question is, can you think of an optimal way to work with hundreds or thousands of classes, which will run some of them every second, without having to create and destroy it in each execution of the method that works with them?

Edit:

First example: Create and save the classes and then use them, I think it would be a memory expense. But keep the garbage collector from working too much.

public class ClassA {

Class1 class1;
Class2 class2;

// ... more classes

Class100 class100;

public ClassA() {
    class1 = new Class1();

    // ... initializations

    class100 = new Class100();
}

public ChooseClass(int numberClass) {

    switch (numberClass) {
        case 1:
            class1.calculate();
            break;
        case 2:
            class2.run();
            break;

            // ... more cases, one for each class

        case 100:
            class100.method();
            break;
        default:
            break;
    }
}

}

Second example: Creating the class when used, saves memory but the garbage collector consumes a lot of CPU.

public class ClassA {

public ChooseClass(int numberClass) {

    switch (numberClass) {
        case 1:
            Class1 class1 = new Class1();
            class1.calculate();
            break;
        case 2:
            Class2 Class2 = new Class2();
            class2.run();
            break;

            // ... more cases, one for each class

        case 100:
            Class100 class100 = new Class100();
            class100.method();
            break;
        default:
            break;
    }
}

}

Body:
The basic problem you face, when you start increasing the number of class instances is that they all need to be accounted and tracked during garbage collection operation, even if you never free those instances, the garbage collector still needs to track them.  There comes a point when the program spends more time performing garbage collection than actual work. We experienced this kind of performance problem with a binary search tree that ended up containing several millions of nodes that originally were class instances.

We were able to circumvent this by using List<T> of structs rather than classes. (The memory of a list is backed by an array, and for structs, the garbage collector only needs to track a single reference to this array). Now, instead of references to a class, we store indices to this list in order to access a desired instance of the struct.

In fact we also faced the problem (notice newer versions of the .NET framework do away with this limitation) that the backing array couldn't grow beyond 2GB even under 64-bits, so we split storage on several lists (256) and used a 32 bit index where 8 bits acted as a list selector and the remaining 24 bits served as an index into the list.

Of course it is convenient to build a class that abstracts all these details, and you need to be aware that when modifying the struct, you actually need to copy it to a local instance, modify it and then replace the original struct with a copy of the modified instance, otherwise your changes will occur in a temporal copy of the struct and not be reflected on your data collection. Also, there is a performance impact, that fortunately is paid-back once the collection is large enough, with extremely fast garbage collection cycles.

Here is some code (quite old), showing these ideas in place, and went from a server spending near 100% of CPU time, to around 15%, just by migrating our search tree to this approach.

public class SplitList<T> where T : struct {
      // A virtual list divided into several sublists, removing the 2GB capacity limit

      private List<T>[] _lists;
      private Queue<int> _free = new Queue<int>();
      private int _maxId = 0;
      private const int _hashingBits = 8;
      private const int _listSelector = 32 - _hashingBits;
      private const int _subIndexMask = (1 << _listSelector) - 1;

      public SplitList() {
         int listCount = 1 << _hashingBits;
         _lists = new List<T>[listCount];
         for( int i = 0; i < listCount; i++ )
            _lists[i] = new List<T>();
      }

      // Access a struct by index
      // Remember that this returns a local copy of the struct, so if changes are to be done,
      // the local copy must be copied to a local struct,  modify it, and then copy back the changes
      // to the list
      public T this[int idx] {
         get {
            return _lists[(idx >> _listSelector)][idx & _subIndexMask];
         }
         set {
            _lists[idx >> _listSelector][idx & _subIndexMask] = value ;
         }
      }

      // returns an index to a "new" struct inside the collection
      public int New() {

         int result;
         T newElement = new T();

         // are there any free indexes available?
         if( _free.Count > 0 ) {
            // yes, return a free index and initialize reused struct to default values
            result = _free.Dequeue();
            this[result] = newElement;
         } else {
            // no, grow the capacity
            result = ++_maxId;
            List<T> list = _lists[result >> _listSelector];
            list.Add(newElement);
         }
         return result;
      }

      // free an index and allow the struct slot to be reused.
      public void Free(int idx) {
         _free.Enqueue(idx);
      }

   }

Here is a snippet of how our binary tree implementation ended up looking using this SplitList backing container class:

 public class CLookupTree {

      public struct TreeNode {
         public int HashValue;
         public int LeftIdx;
         public int RightIdx;
         public int firstSpotIdx;
      }

      SplitList<TreeNode> _nodes;

      …

     private int RotateLeft(int idx) {
        // Performs a tree rotation to the left, here you can see how we need
        // to retrieve the struct to a local copy (thisNode), modify it, and
        // push back the modifications to the node storage list

        // Also note that we are working with indexes rather than references to
        // the nodes
        TreeNode thisNode = _nodes[idx];
        int result = thisNode.RightIdx;
        TreeNode rightNode = _nodes[result];
        thisNode.RightIdx = rightNode.LeftIdx;
        rightNode.LeftIdx = idx;
        _nodes[idx] = thisNode;
        _nodes[result] = rightNode;
        return result;
      }
   }


问:
Excel VBA loop and show interactively changes
I have a VBA Application which loops through a range and does some changes.
However, I don't care much about the running time but I want to show the User that changes were made in run time.

I was thinking about something like this.

```<code>Private Sub ProcessALBODY(ByRef Fullpath, ByRef MasterWB)
...

    For Each Row In rng.rows
    ... 'Do Something

    DoEvents
    ActiveWindow.ScrollRow = 1 'for each row scrolldown and proceed to next row
    Next

...
End Sub
</code>```

Unfortunately my application freezes until it has finished..

答: You could use the status bar to show progress. Use Application.StatusBar = and then follow it with your choice of string, integer, etc. If it is put inside the 'For' statement, it would update with each iteration.

Body:
I have a VBA Application which loops through a range and does some changes.
However, I don't care much about the running time but I want to show the User that changes were made in run time.

I was thinking about something like this.

Private Sub ProcessALBODY(ByRef Fullpath, ByRef MasterWB)
...

    For Each Row In rng.rows
    ... 'Do Something

    DoEvents
    ActiveWindow.ScrollRow = 1 'for each row scrolldown and proceed to next row
    Next

...
End Sub

Unfortunately my application freezes until it has finished..


问:
How can filter this table based on a column's boolean value?
I am trying to filter a table based on whether or not my "projects" are active or not. I currently have a table, where "active" is a column and it will say either true or false based on the project status. I would like to be able to filter my table based on this boolean value.

So I am currently using a selection menu, which will return either true or false based on the selection. From what ive been trying, the table wont filter on boolean values, only on strings. So i have a filtered predicate that is trying to force the filtering only on my active column, however it is currently not working as intended.

```<code>//.ts file
dataSource: MatTableDataSource<OrderTemplateInterfaceWithId> = new MatTableDataSource([]);
  displayedColumns = [
    'dayOfWeek',
    'startTime',
    'endTime',
    'technician',
    'frequency',
    'startDate',
    'endDate',
    'active',
    'actions'
  ];

ngOnInit() {
    this.dataSource.filterPredicate = (data: OrderTemplateInterfaceWithId, filter: string) => {
      return data.active === (filter === "true") || data.active === (filter === "false");
    };
  }

applyFilter(filterValue: string) {
    console.log(this.dataSource);
    this.dataSource.filter = filterValue;
  }

//.html file
<mat-form-field>
<mat-select (selectionChange)="applyFilter($event.value)">
  <mat-option value='true'>Active</mat-option>
  <mat-option value='false'>InActive</mat-option>
</mat-select>
</mat-form-field>
</code>```

So i would expect the results to have my table filtered by the active column based on my selection menu. Any help would be greatly appreciated, thank you!

答:
So figured out that I had to have my filterPredicate inside my applyFilter, right before I did the actual filter. So my applyFilter looked like:</p>

```<code>applyFilter(filterValue: string) {
    if(filterValue === 'all') {
      this.dataSource.filterPredicate = function(data, filter): boolean {
        return String(data.active).includes('true')
          || String(data.active).includes('false');
      };
    }
    else {
      this.dataSource.filterPredicate = function(data, filter): boolean {
        return String(data.active).includes(filter);
      };
    }
    this.dataSource.filter = filterValue;
  }
</code>```

Body:
I am trying to filter a table based on whether or not my "projects" are active or not. I currently have a table, where "active" is a column and it will say either true or false based on the project status. I would like to be able to filter my table based on this boolean value.

So I am currently using a selection menu, which will return either true or false based on the selection. From what ive been trying, the table wont filter on boolean values, only on strings. So i have a filtered predicate that is trying to force the filtering only on my active column, however it is currently not working as intended.

//.ts file
dataSource: MatTableDataSource<OrderTemplateInterfaceWithId> = new MatTableDataSource([]);
  displayedColumns = [
    'dayOfWeek',
    'startTime',
    'endTime',
    'technician',
    'frequency',
    'startDate',
    'endDate',
    'active',
    'actions'
  ];

ngOnInit() {
    this.dataSource.filterPredicate = (data: OrderTemplateInterfaceWithId, filter: string) => {
      return data.active === (filter === "true") || data.active === (filter === "false");
    };
  }

applyFilter(filterValue: string) {
    console.log(this.dataSource);
    this.dataSource.filter = filterValue;
  }

//.html file
<mat-form-field>
<mat-select (selectionChange)="applyFilter($event.value)">
  <mat-option value='true'>Active</mat-option>
  <mat-option value='false'>InActive</mat-option>
</mat-select>
</mat-form-field>

So i would expect the results to have my table filtered by the active column based on my selection menu. Any help would be greatly appreciated, thank you!

Body:
So figured out that I had to have my filterPredicate inside my applyFilter, right before I did the actual filter. So my applyFilter looked like:

applyFilter(filterValue: string) {
    if(filterValue === 'all') {
      this.dataSource.filterPredicate = function(data, filter): boolean {
        return String(data.active).includes('true')
          || String(data.active).includes('false');
      };
    }
    else {
      this.dataSource.filterPredicate = function(data, filter): boolean {
        return String(data.active).includes(filter);
      };
    }
    this.dataSource.filter = filterValue;
  }


问:
How to catch at compile-time an assignment of a subtype to a supertype?
I learnt that the

rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x

This allows an assignment of a variable of a subtype to a variable of a supertype. Is there a way to get a compile-time error regarding that assignment?

(TypeScript Playground)

interface SuperT {
    field: string
}

// an explicitly declared subtype object for a supertype variable generates an error
const super1: SuperT = {field: 'value', extra: 1} // compile-time error: Type '{ field: string; extra: number; }' is not assignable to type 'SuperT'

function subTValue() { return {field: 'value', extra: 1} }
const super2: SuperT = subTValue() // no compile-time error, BUT HOW TO get a compile-time error here?
```

答:
You want exact types which aren't directly supported. You can do various tricks with generics and conditional types  to get closer.  Here's one way to do it indirectly:

```<code>interface SuperT {
    field: string
}

type Exactly<T, U extends T> = T & Record<Exclude<keyof U, keyof T>, never>;
const asExactlySuperT = <U extends Exactly<SuperT, U>>(superT: U) => superT;

const superOkay: SuperT = asExactlySuperT({ field: "a" }); // okay

function subTValue() { return { field: 'value', extra: 1 } }
const superBad: SuperT = asExactlySuperT(subTValue()); // error!
// types of property "extra" are incompatible
</code>```

Link to code

The idea there is that Exactly<T, U> will take a type T and a candidate type U which hopefully matches T exactly with no extra properties.  If it does, then Exactly<T, U> will equal U.  If it does not, then Exactly<T, U> will set the property types of any extra properties to never.  Since asExactlySuperT() requires that U extends Exactly<SuperT, U>, the only way that can happen is if there are no extra properties in U.

Hope that helps.  Good luck!

Body:
I learnt that the

rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x

This allows an assignment of a variable of a subtype to a variable of a supertype. Is there a way to get a compile-time error regarding that assignment?

(<a href="https://www.typescriptlang.org/play/#src=interface%20SuperT%20%7B%0D%0A%20%20%20%20field%3A%20string%0D%0A%7D%0D%0A%0D%0A%2F%2F%20an%20explicitly%20declared%20subtype%20object%20for%20a%20supertype%20variable%20generates%20an%20error%0D%0Aconst%20super1%3A%20SuperT%20%3D%20%7Bfield%3A%20'value'%2C%20extra%3A%201%7D%20%2F%2F%20compile-time%20error%3A%20Type%20'%7B%20field%3A%20string%3B%20extra%3A%20number%3B%20%7D'%20is%20not%20assignable%20to%20type%20'SuperT'%0D%0A%0D%0Afunction%20subTValue()%20%7B%20return%20%7Bfield%3A%20'value'%2C%20extra%3A%201%7D%20%7D%0D%0Aconst%20super2%3A%20SuperT%20%3D%20subTValue()%20%2F%2F%20no%20compile-time%20error%2C%20BUT%20HOW%20TO%20get%20a%20compile-time%20error%20here%3F%20%0D%0A" rel="nofollow noreferrer">TypeScript Playground)

interface SuperT {
    field: string
}

// an explicitly declared subtype object for a supertype variable generates an error
const super1: SuperT = {field: 'value', extra: 1} // compile-time error: Type '{ field: string; extra: number; }' is not assignable to type 'SuperT'

function subTValue() { return {field: 'value', extra: 1} }
const super2: SuperT = subTValue() // no compile-time error, BUT HOW TO get a compile-time error here?

Body:
You want exact types which aren't directly supported. You can do various tricks with generics and conditional types  to get closer.  Here's one way to do it indirectly:

interface SuperT {
    field: string
}

type Exactly<T, U extends T> = T & Record<Exclude<keyof U, keyof T>, never>;
const asExactlySuperT = <U extends Exactly<SuperT, U>>(superT: U) => superT;

const superOkay: SuperT = asExactlySuperT({ field: "a" }); // okay

function subTValue() { return { field: 'value', extra: 1 } }
const superBad: SuperT = asExactlySuperT(subTValue()); // error!
// types of property "extra" are incompatible

Link to code

The idea there is that Exactly<T, U> will take a type T and a candidate type U which hopefully matches T exactly with no extra properties.  If it does, then Exactly<T, U> will equal U.  If it does not, then Exactly<T, U> will set the property types of any extra properties to never.  Since asExactlySuperT<U>() requires that U extends Exactly<SuperT, U>, the only way that can happen is if there are no extra properties in U.

Hope that helps.  Good luck!


问:
rpyc AsyncResultTimeout("result expired")
I'm running classic rpyc server. And when I connect to server and perform long running command:

```<code>rconn = rpyc.classic.connect(host='ip', port='18812')

rsubprocess = rconn.modules.subprocess
rsubprocess.check_output(['my command'], shell=True).decode()
</code>```

I got:

raise AsyncResultTimeout("result expired") TimeoutError: result
  expired

I tried to set:

```<code>rconn._config['timeout'] = 240
</code>```

and

```<code>rconn.ASYNC_REQUEST_TIMEOUT = 240
</code>```

答:
You need to modify the "sync_request_timeout" configuration e.g:

rconn._config['sync_request_timeout'] = 240  # Set timeout to 240 seconds
rconn._config['sync_request_timeout'] = None # No timeout

Body:
I'm running classic rpyc server. And when I connect to server and perform long running command:

rconn = rpyc.classic.connect(host='ip', port='18812')

rsubprocess = rconn.modules.subprocess
rsubprocess.check_output(['my command'], shell=True).decode()

I got:

raise AsyncResultTimeout("result expired") TimeoutError: result
  expired

I tried to set:

rconn._config['timeout'] = 240

and

rconn.ASYNC_REQUEST_TIMEOUT = 240


问:
How do I verify if a file is being downloaded in Selenium Webdriver C#
How to verify file being downloaded. I am stuck at how do I retrieve the downloaded file when the "Download" button had been clicked.</p>

```<code>''  driver = new ChromeDriver();
        driver.Manage().Window.Maximize();
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
        driver.Navigate().GoToUrl("http://192.162.0.1/testing-admin/Login/Login.aspx");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).SendKeys("Jojo");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtPassword")).SendKeys("Man15742368");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_cmdLogin")).Click();
        driver.Navigate().GoToUrl("http://192.162.0.1/testing-admin/User_Document/User_Document_Download.aspx");
      driver.FindElement(By.XPath("//a[@id='ctl00_MainContent_GV_ctl02_lnkDownloadFile']")).Click(); //download button
</code>```

答:
I used this, it work too. But the only downsize is that you have to know the name of the file you downloaded .</p>

```<code>String myDownloadFolder = @"c:\temp\";
        var options = new ChromeOptions();
        options.AddUserProfilePreference("download.default_directory", myDownloadFolder);
        driver = new ChromeDriver(options);
        driver.Navigate().GoToUrl("http://google/download/some"); // download some stuffs
        driver.FindElement(By.LinkText("Download")).Click();
        System.Threading.Thread.Sleep(10000);
        Assert.IsTrue(File.Exists(@"c:\temp\Test.docx"));
</code>```

Body:
How to verify file being downloaded. I am stuck at how do I retrieve the downloaded file when the "Download" button had been clicked.

''  driver = new ChromeDriver();
        driver.Manage().Window.Maximize();
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
        driver.Navigate().GoToUrl("http://192.162.0.1/testing-admin/Login/Login.aspx");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtUserID")).SendKeys("Jojo");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_txtPassword")).SendKeys("Man15742368");
        driver.FindElement(By.Id("ctl00_MainContent_ucLogin_cmdLogin")).Click();
        driver.Navigate().GoToUrl("http://192.162.0.1/testing-admin/User_Document/User_Document_Download.aspx");
      driver.FindElement(By.XPath("//a[@id='ctl00_MainContent_GV_ctl02_lnkDownloadFile']")).Click(); //download button

Body:
I used this, it work too. But the only downsize is that you have to know the name of the file you downloaded .

String myDownloadFolder = @"c:\temp\";
        var options = new ChromeOptions();
        options.AddUserProfilePreference("download.default_directory", myDownloadFolder);
        driver = new ChromeDriver(options);
        driver.Navigate().GoToUrl("http://google/download/some"); // download some stuffs
        driver.FindElement(By.LinkText("Download")).Click();
        System.Threading.Thread.Sleep(10000);
        Assert.IsTrue(File.Exists(@"c:\temp\Test.docx"));


问:
What's the best way of parsing strings?
We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet.

We'll need to support more 'formats' in the future too.

Do we go for a solution using:

Regex

Simply string searching (using string.IndexOf etc)

Lex/ Yacc

Other

The overall solution will be developed in C# 2.0 (hopefully 3.5)

答: Regex would probably be you bes bet, tried and proven. Plus a regular expression can be compiled.</p>

Title: What's the best way of parsing strings?

LastEditorDisplayName: Torsten Marek

OwnerDisplayName: Robert Durgin


问:
What UNIX commands support coloured output?
I enjoy using UNIX/bash commands that support coloured output.  Consequently, I have a few aliases defined which automatically enable coloured output of the commands that I know support this option.  However, I'm sure there are hundreds of commands out there that support coloured output - I'd like to know what they are.

The ones in my ~/.bash_aliases file are:

```<code>ls --color=auto
grep --color
phpunit --ansi
</code>```

What else is there?  Is there a list somewhere of all commands that support coloured output?  Or better still, some command for grepping my local man pages and plucking out the appropriate command names.

答: I'm quite fond of coloring my prompt so that it stands out. A useful article on that sort of thing is available here.</p>

OwnerDisplayName: DavidWinterbottom

Body:
I enjoy using UNIX/bash commands that support coloured output.  Consequently, I have a few aliases defined which automatically enable coloured output of the commands that I know support this option.  However, I'm sure there are hundreds of commands out there that support coloured output - I'd like to know what they are.

The ones in my ~/.bash_aliases file are:

ls --color=auto
grep --color
phpunit --ansi

What else is there?  Is there a list somewhere of all commands that support coloured output?  Or better still, some command for grepping my local man pages and plucking out the appropriate command names.

LastEditorDisplayName: Eddie

OwnerDisplayName: David Dean


问:
Why does copying a worksheet from Excel Add-in into the ActiveWorkbook takes inordinate amount of time?
In my 2007 Excel Add-in, I have a routine that copies a worksheet from the add-in to the users ActiveWorkbook.  When I run the routine, it takes 15-20 seconds to execute this line of code:

```<code>ThisWorkbook.Sheets(roadwayQuantTemplate).Copy Before:=ActiveWorkbook.Sheets(1)
</code>```

This alternate version has the same delay:

```<code>ThisWorkbook.Sheets(roadwayQuantTemplate).Copy Before:=Worksheets(1)
</code>```

Does anyone have any Idea why it takes so long to execute this line?  I have another routine that adds a blank worksheet (then modifies it) and the following line of code excecutes with out any delay:

```<code>ActiveWorkbook.Worksheets.Add Before:=Worksheets(1)
</code>```

Should the Copy method really take that much longer to execute than the Add method? There is not a lot of data in the template worksheet that I am copying, only a few cells that make up the header of the worksheet and less than 100 empty cells with formatting applied.

Any ideas?

答:
It may be faster to use a standalone template, rather than a sheet within the add-in. The syntax is

Worksheets.Add(Type:=TemplatePathAndFileName)

Body:
In my 2007 Excel Add-in, I have a routine that copies a worksheet from the add-in to the users ActiveWorkbook.  When I run the routine, it takes 15-20 seconds to execute this line of code:

ThisWorkbook.Sheets(roadwayQuantTemplate).Copy Before:=ActiveWorkbook.Sheets(1)

This alternate version has the same delay:

ThisWorkbook.Sheets(roadwayQuantTemplate).Copy Before:=Worksheets(1)

Does anyone have any Idea why it takes so long to execute this line?  I have another routine that adds a blank worksheet (then modifies it) and the following line of code excecutes with out any delay:

ActiveWorkbook.Worksheets.Add Before:=Worksheets(1)

Should the Copy method really take that much longer to execute than the Add method? There is not a lot of data in the template worksheet that I am copying, only a few cells that make up the header of the worksheet and less than 100 empty cells with formatting applied.

Any ideas?


问:
How to decode open id connect server Acess token in Web API core
I am working with ASOS ( Asp.net.OpenIDConnect.Server) and using bearer authentication.

I need to check token expiry time and update it.

Not able to decode access token. Can please any one share the way to get it done.

答:
You can use JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.Jwt:

```<code>var token = "YourToken";
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(token) as JwtSecurityToken;
var expire= jsonToken.Claims.First(claim => claim.Type == "exp").Value;
</code>```

Update :

If you are referring to the Opaque tokens ,  which are encrypted and signed by the authorization server using the ASP.NET Core Data Protection stack. Then you are using the AspNet.Security.OAuth.Validation middleware or an introspection middleware . For the AspNet.Security.OAuth.Validation middleware , i think you can check the claims in one of the OAuthValidationEvents such as OnCreateTicket event .

If you are concern about the expire token of access tokens . The recommended way is to use refresh token to issue new access token if the token is expired .

The refresh token default expiration date can be set globally from the options, using the RefreshTokenLifetime property. If you don't provide your own lifetime, they are valid for 14 days.

Note that sliding expiration is also enabled by default, which means you get a new refresh token (valid for 14 days) each time you make a new grant_type=refresh_token request. You can disable sliding expiration by setting UseSlidingExpiration to false.

Reference : https://stackoverflow.com/a/35747870/5751404

Body:
You can use JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.Jwt:

var token = "YourToken";
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(token) as JwtSecurityToken;
var expire= jsonToken.Claims.First(claim => claim.Type == "exp").Value;

Update :

If you are referring to the Opaque tokens ,  which are encrypted and signed by the authorization server using the ASP.NET Core Data Protection stack. Then you are using the AspNet.Security.OAuth.Validation middleware or an introspection middleware . For the AspNet.Security.OAuth.Validation middleware , i think you can check the claims in one of the OAuthValidationEvents such as OnCreateTicket event .

If you are concern about the expire token of access tokens . The recommended way is to use refresh token to issue new access token if the token is expired .

The refresh token default expiration date can be set globally from the options, using the RefreshTokenLifetime property. If you don't provide your own lifetime, they are valid for 14 days.

Note that sliding expiration is also enabled by default, which means you get a new refresh token (valid for 14 days) each time you make a new grant_type=refresh_token request. You can disable sliding expiration by setting UseSlidingExpiration to false.

Reference : https://stackoverflow.com/a/35747870/5751404


问:
fixing a failed ruby gem install
I am installing the ruby gem mysql-dbd on a new system which is running ruby 2.5.  The problem is that it gets a syntax error because at 2.4 ruby combined Integer and Fixed num types.

The failed install leaves the unpacked gem package on disk so I was able to examine the entrails and the fix appears to be trivial (as in insert a '#' in a statement to remove the now redundant reference to FixNum).

My question is having fixed the source how do I go about building and installing the gem?   Not being familiar with rake.

BTW the gem has long been "unsupported".

答:
I can't get the gem source repository to load, but you've got at least two options:

Locally, you might be able to build it. Try running rake build from the root folder of the gem, and look in the pkg folder for the built gem. You should be able to then gem install pkg/<gem name>.gem in that folder

If you need to share it with others, push the code up on github. Make your change, and if you're using bundler in the codebase that's using the gem, update your Gemfile to point to your source.

Title: fixing a failed ruby gem install


问:
Saving dataframe to pdf adjust width
I found that grid.table could be used to plot a dataframe to a pdf file, as described here. I want to save a dataframe to a landscape A4 format, however it seems to not scale the data such that is nicely fits within the borders of the pdf.

Code

```<code>library(gridExtra)

set.seed(1)
strings <- c('Wow this is nice', 'I need some coffee', 'Insert something here', 'No ideas left')
table <- as.data.frame(matrix(ncol = 9, nrow = 30, data = sample(strings,30, replace = TRUE)))
pdf("test.pdf", paper = 'a4r')
grid.table(table)
dev.off()
</code>```

Output

Not the whole table is shown in the pdf:

Question

How can I make sure that the dataframe is scaled to fit within the landscape A4? I don't explicitly need gridExtra or the default pdf save, I can use any other package if these are easier to fix this.

EDIT

I came across this other question, appareantly one can figure out the required height and width of the tableGrob

```<code>tg = gridExtra::tableGrob(table)
h = grid::convertHeight(sum(tg$heights), "mm", TRUE)
w = grid::convertWidth(sum(tg$widths), "mm", TRUE)
ggplot2::ggsave("test.pdf", tg, width=w, height=h, units = 'mm')
</code>```

Here h = 172.2 and w = 444.3 which exceed the size of a standard A4, namely 210 x 279. So I know this causes the problem however still can't figure out to scale down the table to fit it on an A4.

答:
I figured out I could add the scale parameter to ggsave.  I wrote a simple function to get the optimal scale:

optimal.scale <- function(w,h, wanted.w, wanted.h) max(c(w/wanted.w,  h/wanted.h))

I added  0.1 to the scale to add a margin to the plot such that the text is not directly on the edge of the paper. Then I passed the resulting scale to ggsave

```<code>  tg = gridExtra::tableGrob(table
  h = grid::convertHeight(sum(tg$heights), "mm", TRUE)
  w = grid::convertWidth(sum(tg$widths), "mm", TRUE)
  scale = optimal.scale(w,h, 279, 210) + 0.1 #A4 = 279 x 210 in landscape
  ggplot2::ggsave("test.pdf", tg, width = 279, height = 210, units = 'mm' , scale = scale)
</code>```

Now my table fits on the A4:

Title: Saving dataframe to pdf adjust width

Body:
I found that grid.table could be used to plot a dataframe to a pdf file, as described here. I want to save a dataframe to a landscape A4 format, however it seems to not scale the data such that is nicely fits within the borders of the pdf.

Code

library(gridExtra)

set.seed(1)
strings <- c('Wow this is nice', 'I need some coffee', 'Insert something here', 'No ideas left')
table <- as.data.frame(matrix(ncol = 9, nrow = 30, data = sample(strings,30, replace = TRUE)))
pdf("test.pdf", paper = 'a4r')
grid.table(table)
dev.off()

Output

Not the whole table is shown in the pdf:

Question

How can I make sure that the dataframe is scaled to fit within the landscape A4? I don't explicitly need gridExtra or the default pdf save, I can use any other package if these are easier to fix this.

EDIT

I came across this other question, appareantly one can figure out the required height and width of the tableGrob

tg = gridExtra::tableGrob(table)
h = grid::convertHeight(sum(tg$heights), "mm", TRUE)
w = grid::convertWidth(sum(tg$widths), "mm", TRUE)
ggplot2::ggsave("test.pdf", tg, width=w, height=h, units = 'mm')

Here h = 172.2 and w = 444.3 which exceed the size of a standard A4, namely 210 x 279. So I know this causes the problem however still can't figure out to scale down the table to fit it on an A4.

Body:
I figured out I could add the scale parameter to ggsave.  I wrote a simple function to get the optimal scale:

optimal.scale <- function(w,h, wanted.w, wanted.h) max(c(w/wanted.w,  h/wanted.h))

I added  0.1 to the scale to add a margin to the plot such that the text is not directly on the edge of the paper. Then I passed the resulting scale to ggsave

  tg = gridExtra::tableGrob(table
  h = grid::convertHeight(sum(tg$heights), "mm", TRUE)
  w = grid::convertWidth(sum(tg$widths), "mm", TRUE)
  scale = optimal.scale(w,h, 279, 210) + 0.1 #A4 = 279 x 210 in landscape
  ggplot2::ggsave("test.pdf", tg, width = 279, height = 210, units = 'mm' , scale = scale)

Now my table fits on the A4:


问:
Find the department block number having maximum number of departments
To find the department block number having maximum number of departments.
I tried with my code but its not working

```<code>  select department_block_number
  from department
  where department_id in (select max(department_id)
  from department
   group by department_block_number);
</code>```

The above code shows output of 2 values

202

303

while the expected output is a single value of

303

Please help

答:
You need aggregation!

```<code>select department_block_number
from department
group by department_block_number
having count(*) = (select max(cnt)
                   from (select count(*) as cnt
                         from department
                         group by department_block_number
                        )  d
                  );
</code>```

There are other ways to express this logic, but this is what you seem to be trying to do.

Body:
To find the department block number having maximum number of departments.
I tried with my code but its not working

  select department_block_number
  from department
  where department_id in (select max(department_id)
  from department
   group by department_block_number);

The above code shows output of 2 values

202

303

while the expected output is a single value of

303

Please help

Body:
You need aggregation!

select department_block_number
from department
group by department_block_number
having count(*) = (select max(cnt)
                   from (select count(*) as cnt
                         from department
                         group by department_block_number
                        )  d
                  );

There are other ways to express this logic, but this is what you seem to be trying to do.


问:
How to prevent npm run build from deleting directories in build
I have a SPA react app to host my personal projects. The layout is created with react, but each personal project is a directory with normal index.html, .js, and .css files.

I couldn't figure out how to successfully use <Link> to render the regular .html pages on click, so I'm taking the easy route for now: manually moving each directory into build, then linking to it with .

This works, but every time I rerun npm run build it erases all of my project directories. How can I prevent this behavior? (I'm using create-react-app with defaults).

tl;dr: How to tell npm run build not to delete certain directories inside build.

答:
Build folder should be cleaned up on each build. This is best practice so your project can be build by different developers, having only source code.

To achive your task you should use additional npm script which will be automatically run after build. (You may see all possible stages when scripts can be run here)

postbuild script should copy additional files from some path under src folder to build folder. So on each build you'll have all required files in place

Example

```<code>"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postbuild": "copy .\\src\\app.js .\\build\\app.js"
},
</code>```

Last line will copy app.js from src folder to build folder. The same way you can create script to recreate all required directories after each build.

Body:
Build folder should be cleaned up on each build. This is best practice so your project can be build by different developers, having only source code.

To achive your task you should use additional npm script which will be automatically run after build. (You may see all possible stages when scripts can be run here)

postbuild script should copy additional files from some path under src folder to build folder. So on each build you'll have all required files in place

Example

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postbuild": "copy .\\src\\app.js .\\build\\app.js"
},

Last line will copy app.js from src folder to build folder. The same way you can create script to recreate all required directories after each build.