问:
Draw horizontal line on facetplot (seaborn relplot)
I have made the following plot with the code below. I would like to create a horizontal red dashed line running across all the facetplots to highlight all points above 200, but when I run this

```<code>plt.axhline(200, ls='--', linewidth=3, color='red')
</code>```

I only get the line in the last plot. I am guessing I need to loop through all the plots but i am not sure how to do that. Thanks for the help.

```<code>g = sns.relplot(x='hour', y="n",
                 col="w_day", hue="Zone",
                 kind="scatter", ci=95, data=df_1, col_order=col_order)

axes = g.axes.flatten()
axes[0].set_title("Monday")
axes[1].set_title("Tuesday")
axes[2].set_title("Wednesday")
axes[3].set_title("Thursday")
axes[4].set_title("Friday")
axes[5].set_title("Saturday")
axes[6].set_title("Sunday")

axes[0].set_ylabel("Hourly N")
for ax in axes:
    ax.set_xlabel("Hour")

g.fig.suptitle('',
               weight='semibold',
               y= 1.06,
               size='x-large')

plt.axhline(200, ls='--', linewidth=3, color='red')

plt.margins(x=0)
plt.subplots_adjust(hspace=0, wspace=0)
</code>```

答:
```<code>for ax in axes:
    ax.axhline(200, ls='--', linewidth=3, color='red')
</code>```

Body:
I have made the following plot with the code below. I would like to create a horizontal red dashed line running across all the facetplots to highlight all points above 200, but when I run this

plt.axhline(200, ls='--', linewidth=3, color='red')

I only get the line in the last plot. I am guessing I need to loop through all the plots but i am not sure how to do that. Thanks for the help.

g = sns.relplot(x='hour', y="n",
                 col="w_day", hue="Zone",
                 kind="scatter", ci=95, data=df_1, col_order=col_order)

axes = g.axes.flatten()
axes[0].set_title("Monday")
axes[1].set_title("Tuesday")
axes[2].set_title("Wednesday")
axes[3].set_title("Thursday")
axes[4].set_title("Friday")
axes[5].set_title("Saturday")
axes[6].set_title("Sunday")

axes[0].set_ylabel("Hourly N")
for ax in axes:
    ax.set_xlabel("Hour")

g.fig.suptitle('',
               weight='semibold',
               y= 1.06,
               size='x-large')

plt.axhline(200, ls='--', linewidth=3, color='red')

plt.margins(x=0)
plt.subplots_adjust(hspace=0, wspace=0)


来源: stackexchange

问:
How to differentiate between a url with and without parameters using .htaccess
I don't even know how I could title this question but here is the problem:

I use seo friendly urls on this project where there are services. Service links look like; .com/services/service-title-6 and they get translated to; .com/services.php?s=service-title-6. On the other hand, pages don't have the .php extension at the end of their urls like: .com/services or .com/about-us.

The actual problem comes when I'm handling the switch between multiple display languages for this website. I just used a get parameter called lang and I can pass it to any page since I have a php file I call on every page to handle this along with other stuff. On my navigation bar, the language change button links are created dynamically so that the user doesn't have to leave the current page to change the website's language. So if you are viewing the about page, the link is: .com/about-us?lang=en to switch to English. This is generated in php like $current_url . "?lang=en".

However, when I'm viewing a page with parameters such as a service, the link gets translated by .htaccess to something like: .com/services.php?s=service-title-6?lang=en. As you can tell, the 2nd question mark will get ignored as a parameter and not be passed. I would need to use an ampersand instead of the question mark. But when I'm just doing this on a regular page, I can't use ampersand by itself as it will be translated to: .com/about-us.php&lang=en.

Sorry for the long question but any help and ideas to handle this problem would be appreciated. Thanks.

答:
I fixed my problem by appending the next query string to my url. I wasn't aware of the QSA flag of mod_rewrite.

Here is my original rule for the services page:

RewriteRule ^services/(.*?)/?$ services.php?s=$1 [L]

I replaced it with:

RewriteRule ^services/(.*?)/?$ services.php?s=$1&lang=$2 [L,QSA]

I don't know if it's 100% reliable but it seems to work perfectly for what I need, even after doing a few tests.

(Thanks to Joseph Sible-Reinstate Monica for directing me to a helpful question.)

ContentLicense: CC BY-SA 4.0


问:
Bash tool to get nth line from a file
Is there a "canonical" way of doing that? I've been using head -n | tail -1 which does the trick, but I've been wondering if there's a Bash tool that specifically extracts a line (or a range of lines) from a file.

By "canonical" I mean a program whose main function is doing that.

答:
Wow, all the possibilities!

Try this:

```<code>sed -n "${lineNum}p" $file
</code>```

or one of these depending upon your version of Awk:

```<code>awk  -vlineNum=$lineNum 'NR == lineNum {print $0}' $file
awk -v lineNum=4 '{if (NR == lineNum) {print $0}}' $file
awk '{if (NR == lineNum) {print $0}}' lineNum=$lineNum $file
</code>```

(You may have to try the nawk or gawk command).

Is there a tool that only does the print that particular line? Not one of the standard tools. However, sed is probably the closest and simplest to use.

ContentLicense: CC BY-SA 3.0

Title: Bash tool to get nth line from a file

Body:
Wow, all the possibilities!

Try this:

sed -n "${lineNum}p" $file

or one of these depending upon your version of Awk:

awk  -vlineNum=$lineNum 'NR == lineNum {print $0}' $file
awk -v lineNum=4 '{if (NR == lineNum) {print $0}}' $file
awk '{if (NR == lineNum) {print $0}}' lineNum=$lineNum $file

(You may have to try the nawk or gawk command).

Is there a tool that only does the print that particular line? Not one of the standard tools. However, sed is probably the closest and simplest to use.


问:
What causes svn error 413 Request Entity Too Large?
On occasion I receive an error "413 Request Entity Too Large" while updating an svn repository. Once I receive this error, it continues every time I attempt to update the local working copy. A new checkout will solve the problem, but is very inconvenient. The project is over 30 GB, and the SVN repository is hosted externally.

This has occurred in the past on several different computers, including Windows development machines, and our Linux build server.

Most of what I have found regarding this issue relates to large individual files (over 2GB). This is not the case here, as the largest files are approx. 50-60 MB.

Has anyone else ran into this before and/or know the cause/solution to this?

答: If without access to the server, you can also select all the folders using ctrl+A and then right click to update all folders individually using tortoise svn etc. Essentially the same as @lucrussell's solution.</p>

ContentLicense: CC BY-SA 2.5


问:
System.Timers.Timer in Windows Service or Console Application
I'm writing a vb.net .net 4.0 application and am having issues getting the timer to elapse.  Can someone help tell me what I'm doing wrong?

I've troubleshooted the main application so much that I decided to try to make it work in a new project and can't seem to get this to work.

Thanks!

```<code>Module Module1

Public Timer As New System.Timers.Timer

Sub Main()

    AddHandler Timer.Elapsed, AddressOf Timer_Tick
    Timer.AutoReset = True
    Timer.Interval = 1000
    Timer.Start()

    Console.WriteLine("Timer Started")

End Sub

Sub Timer_Tick(source As Object, e As EventArgs)
    Console.WriteLine("TimerTick")
End Sub
End Module
</code>```

答:
```<code>Sub Main

Timer.Interval = 60000  ' one minute
Timer.Enabled

' do stuff

Do until (Some condition, like a stop flag to stop looping and end program)
    System.Threading.Thread.Sleep(10000)
Loop

End

Timer_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles Timer.Elapsed

Timer.enabled = False

' do stuff

Timer.Enabled = True
End Sub
</code>```

Body:
I'm writing a vb.net .net 4.0 application and am having issues getting the timer to elapse.  Can someone help tell me what I'm doing wrong?

I've troubleshooted the main application so much that I decided to try to make it work in a new project and can't seem to get this to work.

Thanks!

Module Module1

Public Timer As New System.Timers.Timer

Sub Main()

    AddHandler Timer.Elapsed, AddressOf Timer_Tick
    Timer.AutoReset = True
    Timer.Interval = 1000
    Timer.Start()

    Console.WriteLine("Timer Started")

End Sub

Sub Timer_Tick(source As Object, e As EventArgs)
    Console.WriteLine("TimerTick")
End Sub
End Module


问:
Does instantiating multiple mysqli objects in a single PHP script get optimized?
I have a base model class that wraps mysqli. When I instantiate multiple models each one calls new mysqli(). If the parameters passed to mysqli() are the same will it be optimized for me and only use one connection?

I guess another way to ask this is...is this:

```$mysqli1 = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$mysqli2 = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$mysqli3 = new mysqli('localhost', 'my_user', 'my_password', 'my_db');```

more or less equivalent to this:

```$mysqli1 = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$mysqli2 = $mysqli1;
$mysqli3 = $mysqli1;```

Edit:
I remember reading somewhere that it does return a copy if you're already connected but I can't find it now.

答: No, it will open a new connection to the database. Every time you create an instance of mysqli class, even if with the same parameters, it will create a new instance.</p>

Body:
I have a base model class that wraps mysqli. When I instantiate multiple models each one calls new mysqli(). If the parameters passed to mysqli() are the same will it be optimized for me and only use one connection?

I guess another way to ask this is...is this:

$mysqli1 = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$mysqli2 = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$mysqli3 = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

more or less equivalent to this:

$mysqli1 = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$mysqli2 = $mysqli1;
$mysqli3 = $mysqli1;

Edit:
I remember reading somewhere that it does return a copy if you're already connected but I can't find it now.


问:
Why is my javascript function not found by the page it is embedded in?
I have a page that has a simple javascript in the header portion of the page:

```<code><script type="text/javascript">
    function doLogout() {
        var conf = confirm("Really log out?");
        if (conf === true) {      //changed == to === for boolean comparison
            $.post("logout.aspx");
        }
    }
</script>
</code>```

It uses jQuery to do an AJAX post to my logout page.  The only issue right now is that when I click on the link (logout) to fire this function, nothing happens.  I checked FireBug's console, and it told me that the function is not defined.  This has happened to me before, but I think I botched a bunch of code to fix it sometimes.

Does anyone know the proper way to fix this issue?

Edit

After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise!  Hopefully this information will be useful for more people.

OwnerDisplayName: Anders

Body:
I have a page that has a simple javascript in the header portion of the page:

It uses jQuery to do an AJAX post to my logout page.  The only issue right now is that when I click on the link (logout) to fire this function, nothing happens.  I checked FireBug's console, and it told me that the function is not defined.  This has happened to me before, but I think I botched a bunch of code to fix it sometimes.

Does anyone know the proper way to fix this issue?

Edit

After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise!  Hopefully this information will be useful for more people.

LastEditorDisplayName: Anders

Body:
Things to test:

1) Can you call this function from something else?  Like add a <script> at the bottom of the page to call it?

2) Does the page validate?  Sometimes I get screwy javascript errors if there is some busted HTML like a missing </b>

3) I've been starting to wrap my javascript in <![CDATA[  ]]> just incase I've got goofy chars in my javascript.

4) I assume you've tested this in other browsers and have the same behavior, right?

5) If you haven't installed it already, install the Web Developer firefox addon.  It has a nifty toolbar menu that will disable the cache for you so everything reloads.

6) As weird as it sounds, I once hit a javascript issue that was because of how my text editor was saving UTF-8 files.  I forget the details, but it was adding some byte-order-mark or something that upset the browser.

OwnerDisplayName: Cory R. King

LastEditorDisplayName: Cory R. King


问:
Problem with wp_enqueue_script
I'm trying to use wp_enqueue_script on my theme, to insert 3 javascript files on my page.

```<code>function mr_forms() {

            wp_register_script('validate-jquery',  get_bloginfo('template_url') . '/js/jquery.validate.min.js', array('jquery'),FALSE,TRUE);
            wp_enqueue_script('validate-jquery');
            wp_register_script('aditional-methods', get_bloginfo('template_url') . '/js/additional-methods.min.js', array('jquery','validate'),FALSE,TRUE);
            wp_enqueue_script('aditional-methods');
            wp_register_script('messages-ptbr', get_bloginfo('template_url') . '/js/messages_ptbr.js', array('jquery','validate'),FALSE,TRUE);
            wp_enqueue_script('messages-ptbr');
            wp_register_script('forms', get_bloginfo('template_url') . '/js/forms.js', array('jquery', 'maskedinput'), FALSE, TRUE);
            wp_enqueue_script('forms');
        }

        add_action('init', 'mr_forms');
</code>```

But only the last javascript, "forms.js" is being inserted on my page, the others arent, does anyone know what might be happening ? and the other doesnt matter...

答:
Have you named validate incorrectly in the other register scripts? Should be validate-jquery instead of validate?

```<code>function mr_forms() {

        wp_register_script('validate-jquery',  get_bloginfo('template_url') . '/js/jquery.validate.min.js', array('jquery'),FALSE,TRUE);
        wp_enqueue_script('validate-jquery');
        wp_register_script('aditional-methods', get_bloginfo('template_url') . '/js/additional-methods.min.js', array('jquery','validate-jquery'),FALSE,TRUE);
        wp_enqueue_script('aditional-methods');

wp_register_script('messages-ptbr', get_bloginfo('template_url') . '/js/messages_ptbr.js', array('jquery','validate-jquery'),FALSE,TRUE);

        wp_enqueue_script('messages-ptbr');
        wp_register_script('forms', get_bloginfo('template_url') . '/js/forms.js', array('jquery', 'maskedinput'), FALSE, TRUE);
        wp_enqueue_script('forms');
    }

    add_action('init', 'mr_forms');
</code>```

Title: Problem with wp_enqueue_script

Body:
I'm trying to use wp_enqueue_script on my theme, to insert 3 javascript files on my page.

function mr_forms() {

            wp_register_script('validate-jquery',  get_bloginfo('template_url') . '/js/jquery.validate.min.js', array('jquery'),FALSE,TRUE);
            wp_enqueue_script('validate-jquery');
            wp_register_script('aditional-methods', get_bloginfo('template_url') . '/js/additional-methods.min.js', array('jquery','validate'),FALSE,TRUE);
            wp_enqueue_script('aditional-methods');
            wp_register_script('messages-ptbr', get_bloginfo('template_url') . '/js/messages_ptbr.js', array('jquery','validate'),FALSE,TRUE);
            wp_enqueue_script('messages-ptbr');
            wp_register_script('forms', get_bloginfo('template_url') . '/js/forms.js', array('jquery', 'maskedinput'), FALSE, TRUE);
            wp_enqueue_script('forms');
        }

        add_action('init', 'mr_forms');

But only the last javascript, "forms.js" is being inserted on my page, the others arent, does anyone know what might be happening ? and the other doesnt matter...

Body:
Have you named validate incorrectly in the other register scripts? Should be validate-jquery instead of validate?

function mr_forms() {

        wp_register_script('validate-jquery',  get_bloginfo('template_url') . '/js/jquery.validate.min.js', array('jquery'),FALSE,TRUE);
        wp_enqueue_script('validate-jquery');
        wp_register_script('aditional-methods', get_bloginfo('template_url') . '/js/additional-methods.min.js', array('jquery','validate-jquery'),FALSE,TRUE);
        wp_enqueue_script('aditional-methods');

wp_register_script('messages-ptbr', get_bloginfo('template_url') . '/js/messages_ptbr.js', array('jquery','validate-jquery'),FALSE,TRUE);

        wp_enqueue_script('messages-ptbr');
        wp_register_script('forms', get_bloginfo('template_url') . '/js/forms.js', array('jquery', 'maskedinput'), FALSE, TRUE);
        wp_enqueue_script('forms');
    }

    add_action('init', 'mr_forms');


问:
Python method not recognized
I am learning python so I have worked on this one thing a long time.  I still can't find the answer.

Interpreter says there is no method called _set_icon()

code:

```<code>import pyodbc as db
import pandas as pd

import Globals

class BatchNodeData(object):
    """support batch node of the tree.  Contains what it needs to do that"""

    def __init__(self):
        pass

    def _set_icon():
        sql_conn = db.connect(Globals.SQL_CONN_STRING)
        b_query = " \
              SELECT top 1 * \
                FROM dbo.ETLBatchRun a \
                Where b.BatchID = " + str(batchid) + \
                "Order by a.StatusDT desc"
        df_icon = pd.read_sql(b_query, sql_conn)
        if not df_icon.empty:
            self.last_status = df_icon['StatusID'].iloc[0]

    def _get_icon_index():
        switcher = {
            1: 2,
            2: 2,
            3: 3,
            4: 4
        }
        switcher_selected = {
            1: 7,
            2: 7,
            3: 8,
            4: 8
        }
        if selected:
            return switcher_selected.get(statusid, 0) # default 0 (yellow bar)
        else:
            return switcher.get(statusid, 0) # default 0 (yellow bar)

    def __init__(self, batchid):
        self.batch_id = None
        self.batch_name = None
        self.critical = None
        self.node_icon_index = None
        self.last_status = None
        self.selected = False
        self.running = False

        sql_conn = db.connect(Globals.SQL_CONN_STRING)
        b_query = " \
              select b.BatchID \
              , b.BatchName \
              , c.AttributeValue as Critical \
              , noRun.AttributeValue as noRun \
              from dbo.ETLBatch b (nolock) \
              left join dbo.etlbatchattribute (nolock) c \
                on c.batchid = b.batchid \
                    and c.AttributeName = 'Critical' \
                    and c.AttributeValue = '1' \
              left join dbo.etlbatchattribute (nolock) noRun \
                on noRun.batchid = b.batchid \
                    and noRun.AttributeName = 'NotRunnableInETLMonitor' \
                    and noRun.AttributeValue = '1' \
              Where b.BatchID = " + str(batchid)
        df_batch = pd.read_sql(b_query, sql_conn)
        for index, row in df_batch.iterrows():
            batch_id = row['BatchID']
            batch_name = row['BatchName']
            critical = row['Critical']
        _set_icon()
        self.node_icon_index = _get_icon_index()
</code>```

答:
Since you've declared _set_icon() as a method bounded by the class, you should be able to call it as:</p>

```<code>BatchNodeData._set_icon()
</code>```

Title: Python method not recognized

Body:
I am learning python so I have worked on this one thing a long time.  I still can't find the answer.

Interpreter says there is no method called _set_icon()

code:

import pyodbc as db
import pandas as pd

import Globals

class BatchNodeData(object):
    """support batch node of the tree.  Contains what it needs to do that"""

    def __init__(self):
        pass

    def _set_icon():
        sql_conn = db.connect(Globals.SQL_CONN_STRING)
        b_query = " \
              SELECT top 1 * \
                FROM dbo.ETLBatchRun a \
                Where b.BatchID = " + str(batchid) + \
                "Order by a.StatusDT desc"
        df_icon = pd.read_sql(b_query, sql_conn)
        if not df_icon.empty:
            self.last_status = df_icon['StatusID'].iloc[0]

    def _get_icon_index():
        switcher = {
            1: 2,
            2: 2,
            3: 3,
            4: 4
        }
        switcher_selected = {
            1: 7,
            2: 7,
            3: 8,
            4: 8
        }
        if selected:
            return switcher_selected.get(statusid, 0) # default 0 (yellow bar)
        else:
            return switcher.get(statusid, 0) # default 0 (yellow bar)

    def __init__(self, batchid):
        self.batch_id = None
        self.batch_name = None
        self.critical = None
        self.node_icon_index = None
        self.last_status = None
        self.selected = False
        self.running = False

        sql_conn = db.connect(Globals.SQL_CONN_STRING)
        b_query = " \
              select b.BatchID \
              , b.BatchName \
              , c.AttributeValue as Critical \
              , noRun.AttributeValue as noRun \
              from dbo.ETLBatch b (nolock) \
              left join dbo.etlbatchattribute (nolock) c \
                on c.batchid = b.batchid \
                    and c.AttributeName = 'Critical' \
                    and c.AttributeValue = '1' \
              left join dbo.etlbatchattribute (nolock) noRun \
                on noRun.batchid = b.batchid \
                    and noRun.AttributeName = 'NotRunnableInETLMonitor' \
                    and noRun.AttributeValue = '1' \
              Where b.BatchID = " + str(batchid)
        df_batch = pd.read_sql(b_query, sql_conn)
        for index, row in df_batch.iterrows():
            batch_id = row['BatchID']
            batch_name = row['BatchName']
            critical = row['Critical']
        _set_icon()
        self.node_icon_index = _get_icon_index()

Body:
Since you've declared _set_icon() as a method bounded by the class, you should be able to call it as:

BatchNodeData._set_icon()


问:
PHP Intl functions does not work for some countries
Trying to get the language name from the language code, I run

```<code>function test($local, $fallback)
{
    $bundle = \ResourceBundle::create($local, 'ICUDATA-lang', $fallback);
    if ($bundle === null) {
        return "$local bundle not found";
    }
    $var = $bundle->get('Languages',$fallback);
    return $var->get('fr',$fallback);
}

$locals = ['en', 'en_US', 'foo', 'en_AU', 'en_NZ'];

foreach ($locals as $local) {
    var_dump(test($local, true));
}
echo PHP_EOL;
foreach ($locals as $local) {
    var_dump(test($local, false));
}
</code>```

```<code>string(6) "French"
string(6) "French"
NULL
NULL
NULL

string(6) "French"
string(22) "en_US bundle not found"
string(20) "foo bundle not found"
NULL
NULL
</code>```

It returns null for Australia and New Zealand that indicates an Intl error of

Cannot load resource element 'fr': U_MISSING_RESOURCE_ERROR"

The third parameter of \ResourceBundle::create functions is for call back that means it should fallback to its parent locale. Interestingly the parent locale of en_AU is en_001.

Is it a bug or I have missed something?

答:
Background

In the ICU-Data-Directory that you listed on GitHub (note that you were on a release branch rather than master branch), there are neither files for en_US nor en_UK present. On the master branch you can find an en_GB file which seems to be the proper locale code rather than UK.

Though I can not say why the en_US is not around (which I would absolutely expect, just as you did), it appears that with all your tests where you are getting "French" as a result, you are not actually loading the correct ICU path but rather because that one can not be found, the root path is loaded.

You already evidenced that by trying with en_foobar. Same works if you try to load any other nonsense locale that just does not exist in that data directory, and the same is true for both en_US and en_UK (since they do both not exist, as explained before).

As a side note: I think you may have misunderstood the fallback parameter. This is so that if the language can not be loaded, the fallback language is loaded - not that any data you request on it would directly be requested on the parent.

Code examples

To make it a bit more clear what I am talking about, here are some examples.

Loading with nonsense locales always loads the whole directory data so you have access to all the root data:

```<code>$bundle = \ResourceBundle::create('stackoverflow-is-great', 'ICUDATA-lang', true);
var_dump($bundle->get('Languages')->get('fr')); // string(6) "French"
var_dump($bundle->get('Languages')->get('de')); // string(6) "German"
</code>```

Loading sub-languages from en_NZ that do not exist:

```<code>$bundle = \ResourceBundle::create('en_NZ', 'ICUDATA-lang', true);
var_dump($bundle->get('Languages')->get('fr')); // NULL
var_dump($bundle->get('Languages')->get('de')); // NULL
</code>```

Loading sub-languages from en_NZ that do exist:

```<code>$bundle = \ResourceBundle::create('en_NZ', 'ICUDATA-lang', true);
var_dump($bundle->get('Languages')->get('mi')); // string(6) "Māori"
</code>```

To put it in a nutshell: It actually works as expected and gives you data where it is available, and no data where none is available.

Debugging

How did I find that out? Based on this user comment on the PHP ResourceBundle docs page. I added a depth output and had a very handy debug function:

```<code>function t($rb, $depth = 0) {
    foreach($rb as $k => $v) {
        echo str_repeat('->', $depth);
        if(is_object($v)) {
            print_r($v);
            var_dump($k);
            t($v, ++$depth);
        } else {
            var_dump($k . " " . $v);
        }
    }
}
$rb = new ResourceBundle('en_UK', 'ICUDATA-lang', true);
var_dump($rb->get('Languages')->get('fr'));

t($rb);
</code>```

This prints a (really long, which is why I am not adding it here) output which looks suspiciously like the root data.

One last side note: en_GB seems to be aliased to en_001 here as well, I am not sure to what effect though.

TL;DR: First three locales do not really exist in the data set and hence root data is loaded, en_NZ and en_AU work just like they should.

Body:
Trying to get the language name from the language code, I run

function test($local, $fallback)
{
    $bundle = \ResourceBundle::create($local, 'ICUDATA-lang', $fallback);
    if ($bundle === null) {
        return "$local bundle not found";
    }
    $var = $bundle->get('Languages',$fallback);
    return $var->get('fr',$fallback);
}

$locals = ['en', 'en_US', 'foo', 'en_AU', 'en_NZ'];

foreach ($locals as $local) {
    var_dump(test($local, true));
}
echo PHP_EOL;
foreach ($locals as $local) {
    var_dump(test($local, false));
}

string(6) "French"
string(6) "French"
NULL
NULL
NULL

string(6) "French"
string(22) "en_US bundle not found"
string(20) "foo bundle not found"
NULL
NULL

It returns null for Australia and New Zealand that indicates an Intl error of

Cannot load resource element 'fr': U_MISSING_RESOURCE_ERROR"

The third parameter of \ResourceBundle::create functions is for call back that means it should fallback to its parent locale. Interestingly the parent locale of en_AU is en_001.

Is it a bug or I have missed something?

Body:
Background

In the ICU-Data-Directory that you listed on GitHub (note that you were on a release branch rather than master branch), there are neither files for en_US nor en_UK present. On the master branch you can find an en_GB file which seems to be the proper locale code rather than UK.

Though I can not say why the en_US is not around (which I would absolutely expect, just as you did), it appears that with all your tests where you are getting "French" as a result, you are not actually loading the correct ICU path but rather because that one can not be found, the root path is loaded.

You already evidenced that by trying with en_foobar. Same works if you try to load any other nonsense locale that just does not exist in that data directory, and the same is true for both en_US and en_UK (since they do both not exist, as explained before).

As a side note: I think you may have misunderstood the fallback parameter. This is so that if the language can not be loaded, the fallback language is loaded - not that any data you request on it would directly be requested on the parent.

Code examples

To make it a bit more clear what I am talking about, here are some examples.

Loading with nonsense locales always loads the whole directory data so you have access to all the root data:

$bundle = \ResourceBundle::create('stackoverflow-is-great', 'ICUDATA-lang', true);
var_dump($bundle->get('Languages')->get('fr')); // string(6) "French"
var_dump($bundle->get('Languages')->get('de')); // string(6) "German"

Loading sub-languages from en_NZ that do not exist:

$bundle = \ResourceBundle::create('en_NZ', 'ICUDATA-lang', true);
var_dump($bundle->get('Languages')->get('fr')); // NULL
var_dump($bundle->get('Languages')->get('de')); // NULL

Loading sub-languages from en_NZ that do exist:

$bundle = \ResourceBundle::create('en_NZ', 'ICUDATA-lang', true);
var_dump($bundle->get('Languages')->get('mi')); // string(6) "Māori"

To put it in a nutshell: It actually works as expected and gives you data where it is available, and no data where none is available.

Debugging

How did I find that out? Based on this user comment on the PHP ResourceBundle docs page. I added a depth output and had a very handy debug function:

function t($rb, $depth = 0) {
    foreach($rb as $k => $v) {
        echo str_repeat('->', $depth);
        if(is_object($v)) {
            print_r($v);
            var_dump($k);
            t($v, ++$depth);
        } else {
            var_dump($k . " " . $v);
        }
    }
}
$rb = new ResourceBundle('en_UK', 'ICUDATA-lang', true);
var_dump($rb->get('Languages')->get('fr'));

t($rb);

This prints a (really long, which is why I am not adding it here) output which looks suspiciously like the root data.

One last side note: en_GB seems to be aliased to en_001 here as well, I am not sure to what effect though.

TL;DR: First three locales do not really exist in the data set and hence root data is loaded, en_NZ and en_AU work just like they should.


问:
JavaScript Define Property in Terms of Method
Please note this question is not answered by
Self-references in object literals / initializers
as that question addresses defining properties in terms of other properites, not methods.

Also, How does the "this" keyword in Javascript act within an object literal? is too high-level a decription of the subject for me to be able to solve my use case.

In Python, I can do this:

```<code>class Test:
    def __init__(self):
        self.id = self.get_id()

    def get_id(self):
        return 10

t = Test()
print(t.id)
</code>```

Meaning an object property can be defined in terms of a method of the same object.

In JavaScript, it doesn't work:

```<code>var Test = {
  id : this.getId(),
  getId : function() {
    return 10;
  }
};
</code>```

Gives script.js:47 Uncaught TypeError: this.getId is not a function

I've tried defining the id after the method definition but that didn't work.

How do I do this in JavaScript please?

答:
You can only use this inside a method. There's no way to reference the current object in an object literal.

But you can refer to it after the object is created.

```<code>var Test = {
  getId : function() {
    return 10;
  }
};
Test.id = Test.getId()
</code>```

Body:
Please note this question is not answered by
Self-references in object literals / initializers
as that question addresses defining properties in terms of other properites, not methods.

Also, How does the "this" keyword in Javascript act within an object literal? is too high-level a decription of the subject for me to be able to solve my use case.

In Python, I can do this:

class Test:
    def __init__(self):
        self.id = self.get_id()

    def get_id(self):
        return 10

t = Test()
print(t.id)

Meaning an object property can be defined in terms of a method of the same object.

In JavaScript, it doesn't work:

var Test = {
  id : this.getId(),
  getId : function() {
    return 10;
  }
};

Gives script.js:47 Uncaught TypeError: this.getId is not a function

I've tried defining the id after the method definition but that didn't work.

How do I do this in JavaScript please?

Body:
You can only use this inside a method. There's no way to reference the current object in an object literal.

But you can refer to it after the object is created.

var Test = {
  getId : function() {
    return 10;
  }
};
Test.id = Test.getId()


问:
The difference between a var and function in javascript
I have been having problems understanding the difference between a var and a function.I have tried to  search it on internet and i wrote the same thing inside a var and  function and i got the same results.I would really like a explanation to tell me when to use var and when to use function.</p>

答:
If you mean this:

```<code>function foo() {
    // ...
}
</code>```

Produces the same result as this:

```<code>var foo = function() {
    // ...
}
</code>```

You've just discovered that the functions are First class citizens in JavaScript. There are almost no differences between the two syntaxes. The latter is useful when manipulating functions as objects (e.g: var foo = bar, bar being a function) but has no real interest when it's about static functions.

One difference between the two syntaxes is that you can call a function before it is declared, but not when it's a variable:

foo();

function foo() {
    console.log('foo');
}

bar();

var bar = function() {
    console.log('bar');
}```
</div>
</div>
</p>

<p>Note that you can reassign a function like you would do with a variable:</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>function foo() {
    // ...
}

// Reassign the function with a string
foo = 'bar';

try {
    foo();
} catch(e) {
    console.error(e);
    console.log('foo:', foo);
}</code>```

Body:
If you mean this:

function foo() {
    // ...
}

Produces the same result as this:

var foo = function() {
    // ...
}

You've just discovered that the functions are First class citizens in JavaScript. There are almost no differences between the two syntaxes. The latter is useful when manipulating functions as objects (e.g: var foo = bar, bar being a function) but has no real interest when it's about static functions.

One difference between the two syntaxes is that you can call a function before it is declared, but not when it's a variable:

foo();

function foo() {
    console.log('foo');
}

bar();

var bar = function() {
    console.log('bar');
}

Note that you can reassign a function like you would do with a variable:

function foo() {
    // ...
}

// Reassign the function with a string
foo = 'bar';

try {
    foo();
} catch(e) {
    console.error(e);
    console.log('foo:', foo);
}


问:
htaccess help moving Expression Engine site to Wordpress
I currently have an Expression Engine blog which I am going to move over to Wordpress, the current url structure is /blog/comments/page-title

I have imported the posts into Wordpress and I'm going to keep the same page title's for the pretty urls but just want the address to be /page-title

the Wordpress htaccess file is as follows

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

can anybody tell me how I do this additional redirect in this block? Also will this totally ensure that search engine indexing won't be affected as it has been running for 4 years and I have over 1700 blog posts currently indexed.

答:
Put this before your WordPress rules in your .htaccess file:

RedirectMatch ^/blog/comments/(.+)$ /$1 [R=301]

This will redirect http://yourdomain.com/blog/comments/my-post to http://yourdomain.com/my-post, and tell search engines that the redirect is permanent.

One note: WordPress discourages the use of /%postname%/ as a permalink structure as it adds many more queries to determine the content to load. From http://codex.wordpress.org/Using_Permalinks:

Starting Permalinks with %postname% is strongly not recommended for performance reasons.

So I'd suggest instead using something like /blog/%postname% instead, in which case your rule would look like:

RedirectMatch ^/blog/comments/(.+)$ /blog/$1 [R=301]

Body:
I currently have an Expression Engine blog which I am going to move over to Wordpress, the current url structure is /blog/comments/page-title

I have imported the posts into Wordpress and I'm going to keep the same page title's for the pretty urls but just want the address to be /page-title

the Wordpress htaccess file is as follows

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

can anybody tell me how I do this additional redirect in this block? Also will this totally ensure that search engine indexing won't be affected as it has been running for 4 years and I have over 1700 blog posts currently indexed.


问:
Time complexity : simple loop calculation
I have a simple loop like this :

```<code>for (int i = 0; i < n; i++) {
  // constant time operation
}
</code>```

It’s very easy to see that it’s of O(n) time complexity, but if we calculate it, why is it 2*n + 2 + c*n (given answer) and not (1+ (n+1) + 2*n + c*n) = (3+c)*n + 2? I see i++ as 2 operations: addition and assignment; thus, it should be 2*n, and the constant operation is executed n times, so it’s c*n.

答:
```<code>2*n
</code>```

(n comparisons (i<n)
+ n increments (i++)) == 2*n

```<code>2
</code>```

(i=0 1 for assignment
+ 1 for allocation of i) == 2

```<code>c*n
</code>```

(n constant time operations) == c*n

Body:
I have a simple loop like this :

for (int i = 0; i < n; i++) {
  // constant time operation
}

It’s very easy to see that it’s of O(n) time complexity, but if we calculate it, why is it 2*n + 2 + c*n (given answer) and not (1+ (n+1) + 2*n + c*n) = (3+c)*n + 2? I see i++ as 2 operations: addition and assignment; thus, it should be 2*n, and the constant operation is executed n times, so it’s c*n.

Body:
2*n

(n comparisons (i<n)
+ n increments (i++)) == 2*n

2

(i=0 1 for assignment
+ 1 for allocation of i) == 2

c*n

(n constant time operations) == c*n


问:
matplotlib.pyplot.FuncAnimation.save() unintentionally crops animations. How do I avoid this?
I want to save an animation made via plt.FuncAnimation(). It has a long title and text boxes (showing various parameters) to the side. I've tried ffpmeg (.mp4), pillow (.gif) and imagemagick (.gif) writers. All attempts lead to the output file seemingly zooming-in on the main figure, both cutting off text and lowering quality. How do I avoid this?

The same issue arose with saving figures via plt.savefig(), but this is fixed via either plt.tight_layout() or plt.savefig(bbox_inches='tight'). Neither of these work with plt.FuncAnimation().save().

Here's an example:

```<code>"""
Matplotlib Animation Example

author: Jake Vanderplas
email: vanderplas@astro.washington.edu
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

ax.set_title('This is a really long title that is cropped in the .mp4, but not the .ipynb output.')

ax.text(3, 0.5, 'Text outside the graph is also cropped in the .mp4, but not the .ipynb output.')

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

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

答: I managed to solve this by using empty subplots. See here for details on how to completely hide a subplot. Then you can add shapes/text in that subplot as desired.</p>

Body:
I want to save an animation made via plt.FuncAnimation(). It has a long title and text boxes (showing various parameters) to the side. I've tried ffpmeg (.mp4), pillow (.gif) and imagemagick (.gif) writers. All attempts lead to the output file seemingly zooming-in on the main figure, both cutting off text and lowering quality. How do I avoid this?

The same issue arose with saving figures via plt.savefig(), but this is fixed via either plt.tight_layout() or plt.savefig(bbox_inches='tight'). Neither of these work with plt.FuncAnimation().save().

Here's an example:

"""
Matplotlib Animation Example

author: Jake Vanderplas
email: vanderplas@astro.washington.edu
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

ax.set_title('This is a really long title that is cropped in the .mp4, but not the .ipynb output.')

ax.text(3, 0.5, 'Text outside the graph is also cropped in the .mp4, but not the .ipynb output.')

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()


答:
From what I can tell, increment/decrement is treated as a single operation. This makes sense because in assembly, you can perform an increment or decrement with a single line of assembly code. Furthermore, most lines of assembly code translate directly to a single binary instruction. Thus, increment/decrement is effectively a constant time operation.

Therefore, we have n operations from incrementing. We also run the body of the loop n times, and the body of the loop performs a constant time operation, so we have an additional c * n operations. When we enter the loop the first time, there is an additional assignment operation. This yields another operation. Finally, after the loop runs the nth time, the loop checks the condition of the loop one more time. This means there are n + 1 comparisons that the loop performs.

Adding these up, we have n + c * n + 1 + (n + 1) = 2 * n + c * n + 2, which is the answer you saw.

Title: Time complexity : simple loop calculation


问:
React hooks how to only execute side effect function only once if I need to update 2 dependency variables
Lets say I have the following component using react hooks

const Component = (props) => {
   [state1, setState1] = useState();
   [state2, setState2] = useState();
   useEffect(()=>{
       // use state1 and state2 as param to fetch data
       ...
   }, [state1, state2])

   onSomethingChange = () => {
       setState1(...);
       setState2(...);
   }

   return (..);
}
```

When onSomethingChange triggers, I thought it would call the side effect function twice since I update 2 different state vars in the same dependency array. And I was going to refactor those 2 vars into 1 object but I thought I would test them as 2 separate vars first.

What I observed is the side effect function only gets executed once even when I update 2 different state vars in the same dependency array, this is what I wanted but I don't know why. Could someone please explain how it works under the bonnet?

答: That's because React sometimes may batch multiple state changes into one update for performance. React will batch state updates if they're triggered from within a React-based event, that's the reason why your side effect block is called only once. For more information, you may refer this thread: https://github.com/facebook/react/issues/14259</p>

Body:
Lets say I have the following component using react hooks

const Component = (props) => {
   [state1, setState1] = useState();
   [state2, setState2] = useState();
   useEffect(()=>{
       // use state1 and state2 as param to fetch data
       ...
   }, [state1, state2])

   onSomethingChange = () => {
       setState1(...);
       setState2(...);
   }

   return (..);
}

When onSomethingChange triggers, I thought it would call the side effect function twice since I update 2 different state vars in the same dependency array. And I was going to refactor those 2 vars into 1 object but I thought I would test them as 2 separate vars first.

What I observed is the side effect function only gets executed once even when I update 2 different state vars in the same dependency array, this is what I wanted but I don't know why. Could someone please explain how it works under the bonnet?


问:
Creating new column based on if statement of another column grabbing data from yet two different columns
I have data that looks like this:

```<code>A    B    C    D
3    1    4    0.5
4    2    6    0.25
2    1    3   -0.4
3    3    6   -0.8
</code>```

And I'd like to add a column E which is the result of either A divided by C or B divided by C based on if D < 0. I figured I should use apply in this situation but I don't really know how to work both a loop and an if statement into apply(). Any suggestions on how to tackle this?

答:
np.where might help here:
Pandas conditional creation of a series/dataframe column</p>

```<code>df['E'] = np.where(df['D'] < 0, df['A']/df['C'], df['B']/df['C'])
</code>```

Body:
I have data that looks like this:

A    B    C    D
3    1    4    0.5
4    2    6    0.25
2    1    3   -0.4
3    3    6   -0.8

And I'd like to add a column E which is the result of either A divided by C or B divided by C based on if D < 0. I figured I should use apply in this situation but I don't really know how to work both a loop and an if statement into apply(). Any suggestions on how to tackle this?

Body:
np.where might help here:
Pandas conditional creation of a series/dataframe column

df['E'] = np.where(df['D'] < 0, df['A']/df['C'], df['B']/df['C'])


问:
Add ACF Post Object field to Wordpress admin column
I have a custom post type for books that has two ACF fields, book_title and book_author. I have a separate custom post type for passages from the book, which pulls in a book, as an ACF post object, into two fields in the passages custom post type with the same field names.

I would like to be able to display the book_title and book_author fields as columns in the passages custom post type list. I am currently able to pull in the title of the book, but thats only because I am grabbing the title of the post, not the actual book_title field from the post. Is there a way to grab fields from a post object like this and set them as columns?

Here is my current code from my passages custom post type file:

function add_acf_columns($columns)
{
    return array_merge($columns, array(
        'book_title' => __('Book Title') ,
        'book_author' => __('Book Author')
    ));
}
add_filter('manage_passages_posts_columns', 'add_acf_columns');

function passages_custom_column($column, $post_id)
{
    switch ($column)
    {
        case 'book_title':
            echo get_the_title(get_field('book_title', $post_id));
        break;
        case 'book_author':
            echo get_post_meta($post_id, 'book_author', true);
        break;
    }
}
add_action('manage_passages_posts_custom_column', 'passages_custom_column', 10, 2);
```

答:
I'm a tad confused on your actual set up, but the general idea should apply here. When using the ACF "Relational > Post Object" field, it stores the actual relative WP_Post object. This allows you to reference anything you want from it without having to invoke anything special.

Just doing the following:

```<code>$object = get_field( 'name_of_field', $post_id );
</code>```

Will give you access to whatever data you want from that post/custom post type:

```<code>$title = $object->post_title;
$author_id = $object->post_author;
</code>```

So, like I mentioned, I'm a bit confused on your actual field names and where the actual object is stored, but I think the same post object is stored in both the book_title and book_author fields? Either way, you just need to get the WP_Post object with get_field, and then you'll have access to everything related to it. Then you can ouput the title, and use something like get_the_author_meta() to get the author's display/first/last name, etc.

```<code>add_action('manage_passages_posts_custom_column', 'passages_custom_column', 10, 2);
function passages_custom_column($column, $post_id) {
    switch( $column ){
        case 'book_title':
            $book_object = get_field( 'book_title', $post_id );
            echo ($book_object) ? $book_object->post_title : '';
            break;
        case 'book_author':
            $book_object = get_field( 'book_author', $post_id );
            if( $book_object ){
                echo get_the_author_meta( 'display_name', $book_object->post_author );
            }
            break;
    }
}
</code>```

Body:
I'm a tad confused on your actual set up, but the general idea should apply here. When using the ACF "Relational > Post Object" field, it stores the actual relative WP_Post object. This allows you to reference anything you want from it without having to invoke anything special.

Just doing the following:

$object = get_field( 'name_of_field', $post_id );

Will give you access to whatever data you want from that post/custom post type:

$title = $object->post_title;
$author_id = $object->post_author;

So, like I mentioned, I'm a bit confused on your actual field names and where the actual object is stored, but I think the same post object is stored in both the book_title and book_author fields? Either way, you just need to get the WP_Post object with get_field, and then you'll have access to everything related to it. Then you can ouput the title, and use something like get_the_author_meta() to get the author's display/first/last name, etc.

add_action('manage_passages_posts_custom_column', 'passages_custom_column', 10, 2);
function passages_custom_column($column, $post_id) {
    switch( $column ){
        case 'book_title':
            $book_object = get_field( 'book_title', $post_id );
            echo ($book_object) ? $book_object->post_title : '';
            break;
        case 'book_author':
            $book_object = get_field( 'book_author', $post_id );
            if( $book_object ){
                echo get_the_author_meta( 'display_name', $book_object->post_author );
            }
            break;
    }
}


问:
Link to external texture file in self-contained XAML representing a 3D model
I have a XAML file representing a 3D model with textures.

I want to make the textures read from the same place the file is, or relative to it.

I read the file using a XamlReader, so I want the file to be self-contained.

I place the textures using an ImageBrush which ImageSource is a pack synatx URI.

When I use a 'siteoforigin' syntax, this only works if the texture file is next to the application. I want it to be next to the Xaml, wherever it is.

I tried setting the current directory to the Xaml directory, but it didn't help.

Not using a pack syntax doesn't work as well - it just look for a resource by that name.

How do I need to write the Xaml image source (or is there another way to place textures for a diffuse material brush?) so it will work?

Itai.

答:
If your model is a stand alone xaml file i think it will be problematic to load the texture using xaml alone in the way you describe. Site of origin will always start from where the application is located, so if your xaml file is at some arbitrary location, and not under the same path of the application, it will not be usable

I'd suggest adding the image file to the resources collection of the control after you've actually loaded it from xaml. Then the actual xaml can then bind to the image like any other resource.


问:
Python - plotting 2D array but need the indices to correspond to coordinates. How do I do this?
I have an array of 2D data that I'd like to plot using imshow(). Since my data is in a 2D array, it's indexed as 0-300 x 0-300. However, the real data translates to physical X,Y coordinates. So, the value at arr[0,0] would actually correspond to the value at X,Y coordinate (-3,-3). I'm not sure how to properly plot that so that the axes of my plot range from (-3 to 3) as opposed to (0 to 300).

I'm using matplotlib and Python.

答: imshow comes with extent which solves your problem, you can read about how to use it here.


问:
Spring Boot: custom AutoConfiguration class fails to find properties
I have a library for a FooService.

Here's it's AutoConfiguration class:

```<code>@Configuration
@EnableConfigurationProperties(FooProperties.class)
public class FooServiceAutoConfigure {

    @Autowired
    FooProperties config;

    @Bean
    public FooService getFooService() throws Exception {
           return new FooService(config.username, config.password)

    }
}
</code>```

Here's the FooProperties class:

```<code>@ConfigurationProperties(prefix = "foo")
public class FooProperties {
    String username;
    String password;
}
</code>```

In resources/META-INF/spring.factories I have the following line:

```<code>org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.my.company.FooServiceAutoConfigure
</code>```

In my main project (which is a @SpringBootApplication), I have:

A Maven dependency to this library.

foo.username and foo.password in application.properties

Some @Autowired FooService.

I can see in the logs that Spring Boot is trying to instantiate FooService but the config.username and config.password are nulls. Why?

答:
Solved.

I'll answer for future readers:

There weren't setters for FooProperties

Body:
I have a library for a FooService.

Here's it's AutoConfiguration class:

@Configuration
@EnableConfigurationProperties(FooProperties.class)
public class FooServiceAutoConfigure {

    @Autowired
    FooProperties config;

    @Bean
    public FooService getFooService() throws Exception {
           return new FooService(config.username, config.password)

    }
}

Here's the FooProperties class:

@ConfigurationProperties(prefix = "foo")
public class FooProperties {
    String username;
    String password;
}

In resources/META-INF/spring.factories I have the following line:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.my.company.FooServiceAutoConfigure

In my main project (which is a @SpringBootApplication), I have:

A Maven dependency to this library.

foo.username and foo.password in application.properties

Some @Autowired FooService.

I can see in the logs that Spring Boot is trying to instantiate FooService but the config.username and config.password are nulls. Why?


问:
Reading array of regs using Verilator and VPI
So I have the following register defined in my verilog

```<code>reg [31:0] register_mem [0:15]/* verilator public */;
</code>```

My goal is from my verilator c++ code to read each of the 16 values stored in it.

I have found that the documentation for this VPI stuff is rather difficult to find. I still cannot figure out what a t_vpi_vecval is and what its parameters are or if it is even the right approach.

Here is my approach at reading the 5th value in the register

```<code>unsigned int read_regs() {
    const std::string path = "TOP.TOP.cpu.reg_file.register_mem";
    vpiHandle vh1 = vpi_handle_by_name((PLI_BYTE8*)path.c_str(), NULL);
    if (!vh1) {
        printf("Name %s", path.c_str());
        vl_fatal(__FILE__, __LINE__, "sim_main", "No handle found: ");
    }
    const char* name = vpi_get_str(vpiName, vh1);

    s_vpi_value v;
    v.format = vpiVectorVal;
    vpi_get_value(vh1, &v);
    return v.value.vector[4].aval;
}
</code>```

No-matter what I do here the method returns 0 suggesting that I am not looking at the register_mem array.

What am I doing wrong?

答:
In order to get values of the array, you need to get values for every element of an array separately. VPI does not return values for the full array.

Actually the handle which you get for an array is a handle of the vpiRegArray type. It can be iterated to access every separate element.

Here is a simple code which does the iteration and prints values of every element in the array:

```<code>
#include "vpi_user.h"

PLI_INT32 preg_calltf( char *txt ) {
    vpiHandle hreg = vpi_handle_by_name("rarr.register_mem", 0);
    vpi_printf("reg type: %s\n", vpi_get_str(vpiType, hreg)); // vpiRegArray

    s_vpi_value val = {vpiDecStrVal}; // struct t_vpi_value

    vpiHandle arrayIterator = vpi_iterate( vpiReg, hreg);
    if( arrayIterator != NULL ) {
        vpiHandle item = NULL;
        while( NULL != ( item = vpi_scan( arrayIterator ) ) ) {
            vpi_get_value(item, &val);
            vpi_printf("item type: %s = %s\n", vpi_get_str(vpiType, item), val.value.str); // vpiReg
            vpi_free_object( item );
        }
    }

    return 0;
}
</code>```

In this case I initialized the val with vpiDecStrVal. It instructs the compiler to prepare value results as a decimal string. The value is now accessible as val.value.str. You have multiple choices to get string or binary data in 2-state or 4-state representation.

For 2-state values up to 32 bit you can use an integer formatting. However, for longer values or 4-state, you need vpiVectorVal. It actually requests verilog to create 2 arrays of 32-bit integers, aval and bval. Both have sizes big enough to keep all bits of the value. Combination of bits in aval and bval represent the 4-state value of all bits in the vector.

All vpi information is available in LRM including relation diagrams and data structures. There are also some books, for example "the verilog pli handbook" by Sutherland.

Body:
So I have the following register defined in my verilog

reg [31:0] register_mem [0:15]/* verilator public */;

My goal is from my verilator c++ code to read each of the 16 values stored in it.

I have found that the documentation for this VPI stuff is rather difficult to find. I still cannot figure out what a t_vpi_vecval is and what its parameters are or if it is even the right approach.

Here is my approach at reading the 5th value in the register

unsigned int read_regs() {
    const std::string path = "TOP.TOP.cpu.reg_file.register_mem";
    vpiHandle vh1 = vpi_handle_by_name((PLI_BYTE8*)path.c_str(), NULL);
    if (!vh1) {
        printf("Name %s", path.c_str());
        vl_fatal(__FILE__, __LINE__, "sim_main", "No handle found: ");
    }
    const char* name = vpi_get_str(vpiName, vh1);

    s_vpi_value v;
    v.format = vpiVectorVal;
    vpi_get_value(vh1, &v);
    return v.value.vector[4].aval;
}

No-matter what I do here the method returns 0 suggesting that I am not looking at the register_mem array.

What am I doing wrong?

Body:
In order to get values of the array, you need to get values for every element of an array separately. VPI does not return values for the full array.

Actually the handle which you get for an array is a handle of the vpiRegArray type. It can be iterated to access every separate element.

Here is a simple code which does the iteration and prints values of every element in the array:

#include "vpi_user.h"

PLI_INT32 preg_calltf( char *txt ) {
    vpiHandle hreg = vpi_handle_by_name("rarr.register_mem", 0);
    vpi_printf("reg type: %s\n", vpi_get_str(vpiType, hreg)); // vpiRegArray

    s_vpi_value val = {vpiDecStrVal}; // struct t_vpi_value

    vpiHandle arrayIterator = vpi_iterate( vpiReg, hreg);
    if( arrayIterator != NULL ) {
        vpiHandle item = NULL;
        while( NULL != ( item = vpi_scan( arrayIterator ) ) ) {
            vpi_get_value(item, &val);
            vpi_printf("item type: %s = %s\n", vpi_get_str(vpiType, item), val.value.str); // vpiReg
            vpi_free_object( item );
        }
    }

    return 0;
}

In this case I initialized the val with vpiDecStrVal. It instructs the compiler to prepare value results as a decimal string. The value is now accessible as val.value.str. You have multiple choices to get string or binary data in 2-state or 4-state representation.

For 2-state values up to 32 bit you can use an integer formatting. However, for longer values or 4-state, you need vpiVectorVal. It actually requests verilog to create 2 arrays of 32-bit integers, aval and bval. Both have sizes big enough to keep all bits of the value. Combination of bits in aval and bval represent the 4-state value of all bits in the vector.

All vpi information is available in LRM including relation diagrams and data structures. There are also some books, for example "the verilog pli handbook" by Sutherland.


问:
How to see what monitor is a thread waiting for via API?
We have a junit test runner which timeout if one test is hanging. Now I want create a thread dump via API.

I know I can request the stacktraces via Thread.getAllStackTraces(). But the thread dump on the console include many more information like the monitor which a thread is waiting.

Are there an API to request the monitor on which a thread is waiting?

答:
JDK 6 documentation contains a section on programmatic monitoring of the JVM MBeans .
I have never used them and would not be able to provide you sample code but it will definately give you a start.

Managing and monitoring programmatic way

The Attach API to connect to a remote JVM

I hope it helps , It will be very helpful if you can share the outcome of your research.


问:
How to use Regex in Oracle SQL request
I have this complex string in a database, which represents 4 elements separated by delimeters '|'

```<code>1944913|200010|157|4*
1944913|200085|157|1.22*
</code>```

NOTE: both lines of strings exist in the same database row. There could be up to 10 lines of strings in a single cell

I want an oracle sql command that, given either 200010 or 200085, returns either the 1st or second element next to it, like:

Given 200010, returns 157 or returns 4*
Given 200085, returns 157 or returns 1.22

How would I go about doing that?

答:
You can use regexp_substr and instr to get the required results:

```<code>select a.*,
      CASE WHEN instr(text1,'200085')>0 then REGEXP_SUBSTR (substr(text1,instr(text1,'200085'),500),'[^,|]+', 1, 2)
          ELSE NULL END as partA,
      CASE WHEN instr(text1,'200085')>0 then REGEXP_SUBSTR (substr(text1,instr(text1,'200085'),500),'[^,|]+', 1, 3)
          ELSE NULL END as partB
from tableA a
</code>```

Simply replace '200085' with the string you are looking for and you should be good to go. Hope this helps.

Title: How to use Regex in Oracle SQL request

Body:
I have this complex string in a database, which represents 4 elements separated by delimeters '|'

1944913|200010|157|4*
1944913|200085|157|1.22*

NOTE: both lines of strings exist in the same database row. There could be up to 10 lines of strings in a single cell

I want an oracle sql command that, given either 200010 or 200085, returns either the 1st or second element next to it, like:

Given 200010, returns 157 or returns 4*
Given 200085, returns 157 or returns 1.22

How would I go about doing that?

Body:
You can use regexp_substr and instr to get the required results:

select a.*,
      CASE WHEN instr(text1,'200085')>0 then REGEXP_SUBSTR (substr(text1,instr(text1,'200085'),500),'[^,|]+', 1, 2)
          ELSE NULL END as partA,
      CASE WHEN instr(text1,'200085')>0 then REGEXP_SUBSTR (substr(text1,instr(text1,'200085'),500),'[^,|]+', 1, 3)
          ELSE NULL END as partB
from tableA a

Simply replace '200085' with the string you are looking for and you should be good to go. Hope this helps.


问:
Why the UI elements disappear in seconds in Xcode 11.3?
I am coding a single view page IOS app in swift for learning in Xcode 11.3 on macOS Catalina. There are a button, a text field and a label elements on the page. Here is the code of ViewController.swift:

```<code>import UIKit
import LiquidCore

class ViewController: UIViewController {

    var txt = "text field"
    @IBOutlet weak var Text: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    func showText() {
        Text.text = txt
    }

    @IBAction func clickButton(_ sender: UIButton) {

        let url = LCMicroService.bundle("example")
        let service = LCMicroService(url: url)
        service?.start()

        txt = "LC started"
        showText()
    }

}
</code>```

Here is the preview of the UI page:

The problem I am having is that all 3 UI elements disappear automatically in about 5 seconds after being shown on launch screen. There are view life cycles for a page but I don't have any of those in my code. What's wrong here?

答:
Copy paste all the designs from LaunchScreen.storyboard to
  Main.storyboard and you will see the magic.

Body:
I am coding a single view page IOS app in swift for learning in Xcode 11.3 on macOS Catalina. There are a button, a text field and a label elements on the page. Here is the code of ViewController.swift:

import UIKit
import LiquidCore

class ViewController: UIViewController {

    var txt = "text field"
    @IBOutlet weak var Text: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    func showText() {
        Text.text = txt
    }

    @IBAction func clickButton(_ sender: UIButton) {

        let url = LCMicroService.bundle("example")
        let service = LCMicroService(url: url)
        service?.start()

        txt = "LC started"
        showText()
    }

}

Here is the preview of the UI page:

The problem I am having is that all 3 UI elements disappear automatically in about 5 seconds after being shown on launch screen. There are view life cycles for a page but I don't have any of those in my code. What's wrong here?


问:
How to check if an object in Python is a PyCapsule?
I have a C Extension that receives and accepts PyCapsule objects.

In my python wrapper, how can I check if a python object is of the PyCapsule type object?

```<code>>>> # My C extension
>>> foo = Foo()
>>> capsule = foo.to_capsule()  # returns a PyCapsule object from the C extension
>>> capsule
<capsule object "foo" at 0xf707df08>
>>> type(capsule)
<class 'PyCapsule'>
isinstance(capsule, PyCapsule)
NameError: name 'PyCapsule' is not defined
</code>```

What I'm trying to do is write a function like:

```<code>def push_capsule(capsule):
    # check that the `capsule` is of type PyCapsule
    # c_extension.push_capsule(capsule)
</code>```

答:
In general, first check if your API offers some way to access the class you want to reference.

If it does not, recover the class from a dummy instance.

```<code>PyCapsule = type(Foo().to_capsule())

...

if isinstance(bar, PyCapsule):
    ...
</code>```

Body:
I have a C Extension that receives and accepts PyCapsule objects.

In my python wrapper, how can I check if a python object is of the PyCapsule type object?

>>> # My C extension
>>> foo = Foo()
>>> capsule = foo.to_capsule()  # returns a PyCapsule object from the C extension
>>> capsule
<capsule object "foo" at 0xf707df08>
>>> type(capsule)
<class 'PyCapsule'>
isinstance(capsule, PyCapsule)
NameError: name 'PyCapsule' is not defined

What I'm trying to do is write a function like:

def push_capsule(capsule):
    # check that the `capsule` is of type PyCapsule
    # c_extension.push_capsule(capsule)

Body:
In general, first check if your API offers some way to access the class you want to reference.

If it does not, recover the class from a dummy instance.

PyCapsule = type(Foo().to_capsule())

...

if isinstance(bar, PyCapsule):
    ...


问:
ModuleNotFoundError when running Optimization examples from floris v1.1.4 develop branch
I have downloaded a local editable installation of floris version 1.1.4 develop branch and am trying to run the Optimization examples:

example_layout_optimization.py

example_power_density_optimization.py

example_yaw_optimization.py

example_yaw_optimization_no_class.py

example_yaw_optimization_wind_rose_no_class.py

in the following manner

floris\examples\optimization>python example_layout_optimization.py

However, for each I get the same error:

```<code>Traceback (most recent call last):
  File "example_power_density_optimization.py", line 36, in <module>
    tmp = opt.optimization.Optimization(model=model, solver='SLSQP')
  File "c:\users\nilsg\floris\floris\tools\optimization\optimization.py", line 41, in __init__
    self.reinitialize(solver=solver)
  File "c:\users\nilsg\floris\floris\tools\optimization\optimization.py", line 78, in reinitialize
    self._reinitialize(solver=solver)
  File "c:\users\nilsg\floris\floris\tools\optimization\optimization.py", line 46, in _reinitialize
    import pyoptsparse
ModuleNotFoundError: No module named 'pyoptsparse'
</code>```

Any help much appreciate, and, as this is my first post I expect to have to rephrase the question because I am unlikely to have done so well.

答:
As stated in the error, the python installation cannot find the module pyoptsparse. This can occur if the module is not installed or is not on the python path. Currently, pyoptsparse is not installed automatically with FLORIS, but requires the user to install it manually, so this is most likely the case. Automatic installation with FLORIS will hopefully be implemented in the near future.

In order to install pyoptsparse, I would refer you to their installation documentation. There you will find the dependencies that pyoptsparse requires (which you may already have), and the commands to install the package. I would recommend for ease, after verifying/installing the required dependencies, to use the

```<code>>>> python setup.py install --user
</code>```

which will install the package to the ~./local directory which is usually on the python path.

Body:
I have downloaded a local editable installation of floris version 1.1.4 develop branch and am trying to run the Optimization examples:

example_layout_optimization.py

example_power_density_optimization.py

example_yaw_optimization.py

example_yaw_optimization_no_class.py

example_yaw_optimization_wind_rose_no_class.py

in the following manner

floris\examples\optimization>python example_layout_optimization.py

However, for each I get the same error:

Traceback (most recent call last):
  File "example_power_density_optimization.py", line 36, in <module>
    tmp = opt.optimization.Optimization(model=model, solver='SLSQP')
  File "c:\users\nilsg\floris\floris\tools\optimization\optimization.py", line 41, in __init__
    self.reinitialize(solver=solver)
  File "c:\users\nilsg\floris\floris\tools\optimization\optimization.py", line 78, in reinitialize
    self._reinitialize(solver=solver)
  File "c:\users\nilsg\floris\floris\tools\optimization\optimization.py", line 46, in _reinitialize
    import pyoptsparse
ModuleNotFoundError: No module named 'pyoptsparse'

Any help much appreciate, and, as this is my first post I expect to have to rephrase the question because I am unlikely to have done so well.

Body:
As stated in the error, the python installation cannot find the module pyoptsparse. This can occur if the module is not installed or is not on the python path. Currently, pyoptsparse is not installed automatically with FLORIS, but requires the user to install it manually, so this is most likely the case. Automatic installation with FLORIS will hopefully be implemented in the near future.

In order to install pyoptsparse, I would refer you to their installation documentation. There you will find the dependencies that pyoptsparse requires (which you may already have), and the commands to install the package. I would recommend for ease, after verifying/installing the required dependencies, to use the

>>> python setup.py install --user

which will install the package to the ~./local directory which is usually on the python path.


问:
Sorting nil Dates to the end of an Array
Trying to sort an array in Swift in descending order. This works well

```<code>objectArray.sort{ $0.date!.compare($1.date!) == .orderedDescending}
</code>```

As you can see, I'm force unwrapping the date. I'm looking for another way so that if the date is nil, the object moves to the end of array.

答:
Here's an example of how to sort the nil dates to the end of an array.

In the example, movies is an array of type Movie, which has a date property.

```<code>let sortedMovies = movies.sorted { (movieA, movieB) -> Bool in

    switch (movieA.date, movieB.date) {
    case (.some, .some):
        return movieA.date! > movieB.date!

    case (.some, .none):
        return true

    case (.none, _):
        return false
    }
}
</code>```

Here are some extensions for this function, one non-mutating and one mutating, and with a parameter for descending/ascending.

```<code>extension Array
{
    func propertySorted<T: Comparable>(_ property: (Element) -> T?, descending: Bool) -> [Element]
    {
        sorted(by: {
            switch (property($0), property($1)) {
            case (.some, .some):
                return descending ? property($0)! > property($1)! : property($0)! < property($1)!

            case (.some, .none):
                return true

            case (.none, _):
                return false
            }
        })
    }

    mutating func propertySort<T: Comparable>(_ property: (Element) -> T?, descending: Bool)
    {
        sort(by: {
            switch (property($0), property($1)) {
            case (.some, .some):
                return descending ? property($0)! > property($1)! : property($0)! < property($1)!

            case (.some, .none):
                return true

            case (.none, _):
                return false
            }
       })
    }
}
</code>```

Usage:

```<code>let movieNames = movies.propertySorted({ $0.name }, descending: false)
let movieDates = movies.propertySorted({ $0.date }, descending: true)

movies.propertySort({ $0.name }, descending: false)
movies.propertySort({ $0.date }, descending: true)
</code>```

Extension assistance credit to @Sweeper for answer on Generic function to sort array of class by properties

Body:
Trying to sort an array in Swift in descending order. This works well

objectArray.sort{ $0.date!.compare($1.date!) == .orderedDescending}

As you can see, I'm force unwrapping the date. I'm looking for another way so that if the date is nil, the object moves to the end of array.

Body:
Here's an example of how to sort the nil dates to the end of an array.

In the example, movies is an array of type Movie, which has a date property.

let sortedMovies = movies.sorted { (movieA, movieB) -> Bool in

    switch (movieA.date, movieB.date) {
    case (.some, .some):
        return movieA.date! > movieB.date!

    case (.some, .none):
        return true

    case (.none, _):
        return false
    }
}

Here are some extensions for this function, one non-mutating and one mutating, and with a parameter for descending/ascending.

extension Array
{
    func propertySorted<T: Comparable>(_ property: (Element) -> T?, descending: Bool) -> [Element]
    {
        sorted(by: {
            switch (property($0), property($1)) {
            case (.some, .some):
                return descending ? property($0)! > property($1)! : property($0)! < property($1)!

            case (.some, .none):
                return true

            case (.none, _):
                return false
            }
        })
    }

    mutating func propertySort<T: Comparable>(_ property: (Element) -> T?, descending: Bool)
    {
        sort(by: {
            switch (property($0), property($1)) {
            case (.some, .some):
                return descending ? property($0)! > property($1)! : property($0)! < property($1)!

            case (.some, .none):
                return true

            case (.none, _):
                return false
            }
       })
    }
}

Usage:

let movieNames = movies.propertySorted({ $0.name }, descending: false)
let movieDates = movies.propertySorted({ $0.date }, descending: true)

movies.propertySort({ $0.name }, descending: false)
movies.propertySort({ $0.date }, descending: true)

Extension assistance credit to @Sweeper for answer on Generic function to sort array of class by properties


问:
ServerError: AADSTS50058: A silent sign-in request was sent but none of the currently signed in user(s) match the requested login hint"
SSO fails "ServerError: AADSTS50058: A silent sign-in request was sent but none of the currently signed in user(s) match the requested login hint"
when I use same account for both work and personal azure account.

I have 2 AAD accounts (one is with my work account and the other one is personal account but both attached with same email and both are using same credentials).  When I use msal.js library for single sign on application. It takes me to my work account where it asks me to validate the credentials (using standard pop up dialog) by giving full email address and does not authenticate properly even if give right credentials. As I need to login using my personal account
I expect this should validate using my ad alias@company.com credentials. I tried with different account option in the dialog, but it fails and shows up same full email account.
How can I use my adalias@company.com as a default user id?

Here are the piece of the code I am trying to use.

```<code>var msalConfig = {
     auth: {
       clientId: 'xxxxxxxxxx', // This is your client ID
       authority: "https://login.microsoftonline.com/{tenantid}"  // This is tenant info
     },
     cache: {
       cacheLocation: "localStorage",
       storeAuthStateInCookie: true
     }
};

var graphConfig = {
  graphMeEndpoint: "https://graph.microsoft.com/v1.0/me"
};

var requestObj = {scopes: ["user.read", "email"]};
// Is there a way to change here to get the required user id?

var myMSALObj = new Msal.UserAgentApplication(msalConfig);
// Register Callbacks for redirect flow
myMSALObj.handleRedirectCallbacks(acquireTokenRedirectCallBack,
acquireTokenErrorRedirectCallBack);
myMSALObj.handleRedirectCallback(authRedirectCallBack);

function signIn() {
  myMSALObj.loginRedirect(requestObj).then(function (loginResponse) {
    // Successful login
    acquireTokenPopupAndCallMSGraph();
  }).catch(function (error) {
    // Please check the console for errors
    console.log(error);
  });
}
</code>```

Here is the error message I get:

ServerError: AADSTS50058: A silent sign-in request was sent but none of the
  currently signed in user(s) match the requested login hint

The expected result is seamless login to other application.

答:
If you want to provide a login_hint to indicate the user you are trying to authenticate try:

```<code>var requestObj = {scopes: ["user.read", "email"], loginHint: "adalias@company.com"};
</code>```

Reference https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/FAQs#q10-how-to-pass-custom-state-parameter-value-in-msaljs-authentication-request-for-example-when-you-want-to-pass-the-page-the-user-is-on-or-custom-info-to-your-redirect-uri

Body:
SSO fails "ServerError: AADSTS50058: A silent sign-in request was sent but none of the currently signed in user(s) match the requested login hint"
when I use same account for both work and personal azure account.

I have 2 AAD accounts (one is with my work account and the other one is personal account but both attached with same email and both are using same credentials).  When I use msal.js library for single sign on application. It takes me to my work account where it asks me to validate the credentials (using standard pop up dialog) by giving full email address and does not authenticate properly even if give right credentials. As I need to login using my personal account
I expect this should validate using my ad alias@company.com credentials. I tried with different account option in the dialog, but it fails and shows up same full email account.
How can I use my adalias@company.com as a default user id?

Here are the piece of the code I am trying to use.

var msalConfig = {
     auth: {
       clientId: 'xxxxxxxxxx', // This is your client ID
       authority: "https://login.microsoftonline.com/{tenantid}"  // This is tenant info
     },
     cache: {
       cacheLocation: "localStorage",
       storeAuthStateInCookie: true
     }
};

var graphConfig = {
  graphMeEndpoint: "https://graph.microsoft.com/v1.0/me"
};

var requestObj = {scopes: ["user.read", "email"]};
// Is there a way to change here to get the required user id?

var myMSALObj = new Msal.UserAgentApplication(msalConfig);
// Register Callbacks for redirect flow
myMSALObj.handleRedirectCallbacks(acquireTokenRedirectCallBack,
acquireTokenErrorRedirectCallBack);
myMSALObj.handleRedirectCallback(authRedirectCallBack);

function signIn() {
  myMSALObj.loginRedirect(requestObj).then(function (loginResponse) {
    // Successful login
    acquireTokenPopupAndCallMSGraph();
  }).catch(function (error) {
    // Please check the console for errors
    console.log(error);
  });
}

Here is the error message I get:

ServerError: AADSTS50058: A silent sign-in request was sent but none of the
  currently signed in user(s) match the requested login hint

The expected result is seamless login to other application.

Body:
If you want to provide a login_hint to indicate the user you are trying to authenticate try:

var requestObj = {scopes: ["user.read", "email"], loginHint: "adalias@company.com"};

Reference https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/FAQs#q10-how-to-pass-custom-state-parameter-value-in-msaljs-authentication-request-for-example-when-you-want-to-pass-the-page-the-user-is-on-or-custom-info-to-your-redirect-uri


问:
css and javascript files are not linked
Good evening everyone
I would like to deploy a web application (WebForm) developed with VS2017 locally on IIS but the css and javascript files are not linked.
I developed under VS2017, everything works perfectly well, but there I have no idea where the problem may come from.
Thank you very much for your help!</p>

答: Using Developer Tools in most browsers (hit f12 when the page is up), go to the network tab and look what css and JavaScript files are not getting loaded. This will show you where the browser is trying to get the files from. You can usually make adjustments from there. You may have to refresh the page once you are on the network tab to have them reload.</p>

Title: css and javascript files are not linked


问:
Phing - how to checkout from svn, then upload via ftp and chmod directories
I have been reading the Phing documentation and it makes sense, but I'm not able to find out from there or on Google (or here) how to do what I would consider to be a fairly normal build procedure - checkout from svn, then upload the checked out copy via ftp and then chmod certain directories (for uploading files).

Is this possible with Phing, or would I have to write my own task class to do it?

答:
Is it possible? Sure, anything is possible - given enough time and resources. You can also extend Phing with your own tasks if it doesn't yet cover what you want.

But regarding your specific question : to checkout from svn use the svncheckout (or svnexport - the latter seems more appropriate for your scenario) task, to transfer with ftp use the ftpdeploy task (or better yet - use scp instead of ftp), and to chmod some files you could use the ssh task (provided that you have SSH access of course).


问:
Fetching SKProduct Price into UICollectionView Cell Label
I'm facing a issue where when I fetch SKProduct locale price on to the label.text of my UICollectionView, Its displaying correctly, however the prices jump around in different labels depending on how fast the page is being loaded.

TopUpViewController (UICollectionView) -> TopUpMoneyCell (MoneyLabel)

Any idea how to solve this? Currently I'm calling SKProduct in TopUpMoneyCell. I have a array of 4 in app product to be called, each with different value.

Should I call it from TopUpViewController instead? If so, how should I pull the data I got from TopUpViewController to TopUpMoneyCell?

Edit 1: Added UI Mockup, once again thanks for commenting.

View of UI Mockup

答:
Without seeing any code, it's a little difficult to see what you're doing, but it sounds like you might want to have your TopUpViewController conform to the UICollectionViewDataSource protocol (https://developer.apple.com/documentation/uikit/uicollectionviewdatasource?language=objc)

Then you could implement something like the following there:

```<code>
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [self.testCollectionView dequeueReusableCellWithReuseIdentifier:@"SomeReuseID"
                                                                                forIndexPath:indexPath];

    // set your custom labeling on the cell here (you probably have a subclass)

    return cell;
}
</code>```

Don't forget to tell the UICollectionView what to use for its dataSource.

From what you are describing, it sounds like your cells are querying some source of data directly, so that when the UICollectionView chooses to reuse a cell, the labels are not in the order you intend.

Body:
Without seeing any code, it's a little difficult to see what you're doing, but it sounds like you might want to have your TopUpViewController conform to the UICollectionViewDataSource protocol (https://developer.apple.com/documentation/uikit/uicollectionviewdatasource?language=objc)

Then you could implement something like the following there:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [self.testCollectionView dequeueReusableCellWithReuseIdentifier:@"SomeReuseID"
                                                                                forIndexPath:indexPath];

    // set your custom labeling on the cell here (you probably have a subclass)

    return cell;
}

Don't forget to tell the UICollectionView what to use for its dataSource.

From what you are describing, it sounds like your cells are querying some source of data directly, so that when the UICollectionView chooses to reuse a cell, the labels are not in the order you intend.


问:
If value is between two other values, do something and continue until it is not. If it is not, try again until it is, then stop when it is not
I have a column of dates in a dataframe that begins with yesterday's date and goes through today+13 days. I'm posting this on 2/19/20, so my dates would be from 2/18/20 - 3/3/20.

I need to write a loop that grabs data in a corresponding column if the date in my date column is between today and today+6. I know how to get the data out of the dataframe, but I'm struggling to get the loop right.

Below is an outline of what I'm trying to do

```<code>df_date = list of dates from dataframe column that I'm checking
current_day = today
seven_day = today + 6

n=0
while df_date[n] >= current_day and df_date[n] <= seven_day:
    grab the data
    n=+1
    continue grabbing data until condition is false, then break
else:
    If the condition is false, add 1 to n until it is true.
    Then grab the data until it is false again and break
</code>```

答:
Since your dates are in a list, this is pretty simple to do. Assuming everything is datetime or timedelta objects, the comparisons are also very simple.

I'm using the following setup for this example:

```<code>from datetime import datetime, timedelta

# This is so the min_date and max_date have their time portion set to midnight
dt = datetime.today()
min_date = datetime(dt.year, dt.month, dt.day)
max_date = datetime(dt.year, dt.month, dt.day) + timedelta(days=6)

dates = [
    datetime(2020, 2, 18),
    datetime(2020, 2, 19),
    datetime(2020, 2, 20),
    datetime(2019, 12, 18),  # <-- outside your defined range
    datetime(2020, 2, 21),
    datetime(2020, 2, 22),
    datetime(2020, 2, 23),
]
</code>```

Then, you can just get the dates with a comprehension:

```<code>>>> [d for d in dates if min_date <= d <= max_date]
[datetime.datetime(2020, 2, 19, 0, 0),
 datetime.datetime(2020, 2, 20, 0, 0),
 datetime.datetime(2020, 2, 21, 0, 0),
 datetime.datetime(2020, 2, 22, 0, 0),
 datetime.datetime(2020, 2, 23, 0, 0)]
</code>```

Body:
I have a column of dates in a dataframe that begins with yesterday's date and goes through today+13 days. I'm posting this on 2/19/20, so my dates would be from 2/18/20 - 3/3/20.

I need to write a loop that grabs data in a corresponding column if the date in my date column is between today and today+6. I know how to get the data out of the dataframe, but I'm struggling to get the loop right.

Below is an outline of what I'm trying to do

df_date = list of dates from dataframe column that I'm checking
current_day = today
seven_day = today + 6

n=0
while df_date[n] >= current_day and df_date[n] <= seven_day:
    grab the data
    n=+1
    continue grabbing data until condition is false, then break
else:
    If the condition is false, add 1 to n until it is true.
    Then grab the data until it is false again and break

Body:
Since your dates are in a list, this is pretty simple to do. Assuming everything is datetime or timedelta objects, the comparisons are also very simple.

I'm using the following setup for this example:

from datetime import datetime, timedelta

# This is so the min_date and max_date have their time portion set to midnight
dt = datetime.today()
min_date = datetime(dt.year, dt.month, dt.day)
max_date = datetime(dt.year, dt.month, dt.day) + timedelta(days=6)

dates = [
    datetime(2020, 2, 18),
    datetime(2020, 2, 19),
    datetime(2020, 2, 20),
    datetime(2019, 12, 18),  # <-- outside your defined range
    datetime(2020, 2, 21),
    datetime(2020, 2, 22),
    datetime(2020, 2, 23),
]

Then, you can just get the dates with a comprehension:

>>> [d for d in dates if min_date <= d <= max_date]
[datetime.datetime(2020, 2, 19, 0, 0),
 datetime.datetime(2020, 2, 20, 0, 0),
 datetime.datetime(2020, 2, 21, 0, 0),
 datetime.datetime(2020, 2, 22, 0, 0),
 datetime.datetime(2020, 2, 23, 0, 0)]