问:
Joomla logo multilanguage
I'm customizing an HTML template for Joomla! 3.7.2, everything seems work fine except for multilanguage redirect when click on logo.

1) I inser the logo in my index.php file as:

```<code><a id="t-logo" href="<?php echo $this->baseurl; ?>/">
    <?php echo $doc->getBuffer('modules', 'logo', array('style' => 'none')); ?>
</a>
</code>```

Then I use a module to assign the image of the logo in that position (so that my Client can change it easily in future).

Anyway I see that if I switch from main language (IT) to EN and then I click the logo, instead of being redirected to the EN homepage, it always redirects me to the IT homepage. This happens only with my template (tested with default Joomla! Protostar and I don't see this problem).

This is my index.php code:

```<code><?php

    defined('_JEXEC') or die;

    $app             = JFactory::getApplication();
    $menu            = $app->getMenu();
    $doc             = JFactory::getDocument();
    $user            = JFactory::getUser();
</code>```

...
loading some CSS and JS
...

```<code>    // Output as HTML5
    $this->setHtml5(true);

    // Getting params from template
    $params = $app->getTemplate(true)->params;

    // Detecting Active Variables
    $option   = $app->input->getCmd('option', '');
    $view     = $app->input->getCmd('view', '');
    $layout   = $app->input->getCmd('layout', '');
    $task     = $app->input->getCmd('task', '');
    $itemid   = $app->input->getCmd('Itemid', '');
    $sitename = $app->get('sitename');

    // Aggiunge la classe della pagina
    $menu = $app->getMenu()->getActive();
    $pageclass = '';

    if (is_object($menu))
    $pageclass = $menu->params->get('pageclass_sfx');
    // fine aggiunge classe della pagina

    if($task == "edit" || $layout == "form" )
    {
        $fullWidth = 1;
    }
    else
    {
        $fullWidth = 0;
    }

?>

<!DOCTYPE html>
<html lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link href="<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
        <jdoc:include type="head" />
        <!--[if lt IE 9]><script src="<?php echo JUri::root(true); ?>/media/jui/js/html5.js"></script><![endif]-->

    </head>

    <body class="<?php echo $pageclass; ?> site <?php echo $option
        . ' view-' . $view
        . ($layout ? ' layout-' . $layout : ' no-layout')
        . ($task ? ' task-' . $task : ' no-task')
        . ($itemid ? ' itemid-' . $itemid : '')
        . ($params->get('fluidContainer') ? ' fluid' : '');
        echo ($this->direction == 'rtl' ? ' rtl' : '');
        ?>">

        <div class="main-wrapper">

            <div class="topbar inner-container container">
                <div class="l-sec col-xs-6 col-md-9">
                    <?php if ($this->countModules('shortinfo')) : ?>
                    <jdoc:include type="modules" name="shortinfo" style="none" />
                    <?php endif; ?>
                </div>

                <div class="r-sec col-xs-6 col-md-3">
                    <?php if ($this->countModules('language')) : ?>
                    <jdoc:include type="modules" name="language" style="none" />
                    <?php endif; ?>
                </div>
            </div>

            <!-- Header Section -->
            <header id="main-header">
                <div class="inner-container container">
                    <div class="l-sec col-xs-6 col-sm-6 col-md-3">
                        <a id="t-logo" href="<?php echo $this->baseurl; ?>/">
                            <?php echo $doc->getBuffer('modules', 'logo', array('style' => 'none')); ?>
                        </a>
                    </div>

                    <?php if ($this->countModules('main-menu')) : ?>
                    <div class="r-sec col-xs-6 col-sm-6 col-md-9">
                        <nav id="main-menu" class="navigation" role="navigation">
                            <jdoc:include type="modules" name="main-menu" style="none" />
                        </nav>
                        <div id="main-menu-handle" class="ravis-btn btn-type-2"><i class="fa fa-bars"></i><i class="fa fa-close"></i></div><!-- Mobile Menu handle -->
                        <?php if ($this->countModules('bookingbutton')) : ?>
                        <jdoc:include type="modules" name="bookingbutton" style="none" />
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <div id="mobile-menu-container"></div>
            </header>
            <!-- End of Header Section -->

            <?php if ($this->countModules('header')) : ?>
            <section id="breadcrumb-section" data-bg-img="<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/images/header.jpg" style="background-image: url('<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/images/header.jpg');">
                <div class="inner-container container">

                    <div class="ravis-title">
                        <div class="inner-box">
                            <div class="title">
                                <h1 itemprop="headline">
                                    <?php echo $page_title = $doc->getTitle(); ?>
                                </h1>
                            </div>
                            <div class="sub-title"><h2 class="great-vibes"><?php echo htmlspecialchars($images->image_intro_alt); ?></h2></div>
                        </div>
                    </div>

                    <div class="breadcrumb">
                        <?php
                            $modules =& JModuleHelper::getModules('breadcrumb');
                            foreach ($modules as $module)
                            {
                                echo JModuleHelper::renderModule($module);
                            }
                        ?>
                    </div>

                </div>
            </section>
            <?php endif; ?>

            <?php if ($this->countModules('main-slider')) : ?>
            <div class="slider-available-sec">
                <jdoc:include type="modules" name="main-slider" style="none" />

                <?php if ($this->countModules('booking-form')) : ?>
                <jdoc:include type="modules" name="booking-form" style="none" />
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <jdoc:include type="message" />

            <div class="componentarea">
                <?php
                    $app = JFactory::getApplication();
                    $menu = $app->getMenu();
                    $lang = JFactory::getLanguage();
                if ($menu->getActive() != $menu->getDefault($lang->getTag())) : ?>

                <jdoc:include type="component" />

                <?php endif; ?>
            </div>

            <?php if ($this->countModules('welcome')) : ?>
            <jdoc:include type="modules" name="welcome" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('luxury-rooms')) : ?>
            <jdoc:include type="modules" name="luxury-rooms" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('events')) : ?>
            <jdoc:include type="modules" name="events" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('services')) : ?>
            <jdoc:include type="modules" name="services" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('tour')) : ?>
            <jdoc:include type="modules" name="tour" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('gallery')) : ?>
            <jdoc:include type="modules" name="gallery" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('testimonials')) : ?>
            <jdoc:include type="modules" name="testimonials" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('pacchetti')) : ?>
            <jdoc:include type="modules" name="pacchetti" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('richiesta')) : ?>
            <jdoc:include type="modules" name="richiesta" style="none" />
            <?php endif; ?>

            <!--Footer Section-->
            <footer id="main-footer">
                <div class="inner-container container">
                    <div class="t-sec clearfix">

                        <?php if ($this->countModules('footer-1')) : ?>
                        <jdoc:include type="modules" name="footer-1" style="xhtml" />
                        <?php endif; ?>

                        <?php if ($this->countModules('footer-2')) : ?>
                        <jdoc:include type="modules" name="footer-2" style="xhtml" />
                        <?php endif; ?>

                        <?php if ($this->countModules('footer-3')) : ?>
                        <jdoc:include type="modules" name="footer-3" style="xhtml" />
                        <?php endif; ?>

                        <?php if ($this->countModules('footer-4')) : ?>
                        <jdoc:include type="modules" name="footer-4" style="xhtml" />
                        <?php endif; ?>

                    </div>
                    <?php if ($this->countModules('copyright')) : ?>
                    <jdoc:include type="modules" name="copyright" style="none" />
                    <?php endif; ?>
                </div>
            </footer>
            <!--End of Footer Section-->

        </div>

    </body>

</html>
</code>```

Any suggestion and how to fix this?

Thanks in advance!

答:
Here's some code I use for one of our templates, it would be easy to adapt this to your situation:  </p>

```<code><?php
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();

if ($this->language ==’en-gb’){
echo ‘<a href=”‘ .$this->baseurl .’/en” class=”” title=””>’;
}
else {
echo ‘<a href=”‘ .$this->baseurl .’/fr” class=”” title=””>’;
}
?>
<img class=”logo” src=”/path/images/header/logo.png” alt=””>

<?php
echo “</a>”;
?>
</code>```

Title: Joomla logo multilanguage

Body:
I'm customizing an HTML template for Joomla! 3.7.2, everything seems work fine except for multilanguage redirect when click on logo.

1) I inser the logo in my index.php file as:

<a id="t-logo" href="<?php echo $this->baseurl; ?>/">
    <?php echo $doc->getBuffer('modules', 'logo', array('style' => 'none')); ?>

Then I use a module to assign the image of the logo in that position (so that my Client can change it easily in future).

Anyway I see that if I switch from main language (IT) to EN and then I click the logo, instead of being redirected to the EN homepage, it always redirects me to the IT homepage. This happens only with my template (tested with default Joomla! Protostar and I don't see this problem).

This is my index.php code:

<?php

    defined('_JEXEC') or die;

    $app             = JFactory::getApplication();
    $menu            = $app->getMenu();
    $doc             = JFactory::getDocument();
    $user            = JFactory::getUser();

...
loading some CSS and JS
...

    // Output as HTML5
    $this->setHtml5(true);

    // Getting params from template
    $params = $app->getTemplate(true)->params;

    // Detecting Active Variables
    $option   = $app->input->getCmd('option', '');
    $view     = $app->input->getCmd('view', '');
    $layout   = $app->input->getCmd('layout', '');
    $task     = $app->input->getCmd('task', '');
    $itemid   = $app->input->getCmd('Itemid', '');
    $sitename = $app->get('sitename');

    // Aggiunge la classe della pagina
    $menu = $app->getMenu()->getActive();
    $pageclass = '';

    if (is_object($menu))
    $pageclass = $menu->params->get('pageclass_sfx');
    // fine aggiunge classe della pagina

    if($task == "edit" || $layout == "form" )
    {
        $fullWidth = 1;
    }
    else
    {
        $fullWidth = 0;
    }

?>

<!DOCTYPE html>
<html lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>">

        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link href="<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
        <jdoc:include type="head" />

    <body class="<?php echo $pageclass; ?> site <?php echo $option
        . ' view-' . $view
        . ($layout ? ' layout-' . $layout : ' no-layout')
        . ($task ? ' task-' . $task : ' no-task')
        . ($itemid ? ' itemid-' . $itemid : '')
        . ($params->get('fluidContainer') ? ' fluid' : '');
        echo ($this->direction == 'rtl' ? ' rtl' : '');
        ?>">

                    <?php if ($this->countModules('shortinfo')) : ?>
                    <jdoc:include type="modules" name="shortinfo" style="none" />
                    <?php endif; ?>

                    <?php if ($this->countModules('language')) : ?>
                    <jdoc:include type="modules" name="language" style="none" />
                    <?php endif; ?>

                        <a id="t-logo" href="<?php echo $this->baseurl; ?>/">
                            <?php echo $doc->getBuffer('modules', 'logo', array('style' => 'none')); ?>

                    <?php if ($this->countModules('main-menu')) : ?>

                            <jdoc:include type="modules" name="main-menu" style="none" />

                        <?php if ($this->countModules('bookingbutton')) : ?>
                        <jdoc:include type="modules" name="bookingbutton" style="none" />
                        <?php endif; ?>

                    <?php endif; ?>

            <?php if ($this->countModules('header')) : ?>
            <section id="breadcrumb-section" data-bg-img="<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/images/header.jpg" style="background-image: url('<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/images/header.jpg');">

                                    <?php echo $page_title = $doc->getTitle(); ?>

<?php echo htmlspecialchars($images->image_intro_alt); ?>

                        <?php
                            $modules =& JModuleHelper::getModules('breadcrumb');
                            foreach ($modules as $module)
                            {
                                echo JModuleHelper::renderModule($module);
                            }
                        ?>

            <?php endif; ?>

            <?php if ($this->countModules('main-slider')) : ?>

                <jdoc:include type="modules" name="main-slider" style="none" />

                <?php if ($this->countModules('booking-form')) : ?>
                <jdoc:include type="modules" name="booking-form" style="none" />
                <?php endif; ?>

            <?php endif; ?>

            <jdoc:include type="message" />

                <?php
                    $app = JFactory::getApplication();
                    $menu = $app->getMenu();
                    $lang = JFactory::getLanguage();
                if ($menu->getActive() != $menu->getDefault($lang->getTag())) : ?>

                <jdoc:include type="component" />

                <?php endif; ?>

            <?php if ($this->countModules('welcome')) : ?>
            <jdoc:include type="modules" name="welcome" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('luxury-rooms')) : ?>
            <jdoc:include type="modules" name="luxury-rooms" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('events')) : ?>
            <jdoc:include type="modules" name="events" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('services')) : ?>
            <jdoc:include type="modules" name="services" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('tour')) : ?>
            <jdoc:include type="modules" name="tour" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('gallery')) : ?>
            <jdoc:include type="modules" name="gallery" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('testimonials')) : ?>
            <jdoc:include type="modules" name="testimonials" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('pacchetti')) : ?>
            <jdoc:include type="modules" name="pacchetti" style="none" />
            <?php endif; ?>

            <?php if ($this->countModules('richiesta')) : ?>
            <jdoc:include type="modules" name="richiesta" style="none" />
            <?php endif; ?>

                        <?php if ($this->countModules('footer-1')) : ?>
                        <jdoc:include type="modules" name="footer-1" style="xhtml" />
                        <?php endif; ?>

                        <?php if ($this->countModules('footer-2')) : ?>
                        <jdoc:include type="modules" name="footer-2" style="xhtml" />
                        <?php endif; ?>

                        <?php if ($this->countModules('footer-3')) : ?>
                        <jdoc:include type="modules" name="footer-3" style="xhtml" />
                        <?php endif; ?>

                        <?php if ($this->countModules('footer-4')) : ?>
                        <jdoc:include type="modules" name="footer-4" style="xhtml" />
                        <?php endif; ?>

                    <?php if ($this->countModules('copyright')) : ?>
                    <jdoc:include type="modules" name="copyright" style="none" />
                    <?php endif; ?>

Any suggestion and how to fix this?

Thanks in advance!

Body:
Here's some code I use for one of our templates, it would be easy to adapt this to your situation:

<?php
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();

if ($this->language ==’en-gb’){
echo ‘<a href=”‘ .$this->baseurl .’/en” class=”” title=””>’;
}
else {
echo ‘<a href=”‘ .$this->baseurl .’/fr” class=”” title=””>’;
}
?>
<img class=”logo” src=”/path/images/header/logo.png” alt=””>

<?php
echo “</a>”;
?>


来源: stackexchange

问:
Visual Studio 2005: Unable to connect to visual studio's localhost web server
I recently upgraded to Windows 10 from Windows 7 and I was unable to debug a web site in Visual Studio 2005. I got the error: unable to connect to visual studio's localhost web server. I don't know if the upgrade caused it to break, but this was previously working.</p>

答:
To resolve this I ran process monitor on devenv.exe to see which calls ended in not SUCCESS. Turns out, my Visual Studio 2005 installation was looking for WebDev.WebServer.exe to be located here:

C:\Program Files (x86)\Microsoft Visual Studio 8\Common7\IDE

Whereas it was missing. I copied it over from here:

C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\9.0

And it seems to work.

Across the internet other answers will tell you it needs to be in the .NET framework folder, but I found that in my case it needed to be in the Visual Studio 8 folder.

ContentLicense: CC BY-SA 3.0


问:
System.IO.StreamWriter has no string constructor in .netcore 1.1
I'm taking my first baby steps in .NET Core V1.1 under VS2017 community edition.

I ported some chunks of code to an ASP.NET Core project that utilizes System.IO.StreamWriter:

```<code>string fileName = "Hello_world.txt";

using (StreamWriter file = new StreamWriter(fileName))
{
    // do stuff...
}
</code>```

With this I get a compiler error:

```<code>error CS1503: Argument 1: cannot convert from 'string' to 'System.IO.Stream'
</code>```

On the other hand the .NET API doc clearly states that a constructor with string is available, see here.

Can anybody tell me why there is no constructor that receives a string and where to find the correct API doc?

答:
The StreamWriter constructors taking string arguments will only be available in .NET Core 2.0 and higher. You can look up the availability at https://apisof.net/catalog/System.IO.StreamWriter..ctor(String)

In the meantime, you can create a FileStream, which is exactly what the constructor taking a string does.

```<code>    string path = "foo.txt";
    using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan))
    using (var streamWriter = new StreamWriter(stream, System.Text.Encoding.UTF8, 1024, false))
    {
        streamWriter.WriteLine("hey");
    }
</code>```

Body:
I'm taking my first baby steps in .NET Core V1.1 under VS2017 community edition.

I ported some chunks of code to an ASP.NET Core project that utilizes System.IO.StreamWriter:

string fileName = "Hello_world.txt";

using (StreamWriter file = new StreamWriter(fileName))
{
    // do stuff...
}

With this I get a compiler error:

error CS1503: Argument 1: cannot convert from 'string' to 'System.IO.Stream'

On the other hand the .NET API doc clearly states that a constructor with string is available, see here.

Can anybody tell me why there is no constructor that receives a string and where to find the correct API doc?

Body:
The StreamWriter constructors taking string arguments will only be available in .NET Core 2.0 and higher. You can look up the availability at https://apisof.net/catalog/System.IO.StreamWriter..ctor(String)

In the meantime, you can create a FileStream, which is exactly what the constructor taking a string does.

    string path = "foo.txt";
    using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan))
    using (var streamWriter = new StreamWriter(stream, System.Text.Encoding.UTF8, 1024, false))
    {
        streamWriter.WriteLine("hey");
    }


问:
Magento 2.1, manuall install extensions wont work
For the last couple of days I cannot install any extension on live server. The problems that I am having:

Web setup wizard is not showing. Found a workaround to access it via /admin/backend/setup ... only to say Upgrad already in progress and it is like that forever, no clue what is going on.

Tried to install it manually following the tutorials on web.

Step 1: Download/purchase the extension

Step 2: Unzip the file in a temporary directory

Step 3: Upload it to your Magento installation root directory

Step 4: Disable the cache under System >> Cache Management

Step 5: Enter the following at the command line:

php f bin/magento setup:upgrade

So I did it.

I unzipped the file and get ebizmarts-magento2-magemonkey-3.0.7 folder.

I copy that folder in my public_html/magento/ folder (magento root folder). So now i got ebizmarts-magento2-magemonkey-3.0.7 inside my root magento.

php f bin/magento setup:upgrade, also tried static content deploy, and nothing.

I can install this extension via composer on my localhost, but I can't manually. On my live server I need to install it manually.

I am guessing that all tutorials on the web are missing some steps. Do I need to follow some naming convention. Some say that I should copy that folder in pub/code. What am I missing?

答:
You should copy the contents of the ebizmarts-magento2-magemonkey-3.0.7 folder to app/code/Ebizmarts/MageMonkey
if app/code/Ebizmarts/MageMonkey does not exist, create those folders first.
Your directory structure should look like this:


问:
File watcher for Cython in Pycharm
Cython's *.pyx files need to be compiled for it to function with other py files. Because of this, I would like a file watcher for PyCharm just like for *.coffee files and for *.ts files.

How would one create a file watcher for Cython in Pycharm. A step by step tutorial would be greatly appreciated.

答:
The easiest way would be "Compile on Save".

As an example, in Netbeans the "Compile on Save" feature can be enabled via "Build -> Compiling"

As for the python-demon itself, you could start it by using gunicorn, store md5 hash for each file, revalidate them all the time, and rebuild as soon as hash key was changed for the file.

Title: File watcher for Cython in Pycharm


问:
Execute multiple url
I have a little problem. I need to execute an script that execute 5000 URL in php.

```<code>$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        header (Location http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user);
}
</code>```

Any idea??

Thx.

答:
The best way would be with CURL (see other answer by Haim Evgi), but if the server doesn't have the curl extension, then this will also work. </p>

```<code><?
$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        file_get_contents("http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user");
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Execute multiple url

Body:
I have a little problem. I need to execute an script that execute 5000 URL in php.

$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        header (Location http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user);
}

Any idea??

Thx.

Body:
The best way would be with CURL (see other answer by Haim Evgi), but if the server doesn't have the curl extension, then this will also work.

<?
$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        file_get_contents("http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user");
}


问:
Keep user django channels OAuth2 authenticatio
I am authenticating user on connect with this Mixin:

```<code>import functools

from channels.handler import AsgiRequest
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.settings import api_settings

authenticators = [auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES]

def rest_auth(func):
    """
    Wraps a HTTP or WebSocket connect consumer (or any consumer of messages
    that provides a "cookies" or "get" attribute) to provide a "http_session"
    attribute that behaves like request.session; that is, it's hung off of
    a per-user session key that is saved in a cookie or passed as the
    "session_key" GET parameter.
    It won't automatically create and set a session cookie for users who
    don't have one - that's what SessionMiddleware is for, this is a simpler
    read-only version for more low-level code.
    If a message does not have a session we can inflate, the "session" attribute
    will be None, rather than an empty session you can write to.
    Does not allow a new session to be set; that must be done via a view. This
    is only an accessor for any existing session.
    """

    @functools.wraps(func)
    def inner(message, *args, **kwargs):
        # Make sure there's NOT a http_session already
        try:
            # We want to parse the WebSocket (or similar HTTP-lite) message
            # to get cookies and GET, but we need to add in a few things that
            # might not have been there.
            if "method" not in message.content:
                message.content['method'] = "FAKE"
            request = AsgiRequest(message)

        except Exception as e:
            raise ValueError(
                f'Cannot parse HTTP message - are you sure this is a HTTP consumer? {e}')
        # Make sure there's a session key
        user = None
        auth = None
        auth_token = request.GET.get("token", None)

        if auth_token:
            # comptatibility with rest framework
            request._request = {}
            request.META["Authorization"] = "Bearer {}".format(auth_token)
            for authenticator in authenticators:
                try:
                    user_auth_tuple = authenticator.authenticate(request)
                except AuthenticationFailed:
                    pass

                if user_auth_tuple is not None:
                    message._authenticator = authenticator
                    user, auth = user_auth_tuple
                    break
        message.user, message.auth = user, auth
        result = func(message, *args, **kwargs)
        return result
    return inner

def rest_token_user(func):
    """
    Wraps a HTTP or WebSocket consumer (or any consumer of messages
    that provides a "COOKIES" attribute) to provide both a "session"
    attribute and a "user" attibute, like AuthMiddleware does.
    This runs http_session() to get a session to hook auth off of.
    If the user does not have a session cookie set, both "session"
    and "user" will be None.
    """

    @rest_auth
    @functools.wraps(func)
    def inner(message, *args, **kwargs):
        # If we didn't get a session, then we don't get a user
        if not hasattr(message, "auth"):
            raise ValueError("Did not see a http session to get auth from")
        return func(message, *args, **kwargs)

    return inner

class RestTokenConsumerMixin:
    """
    Authenticate user with token.
    This mixin has to be passed as the first parent in class definition.
    Pass the token as query parameter eg.
    ws://127.0.0.1:8000/chat/?token=<your_token>
    """
    rest_user = True
    #  This has to be True in order to keep information about the user

    def get_handler(self, message, **kwargs):
        handler = super(RestTokenConsumerMixin, self).get_handler(message, **kwargs)
        if self.rest_user:
            handler = rest_token_user(handler)
        return handler
</code>```

src: https://gist.github.com/leonardoo/9574251b3c7eefccd84fc38905110ce4

And i can access it in connect method in my class based consumer:

```<code>from channels.generic.websockets import JsonWebsocketConsumer
from common.authentication import RestTokenConsumerMixin
from accounts.serializers import UserSerializer

class ChatConsumer(RestTokenConsumerMixin, JsonWebsocketConsumer):

    # Set to True if you want it, else leave it out
    strict_ordering = False
    channel_session = True

    def connection_groups(self, **kwargs):
        """
        Called to return the list of groups to automatically add/remove
        this connection to/from.
        """
        return ["test"]

    def connect(self, message, **kwargs):
        """
        Perform things on connection start
        """
        message.channel_session['user'] = UserSerializer(instance=message.user).data
        if message.user.is_authenticated() and not message.user.is_anonymous:
            message.reply_channel.send({"accept": True})
        else:
            self.disconnect({'Error': 'Not authenticated user'})

    def receive(self, content, **kwargs):
        """
        Called when a message is received with decoded JSON content
        """
        # Simple echo
        self.send(self.message.user.username)

    def disconnect(self, message, **kwargs):
        """
        Perform things on connection close
        """
        pass
</code>```

As you can see right now to keep information about the user I am using serializer and channel_session. Is there a way around it so that I can have the user in receive and disconnect method like from http_user?

And will it be any more efficient than something like:
user = User.objects.get(id=self.message.channel_session['user']['id'])?

答:
I resolved it by creating a simple mixin:</p>

```<code>from django.contrib.auth import get_user_model

class KeepUserConsumerMixin:
    channel_session = True

    @staticmethod
    def _save_user(func):
        def wrapper(message, **kwargs):
            if message.user is not None and message.user.is_authenticated():
                message.channel_session['user_id'] = message.user.id
            return func(message, **kwargs)
        return wrapper

    def __getattribute__(self, name):
        method = super().__getattribute__(name)
        if name == 'connect':
            return self._save_user(method)
        return method

    @property
    def user(self):
        if not hasattr(self, '_user'):
            user_id = self.message.channel_session['user_id']
            self._user = get_user_model().objects.get(id=user_id)
        return self._user
</code>```

Body:
I am authenticating user on connect with this Mixin:

import functools

from channels.handler import AsgiRequest
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.settings import api_settings

authenticators = [auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES]

def rest_auth(func):
    """
    Wraps a HTTP or WebSocket connect consumer (or any consumer of messages
    that provides a "cookies" or "get" attribute) to provide a "http_session"
    attribute that behaves like request.session; that is, it's hung off of
    a per-user session key that is saved in a cookie or passed as the
    "session_key" GET parameter.
    It won't automatically create and set a session cookie for users who
    don't have one - that's what SessionMiddleware is for, this is a simpler
    read-only version for more low-level code.
    If a message does not have a session we can inflate, the "session" attribute
    will be None, rather than an empty session you can write to.
    Does not allow a new session to be set; that must be done via a view. This
    is only an accessor for any existing session.
    """

    @functools.wraps(func)
    def inner(message, *args, **kwargs):
        # Make sure there's NOT a http_session already
        try:
            # We want to parse the WebSocket (or similar HTTP-lite) message
            # to get cookies and GET, but we need to add in a few things that
            # might not have been there.
            if "method" not in message.content:
                message.content['method'] = "FAKE"
            request = AsgiRequest(message)

        except Exception as e:
            raise ValueError(
                f'Cannot parse HTTP message - are you sure this is a HTTP consumer? {e}')
        # Make sure there's a session key
        user = None
        auth = None
        auth_token = request.GET.get("token", None)

        if auth_token:
            # comptatibility with rest framework
            request._request = {}
            request.META["Authorization"] = "Bearer {}".format(auth_token)
            for authenticator in authenticators:
                try:
                    user_auth_tuple = authenticator.authenticate(request)
                except AuthenticationFailed:
                    pass

                if user_auth_tuple is not None:
                    message._authenticator = authenticator
                    user, auth = user_auth_tuple
                    break
        message.user, message.auth = user, auth
        result = func(message, *args, **kwargs)
        return result
    return inner

def rest_token_user(func):
    """
    Wraps a HTTP or WebSocket consumer (or any consumer of messages
    that provides a "COOKIES" attribute) to provide both a "session"
    attribute and a "user" attibute, like AuthMiddleware does.
    This runs http_session() to get a session to hook auth off of.
    If the user does not have a session cookie set, both "session"
    and "user" will be None.
    """

    @rest_auth
    @functools.wraps(func)
    def inner(message, *args, **kwargs):
        # If we didn't get a session, then we don't get a user
        if not hasattr(message, "auth"):
            raise ValueError("Did not see a http session to get auth from")
        return func(message, *args, **kwargs)

    return inner

class RestTokenConsumerMixin:
    """
    Authenticate user with token.
    This mixin has to be passed as the first parent in class definition.
    Pass the token as query parameter eg.
    ws://127.0.0.1:8000/chat/?token=<your_token>
    """
    rest_user = True
    #  This has to be True in order to keep information about the user

    def get_handler(self, message, **kwargs):
        handler = super(RestTokenConsumerMixin, self).get_handler(message, **kwargs)
        if self.rest_user:
            handler = rest_token_user(handler)
        return handler

src: https://gist.github.com/leonardoo/9574251b3c7eefccd84fc38905110ce4

And i can access it in connect method in my class based consumer:

from channels.generic.websockets import JsonWebsocketConsumer
from common.authentication import RestTokenConsumerMixin
from accounts.serializers import UserSerializer

class ChatConsumer(RestTokenConsumerMixin, JsonWebsocketConsumer):

    # Set to True if you want it, else leave it out
    strict_ordering = False
    channel_session = True

    def connection_groups(self, **kwargs):
        """
        Called to return the list of groups to automatically add/remove
        this connection to/from.
        """
        return ["test"]

    def connect(self, message, **kwargs):
        """
        Perform things on connection start
        """
        message.channel_session['user'] = UserSerializer(instance=message.user).data
        if message.user.is_authenticated() and not message.user.is_anonymous:
            message.reply_channel.send({"accept": True})
        else:
            self.disconnect({'Error': 'Not authenticated user'})

    def receive(self, content, **kwargs):
        """
        Called when a message is received with decoded JSON content
        """
        # Simple echo
        self.send(self.message.user.username)

    def disconnect(self, message, **kwargs):
        """
        Perform things on connection close
        """
        pass

As you can see right now to keep information about the user I am using serializer and channel_session. Is there a way around it so that I can have the user in receive and disconnect method like from http_user?

And will it be any more efficient than something like:
user = User.objects.get(id=self.message.channel_session['user']['id'])?

Body:
I resolved it by creating a simple mixin:

from django.contrib.auth import get_user_model

class KeepUserConsumerMixin:
    channel_session = True

    @staticmethod
    def _save_user(func):
        def wrapper(message, **kwargs):
            if message.user is not None and message.user.is_authenticated():
                message.channel_session['user_id'] = message.user.id
            return func(message, **kwargs)
        return wrapper

    def __getattribute__(self, name):
        method = super().__getattribute__(name)
        if name == 'connect':
            return self._save_user(method)
        return method

    @property
    def user(self):
        if not hasattr(self, '_user'):
            user_id = self.message.channel_session['user_id']
            self._user = get_user_model().objects.get(id=user_id)
        return self._user


问:
Angular/TypeScript/RxJS - I've tried all renditions of map, concat, merge etc - trying to get nested items in array
Currently the following final lines (after retrieving from an Observable.forkJoin of 17 this.http.get requests):

```<code>        .map(data => Observable.from(data))
        .finally(() => { console.log(this.topicData) })
        .subscribe((data) => { this.topicData = data });
</code>```

And the console.log above you see gives me data in the following format:

As you can see, this has arrays within arrays.  I just want a single Observable array with the Objects nested two layers within shell arrays.  Again, I have tried all the maps, concat, reduce, merge etc.  With RxJS I feel like I just plug things in until it works.  When I read the documentation, I have difficulty understanding how it relates to what I am trying to do (training resources are welcome also).  For this problem in particular, does anybody know how I can return a single Observable array with the Objects?

Update with additional code from forkJoin:

```<code>return Observable.forkJoin(
            this.http.get(this.baseUrl + webs[0] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[1] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[2] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[3] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[4] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[5] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[6] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[7] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[8] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[9] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[10] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[11] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[12] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[13] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[14] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[15] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[16] + this.topicsRest, this.options).map((res: Response) => res.json().d.results)
        )
</code>```

答:
Get rid of this line:

```<code>.map(data => Observable.from(data))
</code>```

This is wrapping the observable in another observable, probably not what you were intending.

I agree that the Rxjs docs are frustrating! You might find rxmarbles.com  a helpful reference for some of the common functions, although it's not a good resource for first learning.

Hope I answered your question.

Body:
Currently the following final lines (after retrieving from an Observable.forkJoin of 17 this.http.get requests):

        .map(data => Observable.from(data))
        .finally(() => { console.log(this.topicData) })
        .subscribe((data) => { this.topicData = data });

And the console.log above you see gives me data in the following format:

As you can see, this has arrays within arrays.  I just want a single Observable array with the Objects nested two layers within shell arrays.  Again, I have tried all the maps, concat, reduce, merge etc.  With RxJS I feel like I just plug things in until it works.  When I read the documentation, I have difficulty understanding how it relates to what I am trying to do (training resources are welcome also).  For this problem in particular, does anybody know how I can return a single Observable array with the Objects?

Update with additional code from forkJoin:

return Observable.forkJoin(
            this.http.get(this.baseUrl + webs[0] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[1] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[2] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[3] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[4] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[5] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[6] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[7] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[8] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[9] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[10] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[11] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[12] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[13] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[14] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[15] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[16] + this.topicsRest, this.options).map((res: Response) => res.json().d.results)
        )

Body:
Get rid of this line:

.map(data => Observable.from(data))

This is wrapping the observable in another observable, probably not what you were intending.

I agree that the Rxjs docs are frustrating! You might find rxmarbles.com  a helpful reference for some of the common functions, although it's not a good resource for first learning.

Hope I answered your question.


问:
QSerialPort with thread
I have been struggling a project that it communicates through the serial port in Qt for around two weeks. First I tried signal/slot method, it missed some data. Then I decided to use a thread for this, but I got the same result. While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data. Please help me this condition.

The MainWindow Constructor:

```<code>SerialPort *serial= new SerialPort();
serial->moveToThread(&cThread);

connect(this , &MainWindow::finished, &cThread, &QThread::quit);
connect(this , &MainWindow::destroyed, this, &SerialPort::deleteLater);
connect(serial, &SerialPort::getData, this, &MainWindow::displayData);

cThread.start();
</code>```

The Serial Port read thread:

```<code>void SerialPort::newData()
{
     mutex.lock();
     bArray.insert(bArray.length(),serial->readAll());
     mutex.unlock();

     emit getData(&bArray,&mutex);
}
</code>```

The SerialPort Constructor:

```<code>serial = new QSerialPort();
connect(serial, &QSerialPort::readyRead, this,  &SerialPort::newData);

bArray.clear();

fill_serial_ports();
portName = find_stm32_port();

serial->setReadBufferSize(20*1024*1024); // it's a huge buffer.
bArray.reserve(20*1024*1024);  // it's a huge buffer.

open_serial_port();
</code>```

Also, I thought that this can be a bug what misses some data and wrote to the bug tracker. Assignee said that QSerialPort never loses data furthermore, my code is wrong. I'm very confused, I don't know where to make mistakes. Please, could you check my other solution? Where is the mistake?

My bug tracker report (Not accepted) : https://bugreports.qt.io/browse/QTBUG-61233

答:
This problem was solved by Denis Shienkov in qtbugreports. You can take a look the qsp-no-freeze-workaround-windows.zip example for serial port with thread.

Link : https://bugreports.qt.io/browse/QTBUG-61233

Title: QSerialPort with thread

Body:
I have been struggling a project that it communicates through the serial port in Qt for around two weeks. First I tried signal/slot method, it missed some data. Then I decided to use a thread for this, but I got the same result. While the application's window is being resized or maximized /minimized, even hold left mouse button on the window's bar, it missed some data. Please help me this condition.

The MainWindow Constructor:

SerialPort *serial= new SerialPort();
serial->moveToThread(&cThread);

connect(this , &MainWindow::finished, &cThread, &QThread::quit);
connect(this , &MainWindow::destroyed, this, &SerialPort::deleteLater);
connect(serial, &SerialPort::getData, this, &MainWindow::displayData);

cThread.start();

The Serial Port read thread:

void SerialPort::newData()
{
     mutex.lock();
     bArray.insert(bArray.length(),serial->readAll());
     mutex.unlock();

     emit getData(&bArray,&mutex);
}

The SerialPort Constructor:

serial = new QSerialPort();
connect(serial, &QSerialPort::readyRead, this,  &SerialPort::newData);

bArray.clear();

fill_serial_ports();
portName = find_stm32_port();

serial->setReadBufferSize(20*1024*1024); // it's a huge buffer.
bArray.reserve(20*1024*1024);  // it's a huge buffer.

open_serial_port();

Also, I thought that this can be a bug what misses some data and wrote to the bug tracker. Assignee said that QSerialPort never loses data furthermore, my code is wrong. I'm very confused, I don't know where to make mistakes. Please, could you check my other solution? Where is the mistake?

My bug tracker report (Not accepted) : https://bugreports.qt.io/browse/QTBUG-61233


问:
Django custom admin template access GET parameters
I want to create custom django admin template and pass there some data. Is it possible to access GET query in custom template ?</p>

答:
The request object should be injected into all templates, so yes, you can access the GET dictionary.

```<code>{{ request.GET.my_param }}
</code>```

Body:
The request object should be injected into all templates, so yes, you can access the GET dictionary.

{{ request.GET.my_param }}


问:
Semantic UI - Keep thead visible when scrolling tbody
I'm trying to figure out how to keep the table head visible when scrolling. Is there a setting in semantic ui for this? Or will I just have to use a non-semantic ui solution?

You'll need to view "Full page" to see the table correctly.

<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.12.0/semantic.css" rel="stylesheet" />

        Date
        Status
        Facility Name
        Phone

        Date
        Status
        Facility Name
        Phone

        Date
        Status
        Facility Name
        Phone

        Date
        Status
        Facility Name
        Phone

        Date
        Status
        Facility Name
        Phone

        Date
        Status
        Facility Name
        Phone

        Date
        Status
        Facility Name
        Phone

        Date
        Status
        Facility Name
        Phone

        Date
        Status
        Facility Name
        Phone

```

答:
This script will probably do the job for you. Just add the class "sticky" to your table tag and adjust the offset from the top:</p>

```<code>$(document).ready(function(){
    var tableTop = $('.sticky.table').offset().top;

    $('.sticky.table').children('thead').children('tr').children('th').each( function()  {
        $(this).css({  width: $(this).outerWidth() });
    });

    $(window).scroll(function() {
        var fromTop = $(window).scrollTop();

        if($('.sticky.table').length > 0){
            stickyTableHead(fromTop);
        }
    });

    function stickyTableHead(fromTop){
        if(fromTop > tableTop ){
            $('.sticky.table').children('thead').css({'position': 'fixed', top: 0 });
        }else{
            $('.sticky.table').children('thead').css({'position': 'relative', top: 0});
        }
    };
});
</code>```

Body:
This script will probably do the job for you. Just add the class "sticky" to your table tag and adjust the offset from the top:

$(document).ready(function(){
    var tableTop = $('.sticky.table').offset().top;

    $('.sticky.table').children('thead').children('tr').children('th').each( function()  {
        $(this).css({  width: $(this).outerWidth() });
    });

    $(window).scroll(function() {
        var fromTop = $(window).scrollTop();

        if($('.sticky.table').length > 0){
            stickyTableHead(fromTop);
        }
    });

    function stickyTableHead(fromTop){
        if(fromTop > tableTop ){
            $('.sticky.table').children('thead').css({'position': 'fixed', top: 0 });
        }else{
            $('.sticky.table').children('thead').css({'position': 'relative', top: 0});
        }
    };
});


问:
Within each td/box, how to make it so the header in each box is fixed with scrollable div beneath?
I have 9 boxes, I want each box to have a "heading", and scrollable content beneath the "Box n" heading.

Am looking for 1) Ensure the "header" is vertically aligned to the top of each box. 2) The scrollable content takes up the max height of each box.

How do I do this? My HTML is the following:

html,
body {
  width: 100%;
  height: 100%;
}

table {
  border: 1;
  width: 100%;
  height: 100%;
}

td {
  text-align: center;
  background: red;
}

div {
  overflow: auto;
  height: 100%;
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      <div>
        Box1<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
    <td>
      <div>Box2</div>
      <div>
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
    <td>
      <div>
        Box3<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
  </tr>
  <tr>
    <td>Box4</td>
    <td>Box5</td>
    <td>Box6</td>
  </tr>
  <tr>
    <td>Box7</td>
    <td>Box8</td>
    <td>Box9</td>
  </tr>
</table></code>```

The fiddle I have is here:
https://jsfiddle.net/ba5qxzmo/

Box 1 is bad, because the Box1 header text is not "fixed at the top of the box and scrolls with the content.
Box 2 is my attempt at creating a fixed header, but it messes up the look of the box entirely.
Box 3 and the rest of the boxes also do not have a fixed header.

How can I make it such that each box has a "fixed" header? (Box1, Box2, Box3), with scrollable content (overflow) beneath each of them?

答:
Take heading on one div and the content in another div, and make the first div position fixed. and give the second div propperty overflow: scroll;

            Some text

            Some text<br>
        </p>

```<code>     .heading{
        position:fixed;
      }

     .content{
        overflow:scroll;
      }
</code>```

Body:
I have 9 boxes, I want each box to have a "heading", and scrollable content beneath the "Box n" heading.

Am looking for 1) Ensure the "header" is vertically aligned to the top of each box. 2) The scrollable content takes up the max height of each box.

How do I do this? My HTML is the following:

html,
body {
  width: 100%;
  height: 100%;
}

table {
  border: 1;
  width: 100%;
  height: 100%;
}

td {
  text-align: center;
  background: red;
}

div {
  overflow: auto;
  height: 100%;
  background: yellow;
}

        Box1
 Some TExt
 Some TExt
 Some TExt
 Some TExt
Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

Box2

        Some TExt
 Some TExt
 Some TExt
 Some TExt
Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

        Box3
 Some TExt
 Some TExt
 Some TExt
 Some TExt
Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

    Box4
    Box5
    Box6

    Box7
    Box8
    Box9

The fiddle I have is here:
https://jsfiddle.net/ba5qxzmo/

Box 1 is bad, because the Box1 header text is not "fixed at the top of the box and scrolls with the content.
Box 2 is my attempt at creating a fixed header, but it messes up the look of the box entirely.
Box 3 and the rest of the boxes also do not have a fixed header.

How can I make it such that each box has a "fixed" header? (Box1, Box2, Box3), with scrollable content (overflow) beneath each of them?

Body:
Take heading on one div and the content in another div, and make the first div position fixed. and give the second div propperty overflow: scroll;

            Some text

            Some text

     .heading{
        position:fixed;
      }

     .content{
        overflow:scroll;
      }


问:
How to exit cleanly with tcpdump running in subprocess in sudo mode
I am running tcpdump using the subprocess module in python to capture a trace of a website, using this piece of code:

```<code>import subprocess
from tbselenium.tbdriver import TorBrowserDriver

site = "check.torproject.org"

try:

        process = subprocess.Popen(['sudo', 'tcpdump', '-l', '-i', 'eth0', '-w', 'trace.pcap'], stdout=subprocess.PIPE)

        with TorBrowserDriver("/path/to/tor-browser_en-US/") as driver:
            driver.load_url("https://" + site, wait_on_page=20)

        process.send_signal(subprocess.signal.SIGTERM)

except OSError:
    print "OSError"
</code>```

The code gives me an OSError and when I try to open the pcap file in wireshark I get the following error box:

The capture file appears to have been cut short in the middle of a packet.

I've read this solution to the same issue, and have tried sending both a SIGINT and a SIGTERM, but I get the same truncated-packet message in each case along with an OSError. I have also tried using process.terminate() but that doesn't work either. Is there any way I could make tcpdump exit cleanly while running in sudo mode. Thanks!

答:
Since tcpdump needs su privileges you can simply run the script as su and check for it before you spawn tcpdump:

```<code># Check we are running as root:
if os.geteuid() != 0:
    print('This script requires root privileges to capture packets. Try running this script as root.')
    raise SystemExit

# Start TCPDUMP
import subprocess, os
_process = subprocess.Popen(['tcpdump', '-nnvvv', '-s0', '-w', os.path.join('/tmp', 'output.pcap'), ])
</code>```

This way you can run

```<code>_process.terminate()
</code>```

or

```<code>_process.kill()
</code>```

to send the proper signal to tcpdump

Body:
I am running tcpdump using the subprocess module in python to capture a trace of a website, using this piece of code:

import subprocess
from tbselenium.tbdriver import TorBrowserDriver

site = "check.torproject.org"

try:

        process = subprocess.Popen(['sudo', 'tcpdump', '-l', '-i', 'eth0', '-w', 'trace.pcap'], stdout=subprocess.PIPE)

        with TorBrowserDriver("/path/to/tor-browser_en-US/") as driver:
            driver.load_url("https://" + site, wait_on_page=20)

        process.send_signal(subprocess.signal.SIGTERM)

except OSError:
    print "OSError"

The code gives me an OSError and when I try to open the pcap file in wireshark I get the following error box:

The capture file appears to have been cut short in the middle of a packet.

I've read this solution to the same issue, and have tried sending both a SIGINT and a SIGTERM, but I get the same truncated-packet message in each case along with an OSError. I have also tried using process.terminate() but that doesn't work either. Is there any way I could make tcpdump exit cleanly while running in sudo mode. Thanks!

Body:
Since tcpdump needs su privileges you can simply run the script as su and check for it before you spawn tcpdump:

# Check we are running as root:
if os.geteuid() != 0:
    print('This script requires root privileges to capture packets. Try running this script as root.')
    raise SystemExit

# Start TCPDUMP
import subprocess, os
_process = subprocess.Popen(['tcpdump', '-nnvvv', '-s0', '-w', os.path.join('/tmp', 'output.pcap'), ])

This way you can run

_process.terminate()

or

_process.kill()

to send the proper signal to tcpdump


问:
How can I change icons for existing URL shortcuts using Powershell?
I am wanting to change the icon for an existing shortcut using Powershell.

I played around with it but I couldn't set the changes so I went online and came up empty-handed. I've seen examples with VB and Command Shell but nothing with Powershell. Nearly 99% demonstrated how to create the shortcut but I just need to know how to change the icon and only the icon.

Here is what I did so far:

```<code># Make a copy of the icon in the directory
PS> cd Program Files (x86)\Dir\Fol\
PS Program Files (x86)\Dir\Fol> cp 1234567890.ico 12345678901.ico

# Gets the IconFile property and changes it to the new icon
PS Program Files (x86)\Dir\Fol> cd Desktop\Folder\
PS Desktop\Folder>(Get-Content "file name")[6]
IconFile=C:\Program Files (x86)\Dir\Fol\1234567890.ico
PS Desktop\Folder>(Get-Content "file name")[6] -replace ".ico","1.ico"
</code>```

I've tried working with the WScript.Shell ComObject but that seems to only create new shortcuts.

I feel like where I was going with it would work if there was a way to save, update, and apply the new IconFile path in the object.

I'm doing this as a fix action due to icons (or maybe something in the symbolic LNK?) "breaking" and defaulting to a generic icon. Seems to only be an issue with shortcuts. The shortcut works perfectly, everything is fine but for one reason or another, the icons default. If I go in and reapply the same icon name through the GUI, it won't change. However, if I change the name of the .ico file by any measure and then set it, it works. Don't know why it is doing it but I was wanting to create a PS script that would do it automatically (and I was looking for an excuse to jam out a script)

答:
for me .iconlocation does not exist in $shortcut and gives an error (might be the powershell version...). but here is how changed the url icon to a custom one i made: (the main part is the add-content commands)</p>

```<code>$WshShell = New-Object -comObject WScript.Shell

$path = "C:\Users\USER\desktop\WEBSITE.url"

$targetpath = "https://WEBSITE.com"

$iconlocation = "C:\Users\USER\Desktop\YourIcon.ico"

$iconfile = "IconFile=" + $iconlocation

$Shortcut = $WshShell.CreateShortcut($path)

$Shortcut.TargetPath = $targetpath

$Shortcut.Save()

Add-Content $path "HotKey=0"

Add-Content $path "$iconfile"

Add-Content $path "IconIndex=0"
</code>```

Body:
I am wanting to change the icon for an existing shortcut using Powershell.

I played around with it but I couldn't set the changes so I went online and came up empty-handed. I've seen examples with VB and Command Shell but nothing with Powershell. Nearly 99% demonstrated how to create the shortcut but I just need to know how to change the icon and only the icon.

Here is what I did so far:

# Make a copy of the icon in the directory
PS> cd Program Files (x86)\Dir\Fol\
PS Program Files (x86)\Dir\Fol> cp 1234567890.ico 12345678901.ico

# Gets the IconFile property and changes it to the new icon
PS Program Files (x86)\Dir\Fol> cd Desktop\Folder\
PS Desktop\Folder>(Get-Content "file name")[6]
IconFile=C:\Program Files (x86)\Dir\Fol\1234567890.ico
PS Desktop\Folder>(Get-Content "file name")[6] -replace ".ico","1.ico"

I've tried working with the WScript.Shell ComObject but that seems to only create new shortcuts.

I feel like where I was going with it would work if there was a way to save, update, and apply the new IconFile path in the object.

I'm doing this as a fix action due to icons (or maybe something in the symbolic LNK?) "breaking" and defaulting to a generic icon. Seems to only be an issue with shortcuts. The shortcut works perfectly, everything is fine but for one reason or another, the icons default. If I go in and reapply the same icon name through the GUI, it won't change. However, if I change the name of the .ico file by any measure and then set it, it works. Don't know why it is doing it but I was wanting to create a PS script that would do it automatically (and I was looking for an excuse to jam out a script)

Body:
for me .iconlocation does not exist in $shortcut and gives an error (might be the powershell version...). but here is how changed the url icon to a custom one i made: (the main part is the add-content commands)

$WshShell = New-Object -comObject WScript.Shell

$path = "C:\Users\USER\desktop\WEBSITE.url"

$targetpath = "https://WEBSITE.com"

$iconlocation = "C:\Users\USER\Desktop\YourIcon.ico"

$iconfile = "IconFile=" + $iconlocation

$Shortcut = $WshShell.CreateShortcut($path)

$Shortcut.TargetPath = $targetpath

$Shortcut.Save()

Add-Content $path "HotKey=0"

Add-Content $path "$iconfile"

Add-Content $path "IconIndex=0"


问:
Why firebase orderByChild doesn't work on timestamp?
I have a list of post. Each post contain firebase servervalue timestamp in createdAt.

let say, my post titles are 1,2,3,4,5. When i do this query.

```<code>const userPostsRef = database.ref(`userPosts/${uid}`)
                    .orderByChild('createdAt').limitToLast(10);`
</code>```

And it still return 1,2,3,4,5. What I want is 5,4,3,2,1

I tried to navigative timestamp and it works. Why? and is that mean i have to use another child orderTimestamp with negative timestamp for reverse query?

Update json

I mean limitToLast();

```<code>userPosts
 sms|5797235fe618d33da2eb0ad3

  -Km2l4HHE3pONRnA2Akp
   createdAt: 1496859301233
   o: -1496859301233
   title: "2"

 -Km2l5QQRi1F66LJkM45
  createdAt: 1496859305916
  o: -1496859305916
  title: "3"

 -Km2uTa8tAe0G5cJ2U-B
  createdAt: 1496861764218
  o: -1496861764218
  title: "4"

 -Km2uUrfwvY90Im06kg4
  createdAt: 1496861769435
  o: -1496861769435
  title: "5"
</code>```

orderByChild('createdAt')

orderByChild('o')

答: It always returns in ascending order, it is up to you on the client to order it the way you want after retrieval. If you had 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 and you wanted 15,14,13,12,11 you would do .limitToLast(5) instead getting 11,12,13,14,15 and then ordering backwards on the client.

Body:
I have a list of post. Each post contain firebase servervalue timestamp in createdAt.

let say, my post titles are 1,2,3,4,5. When i do this query.

const userPostsRef = database.ref(`userPosts/${uid}`)
                    .orderByChild('createdAt').limitToLast(10);`

And it still return 1,2,3,4,5. What I want is 5,4,3,2,1

I tried to navigative timestamp and it works. Why? and is that mean i have to use another child orderTimestamp with negative timestamp for reverse query?

Update json

I mean limitToLast();

userPosts
 sms|5797235fe618d33da2eb0ad3

  -Km2l4HHE3pONRnA2Akp
   createdAt: 1496859301233
   o: -1496859301233
   title: "2"

 -Km2l5QQRi1F66LJkM45
  createdAt: 1496859305916
  o: -1496859305916
  title: "3"

 -Km2uTa8tAe0G5cJ2U-B
  createdAt: 1496861764218
  o: -1496861764218
  title: "4"

 -Km2uUrfwvY90Im06kg4
  createdAt: 1496861769435
  o: -1496861769435
  title: "5"

orderByChild('createdAt')

orderByChild('o')


问:
Jenkins pipeline pass all parameters down to downstream jobs
I have a pipeline job named buildall which looks like this:

```<code>pipeline {
    stages {
        stage("job1") {
            build job: "job1"
        }
    }
}
</code>```

The buildall job has 25 parameters.  I would like to pass all of buildall's parameters down to job1.  Is there an easy way I can do that, instead of manually specifying each parameter?

In this question: Pipeline pass parameters to downstream jobs
a sub-question was asked but never answered: Or even better, is there a less cumbersome way in which I can just pass ALL the pipeline parameters to the downstream job.

That's the same question that I have.

答:
The following seems to work (I haven't tested it extensively though):

```<code>pipeline {
    agent any
    parameters {
        string(name: 'PARAM1', description: 'Param 1?')
        string(name: 'PARAM2', description: 'Param 2?')
    }
    stages {
        stage('Example') {
            steps {
                echo "${params}"
                script {
                    def myparams = currentBuild.rawBuild.getAction(ParametersAction).getParameters()
                    build job: 'downstream-pipeline-with-params', parameters: myparams
                }
            }
        }
    }
}
</code>```

Drawback: to access rawBuild and getAction you have to disable the Groove sandbox or approve these signatures in Jenkins under Manage Jenkins > In-process Script Approval. This dialog will show you that you might introduced a security vulnerability. So it depends on your environment if you want to take this risk or not.

Body:
I have a pipeline job named buildall which looks like this:

pipeline {
    stages {
        stage("job1") {
            build job: "job1"
        }
    }
}

The buildall job has 25 parameters.  I would like to pass all of buildall's parameters down to job1.  Is there an easy way I can do that, instead of manually specifying each parameter?

In this question: Pipeline pass parameters to downstream jobs
a sub-question was asked but never answered: Or even better, is there a less cumbersome way in which I can just pass ALL the pipeline parameters to the downstream job.

That's the same question that I have.

Body:
The following seems to work (I haven't tested it extensively though):

pipeline {
    agent any
    parameters {
        string(name: 'PARAM1', description: 'Param 1?')
        string(name: 'PARAM2', description: 'Param 2?')
    }
    stages {
        stage('Example') {
            steps {
                echo "${params}"
                script {
                    def myparams = currentBuild.rawBuild.getAction(ParametersAction).getParameters()
                    build job: 'downstream-pipeline-with-params', parameters: myparams
                }
            }
        }
    }
}

Drawback: to access rawBuild and getAction you have to disable the Groove sandbox or approve these signatures in Jenkins under Manage Jenkins > In-process Script Approval. This dialog will show you that you might introduced a security vulnerability. So it depends on your environment if you want to take this risk or not.


问:
better understanding type promotion of variadic parameters in c
When a variable argument function is called in c the integer parameters are promoted to int and floating point parameters are promoted to double

Since the prototype doesn’t specify types for optional arguments, in a call to a variadic function the default argument promotions are performed on the optional argument values. This means the objects of type char or short int (whether signed or not) are promoted to either int or unsigned int, as appropriate; and that objects of type float are promoted to type double. So, if the caller passes a char as an optional argument, it is promoted to an int, and the function can access it with va_arg (ap, int).

int type should be 4 byte on 32 bit machines and 8 byte on 64 bit machines, is that right?

So I wonder what append when I pass a long long int to a variable argument function like printf with %lld format.

And, again, I wonder what append when I pass a long double variable to printf with %Lf format (no matter if on 32 or 64 bit machines).

[Edited]

on a 32 bit machine, I tried this:

```<code>#include <stdio.h>

int main(void)
{
    printf("sizeof(int) %d\n", sizeof(int));
    printf("sizeof(long int) %d\n", sizeof(long int));
    printf("sizeof(long long int) %d\n", sizeof(long long int));
    printf("%lld\n", 1LL<<33);

    printf("sizeof(float) %d\n", sizeof(float));
    printf("sizeof(double) %d\n", sizeof(double));
    printf("sizeof(long double) %d\n", sizeof(long double));
    return 0;
}
</code>```

The result is:

```<code>sizeof(int) 4
sizeof(long int) 4
sizeof(long long int) 8
8589934592
sizeof(float) 4
sizeof(double) 8
sizeof(long double) 12
</code>```

this makes me think that not all parameters are promoted to int, otherwise I would get printed 0 instead of 8589934592.

Maybe only arguments smaller than int are promoted to int. And something similar could be for floating point types.

[Edited]

on a 64 bit machine I run this:

```<code>int main(void)
{
    printf("sizeof(int) %lu\n", sizeof(int));
    printf("sizeof(long) %lu\n", sizeof(long));
    printf("sizeof(long long) %lu\n", sizeof(long long));
    return 0;
}
</code>```

and get

```<code>sizeof(int) 4
sizeof(long) 8
sizeof(long long) 8
</code>```

if I understand well the standard, only char and short are promoted to int. I wonder what happen in smaller architecture, such like 16 bit or 8 bit MCU. I think that int size is dependent by architecture, but I wonder if sizeof(int) can be 1 on 8 bit architecture. In this case promotion of short to int could be impossible unless loosing some bits

答:
So I wonder what append when I pass a long long int to a variable
  argument function like printf with %lld format. And, again, I wonder
  what append when I pass a long double variable to printf with %Lf
  format (no matter if on 32 or 64 bit machines).

Nothing happens, as the long long int has to be at least of the same size as int. Even in the most "pesimistic" scenario, where sizeof(long long int) == sizeof(int), the argument is still passed "as is" (without any promotion). The same applies to long double.

Body:
When a variable argument function is called in c the integer parameters are promoted to int and floating point parameters are promoted to double

Since the prototype doesn’t specify types for optional arguments, in a call to a variadic function the default argument promotions are performed on the optional argument values. This means the objects of type char or short int (whether signed or not) are promoted to either int or unsigned int, as appropriate; and that objects of type float are promoted to type double. So, if the caller passes a char as an optional argument, it is promoted to an int, and the function can access it with va_arg (ap, int).

int type should be 4 byte on 32 bit machines and 8 byte on 64 bit machines, is that right?

So I wonder what append when I pass a long long int to a variable argument function like printf with %lld format.

And, again, I wonder what append when I pass a long double variable to printf with %Lf format (no matter if on 32 or 64 bit machines).

[Edited]

on a 32 bit machine, I tried this:

#include <stdio.h>

int main(void)
{
    printf("sizeof(int) %d\n", sizeof(int));
    printf("sizeof(long int) %d\n", sizeof(long int));
    printf("sizeof(long long int) %d\n", sizeof(long long int));
    printf("%lld\n", 1LL<<33);

    printf("sizeof(float) %d\n", sizeof(float));
    printf("sizeof(double) %d\n", sizeof(double));
    printf("sizeof(long double) %d\n", sizeof(long double));
    return 0;
}

The result is:

sizeof(int) 4
sizeof(long int) 4
sizeof(long long int) 8
8589934592
sizeof(float) 4
sizeof(double) 8
sizeof(long double) 12

this makes me think that not all parameters are promoted to int, otherwise I would get printed 0 instead of 8589934592.

Maybe only arguments smaller than int are promoted to int. And something similar could be for floating point types.

[Edited]

on a 64 bit machine I run this:

int main(void)
{
    printf("sizeof(int) %lu\n", sizeof(int));
    printf("sizeof(long) %lu\n", sizeof(long));
    printf("sizeof(long long) %lu\n", sizeof(long long));
    return 0;
}

and get

sizeof(int) 4
sizeof(long) 8
sizeof(long long) 8

if I understand well the standard, only char and short are promoted to int. I wonder what happen in smaller architecture, such like 16 bit or 8 bit MCU. I think that int size is dependent by architecture, but I wonder if sizeof(int) can be 1 on 8 bit architecture. In this case promotion of short to int could be impossible unless loosing some bits


问:
Detect hangup event when call is parked in Asterisk 11
Is there any way to detect a hangup event in dialplan when call is parked? I see this message in log:

features.c:   == SIP/CHANNAME got tired of being parked

A 'h' extension in context 'parkedcalls' doesn't work:

[parkedcalls]

```<code>exten => h,1,DumpChan()
</code>```

A 'h' extension in main context works, but there is no difference between hangup and pickup.
Thanks for your help.

答:
You can set up a hangup handler, which follows the channel:
https://wiki.asterisk.org/wiki/display/AST/Hangup+Handlers</p>

Body:
Is there any way to detect a hangup event in dialplan when call is parked? I see this message in log:

features.c:   == SIP/CHANNAME got tired of being parked

A 'h' extension in context 'parkedcalls' doesn't work:

[parkedcalls]

exten => h,1,DumpChan()

A 'h' extension in main context works, but there is no difference between hangup and pickup.
Thanks for your help.


问:
how can i put a variable in the middle of the string in loadrunner?
I have a small difficulty with a script that I am setting in loadrunner in c, I need to put a variable in the middle of a text, how can I do?

Thank you.

答: LoadRunner virtual users are standard C language items for most virtual users.  This is where you leverage your foundation skills in the language of your tool to construct the proper string that you need to use.  There are many paths to your solution here.</p>


问:
Getting country name from country code in WooCommerce
WooCommerce defines countries as follows (edited for brevity):

```<code>class WC_Countries {
    public $countries;

    public function __construct() {
        global $woocommerce, $states;

        $this->countries = apply_filters( 'woocommerce_countries', array(
            'AF' => __( 'Afghanistan', 'woocommerce' ),
            'AX' => __( 'Åland Islands', 'woocommerce' ),
            'AL' => __( 'Albania', 'woocommerce' ),
            'DZ' => __( 'Algeria', 'woocommerce' ),
            // […]
        ));
    }
}
</code>```

When an order is placed, the country code is written to the WordPress wp_postmeta table and can be extracted anywhere an order id can be accessed using the get_post_meta() function:

```<code>get_post_meta( $order->id, '_shipping_country', true ),
</code>```

Since we are simply retrieving two characters from the database, the question is how to translate the shipping country code (e.g. AF) to the country name specified in the WC_Countries class?

答:
```<code>function a000_remove_bundles_counting(){
//////////////////////////////
global $woocommerce_bundles;
remove_filter( 'woocommerce_cart_contents_count',
array( $woocommerce_bundles->display, 'woo_bundles_cart_contents_count' ) );
}
add_action( 'init', 'a000_remove_bundles_counting' );
///////////////////////////////////////////////////

//////////////////////////////////////////////////////

function d000_cart_contents_count( $count ) {
    global $woocommerce;
 $cat_check = false;
  foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) { //foreach

 $product = $cart_item['data'];

 if ( has_term( 'VIP', 'product_tag', $product->id ) ) {//search product_cat
$cat_check = true;
// break because we only need one "true" to matter here
if (!function_exists('woo_override_checkout_fields')) {
function woo_override_checkout_fields( $fields ) { // woo_override_checkout_fields Function

$fields['billing']['billing_country'] = array(
'type' => 'select',
'label' => __('Country', 'woocommerce'),
'options' => array('US' => 'United States(US)')
);

$fields['billing']['billing_state'] = array(
'type' => 'select',
'label' => __('State', 'woocommerce'),
'options' => array('CA' => 'California(CA)')

);

return $fields;
} //end woo_override_checkout_fields Function
}
add_filter( 'woocommerce_checkout_fields' , 'woo_override_checkout_fields' );

} // end search product_cat
  }// end foreach

return $count;
}
add_filter( 'woocommerce_cart_contents_count',
'd000_cart_contents_count' );
</code>```

First you have set product tag "VIP or what ever you like and then you will add it to code

```<code>if ( has_term( 'VIP', 'product_tag', $product->id ) ) {//search product_cat

    $cat_check = true;
}
</code>```

in this function looking is there any product with "VIP" Product tag.
  and $cat_check = true;

then inside this in function we adding function
  woo_override_checkout_fields( $fields ) function to set limited
  country as shipping country field.

Inside woo_override_checkout_fields( $fields ) { }

Set which country you want to show

```<code>$fields['billing']['billing_country'] = array(
'type' => 'select',
'label' => __('Country', 'woocommerce'),
'options' => array('US' => 'United States(US)')
);

$fields['billing']['billing_state'] = array(
'type' => 'select',
'label' => __('State', 'woocommerce'),
'options' => array('CA' => 'California(CA)')

);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
WooCommerce defines countries as follows (edited for brevity):

class WC_Countries {
    public $countries;

    public function __construct() {
        global $woocommerce, $states;

        $this->countries = apply_filters( 'woocommerce_countries', array(
            'AF' => __( 'Afghanistan', 'woocommerce' ),
            'AX' => __( 'Åland Islands', 'woocommerce' ),
            'AL' => __( 'Albania', 'woocommerce' ),
            'DZ' => __( 'Algeria', 'woocommerce' ),
            // […]
        ));
    }
}

When an order is placed, the country code is written to the WordPress wp_postmeta table and can be extracted anywhere an order id can be accessed using the get_post_meta() function:

get_post_meta( $order->id, '_shipping_country', true ),

Since we are simply retrieving two characters from the database, the question is how to translate the shipping country code (e.g. AF) to the country name specified in the WC_Countries class?

Body:
function a000_remove_bundles_counting(){
//////////////////////////////
global $woocommerce_bundles;
remove_filter( 'woocommerce_cart_contents_count',
array( $woocommerce_bundles->display, 'woo_bundles_cart_contents_count' ) );
}
add_action( 'init', 'a000_remove_bundles_counting' );
///////////////////////////////////////////////////

//////////////////////////////////////////////////////

function d000_cart_contents_count( $count ) {
    global $woocommerce;
 $cat_check = false;
  foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) { //foreach

 $product = $cart_item['data'];

 if ( has_term( 'VIP', 'product_tag', $product->id ) ) {//search product_cat
$cat_check = true;
// break because we only need one "true" to matter here
if (!function_exists('woo_override_checkout_fields')) {
function woo_override_checkout_fields( $fields ) { // woo_override_checkout_fields Function

$fields['billing']['billing_country'] = array(
'type' => 'select',
'label' => __('Country', 'woocommerce'),
'options' => array('US' => 'United States(US)')
);

$fields['billing']['billing_state'] = array(
'type' => 'select',
'label' => __('State', 'woocommerce'),
'options' => array('CA' => 'California(CA)')

);

return $fields;
} //end woo_override_checkout_fields Function
}
add_filter( 'woocommerce_checkout_fields' , 'woo_override_checkout_fields' );

} // end search product_cat
  }// end foreach

return $count;
}
add_filter( 'woocommerce_cart_contents_count',
'd000_cart_contents_count' );

First you have set product tag "VIP or what ever you like and then you will add it to code

if ( has_term( 'VIP', 'product_tag', $product->id ) ) {//search product_cat

    $cat_check = true;
}

in this function looking is there any product with "VIP" Product tag.
  and $cat_check = true;

then inside this in function we adding function
  woo_override_checkout_fields( $fields ) function to set limited
  country as shipping country field.

Inside woo_override_checkout_fields( $fields ) { }

Set which country you want to show

$fields['billing']['billing_country'] = array(
'type' => 'select',
'label' => __('Country', 'woocommerce'),
'options' => array('US' => 'United States(US)')
);

$fields['billing']['billing_state'] = array(
'type' => 'select',
'label' => __('State', 'woocommerce'),
'options' => array('CA' => 'California(CA)')

);


答:
Just add your whole content of a cell except heading in a div and make the div as scrollable using max-height and overflow-y:scroll and set the height of td, heading and content so that everything will align properly.

html,body {
  width:100%;
  height:100%;
}
table {
  border:1;
  width:100%;
  height:100%;

}
td {
  text-align:center;
  background:red;
  padding:  10px 0;
}

.scroll {
  overflow-y: auto;
  height: 100%;
  background:yellow;
}

.heading{
  height:20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>

        <span class="heading">Box1</span>
        <div class="scroll">
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>

    </td>
    <td>
      <span class="heading">Box1</span>
      <div class="scroll">
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
    <td>

       <span class="heading">Box1</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>

    </td>
  </tr>
  <tr>
    <td>Box4</td>
    <td>Box5</td>
    <td>Box6</td>
  </tr>
  <tr>
    <td>Box7</td>
    <td>Box8</td>
    <td>Box9</td>
  </tr>
</table></code>```

Title: Within each td/box, how to make it so the header in each box is fixed with scrollable div beneath?

Body:
Just add your whole content of a cell except heading in a div and make the div as scrollable using max-height and overflow-y:scroll and set the height of td, heading and content so that everything will align properly.

html,body {
  width:100%;
  height:100%;
}
table {
  border:1;
  width:100%;
  height:100%;

}
td {
  text-align:center;
  background:red;
  padding:  10px 0;
}

.scroll {
  overflow-y: auto;
  height: 100%;
  background:yellow;
}

.heading{
  height:20px;
}

<table>
  <tr>
    <td>

        <span class="heading">Box1</span>
        <div class="scroll">
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>

    </td>
    <td>
      <span class="heading">Box1</span>
      <div class="scroll">
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
    <td>

       <span class="heading">Box1</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>

    </td>
  </tr>
  <tr>
    <td>Box4</td>
    <td>Box5</td>
    <td>Box6</td>
  </tr>
  <tr>
    <td>Box7</td>
    <td>Box8</td>
    <td>Box9</td>
  </tr>
</table>


问:
How can I get get params in url via slashes in Yii2?
I want to build url with get params via slashes.

For exapmle, I want this code:

```<code>Url::to(['/controller/action',
    'filter' => 'filter,
    'param1' => 'value1',
    'param2' => 'value2' ...]);
</code>```

to generate url:
//path.to.site/controller/action/filter/param1/value1/param2/value2...

Is there a way to make this via defaut urlManager?

答:
Sure:

```<code>'urlManager' => [
    'rules' => [
        '<controller>/<action>/<filter>/param1/<param1>/param2/<param2>' => '<controller>/<action>',
    ],
],
</code>```

Then Url::to will return following result:

```<code>Url::to([
    '/controller/action',
    'filter' => 'some-filter',
    'param1' => 'value1',
    'param2' => 'value2'
]);

// Result: http://base.url/controller/action/some-filter/param1/value1/param2/value2
</code>```

Body:
I want to build url with get params via slashes.

For exapmle, I want this code:

Url::to(['/controller/action',
    'filter' => 'filter,
    'param1' => 'value1',
    'param2' => 'value2' ...]);

to generate url:
//path.to.site/controller/action/filter/param1/value1/param2/value2...

Is there a way to make this via defaut urlManager?

Body:
Sure:

'urlManager' => [
    'rules' => [
        '<controller>/<action>/<filter>/param1/<param1>/param2/<param2>' => '<controller>/<action>',
    ],
],

Then Url::to will return following result:

Url::to([
    '/controller/action',
    'filter' => 'some-filter',
    'param1' => 'value1',
    'param2' => 'value2'
]);

// Result: http://base.url/controller/action/some-filter/param1/value1/param2/value2


问:
How do I change the color of all the elements (onHover) in a  even though some are wrapped in ?
The implementation is here: http://jsfiddle.net/chp8y/1/

If you hover over the first box, #1, you will see the 'Add Client' change color but the #1 won't. How do I achieve that without using JS ?

If you do a .sit-in-the-corner:hover it will only work when you hover over the 1. But that's not what I want.

Thoughts?

答:
THe style for the class has higher precedence than the style for the tag, so it will override it.

You can add a style that removes the specific setting for the span when the cell is hovered:

```<code>table td:hover .sit-in-the-corner {
  color: inherit;
}
</code>```

http://jsfiddle.net/chp8y/5/

Title: How do I change the color of all the elements (onHover) in a <td> even though some are wrapped in <span>?

Body:
THe style for the class has higher precedence than the style for the tag, so it will override it.

You can add a style that removes the specific setting for the span when the cell is hovered:

table td:hover .sit-in-the-corner {
  color: inherit;
}

http://jsfiddle.net/chp8y/5/


问:
FromBluetoothAddressAsync never returns on Windows 10 Creators Update in WPF Application
I upgraded to Windows 10, version 1703 build 15063 (Creators Update) official release. When I run the following code in a WPF desktop application, BluetoothLEDevice.FromBluetoothAddressAsync never returns.

This code worked on fine before my Windows 10 update (i.e. the previous 1607 build 14393). This code also works fine if it is running as a UWP in the new Win 10 1703.

```<code>BluetoothLEAdvertisementWatcher BleWatcher = null;

private void Button_Click(object sender, RoutedEventArgs e)
{
     BleWatcher = new BluetoothLEAdvertisementWatcher
     {
          ScanningMode = BluetoothLEScanningMode.Active
     };
     BleWatcher.Received += Watcher_Received;
     BleWatcher.Start();
}

private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender,
                                    BluetoothLEAdvertisementReceivedEventArgs args)
{
         var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
         // never continues beyond this point above with my BTLE devices that previously worked
}
</code>```

I followed the instructions here https://stackoverflow.com/a/37335251/3187714 to setup my WPF desktop app to use the UWP APIs.

The problem is even worse because my existing WPF application will be broken when customers start upgrading to Win 10 1703 because my existing exe no longer works.

Is anyone else experiencing this problem with the Windows 10 1703 update in a (Non UWP) desktop exe?

After further experiments, I did find if I added the optional BluetoothAddressType.Public 2nd argument to the FromBluetoothAddressAsync call, the function returned, but the device returned was null.

```<code>var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress, BluetoothAddressType.Public);
</code>```

答:
If you wish to use the CoInitializeSecurity solution in VB, here is a pinvoke solution.  Remember to unpair/repair all your BLE devices!

Note that is must be the fist thing executed in your code.
Note that this is NOT AT ALL secure.

```<code>Public Enum RpcAuthnLevel
    Default1 = 0
    None = 1
    Connect = 2
    Call1 = 3
    Pkt = 4
    PktIntegrity = 5
    PktPrivacy = 6
End Enum

Public Enum RpcImpLevel
    Default1 = 0
    Anonymous = 1
    Identify = 2
    Impersonate = 3
    Delegate1 = 4
End Enum

Public Enum EoAuthnCap
    None = &H0
    MutualAuth = &H1
    StaticCloaking = &H20
    DynamicCloaking = &H40
    AnyAuthority = &H80
    MakeFullSIC = &H100
    Default1 = &H800
    SecureRefs = &H2
    AccessControl = &H4
    AppID = &H8
    Dynamic = &H10
    RequireFullSIC = &H200
    AutoImpersonate = &H400
    NoCustomMarshal = &H2000
    DisableAAA = &H1000
End Enum

Declare Function CoInitializeSecurity Lib "ole32.dll" (pVoid As IntPtr, cAuthSvc As Integer, asAuthSvc As IntPtr, pReserved1 As IntPtr, dwAuthnLevel As Integer, dwImpLevel As Integer, pAuthList As IntPtr, dwCapabilities As Integer, pReserved3 As IntPtr) As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    CoInitializeSecurity(IntPtr.Zero, -1, IntPtr.Zero, IntPtr.Zero, RpcAuthnLevel.Default1, RpcImpLevel.Identify, IntPtr.Zero, EoAuthnCap.None, IntPtr.Zero)
    'Other code
End Sub
</code>```

Body:
I upgraded to Windows 10, version 1703 build 15063 (Creators Update) official release. When I run the following code in a WPF desktop application, BluetoothLEDevice.FromBluetoothAddressAsync never returns.

This code worked on fine before my Windows 10 update (i.e. the previous 1607 build 14393). This code also works fine if it is running as a UWP in the new Win 10 1703.

BluetoothLEAdvertisementWatcher BleWatcher = null;

private void Button_Click(object sender, RoutedEventArgs e)
{
     BleWatcher = new BluetoothLEAdvertisementWatcher
     {
          ScanningMode = BluetoothLEScanningMode.Active
     };
     BleWatcher.Received += Watcher_Received;
     BleWatcher.Start();
}

private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender,
                                    BluetoothLEAdvertisementReceivedEventArgs args)
{
         var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
         // never continues beyond this point above with my BTLE devices that previously worked
}

I followed the instructions here https://stackoverflow.com/a/37335251/3187714 to setup my WPF desktop app to use the UWP APIs.

The problem is even worse because my existing WPF application will be broken when customers start upgrading to Win 10 1703 because my existing exe no longer works.

Is anyone else experiencing this problem with the Windows 10 1703 update in a (Non UWP) desktop exe?

After further experiments, I did find if I added the optional BluetoothAddressType.Public 2nd argument to the FromBluetoothAddressAsync call, the function returned, but the device returned was null.

var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress, BluetoothAddressType.Public);

Body:
If you wish to use the CoInitializeSecurity solution in VB, here is a pinvoke solution.  Remember to unpair/repair all your BLE devices!

Note that is must be the fist thing executed in your code.
Note that this is NOT AT ALL secure.

Public Enum RpcAuthnLevel
    Default1 = 0
    None = 1
    Connect = 2
    Call1 = 3
    Pkt = 4
    PktIntegrity = 5
    PktPrivacy = 6
End Enum

Public Enum RpcImpLevel
    Default1 = 0
    Anonymous = 1
    Identify = 2
    Impersonate = 3
    Delegate1 = 4
End Enum

Public Enum EoAuthnCap
    None = &H0
    MutualAuth = &H1
    StaticCloaking = &H20
    DynamicCloaking = &H40
    AnyAuthority = &H80
    MakeFullSIC = &H100
    Default1 = &H800
    SecureRefs = &H2
    AccessControl = &H4
    AppID = &H8
    Dynamic = &H10
    RequireFullSIC = &H200
    AutoImpersonate = &H400
    NoCustomMarshal = &H2000
    DisableAAA = &H1000
End Enum

Declare Function CoInitializeSecurity Lib "ole32.dll" (pVoid As IntPtr, cAuthSvc As Integer, asAuthSvc As IntPtr, pReserved1 As IntPtr, dwAuthnLevel As Integer, dwImpLevel As Integer, pAuthList As IntPtr, dwCapabilities As Integer, pReserved3 As IntPtr) As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    CoInitializeSecurity(IntPtr.Zero, -1, IntPtr.Zero, IntPtr.Zero, RpcAuthnLevel.Default1, RpcImpLevel.Identify, IntPtr.Zero, EoAuthnCap.None, IntPtr.Zero)
    'Other code
End Sub


问:
can activeMQ read public synonyms
Currently in my application activeMQ is generating 3 table at run time , but whole application is using table through public synonym which is generated at run time. So when ever i created 3 tables manually despite of generating ActiveMQ at run time .
Then ActiveMQ is not able to access table from public synonym.

Thanks in Advance !

答:
Please try below methods (based on the info which you have given) and also can you please mention the username you are setting in your activemq.xml for below tag

```<code><property name="username" value="?????"/>
</code>```

1.After creating public synonym request you to please grant to the table names . Follow below steps

```<code>CREATE OR REPLACE PUBLIC SYNONYM ACTIVEMQ_MSGS
FOR <SCHEMA OR USER>.ACTIVEMQ_MSGS;

grant select on ACTIVEMQ_MSGS to public or <schema name which you have given tag of activemq.xml <property name="username" value="?????"/> >;
</code>```

similarly for other 2 tables as well

I believe a public synonym can be queried by any user, but if you want to have access to the base table you need to have a grant on that table.

a synonym is just an alias for the table.

Please do revert back in case you didn't found your answer.

Title: can activeMQ read public synonyms

Body:
Please try below methods (based on the info which you have given) and also can you please mention the username you are setting in your activemq.xml for below tag

<property name="username" value="?????"/>

1.After creating public synonym request you to please grant to the table names . Follow below steps

CREATE OR REPLACE PUBLIC SYNONYM ACTIVEMQ_MSGS
FOR <SCHEMA OR USER>.ACTIVEMQ_MSGS;

grant select on ACTIVEMQ_MSGS to public or <schema name which you have given tag of activemq.xml <property name="username" value="?????"/> >;

similarly for other 2 tables as well

I believe a public synonym can be queried by any user, but if you want to have access to the base table you need to have a grant on that table.

a synonym is just an alias for the table.

Please do revert back in case you didn't found your answer.