问:
Horizontal scrollbar doesn't appear when container width is more than device width
I have started an advanced CSS course on edx.org which is provided by Microsoft. While doing module 1, I am not able to comprehend why the horizontal scrollbar is not appearing when the container width is more than the device width. Also, why the sections have automatic 100% width. Why is container width is given in pixels rather then % to make the layout responsive?

Help would be highly appreciated.

/***************************
****************************
Reset Styles
****************************
***************************/

/*! normalize.css v4.1.1 | MIT License | github.com/necolas/normalize.css */

/**
 * 1. Change the default font family in all browsers (opinionated).
 * 2. Prevent adjustments of font size after orientation changes in IE and iOS.
 */

html {
  font-family: sans-serif;
  /* 1 */
  -ms-text-size-adjust: 100%;
  /* 2 */
  -webkit-text-size-adjust: 100%;
  /* 2 */
}

/**
 * Remove the margin in all browsers (opinionated).
 */

body {
  margin: 0;
}

/* HTML5 display definitions
   ========================================================================== */

/**
 * Add the correct display in IE 9-.
 * 1. Add the correct display in Edge, IE, and Firefox.
 * 2. Add the correct display in IE.
 */

article,
aside,
details,

/* 1 */

figcaption,
figure,
footer,
header,
main,

/* 2 */

menu,
nav,
section,
summary {
  /* 1 */
  display: block;
}

/**
 * Add the correct display in IE 9-.
 */

audio,
canvas,
progress,
video {
  display: inline-block;
}

/**
 * Add the correct display in iOS 4-7.
 */

audio:not([controls]) {
  display: none;
  height: 0;
}

/**
 * Add the correct vertical alignment in Chrome, Firefox, and Opera.
 */

progress {
  vertical-align: baseline;
}

/**
 * Add the correct display in IE 10-.
 * 1. Add the correct display in IE.
 */

template,

/* 1 */

[hidden] {
  display: none;
}

/* Links
   ========================================================================== */

/**
 * 1. Remove the gray background on active links in IE 10.
 * 2. Remove gaps in links underline in iOS 8+ and Safari 8+.
 */

a {
  background-color: transparent;
  /* 1 */
  -webkit-text-decoration-skip: objects;
  /* 2 */
}

/**
 * Remove the outline on focused links when they are also active or hovered
 * in all browsers (opinionated).
 */

a:active,
a:hover {
  outline-width: 0;
}

/* Text-level semantics
   ========================================================================== */

/**
 * 1. Remove the bottom border in Firefox 39-.
 * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
 */

abbr[title] {
  border-bottom: none;
  /* 1 */
  text-decoration: underline;
  /* 2 */
  text-decoration: underline dotted;
  /* 2 */
}

/**
 * Prevent the duplicate application of `bolder` by the next rule in Safari 6.
 */

b,
strong {
  font-weight: inherit;
}

/**
 * Add the correct font weight in Chrome, Edge, and Safari.
 */

b,
strong {
  font-weight: bolder;
}

/**
 * Add the correct font style in Android 4.3-.
 */

dfn {
  font-style: italic;
}

/**
 * Correct the font size and margin on `h1` elements within `section` and
 * `article` contexts in Chrome, Firefox, and Safari.
 */

h1 {
  font-size: 2em;
  margin: 0.67em 0;
}

/**
 * Add the correct background and color in IE 9-.
 */

mark {
  background-color: #ff0;
  color: #000;
}

/**
 * Add the correct font size in all browsers.
 */

small {
  font-size: 80%;
}

/**
 * Prevent `sub` and `sup` elements from affecting the line height in
 * all browsers.
 */

sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -0.25em;
}

sup {
  top: -0.5em;
}

/* Embedded content
   ========================================================================== */

/**
 * Remove the border on images inside links in IE 10-.
 */

img {
  border-style: none;
}

/**
 * Hide the overflow in IE.
 */

svg:not(:root) {
  overflow: hidden;
}

/* Grouping content
   ========================================================================== */

/**
 * 1. Correct the inheritance and scaling of font size in all browsers.
 * 2. Correct the odd `em` font sizing in all browsers.
 */

code,
kbd,
pre,
samp {
  font-family: monospace, monospace;
  /* 1 */
  font-size: 1em;
  /* 2 */
}

/**
 * Add the correct margin in IE 8.
 */

figure {
  margin: 1em 40px;
}

/**
 * 1. Add the correct box sizing in Firefox.
 * 2. Show the overflow in Edge and IE.
 */

hr {
  box-sizing: content-box;
  /* 1 */
  height: 0;
  /* 1 */
  overflow: visible;
  /* 2 */
}

/* Forms
   ========================================================================== */

/**
 * 1. Change font properties to `inherit` in all browsers (opinionated).
 * 2. Remove the margin in Firefox and Safari.
 */

button,
input,
select,
textarea {
  font: inherit;
  /* 1 */
  margin: 0;
  /* 2 */
}

/**
 * Restore the font weight unset by the previous rule.
 */

optgroup {
  font-weight: bold;
}

/**
 * Show the overflow in IE.
 * 1. Show the overflow in Edge.
 */

button,
input {
  /* 1 */
  overflow: visible;
}

/**
 * Remove the inheritance of text transform in Edge, Firefox, and IE.
 * 1. Remove the inheritance of text transform in Firefox.
 */

button,
select {
  /* 1 */
  text-transform: none;
}

/**
 * 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
 *    controls in Android 4.
 * 2. Correct the inability to style clickable types in iOS and Safari.
 */

button,
html [type="button"],

/* 1 */

[type="reset"],
[type="submit"] {
  -webkit-appearance: button;
  /* 2 */
}

/**
 * Remove the inner border and padding in Firefox.
 */

button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
  border-style: none;
  padding: 0;
}

/**
 * Restore the focus styles unset by the previous rule.
 */

button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
  outline: 1px dotted ButtonText;
}

/**
 * Change the border, margin, and padding in all browsers (opinionated).
 */

fieldset {
  border: 1px solid #c0c0c0;
  margin: 0 2px;
  padding: 0.35em 0.625em 0.75em;
}

/**
 * 1. Correct the text wrapping in Edge and IE.
 * 2. Correct the color inheritance from `fieldset` elements in IE.
 * 3. Remove the padding so developers are not caught out when they zero out
 *    `fieldset` elements in all browsers.
 */

legend {
  box-sizing: border-box;
  /* 1 */
  color: inherit;
  /* 2 */
  display: table;
  /* 1 */
  max-width: 100%;
  /* 1 */
  padding: 0;
  /* 3 */
  white-space: normal;
  /* 1 */
}

/**
 * Remove the default vertical scrollbar in IE.
 */

textarea {
  overflow: auto;
}

/**
 * 1. Add the correct box sizing in IE 10-.
 * 2. Remove the padding in IE 10-.
 */

[type="checkbox"],
[type="radio"] {
  box-sizing: border-box;
  /* 1 */
  padding: 0;
  /* 2 */
}

/**
 * Correct the cursor style of increment and decrement buttons in Chrome.
 */

[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
  height: auto;
}

/**
 * 1. Correct the odd appearance in Chrome and Safari.
 * 2. Correct the outline style in Safari.
 */

[type="search"] {
  -webkit-appearance: textfield;
  /* 1 */
  outline-offset: -2px;
  /* 2 */
}

/**
 * Remove the inner padding and cancel buttons in Chrome and Safari on OS X.
 */

[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
}

/**
 * Correct the text style of placeholders in Chrome, Edge, and Safari.
 */

::-webkit-input-placeholder {
  color: inherit;
  opacity: 0.54;
}

/**
 * 1. Correct the inability to style clickable types in iOS and Safari.
 * 2. Change font properties to `inherit` in Safari.
 */

::-webkit-file-upload-button {
  -webkit-appearance: button;
  /* 1 */
  font: inherit;
  /* 2 */
}

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

/***************************
****************************
Base Styles
****************************
***************************/

body {
  color: #414042;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: normal;
}

h1,
h2,
h3 {
  font-weight: bold;
}

a {
  color: #8dc63f;
  font-weight: bold;
}

a:hover {
  text-decoration: underline;
}

/***************************
****************************
Layout Styles
****************************
***************************/

.container {
  padding-left: 15px;
  padding-right: 15px;
  margin-right: auto;
  margin-left: auto;
  max-width: 1170px;
}

.row {
  margin-right: -15px;
  margin-left: -15px;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

/***************************
****************************
Module Styles
****************************
***************************/

/***************************
****************************
Theme Styles
****************************
***************************/

.background-primary {
  background: #F7941E;
  /*Orange*/
}

.background-secondary {
  background: #00AEEF;
  /*Blue*/
}

.background-tertiary {
  background: #8DC63F;
  /*Green*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>title</title>
  <link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>

<body>
  <header class="background-primary">
    <div class="container">
      Header Content
    </div>
  </header>
  <main>
    <section class="background-secondary">
      <div class="container">
        Hero Primary Content
      </div>
    </section>
    <section>
      <div class="container">
        Image and Text Content
      </div>
    </section>
    <section>
      <div class="container">
        Featured Content
      </div>
    </section>
    <section class="background-primary">
      <div class="container">
        Testimonial Content
      </div>
    </section>
    <section class="background-secondary">
      <div class="container">Media Objects
      </div>
    </section>
    <section class="background-tertiary">
      <div class="container">
        More Content
      </div>
    </section>
  </main>
  <footer class="background-primary">
    <div class="container">
      Footer Content
    </div>
  </footer>
</body>

</html></code>```

答:
The horizontal scroll-bar is not appearing because there is no overflow. If you inspect the elements, you will see that the section elements take up 100% of the width of the screen.

The section elements take up 100% of the width since they are block level elements. This is how they behave.
Read here: https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements and here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section

The .container elements are not being given width, they are being given max-width: 1170px. This means that they will be "responsive" up to 1170px. Sometimes you want to keep the content of your app/page within a certain width - and not stretch out depending on the size of your device's screen.

Body:
I have started an advanced CSS course on edx.org which is provided by Microsoft. While doing module 1, I am not able to comprehend why the horizontal scrollbar is not appearing when the container width is more than the device width. Also, why the sections have automatic 100% width. Why is container width is given in pixels rather then % to make the layout responsive?

Help would be highly appreciated.

/***************************
****************************
Reset Styles
****************************
***************************/

/*! normalize.css v4.1.1 | MIT License | github.com/necolas/normalize.css */

/**
 * 1. Change the default font family in all browsers (opinionated).
 * 2. Prevent adjustments of font size after orientation changes in IE and iOS.
 */

html {
  font-family: sans-serif;
  /* 1 */
  -ms-text-size-adjust: 100%;
  /* 2 */
  -webkit-text-size-adjust: 100%;
  /* 2 */
}

/**
 * Remove the margin in all browsers (opinionated).
 */

body {
  margin: 0;
}

/* HTML5 display definitions
   ========================================================================== */

/**
 * Add the correct display in IE 9-.
 * 1. Add the correct display in Edge, IE, and Firefox.
 * 2. Add the correct display in IE.
 */

article,
aside,
details,

/* 1 */

figcaption,
figure,
footer,
header,
main,

/* 2 */

menu,
nav,
section,
summary {
  /* 1 */
  display: block;
}

/**
 * Add the correct display in IE 9-.
 */

audio,
canvas,
progress,
video {
  display: inline-block;
}

/**
 * Add the correct display in iOS 4-7.
 */

audio:not([controls]) {
  display: none;
  height: 0;
}

/**
 * Add the correct vertical alignment in Chrome, Firefox, and Opera.
 */

progress {
  vertical-align: baseline;
}

/**
 * Add the correct display in IE 10-.
 * 1. Add the correct display in IE.
 */

template,

/* 1 */

[hidden] {
  display: none;
}

/* Links
   ========================================================================== */

/**
 * 1. Remove the gray background on active links in IE 10.
 * 2. Remove gaps in links underline in iOS 8+ and Safari 8+.
 */

a {
  background-color: transparent;
  /* 1 */
  -webkit-text-decoration-skip: objects;
  /* 2 */
}

/**
 * Remove the outline on focused links when they are also active or hovered
 * in all browsers (opinionated).
 */

a:active,
a:hover {
  outline-width: 0;
}

/* Text-level semantics
   ========================================================================== */

/**
 * 1. Remove the bottom border in Firefox 39-.
 * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
 */

abbr[title] {
  border-bottom: none;
  /* 1 */
  text-decoration: underline;
  /* 2 */
  text-decoration: underline dotted;
  /* 2 */
}

/**
 * Prevent the duplicate application of `bolder` by the next rule in Safari 6.
 */

b,
strong {
  font-weight: inherit;
}

/**
 * Add the correct font weight in Chrome, Edge, and Safari.
 */

b,
strong {
  font-weight: bolder;
}

/**
 * Add the correct font style in Android 4.3-.
 */

dfn {
  font-style: italic;
}

/**
 * Correct the font size and margin on `h1` elements within `section` and
 * `article` contexts in Chrome, Firefox, and Safari.
 */

h1 {
  font-size: 2em;
  margin: 0.67em 0;
}

/**
 * Add the correct background and color in IE 9-.
 */

mark {
  background-color: #ff0;
  color: #000;
}

/**
 * Add the correct font size in all browsers.
 */

small {
  font-size: 80%;
}

/**
 * Prevent `sub` and `sup` elements from affecting the line height in
 * all browsers.
 */

sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -0.25em;
}

sup {
  top: -0.5em;
}

/* Embedded content
   ========================================================================== */

/**
 * Remove the border on images inside links in IE 10-.
 */

img {
  border-style: none;
}

/**
 * Hide the overflow in IE.
 */

svg:not(:root) {
  overflow: hidden;
}

/* Grouping content
   ========================================================================== */

/**
 * 1. Correct the inheritance and scaling of font size in all browsers.
 * 2. Correct the odd `em` font sizing in all browsers.
 */

code,
kbd,
pre,
samp {
  font-family: monospace, monospace;
  /* 1 */
  font-size: 1em;
  /* 2 */
}

/**
 * Add the correct margin in IE 8.
 */

figure {
  margin: 1em 40px;
}

/**
 * 1. Add the correct box sizing in Firefox.
 * 2. Show the overflow in Edge and IE.
 */

hr {
  box-sizing: content-box;
  /* 1 */
  height: 0;
  /* 1 */
  overflow: visible;
  /* 2 */
}

/* Forms
   ========================================================================== */

/**
 * 1. Change font properties to `inherit` in all browsers (opinionated).
 * 2. Remove the margin in Firefox and Safari.
 */

button,
input,
select,
textarea {
  font: inherit;
  /* 1 */
  margin: 0;
  /* 2 */
}

/**
 * Restore the font weight unset by the previous rule.
 */

optgroup {
  font-weight: bold;
}

/**
 * Show the overflow in IE.
 * 1. Show the overflow in Edge.
 */

button,
input {
  /* 1 */
  overflow: visible;
}

/**
 * Remove the inheritance of text transform in Edge, Firefox, and IE.
 * 1. Remove the inheritance of text transform in Firefox.
 */

button,
select {
  /* 1 */
  text-transform: none;
}

/**
 * 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
 *    controls in Android 4.
 * 2. Correct the inability to style clickable types in iOS and Safari.
 */

button,
html [type="button"],

/* 1 */

[type="reset"],
[type="submit"] {
  -webkit-appearance: button;
  /* 2 */
}

/**
 * Remove the inner border and padding in Firefox.
 */

button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
  border-style: none;
  padding: 0;
}

/**
 * Restore the focus styles unset by the previous rule.
 */

button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
  outline: 1px dotted ButtonText;
}

/**
 * Change the border, margin, and padding in all browsers (opinionated).
 */

fieldset {
  border: 1px solid #c0c0c0;
  margin: 0 2px;
  padding: 0.35em 0.625em 0.75em;
}

/**
 * 1. Correct the text wrapping in Edge and IE.
 * 2. Correct the color inheritance from `fieldset` elements in IE.
 * 3. Remove the padding so developers are not caught out when they zero out
 *    `fieldset` elements in all browsers.
 */

legend {
  box-sizing: border-box;
  /* 1 */
  color: inherit;
  /* 2 */
  display: table;
  /* 1 */
  max-width: 100%;
  /* 1 */
  padding: 0;
  /* 3 */
  white-space: normal;
  /* 1 */
}

/**
 * Remove the default vertical scrollbar in IE.
 */

textarea {
  overflow: auto;
}

/**
 * 1. Add the correct box sizing in IE 10-.
 * 2. Remove the padding in IE 10-.
 */

[type="checkbox"],
[type="radio"] {
  box-sizing: border-box;
  /* 1 */
  padding: 0;
  /* 2 */
}

/**
 * Correct the cursor style of increment and decrement buttons in Chrome.
 */

[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
  height: auto;
}

/**
 * 1. Correct the odd appearance in Chrome and Safari.
 * 2. Correct the outline style in Safari.
 */

[type="search"] {
  -webkit-appearance: textfield;
  /* 1 */
  outline-offset: -2px;
  /* 2 */
}

/**
 * Remove the inner padding and cancel buttons in Chrome and Safari on OS X.
 */

[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
}

/**
 * Correct the text style of placeholders in Chrome, Edge, and Safari.
 */

::-webkit-input-placeholder {
  color: inherit;
  opacity: 0.54;
}

/**
 * 1. Correct the inability to style clickable types in iOS and Safari.
 * 2. Change font properties to `inherit` in Safari.
 */

::-webkit-file-upload-button {
  -webkit-appearance: button;
  /* 1 */
  font: inherit;
  /* 2 */
}

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

/***************************
****************************
Base Styles
****************************
***************************/

body {
  color: #414042;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: normal;
}

h1,
h2,
h3 {
  font-weight: bold;
}

a {
  color: #8dc63f;
  font-weight: bold;
}

a:hover {
  text-decoration: underline;
}

/***************************
****************************
Layout Styles
****************************
***************************/

.container {
  padding-left: 15px;
  padding-right: 15px;
  margin-right: auto;
  margin-left: auto;
  max-width: 1170px;
}

.row {
  margin-right: -15px;
  margin-left: -15px;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

/***************************
****************************
Module Styles
****************************
***************************/

/***************************
****************************
Theme Styles
****************************
***************************/

.background-primary {
  background: #F7941E;
  /*Orange*/
}

.background-secondary {
  background: #00AEEF;
  /*Blue*/
}

.background-tertiary {
  background: #8DC63F;
  /*Green*/
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>title</title>
  <link rel="stylesheet" href="stylesheet.css" type="text/css">

      Header Content

        Hero Primary Content

        Image and Text Content

        Featured Content

        Testimonial Content

Media Objects

        More Content

      Footer Content


来源: stackexchange

问:
How do I check whether an agda term associated with a specific name relies on hole?
For the purpose of a script I would like to query the agda compiler about the definition of a function in an agda source file. I would like to ask the question: does the function named by X rely on a hole, or not? (i.e. is it a "completed proof", or is it a "proof in progress"). Where X is the name of the function in the source file.

For example, take the following example source file:

```<code>open import Relation.Binary.PropositionalEquality

postulate
  A : Set
  x : A
  y : A
  z : A
  q1 : x ≡ y
  q2 : y ≡ z

pf1 : x ≡ z
pf1 = trans q1 q2

pf2 : z ≡ x
pf2 rewrite q1 | q2 = refl
</code>```

I would like to be able to determine (in my script), does pf2 rely on any holes? In this case the answer is no.

Alternatively, suppose that file were something like:

```<code>open import Relation.Binary.PropositionalEquality

postulate
  A : Set
  x : A
  y : A
  z : A
  q1 : x ≡ y
  q2 : y ≡ z

pf1 : x ≡ z
pf1 = trans q1 q2

lemma1 : z ≡ y
lemma1 = {!!}

pf2 : z ≡ x
pf2 rewrite q1 = lemma1
</code>```

Now the answer to the question posed above is "yes": pf2 is incomplete because it relies on a hole (indirectly, through lemma1).

I know that I can find out the answer to the question: are there any functions in this agda source file that rely on holes. When we run the agda compiler on a source file, the return status will be 1 if there are "unsolved interaction metas", and the status will be 0 if everything is completed. However I would like to know the granular information of whether a particular function (by name) within a source file has "unsolved interaction metas".

Is there any way to do this?

I looked through the source code for the interaction mode of agda (the interface used by the agda-mode emacs code), but it seems most of the commands defined for the interaction mode rely on character ranges rather than symbols, so I haven't found a way to get this information from interaction mode.

EDIT: based on user3237465's comment, I looked into using reflection to solve this issue. It seems like it could work but there is an issue with rewrites. For example, suppose we have the following file loaded in emacs:

```<code>open import Relation.Binary.PropositionalEquality
open import Agda.Builtin.Reflection

postulate
  A : Set
  x : A
  y : A
  z : A
  q1 : x ≡ y
  q2 : y ≡ z

pf1 : x ≡ z
pf1 = trans q1 q2

lemma1 : z ≡ y
lemma1 = {!!}

pf2 : z ≡ x
pf2 rewrite q1 = lemma1

pf3 : z ≡ x
pf3 = trans lemma1 (sym q1)

-- user3237465 suggested this macro.
-- unfortunately, normalizing `test`
-- using this macro still doesn't show
-- information about the contents of
-- lemma1
macro
  actualQuote : Term -> Term -> TC _
  actualQuote term hole =
    bindTC (normalise term) λ nterm ->
    bindTC (quoteTC nterm) (unify hole)

test = actualQuote pf2
test2 = actualQuote pf3
test3 = actualQuote pf1
</code>```

If I type C-c C-n and enter quoteTC pf3, it outputs quoteTC (trans ?0 (sym q1)). This is what I wanted because it indicates that a the proof depends on a hole.

On the other hand, if I type C-c C-n and enter quoteTC pf2, it outputs quoteTC (pf2 | x | q1). So it appears that the normalization process can't see past a rewrite.

Does anyone know if there is a way around this?

EDIT2: the normalization of pf2 using user3237465's macro is:

```<code>def (quote .test4.rewrite-20)
(arg (arg-info visible relevant)
 (def (quote x) .Agda.Builtin.List.List.[])
 .Agda.Builtin.List.List.∷
 arg (arg-info visible relevant)
 (def (quote q1) .Agda.Builtin.List.List.[])
 .Agda.Builtin.List.List.∷ .Agda.Builtin.List.List.[])
</code>```

答:
This answer is about using reflection to solve the problem.

The thing missing from your attempt is using getDefinition to look inside defined functions.

Here's a complete example using agda-prelude (https://github.com/UlfNorell/agda-prelude) because I don't have time to figure out to do this with the standard library (exercise for the reader).

```<code>open import Prelude
open import Tactic.Reflection
open import Control.Monad.State
open import Container.Traversable
</code>```

We need to keep track of which names we have already looked inside to avoid looping on recursive functions, so let's use a state monad.

```<code>M = StateT (List Name) TC

runM : {A : Set} → M A → TC A
runM m = fst <$> runStateT m []

isVisited : Name → M Bool
isVisited x = gets (elem x)

setVisited : Name → M ⊤
setVisited x = _ <$ modify (x ∷_)

anyM : {A : Set} → (A → M Bool) → List A → M Bool
anyM p xs = foldr _||_ false <$> traverse p xs
</code>```

Unfortunately we're not going to be able to convince the termination checker that there can only be a finite number of defined functions, so let's cheat. The no-cheat option would be to set a depth limit and return true (or dont-know) if we run out of depth.

```<code>{-# TERMINATING #-}
anyMetas : Term → M Bool

checkClause : Clause → M Bool
checkClause (clause ps t) = anyMetas t
checkClause (absurd-clause ps) = return false

checkName : Name → M Bool
checkName f = do
  false ← isVisited f
    where true → return false
  function cs ← lift (getDefinition f)
    where _ → return false
  anyM checkClause cs
</code>```

I couldn't resist using do-notation for checkName since it makes the code so much nicer. If you're not building the latest Agda from github, you can use the commented code:

```<code>  -- caseM isVisited f of λ where
  --   true → return false
  --   false → setVisited f >>
  --     (caseM lift (getDefinition f) of λ where
  --       (function cs) → anyM checkClause cs
  --       _ → return false)
</code>```

```<code>anyMetaArgs = anyM (anyMetas ∘ unArg)

checkSort : Sort → M Bool
checkSort (set t) = anyMetas t
checkSort (lit n) = return false
checkSort unknown = return false

anyMetas (var x args) = anyMetaArgs args
anyMetas (con c args) = anyMetaArgs args
anyMetas (def f args) = (| checkName f || anyMetaArgs args |)
anyMetas (lam v t) = anyMetas (unAbs t)
anyMetas (pat-lam cs args) = (| anyM checkClause cs || anyMetaArgs args |)
anyMetas (pi a b) = (| anyMetas (unArg a) || anyMetas (unAbs b) |)
anyMetas (agda-sort s) = checkSort s
anyMetas (lit l) = return false
anyMetas (meta x x₁) = return true
anyMetas unknown = return false
</code>```

With the anyMetas function we can define a macro taking a name and returning a boolean indicating if the name depends on a meta.

```<code>macro
  dependsOnMeta? : Name → Term → TC ⊤
  dependsOnMeta? x hole = unify hole =<< quoteTC =<< runM (anyMetas (def x []))
</code>```

Your test case now goes through

```<code>postulate
  A : Set
  x : A
  y : A
  z : A
  q1 : x ≡ y
  q2 : y ≡ z

pf1 : x ≡ z
pf1 = trans q1 q2

lemma1 : z ≡ y
lemma1 = {!!}

pf2 : z ≡ x
pf2 rewrite q1 = lemma1

pf3 : z ≡ x
pf3 = trans lemma1 (sym q1)

test1 : dependsOnMeta? pf1 ≡ false
test1 = refl

test2 : dependsOnMeta? pf2 ≡ true
test2 = refl

test3 : dependsOnMeta? pf3 ≡ true
test3 = refl
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For the purpose of a script I would like to query the agda compiler about the definition of a function in an agda source file. I would like to ask the question: does the function named by X rely on a hole, or not? (i.e. is it a "completed proof", or is it a "proof in progress"). Where X is the name of the function in the source file.

For example, take the following example source file:

open import Relation.Binary.PropositionalEquality

postulate
  A : Set
  x : A
  y : A
  z : A
  q1 : x ≡ y
  q2 : y ≡ z

pf1 : x ≡ z
pf1 = trans q1 q2

pf2 : z ≡ x
pf2 rewrite q1 | q2 = refl

I would like to be able to determine (in my script), does pf2 rely on any holes? In this case the answer is no.

Alternatively, suppose that file were something like:

open import Relation.Binary.PropositionalEquality

postulate
  A : Set
  x : A
  y : A
  z : A
  q1 : x ≡ y
  q2 : y ≡ z

pf1 : x ≡ z
pf1 = trans q1 q2

lemma1 : z ≡ y
lemma1 = {!!}

pf2 : z ≡ x
pf2 rewrite q1 = lemma1

Now the answer to the question posed above is "yes": pf2 is incomplete because it relies on a hole (indirectly, through lemma1).

I know that I can find out the answer to the question: are there any functions in this agda source file that rely on holes. When we run the agda compiler on a source file, the return status will be 1 if there are "unsolved interaction metas", and the status will be 0 if everything is completed. However I would like to know the granular information of whether a particular function (by name) within a source file has "unsolved interaction metas".

Is there any way to do this?

I looked through the source code for the interaction mode of agda (the interface used by the agda-mode emacs code), but it seems most of the commands defined for the interaction mode rely on character ranges rather than symbols, so I haven't found a way to get this information from interaction mode.

EDIT: based on user3237465's comment, I looked into using reflection to solve this issue. It seems like it could work but there is an issue with rewrites. For example, suppose we have the following file loaded in emacs:

open import Relation.Binary.PropositionalEquality
open import Agda.Builtin.Reflection

postulate
  A : Set
  x : A
  y : A
  z : A
  q1 : x ≡ y
  q2 : y ≡ z

pf1 : x ≡ z
pf1 = trans q1 q2

lemma1 : z ≡ y
lemma1 = {!!}

pf2 : z ≡ x
pf2 rewrite q1 = lemma1

pf3 : z ≡ x
pf3 = trans lemma1 (sym q1)

-- user3237465 suggested this macro.
-- unfortunately, normalizing `test`
-- using this macro still doesn't show
-- information about the contents of
-- lemma1
macro
  actualQuote : Term -> Term -> TC _
  actualQuote term hole =
    bindTC (normalise term) λ nterm ->
    bindTC (quoteTC nterm) (unify hole)

test = actualQuote pf2
test2 = actualQuote pf3
test3 = actualQuote pf1

If I type C-c C-n and enter quoteTC pf3, it outputs quoteTC (trans ?0 (sym q1)). This is what I wanted because it indicates that a the proof depends on a hole.

On the other hand, if I type C-c C-n and enter quoteTC pf2, it outputs quoteTC (pf2 | x | q1). So it appears that the normalization process can't see past a rewrite.

Does anyone know if there is a way around this?

EDIT2: the normalization of pf2 using user3237465's macro is:

def (quote .test4.rewrite-20)
(arg (arg-info visible relevant)
 (def (quote x) .Agda.Builtin.List.List.[])
 .Agda.Builtin.List.List.∷
 arg (arg-info visible relevant)
 (def (quote q1) .Agda.Builtin.List.List.[])
 .Agda.Builtin.List.List.∷ .Agda.Builtin.List.List.[])

Body:
This answer is about using reflection to solve the problem.

The thing missing from your attempt is using getDefinition to look inside defined functions.

Here's a complete example using agda-prelude (https://github.com/UlfNorell/agda-prelude) because I don't have time to figure out to do this with the standard library (exercise for the reader).

open import Prelude
open import Tactic.Reflection
open import Control.Monad.State
open import Container.Traversable

We need to keep track of which names we have already looked inside to avoid looping on recursive functions, so let's use a state monad.

M = StateT (List Name) TC

runM : {A : Set} → M A → TC A
runM m = fst <$> runStateT m []

isVisited : Name → M Bool
isVisited x = gets (elem x)

setVisited : Name → M ⊤
setVisited x = _ <$ modify (x ∷_)

anyM : {A : Set} → (A → M Bool) → List A → M Bool
anyM p xs = foldr _||_ false <$> traverse p xs

Unfortunately we're not going to be able to convince the termination checker that there can only be a finite number of defined functions, so let's cheat. The no-cheat option would be to set a depth limit and return true (or dont-know) if we run out of depth.

{-# TERMINATING #-}
anyMetas : Term → M Bool

checkClause : Clause → M Bool
checkClause (clause ps t) = anyMetas t
checkClause (absurd-clause ps) = return false

checkName : Name → M Bool
checkName f = do
  false ← isVisited f
    where true → return false
  function cs ← lift (getDefinition f)
    where _ → return false
  anyM checkClause cs

I couldn't resist using do-notation for checkName since it makes the code so much nicer. If you're not building the latest Agda from github, you can use the commented code:

  -- caseM isVisited f of λ where
  --   true → return false
  --   false → setVisited f >>
  --     (caseM lift (getDefinition f) of λ where
  --       (function cs) → anyM checkClause cs
  --       _ → return false)

anyMetaArgs = anyM (anyMetas ∘ unArg)

checkSort : Sort → M Bool
checkSort (set t) = anyMetas t
checkSort (lit n) = return false
checkSort unknown = return false

anyMetas (var x args) = anyMetaArgs args
anyMetas (con c args) = anyMetaArgs args
anyMetas (def f args) = (| checkName f || anyMetaArgs args |)
anyMetas (lam v t) = anyMetas (unAbs t)
anyMetas (pat-lam cs args) = (| anyM checkClause cs || anyMetaArgs args |)
anyMetas (pi a b) = (| anyMetas (unArg a) || anyMetas (unAbs b) |)
anyMetas (agda-sort s) = checkSort s
anyMetas (lit l) = return false
anyMetas (meta x x₁) = return true
anyMetas unknown = return false

With the anyMetas function we can define a macro taking a name and returning a boolean indicating if the name depends on a meta.

macro
  dependsOnMeta? : Name → Term → TC ⊤
  dependsOnMeta? x hole = unify hole =<< quoteTC =<< runM (anyMetas (def x []))

Your test case now goes through

postulate
  A : Set
  x : A
  y : A
  z : A
  q1 : x ≡ y
  q2 : y ≡ z

pf1 : x ≡ z
pf1 = trans q1 q2

lemma1 : z ≡ y
lemma1 = {!!}

pf2 : z ≡ x
pf2 rewrite q1 = lemma1

pf3 : z ≡ x
pf3 = trans lemma1 (sym q1)

test1 : dependsOnMeta? pf1 ≡ false
test1 = refl

test2 : dependsOnMeta? pf2 ≡ true
test2 = refl

test3 : dependsOnMeta? pf3 ≡ true
test3 = refl


问:
Filter array by index and save it to another array
I´m trying to filter all values in name where id = 1 and save to an array.

This is the output I get from my WS:

[{id=1; name=Des Moines; }, {id=2; name=Cedar Rapids; }, {id=3; name=Yakima; },{id=4; name=Fort Dodge; }, {id=1; name=Iowa City; }]

if I try get property it splits my content.

Could anyone help me out on how to get the desire output?

答:
You can try something like the following
your json string must be like:

["items":{id=1; name=Des Moines; }, {id=2; name=Cedar Rapids; }, {id=3; name=Yakima; },{id=4; name=Fort Dodge; }, {id=1; name=Iowa City; }]

```<code>JSONObject jsonObject = null;
jsonObject = new JSONObject("your json string goes here!!");
String items = jsonObject.getString("items");
JSONArray array = new JSONArray(weather);
ArrayList<JSONObject > arrList = new ArrayList<JSONObject >();
for(int i = 0; i < array.length(); i++)
{
    JSONObject jsonObject1 = array.getJSONObject(i);
    arrList.add(jsonObject1 );
    String id = jsonObject1.get("id").toString();
    String name = jsonObject1.get("name").toString();

}
</code>```

Body:
You can try something like the following
your json string must be like:

["items":{id=1; name=Des Moines; }, {id=2; name=Cedar Rapids; }, {id=3; name=Yakima; },{id=4; name=Fort Dodge; }, {id=1; name=Iowa City; }]

JSONObject jsonObject = null;
jsonObject = new JSONObject("your json string goes here!!");
String items = jsonObject.getString("items");
JSONArray array = new JSONArray(weather);
ArrayList<JSONObject > arrList = new ArrayList<JSONObject >();
for(int i = 0; i < array.length(); i++)
{
    JSONObject jsonObject1 = array.getJSONObject(i);
    arrList.add(jsonObject1 );
    String id = jsonObject1.get("id").toString();
    String name = jsonObject1.get("name").toString();

}


问:
How do I do backups in MySQL?
How do I do backups in MySQL?

I'm hoping there'll be something better than just running mysqldump every "x" hours.

Is there anything like SQL Server has, where you can take a full backup each day, and then incrementals every hour, so if your DB dies you can restore up to the latest backup?

Something like the DB log, where as long as the log doesn't die, you can restore up to the  exact point where the DB died?

Also, how do these things affect locking?
I'd expect the online transactions to be locked for a while if I do a mysqldump.

答:
The problem with a straight backup of the mysql database folder is that the backup will not necessarily be consistent, unless you do a write-lock during the backup.

I run a script that iterates through all of the databases, doing a mysqldump and gzip on each to a backup folder, and then backup that folder to tape.

This, however, means that there is no such thing as incremental backups, since the nightly dump is a complete dump.  But I would argue that this could be a good thing, since a restore from a full backup will be a significantly quicker process than restoring from incrementals - and if you are backing up to tape, it will likely mean gathering a number of tapes before you can do a full restore.

In any case, whichever backup plan you go with, make sure to do a trial restore to ensure that it works, and get an idea of how long it might take, and exactly what the steps are that you need to go through.

OwnerDisplayName: Daniel Magliola

ContentLicense: CC BY-SA 2.5

Title: How do I do backups in MySQL?

LastEditorDisplayName: Thomas Owens

OwnerDisplayName: Brent Nesbitt


问:
Subversion - Async development cycle... two trunks?
Currently in our enterprise we have a situation that i think it's not very common, or at least i haven't found a similar case in Internet. My problem is that we have software that can evolve by more than one requirement, and both not necessarily will coincide in their release date.

We have a development cycle where all software is developed in a "DEV" environment, and then it's handled to SQA so it can be tested on "LAB" environment; if all works OK then this software is moved to "PROD" environment. The problem i am facing here is that i cant use a single trunk and i don't see how a single branch could work either.

For example, lets say i have requirements A and B, one to be released today and the other a week from today. Both have reached LAB environment but today's release to PROD environment only has to contain A, since B is not yet needed by our business users (and it cannot be released early because it would introduce some error's to others systems). Both requirements where developed in different branches (they respond to different needs). In this case my problem is that i can't have a single trunk where developers can merge to see both changes in "DEV" environment, and then use the same trunk to feed "LAB" environment since it would have source code not yet scheduled for release.

I think i should also mention that having a separate development environment for each branch is not possible because this software is based on PL/SQL (Oracle) and our current test database is about 350Mb in size, so having a different one for each requirement would be quite expensive and hard to manage.

Any suggestion or similar experience would be appreciated.

Regards

答:
I would suggest following:

product-1/

trunk/

branches/

feature-branches/

req-A/

req-B/

pre-lab/

lab/

prod/

Developers start developing for new requirements on the respective feature-branch.  Then you reintegrate the feature-branches which have been decided to be included for environment LAB/ to pre-lab/, where you can integrate the changes for new features and bugfixes from trunk/.

As soon as you know that works (will take some time, as any integration step merging from several sources), you merge all changes from pre-lab/ to lab/.  When you restrict yourself to merge only from pre-lab/ to lab/, this merge will always be clean, i.e. one mouse-click away.

In trunk/ you could merge all feature-branches and bug-fixes together, but depending on your project-structure and software-development-process this may need some further discussion.

Be sure to use Subversion 1.5, as this merging will get you lost in hell with older versions.

OwnerDisplayName: Patricio Téllez

LastEditorDisplayName: Adam Lassek

OwnerDisplayName: gimpf


问:
A business scenario that could involve integration of a number of IT systems using JMS?
Can anyone give me some suggestions of a business scenarios where I can implement Java Messaging Services (JMS). The message can be sent either by queue(point-to-point) or topic (regular/durable subscription).

I will be using JMS (enabled through TIBCO Enterprise Messaging Services).

The business scenarios must involve atleast 3 IT systems/applications.

答:
The classic use case is that of an Enterprise Service Bus with JMS as one of the available transports.  In this case any number of IT systems can request a service invocation by placing a message on a well-known queue.  The service provider listening on that queue dynamically determines the reply based on the JMS message's Reply-To fields.  An example of a typical service is to inquire on or update customer demographic information.  For purposes of inquiry, this definitely meets your requirement of involving at least 3 IT systems since pretty much everything dealing with customers would need to request this service.

Another example with broad application is logging.  I have several customers using JMS messages to capture log records from across the network and forward them to a hub of central servers.  Because it is JMS, the central hub can be highly available by using redundant servers and can scale horizontally to absorb seasonal loads.

For pub/sub an example I really liked is from an insurance company.  They publish events on topics that are subscribed in various call centers, internal news tickers and to business partners.  During a hurricane a few years back, these events included updates on landfall predictions and then after the storm passed the updates included locations of mobile claims adjusters and other support services.  Pub/Sub was a great way to coordinate this massive mobilization of personnel and communicate back to ground support back at headquarters.

A more mundane pub/sub use case with broad applicability is systems management.  Instrumented applications can publish their status and interested parties can receive those notifications.  If something is acting weird in Production, the administrator can dynamically enable a subscription to a stream of diagnostics.  Ordinarily with no subscribers, the diagnostics are not produced.  However, without any interruption in the running system, simply by subscribing, diagnostic messages from the app are produced on demand.

It's actually harder to find examples where JMS messaging should not be used.  The most common contraindications are truly synchronous messaging and a requirement to process messages in strict sequence.  All JMS providers I'm aware of make allowances for these requirements to varying degrees and I'm aware of many deployments of systems with these requirements.  However the ideal use cases for JMS messaging are truly asynchronous or pseudo-synchronous communication and messages that are atomic (that is to say messages have no dependencies on each other or to specific broker instances).


问:
How to upload a generic file into a Jenkins job?
I am trying to find a way to prompt the user to select and upload a generic file from a local machine to a Jenkins job prior to build. The input file that user is going to upload is not necessarily a text or a property file.

I am specifically trying to get the user to "select" their desired file - browse to their file ; the user should not pass the file's path.

Thanks

答:
This is kind of annoying to handle when you don't know what the file name will be or need to change its name before it reaches its destination. You kind of need to perform a hack. This is how I do it:

Use the "File parameter" parameter to upload your file

Use the OS-specific script to rename the file from whatever you named your File Parameter to whatever you want it to be, e.g., if my File Parameter had the File location value of file_name instead of an actual relative file-path, I'd then do something like this for say, Windows inside a Build-Step for "Execute Windows Batch Command":

move .\file_name .\%file_name%

And then just use ArtifactDeployer to copy everything there to your desired location.

ps: this won't remove digital signatures, so the move-operation should be considered mostly safe.


问:
How to achieve this complex layout with CSS?
I've this (apparently) simple layout :

There is a lot of technique out there, but I can't find one that will fulfill all the requirements. Could you point me to te correct direction ?

Edit : I need my layout to be 100% of it's parent, and to fall back to divs (or td's) one under this other on small screens. See my fiddle.

And I will need gutters.

table

Piece of cake, of course, thanks to rowspan and colspan. And it's easily fluid. But, can't use media query to change the display for small screens.

Edit : actually, media query works with td's. I just set it as display:block on small screens, and here we go. This is my working fiddle. But you know, "table is bad"...

float

I didn't even try. Do you think I should have ?

imbricated div's

It's not possible to imbricated this. I could use absolute positionning, but it wouldn't be fluid anymore

flexbox

Each time I try to use flexbox, it ends with a headache. But if I'm not wrong, we can't have rowspan and colspan at the same time.

css grid layout

It's the graal. Maybe it's metaphysic.

答:
My two cent on this issue, using some flexbox and without float.

See my fiddle.

Here would be the step by step approach:

we create a container box that will handle our design (200px by 300px)

we use flexbox to create a 2 by 2 box (without the hole in the middle). Flexbox helps to create two rows, each divided into two columns just using flex-flow: row wrap (it will distribute divs in a row, and when it's too narrow it wraps the rest into a new line).

In our case we need to fine-tune .landscape and .portrait divs to fit desired proportions (40% and 60% width or height depending on the case). As 60% + 40% will always occupy 100% of a row, we are assured that the flex-flow property will wrap the other two divs into a new line, itself fitting 100% as well.

At this stage, the shape looks pretty good except for the blue div which is not correctly aligned with the yellow one.

we just correct above point by applying basic repositioning to the blue div


问:
Search View disappearing (icon)
I have an interesting problem - though maybe it is the expected behavior? I have a SearchView in my tool bar, which functions just fine till I enter a search then close it, at which time the search icon disappears and the ability to do another search is lost.

This behavior only happens when the search query is initiated - so if I enter search text, clear the search, then close it, the icon is there. But if I close it with data in it, then the Icon disappears. It is not the text color - I have clicked away and nothing seems to be there.

Here are some pictures of what I am talking about:

Search is there:

Enter search, query:

Close SearchView, icon gone

Menu:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/library_forms_refresh"
        android:orderInCategory="100"
        android:showAsAction="always|withText"
        android:icon="@drawable/ic_action_refresh"
        android:title="refresh"/>

</menu>
</code>```

The code looks like this:

```<code>import android.widget.SearchView;

@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
    menu.clear();
    mMenu = menu; // remember so we can get to later.
    inflater.inflate(R.menu.library_forms, menu);

    (removed some code not related to this)

    // Implementing ActionBar Search inside a fragment
    MenuItem item = menu.add("Search");
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    sv = new SearchView(getActivity());

    // If we are on a Phone, make the search an icon, otherwise show it all
    if (GlobalState.getInstance().isTwoPane == true) {
        sv.setIconifiedByDefault(false);
    }
    else {
        sv.setIconifiedByDefault(true);
    }
    sv.setFocusable(false);

    // modifying the text inside edit text component
    int id = sv.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
    TextView textView = (TextView) sv.findViewById(id);
    textView.setHint("Form or Reference Number");
    textView.setHintTextColor(Color.WHITE);
    textView.setTextColor(Color.WHITE);

    // Change the Icon color
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        int searchButtonId = sv.getContext().getResources().getIdentifier("android:id/search_button", null, null);
        ImageView searchButton = (ImageView) sv.findViewById(searchButtonId);
        searchButton.setImageTintList(ColorStateList.valueOf(Color.WHITE));
    }

    // implementing the listener
    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        Handler handler = new Handler();

        @Override
        public boolean onQueryTextSubmit(String s) {
            handler.removeCallbacksAndMessages(null);
            if (s != null && s.trim().length() > 0)
            {
                searchFilter = s;
                // Delay the lookup by 800 ms
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // do some stuff here...
                    }
                }, 800);

            }
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            // If the string is empty, reload the form
            if (newText == null || newText.trim().length() == 0)
            {
                searchFilter = null;
                // do some stuff here...
                // Hides the soft keyboard
                sv.setVisibility(View.INVISIBLE);
                sv.setVisibility(View.GONE);
            }
            else {
                onQueryTextSubmit(newText);
            }
            return true;
        }
    });
    item.setActionView(sv);
}
</code>```

答:
The problem was this code:

```<code>        // do some stuff here...
        // Hides the soft keyboard
        sv.setVisibility(View.INVISIBLE);
        sv.setVisibility(View.GONE);
</code>```

Which hid the keyboard and the icon.

Title: Search View disappearing (icon)

Body:
I have an interesting problem - though maybe it is the expected behavior? I have a SearchView in my tool bar, which functions just fine till I enter a search then close it, at which time the search icon disappears and the ability to do another search is lost.

This behavior only happens when the search query is initiated - so if I enter search text, clear the search, then close it, the icon is there. But if I close it with data in it, then the Icon disappears. It is not the text color - I have clicked away and nothing seems to be there.

Here are some pictures of what I am talking about:

Search is there:

Enter search, query:

Close SearchView, icon gone

Menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/library_forms_refresh"
        android:orderInCategory="100"
        android:showAsAction="always|withText"
        android:icon="@drawable/ic_action_refresh"
        android:title="refresh"/>

</menu>

The code looks like this:

import android.widget.SearchView;

@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
    menu.clear();
    mMenu = menu; // remember so we can get to later.
    inflater.inflate(R.menu.library_forms, menu);

    (removed some code not related to this)

    // Implementing ActionBar Search inside a fragment
    MenuItem item = menu.add("Search");
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    sv = new SearchView(getActivity());

    // If we are on a Phone, make the search an icon, otherwise show it all
    if (GlobalState.getInstance().isTwoPane == true) {
        sv.setIconifiedByDefault(false);
    }
    else {
        sv.setIconifiedByDefault(true);
    }
    sv.setFocusable(false);

    // modifying the text inside edit text component
    int id = sv.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
    TextView textView = (TextView) sv.findViewById(id);
    textView.setHint("Form or Reference Number");
    textView.setHintTextColor(Color.WHITE);
    textView.setTextColor(Color.WHITE);

    // Change the Icon color
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        int searchButtonId = sv.getContext().getResources().getIdentifier("android:id/search_button", null, null);
        ImageView searchButton = (ImageView) sv.findViewById(searchButtonId);
        searchButton.setImageTintList(ColorStateList.valueOf(Color.WHITE));
    }

    // implementing the listener
    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        Handler handler = new Handler();

        @Override
        public boolean onQueryTextSubmit(String s) {
            handler.removeCallbacksAndMessages(null);
            if (s != null && s.trim().length() > 0)
            {
                searchFilter = s;
                // Delay the lookup by 800 ms
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // do some stuff here...
                    }
                }, 800);

            }
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            // If the string is empty, reload the form
            if (newText == null || newText.trim().length() == 0)
            {
                searchFilter = null;
                // do some stuff here...
                // Hides the soft keyboard
                sv.setVisibility(View.INVISIBLE);
                sv.setVisibility(View.GONE);
            }
            else {
                onQueryTextSubmit(newText);
            }
            return true;
        }
    });
    item.setActionView(sv);
}

Body:
The problem was this code:

        // do some stuff here...
        // Hides the soft keyboard
        sv.setVisibility(View.INVISIBLE);
        sv.setVisibility(View.GONE);

Which hid the keyboard and the icon.


问:
array_push and >= not working
Heyo! I've never knew this actually but the following method doesn't seem to work properly.

```<code>array_push($items[$key], 'price' => 100);
</code>```

How can I push it in an array so it displays,
{'price':100, 'moredata':1231}

What am I missing?

答:
You can't specify a key with array_push.

Fortunately, most of the time* when people use array_push it isn't actually necessary.

```<code>$items[$key]['price'] = 100
</code>```

*at least most of the time in Stack Overflow questions

Title: array_push and >= not working

Body:
Heyo! I've never knew this actually but the following method doesn't seem to work properly.

array_push($items[$key], 'price' => 100);

How can I push it in an array so it displays,
{'price':100, 'moredata':1231}

What am I missing?

Body:
You can't specify a key with array_push.

Fortunately, most of the time* when people use array_push it isn't actually necessary.

$items[$key]['price'] = 100

*at least most of the time in Stack Overflow questions


问:
How to add additional express routes in react server side rendering to use as backend
Find Edits at the bottom.

I have been really researching a lot of tutorials and even the documentation of the react training server side rendering located here: https://reacttraining.com/react-router/web/guides/server-rendering

Something that has been a problem for me is using other routes in order to have a full stack application. So for example we will use the MERN stack
(mongodb express React/Redux nodejs). Lets say we have two routes in the

app.js like so:

```<code>app.use('/users', users);
app.use('/posts', posts);
</code>```

and our Server Side Rendering is set up like most of these tutorials, actually I couldn't find one that did not set it up this way, and to save time I will just put where the SSR code would go. If you don't know how to do SSR then please look at the docs in the link I gave above. I think it may not be needed, but if it is let me know and I could add a simple set up.

Something like:

```<code>app.get('*', (req, res) => { //server side rendering code here});
</code>```

So the problem here is that it hits every route and inside of server side rendering for React Router 4, most people will use matchRoutes function and pass in their routes that they use for the react side.

Okay so I have explained a lot, but not really what the problem is:

PROBLEM: When on the react side, lets say using an action and we will use axios for a simple example here.

If I do:

```<code>axios.get('/posts')
.then(response => {
 console.log(response.data);
 })
.catch(err => {
 console.log(err);
 });
</code>```

This runs into a problem. And for any of you who know express and SSR well you will know why. The app.get('*') is hitting every route or in better words every route request will go through here, the problem is that when we send a request to /posts one of two cases will happen.

Case 1: there is a client side route /posts in the routes file for react side and this case will return the server side html as the response.data which is obviously not what we want.

Case 2: there is no client side route /posts in the routes file for react side and this case will return a 404 error or something similar to route or page not found if you set up your SSR correctly.

I need a way to be able to use my back-end, but be able to use the SSR for react as well.

Possible Solution?

Use some type of proxy and say if /api/routename then use the proxy that way your calls don't get pushed through the app.get('*').

Or some way of only doing SSR on individual routes.

Or excluding certain routes, but being able to use all of the client side routes. In this I mean if I have client side /users and an express side /users, I don't want the client side to break if I exclude /users, but some how still exclude the express side.

I'm not totally sure how to do these solutions of if they are possible, but I need to be able to use my express routes, and I can't find a concrete way on how to do it, or what is best practice.

EDITS:

server side app.js:

```<code>require('babel-core/register')({
  presets: ['env', 'react', 'stage-0', 'stage-1']
});

const pkg_json = require('./package.json');
const vertex = require('vertex360')({ site_id: pkg_json.app });
var renderer = require('./renderer.js');

// initialize app
const app = vertex.app();

// import routes
const index = require('./routes/index');
const api = require('./routes/api');
const users = require('./routes/users');

// set routes
app.use('/api/users', users);

// hopefully will be used on every Route, this should handle SSR RR4
app.use(renderer);

module.exports = app;
</code>```

renderer.js:

```<code>import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { renderRoutes } from 'react-router-config';
import serialize from 'serialize-javascript';
import { Helmet } from 'react-helmet';
import { matchRoutes } from 'react-router-config';

import routes from './src/routes';
import createStore from './src/stores';

function handleRender(req, res) {
  const store = createStore.configure(null); // create Store in order to get data from redux

  const promises = matchRoutes(routes, req.path)
    .map(({ route }) => {
      // Matches the route and loads data if loadData function is there
      return route.loadData ? route.loadData(store) : null;
    })
    .map(promise => {
      if (promise) {
        return new Promise((resolve, reject) => {
          promise.then(resolve).catch(resolve); // lets all data load even if route fails
        });
      }
    });

  Promise.all(promises).then(() => {
    const context = {};
    if (context.url) {
      return res.redirect(301, context.url); // redirect for non auth users
    }

    if (context.notFound) {
      res.status(404); // set status to 404 for unknown route
    }

    const content = renderToString(
      <Provider store={store}>
        <StaticRouter location={req.path} context={context}>
          <div>{renderRoutes(routes)}</div>
        </StaticRouter>
      </Provider>
    );

    const initialState = serialize(store.getState());

    const helmet = Helmet.renderStatic();

    res.render('index', { content, initialState, helmet });
  });
}

module.exports = handleRender;
</code>```

React entry point:

```<code>import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { renderRoutes } from 'react-router-config';
import serialize from 'serialize-javascript';
import { Helmet } from 'react-helmet';
import { matchRoutes } from 'react-router-config';

import routes from './src/routes';
import createStore from './src/stores';

function handleRender(req, res) {
  const store = createStore.configure(null); // create Store in order to get data from redux

  const promises = matchRoutes(routes, req.path)
    .map(({ route }) => {
      // Matches the route and loads data if loadData function is there
      return route.loadData ? route.loadData(store) : null;
    })
    .map(promise => {
      if (promise) {
        return new Promise((resolve, reject) => {
          promise.then(resolve).catch(resolve); // lets all data load even if route fails
        });
      }
    });

  Promise.all(promises).then(() => {
    const context = {};
    if (context.url) {
      return res.redirect(301, context.url); // redirect for non auth users
    }

    if (context.notFound) {
      res.status(404); // set status to 404 for unknown route
    }

    const content = renderToString(
      <Provider store={store}>
        <StaticRouter location={req.path} context={context}>
          <div>{renderRoutes(routes)}</div>
        </StaticRouter>
      </Provider>
    );

    const initialState = serialize(store.getState());

    const helmet = Helmet.renderStatic();

    res.render('index', { content, initialState, helmet });
  });
}

module.exports = handleRender;
</code>```

答:
Thanks to @VivekN, the way you do this is make sure that your
app.get('*') is below each of the declared routes. This should allow your other routes to be passed through first.

Body:
Find Edits at the bottom.

I have been really researching a lot of tutorials and even the documentation of the react training server side rendering located here: https://reacttraining.com/react-router/web/guides/server-rendering

Something that has been a problem for me is using other routes in order to have a full stack application. So for example we will use the MERN stack
(mongodb express React/Redux nodejs). Lets say we have two routes in the

app.js like so:

app.use('/users', users);
app.use('/posts', posts);

and our Server Side Rendering is set up like most of these tutorials, actually I couldn't find one that did not set it up this way, and to save time I will just put where the SSR code would go. If you don't know how to do SSR then please look at the docs in the link I gave above. I think it may not be needed, but if it is let me know and I could add a simple set up.

Something like:

app.get('*', (req, res) => { //server side rendering code here});

So the problem here is that it hits every route and inside of server side rendering for React Router 4, most people will use matchRoutes function and pass in their routes that they use for the react side.

Okay so I have explained a lot, but not really what the problem is:

PROBLEM: When on the react side, lets say using an action and we will use axios for a simple example here.

If I do:

axios.get('/posts')
.then(response => {
 console.log(response.data);
 })
.catch(err => {
 console.log(err);
 });

This runs into a problem. And for any of you who know express and SSR well you will know why. The app.get('*') is hitting every route or in better words every route request will go through here, the problem is that when we send a request to /posts one of two cases will happen.

Case 1: there is a client side route /posts in the routes file for react side and this case will return the server side html as the response.data which is obviously not what we want.

Case 2: there is no client side route /posts in the routes file for react side and this case will return a 404 error or something similar to route or page not found if you set up your SSR correctly.

I need a way to be able to use my back-end, but be able to use the SSR for react as well.

Possible Solution?

Use some type of proxy and say if /api/routename then use the proxy that way your calls don't get pushed through the app.get('*').

Or some way of only doing SSR on individual routes.

Or excluding certain routes, but being able to use all of the client side routes. In this I mean if I have client side /users and an express side /users, I don't want the client side to break if I exclude /users, but some how still exclude the express side.

I'm not totally sure how to do these solutions of if they are possible, but I need to be able to use my express routes, and I can't find a concrete way on how to do it, or what is best practice.

EDITS:

server side app.js:

require('babel-core/register')({
  presets: ['env', 'react', 'stage-0', 'stage-1']
});

const pkg_json = require('./package.json');
const vertex = require('vertex360')({ site_id: pkg_json.app });
var renderer = require('./renderer.js');

// initialize app
const app = vertex.app();

// import routes
const index = require('./routes/index');
const api = require('./routes/api');
const users = require('./routes/users');

// set routes
app.use('/api/users', users);

// hopefully will be used on every Route, this should handle SSR RR4
app.use(renderer);

module.exports = app;

renderer.js:

import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { renderRoutes } from 'react-router-config';
import serialize from 'serialize-javascript';
import { Helmet } from 'react-helmet';
import { matchRoutes } from 'react-router-config';

import routes from './src/routes';
import createStore from './src/stores';

function handleRender(req, res) {
  const store = createStore.configure(null); // create Store in order to get data from redux

  const promises = matchRoutes(routes, req.path)
    .map(({ route }) => {
      // Matches the route and loads data if loadData function is there
      return route.loadData ? route.loadData(store) : null;
    })
    .map(promise => {
      if (promise) {
        return new Promise((resolve, reject) => {
          promise.then(resolve).catch(resolve); // lets all data load even if route fails
        });
      }
    });

  Promise.all(promises).then(() => {
    const context = {};
    if (context.url) {
      return res.redirect(301, context.url); // redirect for non auth users
    }

    if (context.notFound) {
      res.status(404); // set status to 404 for unknown route
    }

    const content = renderToString(
      <Provider store={store}>
        <StaticRouter location={req.path} context={context}>

{renderRoutes(routes)}

        </StaticRouter>
      </Provider>
    );

    const initialState = serialize(store.getState());

    const helmet = Helmet.renderStatic();

    res.render('index', { content, initialState, helmet });
  });
}

module.exports = handleRender;

React entry point:

import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { renderRoutes } from 'react-router-config';
import serialize from 'serialize-javascript';
import { Helmet } from 'react-helmet';
import { matchRoutes } from 'react-router-config';

import routes from './src/routes';
import createStore from './src/stores';

function handleRender(req, res) {
  const store = createStore.configure(null); // create Store in order to get data from redux

  const promises = matchRoutes(routes, req.path)
    .map(({ route }) => {
      // Matches the route and loads data if loadData function is there
      return route.loadData ? route.loadData(store) : null;
    })
    .map(promise => {
      if (promise) {
        return new Promise((resolve, reject) => {
          promise.then(resolve).catch(resolve); // lets all data load even if route fails
        });
      }
    });

  Promise.all(promises).then(() => {
    const context = {};
    if (context.url) {
      return res.redirect(301, context.url); // redirect for non auth users
    }

    if (context.notFound) {
      res.status(404); // set status to 404 for unknown route
    }

    const content = renderToString(
      <Provider store={store}>
        <StaticRouter location={req.path} context={context}>

{renderRoutes(routes)}

        </StaticRouter>
      </Provider>
    );

    const initialState = serialize(store.getState());

    const helmet = Helmet.renderStatic();

    res.render('index', { content, initialState, helmet });
  });
}

module.exports = handleRender;


问:
css vertical-alignment should it work when cell position is absolute or is this a bug/gap in the browsers
I noticed that the table cell vertical-alignment is not working when the position is set to absolute. Am I doing something wrong?

NON WORKING SAMPLE

          bottom alignament is not working
           a

           a

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

<p>The usual approach works fine</p>

<p>WORKING SAMPLE
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <table style="border:solid 1px #CCCCCC">
      <thead>
        <tr>
          <th rowspan="2" style="vertical-align:bottom; border:solid 1px #CCCCCC">bottom alignament ok</th>
          <th > a</th>
        </tr>
        <tr>
          <th > a</th>
        </tr>
      </thead>
    </table></code>```

答:
Vertical align table-cell don't work with position absolute post looks like this?

Wrap the  in some wrapper element,  for instance. Make the wrapper absolute positioned.

            bottom alignament is not working

           a

           a

```

Body:
I noticed that the table cell vertical-alignment is not working when the position is set to absolute. Am I doing something wrong?

NON WORKING SAMPLE

          bottom alignament is not working
           a

           a

The usual approach works fine

WORKING SAMPLE

          bottom alignament ok
           a

           a

Body:
Vertical align table-cell don't work with position absolute post looks like this?

Wrap the  in some wrapper element,  for instance. Make the wrapper absolute positioned.

    <table>
      <thead >
        <tr>
          <span style="position:absolute;">
            <th rowspan="2" style="border:solid 1px #CCCCCC; left:100px; height:200px; vertical-align:bottom;">bottom alignament is not working</th>
          </span>
          <th style="position:absolute; left:400px;border:solid 1px #CCCCCC;"> a</th>
        </tr>
        <tr >
          <th style="position:absolute; left:500px; border:solid 1px #CCCCCC;"> a</th>
        </tr>
      </thead>
    </table>


问:
HttpUrlConnection Post with header info but no body
I am developing an Android app that uses an API I developed.

I am doing this connection using HttpUrlConnection and so far the login works fine. The problem arises with the logout. It´s not doing anything. When I do the logout request with Postman then it works fine, but with HttpUrlConnection it does not.

The logout works like this:
Do a POST request to http://ipaddress:12345/api/LogOut

and in the header include the token of the logged user. Then the server should go to the database and delete the token for that user:

This is how I´m trying to do the request:

```<code>URL url = new URL(getString(R.string.url) + "LogOut");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Token", TokenSingleton.getToken());

con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

con.connect();
con.getOutputStream().flush();
con.getOutputStream().close();
con.disconnect();
</code>```

答:
Nothing happens until you do some input. At least call getResponseCode() to see whether you got a 200 or not. Preferably you should consume the input stream, if 200 <= response code <= 299, otherwise the error stream.

NB setDoOutput(true) sets the request method to POST. You don't need to do that yourself. And setDoInput(true) is the default. And close() implies flush().

Body:
I am developing an Android app that uses an API I developed.

I am doing this connection using HttpUrlConnection and so far the login works fine. The problem arises with the logout. It´s not doing anything. When I do the logout request with Postman then it works fine, but with HttpUrlConnection it does not.

The logout works like this:
Do a POST request to http://ipaddress:12345/api/LogOut

and in the header include the token of the logged user. Then the server should go to the database and delete the token for that user:

This is how I´m trying to do the request:

URL url = new URL(getString(R.string.url) + "LogOut");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Token", TokenSingleton.getToken());

con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

con.connect();
con.getOutputStream().flush();
con.getOutputStream().close();
con.disconnect();


问:
get primary key from context ofbiz
can any one help me pleaze , i have a entity named Person and formateur extend from this entity
so i want to add a formateur the probleme that i need  the id of the table Person how i can get it plz

```<code>public static Map<String, Object> createFormateur(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = ServiceUtil.returnSuccess();
Delegator delegator = dctx.getDelegator();
try {
    GenericValue formateurAdd = delegator.makeValue("twFormateur");

    formateurAdd.setString("partyId", context.toString());

    formateurAdd.setNonPKFields(context);
    // Creating record in database for OfbizDemo entity for prepared value
    formateurAdd = delegator.create(formateurAdd);
    result.put("partyId", formateurAdd.getString("partyId"));
    Debug.log("==========Thisis my first Java Service implementation in Apache OFBiz. OfbizDemo record created successfully with ofbizDemoId: "+formateurAdd.getString("partyId"));
} catch (GenericEntityException e) {
    Debug.logError(e, module);
    return ServiceUtil.returnError("Error in creating record in OfbizDemo entity ........" +module);
}
return result;
</code>```

}

答:
If you need to get a single key from context, partyId for example, you can try :

```<code>String partyId = (String)context.get("partyId");
</code>```

in this case you probably want to populate all the information of the context into your GenericValue, you can try :

```<code>GenericValue formateurAdd = delegator.makeValidValue("twFormateur", context);
</code>```

Title: get primary key from context ofbiz

Body:
can any one help me pleaze , i have a entity named Person and formateur extend from this entity
so i want to add a formateur the probleme that i need  the id of the table Person how i can get it plz

public static Map<String, Object> createFormateur(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = ServiceUtil.returnSuccess();
Delegator delegator = dctx.getDelegator();
try {
    GenericValue formateurAdd = delegator.makeValue("twFormateur");

    formateurAdd.setString("partyId", context.toString());

    formateurAdd.setNonPKFields(context);
    // Creating record in database for OfbizDemo entity for prepared value
    formateurAdd = delegator.create(formateurAdd);
    result.put("partyId", formateurAdd.getString("partyId"));
    Debug.log("==========Thisis my first Java Service implementation in Apache OFBiz. OfbizDemo record created successfully with ofbizDemoId: "+formateurAdd.getString("partyId"));
} catch (GenericEntityException e) {
    Debug.logError(e, module);
    return ServiceUtil.returnError("Error in creating record in OfbizDemo entity ........" +module);
}
return result;

}

Body:
If you need to get a single key from context, partyId for example, you can try :

String partyId = (String)context.get("partyId");

in this case you probably want to populate all the information of the context into your GenericValue, you can try :

GenericValue formateurAdd = delegator.makeValidValue("twFormateur", context);


问:
Python - Django query using auth.User model as OneToOneField
I am using the auth.User model for login info, and a custom UserProfile model for all of a user's profile data.

The auth.User.username is a random string.
and the UserProfile.user is the same string.

When attempting to query the database table "UserProfile" I get the following error:

```<code>ValueError: invalid literal for int() with base 10: '3df69698-c97d-11e7-a924-b0c0905e8512'
</code>```

models.py

```<code>from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=256, default=None)
    last_name = models.CharField(max_length=256, default=None)
    ...

    def __str__(self):
        return str(self.user)
</code>```

views.py

```<code>from .models import UserProfile
from django.contrib.auth.models import User

def get_users(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = escape(data['id'])

    # error occurs here
    user_pref = UserProfile.objects.get(user=user_id)
</code>```

The problem comes when trying to query the database, and using a string compared to an auth.User object. I do not know how to get around this?

答:
Is that string supposed to be the username? If so you should query that field explicitly:</p>

```<code>UserProfile.objects.get(user__username=user_id)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the auth.User model for login info, and a custom UserProfile model for all of a user's profile data.

The auth.User.username is a random string.
and the UserProfile.user is the same string.

When attempting to query the database table "UserProfile" I get the following error:

ValueError: invalid literal for int() with base 10: '3df69698-c97d-11e7-a924-b0c0905e8512'

models.py

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=256, default=None)
    last_name = models.CharField(max_length=256, default=None)
    ...

    def __str__(self):
        return str(self.user)

views.py

from .models import UserProfile
from django.contrib.auth.models import User

def get_users(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = escape(data['id'])

    # error occurs here
    user_pref = UserProfile.objects.get(user=user_id)

The problem comes when trying to query the database, and using a string compared to an auth.User object. I do not know how to get around this?

Body:
Is that string supposed to be the username? If so you should query that field explicitly:

UserProfile.objects.get(user__username=user_id)


问:
How to automate telnet session using Expect?
I'm trying to write an expect script to automate telnet.  This is what I have so far.

```<code>#!/usr/bin/expect
# Test expect script to telnet.

spawn telnet 10.62.136.252
expect "foobox login:"
send "foo1\r"
expect "Password:"
send "foo2\r"
send "echo HELLO WORLD\r"
# end of expect script.
</code>```

Basically, what I want to do is telnet to the following IP address and then echo HELLO WORLD.  However, it seems that the script fails after attempting to telnet...I'm not sure if it's able to accept login and password input, but it is not echoing HELLO WORLD.  Instead, I just get this output:

```<code>cheungj@sfgpws30:~/justin> ./hpuxrama
spawn telnet 10.62.136.252
Trying 10.62.136.252...
Connected to 10.62.136.252.
Escape character is '^]'.
Welcome to openSUSE 11.1 - Kernel 2.6.27.7-9-pae (7).

foobox login: foo1
Password: foo2~/justin>
</code>```

答:
Here is a simplified version </p>

```<code>#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed

set ip [lindex $argv 0]
set port [lindex $argv 1]

set timeout 5
spawn telnet $ip $port
expect "'^]'."
</code>```

Body:
I'm trying to write an expect script to automate telnet.  This is what I have so far.

#!/usr/bin/expect
# Test expect script to telnet.

spawn telnet 10.62.136.252
expect "foobox login:"
send "foo1\r"
expect "Password:"
send "foo2\r"
send "echo HELLO WORLD\r"
# end of expect script.

Basically, what I want to do is telnet to the following IP address and then echo HELLO WORLD.  However, it seems that the script fails after attempting to telnet...I'm not sure if it's able to accept login and password input, but it is not echoing HELLO WORLD.  Instead, I just get this output:

cheungj@sfgpws30:~/justin> ./hpuxrama
spawn telnet 10.62.136.252
Trying 10.62.136.252...
Connected to 10.62.136.252.
Escape character is '^]'.
Welcome to openSUSE 11.1 - Kernel 2.6.27.7-9-pae (7).

foobox login: foo1
Password: foo2~/justin>

Body:
Here is a simplified version

#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed

set ip [lindex $argv 0]
set port [lindex $argv 1]

set timeout 5
spawn telnet $ip $port
expect "'^]'."


问:
Interactive shell using Docker Compose
Is there any way to start an interactive shell in a container using Docker Compose only? I've tried something like this, in my docker-compose.yml:

```<code>myapp:
  image: alpine:latest
  entrypoint: /bin/sh
</code>```

When I start this container using docker-compose up it's exited immediately. Are there any flags I can add to the entrypoint command, or as an additional option to myapp, to start an interactive shell?

I know there are native docker command options to achieve this, just curious if it's possible using only Docker Compose, too.

答:
The official getting started example (https://docs.docker.com/compose/gettingstarted/) uses the following docker-compose.yml:

version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:5000"
  redis:
    image: "redis:alpine"
```
<p>After you start this with <code>docker-compose up</code>, you can shell into either your <code>redis</code> container or your <code>web</code> container with:</p>
<pre class="lang-sh prettyprint-override"><code>docker-compose exec redis sh
docker-compose exec web sh
</code>```

Title: Interactive shell using Docker Compose

Body:
Is there any way to start an interactive shell in a container using Docker Compose only? I've tried something like this, in my docker-compose.yml:

myapp:
  image: alpine:latest
  entrypoint: /bin/sh

When I start this container using docker-compose up it's exited immediately. Are there any flags I can add to the entrypoint command, or as an additional option to myapp, to start an interactive shell?

I know there are native docker command options to achieve this, just curious if it's possible using only Docker Compose, too.

Body:
The official getting started example (https://docs.docker.com/compose/gettingstarted/) uses the following docker-compose.yml:

version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:5000"
  redis:
    image: "redis:alpine"

After you start this with docker-compose up, you can shell into either your redis container or your web container with:

docker-compose exec redis sh
docker-compose exec web sh


问:
bootstrap-datepicker: Show DIV when selecting specific date
Using the bootstrap-datepicker plugin with the embedded markup...

How to show/reveal a DIV element when selecting a specific date AND hide it again when another date has been selected?

```<code><head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>

  <style>
    #example {
      display: none;
      color: green;
      font-weight: bold;
    }

  </style>
</head>

<body>
  <div id="example">Yay my favorate day!</div>
  Please select <b>11/07/2017</b> to show an example:
  <br />
  <div id="myCalendar"></div>
  <input type="hidden" id="hiddenInput">

  <script>
    $(function() {
      $('#myCalendar').datepicker({
        format: 'mm-dd-yyyy',
        weekStart: 1,
        maxViewMode: 2,
        todayBtn: "linked",
        daysOfWeekHighlighted: "0,6",
        todayHighlight: true
      }).on('changeDate', function() {
        $('#hiddenInput').val(
          $('#myCalendar').datepicker('getFormattedDate')
        );
      }).change(function() {
        $("#example").toggle($(this).val() === "11-07-2017");
      });
    });

  </script>
</body>
</code>```

Demo on JSFiddle

答:
You can do this by checking the value of the datepicker.  For this example I use 11/07/2017 as the date you are checking for (aka November 17th, 2017).

$(function(){
   $('.datepicker').datepicker({
      format: 'mm-dd-yyyy'
    }).change(function () {
      $("#example").toggle($(this).val() === "11-07-2017");
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#example {
  display:none;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" />

Yay my favorate day!

Please select 11/07/2017 to show an example:

<input type="text" class="datepicker" placeholder="Date..." name="date">```

Body:
Using the bootstrap-datepicker plugin with the embedded markup...

How to show/reveal a DIV element when selecting a specific date AND hide it again when another date has been selected?

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" />

Yay my favorate day!

  Please select 11/07/2017 to show an example:

  <input type="hidden" id="hiddenInput">

Demo on JSFiddle

Body:
You can do this by checking the value of the datepicker.  For this example I use 11/07/2017 as the date you are checking for (aka November 17th, 2017).

$(function(){
   $('.datepicker').datepicker({
      format: 'mm-dd-yyyy'
    }).change(function () {
      $("#example").toggle($(this).val() === "11-07-2017");
    });
});

#example {
  display:none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<div id="example">Yay my favorate day!</div>
Please select <b>11/07/2017</b> to show an example:
<br />
<input type="text" class="datepicker" placeholder="Date..." name="date">