问:
margin / padding not working
I have 2 main divs within a main div. I've tried adding margin and padding with a large number to test, but it just work work. Why can't I add margin / padding between them? Please help.

HTML

```<code> <div id="mainWrapper">

    <header class="container">

        <div id="nav2" class="container">
            <ul class="nav2a">
                <li><a href="#">Login</a></li>
                <li><a href="#">Quick Search</a></li>
                <li><a href="#">Advanced Search</a></li>
                <li><a href="#">English <i class="fa fa-caret-down"></i></p></a>
                    <ul class="nav2b">
                        <li><a href="#">French</a></li>
                        <li><a href="#">Italian</a></li>
                        <li><a href="#">Spanish</a></li>
                        <li><a href="#">German</a></li>
                    </ul>
                </li>
            </ul>
        </div> <!-- end nav2 -->

    </header>

    <div class="clearfloat"></div>

   <div id="fullNav" class="container">

        <div id="logoSymbol">
            <a href="#">
                <img src="images/gpj-baker-symbol.png" width="54" height="51" />
            </a>
        </div>

        <div id="logoText">
            <a href="#">
                <img src="images/gpj-baker-text.png" width="200" height="30" />
            </a>
       </div>

        <div class="clearfloat"></div>

        <div id="mainNav">
             <ul class="nav1a">
                 <li><a href="#">Brands</a></li>
                 <li><a href="#">Fabrics & Wallcoverings</a></li>
                 <li><a href="#">Contact</a></li>
                 <li><a href="#">About Us</a></li>
                 <li><a href="#">Where To Buy</a></li>
                 <li><a href="#">Press</a></li>
            </ul>
        </div>

        <div class="clearfloat"></div>

        <div class="hr"><hr/></div>

        <div class="clearfloat"></div>

    </div> <!-- end fullNav -->

    <div class="clearfloat"></div>

    <div id="brandContainer" class="container">

        <div id="breadcrumbs" class="container">
            <ul class="breadInfo">
                <li><a href="#">Home</a></li>
                <li><a href="brands.html" class="currentPg">Brands</a></li>
            </ul>
        </div> <!-- end breadIcrumbs -->

        <div class="clearfloat"></div>

        <div class="brandList">

            <div class="brandImg">
                <a href="#"><img src="http://placehold.it/442x294" /></a>
            </div>

            <div class="brandCopy">
                <a href="#">
                    <img src="images/gpj-baker-text.png" width="162" height="25" />
                </a>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dui ex, pharetra a commodo maximus, luctus id ligula. Curabitur tempus arcu ac orci fringilla varius.</p>

                <p>Cras hendrerit, mi interdum varius luctus, nisl lectus accumsan mauris, eu tristique arcu massa et arcu. Vivamus venenatis purus blandit, placerat urna eget, faucibus mauris.</p>
                <a href="#">Explore <i class="fa fa-caret-right"></i></a>
          </div>

        </div> <!-- end brandList -->

        <div class="clearfloat"></div>

        <div class="brandList">

            <div class="brandImg">
                <a href="#"><img src="http://placehold.it/442x294" /></a>
            </div>

            <div class="brandCopy">
                <a href="#">
                    <img src="images/gpj-baker-text.png" width="162" height="25" />
                </a>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dui ex, pharetra a commodo maximus, luctus id ligula. Curabitur tempus arcu ac orci fringilla varius.</p>

                <p>Cras hendrerit, mi interdum varius luctus, nisl lectus accumsan mauris, eu tristique arcu massa et arcu. Vivamus venenatis purus blandit, placerat urna eget, faucibus mauris.</p>
                <a href="#">Explore <i class="fa fa-caret-right"></i></a>
          </div>

        </div> <!-- end brandList -->

    </div><!-- end brandContainer -->
</code>```

CSS

```<code>html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit;
vertical-align: baseline;} /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {display: block;} body {line-height: 1;} ol, ul {list-style: none;} blockquote, q {quotes: none;} blockquote:before, blockquote:after, q:before, q:after {content: ''; content: none;} table {border-collapse: collapse; border-spacing: 0;}

body {
    font-size: 16px;
    text-decoration: none;
}

h1, h2, h3, h4, h5, h6, p, a {
    font-family: "Lato", Helvetica, Arial, sans-serif;
}

.clearfloat {
    clear: both;
}

#mainWrapper {
    margin: 0 auto;
    max-width: 1280px;
    vertical-align: middle;
    width: 100%;
}

.container {
    margin: 0 auto;
    max-width: 980px;
    vertical-align: middle;
    width: 100%;
}

header .container {
    display: block;
    float: right;
}

header #nav {
    float: right;
}

div.hr {
    border: 0.01em solid #676767;
}

#nav2 {
    float: right;
    font-size: 12px;
    font-weight: 400;
    margin: 0 auto;
    padding: 5px 0;
    text-transform: uppercase;
}

    #nav2 a:link,
    #nav2 a:visited {
        color: #676767;
    }

    #nav2 a:hover {
        color: #4284b8;
    }

    #nav2 li {
        vertical-align: middle;
        float:left;
    }

    #nav2 li,
    #nav2 li a {
        display: inline-block;
        text-decoration: none;
    }

    #nav2 li a {
        padding: 5px 10px;
    }

    #nav2 li ul {
        display: none;
        position: absolute;
    }

    #nav2 li:hover ul {
        display: block;
    }

    #nav2 li ul li {
        clear: both;
    }

    #nav2 .nav2a {
        float: right;
    }

#fullNav {
    text-align: center;
}

    #fullNav #logoSymbol,
    #fullNav #logoText {
        display: inline;
        margin: 0 auto;
        padding: 0 5px;
    }

#mainNav {
    font-size: 12px;
    font-weight: 400;
    margin: 0 auto;
    padding: 5px 0;
    text-transform: uppercase;
}

    #mainNav a:link,
    #mainNav a:visited {
        color: #676767;
    }

    #mainNav a:hover {
        color: #4284b8;
    }

    #mainNav li {
        vertical-align: middle;
    }

    #mainNav li,
    #mainNav li a {
        display: inline-block;
        text-decoration: none;
    }

    #mainNav li a {
        padding: 5px 25px;
    }

    #mainNav li ul {
        display: none;
        position: absolute;
    }

    #mainNav li:hover ul {
        display: block;
    }

    #mainNav li ul li {
        clear: both;
    }

#footerNav {
    float: right;
    font-size: 12px;
    font-weight: 400;
    margin: 0 auto;
    padding: 5px 0;
    text-transform: uppercase;
}

    #footerNav a:link,
    #footerNav a:visited {
        color: #676767;
    }

    #footerNav a:hover {
        color: #6e8878;
    }

    #footerNav li {
        vertical-align: middle;
        float:left;
    }

    #footerNav li,
    #footerNav li a {
        display: inline-block;
        text-decoration: none;
    }

    #footerNav li a {
        padding: 5px 10px;
    }

    #footerNav li ul {
        display: none;
        position: absolute;
    }

    #footerNav li:hover ul {
        display: block;
    }

#nav3b {
    display: none;
    clear: both;
}

#nav3b a:hover {
    display: block;
}

    #footerNav .nav3a {
        float: right;
    }

#breadcrumbs {
    float: right;
    font-size: 9px;
    font-weight: 400;
    margin: 0 auto;
    text-transform: uppercase;
}

    #breadcrumbs .currentPg {
        color: #676767;
        font-weight:bold;
    }

    #breadcrumbs a:link,
    #breadcrumbs a:visited {
        color: #8b8b8b;
    }

    #breadcrumbs a:hover {
        color: #4284b8;
    }

    #breadcrumbs li {
        vertical-align: middle;
        float:left;
    }

        #breadcrumbs li {
            padding: 0 .25em 0 0;
        }

        #breadcrumbs li:after {
            content: " | ";
            display: inline-block;
            font-size: 100%;
            margin: 0 0 0 1.25em;
        }

        #breadcrumbs li:last-child:after {
            content: " ";
        }

        #breadcrumbs li,
        #breadcrumbs li a {
            display: inline-block;
            text-decoration: none;
        }

        #breadcrumbs li a {
            padding: 5px 10px;
        }

        #breadcrumbs li a:last-child {
            padding-right: 0;
        }

    #breadcrumbs .breadInfo {
        float: right;
        padding-bottom: 5px;
    }

.brandList {
    display: inline;
    overflow: auto;
    text-align: center;
    vertical-align: middle;
    width: 100%;
}

.brandImg {
    display: block;
    float: left;
    margin: 0 auto;
    max-width: 442px;
    padding-right: 8px;
    vertical-align: middle;
    width: 50%;
}

.brandCopy {
    display: block;
    float: left;
    font-size: 12px;
    font-weight: 400;
    margin: 0 auto;
    overflow: hidden;
    padding-left: 8px;
    position: relative;
    text-transform: uppercase;
    vertical-align: middle;
    width: 50%;
}

    .brandCopy p {
        display: block;
        font-size: 16px;
        text-transform: none;
        line-height: 150%;
    }

    .brandCopy .currentPg {
        color: #676767;
        font-weight:bold;
    }

    .brandCopy a:link,
    .brandCopy a:visited {
        color: #4284b8;
        font-weight: bold;
        text-decoration: none;
    }

    .brandCopy a:hover {
        color: #959595;
    }

    .brandCopy .breadInfo {
        float: right;
        padding-bottom: 5px;
    }

    .brandCopy a img {
        margin: 0 auto;
        margin-bottom: 16px;
        max-width: 442px;
        text-align: center;
    }

    .brandCopy p {
        margin-bottom: 16px;
        overflow: auto;
        text-align: left;
    }
</code>```

EDIT: Full CSS added.

答: margin doesn't work on an inline HTML element. If you want to apply margin on an inline element then you must convert the target element into block level element by applying display: inline-block property.

Title: margin / padding not working

Body:
I have 2 main divs within a main div. I've tried adding margin and padding with a large number to test, but it just work work. Why can't I add margin / padding between them? Please help.

HTML

Login

Quick Search

Advanced Search

English

French

Italian

Spanish

German

Brands

Fabrics & Wallcoverings

Contact

About Us

Where To Buy

Press

Home

Brands

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dui ex, pharetra a commodo maximus, luctus id ligula. Curabitur tempus arcu ac orci fringilla varius.

Cras hendrerit, mi interdum varius luctus, nisl lectus accumsan mauris, eu tristique arcu massa et arcu. Vivamus venenatis purus blandit, placerat urna eget, faucibus mauris.

                Explore

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dui ex, pharetra a commodo maximus, luctus id ligula. Curabitur tempus arcu ac orci fringilla varius.

Cras hendrerit, mi interdum varius luctus, nisl lectus accumsan mauris, eu tristique arcu massa et arcu. Vivamus venenatis purus blandit, placerat urna eget, faucibus mauris.

                Explore

CSS

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit;
vertical-align: baseline;} /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {display: block;} body {line-height: 1;} ol, ul {list-style: none;} blockquote, q {quotes: none;} blockquote:before, blockquote:after, q:before, q:after {content: ''; content: none;} table {border-collapse: collapse; border-spacing: 0;}

body {
    font-size: 16px;
    text-decoration: none;
}

h1, h2, h3, h4, h5, h6, p, a {
    font-family: "Lato", Helvetica, Arial, sans-serif;
}

.clearfloat {
    clear: both;
}

#mainWrapper {
    margin: 0 auto;
    max-width: 1280px;
    vertical-align: middle;
    width: 100%;
}

.container {
    margin: 0 auto;
    max-width: 980px;
    vertical-align: middle;
    width: 100%;
}

header .container {
    display: block;
    float: right;
}

header #nav {
    float: right;
}

div.hr {
    border: 0.01em solid #676767;
}

#nav2 {
    float: right;
    font-size: 12px;
    font-weight: 400;
    margin: 0 auto;
    padding: 5px 0;
    text-transform: uppercase;
}

    #nav2 a:link,
    #nav2 a:visited {
        color: #676767;
    }

    #nav2 a:hover {
        color: #4284b8;
    }

    #nav2 li {
        vertical-align: middle;
        float:left;
    }

    #nav2 li,
    #nav2 li a {
        display: inline-block;
        text-decoration: none;
    }

    #nav2 li a {
        padding: 5px 10px;
    }

    #nav2 li ul {
        display: none;
        position: absolute;
    }

    #nav2 li:hover ul {
        display: block;
    }

    #nav2 li ul li {
        clear: both;
    }

    #nav2 .nav2a {
        float: right;
    }

#fullNav {
    text-align: center;
}

    #fullNav #logoSymbol,
    #fullNav #logoText {
        display: inline;
        margin: 0 auto;
        padding: 0 5px;
    }

#mainNav {
    font-size: 12px;
    font-weight: 400;
    margin: 0 auto;
    padding: 5px 0;
    text-transform: uppercase;
}

    #mainNav a:link,
    #mainNav a:visited {
        color: #676767;
    }

    #mainNav a:hover {
        color: #4284b8;
    }

    #mainNav li {
        vertical-align: middle;
    }

    #mainNav li,
    #mainNav li a {
        display: inline-block;
        text-decoration: none;
    }

    #mainNav li a {
        padding: 5px 25px;
    }

    #mainNav li ul {
        display: none;
        position: absolute;
    }

    #mainNav li:hover ul {
        display: block;
    }

    #mainNav li ul li {
        clear: both;
    }

#footerNav {
    float: right;
    font-size: 12px;
    font-weight: 400;
    margin: 0 auto;
    padding: 5px 0;
    text-transform: uppercase;
}

    #footerNav a:link,
    #footerNav a:visited {
        color: #676767;
    }

    #footerNav a:hover {
        color: #6e8878;
    }

    #footerNav li {
        vertical-align: middle;
        float:left;
    }

    #footerNav li,
    #footerNav li a {
        display: inline-block;
        text-decoration: none;
    }

    #footerNav li a {
        padding: 5px 10px;
    }

    #footerNav li ul {
        display: none;
        position: absolute;
    }

    #footerNav li:hover ul {
        display: block;
    }

#nav3b {
    display: none;
    clear: both;
}

#nav3b a:hover {
    display: block;
}

    #footerNav .nav3a {
        float: right;
    }

#breadcrumbs {
    float: right;
    font-size: 9px;
    font-weight: 400;
    margin: 0 auto;
    text-transform: uppercase;
}

    #breadcrumbs .currentPg {
        color: #676767;
        font-weight:bold;
    }

    #breadcrumbs a:link,
    #breadcrumbs a:visited {
        color: #8b8b8b;
    }

    #breadcrumbs a:hover {
        color: #4284b8;
    }

    #breadcrumbs li {
        vertical-align: middle;
        float:left;
    }

        #breadcrumbs li {
            padding: 0 .25em 0 0;
        }

        #breadcrumbs li:after {
            content: " | ";
            display: inline-block;
            font-size: 100%;
            margin: 0 0 0 1.25em;
        }

        #breadcrumbs li:last-child:after {
            content: " ";
        }

        #breadcrumbs li,
        #breadcrumbs li a {
            display: inline-block;
            text-decoration: none;
        }

        #breadcrumbs li a {
            padding: 5px 10px;
        }

        #breadcrumbs li a:last-child {
            padding-right: 0;
        }

    #breadcrumbs .breadInfo {
        float: right;
        padding-bottom: 5px;
    }

.brandList {
    display: inline;
    overflow: auto;
    text-align: center;
    vertical-align: middle;
    width: 100%;
}

.brandImg {
    display: block;
    float: left;
    margin: 0 auto;
    max-width: 442px;
    padding-right: 8px;
    vertical-align: middle;
    width: 50%;
}

.brandCopy {
    display: block;
    float: left;
    font-size: 12px;
    font-weight: 400;
    margin: 0 auto;
    overflow: hidden;
    padding-left: 8px;
    position: relative;
    text-transform: uppercase;
    vertical-align: middle;
    width: 50%;
}

    .brandCopy p {
        display: block;
        font-size: 16px;
        text-transform: none;
        line-height: 150%;
    }

    .brandCopy .currentPg {
        color: #676767;
        font-weight:bold;
    }

    .brandCopy a:link,
    .brandCopy a:visited {
        color: #4284b8;
        font-weight: bold;
        text-decoration: none;
    }

    .brandCopy a:hover {
        color: #959595;
    }

    .brandCopy .breadInfo {
        float: right;
        padding-bottom: 5px;
    }

    .brandCopy a img {
        margin: 0 auto;
        margin-bottom: 16px;
        max-width: 442px;
        text-align: center;
    }

    .brandCopy p {
        margin-bottom: 16px;
        overflow: auto;
        text-align: left;
    }

EDIT: Full CSS added.


来源: stackexchange

问:
How to design using patterns
I am a college student and I'm learning about software patterns (specifically the ones mentioned in the GoF book). I have never been that good at software design, but I'm learning how each pattern works and solves different problems to produce more flexible software. I have a question that has been bugging me.

What's the best way to look at a problem (a piece of software that needs to be written) and determine how to organize it and apply patterns? I recently had a group Java project that went really sour because our design just wasn't very flexible. I honestly just had a great deal of trouble trying to break down the problem into manageable pieces to sort out. I know I can write code, but I don't know how to organize it.

The patterns I have gone through currently are Composite, Builder, Adapter, Proxy, Observer, State, Strategy, Template Method, and Iterator. Like I have mentioned, I know what they are supposed to solve, but I feel like I am trying to force patterns into place. Any help or links to pages would be greatly appreciated. Thank you all!

答:
Bill Venners: Is the value of patterns, then, that in the real world when I feel a particular kind of pain I'll be able to reach for a known solution?

Erich Gamma: This is definitely the way I'd recommend that people use patterns. Do not start immediately throwing patterns into a design, but use them as you go and understand more of the problem. Because of this I really like to use patterns after the fact, refactoring to patterns. One comment I saw in a news group just after patterns started to become more popular was someone claiming that in a particular program they tried to use all 23 GoF patterns. They said they had failed, because they were only able to use 20. They hoped the client would call them again to come back again so maybe they could squeeze in the other 3.

Trying to use all the patterns is a bad thing, because you will end up with synthetic designs—speculative designs that have flexibility that no one needs. These days software is too complex. We can't afford to speculate what else it should do. We need to really focus on what it needs. That's why I like refactoring to patterns. People should learn that when they have a particular kind of problem or code smell, as people call it these days, they can go to their patterns toolbox to find a solution.

Bill Venners: That's funny, because my second question was that I have observed that often people feel the design with the most patterns is the best. In our design seminar, I have the participants do a design project, which they present to the others at the end of the seminar. Almost invariably, the presenters want to show off how many patterns they used in their design, even though I try to tell them the goal is a clean, easy to understand API, not to win an I-used-the-most-patterns contest. I just heard you say the same thing, that that's not the right way to think about patterns. If not, what is the proper justification for using patterns in designs?

Erich Gamma: A lot of the patterns are about extensibility and reusability. When you really need extensibility, then patterns provide you with a way to achieve it and this is cool. But when you don't need it, you should keep your design simple and not add unnecessary levels of indirection. One of our Eclipse mottos is that we want extensibility where it matters. Actually, if you are interested in how we use patterns in Eclipse I did an attempt to capture their uses in a chapter in the Contributing to Eclipse book [see Resources]. In this chapter I used design patterns to explain pieces of the Eclipse architecture.

http://www.artima.com/lejava/articles/gammadp.html

google parts II - IV too! :) those are great readings

ContentLicense: CC BY-SA 3.0

Title: How to design using patterns


问:
Unable to create the correct link with vue router-link
I am using the vue rounter-link tag to navigate to a different page. My problem is that it does not seem to navigate to a different page. I think the problem lies within the "params" of the router-link. I do have a blog_id as 2 but it always shows the current page blog_id that I am at.

Initially I have

```<code><router-link v-bind:to="{name:'datascience-single', params: {blog_id: blog.blog_id}}">
    <i class="fa fa-cogs" aria-hidden="true"></i>
</router-link>
</code>```

but then I started to think that maybe it's not taking the blog.blog_id correctly so I replaced it with a fixed value

```<code>        <li v-for="blog in blogs" v-bind:key="blog.id">
          <h1>{{blog.title}}</h1>
          {{blog.content}}
          <router-link v-bind:to="{name:'datascience-single', params: {blog_id: 2}}">
            <i class="fa fa-cogs" aria-hidden="true"></i>
          </router-link>
        </li>
</code>```

However the problem remains the same.

答:
This answer assumes you are already on the same route you are navigating to.

Navigating to the same route does not refresh your components. We are used that whenever we go to a different URL the page should refresh, with multipage websites. However Vue router handles this differently. For the router the route,  eg: /blogs/{id}, is not changing whenever id is being updated, we are still on /blogs/{id} but with a different parameter.

In order to detect this change we can simply make a watcher on the route parameter:

```<code>watch: {
    '$route.params.id': (id) => {
        // The route is the same, but our parameter changed.
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the vue rounter-link tag to navigate to a different page. My problem is that it does not seem to navigate to a different page. I think the problem lies within the "params" of the router-link. I do have a blog_id as 2 but it always shows the current page blog_id that I am at.

Initially I have

<router-link v-bind:to="{name:'datascience-single', params: {blog_id: blog.blog_id}}">

</router-link>

but then I started to think that maybe it's not taking the blog.blog_id correctly so I replaced it with a fixed value

{{blog.title}}

          {{blog.content}}
          <router-link v-bind:to="{name:'datascience-single', params: {blog_id: 2}}">

          </router-link>

However the problem remains the same.

Body:
This answer assumes you are already on the same route you are navigating to.

Navigating to the same route does not refresh your components. We are used that whenever we go to a different URL the page should refresh, with multipage websites. However Vue router handles this differently. For the router the route,  eg: /blogs/{id}, is not changing whenever id is being updated, we are still on /blogs/{id} but with a different parameter.

In order to detect this change we can simply make a watcher on the route parameter:

watch: {
    '$route.params.id': (id) => {
        // The route is the same, but our parameter changed.
    }
}


问:
How to fix errors with timeout on okhttp client
I have already set a connection with API, everything seems to be working but I need to set a timeout for data to show. I have checked the answers from before here on StackOverflow, but none of the methods seem to fit. Do you know any way of how to set the timeout right?

I tried several codes from these answers (How to set connection timeout with OkHttp) and there was always some issues with it. At this point, I have an error that says that it cannot resolve the method setReadConnection

OkHttpClient client = new OkHttpClient.Builder().setReadTimeout(30, TimeUnit.SECONDS).build();

I was just hoping that this would help me to finally show the data in the app. Thanks for any tips

答:
Is that you looking for?  </p>

```<code>OkHttpClient okHttpClient = new OkHttpClient.Builder()
            //default timeout for not annotated requests
            .readTimeout(10000, TimeUnit.MILLISECONDS)
            .connectTimeout(10000, TimeUnit.MILLISECONDS)
            .writeTimeout(10000, TimeUnit.MILLISECONDS)
            .build();
</code>```

Body:
Is that you looking for?

OkHttpClient okHttpClient = new OkHttpClient.Builder()
            //default timeout for not annotated requests
            .readTimeout(10000, TimeUnit.MILLISECONDS)
            .connectTimeout(10000, TimeUnit.MILLISECONDS)
            .writeTimeout(10000, TimeUnit.MILLISECONDS)
            .build();


问:
Spring Boot Microservice cant connect to Eureka Server
I try to connect my service (auth-service) to the Eureka Server for the service registry. The Eureka server is running, but when I try to connect the auth-service nothing happens.

I added the configurations to application.yaml and application.properties, but nothing helped.

application.yaml from auth-service:

```<code>eureka:
      client:
        fetchRegistry: true
        registryFetchIntervalSeconds: 5
        serviceUrl:
          defaultZone: http://localhost:8761/eureka
      instance:
        preferIpAddress: true
</code>```

URL of Eureka server: http://localhost:8761/

DS Replicas: localhost

Message when I start auth-service:

```<code>2019-05-24 16:58:11.457  INFO [auth-service,,,] 14704 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-05-24 16:58:13.293  INFO [auth-service,,,] 14704 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2019-05-24 16:58:14.521  INFO [auth-service,,,] 14704 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-05-24 16:58:14.524  INFO [auth-service,,,] 14704 --- [           main] d.h.authservice.AuthServiceApplication   : Started AuthServiceApplication in 11.448 seconds (JVM running for 12.63)
</code>```

The Eureka Server is annotated with @EnableEurekaServer and the Client is annotated with @EnableDiscoveryClient

auth-service pom:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>de.hspf</groupId>
<artifactId>auth-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>auth-service</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.sendgrid</groupId>
        <artifactId>sendgrid-java</artifactId>
        <version>4.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>org.modelmapper</groupId>
        <artifactId>modelmapper</artifactId>
        <version>1.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring3</artifactId>
        <version>3.0.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.xmlunit</groupId>
        <artifactId>xmlunit-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-sleuth-zipkin</artifactId>
        <version>2.1.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-netflix-eureka-client</artifactId>
        <version>2.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-starter</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley.M9</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

Discovery Service pom

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>discovery-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>discovery-server</name>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>

    <dependencies>

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-dependencies</artifactId>

            <version>Finchley.M9</version>

            <type>pom</type>

            <scope>import</scope>

        </dependency>

    </dependencies>

</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
</code>```

答:
Try to use this dependency for client

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</code>```

instead of

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-netflix-eureka-client</artifactId>
    <version>2.0.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-starter</artifactId>
</dependency>
</code>```

Body:
I try to connect my service (auth-service) to the Eureka Server for the service registry. The Eureka server is running, but when I try to connect the auth-service nothing happens.

I added the configurations to application.yaml and application.properties, but nothing helped.

application.yaml from auth-service:

eureka:
      client:
        fetchRegistry: true
        registryFetchIntervalSeconds: 5
        serviceUrl:
          defaultZone: http://localhost:8761/eureka
      instance:
        preferIpAddress: true

URL of Eureka server: http://localhost:8761/

DS Replicas: localhost

Message when I start auth-service:

2019-05-24 16:58:11.457  INFO [auth-service,,,] 14704 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-05-24 16:58:13.293  INFO [auth-service,,,] 14704 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2019-05-24 16:58:14.521  INFO [auth-service,,,] 14704 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-05-24 16:58:14.524  INFO [auth-service,,,] 14704 --- [           main] d.h.authservice.AuthServiceApplication   : Started AuthServiceApplication in 11.448 seconds (JVM running for 12.63)

The Eureka Server is annotated with @EnableEurekaServer and the Client is annotated with @EnableDiscoveryClient

auth-service pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
    <relativePath/>
</parent>
<groupId>de.hspf</groupId>
<artifactId>auth-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>auth-service</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.sendgrid</groupId>
        <artifactId>sendgrid-java</artifactId>
        <version>4.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>org.modelmapper</groupId>
        <artifactId>modelmapper</artifactId>
        <version>1.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring3</artifactId>
        <version>3.0.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.xmlunit</groupId>
        <artifactId>xmlunit-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-sleuth-zipkin</artifactId>
        <version>2.1.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-netflix-eureka-client</artifactId>
        <version>2.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-starter</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley.M9</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Discovery Service pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>discovery-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>discovery-server</name>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>

    <dependencies>

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-dependencies</artifactId>

            <version>Finchley.M9</version>

            <type>pom</type>

            <scope>import</scope>

        </dependency>

    </dependencies>

</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

Body:
Try to use this dependency for client

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

instead of

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-netflix-eureka-client</artifactId>
    <version>2.0.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-starter</artifactId>
</dependency>


问:
Spark Structured Streaming OutOfMemoryError caused by thousands of KafkaMbean instances
Spark Structured Streaming executor fails with OutOfMemoryError

Checking the heap allocation with VirtualVM indicate that JMX Mbean Server memory usage grows linearly with time.

After a further investigation it seems that JMX Mbean is filled with thousands of instances of KafkaMbean objects with metrics for consumer-(\d+) that goes into thousands (equal to the number of tasks created on the executor).

Running Kafka consumer with DEBUG logs on the executor shows that the executor adds thousands of metrics sensors and often does not remove them at all or only removes some

I am running HDP Spark 2.3.0.2.6.5.0-292 with HDP Kafka 1.0.0.2.6.5.0-292.

Here is how I initialise structured streaming:

```<code>sparkSession
  .readStream
  .format("kafka")
  .options(Map("kafka.bootstrap.servers" -> KAFKA_BROKERS,
               "subscribePattern"        -> INPUT_TOPIC,
               "startingOffsets"         -> "earliest",
               "failOnDataLoss"          -> "false"))
  .mapPartitions(processData)
  .writeStream
  .format("kafka")
  .options(Map("kafka.bootstrap.servers" -> KAFKA_BROKERS,
               "checkpointLocation" -> CHECKPOINT_LOCATION))
  .queryName("Process Data")
  .outputMode("update")
  .trigger(Trigger.ProcessingTime(1000))
  .load()
  .start()
  .awaitTermination()
</code>```

I was expecting Spark/Kafka to properly clean the MBeans on task completion, but that seems not to be the case.

答:
Your HDP version is probably using spark 2.3.1 which has a known bug reading data from Kafka(this issue appears when you are reading from a topic that doesn't have new data every micro batch):

https://issues.apache.org/jira/browse/SPARK-24987

https://issues.apache.org/jira/browse/SPARK-25106

This bug was as a result of a change that was made in version 2.3.1 (it doesn't exists in version 2.3.0) so you can either upgrade your spark version or get a patch for your HDP version.

Body:
Spark Structured Streaming executor fails with OutOfMemoryError

Checking the heap allocation with VirtualVM indicate that JMX Mbean Server memory usage grows linearly with time.

After a further investigation it seems that JMX Mbean is filled with thousands of instances of KafkaMbean objects with metrics for consumer-(\d+) that goes into thousands (equal to the number of tasks created on the executor).

Running Kafka consumer with DEBUG logs on the executor shows that the executor adds thousands of metrics sensors and often does not remove them at all or only removes some

I am running HDP Spark 2.3.0.2.6.5.0-292 with HDP Kafka 1.0.0.2.6.5.0-292.

Here is how I initialise structured streaming:

sparkSession
  .readStream
  .format("kafka")
  .options(Map("kafka.bootstrap.servers" -> KAFKA_BROKERS,
               "subscribePattern"        -> INPUT_TOPIC,
               "startingOffsets"         -> "earliest",
               "failOnDataLoss"          -> "false"))
  .mapPartitions(processData)
  .writeStream
  .format("kafka")
  .options(Map("kafka.bootstrap.servers" -> KAFKA_BROKERS,
               "checkpointLocation" -> CHECKPOINT_LOCATION))
  .queryName("Process Data")
  .outputMode("update")
  .trigger(Trigger.ProcessingTime(1000))
  .load()
  .start()
  .awaitTermination()

I was expecting Spark/Kafka to properly clean the MBeans on task completion, but that seems not to be the case.


问:
What is the correct way to treat the primary key exception, when I can safely ignore it?
I need to enter some data fetched from the Hattrick website (online football manager) into a database, using C#. The database structure is the following:

```<code>MatchID (which is also primary key)
Rating1
Rating2
...
Rating16
</code>```

All the fields are TinyInt.

Because the way the data are conceived, if I enter into the database a MatchID which is already present, I am 100% sure that the other fields Ratingx will have the same value, so this exception can be safely ignored, so as not to bother the user.

To treat this exception, I used the following code:

```<code>string AddMatchCommand = "Insert into Games values (@Match, @Ratings1, @Ratings2, @Ratings3, @Ratings4, @Ratings5, @Ratings6, @Ratings7, @Ratings8, @Ratings9, @Ratings10, @Ratings11, @Ratings12, @Ratings13, @Ratings14, @Ratings15, @Ratings16)";
SqlConnection MyConn = new SqlConnection(CreateTableConnectionString);
SqlCommand command = new SqlCommand(AddMatchCommand, MyConn);

command.Parameters.AddWithValue("@Match", MatchIDToInsert.ToString(CultureInfo.InvariantCulture));
command.Parameters.AddWithValue("@Ratings1", RatingsToInsert[0].ToString(CultureInfo.InvariantCulture));
command.Parameters.AddWithValue("@Ratings2", RatingsToInsert[1].ToString(CultureInfo.InvariantCulture));
//...
command.Parameters.AddWithValue("@Ratings16", RatingsToInsert[15].ToString(CultureInfo.InvariantCulture));

MyConn.Open();
try
{
 command.ExecuteNonQuery();
}
catch (SqlException S)
{
 if (S.Number != 2627)  //2627 is the ID for the exception I want to ignore
 {
  MessageBox.Show(S.Message);
 }
}
MyConn.Close();
</code>```

The code above does its job. However, is there a better way to handle this situation? I am pretty sure that I may find a bug or two down the line, but I cannot prove this.

答:
You can phrase the query like this to avoid an error:</p>

```<code>Insert into Games
    select @Match, @Ratings1, @Ratings2, @Ratings3, @Ratings4, @Ratings5, @Ratings6, @Ratings7, @Ratings8, @Ratings9, @Ratings10, @Ratings11, @Ratings12, @Ratings13, @Ratings14, @Ratings15, @Ratings16
    where not exists (select 1 from Games g where g.matchid = @match);
</code>```

Body:
I need to enter some data fetched from the Hattrick website (online football manager) into a database, using C#. The database structure is the following:

MatchID (which is also primary key)
Rating1
Rating2
...
Rating16

All the fields are TinyInt.

Because the way the data are conceived, if I enter into the database a MatchID which is already present, I am 100% sure that the other fields Ratingx will have the same value, so this exception can be safely ignored, so as not to bother the user.

To treat this exception, I used the following code:

string AddMatchCommand = "Insert into Games values (@Match, @Ratings1, @Ratings2, @Ratings3, @Ratings4, @Ratings5, @Ratings6, @Ratings7, @Ratings8, @Ratings9, @Ratings10, @Ratings11, @Ratings12, @Ratings13, @Ratings14, @Ratings15, @Ratings16)";
SqlConnection MyConn = new SqlConnection(CreateTableConnectionString);
SqlCommand command = new SqlCommand(AddMatchCommand, MyConn);

command.Parameters.AddWithValue("@Match", MatchIDToInsert.ToString(CultureInfo.InvariantCulture));
command.Parameters.AddWithValue("@Ratings1", RatingsToInsert[0].ToString(CultureInfo.InvariantCulture));
command.Parameters.AddWithValue("@Ratings2", RatingsToInsert[1].ToString(CultureInfo.InvariantCulture));
//...
command.Parameters.AddWithValue("@Ratings16", RatingsToInsert[15].ToString(CultureInfo.InvariantCulture));

MyConn.Open();
try
{
 command.ExecuteNonQuery();
}
catch (SqlException S)
{
 if (S.Number != 2627)  //2627 is the ID for the exception I want to ignore
 {
  MessageBox.Show(S.Message);
 }
}
MyConn.Close();

The code above does its job. However, is there a better way to handle this situation? I am pretty sure that I may find a bug or two down the line, but I cannot prove this.

Body:
You can phrase the query like this to avoid an error:

Insert into Games
    select @Match, @Ratings1, @Ratings2, @Ratings3, @Ratings4, @Ratings5, @Ratings6, @Ratings7, @Ratings8, @Ratings9, @Ratings10, @Ratings11, @Ratings12, @Ratings13, @Ratings14, @Ratings15, @Ratings16
    where not exists (select 1 from Games g where g.matchid = @match);


问:
Any utility which can print out map quickly
I am wondering any utility to print out map quickly for debugging purpose.</p>

答:
```<code>public final class Foo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        System.out.println(map);
    }
}
</code>```

Output:

```<code>{key2=value2, key1=value1}
</code>```

Body:
public final class Foo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        System.out.println(map);
    }
}

Output:

{key2=value2, key1=value1}


问:
How to create a copy of sheet in a target folder
I have a script which creates a copy of the sheets file in the root folder itself but I would prefer the new file to be placed into a different folder, and also to pop up to indicate the new file has been created, the new file name should only end with a date stamp (DD/MM/YYYY) no time stamp required.

I have added the target folder id in the
drive.makeCopy(fileName, 'Taget location id');
and this does not work

```<code>function dialog() {
    var data = '<input type="button" value="Create A Copy" onclick="google.script.run.withSuccessHandler(openfile).copyDoc();"><script>function openfile(url) {window.open(url);}</script>';
    var html = HtmlService.createHtmlOutput(data);
    SpreadsheetApp.getUi().showModalDialog(html, 'New Form - Click here');
}
function copyDoc() {
    var drive=DriveApp.getFileById('fileid');
    var timestamp = new Date().toISOString().replace("T", " ").split(".")[0];
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var file = DriveApp.getFileById(ss.getId());
    var fileName = ('filename - '+timestamp);
    drive.makeCopy(fileName);
}
</code>```

答:
If you want to copy file to an exact location, you should specify the destination argument when invoking .makeCopy() method and the destination must be a Folder instance, not its Id. Furthermore, if you want to then open a file, your server-side function should explicitly return something (in your case, a file Url).

Just modify your code a bit at the end:

```<code>var destination = DriveApp.getFolderById('yourFolderId');
var copy = drive.makeCopy(fileName,destination);
return copy.getUrl();
</code>```

Btw, it is best practice nowadays to add event listeners programmatically:

```<code>function openfile(url) {
  window.open(url);
}

var input = document.querySelector('input[type=button]');
    input.addEventListener('click',function(event){
      google.script.run.withSuccessHandler(openfile).copyDoc();
    });
</code>```

Body:
I have a script which creates a copy of the sheets file in the root folder itself but I would prefer the new file to be placed into a different folder, and also to pop up to indicate the new file has been created, the new file name should only end with a date stamp (DD/MM/YYYY) no time stamp required.

I have added the target folder id in the
drive.makeCopy(fileName, 'Taget location id');
and this does not work

function dialog() {
    var data = '<input type="button" value="Create A Copy" onclick="google.script.run.withSuccessHandler(openfile).copyDoc();">';
    var html = HtmlService.createHtmlOutput(data);
    SpreadsheetApp.getUi().showModalDialog(html, 'New Form - Click here');
}
function copyDoc() {
    var drive=DriveApp.getFileById('fileid');
    var timestamp = new Date().toISOString().replace("T", " ").split(".")[0];
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var file = DriveApp.getFileById(ss.getId());
    var fileName = ('filename - '+timestamp);
    drive.makeCopy(fileName);
}

Body:
If you want to copy file to an exact location, you should specify the destination argument when invoking .makeCopy() method and the destination must be a Folder instance, not its Id. Furthermore, if you want to then open a file, your server-side function should explicitly return something (in your case, a file Url).

Just modify your code a bit at the end:

var destination = DriveApp.getFolderById('yourFolderId');
var copy = drive.makeCopy(fileName,destination);
return copy.getUrl();

Btw, it is best practice nowadays to add event listeners programmatically:

function openfile(url) {
  window.open(url);
}

var input = document.querySelector('input[type=button]');
    input.addEventListener('click',function(event){
      google.script.run.withSuccessHandler(openfile).copyDoc();
    });


问:
How to print <incomplete type> variable in gdb
Sometimes gdb prints "incomplete type" for some type of variables. What does this mean and how can we see that value?</p>

答:
Disclaimer: I'm a Python developer with only some minimum knowledge of C++ and how Linux OS functions, so what I describe below is just my solution to a problem I personally experienced.

If you trying to work with types coming from 3rd party libraries, make sure those libraries aren't missing debug info.

Example

```<code>(gdb) info share Qt
From                To                  Syms Read   Shared Object Library
0x00007ffff5336080  0x00007ffff56ba585  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
0x00007ffff4ad3510  0x00007ffff4ef0cbe  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5
0x00007ffff47829c0  0x00007ffff47e1ba1  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5
0x00007ffff40bb5e0  0x00007ffff439dd92  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
0x00007ffff2e581e0  0x00007ffff2e78e4f  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5
0x00007ffff28c8a00  0x00007ffff29d9999  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Network.so.5
0x00007ffff2251750  0x00007ffff2252a46  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5X11Extras.so.5
0x00007ffff1cc9f80  0x00007ffff1cfc861  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5PrintSupport.so.5
0x00007fffee269c10  0x00007fffee297b57  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Svg.so.5
0x00007fffed987560  0x00007fffed98b6a8  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5TextToSpeech.so.5
0x00007fffe980e130  0x00007fffe9900c0c  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5XcbQpa.so.5
0x00007fffe69ef650  0x00007fffe69ffe0d  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5QuickControls2.so.5
0x00007fffe5c0f890  0x00007fffe5eae1c1  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5
0x00007fffe5522690  0x00007fffe581f636  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Qml.so.5
0x00007fffe51996b0  0x00007fffe5221363  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5QuickTemplates2.so.5
(*): Shared library is missing debugging information.
</code>```

^ all Qt libraries in current example are missing debug info. This is because debug info for qt libs are coming in separate packages, which are not being installed.

Whenever I did whatis everything worked fine:

```<code>(gdb) whatis e
type = QEvent *
</code>```

but when I tried to access it's members

```<code>(gdb) p e->type()
Couldn't find method QEvent::type
</code>```

and trying to get detailed type description

```<code>(gdb) ptype e
type = class QEvent {
  <incomplete type>
} *
</code>```

Solution (for Qt on Ubuntu)

Find to which package within your OS distribution does the file belongs

```<code>$ dpkg -S /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
libqt5core5a:amd64: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
</code>```

Search for related packages

Search with keywork libqt5core5a returned 2 packages, one is libqt5core5a itself, and another is libqt5core5a-dbgsym. Description for the latter says: "debug symbols for libqt5core5a"

Install packages with debug symbols (I also installed debug symbols for some other essential Qt libraries)

```<code>$ sudo apt install libqt5core5a-dbgsym libqt5widgets5-dbgsym libqt5gui5-dbgsym
</code>```

Make sure in gdb that libraries now have debug info

```<code>(gdb) info share Qt
From                To                  Syms Read   Shared Object Library
0x00007ffff5336080  0x00007ffff56ba585  Yes         /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
0x00007ffff4ad3510  0x00007ffff4ef0cbe  Yes         /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5
0x00007ffff47829c0  0x00007ffff47e1ba1  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5
0x00007ffff40bb5e0  0x00007ffff439dd92  Yes         /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
0x00007ffff2e571e0  0x00007ffff2e77e4f  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5
0x00007ffff28c7a00  0x00007ffff29d8999  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Network.so.5
0x00007ffff2250750  0x00007ffff2251a46  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5X11Extras.so.5
0x00007ffff1cc8f80  0x00007ffff1cfb861  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5PrintSupport.so.5
0x00007fffee268c10  0x00007fffee296b57  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Svg.so.5
0x00007fffed985560  0x00007fffed9896a8  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5TextToSpeech.so.5
0x00007fffe95fc130  0x00007fffe96eec0c  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5XcbQpa.so.5
0x00007fffe701f650  0x00007fffe702fe0d  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5QuickControls2.so.5
0x00007fffe623c890  0x00007fffe64db1c1  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5
0x00007fffe5b4f690  0x00007fffe5e4c636  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Qml.so.5
0x00007fffe57c66b0  0x00007fffe584e363  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5QuickTemplates2.so.5
(*): Shared library is missing debugging information.
</code>```

Now working with Qt types works as expected

```<code>(gdb) p e->type()
$4 = QEvent::Paint
(gdb) ptype e
type = class QEvent {
  public:
...
}
</code>```

OwnerDisplayName: grigy

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: grigy

Body:
Disclaimer: I'm a Python developer with only some minimum knowledge of C++ and how Linux OS functions, so what I describe below is just my solution to a problem I personally experienced.

If you trying to work with types coming from 3rd party libraries, make sure those libraries aren't missing debug info.

Example

(gdb) info share Qt
From                To                  Syms Read   Shared Object Library
0x00007ffff5336080  0x00007ffff56ba585  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
0x00007ffff4ad3510  0x00007ffff4ef0cbe  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5
0x00007ffff47829c0  0x00007ffff47e1ba1  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5
0x00007ffff40bb5e0  0x00007ffff439dd92  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
0x00007ffff2e581e0  0x00007ffff2e78e4f  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5
0x00007ffff28c8a00  0x00007ffff29d9999  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Network.so.5
0x00007ffff2251750  0x00007ffff2252a46  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5X11Extras.so.5
0x00007ffff1cc9f80  0x00007ffff1cfc861  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5PrintSupport.so.5
0x00007fffee269c10  0x00007fffee297b57  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Svg.so.5
0x00007fffed987560  0x00007fffed98b6a8  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5TextToSpeech.so.5
0x00007fffe980e130  0x00007fffe9900c0c  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5XcbQpa.so.5
0x00007fffe69ef650  0x00007fffe69ffe0d  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5QuickControls2.so.5
0x00007fffe5c0f890  0x00007fffe5eae1c1  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5
0x00007fffe5522690  0x00007fffe581f636  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Qml.so.5
0x00007fffe51996b0  0x00007fffe5221363  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5QuickTemplates2.so.5
(*): Shared library is missing debugging information.

^ all Qt libraries in current example are missing debug info. This is because debug info for qt libs are coming in separate packages, which are not being installed.

Whenever I did whatis everything worked fine:

(gdb) whatis e
type = QEvent *

but when I tried to access it's members

(gdb) p e->type()
Couldn't find method QEvent::type

and trying to get detailed type description

(gdb) ptype e
type = class QEvent {
  <incomplete type>
} *

Solution (for Qt on Ubuntu)

Find to which package within your OS distribution does the file belongs

$ dpkg -S /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
libqt5core5a:amd64: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5

Search for related packages

Search with keywork libqt5core5a returned 2 packages, one is libqt5core5a itself, and another is libqt5core5a-dbgsym. Description for the latter says: "debug symbols for libqt5core5a"

Install packages with debug symbols (I also installed debug symbols for some other essential Qt libraries)

$ sudo apt install libqt5core5a-dbgsym libqt5widgets5-dbgsym libqt5gui5-dbgsym

Make sure in gdb that libraries now have debug info

(gdb) info share Qt
From                To                  Syms Read   Shared Object Library
0x00007ffff5336080  0x00007ffff56ba585  Yes         /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
0x00007ffff4ad3510  0x00007ffff4ef0cbe  Yes         /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5
0x00007ffff47829c0  0x00007ffff47e1ba1  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5
0x00007ffff40bb5e0  0x00007ffff439dd92  Yes         /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
0x00007ffff2e571e0  0x00007ffff2e77e4f  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5
0x00007ffff28c7a00  0x00007ffff29d8999  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Network.so.5
0x00007ffff2250750  0x00007ffff2251a46  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5X11Extras.so.5
0x00007ffff1cc8f80  0x00007ffff1cfb861  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5PrintSupport.so.5
0x00007fffee268c10  0x00007fffee296b57  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Svg.so.5
0x00007fffed985560  0x00007fffed9896a8  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5TextToSpeech.so.5
0x00007fffe95fc130  0x00007fffe96eec0c  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5XcbQpa.so.5
0x00007fffe701f650  0x00007fffe702fe0d  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5QuickControls2.so.5
0x00007fffe623c890  0x00007fffe64db1c1  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5
0x00007fffe5b4f690  0x00007fffe5e4c636  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5Qml.so.5
0x00007fffe57c66b0  0x00007fffe584e363  Yes (*)     /usr/lib/x86_64-linux-gnu/libQt5QuickTemplates2.so.5
(*): Shared library is missing debugging information.

Now working with Qt types works as expected

(gdb) p e->type()
$4 = QEvent::Paint
(gdb) ptype e
type = class QEvent {
  public:
...
}


问:
VS Code -- Are there user/support forums or an IRC channel?
There seem to be multiple places to ask questions, report bugs, feature requests, etc.  Here, Github, MSDN.  It's kind of all over the place.  Are there any README documents that I'm missing that discuss support options?

答:
there appear to be 3 separate VSCode support channels on freenode, i ordered them by apparent population:

irc://irc.freenode.net/#VSCode (24 people connected as of writing)

irc://irc.freenode.net/##vs-code (22 people connected as of writing)

irc://irc.freenode.net/##VSCode (10 people connected as of writing)

as of writing means: 2019-05-26T12:40:21+00:00 (ISO 8601)


问:
Time of the day greeting code won't work in a am/pm format
Yea so the problem is simple and I assume the solution should also be simple but I am a complete newb so no clue how it works. The code below won't work if the source of the time is in an am pm format, any idea how to make it work in both cases?</p>

```<code>var today = new Date ();
var hourNow = today.getHours();
var greeting;

if (hourNow > 18) {
  greeting = 'Good Evening!';
} else if (hourNow > 12) {
  greeting = 'Good Afternoon!';
} else if (hourNow > 0) {
  greeting = 'Good morning!';
} else {
  greeting = 'Welcome!';
}

document.write('<h1>' + greeting + '</h1>');
</code>```

答:
As Turbo has commented, Date object doesn't store data in AM/PM format, so your code must work everywhere, and I tested in browser its working for me.</p>

```<code>var today = new Date ();
console.log(today);       // Sun May 26 2019 18:04:28 GMT+0530 (India Standard Time)
var hourNow = today.getHours();
console.log(hourNow);     // 18
</code>```

Body:
Yea so the problem is simple and I assume the solution should also be simple but I am a complete newb so no clue how it works. The code below won't work if the source of the time is in an am pm format, any idea how to make it work in both cases?

var today = new Date ();
var hourNow = today.getHours();
var greeting;

if (hourNow > 18) {
  greeting = 'Good Evening!';
} else if (hourNow > 12) {
  greeting = 'Good Afternoon!';
} else if (hourNow > 0) {
  greeting = 'Good morning!';
} else {
  greeting = 'Welcome!';
}

document.write('
' + greeting + '
');

Body:
As Turbo has commented, Date object doesn't store data in AM/PM format, so your code must work everywhere, and I tested in browser its working for me.

var today = new Date ();
console.log(today);       // Sun May 26 2019 18:04:28 GMT+0530 (India Standard Time)
var hourNow = today.getHours();
console.log(hourNow);     // 18


问:
How to check if a DataBase exist or not after the connection is made JAVA
I have a big question...
I have a database java program creation.

I want to know if the database exists or not, and the if exists just connect, if not to create it.

I tried this one:

```<code>if (dbName.exists() == false) {}
</code>```

THIS IS ALL THE CODE...

```<code>Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC driver loaded ok.");
</code>```

THIS IS A BACKUP CODE FOR IT, JUST TO WORK FOR NOW....
PARTIAL CODE THAT WORKS !

```<code>conn = DriverManager.getConnection(DBurl + url
+ "?createDatabaseIfNotExist=true& + "
+ "useUnicode=true&characterEncoding=utf-8&user="
+ userName + "&&password=" + password);

System.out.println("Connected to database ");
System.out.println("Connected to the database " + url);
</code>```

BUT I WANT SOMETHING LIKE:

```<code>FILE dbName = new FILE (url);
Statement stmt = new Statement;

if (dbName.exists() == true)
   System.out.println("Database exists ! Connecting ... ");
else {
   String sql = "CREATE DATABASE "+url;
   stmt.executeUpdate (sql);
}
</code>```

I don't want to put the url with the password and username in the same place... because they are provided from an external part, but that is allready implemented and working.

So I want to rip in 2 peaces, 1 Connect "jdbc:mysql://localhost:3306/"; WITHOUT URL which is the database NAME ...
AND THEN IF A DATABASE DOES NOT EXISTS THERE WITH THAT NAME JUST CREATE ON.

It is not working.... not entering in the else more, and says that Exeption Database already exists.

Thanks you very much.

答:
```<code>try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "admin");
        Statement statement = connection.createStatement();
        String sql = "CREATE DATABASE IF NOT EXISTS DBNAME";
        statement.executeUpdate(sql);
    } catch (ClassNotFoundException | SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

Kindly Note a Two things

The new driver class is `com.mysql.cj.jdbc.Driver'

The query CREATE DATABASE IF NOT EXISTS DBNAME means you dont have to check if database exits

Body:
I have a big question...
I have a database java program creation.

I want to know if the database exists or not, and the if exists just connect, if not to create it.

I tried this one:

if (dbName.exists() == false) {}

THIS IS ALL THE CODE...

Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC driver loaded ok.");

THIS IS A BACKUP CODE FOR IT, JUST TO WORK FOR NOW....
PARTIAL CODE THAT WORKS !

conn = DriverManager.getConnection(DBurl + url
+ "?createDatabaseIfNotExist=true& + "
+ "useUnicode=true&characterEncoding=utf-8&user="
+ userName + "&&password=" + password);

System.out.println("Connected to database ");
System.out.println("Connected to the database " + url);

BUT I WANT SOMETHING LIKE:

FILE dbName = new FILE (url);
Statement stmt = new Statement;

if (dbName.exists() == true)
   System.out.println("Database exists ! Connecting ... ");
else {
   String sql = "CREATE DATABASE "+url;
   stmt.executeUpdate (sql);
}

I don't want to put the url with the password and username in the same place... because they are provided from an external part, but that is allready implemented and working.

So I want to rip in 2 peaces, 1 Connect "jdbc:mysql://localhost:3306/"; WITHOUT URL which is the database NAME ...
AND THEN IF A DATABASE DOES NOT EXISTS THERE WITH THAT NAME JUST CREATE ON.

It is not working.... not entering in the else more, and says that Exeption Database already exists.

Thanks you very much.

Body:
try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "admin");
        Statement statement = connection.createStatement();
        String sql = "CREATE DATABASE IF NOT EXISTS DBNAME";
        statement.executeUpdate(sql);
    } catch (ClassNotFoundException | SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Kindly Note a Two things

The new driver class is `com.mysql.cj.jdbc.Driver'

The query CREATE DATABASE IF NOT EXISTS DBNAME means you dont have to check if database exits


问:
Message (alert) asking for confirmation
I'm beginner in JS.

I have this code:

```<code>            var fileLimit = parseInt(1);

            function refreshFileList() {
                $(".dz-preview").remove();
                $.ajax({
                    url: 'http://test/admin/showFilesDJS?type=SplashImage&id=1',
                    type: 'get',
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    },
                    cache: false,
                    success: function (response) {

                        $.each(response, function (key, value) {
                            var mockFile = {
                                name: value.name,
                                size: value.size
                            };
                            dpzMultipleFiles.emit('addedfile', mockFile);
                            dpzMultipleFiles.emit('thumbnail', mockFile, value.path);
                            dpzMultipleFiles.emit('complete', mockFile)
                        })
                    },
                    error: function (response) {
                        alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                    }
                });
            }

            Dropzone.options.dpzMultipleFiles =
                {
                    maxFiles: fileLimit,
                    clickable: true,
                    thumbnailWidth: 250,
                    thumbnailHeight: 250,
                    autoProcessQueue: true,
                    dictDefaultMessage: '',
                    uploadMultiple: true,
                    paramName: "myFile",
                    acceptedFiles: ".jpg,.jpeg",
                    addRemoveLinks: true,
                    timeout: 50000,
                    dictRemoveFile: 'Usuń plik',

                    init: function () {
                        dpzMultipleFiles = this;
                        refreshFileList();

                        this.on("thumbnail", function (file, dataUrl) {
                            $('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
                        }),

                            this.on('completemultiple', function (file, json) {
                                //$('.sortable').sortable('enable');
                            });
                        this.on('success', function (file, json) {
                            //alert('aa');
                        });

                        this.on('addedfile', function (file) {
                            fileLimit = fileLimit - 1;
                        });

                        this.on('drop', function (file) {
                            fileLimit = fileLimit + 1;
                        });

                        this.on("maxfilesexceeded", function (file) {
                            alert('Plik ' + file.name + ' nie został wysłany na serwer. Limit plików został przekroczony!')
                            this.removeFile(file);
                        });
                    },

                    removedfile: function (file) {
                        $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                            },
                            cache: false,
                            type: 'POST',
                            url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
                            data: {filename: file.name, id: file.name, type: 'SplashImage'},
                            success: function (data) {
                                console.log("File has been successfully removed!!");
                                //refreshFileList();
                            },
                            error: function (e) {
                                console.log(e);
                            }
                        });

                        var fileRef;
                        return (fileRef = file.previewElement) != null ?
                            fileRef.parentNode.removeChild(file.previewElement) : void 0;
                    }
                };
            $(function () {
                $(".dropzone").sortable({
                    items: '.dz-preview',
                    cursor: 'move',
                    opacity: 0.5,
                    containment: '.dropzone',
                    distance: 20,
                    tolerance: 'pointer',
                    update: function (event, ui) {
                        $(".dz-filename span").each(function (index) {
                            $.ajax({
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                                },
                                url: 'http://test/admin/changeOrderFilesDJS?type=SplashImage&id=1&index='+index+'&file='+ $(this).text(),
                                dataType: 'text',
                                type: 'post',
                                cache: false,
                                data: $(this).serialize(),
                                success: function (data, textStatus, jQxhr) {
                                },
                                error: function (jqXhr, textStatus, errorThrown) {
                                    alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                                }
                            });
                        });
                    }
                });
            });
</code>```

This is Dropzone.JS. This code work fine.

I would like to add after clicking on the button remove (usuń plik) - the question: do you really want to delete this file? Only after clicking on YES the file would be deleted.

How to do it? I need a simple alert with a question in JS

答:
You can use bootstrap modal for the confirmation that you want to ask.
the link is here</p>

Title: Message (alert) asking for confirmation

Body:
I'm beginner in JS.

I have this code:

            var fileLimit = parseInt(1);

            function refreshFileList() {
                $(".dz-preview").remove();
                $.ajax({
                    url: 'http://test/admin/showFilesDJS?type=SplashImage&id=1',
                    type: 'get',
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    },
                    cache: false,
                    success: function (response) {

                        $.each(response, function (key, value) {
                            var mockFile = {
                                name: value.name,
                                size: value.size
                            };
                            dpzMultipleFiles.emit('addedfile', mockFile);
                            dpzMultipleFiles.emit('thumbnail', mockFile, value.path);
                            dpzMultipleFiles.emit('complete', mockFile)
                        })
                    },
                    error: function (response) {
                        alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                    }
                });
            }

            Dropzone.options.dpzMultipleFiles =
                {
                    maxFiles: fileLimit,
                    clickable: true,
                    thumbnailWidth: 250,
                    thumbnailHeight: 250,
                    autoProcessQueue: true,
                    dictDefaultMessage: '',
                    uploadMultiple: true,
                    paramName: "myFile",
                    acceptedFiles: ".jpg,.jpeg",
                    addRemoveLinks: true,
                    timeout: 50000,
                    dictRemoveFile: 'Usuń plik',

                    init: function () {
                        dpzMultipleFiles = this;
                        refreshFileList();

                        this.on("thumbnail", function (file, dataUrl) {
                            $('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
                        }),

                            this.on('completemultiple', function (file, json) {
                                //$('.sortable').sortable('enable');
                            });
                        this.on('success', function (file, json) {
                            //alert('aa');
                        });

                        this.on('addedfile', function (file) {
                            fileLimit = fileLimit - 1;
                        });

                        this.on('drop', function (file) {
                            fileLimit = fileLimit + 1;
                        });

                        this.on("maxfilesexceeded", function (file) {
                            alert('Plik ' + file.name + ' nie został wysłany na serwer. Limit plików został przekroczony!')
                            this.removeFile(file);
                        });
                    },

                    removedfile: function (file) {
                        $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                            },
                            cache: false,
                            type: 'POST',
                            url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
                            data: {filename: file.name, id: file.name, type: 'SplashImage'},
                            success: function (data) {
                                console.log("File has been successfully removed!!");
                                //refreshFileList();
                            },
                            error: function (e) {
                                console.log(e);
                            }
                        });

                        var fileRef;
                        return (fileRef = file.previewElement) != null ?
                            fileRef.parentNode.removeChild(file.previewElement) : void 0;
                    }
                };
            $(function () {
                $(".dropzone").sortable({
                    items: '.dz-preview',
                    cursor: 'move',
                    opacity: 0.5,
                    containment: '.dropzone',
                    distance: 20,
                    tolerance: 'pointer',
                    update: function (event, ui) {
                        $(".dz-filename span").each(function (index) {
                            $.ajax({
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                                },
                                url: 'http://test/admin/changeOrderFilesDJS?type=SplashImage&id=1&index='+index+'&file='+ $(this).text(),
                                dataType: 'text',
                                type: 'post',
                                cache: false,
                                data: $(this).serialize(),
                                success: function (data, textStatus, jQxhr) {
                                },
                                error: function (jqXhr, textStatus, errorThrown) {
                                    alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                                }
                            });
                        });
                    }
                });
            });

This is Dropzone.JS. This code work fine.

I would like to add after clicking on the button remove (usuń plik) - the question: do you really want to delete this file? Only after clicking on YES the file would be deleted.

How to do it? I need a simple alert with a question in JS


问:
Javascript program to automate task
I am trying to automate a tedious task we do at my current job. We have a website we use to process customer orders and every day, we have to print out papers and force orders over so they can be processed.

I had done it before using Python and the Selenium Webdriver but that stopped working because they upgraded the PCs (and I would like to try utilizing Javascript instead now since it's built into the web browsers (was previously running the script off a flash drive that had python installed on it). I've figured out most of the basic stuff, but I'm having trouble finding answers to how this can be done.

I need to be able to run the script easily (not just me but my coworkers as well when I'm not there and they're all not very knowledgeable in this stuff).

Is it possible to actually write a Javascript script that can be run and automate this task? The website does require us to login. With Pytbon, I used a GUI form where the user would type in their username, password, and a day of the week and it would take those values and just login and navigate the pages, "clicking" everything for us and printing. Would prefer to be able to do it in Internet Explorer because that's what the website we use is optimized for (chrome has weird side effects when the paperwork is printed).

Thanks to anyone who can give me some advice, suggestions, or even links to other resources that could help.

答:
If you have a browser window open you can simply do something like this:

```<code>setInterval(() => {
 // automation logic goes here

// get current date

// get DOM elements

// simulate inputs and clicks

}, 1000 * 60 * 60 * 24);
</code>```

This will run once every 24h.

Title: Javascript program to automate task

Body:
If you have a browser window open you can simply do something like this:

setInterval(() => {
 // automation logic goes here

// get current date

// get DOM elements

// simulate inputs and clicks

}, 1000 * 60 * 60 * 24);

This will run once every 24h.


问:
c#.net function
```<code>namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}
</code>```

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

答:
Methods don't work like that in C#. The middle bit needs to look like this</p>

```<code>static void Main(string[] args)
{
    int result = AddNumbers(10, 5);
    Console.WriteLine(result);
}
public static int AddNumbers(int number1, int number2)
{
    return number1 + number2;
}
</code>```

Title: c#.net function

Body:
namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

Body:
Methods don't work like that in C#. The middle bit needs to look like this

static void Main(string[] args)
{
    int result = AddNumbers(10, 5);
    Console.WriteLine(result);
}
public static int AddNumbers(int number1, int number2)
{
    return number1 + number2;
}


问:
Can you run a background iBeacon/Eddystone scan in web-bluetooth using a service worker?
With the release of new web-bluetooth features, I believe iBeacon/Eddystone beacon scanning is possible in PWAs using web-bluetooth. I am running a use-case and I would like some help on achieving a background service worker, which scans for beacons in background using chrome service-workers or something similar in smartphones?

Is this possible and if yes how?

答:
According to the Chrome feature status page, the Web Bluetooth scanning feature has not been implemented at all as of May 2019.  This makes it impossible to scan for beacons: https://github.com/WebBluetoothCG/web-bluetooth/blob/master/implementation-status.md#scanning-api

There are other APIs implemented that let you find and connect to Bluetooth devices, but because you cannot see and decode the advertisements (what the above unimplemented API would provide), you cannot use them as beacons.