问:
How can I detect a partial rectangle and align image using Matlab?
I was wondering how it would be possible to detect the bottom right corner of a paper square I manually made (which is probably not perfectly a square, because I drew it myself) on top of another object. What I want to do is use this square as a reference and align the image according to the bottom right corner of the square. I'm quite a Matlab amateur. Can anybody help?

The top left square is the paper square I need to detect which is the reference point.

答:
You have a lot of choices to detect the square; it's actually a rectangle; you want to detect, but the easiest way is using morphological operations. Here I provided a commented script to help you; since you are a MATLAB amateur.

ShowMaskAsOverlay is not a built-in command in MATLAB, though, It is very useful. If you want to download it visit this link.

Another way I would suggest from what I understood from your question. You can save the image before making the square, and save another image after making the square. Then you will only need to get the difference between the two images.

```<code>close all;clear all;clc;

% Read in Image
im = imread('stack.png');

[r, c, ch] = size(im);

% Convert Image to Gray if it's RGB
if ch == 3
    gray = rgb2gray(im);
end

% Threshold Value; > 0.87 = 1 and  < 0.87 = 0
thresh = 0.87;
bw = im2bw(gray, thresh);

% Removing unwanted white pixels
bw = bwareaopen(bw, 400);
bw = imerode(bw, strel('disk', 3));
bw = imfill(bw, 'holes');
bw = bwareaopen(bw, 600);
bw = imdilate(bw, strel('disk', 3)); %optional. Could be omitted

% Calculating the BoundingBox of the Square
s = regionprops(bw, 'BoundingBox');
box = struct2cell(s);
pos = cell2mat(box);

%% Displaying Images
figure(1)
imshow(im)
rectangle('position', pos, 'edgecolor', 'red', 'linewidth', 1.5)
str = ['Bounding Box Bottom Right Corner Coordinate Value = ', num2str(pos(4))];
h = text(pos(3), pos(4), num2str(pos(4)));
set(h, 'Color', 'k', 'FontSize', 12, 'FontWeight', 'bold')
title(str)

figure(2)
imshow(gray)
showMaskAsOverlay(0.5, bw, 'g')
</code>```

Body:
You have a lot of choices to detect the square; it's actually a rectangle; you want to detect, but the easiest way is using morphological operations. Here I provided a commented script to help you; since you are a MATLAB amateur.

ShowMaskAsOverlay is not a built-in command in MATLAB, though, It is very useful. If you want to download it visit this link.

Another way I would suggest from what I understood from your question. You can save the image before making the square, and save another image after making the square. Then you will only need to get the difference between the two images.

close all;clear all;clc;

% Read in Image
im = imread('stack.png');

[r, c, ch] = size(im);

% Convert Image to Gray if it's RGB
if ch == 3
    gray = rgb2gray(im);
end

% Threshold Value; > 0.87 = 1 and  < 0.87 = 0
thresh = 0.87;
bw = im2bw(gray, thresh);

% Removing unwanted white pixels
bw = bwareaopen(bw, 400);
bw = imerode(bw, strel('disk', 3));
bw = imfill(bw, 'holes');
bw = bwareaopen(bw, 600);
bw = imdilate(bw, strel('disk', 3)); %optional. Could be omitted

% Calculating the BoundingBox of the Square
s = regionprops(bw, 'BoundingBox');
box = struct2cell(s);
pos = cell2mat(box);

%% Displaying Images
figure(1)
imshow(im)
rectangle('position', pos, 'edgecolor', 'red', 'linewidth', 1.5)
str = ['Bounding Box Bottom Right Corner Coordinate Value = ', num2str(pos(4))];
h = text(pos(3), pos(4), num2str(pos(4)));
set(h, 'Color', 'k', 'FontSize', 12, 'FontWeight', 'bold')
title(str)

figure(2)
imshow(gray)
showMaskAsOverlay(0.5, bw, 'g')


来源: stackexchange

问:
Why are my UITableViewCell's repeating?
When I scroll offscreen I get some repeating cells. How can I fix this?</p>

```<code>// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = [NSString stringWithFormat:@"Bar Cafe",indexPath.row];
            break;
        case 1:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester",indexPath.row];
            break;
        case 2:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester Shoes",indexPath.row];
            break;
        case 3:
            cell.textLabel.text = [NSString stringWithFormat:@"Local Advice - Paulina",indexPath.row];
            break;
        case 4:
            cell.textLabel.text = [NSString stringWithFormat:@"Museum Brileyeglass",indexPath.row];
            break;
        case 5:
            cell.textLabel.text = [NSString stringWithFormat:@"Redlight Swans",indexPath.row];
            break;
        case 6:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Flying Dutchman",indexPath.row];
            break;
        case 7:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Tiani Hempshop",indexPath.row];
            break;

        default:
            break;
    }

    // Configure the cell...
    //cell.textLabel.text = [NSString stringWithFormat:@"Featured Event %d",indexPath.row];
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"Description %d", indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}
</code>```

答: Because in the cellForRowAtIndexPath method, the cells are reused and whenever the u scroll, the indexpath will start from 0. For more detail u can use NSLog(@"Index Path.row=%d",indexPath.row) and see in Console window.</p>

ContentLicense: CC BY-SA 2.5

Title: Why are my UITableViewCell's repeating?

Body:
When I scroll offscreen I get some repeating cells. How can I fix this?

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = [NSString stringWithFormat:@"Bar Cafe",indexPath.row];
            break;
        case 1:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester",indexPath.row];
            break;
        case 2:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester Shoes",indexPath.row];
            break;
        case 3:
            cell.textLabel.text = [NSString stringWithFormat:@"Local Advice - Paulina",indexPath.row];
            break;
        case 4:
            cell.textLabel.text = [NSString stringWithFormat:@"Museum Brileyeglass",indexPath.row];
            break;
        case 5:
            cell.textLabel.text = [NSString stringWithFormat:@"Redlight Swans",indexPath.row];
            break;
        case 6:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Flying Dutchman",indexPath.row];
            break;
        case 7:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Tiani Hempshop",indexPath.row];
            break;

        default:
            break;
    }

    // Configure the cell...
    //cell.textLabel.text = [NSString stringWithFormat:@"Featured Event %d",indexPath.row];
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"Description %d", indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}


问:
Pagespeed issues: Leverage Browser Caching
I am failing the Google and GTmetrix speed tests miserably for my WordPress site. Both specify that browser caching is not enabled.

I have tried a few caching plugins, such as WP Super Cache, but they have had zero effect.

I have also manually edited the .htaccess file with the following:

```<code>##### EXPIRE CACHING - LEVERAGE BROWSER CACHING #####
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month 1 days"
ExpiresByType text/html "access plus 1 month 1 days"
ExpiresByType image/gif "access plus 1 month 1 days"
ExpiresByType image/jpeg "access plus 1 month 1 days"
ExpiresByType image/png "access plus 1 month 1 days"
ExpiresByType text/css "access plus 1 month 1 days"
ExpiresByType text/javascript "access plus 1 month 1 week"
ExpiresByType application/x-javascript "access plus 1 month 1 days"
ExpiresByType text/xml "access plus 1 seconds"
</IfModule>
##### END EXPIRE CACHING #####
</code>```

But, again, it  has had zero impact. I have tried my host provider, BlueHost, three times and they have given me a different response each time but they all roughly equate to "nothing to do with us."

Does anyone have an idea what I may be doing wrong?

I feel like I am hitting my head against a brick wall with this one!

I would appreciate any help you can give me.

答:
The code that you have added will work only when apache module mod_expires is active.

Alternatively, you can use the following code (add it to .htaccess)

```<code># 1 YEAR
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
# 1 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
# 1 WEEK
<FilesMatch "\.(txt|xml|js|css)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>
# NEVER CACHE - notice the extra directives
<FilesMatch "\.(html|htm|php|cgi|pl)$">
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
</FilesMatch>
</code>```

Please note, that this will leverage browser caching only for internal files, you can't control it for external files.

ContentLicense: CC BY-SA 3.0

Body:
I am failing the Google and GTmetrix speed tests miserably for my WordPress site. Both specify that browser caching is not enabled.

I have tried a few caching plugins, such as WP Super Cache, but they have had zero effect.

I have also manually edited the .htaccess file with the following:

##### EXPIRE CACHING - LEVERAGE BROWSER CACHING #####
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month 1 days"
ExpiresByType text/html "access plus 1 month 1 days"
ExpiresByType image/gif "access plus 1 month 1 days"
ExpiresByType image/jpeg "access plus 1 month 1 days"
ExpiresByType image/png "access plus 1 month 1 days"
ExpiresByType text/css "access plus 1 month 1 days"
ExpiresByType text/javascript "access plus 1 month 1 week"
ExpiresByType application/x-javascript "access plus 1 month 1 days"
ExpiresByType text/xml "access plus 1 seconds"
</IfModule>
##### END EXPIRE CACHING #####

But, again, it  has had zero impact. I have tried my host provider, BlueHost, three times and they have given me a different response each time but they all roughly equate to "nothing to do with us."

Does anyone have an idea what I may be doing wrong?

I feel like I am hitting my head against a brick wall with this one!

I would appreciate any help you can give me.

Body:
The code that you have added will work only when apache module mod_expires is active.

Alternatively, you can use the following code (add it to .htaccess)

# 1 YEAR
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
# 1 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
# 1 WEEK
<FilesMatch "\.(txt|xml|js|css)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>
# NEVER CACHE - notice the extra directives
<FilesMatch "\.(html|htm|php|cgi|pl)$">
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
</FilesMatch>

Please note, that this will leverage browser caching only for internal files, you can't control it for external files.


问:
how to store javascript variables with cookies js
I'm trying to make a simple program that stores the h1 value in a variable and then store it in a cookie. But whenever I reload the page the h1 value always goes back to 0 and is not being saved. Can someone please explain how I can save the variable in a cookie so when I reload the page it stays there.

```<code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body>
    <div class="container">
        <h1 id="hs">1 </h1> <img src="image01.jpg" width="960" height="640" />
        <button onclick="increase()" id="d">Increase value of cookie</button>
    </div>
    <script src="cookies.min.js"></script>
    <script>
        Cookies.set('name', 'leo');
        Cookies.set('nams', 'ddleo');
        var h = document.getElementById("hs");

        function increase() {
            var values = parseInt(document.getElementById('hs').innerHTML, 10);
            values++;
            Cookies.set("name", values);
            document.getElementById('hs').innerHTML = Cookies.get("name", values);
        }
    </script>
</body>

</html>
</code>```

答:
When the page loads, you need to replace the
 with the value from the cookie.

```<code>var h=document.getElementById("hs");
var value = Cookies.get('name');
if (value) {
    h.innerHTML = value;
}
</code>```

Body:
I'm trying to make a simple program that stores the h1 value in a variable and then store it in a cookie. But whenever I reload the page the h1 value always goes back to 0 and is not being saved. Can someone please explain how I can save the variable in a cookie so when I reload the page it stays there.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

1

        <button onclick="increase()" id="d">Increase value of cookie</button>

Body:
When the page loads, you need to replace the <h1> with the value from the cookie.

var h=document.getElementById("hs");
var value = Cookies.get('name');
if (value) {
    h.innerHTML = value;
}


问:
Import library only if document is present (not on server)
I am using sever rendering with my app and came across an issue while using a react extension for dragula library called react-dragula

issue here lies within

```<code>import Dragula from 'react-dragula';
</code>```

for some reason this uses document hence causes error during server side rendering as document is not present, therefore I need a way to only include it once document is available so I can start using it.

答:
Adding to the dannyjolie suggestion.

You can use try catch instead of setting in gulp/grunt

```<code>try {
  if(window)
     module.exports = require('react-dragula');
}
catch(ex)
{
 module.exports = function(){};
}
</code>```

Body:
I am using sever rendering with my app and came across an issue while using a react extension for dragula library called react-dragula

issue here lies within

import Dragula from 'react-dragula';

for some reason this uses document hence causes error during server side rendering as document is not present, therefore I need a way to only include it once document is available so I can start using it.

Body:
Adding to the dannyjolie suggestion.

You can use try catch instead of setting in gulp/grunt

try {
  if(window)
     module.exports = require('react-dragula');
}
catch(ex)
{
 module.exports = function(){};
}


问:
Make Magento render complete HTML page
I'm new to Magento

I get this template that I don't want to split into multiple blocks. I just want to render the page as it is (not only, but this is something I can try to understand later) when I go to some url.

So for example, going to /route/controller/action should display an html page I wrote from  to  (including, of course, HEAD and BODY).

So I read a few things. I followed some official tutorials and could create a module and an Action to render a JSON. Works fine! Going to /test/page/view shows a dumb json. Now I want to do something similar to render a page (and eventually pass parameters to it)

(http://devdocs.magento.com/videos/fundamentals/create-a-new-module/)

So this is what I get right now:

/Vendor/Module/etc/frontend/routes.xml

```<code><?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="victor" frontName="test">
            <module name="Victor_Template" />
        </route>
    </router>
</config>
</code>```

/Vendor/Module/Controller/Page/View.php

```<code>namespace Victor\Template\Controller\Page;

use \Magento\Backend\App\Action\Context;
use \Magento\Framework\App\Action\Action;
use \Magento\Framework\Controller\Result\JsonFactory;
use \Magento\Framework\View\Result\PageFactory;

class View extends Action
{
    protected $resultPageFactory;

    function __construct(Context $context, PageFactory $resultPageFactory){
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    public function execute(){
         return $this->resultPageFactory->create();
    }
}
</code>```

.../view/frontend/layout/template_page_view.xml (maybe the error is here)

```<code><?xml version="1.0" ?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Victor\Template\Block\Page\View" name="page.view" template="Victor_Template::page/view.phtml"/>
        </referenceContainer>
    </body>
</page>
</code>```

.../view/frontend/templates/page/view.phtml

```<code><h1>Hello World!</h1>
</code>```

After cleaning cache, flushing cache, giving permissions and upgrading setup (something I have to do all the time some change occurs in the code), I get an HTTP code 200 that gives me back a blank (totally white) Magento page that contains references to css, javascript files and a weird  like this:

Anyway, I don't know what is happening in background. Something tells me the error is the definition of the layout (template_page_view)

I tried to use echo before the return in the execute() method in the View, but it didn't show up, exit also won't stop that magento black/white page to be rendered.

I wanted the response to be just
Hwllo World!
.

What am I doing wrong and what is the proper way of doing it on Magento??

@edit
alright there seems to be a lot of cache issues. Now echo and exit works. but I still don't get the the Hello world

答:
It won't be easy but try this:

1) in your layout xml file (view/frontend/layout/template_page_view.xml):

```<code><?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="empty" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="top.container" remove="true" />
        <referenceContainer name="top.container" remove="true" />
        <referenceContainer name="page.bottom.container" remove="true"/>
        <referenceContainer name="before.body.end" remove="true"/>
        <referenceContainer name="after.body.start" remove="true"/>
        <referenceContainer name="footer" remove="true" />
        <referenceContainer name="footer-container" remove="true" />
        <referenceContainer name="global.notices" remove="true" />

        <referenceContainer name="content">
            <block class="Victor\Template\Block\Page\View" name="page.view" template="Victor_Template::page/view.phtml"/>
        </referenceContainer>
    </body>
</page>
</code>```

You probably will need to add more containers to remove depending on your theme and any additional 3rd party modules

2) in your controller create Page object like this:

```<code>return $this->resultPageFactory->create(false, ['template' => 'Vendrom_Module::blank.phtml']);
</code>```

3) last create file ../view/frontend/blank.phtml

```<code><!doctype html>
<html>
<body>
<?php /* @escapeNotVerified */ echo $layoutContent ?>
</body>
</html>
</code>```

Title: Make Magento render complete HTML page

Body:
I'm new to Magento

I get this template that I don't want to split into multiple blocks. I just want to render the page as it is (not only, but this is something I can try to understand later) when I go to some url.

So for example, going to /route/controller/action should display an html page I wrote from  to  (including, of course, HEAD and BODY).

So I read a few things. I followed some official tutorials and could create a module and an Action to render a JSON. Works fine! Going to /test/page/view shows a dumb json. Now I want to do something similar to render a page (and eventually pass parameters to it)

(http://devdocs.magento.com/videos/fundamentals/create-a-new-module/)

So this is what I get right now:

/Vendor/Module/etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="victor" frontName="test">
            <module name="Victor_Template" />
        </route>
    </router>
</config>

/Vendor/Module/Controller/Page/View.php

namespace Victor\Template\Controller\Page;

use \Magento\Backend\App\Action\Context;
use \Magento\Framework\App\Action\Action;
use \Magento\Framework\Controller\Result\JsonFactory;
use \Magento\Framework\View\Result\PageFactory;

class View extends Action
{
    protected $resultPageFactory;

    function __construct(Context $context, PageFactory $resultPageFactory){
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    public function execute(){
         return $this->resultPageFactory->create();
    }
}

.../view/frontend/layout/template_page_view.xml (maybe the error is here)

<?xml version="1.0" ?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <referenceContainer name="content">
            <block class="Victor\Template\Block\Page\View" name="page.view" template="Victor_Template::page/view.phtml"/>
        </referenceContainer>

</page>

.../view/frontend/templates/page/view.phtml

Hello World!

After cleaning cache, flushing cache, giving permissions and upgrading setup (something I have to do all the time some change occurs in the code), I get an HTTP code 200 that gives me back a blank (totally white) Magento page that contains references to css, javascript files and a weird  like this:

Anyway, I don't know what is happening in background. Something tells me the error is the definition of the layout (template_page_view)

I tried to use echo before the return in the execute() method in the View, but it didn't show up, exit also won't stop that magento black/white page to be rendered.

I wanted the response to be just
Hwllo World!
.

What am I doing wrong and what is the proper way of doing it on Magento??

@edit
alright there seems to be a lot of cache issues. Now echo and exit works. but I still don't get the the Hello world

Body:
It won't be easy but try this:

1) in your layout xml file (view/frontend/layout/template_page_view.xml):

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="empty" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="top.container" remove="true" />
        <referenceContainer name="top.container" remove="true" />
        <referenceContainer name="page.bottom.container" remove="true"/>
        <referenceContainer name="before.body.end" remove="true"/>
        <referenceContainer name="after.body.start" remove="true"/>
        <referenceContainer name="footer" remove="true" />
        <referenceContainer name="footer-container" remove="true" />
        <referenceContainer name="global.notices" remove="true" />

        <referenceContainer name="content">
            <block class="Victor\Template\Block\Page\View" name="page.view" template="Victor_Template::page/view.phtml"/>
        </referenceContainer>
    </body>
</page>

You probably will need to add more containers to remove depending on your theme and any additional 3rd party modules

2) in your controller create Page object like this:

return $this->resultPageFactory->create(false, ['template' => 'Vendrom_Module::blank.phtml']);

3) last create file ../view/frontend/blank.phtml

<!doctype html>
<html>
<body>
<?php /* @escapeNotVerified */ echo $layoutContent ?>
</body>
</html>


问:
Reversing order of divs depending on width
I'm currently working on a menu consisting of two parts (see image). On mobile, I'd like to show these menu items stacked from top to bottom, but starting with the bottom menu and ending with the top menu. Is there any (clean) way to do this with CSS or will I have to create two menus and show the correct one depending on page width?

EDIT: To clarify, the image is just to show an example of what I mean. I'm wondering in a more general sense if it's possible to somehow reverse the divs in CSS (without absolute positioning etc).

EDIT 2: Apologies for not adding any code. Here's a small pen that shows the situation: https://codepen.io/anon/pen/GWwrMW

```<code><div class="nav">
  <ul class="nav__top">
    <li>Sub Item 1</li>
    <li>Sub Item 2</li>
  </ul>
  <ul class="nav__primary">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>
</div>

.nav__top,
.nav__primary {
  list-style: none;
  margin: 0 0 20px 0;
  text-align: right;
  li {
    display: inline-block;
    padding: 10px;
    background-color: #ccc;
  }
}
</code>```

On mobile, I want the sub items to be displayed underneath the main items.

答:
Figured it out. Since I only need to support mobile browsers I can use Flexbox:</p>

```<code>.nav {
  display: flex;
  flex-direction: column-reverse;
}
</code>```

Body:
I'm currently working on a menu consisting of two parts (see image). On mobile, I'd like to show these menu items stacked from top to bottom, but starting with the bottom menu and ending with the top menu. Is there any (clean) way to do this with CSS or will I have to create two menus and show the correct one depending on page width?

EDIT: To clarify, the image is just to show an example of what I mean. I'm wondering in a more general sense if it's possible to somehow reverse the divs in CSS (without absolute positioning etc).

EDIT 2: Apologies for not adding any code. Here's a small pen that shows the situation: https://codepen.io/anon/pen/GWwrMW

Sub Item 1

Sub Item 2

Item 1

Item 2

Item 3

Item 4

.nav__top,
.nav__primary {
  list-style: none;
  margin: 0 0 20px 0;
  text-align: right;
  li {
    display: inline-block;
    padding: 10px;
    background-color: #ccc;
  }
}

On mobile, I want the sub items to be displayed underneath the main items.

Body:
Figured it out. Since I only need to support mobile browsers I can use Flexbox:

.nav {
  display: flex;
  flex-direction: column-reverse;
}


问:
How do I take a compressed file (through indexes) and re-create the original file? (Java)
Background of question

I have been developing some code that focuses on firstly, reading a string and creating a file. Secondly, spliting a string into an array. Then getting the indexes for each word in the array and finally, removing the duplicates and printing it to a different file.
I currently have made the code for this here is a link https://pastebin.com/gqWH0x0 (there is a menu system as well) but it is rather long so I have refrained from implementing it in this question.

The compression method is done via hashmaps, getting indexes of the array and mapping them to the relevant word. Here is an example:

Original: "sea sea see sea see see"

Output: see[2, 4, 5],sea[0, 1, 3],

Question

The next stage is getting the output back into the original state. I am currently relatively new to java so I am not aware of the techniques required. The code should be able to take the output file (shown above) and put it back into the original.

My current thinking is that you would just rewrite this hashmap (below). Would I be correct in thinking this? I thought I should check with stack overflow first!

```<code>Map<String, Set<Integer>> seaMap = new HashMap<>(); //new hashmap
                    for (int seaInt = 0; seaInt < sealist.length; seaInt++) {
                        if (seaMap.keySet().contains(sealist[seaInt])) {
                            Set<Integer> index = seaMap.get(sealist[seaInt]);
                            index.add(seaInt);
                        } else {
                            Set<Integer> index = new HashSet<>();
                            index.add(seaInt);
                            seaMap.put(sealist[seaInt], index);
                        }
                    }
                    System.out.print("Compressed: ");
                    seaMap.forEach((seawords, seavalues) -> System.out.print(seawords + seavalues + ","));
                    System.out.println("\n");
</code>```

If anyone has any good ideas / answers then please let me know, I am really desperate for a solution!

Link to current code: https://pastebin.com/gqWH0x0K

答:
first you will have to separate the words with index(es) from your compressed line, using your example:

```<code>"see[2, 4, 5],sea[0, 1, 3],"
</code>```

to obtain following Strings:

```<code>"see[2, 4, 5]" and "sea[0, 1, 3]"
</code>```

for each you must read the indexes, e.g. for first:

```<code>2, 4 and 5
</code>```

now just write the word in an ArrayList (or array) at the given index.

For the first two steps you can use a regular expression to find each word and the index list. Then use String.split and Integer.parseInt to get all indexes.

```<code>Pattern pattern = Pattern.compile("(.*?)\\[(.*?)\\],");
String line = "see[2, 4, 5],sea[0, 1, 3],";
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    String word = matcher.group(1);
    String[] indexes = matcher.group(2).split(", ");
    for (String str : indexes) {
        int index = Integer.parseInt(str);
</code>```

Now just check that the result List is big enough and set the word at the found indexes.

Body:
Background of question

I have been developing some code that focuses on firstly, reading a string and creating a file. Secondly, spliting a string into an array. Then getting the indexes for each word in the array and finally, removing the duplicates and printing it to a different file.
I currently have made the code for this here is a link https://pastebin.com/gqWH0x0 (there is a menu system as well) but it is rather long so I have refrained from implementing it in this question.

The compression method is done via hashmaps, getting indexes of the array and mapping them to the relevant word. Here is an example:

Original: "sea sea see sea see see"

Output: see[2, 4, 5],sea[0, 1, 3],

Question

The next stage is getting the output back into the original state. I am currently relatively new to java so I am not aware of the techniques required. The code should be able to take the output file (shown above) and put it back into the original.

My current thinking is that you would just rewrite this hashmap (below). Would I be correct in thinking this? I thought I should check with stack overflow first!

Map<String, Set<Integer>> seaMap = new HashMap<>(); //new hashmap
                    for (int seaInt = 0; seaInt < sealist.length; seaInt++) {
                        if (seaMap.keySet().contains(sealist[seaInt])) {
                            Set<Integer> index = seaMap.get(sealist[seaInt]);
                            index.add(seaInt);
                        } else {
                            Set<Integer> index = new HashSet<>();
                            index.add(seaInt);
                            seaMap.put(sealist[seaInt], index);
                        }
                    }
                    System.out.print("Compressed: ");
                    seaMap.forEach((seawords, seavalues) -> System.out.print(seawords + seavalues + ","));
                    System.out.println("\n");

If anyone has any good ideas / answers then please let me know, I am really desperate for a solution!

Link to current code: https://pastebin.com/gqWH0x0K

Body:
first you will have to separate the words with index(es) from your compressed line, using your example:

"see[2, 4, 5],sea[0, 1, 3],"

to obtain following Strings:

"see[2, 4, 5]" and "sea[0, 1, 3]"

for each you must read the indexes, e.g. for first:

2, 4 and 5

now just write the word in an ArrayList (or array) at the given index.

For the first two steps you can use a regular expression to find each word and the index list. Then use String.split and Integer.parseInt to get all indexes.

Pattern pattern = Pattern.compile("(.*?)\\[(.*?)\\],");
String line = "see[2, 4, 5],sea[0, 1, 3],";
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    String word = matcher.group(1);
    String[] indexes = matcher.group(2).split(", ");
    for (String str : indexes) {
        int index = Integer.parseInt(str);

Now just check that the result List is big enough and set the word at the found indexes.


问:
How to use jquery.hover() using jquery.bind()?
I am creating a table and replacing it in to a div in an aspx page. In that table I have four columns and in each columns i have a particular class. The content of div (ie table) will be changed using $ajax() everytime when a dropdownlist changes it value.I am getting the table and it will be coming inside the div.What i requires is I need to do jquery.hover() in that particular class.So how can i do by giving the class name. I have already tested $.('.ovr')bind(mouseover,mouseout).But this is also not works. Can u pls give a solution?

答:
to bind a "hover" event manually you have to bind the mouseenter and mouseleave events (jQuery's hover documentation mentions that hover actually binds mouseenter and mouseleave event handlers). Something like this should work:

```<code>$("...").bind("mouseenter mouseleave", function(e) {
    if (e.type == "mouseenter") {
        // hover in
    } else {
        // hover out
    }
});
</code>```

Hope this helps.

Body:
to bind a "hover" event manually you have to bind the mouseenter and mouseleave events (jQuery's hover documentation mentions that hover actually binds mouseenter and mouseleave event handlers). Something like this should work:

$("...").bind("mouseenter mouseleave", function(e) {
    if (e.type == "mouseenter") {
        // hover in
    } else {
        // hover out
    }
});

Hope this helps.


问:
How to style drop down list for Ajax / jQuery results
I'm using ajax and jquery UI to search and select in the input field. How can I style the drop down thing to not to show me
 bullets and also have a white background? I have been trying to target the search field using ID but it changes the input box and not the drop down box. I'm attaching the screenshot here.

答:
A css solution

change the list style type on you li tags to none. and add a white background to your ul tag

li {
  list-style-type: none
}

ul {
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Option</li>
  </ul</code>```

Body:
A css solution

change the list style type on you li tags to none. and add a white background to your ul tag

li {
  list-style-type: none
}

ul {
  background: white;
}

<ul>
  <li>Option</li>
  </ul


问:
speeding up php/mysql query/correct usage of joins?
I'm having some issues with some mysql queries taking around 50 seconds to execute some times, but other times its around 1 second. The query does what I need it do but obviously is too slow.

Below are the three tables that are used and showing some of the columns:

products Table (14315 rows)

```<code>id    | title  | image | price | rrp   | upsell
20381 | test   | test  | 24.00 | 30.00 | 1
</code>```

product_to_category Table (26283 rows)

```<code>ptc_id | product_id | category_id
33797  | 20381      | 29
</code>```

category_description Table (29 rows)

```<code>category_id | name     | url_slug
29          | Kitchens | kitchen-products
</code>```

seo_slugs Table (14898 rows)

```<code>seo_slug_id | route         | seo_slug
26987       | product=20381 | test-product-kitchen-area-2000-500
</code>```

Below is the current codeigniter functions I am using.

```<code>public function getUpsells() {
$this->db->select('products.id, products.title, products.image, products.category, products.price, products.rrp', FALSE);
$this->db->from('product_to_category');
$this->db->join('products', 'products.id = product_to_category.product_id');
$this->db->join('category_description', 'category_description.category_id = product_to_category.category_id');
$this->db->join('seo_slugs', 'seo_slugs.route = concat(\'product=\', product_to_category.product_id)');
$this->db->where('products.upsell',1);
$this->db->where('products.status',1);
$this->db->group_by('product_to_category.product_id');
$query = $this->db->get();
return $query->result();
</code>```

}
I'm hoping someone can point me in the right direction and advise where I'm going wrong. It is to be honest the first time i've used joins in a query and although it seems to work, it is generally very slow when first loading the page, then if refreshed etc it seems to load fairly quick.

Below is the query it runs:

```<code>SELECT products.id, products.title, products.image, products.category, products.price, products.rrp
FROM `product_to_category`
JOIN `products` ON `products`.`id` = `product_to_category`.`product_id`
JOIN `category_description` ON `category_description`.`category_id` = `product_to_category`.`category_id`
JOIN `seo_slugs` ON `seo_slugs`.`route` = concat('product=', product_to_category.product_id)
WHERE `products`.`upsell` = 1
AND `products`.`status` = 1
GROUP BY `product_to_category`.`product_id`
</code>```

Profiling result:

```<code>Starting    18 µs
Waiting For Query Cache Lock    5 µs
Checking Query Cache For Query  48 µs
Checking Permissions    5 µs
Checking Permissions    4 µs
Checking Permissions    4 µs
Checking Permissions    5 µs
Opening Tables  20 µs
System Lock 9 µs
Waiting For Query Cache Lock    15 µs
Init    25 µs
Optimizing  13 µs
Statistics  23 µs
Preparing   19 µs
Creating Tmp Table  21 µs
Executing   5 µs
Copying To Tmp Table    51.8 s
Sorting Result  26 µs
Sending Data    24 µs
End 9 µs
Removing Tmp Table  33 µs
End 7 µs
Query End   7 µs
Closing Tables  14 µs
Freeing Items   12 µs
Waiting For Query Cache Lock    6 µs
Freeing Items   11 µs
Waiting For Query Cache Lock    7 µs
Freeing Items   7 µs
Storing Result In Query Cache   162 µs
Logging Slow Query  6 µs
Logging Slow Query  38 µs
Cleaning Up 7 µs
</code>```

EXPLAIN Result:

```+----+-------------+----------------------+--------+---------------+---------+---------+-----------------------------------------------------+-------+---------------------------------+
| id | select_type |        table         |  type  | possible_keys |   key   | key_len |                         ref                         | rows  |              Extra              |
+----+-------------+----------------------+--------+---------------+---------+---------+-----------------------------------------------------+-------+---------------------------------+
|  1 | SIMPLE      | seo_slugs            | ALL    | NULL          | NULL    | NULL    | NULL                                                | 14958 | Using temporary; Using filesort |
|  1 | SIMPLE      | product_to_category  | ALL    | category_id   | NULL    | NULL    | NULL                                                | 26343 | Using where; Using join buffer  |
|  1 | SIMPLE      | category_description | eq_ref | PRIMARY       | PRIMARY | 4       | wilsonar_hcsupplies.product_to_category.category_id |     1 | Using index                     |
|  1 | SIMPLE      | products             | eq_ref | PRIMARY,id    | PRIMARY | 4       | wilsonar_hcsupplies.product_to_category.product_id  |     1 | Using where                     |
+----+-------------+----------------------+--------+---------------+---------+---------+-----------------------------------------------------+-------+---------------------------------+
```

答:
(I have yet to see a useful "Profile".)

Even without seeing the table structure of product_to_category, I suspect it is the deficient part.

Get rid if ptc_id

Change to PRIMARY KEY(product_id, category_id)

Also have INDEX(category_id, product_id)

Further discussion of the optimal many:many mapping table.

Also, have INDEX(upsell, status).  This composite index may or may not be used, depending on the cardinality of those columns.  If useful, it will be quite beneficial.  If not, then a table scan is necessary.

And get rid of the last two join()s -- you don't use those table.  MySQL is joining to the to make sure they exist, but wasting time in doing so.

Once you get rid of the two unnecessary tables, you can get rid of the GROUP BY.

But, then why touch categories at all?  Getting rid of that, gets rid of products_to_categories.

So this is all you needed is the above index, plus

```<code>SELECT id, title, image, category, price, rrp
FROM `products`
WHERE `upsell` = 1
  AND `status` = 1
</code>```

But, wait!  That won't work because there is not a products.category.

Why sometimes fast?  You have the "Query cache" turned on.  When you run the identical query a second time before any changes to any of the relevant tables, it will be fetched from the QC, usually in a millisecond or so.

Body:
I'm having some issues with some mysql queries taking around 50 seconds to execute some times, but other times its around 1 second. The query does what I need it do but obviously is too slow.

Below are the three tables that are used and showing some of the columns:

products Table (14315 rows)

id    | title  | image | price | rrp   | upsell
20381 | test   | test  | 24.00 | 30.00 | 1

product_to_category Table (26283 rows)

ptc_id | product_id | category_id
33797  | 20381      | 29

category_description Table (29 rows)

category_id | name     | url_slug
29          | Kitchens | kitchen-products

seo_slugs Table (14898 rows)

seo_slug_id | route         | seo_slug
26987       | product=20381 | test-product-kitchen-area-2000-500

Below is the current codeigniter functions I am using.

public function getUpsells() {
$this->db->select('products.id, products.title, products.image, products.category, products.price, products.rrp', FALSE);
$this->db->from('product_to_category');
$this->db->join('products', 'products.id = product_to_category.product_id');
$this->db->join('category_description', 'category_description.category_id = product_to_category.category_id');
$this->db->join('seo_slugs', 'seo_slugs.route = concat(\'product=\', product_to_category.product_id)');
$this->db->where('products.upsell',1);
$this->db->where('products.status',1);
$this->db->group_by('product_to_category.product_id');
$query = $this->db->get();
return $query->result();

}
I'm hoping someone can point me in the right direction and advise where I'm going wrong. It is to be honest the first time i've used joins in a query and although it seems to work, it is generally very slow when first loading the page, then if refreshed etc it seems to load fairly quick.

Below is the query it runs:

SELECT products.id, products.title, products.image, products.category, products.price, products.rrp
FROM `product_to_category`
JOIN `products` ON `products`.`id` = `product_to_category`.`product_id`
JOIN `category_description` ON `category_description`.`category_id` = `product_to_category`.`category_id`
JOIN `seo_slugs` ON `seo_slugs`.`route` = concat('product=', product_to_category.product_id)
WHERE `products`.`upsell` = 1
AND `products`.`status` = 1
GROUP BY `product_to_category`.`product_id`

Profiling result:

Starting    18 µs
Waiting For Query Cache Lock    5 µs
Checking Query Cache For Query  48 µs
Checking Permissions    5 µs
Checking Permissions    4 µs
Checking Permissions    4 µs
Checking Permissions    5 µs
Opening Tables  20 µs
System Lock 9 µs
Waiting For Query Cache Lock    15 µs
Init    25 µs
Optimizing  13 µs
Statistics  23 µs
Preparing   19 µs
Creating Tmp Table  21 µs
Executing   5 µs
Copying To Tmp Table    51.8 s
Sorting Result  26 µs
Sending Data    24 µs
End 9 µs
Removing Tmp Table  33 µs
End 7 µs
Query End   7 µs
Closing Tables  14 µs
Freeing Items   12 µs
Waiting For Query Cache Lock    6 µs
Freeing Items   11 µs
Waiting For Query Cache Lock    7 µs
Freeing Items   7 µs
Storing Result In Query Cache   162 µs
Logging Slow Query  6 µs
Logging Slow Query  38 µs
Cleaning Up 7 µs

EXPLAIN Result:

+----+-------------+----------------------+--------+---------------+---------+---------+-----------------------------------------------------+-------+---------------------------------+
| id | select_type |        table         |  type  | possible_keys |   key   | key_len |                         ref                         | rows  |              Extra              |
+----+-------------+----------------------+--------+---------------+---------+---------+-----------------------------------------------------+-------+---------------------------------+
|  1 | SIMPLE      | seo_slugs            | ALL    | NULL          | NULL    | NULL    | NULL                                                | 14958 | Using temporary; Using filesort |
|  1 | SIMPLE      | product_to_category  | ALL    | category_id   | NULL    | NULL    | NULL                                                | 26343 | Using where; Using join buffer  |
|  1 | SIMPLE      | category_description | eq_ref | PRIMARY       | PRIMARY | 4       | wilsonar_hcsupplies.product_to_category.category_id |     1 | Using index                     |
|  1 | SIMPLE      | products             | eq_ref | PRIMARY,id    | PRIMARY | 4       | wilsonar_hcsupplies.product_to_category.product_id  |     1 | Using where                     |
+----+-------------+----------------------+--------+---------------+---------+---------+-----------------------------------------------------+-------+---------------------------------+

Body:
(I have yet to see a useful "Profile".)

Even without seeing the table structure of product_to_category, I suspect it is the deficient part.

Get rid if ptc_id

Change to PRIMARY KEY(product_id, category_id)

Also have INDEX(category_id, product_id)

Further discussion of the optimal many:many mapping table.

Also, have INDEX(upsell, status).  This composite index may or may not be used, depending on the cardinality of those columns.  If useful, it will be quite beneficial.  If not, then a table scan is necessary.

And get rid of the last two join()s -- you don't use those table.  MySQL is joining to the to make sure they exist, but wasting time in doing so.

Once you get rid of the two unnecessary tables, you can get rid of the GROUP BY.

But, then why touch categories at all?  Getting rid of that, gets rid of products_to_categories.

So this is all you needed is the above index, plus

SELECT id, title, image, category, price, rrp
FROM `products`
WHERE `upsell` = 1
  AND `status` = 1

But, wait!  That won't work because there is not a products.category.

Why sometimes fast?  You have the "Query cache" turned on.  When you run the identical query a second time before any changes to any of the relevant tables, it will be fetched from the QC, usually in a millisecond or so.


问:
Accessing session object during Unit test of Flask application
I know it is possible to create session object using session_transaction() method. However, is there a way to access the current session object which gets created when for example "/" route gets hit? I did from flask import session to access the session but it's empty. Let me know if it is possible. Thanks.

答:
This is what you're looking for. As it says however, you'd have to use the instantiation you create in your with statement.

```<code>with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['a_key'] = 'a value'

    # once this is reached the session was stored
    result = app.test_client.get('/a_url')
    # NOT part of the 2nd context
</code>```

Note that this won't work if you run your test within the scope of the with c.session_transaction() as sess statement, it needs to be run after that block.

Body:
This is what you're looking for. As it says however, you'd have to use the instantiation you create in your with statement.

with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['a_key'] = 'a value'

    # once this is reached the session was stored
    result = app.test_client.get('/a_url')
    # NOT part of the 2nd context

Note that this won't work if you run your test within the scope of the with c.session_transaction() as sess statement, it needs to be run after that block.

ContentLicense: CC BY-SA 4.0


问:
Prevent files in src/main/app being embedded in the Mule .zip
It's mostly in the title; I'm trying to embed a SPA webapplication (some html and js) in src/main/app and let Mule serve it trough a static handler.

Though I'd only like the minified javascript to be served which I place (using webpack) in the /src/main/app/webapp/build directory. I'd like to exclude the /src/main/app/webapp/project directory from the Mule zip after a Maven 'package'. The /project/ directory has thousands of files for the webapp potentially.

I think I tried all of the Maven guides to exclude files out there but can't get it to work:

```<code>    <resource>
        <directory>src/main/app</directory>
        <excludes>
            <exclude>webapp/project/**</exclude>
        </excludes>
    </resource>
</code>```

Any ideas?

答: I would try to move those files from /src/main/app to /src/main/resources. As the src/main/app folder is going to be loaded in the classpath when using the maven plugin to package your mule app</p>

Body:
It's mostly in the title; I'm trying to embed a SPA webapplication (some html and js) in src/main/app and let Mule serve it trough a static handler.

Though I'd only like the minified javascript to be served which I place (using webpack) in the /src/main/app/webapp/build directory. I'd like to exclude the /src/main/app/webapp/project directory from the Mule zip after a Maven 'package'. The /project/ directory has thousands of files for the webapp potentially.

I think I tried all of the Maven guides to exclude files out there but can't get it to work:

    <resource>
        <directory>src/main/app</directory>
        <excludes>
            <exclude>webapp/project/**</exclude>
        </excludes>
    </resource>

Any ideas?


问:
Python 2.7 : store the variable value permanently even when I run the session next time
Scenario: python code which checks the number of visitors entered through a gate.
depending on that number I build the next job.

EDIT 1 :

#

file1 :(
First Run
this file counts the number of visitors that are arriving default is 3 in my case. Now i execute the file and I found that visitors arrived are 4 . Now and export the same to file2 and print the visitor count as 4 at the same time the visitors value is changed to 4 now in file1.

Now the second run:

Now in file1 the visitors value is 4 and it is checking if visitors > 4 , now if the count is 4 then i export the same to file2 if count is 5 now then i export the same to file2 and retain the value as 5 **count of visitors completely depends on the URL) ####

```<code>datasource = "www.PPrestraunt.com/personsentered"
data = len(datasource) #gives me the live value of the number of persons entered
if(visitors > 3):
   bottles = data
   visitors = bottles
   print bottles
else:
   visitors = 3
</code>```

this above code is imported to a another file which has the working

file2:

```<code>from file1 import visitors
number_of_bottles = visitors
print number_of_bottles
</code>```

I have setup the same in jenkins job so it builds every 5 mins.
In the above code the value of visitors is not changing every time I am running the code value remains 3 even though the number is increased to 4.

expected case: If value is more than 3 value should be retained in next session too and the if condition should now check for the new value ex: (if(visitors > 4)

any help is appreciated.

答:
Like what @juanpa wrote.

Here is a small program that increments a counter, you can tailor it to your code

```<code>import os
data_file = "lower_bound.txt"
is_file_empty = (os.path.isfile(data_file)==False) or (os.stat(data_file).st_size == 0)
if (is_file_empty):
    with open(data_file,"w") as f:
        f.write("3");

datasource = "www.PPrestraunt.com/personsentered"
data = len(datasource) #gives me the live value of the number of persons entered
lower_bound = 0;
with open(data_file,"r") as f:
    lower_bound = int(f.read());

if (visitors>lower_bound):
    bottles = data
    visitors = bottles
    print bottles
    // @Alex either lower_bound+=1; or lower_bound = visitors not sure what you want
else:
    visitors = lower_bound;
with open(data_file,"w") as f:
    f.write(str(lower_bound));
print lower_bound,"is the new minimum and",visitors,"is the current visitor count";
</code>```

Body:
Scenario: python code which checks the number of visitors entered through a gate.
depending on that number I build the next job.

EDIT 1 :

#

file1 :(
First Run
this file counts the number of visitors that are arriving default is 3 in my case. Now i execute the file and I found that visitors arrived are 4 . Now and export the same to file2 and print the visitor count as 4 at the same time the visitors value is changed to 4 now in file1.

Now the second run:

Now in file1 the visitors value is 4 and it is checking if visitors > 4 , now if the count is 4 then i export the same to file2 if count is 5 now then i export the same to file2 and retain the value as 5 **count of visitors completely depends on the URL) ####

datasource = "www.PPrestraunt.com/personsentered"
data = len(datasource) #gives me the live value of the number of persons entered
if(visitors > 3):
   bottles = data
   visitors = bottles
   print bottles
else:
   visitors = 3

this above code is imported to a another file which has the working

file2:

from file1 import visitors
number_of_bottles = visitors
print number_of_bottles

I have setup the same in jenkins job so it builds every 5 mins.
In the above code the value of visitors is not changing every time I am running the code value remains 3 even though the number is increased to 4.

expected case: If value is more than 3 value should be retained in next session too and the if condition should now check for the new value ex: (if(visitors > 4)

any help is appreciated.

Body:
Like what @juanpa wrote.

Here is a small program that increments a counter, you can tailor it to your code

import os
data_file = "lower_bound.txt"
is_file_empty = (os.path.isfile(data_file)==False) or (os.stat(data_file).st_size == 0)
if (is_file_empty):
    with open(data_file,"w") as f:
        f.write("3");

datasource = "www.PPrestraunt.com/personsentered"
data = len(datasource) #gives me the live value of the number of persons entered
lower_bound = 0;
with open(data_file,"r") as f:
    lower_bound = int(f.read());

if (visitors>lower_bound):
    bottles = data
    visitors = bottles
    print bottles
    // @Alex either lower_bound+=1; or lower_bound = visitors not sure what you want
else:
    visitors = lower_bound;
with open(data_file,"w") as f:
    f.write(str(lower_bound));
print lower_bound,"is the new minimum and",visitors,"is the current visitor count";


问:
Xamarin.Forms DisplayAlert - duplicated title in Android
I'm trying to display an alert in my Xamarin.Forms project using the following code:

```<code>DisplayAlert("¡Oops!", "Nos es imposible ubicarte, intenta ubicarte manualmente", "Ok");
</code>```

In iOS it works all OK, but in the Android emulator I see a duplicated title. Please see the below image

Is this behavior normal? Thanks in advance.

答:
Oops :D!

My bad. I'm using the Grial UI Kit for Xamarin.Forms... hence here's the solution:

https://github.com/UXDivers/Grial-UI-Kit-Support/issues/75

Body:
I'm trying to display an alert in my Xamarin.Forms project using the following code:

DisplayAlert("¡Oops!", "Nos es imposible ubicarte, intenta ubicarte manualmente", "Ok");

In iOS it works all OK, but in the Android emulator I see a duplicated title. Please see the below image

Is this behavior normal? Thanks in advance.


问:
MS Access Input Mask for Postcode
Is there a way to set an input mask in MS Access 2007 so that certain elements are optional? UK postcodes can be in a number of formats: LL00 0LL or L00 0LL or even LL00 L00LL. For this particular assignment, I need only worry about the first two formats.

So, is there a way for me to set the input mask so that the first letter is optional?

答:
Don't bother.  Just use a text field and let the users insert the blanks.   Put some code in checking for approriate alphabetic vs numeric characters.

The advntage is this approach will work for any country.

Title: MS Access Input Mask for Postcode


问:
How to use generics to return child type from a parent method to support builder pattern
I am trying to support a builder pattern with inheritance, to allow chaining setters from parent and child class with no issue. For this I need the parent class to know to return back the child type to keep all methods exposed for chaining.

Here is a sample of code I wrote following this article which I think should work, But as you'll see, the first example using a1 works fine, but if I change the order of the setters, the last setter is not recognized.

Problem is: once I call a method from the parent class, it will return itself as a type and not the child, even thought T is defined as the child type.

```<code>public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        A a1 = new B<>().setAge(0).setId(0).setName("name"); //Works fine
        A a2 = new B<>().setAge(0).setName("name").setId(0); //setId is not found

    }

    static class A<T extends A> {
        private String mpName;

        T setName(String name) {
            mpName = name;
            return (T) this;
        }
    }

    static class B<T extends B> extends A<T> {
        private int mpAge;
        private int mpId;

        T setAge(int age) {
            mpAge = age;
            return (T) this;
        }

        T setId(int id) {
            mpId = id;
            return (T) this;
        }
    }
}
</code>```

答:
Do we need parameterized types on the child class?</p>

```<code>class Class {

  public static void main(String[] args) {

    new Child().setAge(0).setId(0).setName("name");
    new Child().setAge(0).setName("name").setId(0);

  }

  static class Parent<C extends Parent> {
    private String mpName;

    C setName(String name) {
      mpName = name;
      return (C) this;
    }
  }

  static class Child extends Parent<Child> {
    private int mpAge;
    private int mpId;

    Child setAge(int age) {
      mpAge = age;
      return this;
    }

    Child setId(int id) {
      mpId = id;
      return this;
    }
  }
}
</code>```

Body:
I am trying to support a builder pattern with inheritance, to allow chaining setters from parent and child class with no issue. For this I need the parent class to know to return back the child type to keep all methods exposed for chaining.

Here is a sample of code I wrote following this article which I think should work, But as you'll see, the first example using a1 works fine, but if I change the order of the setters, the last setter is not recognized.

Problem is: once I call a method from the parent class, it will return itself as a type and not the child, even thought T is defined as the child type.

public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        A a1 = new B<>().setAge(0).setId(0).setName("name"); //Works fine
        A a2 = new B<>().setAge(0).setName("name").setId(0); //setId is not found

    }

    static class A<T extends A> {
        private String mpName;

        T setName(String name) {
            mpName = name;
            return (T) this;
        }
    }

    static class B<T extends B> extends A<T> {
        private int mpAge;
        private int mpId;

        T setAge(int age) {
            mpAge = age;
            return (T) this;
        }

        T setId(int id) {
            mpId = id;
            return (T) this;
        }
    }
}

Body:
Do we need parameterized types on the child class?

class Class {

  public static void main(String[] args) {

    new Child().setAge(0).setId(0).setName("name");
    new Child().setAge(0).setName("name").setId(0);

  }

  static class Parent<C extends Parent> {
    private String mpName;

    C setName(String name) {
      mpName = name;
      return (C) this;
    }
  }

  static class Child extends Parent<Child> {
    private int mpAge;
    private int mpId;

    Child setAge(int age) {
      mpAge = age;
      return this;
    }

    Child setId(int id) {
      mpId = id;
      return this;
    }
  }
}


问:
Add Playground to a Storyboard project: Could not find a storyboard ... in bundle NSBundle
I have a working iOS project with Storyboards. Then I added a playground file to it with following content:

The

```<code>import UIKit
import PlaygroundSupport
import SpriteKit

var str = "Hello, playground"
let gameViewController = GameViewController.loadFromStoryboard() // <<<<- Fails
PlaygroundPage.current.liveView = gameViewController
</code>```

I am getting following error at line, where I loadFromStoryboard():

```<code>NSInvalidArgumentException', reason: 'Could not find a storyboard named 'Main' in bundle NSBundle
</code>```

What should I fix?
There are tonnes of questions on stackoverflow with the above title/contents however, each has a very specific scenario. I have gone through many of them over past few days and I think that my scenario is distinct due to use of Playground hence I am posting again.

答:
If this is in an existing project, you can instantiate the storyboard by using your full bundle identifier, as demonstrated here:

```<code>let myBundle = Bundle(identifier: "com.asad.MyProgram")
let storyboard = UIStoryboard(name: "MyStoryboard", bundle: myBundle)
</code>```

Please note that this does require that the playground is in the same workspace as the project with that particular bundle identifier.

Body:
I have a working iOS project with Storyboards. Then I added a playground file to it with following content:

The

import UIKit
import PlaygroundSupport
import SpriteKit

var str = "Hello, playground"
let gameViewController = GameViewController.loadFromStoryboard() // <<<<- Fails
PlaygroundPage.current.liveView = gameViewController

I am getting following error at line, where I loadFromStoryboard():

NSInvalidArgumentException', reason: 'Could not find a storyboard named 'Main' in bundle NSBundle

What should I fix?
There are tonnes of questions on stackoverflow with the above title/contents however, each has a very specific scenario. I have gone through many of them over past few days and I think that my scenario is distinct due to use of Playground hence I am posting again.

Body:
If this is in an existing project, you can instantiate the storyboard by using your full bundle identifier, as demonstrated here:

let myBundle = Bundle(identifier: "com.asad.MyProgram")
let storyboard = UIStoryboard(name: "MyStoryboard", bundle: myBundle)

Please note that this does require that the playground is in the same workspace as the project with that particular bundle identifier.


问:
ggplot fitted distributions aren't quite level with the x axis
I am trying to model output data from the "mixtools" package in a similar manner to how jhoward did here with minor changes.  The examples provided work as expected and his solution works with my data, however the fitted distributions seem...tilted.

Notice how both distributions are angled above the x axis slightly.

Using an artificial dataset doesn't show the problem anymore.

```<code>`sample.ratio`=c(rnorm(120000,0.386,0.0842),rnorm(200000,0.653,0.1153))
`mixmdl_k2.sample`=normalmixEM(`sample.ratio`, k=2)

ggplot_mixEM <- function(EM) {
  require(ggplot2)
  x       <- with(EM,seq(min(x),max(x),len=1000))
  pars    <- with(EM,data.frame(comp=colnames(posterior), mu, sigma,lambda))
  em.df   <- data.frame(x=rep(x,each=nrow(pars)),pars)
  em.df$y <- with(em.df,lambda*dnorm(x,mean=mu,sd=sigma))
  ggplot(data.frame(x=EM$x),aes(x,y=..density..)) +
    geom_histogram(fill=NA,color="black")+
    geom_polygon(data=em.df,aes(x,y,fill=comp),color="grey50", alpha=0.5)+
    scale_fill_discrete("Component\nModes",labels=format(em.df$mu,digits=3))+
    geom_density(color="red",linetype="dotted")
}
ggplot_mixEM(`mixmdl_k2.sample`)
</code>```

.  The distribution fills are now level, though they are also no longer constrained to the (0,1) interval.

About my data: it ranges explicitly from 0-1, and the bimodal distribution modeled by mixtools is expected.  Increasing the x scale with scale_x_continuous(limits=c(-0.1,1.1)) didn't solve the issue.  The first solution from the link above, provided by Spacedman, also worked on my data, but gave the same "tilted plot" results.

Does anyone know why this is happening and how to fix this tilt? Is there a way to force extend the shading to the x axis?

Thank you.

Edit: added in sample code.

答:
Changing the line

x       <- with(EM,seq(min(x),max(x),len=1000))

to

```<code>x       <- with(EM,seq(min(x),max(1.1),len=1000))
</code>```

Seems to have fixed it.

Body:
I am trying to model output data from the "mixtools" package in a similar manner to how jhoward did here with minor changes.  The examples provided work as expected and his solution works with my data, however the fitted distributions seem...tilted.

Notice how both distributions are angled above the x axis slightly.

Using an artificial dataset doesn't show the problem anymore.

`sample.ratio`=c(rnorm(120000,0.386,0.0842),rnorm(200000,0.653,0.1153))
`mixmdl_k2.sample`=normalmixEM(`sample.ratio`, k=2)

ggplot_mixEM <- function(EM) {
  require(ggplot2)
  x       <- with(EM,seq(min(x),max(x),len=1000))
  pars    <- with(EM,data.frame(comp=colnames(posterior), mu, sigma,lambda))
  em.df   <- data.frame(x=rep(x,each=nrow(pars)),pars)
  em.df$y <- with(em.df,lambda*dnorm(x,mean=mu,sd=sigma))
  ggplot(data.frame(x=EM$x),aes(x,y=..density..)) +
    geom_histogram(fill=NA,color="black")+
    geom_polygon(data=em.df,aes(x,y,fill=comp),color="grey50", alpha=0.5)+
    scale_fill_discrete("Component\nModes",labels=format(em.df$mu,digits=3))+
    geom_density(color="red",linetype="dotted")
}
ggplot_mixEM(`mixmdl_k2.sample`)

.  The distribution fills are now level, though they are also no longer constrained to the (0,1) interval.

About my data: it ranges explicitly from 0-1, and the bimodal distribution modeled by mixtools is expected.  Increasing the x scale with scale_x_continuous(limits=c(-0.1,1.1)) didn't solve the issue.  The first solution from the link above, provided by Spacedman, also worked on my data, but gave the same "tilted plot" results.

Does anyone know why this is happening and how to fix this tilt? Is there a way to force extend the shading to the x axis?

Thank you.

Edit: added in sample code.

Body:
Changing the line

x       <- with(EM,seq(min(x),max(x),len=1000))

to

x       <- with(EM,seq(min(x),max(1.1),len=1000))

Seems to have fixed it.


问:
how to show dialog only once
Hi i'm trying to create dialog contains two buttons [ GOT IT ! ] and [ DON'T SHOW ME THIS AGAIN ] i want when i click [ DON'T SHOW ME THIS AGAIN ] button dialog Completely closed And do not show again at application Reopen

```<code>public boolean Show = false;

public void IntroSupport(){

    Show = true;

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    ImageView image = new ImageView(this);
    image.setImageResource(R.mipmap.ic_launcher);
    builder.setIcon(R.mipmap.service)
            .setTitle("Online Support :")
            .setView(image)
            .setMessage("Some text")
            .setNegativeButton("GOT it!",null)
            .setPositiveButton("Don't Show Me this Again", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
    builder.setCancelable(false);
    AlertDialog about = builder.create();
    about.show();
    TextView messageText = (TextView) about.findViewById(android.R.id.message);
    messageText.setGravity(Gravity.CENTER);
    Button nbutton = about.getButton(DialogInterface.BUTTON_NEGATIVE);
    nbutton.setTextColor(Color.BLACK);
}

        @Override
        public void onPageSelected(int position) {
            switch (position){
                case 0:
          getSupportActionBar().setTitle(Html.fromHtml("title :"+Pb));
                    tabLayout.getTabAt(0).setIcon(R.mipmap.ic1vrai);
                    tabLayout.getTabAt(1).setIcon(R.mipmap.ic__2vrai);
                    break;
                case 1:

                    if(Show == false){
                        IntroSupport();
                    }

                    getSupportActionBar().setTitle(Html.fromHtml("("titl"+sus));
                    tabLayout.getTabAt(1).setIcon(R.mipmap.ic_2faux);
                    tabLayout.getTabAt(0).setIcon(R.mipmap.ic1faux);
                    break;
            }
        }
</code>```

答:
You can store a value to the SharedPreferences if the user press on the Don't show me this again button. Then you should wrap your dialog stuff in an if clause which checks if the value in the SharedPreferences is set or not.

Here is the link to the documentation of the SharedPreferences: https://developer.android.com/reference/android/content/SharedPreferences.html

Title: how to show dialog only once

Body:
Hi i'm trying to create dialog contains two buttons [ GOT IT ! ] and [ DON'T SHOW ME THIS AGAIN ] i want when i click [ DON'T SHOW ME THIS AGAIN ] button dialog Completely closed And do not show again at application Reopen

public boolean Show = false;

public void IntroSupport(){

    Show = true;

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    ImageView image = new ImageView(this);
    image.setImageResource(R.mipmap.ic_launcher);
    builder.setIcon(R.mipmap.service)
            .setTitle("Online Support :")
            .setView(image)
            .setMessage("Some text")
            .setNegativeButton("GOT it!",null)
            .setPositiveButton("Don't Show Me this Again", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
    builder.setCancelable(false);
    AlertDialog about = builder.create();
    about.show();
    TextView messageText = (TextView) about.findViewById(android.R.id.message);
    messageText.setGravity(Gravity.CENTER);
    Button nbutton = about.getButton(DialogInterface.BUTTON_NEGATIVE);
    nbutton.setTextColor(Color.BLACK);
}

        @Override
        public void onPageSelected(int position) {
            switch (position){
                case 0:
          getSupportActionBar().setTitle(Html.fromHtml("title :"+Pb));
                    tabLayout.getTabAt(0).setIcon(R.mipmap.ic1vrai);
                    tabLayout.getTabAt(1).setIcon(R.mipmap.ic__2vrai);
                    break;
                case 1:

                    if(Show == false){
                        IntroSupport();
                    }

                    getSupportActionBar().setTitle(Html.fromHtml("("titl"+sus));
                    tabLayout.getTabAt(1).setIcon(R.mipmap.ic_2faux);
                    tabLayout.getTabAt(0).setIcon(R.mipmap.ic1faux);
                    break;
            }
        }


问:
Process Uploaded file on web server without storing locally first?
I am trying to process the user uploaded file real time on the websever,
but it seems, APACHE invokes PHP, only once complete file is uploaded.

When i uploaded the file using CURL, and set

Transfer-Encoding : "Chunked"

I had some success, but can't do same thing via browser.

I used Dropzone.js but when i tried to set same header, it said Transfer -Encoding is an unsafe header, hence not setting it.

This answer explains what is the issue there.
Can't set Transfer-Encoding :"Chunked from Browser"

In a Nutshell problem is , when a user uploads the file to webserver, i want webserver to start processing it as soon as first byte is available.
by process i mean, PIPING it to a Named Pipe.

Dont want 500mb first getting uploaded to a server, then start processing it.

But with current Webserver (APACHE - PHP), I cant seem to be able to accomplish it.

could someone please explain, what technology stack or workarounds to use, so that i can upload the large file via browser and start processing it, as soon as first byte is available.

答:
you can upload file with html5 resumable upload tools (like Resumable.js) and process uploaded parts as soon as they received.

or as a workaround , you may find the path of uploaded file (usually in /tmp) and then write a background job to stream it to 3rd app. it may be harder.

there may be other solutions...


问:
Is it possible to pull all messages contained in an Azure Servicebus Topic into an app?
The only method I see to pull messages from a topic is SubscriptionClient.OnMessage(), which seems to only trigger if the topic receives a new message.

Queues have the QueueClient.Receive() method for this purpose, but topics don't seem to have this capability.

Am I missing something?

答:
Messages cannot be received from a topic, only sent to. Topic is used in conjunctions with subscriptions to receive messages.

Queues and subscriptions support OnMessage API. This, though, won't give you all the messages, but instead will give one message at a time X the concurrency level you'll set with OnMessageOptions.

An alternative approach would be to receive batches (see ReceiveBatchAsync(Int32, TimeSpan)). This will allow you handle more than one message if that's what you need.


问:
Sum in an ArrayList with HashMap or with other method
I can't figure it out.

```<code>List<String[]> dogList = new ArrayList<String[]>();

dogList.add(new String[] { "id_tag", "breed", "rank", "nickname"});
dogList.add(new String[] { "t4639", "Akita", "First", "Marshal"});
dogList.add(new String[] { "t4638", "Akita", "First", "Tom"});
dogList.add(new String[] { "t4637", "Beagle", "First", "Eddy"});
dogList.add(new String[] { "t4636", "Beagle", "Second", "Franky"});
</code>```

I would like to put in an other ArrayList sum by breed and rank

```<code>List<String[]> dogTotal = new ArrayList<String[]>();
</code>```

To get an output like this if i iterate over dogTotal

```<code>"Akita", "First", "2"
"Beagle", "First", "1"
"Beagle", "Second", "1"
</code>```

I have tried to use HashMap without success.

答:
Hey what you can do is use <breed>_<rank> as key for maintaining the counts for the HashMap. When done with counting just iterate the hash map and split the key using _ as delimiter to get back breed and rank along with count value from value.

```<code>    List<String[]> dogList = new ArrayList<String[]>();
    dogList.add(new String[] { "id_tag", "breed", "rank", "nickname"});
    dogList.add(new String[] { "t4639", "Akita", "First", "Marshal"});
    dogList.add(new String[] { "t4638", "Akita", "First", "Tom"});
    dogList.add(new String[] { "t4637", "Beagle", "First", "Eddy"});
    dogList.add(new String[] { "t4636", "Beagle", "Second", "Franky"});
    List<String[]> dogTotal = new ArrayList<String[]>();
    HashMap<String,Integer> map = new HashMap<>();
    for(int i=1;i<dogList.size();i++){
        String key = dogList.get(i)[1]+"_"+dogList.get(i)[2];

        map.put(key,map.get(key)==null?1:map.get(key)+1);
    }
    for(Map.Entry<String,Integer> entry : map.entrySet()){
        String key = entry.getKey();
        String breedRank[] = new String[3];
        String getBackValues[] = key.split("_");
        breedRank[0] = getBackValues[0];
        breedRank[1] = getBackValues[1];
        breedRank[2] = String.valueOf(entry.getValue());
        System.out.println(breedRank[0]+ ", " + breedRank[1]+","+ breedRank[2]);
        dogTotal.add(breedRank);
    }
    System.out.println(dogTotal);
</code>```

Body:
I can't figure it out.

List<String[]> dogList = new ArrayList<String[]>();

dogList.add(new String[] { "id_tag", "breed", "rank", "nickname"});
dogList.add(new String[] { "t4639", "Akita", "First", "Marshal"});
dogList.add(new String[] { "t4638", "Akita", "First", "Tom"});
dogList.add(new String[] { "t4637", "Beagle", "First", "Eddy"});
dogList.add(new String[] { "t4636", "Beagle", "Second", "Franky"});

I would like to put in an other ArrayList sum by breed and rank

List<String[]> dogTotal = new ArrayList<String[]>();

To get an output like this if i iterate over dogTotal

"Akita", "First", "2"
"Beagle", "First", "1"
"Beagle", "Second", "1"

I have tried to use HashMap without success.

Body:
Hey what you can do is use <breed>_<rank> as key for maintaining the counts for the HashMap. When done with counting just iterate the hash map and split the key using _ as delimiter to get back breed and rank along with count value from value.

    List<String[]> dogList = new ArrayList<String[]>();
    dogList.add(new String[] { "id_tag", "breed", "rank", "nickname"});
    dogList.add(new String[] { "t4639", "Akita", "First", "Marshal"});
    dogList.add(new String[] { "t4638", "Akita", "First", "Tom"});
    dogList.add(new String[] { "t4637", "Beagle", "First", "Eddy"});
    dogList.add(new String[] { "t4636", "Beagle", "Second", "Franky"});
    List<String[]> dogTotal = new ArrayList<String[]>();
    HashMap<String,Integer> map = new HashMap<>();
    for(int i=1;i<dogList.size();i++){
        String key = dogList.get(i)[1]+"_"+dogList.get(i)[2];

        map.put(key,map.get(key)==null?1:map.get(key)+1);
    }
    for(Map.Entry<String,Integer> entry : map.entrySet()){
        String key = entry.getKey();
        String breedRank[] = new String[3];
        String getBackValues[] = key.split("_");
        breedRank[0] = getBackValues[0];
        breedRank[1] = getBackValues[1];
        breedRank[2] = String.valueOf(entry.getValue());
        System.out.println(breedRank[0]+ ", " + breedRank[1]+","+ breedRank[2]);
        dogTotal.add(breedRank);
    }
    System.out.println(dogTotal);


问:
How to rotate an image clockwise or counterclockwise, whichever is shorter?
I'm making a web page that includes a clock with an arrow in the center.  When the user clicks on an hour, the arrow rotates to point to what he/she has clicked.

I'm using a jQuery image rotate plugin (jQueryRotate) to rotate the arrow.

Here is the current code to compute the number of degrees to rotate:

```<code>var numTiles = $("ul li").size(); // Number of tiles is however many are listed in the UL, which is 12
var sel = 0; // Default hour selection
var rot = 0; // Default rotation is at the top (0 degrees)
var gap = 360 / numTiles; // Degrees between each tile

function rotateArrow(num) {
  rot = num * gap;
  $("#arrow").rotateAnimation(rot);
  sel = num;
}
</code>```

When the user clicks one of the hours, it passes num as a value of 1 through 12.

It works fine, but the problem is that if the arrow is pointing to 1 o'clock, and the user clicks 11 o'clock, the arrow rotates clockwise 300 degrees, when it would make more sense to rotate 60 degrees counterclockwise.

So, how can I write an equation to take the current hour (num) and the hour clicked (sel), and output a value as a positive or negative number, which equals the number of degrees to rotate that is most efficient, rather than just rotate only in one direction?

Any advice is appreciated.  Let me know if you have any questions.  Thanks!

答:
This does the rather boring job:

```<code>function diff(x, y) {
    var a = (x * Math.PI / 180) - Math.PI;
    var b = (y * Math.PI / 180) - Math.PI;
    return Math.atan2(Math.sin(b - a), Math.cos(b - a)) * (180 / Math.PI);
}
</code>```

It returns -180 to 180, depending on which rotation will be the shortest.

```<code>diff(360, 20)
> 19.999999999999993
diff(20, 360)
> -19.999999999999993
diff(0, 160)
> 160
diff(0, 190)
> -170
</code>```

Body:
I'm making a web page that includes a clock with an arrow in the center.  When the user clicks on an hour, the arrow rotates to point to what he/she has clicked.

I'm using a jQuery image rotate plugin (jQueryRotate) to rotate the arrow.

Here is the current code to compute the number of degrees to rotate:

var numTiles = $("ul li").size(); // Number of tiles is however many are listed in the UL, which is 12
var sel = 0; // Default hour selection
var rot = 0; // Default rotation is at the top (0 degrees)
var gap = 360 / numTiles; // Degrees between each tile

function rotateArrow(num) {
  rot = num * gap;
  $("#arrow").rotateAnimation(rot);
  sel = num;
}

When the user clicks one of the hours, it passes num as a value of 1 through 12.

It works fine, but the problem is that if the arrow is pointing to 1 o'clock, and the user clicks 11 o'clock, the arrow rotates clockwise 300 degrees, when it would make more sense to rotate 60 degrees counterclockwise.

So, how can I write an equation to take the current hour (num) and the hour clicked (sel), and output a value as a positive or negative number, which equals the number of degrees to rotate that is most efficient, rather than just rotate only in one direction?

Any advice is appreciated.  Let me know if you have any questions.  Thanks!

Body:
This does the rather boring job:

function diff(x, y) {
    var a = (x * Math.PI / 180) - Math.PI;
    var b = (y * Math.PI / 180) - Math.PI;
    return Math.atan2(Math.sin(b - a), Math.cos(b - a)) * (180 / Math.PI);
}

It returns -180 to 180, depending on which rotation will be the shortest.

diff(360, 20)
> 19.999999999999993
diff(20, 360)
> -19.999999999999993
diff(0, 160)
> 160
diff(0, 190)
> -170


问:
How to add description to JMX MXBean
I want to expose my MXBeans on Apache-Tomcat 7.0.
Though my MXBean registers successfully, I am unable to add description to the Operations that are exposed by thoese MXBeans.

Registering MXBeans

```<code>MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName m_mxbeanOName = new ObjectName( "MyMXBean:type=" + "MyComponent"+",name=MyMXBean");
MyMXBean m_mxbean = new MyMXBean ();
if(!mbs.isRegistered(m_mxbeanOName))
    mbs.registerMBean(m_mxbean,  m_mxbeanOName);
</code>```

MyMXBean Interface

```<code>public interface MyMXBean {
    public int add (int x, int y);
}
</code>```

MyMXBean Implementation

```<code>import com.sun.org.glassfish.gmbal.Description;
import com.sun.org.glassfish.gmbal.DescriptorFields;
import com.sun.org.glassfish.gmbal.Impact;
import com.sun.org.glassfish.gmbal.ManagedOperation;

public class MyMXBeanImpl implements MyMXBean {
    @ManagedOperation(impact=Impact.ACTION_INFO)
    @Description("Integer Addition: First parameter is the augend and second parameter is the addend.")
    @DescriptorFields({"p1=augend","p2=addend"})
    public int add(int x, int y) {
        return x + y;
    }
</code>```

The annotation @ManagedOperation, @Description, @DescriptorFields has no effect on the jconsole. JConsole continues to show default values

Please tell me ways to show the description about my MXBean operations on JConsole.

答:
I found this very nice blogentry with code for @Descriptor and @Name attributes and a AnnotatedStandardMXBean wrapper which handles this.

http://actimem.com/java/jmx-annotations/

Sample MXBean using this:

```<code>  @MXBean
    @Description("A test resource")
    public interface SampleMXBean {
        @Description("string#1")
        String getString1();

        @Description("string#2")
        String getString2();

        @Description("string#3")
        String string3(@Description("int i") @Name("i") int i, @Description("long j") @Name("j") long j);
    }
</code>```

Title: How to add description to JMX MXBean

Body:
I want to expose my MXBeans on Apache-Tomcat 7.0.
Though my MXBean registers successfully, I am unable to add description to the Operations that are exposed by thoese MXBeans.

Registering MXBeans

MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName m_mxbeanOName = new ObjectName( "MyMXBean:type=" + "MyComponent"+",name=MyMXBean");
MyMXBean m_mxbean = new MyMXBean ();
if(!mbs.isRegistered(m_mxbeanOName))
    mbs.registerMBean(m_mxbean,  m_mxbeanOName);

MyMXBean Interface

public interface MyMXBean {
    public int add (int x, int y);
}

MyMXBean Implementation

import com.sun.org.glassfish.gmbal.Description;
import com.sun.org.glassfish.gmbal.DescriptorFields;
import com.sun.org.glassfish.gmbal.Impact;
import com.sun.org.glassfish.gmbal.ManagedOperation;

public class MyMXBeanImpl implements MyMXBean {
    @ManagedOperation(impact=Impact.ACTION_INFO)
    @Description("Integer Addition: First parameter is the augend and second parameter is the addend.")
    @DescriptorFields({"p1=augend","p2=addend"})
    public int add(int x, int y) {
        return x + y;
    }

The annotation @ManagedOperation, @Description, @DescriptorFields has no effect on the jconsole. JConsole continues to show default values

Please tell me ways to show the description about my MXBean operations on JConsole.

Body:
I found this very nice blogentry with code for @Descriptor and @Name attributes and a AnnotatedStandardMXBean wrapper which handles this.

http://actimem.com/java/jmx-annotations/

Sample MXBean using this:

  @MXBean
    @Description("A test resource")
    public interface SampleMXBean {
        @Description("string#1")
        String getString1();

        @Description("string#2")
        String getString2();

        @Description("string#3")
        String string3(@Description("int i") @Name("i") int i, @Description("long j") @Name("j") long j);
    }


问:
How can I unit test the result of a ui-bootsrap $uibModal instance?
I have a controller that calls $uibModal.open to pop a ui-bootstrap modal. The controller looks like this:

```<code>(function () {
    'use strict';

    angular
        .module('app')
        .controller('MyCtrl', myCtrl);

    function myCtrl($uibModal) {
        var vm = this;
        vm.showModal = showModal;

        vm.results = [];

        function showModal() {
            var modalInstance = $uibModal.open({
                templateUrl: '/mymodal.html',
                controller: 'ModalCtrl ',
                controllerAs: 'modalCtrl',
            });

            modalInstance.result.then(function (myResult) {
            // I want to test that my code here  gets called and behaves as   expected. shortened for brevity
                vm.results.push(myResult);
            });
        }
    }
})();
</code>```

I have successfully tested opening the modal with correct config options. But I would like to test the result of the modal as some logic is executed when this happens but I can't seem to figure out how I can hook into the result or get it to even execute in my tests

Tests with some setup code omitted

```<code>(function() {
    'use strict';

    describe('myPageWithModal', function() {

        //mock edit modal
        var mockModalInstance = {
            result: {
                then: function(confirmCallback, cancelCallback) {
                    // Store the callbacks for later when the user clicks
                    // on the OK or Cancel button of the dialog
                    this.confirmCallBack = confirmCallback;
                    this.cancelCallback = cancelCallback;
                }
            },
            close: function( item ) {
                // The user clicked OK on the modal dialog, call the stored
                // confirm callback with the selected item
                this.result.confirmCallBack( item );
            },
            dismiss: function( type ) {
                // The user clicked cancel on the modal dialog, call
                // the stored cancel callback
                this.result.cancelCallback( type );
            }
        }

        var mockModalOptions = {
            controller: 'ModalCtrl ',
            controllerAs: 'modalCtrl',
            templateUrl: '/mymodal.html',
        }

        describe('myModal', function() {
            var actualModalOptions;

            beforeEach(function() {
                ctrl = //omitted

                //set up a spy to listen for when modal dialogs are opened and return our mock modal
                spyOn($uibModal, 'open').and.callFake(function(options) {
                    actualModalOptions = options;
                    return mockModalInstance;
                });
            });

            it('should open edit modal with options', function() {
                ctrl.showModal();

                expect($uibModal.open).toHaveBeenCalledWith(mockModalOptions);
            });

            it('should close modal and execute the modalInstance.result logic',     function() {

            });
        });
    });
})();
</code>```

答:
Considering that $uibModal.open was mocked in current spec to return mockModalInstance, mockModalInstance should be freshly defined for each spec where it is used, and mockModalInstance.result should be a promise:

```<code>var modalResult = {};
var mockModalInstance = { result: $q.resolve(modalResult) };
spyOn(mockModalInstance.result, 'then').and.callThrough();
spyOn($uibModal, 'open').and.returnValue(mockModalInstance);

ctrl.showModal();
$rootScope.$digest();

expect(mockModalInstance.result.then).toHaveBeenCalledWith(jasmine.any(Function));
expect(ctrl.results.length).toBe(1);
expect(ctrl.results[0]).toBe(modalResult);
</code>```

Body:
I have a controller that calls $uibModal.open to pop a ui-bootstrap modal. The controller looks like this:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('MyCtrl', myCtrl);

    function myCtrl($uibModal) {
        var vm = this;
        vm.showModal = showModal;

        vm.results = [];

        function showModal() {
            var modalInstance = $uibModal.open({
                templateUrl: '/mymodal.html',
                controller: 'ModalCtrl ',
                controllerAs: 'modalCtrl',
            });

            modalInstance.result.then(function (myResult) {
            // I want to test that my code here  gets called and behaves as   expected. shortened for brevity
                vm.results.push(myResult);
            });
        }
    }
})();

I have successfully tested opening the modal with correct config options. But I would like to test the result of the modal as some logic is executed when this happens but I can't seem to figure out how I can hook into the result or get it to even execute in my tests

Tests with some setup code omitted

(function() {
    'use strict';

    describe('myPageWithModal', function() {

        //mock edit modal
        var mockModalInstance = {
            result: {
                then: function(confirmCallback, cancelCallback) {
                    // Store the callbacks for later when the user clicks
                    // on the OK or Cancel button of the dialog
                    this.confirmCallBack = confirmCallback;
                    this.cancelCallback = cancelCallback;
                }
            },
            close: function( item ) {
                // The user clicked OK on the modal dialog, call the stored
                // confirm callback with the selected item
                this.result.confirmCallBack( item );
            },
            dismiss: function( type ) {
                // The user clicked cancel on the modal dialog, call
                // the stored cancel callback
                this.result.cancelCallback( type );
            }
        }

        var mockModalOptions = {
            controller: 'ModalCtrl ',
            controllerAs: 'modalCtrl',
            templateUrl: '/mymodal.html',
        }

        describe('myModal', function() {
            var actualModalOptions;

            beforeEach(function() {
                ctrl = //omitted

                //set up a spy to listen for when modal dialogs are opened and return our mock modal
                spyOn($uibModal, 'open').and.callFake(function(options) {
                    actualModalOptions = options;
                    return mockModalInstance;
                });
            });

            it('should open edit modal with options', function() {
                ctrl.showModal();

                expect($uibModal.open).toHaveBeenCalledWith(mockModalOptions);
            });

            it('should close modal and execute the modalInstance.result logic',     function() {

            });
        });
    });
})();

Body:
Considering that $uibModal.open was mocked in current spec to return mockModalInstance, mockModalInstance should be freshly defined for each spec where it is used, and mockModalInstance.result should be a promise:

var modalResult = {};
var mockModalInstance = { result: $q.resolve(modalResult) };
spyOn(mockModalInstance.result, 'then').and.callThrough();
spyOn($uibModal, 'open').and.returnValue(mockModalInstance);

ctrl.showModal();
$rootScope.$digest();

expect(mockModalInstance.result.then).toHaveBeenCalledWith(jasmine.any(Function));
expect(ctrl.results.length).toBe(1);
expect(ctrl.results[0]).toBe(modalResult);


问:
gsutil ls command not working due to ampersand in path
I couldn't able to get succeed after multiple tries to list out the contents available in path, because my folder name contains ampersand like below.

gsutil ls -r gs://testing_purpose/U&T

It returns error like below
  CommandException: One or more URLs matched no objects.

'T' is not recognized as an internal or external command,
  operable program or batch file.

答:
Your command shell is interpreting & as a control character, so your statement looks like this to the shell:

```<code>yourshell$ gsutil ls -r gs://testing_purpose/U
yourshell$ T
</code>```

To fix those, you should quote the argument with the control character, like so:

gsutil ls -r "gs://testing_purpose/U&T"

Body:
Your command shell is interpreting & as a control character, so your statement looks like this to the shell:

yourshell$ gsutil ls -r gs://testing_purpose/U
yourshell$ T

To fix those, you should quote the argument with the control character, like so:

gsutil ls -r "gs://testing_purpose/U&T"


问:
Regex for ranges of values in comma-separated list
I want to write a regex that match a list of numeric values, given in a comma-separated list, ranges allowed. Empty is not allowed.

Something like: 1-10,20-56,8,7

So far I have (([0-9]+)|([0-9]+-[0-9]+),)*[0-9]+. This does most of the job, except it misses the case of one range only (eg: 1-10 would not validate).

The checking for each range can be omitted (eg: 20-10 can be allowed as a valid range).

Any help would be appreciated.

答:
Lets say that CORE of your patter is

```<code>([0-9]+.)|([0-9]+-[0-9]+)
</code>```

It matches a single numeric value or a range. So, what you need is:

```<code>(CORE,)*CORE
</code>```

And what you have is:

```<code>(CORE,)*DIGIT
</code>```

Do like this and you will be fine:

```<code>(([0-9]+.)|([0-9]+-[0-9]+),)*([0-9]+.)|([0-9]+-[0-9]+)
</code>```

Body:
Lets say that CORE of your patter is

([0-9]+.)|([0-9]+-[0-9]+)

It matches a single numeric value or a range. So, what you need is:

(CORE,)*CORE

And what you have is:

(CORE,)*DIGIT

Do like this and you will be fine:

(([0-9]+.)|([0-9]+-[0-9]+),)*([0-9]+.)|([0-9]+-[0-9]+)