问:
Self-hosted fonts using NextJS
I'm trying to self-host webfonts using my NextJS app and having trouble.
This is the URL browser tries to access these fonts:

```<code>localhost:3000/_next/static/css/fonts/Avenir.woff2
</code>```

The actual path is:

```<code>_project_dir/static/fonts/Avenir.woff2
</code>```

I tried including the link in the the _app.js, it does download the fonts, but the text remains unstyled.

<link rel="preload" as="font" href="/static/fonts/Avenir.woff2" type="font/woff2" crossorigin />
```
<p>Here's my <code>_app.js</code>:</p>
```
  render() {
    const { Component, pageProps } = this.props;
    return (
      <Container>
        <link href="https://fonts.googleapis.com/css?family=Poppins:500,500i,600&display=swap" rel="stylesheet" />
        <link rel="preload" as="font" href="/static/fonts/Avenir.woff2" type="font/woff2" crossorigin />
        <link rel="preload" as="font" href="/static/fonts/AvenirHeavy.woff2" type="font/woff2" crossorigin />

          <title>Project</title>

        <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
            <Component pageContext={this.pageContext} {...pageProps} />
          </PersistGate>
        </Provider>
      </Container>
    );
  }
}
```
<p>My <code>main.css</code></p>
<pre class="lang-css prettyprint-override"><code>@font-face {
  font-family: 'Avenir';
  font-weight: 400;
  font-style: normal;
  font-display: swap;
  src: url('fonts/Avenir.eot');
  src: url('fonts/Avenir.eot?#iefix') format('embedded-opentype'), url('fonts/Avenir.woff2') format('woff2'),
    url('fonts/Avenir.woff') format('woff'), url('fonts/Avenir.ttf') format('truetype');
}

@font-face {
  font-family: 'Avenir';
  font-weight: 500;
  src: url('fonts/Avenir.eot');
  src: url('fonts/Avenir.eot?#iefix') format('embedded-opentype'), url('fonts/Avenir.woff2') format('woff2'),
    url('fonts/Avenir.woff') format('woff'), url('fonts/Avenir.ttf') format('truetype');
}

@font-face {
  font-family: 'Avenir';
  font-weight: 900;
  src: url('fonts/AvenirHeavy.eot');
  src: url('fonts/AvenirHeavy.eot?#iefix') format('embedded-opentype'), url('fonts/AvenirHeavy.woff2') format('woff2'),
    url('fonts/AvenirHeavy.woff') format('woff'), url('fonts/AvenirHeavy.ttf') format('truetype');
}

</code>```

And my next.config.js:

  webpack(config, options) {
    config.module.rules.push({
      test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 100000,
        },
      },
    });
    return config;
  },

```

答:
In my case, I had my code set up as brc-dd had described, but it still wasn't working: the fonts were downloaded in the network tab, but the text was still unstyled.

In the end, converting my fonts from .ttf to .woff2 fixed the issue for me.

My working code looks like this in Next 11:

```<code>// document.js
<Head>
  <link
    rel="preload"
    href="/fonts/Lato/Lato-Light.woff2" // fix: convert .ttf to .woff2
    as="font"
    type="font/woff2"
    crossOrigin="anonymous"
  />
</Head>
</code>```
```<code>// globals.css
@font-face {
  font-family: "Lato";
  font-style: normal;
  font-weight: 300;
  font-display: optional;
  src: url("/fonts/Lato/Lato-Light.woff2") format("woff2");
}
</code>```

My fonts are stored in project_root/public/fonts/[fontname]/[fontfile].woff2

Title: Self-hosted fonts using NextJS

Body:
I'm trying to self-host webfonts using my NextJS app and having trouble.
This is the URL browser tries to access these fonts:

localhost:3000/_next/static/css/fonts/Avenir.woff2

The actual path is:

_project_dir/static/fonts/Avenir.woff2

I tried including the link in the the _app.js, it does download the fonts, but the text remains unstyled.

<link rel="preload" as="font" href="/static/fonts/Avenir.woff2" type="font/woff2" crossorigin />

Here's my _app.js:

  render() {
    const { Component, pageProps } = this.props;
    return (
      <Container>
        <link href="https://fonts.googleapis.com/css?family=Poppins:500,500i,600&display=swap" rel="stylesheet" />
        <link rel="preload" as="font" href="/static/fonts/Avenir.woff2" type="font/woff2" crossorigin />
        <link rel="preload" as="font" href="/static/fonts/AvenirHeavy.woff2" type="font/woff2" crossorigin />

          <title>Project</title>

        <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
            <Component pageContext={this.pageContext} {...pageProps} />
          </PersistGate>
        </Provider>
      </Container>
    );
  }
}

My main.css

@font-face {
  font-family: 'Avenir';
  font-weight: 400;
  font-style: normal;
  font-display: swap;
  src: url('fonts/Avenir.eot');
  src: url('fonts/Avenir.eot?#iefix') format('embedded-opentype'), url('fonts/Avenir.woff2') format('woff2'),
    url('fonts/Avenir.woff') format('woff'), url('fonts/Avenir.ttf') format('truetype');
}

@font-face {
  font-family: 'Avenir';
  font-weight: 500;
  src: url('fonts/Avenir.eot');
  src: url('fonts/Avenir.eot?#iefix') format('embedded-opentype'), url('fonts/Avenir.woff2') format('woff2'),
    url('fonts/Avenir.woff') format('woff'), url('fonts/Avenir.ttf') format('truetype');
}

@font-face {
  font-family: 'Avenir';
  font-weight: 900;
  src: url('fonts/AvenirHeavy.eot');
  src: url('fonts/AvenirHeavy.eot?#iefix') format('embedded-opentype'), url('fonts/AvenirHeavy.woff2') format('woff2'),
    url('fonts/AvenirHeavy.woff') format('woff'), url('fonts/AvenirHeavy.ttf') format('truetype');
}

And my next.config.js:

  webpack(config, options) {
    config.module.rules.push({
      test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 100000,
        },
      },
    });
    return config;
  },

Body:
In my case, I had my code set up as brc-dd had described, but it still wasn't working: the fonts were downloaded in the network tab, but the text was still unstyled.

In the end, converting my fonts from .ttf to .woff2 fixed the issue for me.

My working code looks like this in Next 11:

// document.js
<Head>
  <link
    rel="preload"
    href="/fonts/Lato/Lato-Light.woff2" // fix: convert .ttf to .woff2
    as="font"
    type="font/woff2"
    crossOrigin="anonymous"
  />
</Head>

// globals.css
@font-face {
  font-family: "Lato";
  font-style: normal;
  font-weight: 300;
  font-display: optional;
  src: url("/fonts/Lato/Lato-Light.woff2") format("woff2");
}

My fonts are stored in project_root/public/fonts/[fontname]/[fontfile].woff2


来源: stackexchange

问:
Conditionally rendering when useEffect runs
I am making an application in which I am calling 2 APIS on one screen. I want to call the first one when the screen renders for the first time and set response to some state values when it's done I am starting a count down function for approximately 3mins and when the count down ends I am calling the second API with data which are fetched from the first one and repeat the same process again for another cont down and re-renders the screen but I don't want to run the first API every time when screen re-renders.
Currently, I don't have code with me so hope you understood my problem any help will be appreciated.

first api call

```<code>
const [stopTime, setStopTime] = useState('')

[period, setPeriod] = useState('')

const [minutes Left, setMinutes Left] = useState (null);

const [seconds Left, setSeconds Left]

= useState (null);

const [isTimeron, setTimeron] = useState (false);

const [issecondTime, setIsSecondTime] = useState(false) =

const userToken = user.userToken;

// console.log(userToken);

// function to get current period and result time
const getGameData = ({token}) => {

const formdata = new FormData();

formdata.append('token', token);

axios({

method: 'POST',

url: BASE_URL + '/color_game.php',

data: formdata,

}).then (res ⇒>{

//console.log('first ${res.data. response.currentTimer}

setPeriod (res.data. response.timerId);
setStopTime (res.data.response.currentTimer);

setIsSecond Time (true)

setTimeron (true);

}
</code>```

Second api call

```<code> const formdata = new FormData();

formdata.append('token', token);
 formdata.append('currentTimer', currentTimer);
formdata, append('timerId', timerId);

axios({

method: 'POST',

url: BASE_URL + '/color_game.php',

data: formdata,

}).then (res => {

// console.log('second");

console.log('second ${res.data.response.currentTimer} ');
if (res.data. response.timerId != null) {
 setStopTime (res.data. response.currentTimer);
setPeriod (res.data.response.timerId);
setTimeron (true);

} else {

console.log('nothing');

} });

};

</code>```

Cony down fuction

```<code>const countdown = () => {
if(isTimerOn){

var resultTime = new Date stopTime).getTime();

const time Interval=setInterval (() => {

var now = new Date().getTime();

var duration = resultTime - now; console.log(duration);

setMinutes Left (Math.floor( (duration % (1000 * 60

setSeconds Left (Math.floor( (duration % (1000 * 60)

if (duration <= 0) {
clearInterval (timeInterval);

getGameDataSecondTime ({

token: userToken, timerId: period,

currentTimer: stopTime,

});

}

}, 1000);

}

};
</code>```

答:
So you have 2 API calls. The first is called when the screen first renders and never again. The second depends on data from the first and is called every 3 minutes.

Effects are called based on the dependency array passed to them (e.g an empty array runs once). So I would base the code around that and do something like this:

//  keeps track of whether the first api has been called
const [calledFirstApi, setCalledFirstApi] = useState(false);
// data from first api call will be stored here
const [data, setData] = useState({});
// store secondApi data here if it needs to trigger a re-render
const [otherData,setOtherData] = useState({});

const interval = useRef(null);
const time = 60*1000*3;

//dont know if your api is asynchronous or not
const callFirstApi = async ()=>{
  let apiData = await firstApi();
  setData(apiData);
}

const callSecondApi = async ()=>{
  //the second api call uses data from the first
  let apiData2 = await secondApi(data);
  setOtherData(apiData2)
}

// effect for first render
useEffect(()=>{
  callFirstApi();
  // mark api called
  setCalledFirstApi(true);
},[]);

//effect for when calledFirstApi changes
useEffect(()=>{
  // if false, do nothing/ return
  if(!calledFirstApi)
    return
  // when true start interval
  interval.current = setInterval(()=>{
    callSecondApi()
  }
  ,time)
  // the return of an effect is a cleanup function
  // (function will run when unmounting component)
  return ()=>clearInterval(interval.current);
}),[calledFirstApi]);
```

ContentLicense: CC BY-SA 4.0

Body:
I am making an application in which I am calling 2 APIS on one screen. I want to call the first one when the screen renders for the first time and set response to some state values when it's done I am starting a count down function for approximately 3mins and when the count down ends I am calling the second API with data which are fetched from the first one and repeat the same process again for another cont down and re-renders the screen but I don't want to run the first API every time when screen re-renders.
Currently, I don't have code with me so hope you understood my problem any help will be appreciated.

first api call

const [stopTime, setStopTime] = useState('')

[period, setPeriod] = useState('')

const [minutes Left, setMinutes Left] = useState (null);

const [seconds Left, setSeconds Left]

= useState (null);

const [isTimeron, setTimeron] = useState (false);

const [issecondTime, setIsSecondTime] = useState(false) =

const userToken = user.userToken;

// console.log(userToken);

// function to get current period and result time
const getGameData = ({token}) => {

const formdata = new FormData();

formdata.append('token', token);

axios({

method: 'POST',

url: BASE_URL + '/color_game.php',

data: formdata,

}).then (res ⇒>{

//console.log('first ${res.data. response.currentTimer}

setPeriod (res.data. response.timerId);
setStopTime (res.data.response.currentTimer);

setIsSecond Time (true)

setTimeron (true);

}

Second api call

 const formdata = new FormData();

formdata.append('token', token);
 formdata.append('currentTimer', currentTimer);
formdata, append('timerId', timerId);

axios({

method: 'POST',

url: BASE_URL + '/color_game.php',

data: formdata,

}).then (res => {

// console.log('second");

console.log('second ${res.data.response.currentTimer} ');
if (res.data. response.timerId != null) {
 setStopTime (res.data. response.currentTimer);
setPeriod (res.data.response.timerId);
setTimeron (true);

} else {

console.log('nothing');

} });

};

Cony down fuction

const countdown = () => {
if(isTimerOn){

var resultTime = new Date stopTime).getTime();

const time Interval=setInterval (() => {

var now = new Date().getTime();

var duration = resultTime - now; console.log(duration);

setMinutes Left (Math.floor( (duration % (1000 * 60

setSeconds Left (Math.floor( (duration % (1000 * 60)

if (duration <= 0) {
clearInterval (timeInterval);

getGameDataSecondTime ({

token: userToken, timerId: period,

currentTimer: stopTime,

});

}

}, 1000);

}

};


问:
jQuery cannot change a value where JS can because the library is out of date
Simple answer:

The jQuery library my code base was using was out of date.

If yours is up to date try the following:

Step though the unminified version of jQuery to see if the issue is inside the library (which 9 times out of 10 it probably will not be)

When all else fails, just write a pure javascript solution.

Sometimes when I am writing a "class" in javscript with jQuery, jQuery will just not function as it should.  For example today I was doing the following on an input select:

$(this).val(newValue);

This was working in jFiddle just fine, but not working in my project (both had 0 script errors). I tried to isolate the code as much as possible, but to no avail I could not get it to work.

The "solution" for this was to just write straight up javascript to set the value and it worked just fine.

I am not a jQuery master, but this is not the first time I had to write a straight javascript solution when jQuery "failed."  Do any jQuery masters out there know why something like this might happen?  Is there a method of debugging jQuery I am not aware of?  Does anyone else run into these types of problems with jQuery?  If so, do you have a solution?

Update(s):

Aug 25, 2011

I downloaded the most recent version of the jQuery library and stepped through it only to find that the bug was probably resolved between jQuery 1.4.4 and 1.6.2.  I didn't realize the person who handles most of the javascript wasn't keeping the jQuery library up to date.  After stepping through the jQuery 1.4.4 library it seems that jQuery was not able to find my selector for some reason and therefore was never setting the value.  This problem has been resolved in 1.6.2....

Lesson of the week... keep your jQuery library up to date and verify your senior developer's statements when things aren't matching up.

-

I chose the answer I did because it was the only one which really helped me diagnose the source of the problem.  While stepping through the unminified version of jQuery is such a simple solution, I actually should have done that before posting this question.  I will post my findings as to why it didn't work later.

Aug 24, 2011

I agree with the user Sohnee that having a duplicate 'name' isn't bad practice and in some places you actually need it.

I feel rather stupid because the posted code has been wrong for almost a week now.  I have updated the code.  I moved the init function to the public scope.

Aug 22, 2011

While I am partially satisfied that the core of the problem is with duplicate names, I need to know why are duplicate names bad?

I know when dealing with inputs/css/etc you usually except IDs to be unique and classes to represent groups.  I didn't think there were any rules about names, but if someone can explain to me why having duplicate names is bad practice, I will consider that the answer to this problem.

Aug 16, 2011

As for the current answers, I don't think it is a conflict.  jQuery is working just fine.  The binds are triggering causing the functions to be called in both implementations.

The problem line is

```<code>$(overrideSelector).each(
    function(){
        $(this).val(newVal);
    }
);
</code>```

For example, if I console out newVal in the .each() it will have a value of lets say 'A'.

Then if I console log out $(this).val() it will be 'B'. Then $(this).val(newVal); is run.  After that if I do a console log of $(this).val() it will still be 'B'.

In the comments someone mentioned that I might be using the word this wrong.  Both of these returned 0 javascript errors on Chrome's console. I will give the following code snippet was what was having problems.  I will write the original and then what I replaced it with javascript.

I am aware the name is the same, but that is ok.  The page I am working on is a huge form and the cloned select is just to make the user not have to scroll back to another part of the form.

HTML:

```<code><div id='overrideHolder'>
</div>

<select name='mySelect'>
    <option value='A'>A</option>
    <option value='B'>B</option>
</select>
</code>```

jQuery (this does not work):

```<code>var someClass = (function(){
    var overrideSelector = '[name="mySelect"]';
    ...

    return{
        init : function(){
            $(overrideSelector).clone().appendTo('#overrideHolder');
            $(overrideSelector).each(
                function(){
                    $(this).bind(
                                 'change',
                                 {},
                                 function(){
                                        someClass.overrideTryAgain(this);
                                 }
                    );
                }
            );
        }

        overrideTryAgain : function(element){
            var newVal = $(element).val();

            $(overrideSelector).each(
                function(){
                    $(this).val(newVal);
                }
            );

            ...
         },
         ...
    }
})();

$(document).ready(function(){
    someClass.init();
}
</code>```

Javascript (this works):

```<code>var someClass : (function(){
    var overrideSelector = '[name="mySelect"]';
    ...

    return{
        init : function(){
            $(overrideSelector).clone().appendTo('#overrideHolder');
            $(overrideSelector).each(
                function(){
                    $(this).bind(
                                 'change',
                                 {},
                                 function(){
                                        someClass.overrideTryAgain(this);
                                 }
                    );
                }
            );
        }

        overrideTryAgain : function(element){
            // NOTE: Using javascript instead of jQuery because jQuery was not duplicating the selected value properly
            var newValue = $(element).get(0);
            newValue = newValue.selectedIndex;

            $(overrideSelector).each(
                function(){
                    var currentSelect = $(this).get(0);
                    currentSelect.options[newValue].selected = true;
                }
            );

            ...
        },
        ...
    }
})();

...

$(document).ready(function(){
    someClass.init();
}
</code>```

答:
If the purpose is simply to clone and "synchronise" values between selects your solution seems to be a bit too complex for what it is. First of all you probably do not need all the each loops as the $(overrideSelector) will do that for you automagically. Anyhow here is a simplified version of your code (If I missed the purpose of what your code is supposed to do let me know)</p>

```<code>var someClass = new function() {
         var overrideSelector = '[name="mySelect"]';

        this.init = function() {
            $(overrideSelector).clone().appendTo('#overrideHolder');

            $(overrideSelector).live("change", function() {

                $(overrideSelector).val($(this).val())
            })
        }
    }
    $(document).ready( function() {
        someClass.init();
    })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Simple answer:

The jQuery library my code base was using was out of date.

If yours is up to date try the following:

Step though the unminified version of jQuery to see if the issue is inside the library (which 9 times out of 10 it probably will not be)

When all else fails, just write a pure javascript solution.

Sometimes when I am writing a "class" in javscript with jQuery, jQuery will just not function as it should.  For example today I was doing the following on an input select:

$(this).val(newValue);

This was working in jFiddle just fine, but not working in my project (both had 0 script errors). I tried to isolate the code as much as possible, but to no avail I could not get it to work.

The "solution" for this was to just write straight up javascript to set the value and it worked just fine.

I am not a jQuery master, but this is not the first time I had to write a straight javascript solution when jQuery "failed."  Do any jQuery masters out there know why something like this might happen?  Is there a method of debugging jQuery I am not aware of?  Does anyone else run into these types of problems with jQuery?  If so, do you have a solution?

Update(s):

Aug 25, 2011

I downloaded the most recent version of the jQuery library and stepped through it only to find that the bug was probably resolved between jQuery 1.4.4 and 1.6.2.  I didn't realize the person who handles most of the javascript wasn't keeping the jQuery library up to date.  After stepping through the jQuery 1.4.4 library it seems that jQuery was not able to find my selector for some reason and therefore was never setting the value.  This problem has been resolved in 1.6.2....

Lesson of the week... keep your jQuery library up to date and verify your senior developer's statements when things aren't matching up.

-

I chose the answer I did because it was the only one which really helped me diagnose the source of the problem.  While stepping through the unminified version of jQuery is such a simple solution, I actually should have done that before posting this question.  I will post my findings as to why it didn't work later.

Aug 24, 2011

I agree with the user Sohnee that having a duplicate 'name' isn't bad practice and in some places you actually need it.

I feel rather stupid because the posted code has been wrong for almost a week now.  I have updated the code.  I moved the init function to the public scope.

Aug 22, 2011

While I am partially satisfied that the core of the problem is with duplicate names, I need to know why are duplicate names bad?

I know when dealing with inputs/css/etc you usually except IDs to be unique and classes to represent groups.  I didn't think there were any rules about names, but if someone can explain to me why having duplicate names is bad practice, I will consider that the answer to this problem.

Aug 16, 2011

As for the current answers, I don't think it is a conflict.  jQuery is working just fine.  The binds are triggering causing the functions to be called in both implementations.

The problem line is

$(overrideSelector).each(
    function(){
        $(this).val(newVal);
    }
);

For example, if I console out newVal in the .each() it will have a value of lets say 'A'.

Then if I console log out $(this).val() it will be 'B'. Then $(this).val(newVal); is run.  After that if I do a console log of $(this).val() it will still be 'B'.

In the comments someone mentioned that I might be using the word this wrong.  Both of these returned 0 javascript errors on Chrome's console. I will give the following code snippet was what was having problems.  I will write the original and then what I replaced it with javascript.

I am aware the name is the same, but that is ok.  The page I am working on is a huge form and the cloned select is just to make the user not have to scroll back to another part of the form.

HTML:

<select name='mySelect'>
    <option value='A'>A</option>
    <option value='B'>B</option>
</select>

jQuery (this does not work):

var someClass = (function(){
    var overrideSelector = '[name="mySelect"]';
    ...

    return{
        init : function(){
            $(overrideSelector).clone().appendTo('#overrideHolder');
            $(overrideSelector).each(
                function(){
                    $(this).bind(
                                 'change',
                                 {},
                                 function(){
                                        someClass.overrideTryAgain(this);
                                 }
                    );
                }
            );
        }

        overrideTryAgain : function(element){
            var newVal = $(element).val();

            $(overrideSelector).each(
                function(){
                    $(this).val(newVal);
                }
            );

            ...
         },
         ...
    }
})();

$(document).ready(function(){
    someClass.init();
}

Javascript (this works):

var someClass : (function(){
    var overrideSelector = '[name="mySelect"]';
    ...

    return{
        init : function(){
            $(overrideSelector).clone().appendTo('#overrideHolder');
            $(overrideSelector).each(
                function(){
                    $(this).bind(
                                 'change',
                                 {},
                                 function(){
                                        someClass.overrideTryAgain(this);
                                 }
                    );
                }
            );
        }

        overrideTryAgain : function(element){
            // NOTE: Using javascript instead of jQuery because jQuery was not duplicating the selected value properly
            var newValue = $(element).get(0);
            newValue = newValue.selectedIndex;

            $(overrideSelector).each(
                function(){
                    var currentSelect = $(this).get(0);
                    currentSelect.options[newValue].selected = true;
                }
            );

            ...
        },
        ...
    }
})();

...

$(document).ready(function(){
    someClass.init();
}

Body:
If the purpose is simply to clone and "synchronise" values between selects your solution seems to be a bit too complex for what it is. First of all you probably do not need all the each loops as the $(overrideSelector) will do that for you automagically. Anyhow here is a simplified version of your code (If I missed the purpose of what your code is supposed to do let me know)

var someClass = new function() {
         var overrideSelector = '[name="mySelect"]';

        this.init = function() {
            $(overrideSelector).clone().appendTo('#overrideHolder');

            $(overrideSelector).live("change", function() {

                $(overrideSelector).val($(this).val())
            })
        }
    }
    $(document).ready( function() {
        someClass.init();
    })


问:
Printf left align and right align to obtain a fixed length string without truncation by varying space separators
I would like to obtain the following output from Bash printf using three variables (code, parameter, value):

```<code>[OK] Percentage:                 100%
[OK] Ping time:                  31ms
[OK] Memory usage:                7MB
[KO] Main Drive Temperature:    104°C
[OK] Uptime:               4d 22h 32m
</code>```

Space between parameter 1 and 2 is one space since 1 is always four characters long, while space between 2 and 3 varies to make the total length equal to 37 (arbitrary number). There is no truncation of either parameters or values, if their sum exceeds 37 I just specify a bigger number as the total string length, also for all the other lines.

This gets the job done most of the time, but it's not perfect:

printf '%s %-20s %11s\n' "$1" "$2" "$3"
```

答:
You have all the strings with length. Take a piece of paper and draw it. For example:

```<code>[OK] |--------------------------------|  the whole space
                                 |----|  trailing part
     |---------------------------|       initial part = the whole space - trailing part
</code>```

```<code> width=40
 printf "%s %-*s%s\n" "[OK]" "$((width - ${#3}))" "$2" "$3"
</code>```

Body:
I would like to obtain the following output from Bash printf using three variables (code, parameter, value):

[OK] Percentage:                 100%
[OK] Ping time:                  31ms
[OK] Memory usage:                7MB
[KO] Main Drive Temperature:    104°C
[OK] Uptime:               4d 22h 32m

Space between parameter 1 and 2 is one space since 1 is always four characters long, while space between 2 and 3 varies to make the total length equal to 37 (arbitrary number). There is no truncation of either parameters or values, if their sum exceeds 37 I just specify a bigger number as the total string length, also for all the other lines.

This gets the job done most of the time, but it's not perfect:

printf '%s %-20s %11s\n' "$1" "$2" "$3"

Body:
You have all the strings with length. Take a piece of paper and draw it. For example:

[OK] |--------------------------------|  the whole space
                                 |----|  trailing part
     |---------------------------|       initial part = the whole space - trailing part

 width=40
 printf "%s %-*s%s\n" "[OK]" "$((width - ${#3}))" "$2" "$3"


问:
Programmatic Custom Json Layout Log4j2
I have Java desktop client application that utilizes Log4j2 framework. JSON structure is used when logging the exceptions or infos with custom parameters. I am trying to configure the Log4j2 programmatically for this reason. I am aware that the file based configuration is recommended but it seems like it'd be better to programmatically initialize the framework for my case.

This is the structure I am trying to build.

Custom Json Layout

HttpAppender that will send the logs over HTTP

If HttpAppender fails, it will use JdbcAppender to write to the database

If JdbcAppender fails, it will use FileAppender to write to a log file

I am able to generate JsonLayout but I cannot add custom fields and remove existing ones from the default structure. I've probably checked over 50 articles/questions but none of them worked for me. This is the current code I have.

```<code>    public static void initializeLogger()
    {
       ConfigurationBuilder<BuiltConfiguration> builder =
               ConfigurationBuilderFactory.newConfigurationBuilder();

       builder.setStatusLevel(Level.DEBUG);
       builder.setConfigurationName("DefaultLogger");

       //Creating console appender just to see logging is there.
       AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
            .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
       appenderBuilder.add(builder.newLayout("PatternLayout")
            .addAttribute("pattern", pattern)
            .addAttribute("AdditionalField.key", "asd")
            .addAttribute("AdditionalField.value", "qwe"));
       RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
       rootLogger.add(builder.newAppenderRef("Console"));

       builder.add(appenderBuilder);

       //Creating the file appender
       LayoutComponentBuilder layoutBuilder = builder.newLayout("JsonLayout")
            .addAttribute("compact", "false")
            .addAttribute("AdditionalField", builder.newKeyValuePair("asd", "qwe"));

       ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
            .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "1KB"));
       appenderBuilder = builder.newAppender("LogToRollingFile", "RollingFile")
            .addAttribute("fileName", fileName)
            .addAttribute("filePattern", "applog-%d{MM-dd-yy-HH-mm-ss}.log.")
            .add(layoutBuilder)
            .addComponent(triggeringPolicy);
       builder.add(appenderBuilder);

       rootLogger.add(builder.newAppenderRef("LogToRollingFile"));
       builder.add(rootLogger);

       Configurator.reconfigure(builder.build());
}
</code>```

This code prints to the console and writes Json formatted logging to a file. The custom values are not added to the Json. I tried to create JsonLayout via its builder but I cannot add it to the builder itself.

```<code>//Probably creating a new layout instance with additional fields
//might be helpful but I cannot use this in the builder above.
JsonLayout layout = JsonLayout.newBuilder()
    .setAdditionalFields(new KeyValuePair [] {
         new KeyValuePair("asd", "qwe"),
         new KeyValuePair("zxc", "rty"),
     }).build();
</code>```

The parameters that I need to add to the Json is dynamic and I do not know the keys and values of the custom nodes. At this stage, I am trying to create a custom Json Layout at write it to the file.

I might be doing this completely wrong so please advice! I'm open to suggestions.
Thanks.

答:
You can use the following class to subtract any of the attributes you want in the class from the log.

```<code>     import com.fanap.midhco.applicationUtil.JsonUtil;
     import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;
     import com.fasterxml.jackson.databind.ObjectWriter;
     import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
     import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
     import org.apache.logging.log4j.core.Layout;
     import org.apache.logging.log4j.core.LogEvent;
     import org.apache.logging.log4j.core.config.Node;
     import org.apache.logging.log4j.core.config.plugins.Plugin;
     import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
     import org.apache.logging.log4j.core.config.plugins.PluginFactory;
     import org.apache.logging.log4j.core.impl.Log4jLogEvent;
     import org.apache.logging.log4j.core.jackson.JsonConstants;
     import org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper;
     import org.apache.logging.log4j.core.layout.AbstractStringLayout;
     import org.apache.logging.log4j.core.util.StringBuilderWriter;
     import org.apache.logging.log4j.util.Strings;

     import java.io.IOException;
     import java.nio.charset.StandardCharsets;
     import java.util.HashSet;
     import java.util.Set;

     @Plugin(name = "MineCustLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
     public class MineCustLayout extends AbstractStringLayout {

         private final ObjectWriter objectWriter;

         @PluginFactory
         public static MineCustLayout createLayout(
                 @PluginAttribute(value = "locationInfo", defaultBoolean = false) final boolean locationInfo, @PluginAttribute(value = "eventEol", defaultBoolean = true) final boolean eventEol
         ) {
             final SimpleFilterProvider filters = new SimpleFilterProvider();
             final Set<String> except = new HashSet<>();
             if (!locationInfo) {
                 except.add(JsonConstants.ELT_SOURCE);
             }
             except.add("loggerFqcn");
             except.add("level");
             except.add("timeMillis");
             except.add("instant");
             except.add("thread");
             except.add("loggerName");
             except.add("threadId");
             except.add("threadPriority");
             except.add("contextMap");
             except.add("endOfBatch");
             except.add(JsonConstants.ELT_NANO_TIME);
             filters.addFilter(Log4jLogEvent.class.getName(), SimpleBeanPropertyFilter.serializeAllExcept(except));
             final ObjectWriter writer = new Log4jJsonObjectMapper().writer(new MinimalPrettyPrinter());
             return new MineCustLayout(writer.with(filters));
         }

         public MineCustLayout(ObjectWriter objectWriter) {
             super(StandardCharsets.UTF_8, null, null);
             this.objectWriter = objectWriter;
         }

         @Override
         public String toSerializable(LogEvent event) {
             final StringBuilderWriter writer = new StringBuilderWriter();
             try {
                 objectWriter.writeValue(writer, event);
     //            writer.write('\n');
                 return JsonUtil.getJsonObject(writer.toString()).get("message").toString() + '\n';
             } catch (final IOException e) {
                 LOGGER.error(e);
                 return Strings.EMPTY;
             }
         }
     }
</code>```

And also inside the config:

```<code>     <RollingFile name="logFile_json" fileName="${sys:catalina.home}/logs/logFile_json.json"
                 filePattern="${sys:catalina.home}/logs/logFile_json-%d{MM-dd-yyyy}-%i.json">
        <MineCustLayout>
        </MineCustLayout>
        <Policies>
            <SizeBasedTriggeringPolicy size="50 MB"/>
        </Policies>
        <DefaultRolloverStrategy min="1" max="100"/>
     </RollingFile>
</code>```

Title: Programmatic Custom Json Layout Log4j2

Body:
I have Java desktop client application that utilizes Log4j2 framework. JSON structure is used when logging the exceptions or infos with custom parameters. I am trying to configure the Log4j2 programmatically for this reason. I am aware that the file based configuration is recommended but it seems like it'd be better to programmatically initialize the framework for my case.

This is the structure I am trying to build.

Custom Json Layout

HttpAppender that will send the logs over HTTP

If HttpAppender fails, it will use JdbcAppender to write to the database

If JdbcAppender fails, it will use FileAppender to write to a log file

I am able to generate JsonLayout but I cannot add custom fields and remove existing ones from the default structure. I've probably checked over 50 articles/questions but none of them worked for me. This is the current code I have.

    public static void initializeLogger()
    {
       ConfigurationBuilder<BuiltConfiguration> builder =
               ConfigurationBuilderFactory.newConfigurationBuilder();

       builder.setStatusLevel(Level.DEBUG);
       builder.setConfigurationName("DefaultLogger");

       //Creating console appender just to see logging is there.
       AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
            .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
       appenderBuilder.add(builder.newLayout("PatternLayout")
            .addAttribute("pattern", pattern)
            .addAttribute("AdditionalField.key", "asd")
            .addAttribute("AdditionalField.value", "qwe"));
       RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
       rootLogger.add(builder.newAppenderRef("Console"));

       builder.add(appenderBuilder);

       //Creating the file appender
       LayoutComponentBuilder layoutBuilder = builder.newLayout("JsonLayout")
            .addAttribute("compact", "false")
            .addAttribute("AdditionalField", builder.newKeyValuePair("asd", "qwe"));

       ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
            .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "1KB"));
       appenderBuilder = builder.newAppender("LogToRollingFile", "RollingFile")
            .addAttribute("fileName", fileName)
            .addAttribute("filePattern", "applog-%d{MM-dd-yy-HH-mm-ss}.log.")
            .add(layoutBuilder)
            .addComponent(triggeringPolicy);
       builder.add(appenderBuilder);

       rootLogger.add(builder.newAppenderRef("LogToRollingFile"));
       builder.add(rootLogger);

       Configurator.reconfigure(builder.build());
}

This code prints to the console and writes Json formatted logging to a file. The custom values are not added to the Json. I tried to create JsonLayout via its builder but I cannot add it to the builder itself.

//Probably creating a new layout instance with additional fields
//might be helpful but I cannot use this in the builder above.
JsonLayout layout = JsonLayout.newBuilder()
    .setAdditionalFields(new KeyValuePair [] {
         new KeyValuePair("asd", "qwe"),
         new KeyValuePair("zxc", "rty"),
     }).build();

The parameters that I need to add to the Json is dynamic and I do not know the keys and values of the custom nodes. At this stage, I am trying to create a custom Json Layout at write it to the file.

I might be doing this completely wrong so please advice! I'm open to suggestions.
Thanks.

Body:
You can use the following class to subtract any of the attributes you want in the class from the log.

     import com.fanap.midhco.applicationUtil.JsonUtil;
     import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;
     import com.fasterxml.jackson.databind.ObjectWriter;
     import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
     import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
     import org.apache.logging.log4j.core.Layout;
     import org.apache.logging.log4j.core.LogEvent;
     import org.apache.logging.log4j.core.config.Node;
     import org.apache.logging.log4j.core.config.plugins.Plugin;
     import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
     import org.apache.logging.log4j.core.config.plugins.PluginFactory;
     import org.apache.logging.log4j.core.impl.Log4jLogEvent;
     import org.apache.logging.log4j.core.jackson.JsonConstants;
     import org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper;
     import org.apache.logging.log4j.core.layout.AbstractStringLayout;
     import org.apache.logging.log4j.core.util.StringBuilderWriter;
     import org.apache.logging.log4j.util.Strings;

     import java.io.IOException;
     import java.nio.charset.StandardCharsets;
     import java.util.HashSet;
     import java.util.Set;

     @Plugin(name = "MineCustLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
     public class MineCustLayout extends AbstractStringLayout {

         private final ObjectWriter objectWriter;

         @PluginFactory
         public static MineCustLayout createLayout(
                 @PluginAttribute(value = "locationInfo", defaultBoolean = false) final boolean locationInfo, @PluginAttribute(value = "eventEol", defaultBoolean = true) final boolean eventEol
         ) {
             final SimpleFilterProvider filters = new SimpleFilterProvider();
             final Set<String> except = new HashSet<>();
             if (!locationInfo) {
                 except.add(JsonConstants.ELT_SOURCE);
             }
             except.add("loggerFqcn");
             except.add("level");
             except.add("timeMillis");
             except.add("instant");
             except.add("thread");
             except.add("loggerName");
             except.add("threadId");
             except.add("threadPriority");
             except.add("contextMap");
             except.add("endOfBatch");
             except.add(JsonConstants.ELT_NANO_TIME);
             filters.addFilter(Log4jLogEvent.class.getName(), SimpleBeanPropertyFilter.serializeAllExcept(except));
             final ObjectWriter writer = new Log4jJsonObjectMapper().writer(new MinimalPrettyPrinter());
             return new MineCustLayout(writer.with(filters));
         }

         public MineCustLayout(ObjectWriter objectWriter) {
             super(StandardCharsets.UTF_8, null, null);
             this.objectWriter = objectWriter;
         }

         @Override
         public String toSerializable(LogEvent event) {
             final StringBuilderWriter writer = new StringBuilderWriter();
             try {
                 objectWriter.writeValue(writer, event);
     //            writer.write('\n');
                 return JsonUtil.getJsonObject(writer.toString()).get("message").toString() + '\n';
             } catch (final IOException e) {
                 LOGGER.error(e);
                 return Strings.EMPTY;
             }
         }
     }

And also inside the config:

     <RollingFile name="logFile_json" fileName="${sys:catalina.home}/logs/logFile_json.json"
                 filePattern="${sys:catalina.home}/logs/logFile_json-%d{MM-dd-yyyy}-%i.json">
        <MineCustLayout>
        </MineCustLayout>
        <Policies>
            <SizeBasedTriggeringPolicy size="50 MB"/>
        </Policies>
        <DefaultRolloverStrategy min="1" max="100"/>
     </RollingFile>


问:
Is there a way to sort logs in AWS Log Insights the same way they appear in the log file?
I have a query in Log Insights that prints some messages from the web.stdout.log file and sorts them by @timestamp.

When the timestamp is the same for two messages, it prints them with no order.
Is there any way to sort the messages by the same order as they are printed in the original log file (web.stdout.log)?

答:
Your log will keep the messages in order of appearance.

A Logs Insights query will treat @timestamp as a text field.

The granularity is to the millisecond, so two lines written on the same millisecond will be treated by the query as equal values. Just like other fields with equal values will.

There will be other ways to parse your log and keep the items in order, but not within Logs Insights with data from log groups.


问:
hidden variable in html
I am working in Ruby Sinatra.  In Ruby, I create a nokogiri object (@xml) that the erb page has access to.  In the post, I need to have access to that same object, so I create a hidden variable like so:

```<code>    <input type="hidden" name="xml" value= '<%= @xml %>' >
</code>```

However, in some cases, the page displays a bunch of text from the @xml object that I don't want displayed.  As a workaround, I moved it offscreen, like this:

```<code><div style="position:absolute; left:5000px; top:200px;">
    <input type="hidden" name="xml" value= '<%= @xml %>' >
</div>
</code>```

but there must be a better way.  Suggestions?  Thanks.

答:
The problem could be in content of the @xml object. You should encode the special characters before printing the variable into value attribute.

If the @xml object contains a single quote, browser will interpret it like the end of value attribute.

Take a look at HTMLentities library for Ruby.

Title: hidden variable in html

Body:
I am working in Ruby Sinatra.  In Ruby, I create a nokogiri object (@xml) that the erb page has access to.  In the post, I need to have access to that same object, so I create a hidden variable like so:

    <input type="hidden" name="xml" value= '<%= @xml %>' >

However, in some cases, the page displays a bunch of text from the @xml object that I don't want displayed.  As a workaround, I moved it offscreen, like this:

    <input type="hidden" name="xml" value= '<%= @xml %>' >

but there must be a better way.  Suggestions?  Thanks.


问:
xdebug_info() shows old values
My Xdebug doesn't work on Ubuntu 20.4. I get the error:

[Step Debug] Creating socket for 'localhost:9009', poll success, but error: Operation now in progress (29).

I have already made some changes in the /etc/php/8.1/mods-available/xdebug.ini file. Restarting Apache via service apache2 restart or via /etc/init.d/apache2 force-reload does not change anything for xdebug_info(). The new values are only displayed after restarting the computer.

Does xdebug_info() show a mirage? Or are the values real at this point? Which blockage do I have to fix instead?

答: xdebug_info() shows the current accurate, and real values.

Title: xdebug_info() shows old values


问:
WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding
I've got a WCF Service running on my local IIS server. I've added it as a service reference to a C# Website Project and it adds fine and generates the proxy classes automatically.

However, when I try and call any of the service contracts, I get the following error:

Description: An unhandled exception occurred during the
execution of the current web  request.
Please review the stack trace for more
information about the error and where
it originated in the code.

Exception Details: System.ServiceModel.ProtocolException:
The content type text/html;
charset=utf-8 of the response message
does not match the content type of the
binding (application/soap+xml;
charset=utf-8). If using a custom
encoder, be sure that the
IsContentTypeSupported method is
implemented properly. The first 1024
bytes of the response were: '

     function
bredir(d,u,r,v,c){var w,h,wd,hd,bi;var
b=false;var p=false;var
s=[[300,250,false],[250,250,false],[240,400,false],[336,280,false],[180,150,false],[468,60,false],[234,60,false],[88,31,false],[120,90,false],[120,60,false],[120,240,false],[125,125,false],[728,90,false],[160,600,false],[120,600,false],[300,600,false],[300,125,false],[530,300,false],[190,200,false],[470,250,false],[720,300,true],[500,350,true],[550,480,true]];if(typeof(window.innerHeight)=='number'){h=window.innerHeight;w=window.innerWidth;}else
if(typeof(document.body.offsetHeight)=='number'){h=document.body.offsetHeight;w=document.body.offsetWidth;}for(var
i=0;i

I also have a console application which also communicates with the WCF Service and the console app is able to call methods fine without getting this error.

Below are excerpts from my config files.

WCF Service Web.Config:

```<code><system.serviceModel>
   <services>
      <service name="ScraperService" behaviorConfiguration="ScraperServiceBehavior">
         <endpoint address=""
                   binding="wsHttpBinding"
                   bindingConfiguration="WSHttpBinding_IScraperService"
                   contract="IScraperService" />
         <endpoint address="mex"
                   binding="mexHttpBinding"
                   contract="IMetadataExchange" />
         <host>
            <baseAddresses>
                <add baseAddress="http://example.com" />
            </baseAddresses>
         </host>
      </service>
   </services>
   <bindings>
       <wsHttpBinding>
           <binding name="WSHttpBinding_IScraperService"
                    bypassProxyOnLocal="false" transactionFlow="false"
                    hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="2000000" maxReceivedMessageSize="2000000"
                    messageEncoding="Text" textEncoding="utf-8"
                    useDefaultWebProxy="true" allowCookies="false">
               <readerQuotas
                     maxDepth="2000000" maxStringContentLength="2000000"
                     maxArrayLength="2000000" maxBytesPerRead="2000000"
                     maxNameTableCharCount="2000000" />
               <reliableSession
                     enabled="false" ordered="true" inactivityTimeout="00:10:00" />
               <security mode="Message">
                   <message clientCredentialType="Windows"
                            negotiateServiceCredential="true"
                            algorithmSuite="Default"
                            establishSecurityContext="true" />
               </security>
            </binding>
          </wsHttpBinding>
      </bindings>
      <behaviors>
          <serviceBehaviors>
              <behavior name="ScraperServiceBehavior">
                  <serviceMetadata httpGetEnabled="true" />
                  <serviceDebug includeExceptionDetailInFaults="true" />
              </behavior>
          </serviceBehaviors>
     </behaviors>
</system.serviceModel>
</code>```

Website Project Service Client Web.Config:

```<code><system.serviceModel>
   <bindings>
      <wsHttpBinding>
          <binding name="WSHttpBinding_IScraperService"
              closeTimeout="00:01:00" openTimeout="00:01:00"
              receiveTimeout="00:10:00" sendTimeout="00:01:00"
              bypassProxyOnLocal="false" transactionFlow="false"
              hostNameComparisonMode="StrongWildcard"
              maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
              messageEncoding="Text" textEncoding="utf-8"
              useDefaultWebProxy="true" allowCookies="false">
              <readerQuotas
                  maxDepth="32" maxStringContentLength="8192"
                  maxArrayLength="16384" maxBytesPerRead="4096"
                  maxNameTableCharCount="16384" />
              <reliableSession enabled="false"
                  ordered="true" inactivityTimeout="00:10:00" />
              <security mode="Message">
                  <transport clientCredentialType="Windows"
                       proxyCredentialType="None" realm="" />
                  <message clientCredentialType="Windows"
                       negotiateServiceCredential="true"
                       algorithmSuite="Default" />
              </security>
          </binding>
       </wsHttpBinding>
    </bindings>
<client>
        <endpoint name="WSHttpBinding_IScraperService"
            address="http://example.com/ScraperService.svc"
            binding="wsHttpBinding"
            bindingConfiguration="WSHttpBinding_IScraperService"
            contract="ScraperService.IScraperService" >
           <identity>
               <servicePrincipalName value="host/FreshNET-II" />
           </identity>
        </endpoint>
     </client>
</system.serviceModel>
</code>```

答:
This error happens also when :

targetNamespace is wrongly defined in the wsdl
or
when the ns2 is wrongly defined in the response (different from the ns in the request) . For example
request

```<code><.. xmlns:des="http://zef/">
</code>```

response

```<code><ns2:authenticateResponse xmlns:ns2="http://xyz/">
</code>```

Body:
I've got a WCF Service running on my local IIS server. I've added it as a service reference to a C# Website Project and it adds fine and generates the proxy classes automatically.

However, when I try and call any of the service contracts, I get the following error:

Description: An unhandled exception occurred during the
execution of the current web  request.
Please review the stack trace for more
information about the error and where
it originated in the code.

Exception Details: System.ServiceModel.ProtocolException:
The content type text/html;
charset=utf-8 of the response message
does not match the content type of the
binding (application/soap+xml;
charset=utf-8). If using a custom
encoder, be sure that the
IsContentTypeSupported method is
implemented properly. The first 1024
bytes of the response were: '

     function
bredir(d,u,r,v,c){var w,h,wd,hd,bi;var
b=false;var p=false;var
s=[[300,250,false],[250,250,false],[240,400,false],[336,280,false],[180,150,false],[468,60,false],[234,60,false],[88,31,false],[120,90,false],[120,60,false],[120,240,false],[125,125,false],[728,90,false],[160,600,false],[120,600,false],[300,600,false],[300,125,false],[530,300,false],[190,200,false],[470,250,false],[720,300,true],[500,350,true],[550,480,true]];if(typeof(window.innerHeight)=='number'){h=window.innerHeight;w=window.innerWidth;}else
if(typeof(document.body.offsetHeight)=='number'){h=document.body.offsetHeight;w=document.body.offsetWidth;}for(var
i=0;i

I also have a console application which also communicates with the WCF Service and the console app is able to call methods fine without getting this error.

Below are excerpts from my config files.

WCF Service Web.Config:

<system.serviceModel>
   <services>
      <service name="ScraperService" behaviorConfiguration="ScraperServiceBehavior">
         <endpoint address=""
                   binding="wsHttpBinding"
                   bindingConfiguration="WSHttpBinding_IScraperService"
                   contract="IScraperService" />
         <endpoint address="mex"
                   binding="mexHttpBinding"
                   contract="IMetadataExchange" />
         <host>
            <baseAddresses>
                <add baseAddress="http://example.com" />
            </baseAddresses>
         </host>
      </service>
   </services>
   <bindings>
       <wsHttpBinding>
           <binding name="WSHttpBinding_IScraperService"
                    bypassProxyOnLocal="false" transactionFlow="false"
                    hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="2000000" maxReceivedMessageSize="2000000"
                    messageEncoding="Text" textEncoding="utf-8"
                    useDefaultWebProxy="true" allowCookies="false">
               <readerQuotas
                     maxDepth="2000000" maxStringContentLength="2000000"
                     maxArrayLength="2000000" maxBytesPerRead="2000000"
                     maxNameTableCharCount="2000000" />
               <reliableSession
                     enabled="false" ordered="true" inactivityTimeout="00:10:00" />
               <security mode="Message">
                   <message clientCredentialType="Windows"
                            negotiateServiceCredential="true"
                            algorithmSuite="Default"
                            establishSecurityContext="true" />
               </security>
            </binding>
          </wsHttpBinding>
      </bindings>
      <behaviors>
          <serviceBehaviors>
              <behavior name="ScraperServiceBehavior">
                  <serviceMetadata httpGetEnabled="true" />
                  <serviceDebug includeExceptionDetailInFaults="true" />
              </behavior>
          </serviceBehaviors>
     </behaviors>
</system.serviceModel>

Website Project Service Client Web.Config:

<system.serviceModel>
   <bindings>
      <wsHttpBinding>
          <binding name="WSHttpBinding_IScraperService"
              closeTimeout="00:01:00" openTimeout="00:01:00"
              receiveTimeout="00:10:00" sendTimeout="00:01:00"
              bypassProxyOnLocal="false" transactionFlow="false"
              hostNameComparisonMode="StrongWildcard"
              maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
              messageEncoding="Text" textEncoding="utf-8"
              useDefaultWebProxy="true" allowCookies="false">
              <readerQuotas
                  maxDepth="32" maxStringContentLength="8192"
                  maxArrayLength="16384" maxBytesPerRead="4096"
                  maxNameTableCharCount="16384" />
              <reliableSession enabled="false"
                  ordered="true" inactivityTimeout="00:10:00" />
              <security mode="Message">
                  <transport clientCredentialType="Windows"
                       proxyCredentialType="None" realm="" />
                  <message clientCredentialType="Windows"
                       negotiateServiceCredential="true"
                       algorithmSuite="Default" />
              </security>
          </binding>
       </wsHttpBinding>
    </bindings>
<client>
        <endpoint name="WSHttpBinding_IScraperService"
            address="http://example.com/ScraperService.svc"
            binding="wsHttpBinding"
            bindingConfiguration="WSHttpBinding_IScraperService"
            contract="ScraperService.IScraperService" >
           <identity>
               <servicePrincipalName value="host/FreshNET-II" />
           </identity>
        </endpoint>
     </client>
</system.serviceModel>

Body:
This error happens also when :

targetNamespace is wrongly defined in the wsdl
or
when the ns2 is wrongly defined in the response (different from the ns in the request) . For example
request

<.. xmlns:des="http://zef/">

response

<ns2:authenticateResponse xmlns:ns2="http://xyz/">


问:
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/1/
I am trying to communicate between Django and Python file but I am getting below error :

requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/1/ (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

I have created a Python file named test.py In a Django app and trying to communicate between them. My Python file contains below code :

```<code>import requests
BASE_URL='http://127.0.0.1:8000/'
ENDPOINT='api/'
def get_resource(id):
    resp=requests.get(BASE_URL+ENDPOINT+id+'/')
    print(resp.status_code)
    print(resp.json())
id=input("Enter some ID: ")
get_resource(id)
</code>```

Models.py contains:-

```<code>from django.db import models

# Create your models here.
class Employee(models.Model):
    eno=models.IntegerField()
    ename=models.CharField(max_length=70)
    esal=models.FloatField()
    eaddr=models.CharField(max_length=100)
</code>```

Admin.py contains:-

```<code>from django.contrib import admin
from testapp.models import Employee
# Register your models here.
class EmployeeAdmin(admin.ModelAdmin):
    list_display=  ['id','eno','ename','esal','eaddr']

admin.site.register(Employee,EmployeeAdmin)
</code>```

My Views.py contains:-

```<code>from django.shortcuts import render
from django.views.generic import View
from testapp.models import Employee
import json
from django.http import HttpResponse

class EmployeeDetailCBV(View):
def get(self,request,id,*args,**kwargs):
    emp = Employee.objects.get(id=id)
    emp_data = {'eno':emp.eno , 'ename':emp.ename , 'esal':emp.esal , 'eaddr':emp.eaddr}
    json_data=json.dumps(emp_data)
    return HttpResponse(json_data , content_type='application/json')
</code>```

urls.py file contains:-

```<code>from django.contrib import admin
from django.urls import path
from testapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/(?P<id>\d+)/$', views.EmployeeDetailCBV.as_view()),
]
</code>```

Getting error like :

requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/1/ (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

Please help me. Thank you techies....

答:
To launch your code locally, use your fixed IPv4 address.

For Windows users: open a command prompt (cmd) and run the ipconfig command, retrieve the IP@ which is at IPv4 address. . . . . . . . . . . . . .: it is generally of type 192.168.x.x

IPv4 address in command prompt

then go to your settings.py and add: ALLOWED_HOSTS = ['*']

Body:
I am trying to communicate between Django and Python file but I am getting below error :

requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/1/ (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

I have created a Python file named test.py In a Django app and trying to communicate between them. My Python file contains below code :

import requests
BASE_URL='http://127.0.0.1:8000/'
ENDPOINT='api/'
def get_resource(id):
    resp=requests.get(BASE_URL+ENDPOINT+id+'/')
    print(resp.status_code)
    print(resp.json())
id=input("Enter some ID: ")
get_resource(id)

Models.py contains:-

from django.db import models

# Create your models here.
class Employee(models.Model):
    eno=models.IntegerField()
    ename=models.CharField(max_length=70)
    esal=models.FloatField()
    eaddr=models.CharField(max_length=100)

Admin.py contains:-

from django.contrib import admin
from testapp.models import Employee
# Register your models here.
class EmployeeAdmin(admin.ModelAdmin):
    list_display=  ['id','eno','ename','esal','eaddr']

admin.site.register(Employee,EmployeeAdmin)

My Views.py contains:-

from django.shortcuts import render
from django.views.generic import View
from testapp.models import Employee
import json
from django.http import HttpResponse

class EmployeeDetailCBV(View):
def get(self,request,id,*args,**kwargs):
    emp = Employee.objects.get(id=id)
    emp_data = {'eno':emp.eno , 'ename':emp.ename , 'esal':emp.esal , 'eaddr':emp.eaddr}
    json_data=json.dumps(emp_data)
    return HttpResponse(json_data , content_type='application/json')

urls.py file contains:-

from django.contrib import admin
from django.urls import path
from testapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/(?P<id>\d+)/$', views.EmployeeDetailCBV.as_view()),
]

Getting error like :

requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /api/1/ (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

Please help me. Thank you techies....


问:
Using HTML5/Canvas/JavaScript to take in-browser screenshots
Google's "Report a Bug" or "Feedback Tool" lets you select an area of your browser window to create a screenshot that is submitted with your feedback about a bug.

Screenshot by Jason Small, posted in a duplicate question.

How are they doing this?  Google's JavaScript feedback API is loaded from here and their overview of the feedback module will demonstrate the screenshot capability.

答:
You can try my new JS library: screenshot.js.

It's enable to take real screenshot.

You load the script:

```
<p>and take screenshot:</p>
<pre class="lang-js prettyprint-override"><code>new Screenshot({success: img => {
        // callback function
        myimage = img;
    }});
</code>```

You can read more options in project page.

Body:
You can try my new JS library: screenshot.js.

It's enable to take real screenshot.

You load the script:

<script src="https://raw.githubusercontent.com/amiad/screenshot.js/master/screenshot.js"></script>

and take screenshot:

new Screenshot({success: img => {
        // callback function
        myimage = img;
    }});

You can read more options in project page.


问:
facing problem while try to read ,tab file in R
I am using illumina sequencing based data. I have problems while trying to read .tab file in R.
I tried to run working directory and get this error,

```<code>getwd()

setwd("D:/plan A/find new data set/selecting dataset procedure/ENRICHMENT/FILES/WILD TYPE/DORSAL DG")
</code>```

the result is

Error in setwd("D:/plan A/find new data set/selecting dataset procedure/ENRICHMENT/\n \n FILES/WILD TYPE/DORSAL DG") :
cannot change working directory

答:
You could use choose.dir() to select the working directory but this is OS-Specific...

```<code>choose.dir(getwd(), "Search for the specific folder")
</code>```

Another OS-Independent way is to use:

```<code>library(tcltk)
dir <- tclvalue(tkchooseDirectory())
setwd(dir)
</code>```

ALSO in your error "/ENRICHMENT/\n \n FILES/" you get \n's which causes the problem. Just set it to be in one line while copying and issue should also be solved!

Body:
I am using illumina sequencing based data. I have problems while trying to read .tab file in R.
I tried to run working directory and get this error,

getwd()

setwd("D:/plan A/find new data set/selecting dataset procedure/ENRICHMENT/FILES/WILD TYPE/DORSAL DG")

the result is

Error in setwd("D:/plan A/find new data set/selecting dataset procedure/ENRICHMENT/\n \n FILES/WILD TYPE/DORSAL DG") :
cannot change working directory

Body:
You could use choose.dir() to select the working directory but this is OS-Specific...

choose.dir(getwd(), "Search for the specific folder")

Another OS-Independent way is to use:

library(tcltk)
dir <- tclvalue(tkchooseDirectory())
setwd(dir)

ALSO in your error "/ENRICHMENT/\n \n FILES/" you get \n's which causes the problem. Just set it to be in one line while copying and issue should also be solved!


问:
I am having trouble updating node and npm
I'm currently using Ubuntu 18.04.6 LTS and I want to upgrade nodejs to version 16 but, unable to.
I have almost spent 4 hours trying to resolve this and stackoverflow is my last option.

Problems

Sudo apt-get update gives:
error about some docker repo 404  Not Found [IP: 13.35.169.116 443]

I followed this tutorial and it did not help.

Running node --version gives v0.10.31

Running npm --version gives This

答: Node is not up to date in ubuntu's ppa. I would recommend just using nvm ( node version manager ) to install the version you need: https://github.com/nvm-sh/nvm/blob/master/README.md</p>


问:
How do I play a sound in Mac OS?
I want to play a .mp3 file in an Objective-C app being designed for use on Mac OS X Lion 10.7, not for the iPhone. Thanks!</p>

答:
Take a look at the NSSound class:

```<code>NSSound *sound = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"mySound" ofType:@"mp3"] byReference:NO];
[sound play];
[sound release];
</code>```

Title: How do I play a sound in Mac OS?

Body:
Take a look at the NSSound class:

NSSound *sound = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"mySound" ofType:@"mp3"] byReference:NO];
[sound play];
[sound release];


问:
How to get average value from SQL(Superset, SQLAlchemy under PostgreSQL) timestamp
I tried to calculate the average timestamp and the query is successfully executed directly in postgresql, but when executed through superset(python's SQLAlchemy), an error occurs when converting an integer to a timestamp. How can I fix the error or do it in another way?

Query1:

```<code>select
    to_timestamp(
        avg(
            cast(
                extract(epoch from last_checked_at) as integer)
                )::integer
        ) as datetime
from
    the_best_table
</code>```

Query1 postgresql result:

datetime

2022-02-06 03:15:19+00

Query1 superset(SQLAlchemy) result:

PostgreSQL Error postgresql error: '>=' not supported between
instances of 'datetime.timedelta' and 'int'

This may be triggered by: Issue 1002 - The database returned an
unexpected error. link

Also below you can see the results of the query to convert an integer to datetime. The problem is in this part of the code.

Query2:

```<code>select to_timestamp(1644117319) as datetime
</code>```

Query2 postgresql result:

datetime

2022-02-06 03:15:19+00

Query2 superset(SQLAlchemy) result:

PostgreSQL Error postgresql error: '>=' not supported between
instances of 'datetime.timedelta' and 'int'

This may be triggered by: Issue 1002 - The database returned an
unexpected error. link

答:
I was not able to reproduce the error.
Works fine.

Setup in Postgresql Database:

```<code>postgres=> create table the_best_table(last_checked_at timestamp);
CREATE TABLE
postgres=> insert into the_best_table values(now());
INSERT 0 1
postgres=> select
    to_timestamp(
        avg(
            cast(
                extract(epoch from last_checked_at) as integer)
                )::integer
        ) as datetime
from
    the_best_table;
        datetime
------------------------
 2022-02-07 04:54:06+09
(1 row)
</code>```

The exact two queries run fine for me in SQLAlchemy:

```<code>>>> from sqlalchemy import create_engine
>>> engine = create_engine('postgresql+pg8000://<username>:<passwd>@192.xxx.xxx.123/postgres')
>>>  metadata.create_all(engine)
>>> with engine.connect() as con:
...     rs = con.execute('select to_timestamp(avg(cast(extract(epoch from last_checked_at) as integer))::integer ) as datetime from the_best_table;')
...     for row in rs:
...             print(row)
...
(datetime.datetime(2022, 2, 7, 4, 54, 6, tzinfo=datetime.timezone(datetime.timedelta(seconds=32400))),)
>>> with engine.connect() as con:
...     rs = con.execute('select to_timestamp(1644117319) as datetime;')
...     for row in rs:
...             print(row)
...
(datetime.datetime(2022, 2, 6, 12, 15, 19, tzinfo=datetime.timezone(datetime.timedelta(seconds=32400))),)
</code>```

Body:
I tried to calculate the average timestamp and the query is successfully executed directly in postgresql, but when executed through superset(python's SQLAlchemy), an error occurs when converting an integer to a timestamp. How can I fix the error or do it in another way?

Query1:

select
    to_timestamp(
        avg(
            cast(
                extract(epoch from last_checked_at) as integer)
                )::integer
        ) as datetime
from
    the_best_table

Query1 postgresql result:

datetime

2022-02-06 03:15:19+00

Query1 superset(SQLAlchemy) result:

PostgreSQL Error postgresql error: '>=' not supported between
instances of 'datetime.timedelta' and 'int'

This may be triggered by: Issue 1002 - The database returned an
unexpected error. link

Also below you can see the results of the query to convert an integer to datetime. The problem is in this part of the code.

Query2:

select to_timestamp(1644117319) as datetime

Query2 postgresql result:

datetime

2022-02-06 03:15:19+00

Query2 superset(SQLAlchemy) result:

PostgreSQL Error postgresql error: '>=' not supported between
instances of 'datetime.timedelta' and 'int'

This may be triggered by: Issue 1002 - The database returned an
unexpected error. link

Body:
I was not able to reproduce the error.
Works fine.

Setup in Postgresql Database:

postgres=> create table the_best_table(last_checked_at timestamp);
CREATE TABLE
postgres=> insert into the_best_table values(now());
INSERT 0 1
postgres=> select
    to_timestamp(
        avg(
            cast(
                extract(epoch from last_checked_at) as integer)
                )::integer
        ) as datetime
from
    the_best_table;
        datetime
------------------------
 2022-02-07 04:54:06+09
(1 row)

The exact two queries run fine for me in SQLAlchemy:

>>> from sqlalchemy import create_engine
>>> engine = create_engine('postgresql+pg8000://<username>:<passwd>@192.xxx.xxx.123/postgres')
>>>  metadata.create_all(engine)
>>> with engine.connect() as con:
...     rs = con.execute('select to_timestamp(avg(cast(extract(epoch from last_checked_at) as integer))::integer ) as datetime from the_best_table;')
...     for row in rs:
...             print(row)
...
(datetime.datetime(2022, 2, 7, 4, 54, 6, tzinfo=datetime.timezone(datetime.timedelta(seconds=32400))),)
>>> with engine.connect() as con:
...     rs = con.execute('select to_timestamp(1644117319) as datetime;')
...     for row in rs:
...             print(row)
...
(datetime.datetime(2022, 2, 6, 12, 15, 19, tzinfo=datetime.timezone(datetime.timedelta(seconds=32400))),)


问:
Layout problem after integrating a slideshow html css
one page of my website is locking like that:
http://www.pflanzspass.bplaced.net/

Yesterdy I tried to integrate a slideshow:
http://www.pflanzspass.bplaced.net/indextest.php

The slideshow is working, but now there are some new layout problems:

now:

before:

I don't know why.

This is my new css-Code for the slideshow:

```<code>  * {box-sizing: border-box}
  /*body {
  font-family: Verdana, sans-serif;
  margin:0
  }*/
  .mySlides {display: none}
  img {vertical-align: middle;}
  .slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
  }
  /* Next & previous buttons */
  .prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
  }
  /* Position the "next button" to the right */
  .next {
  right: 0;
  border-radius: 3px 0 0 3px;
  }
  /* On hover, add a black background color with a little bit see-through */
  .prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
  }
  /* Caption text */
  .text {
  color: #ffffff;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
  }
  /* Number text (1/3 etc) */
  .numbertext {
  color: #ffffff;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
  }
  /* The dots/bullets/indicators */
  .dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #999999;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
  }
  .active, .dot:hover {
  background-color: #111111;
  }
  /* Fading animation */
  .fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
  }
  @-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
  }
  @keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
  }
  /* On smaller screens, decrease text size */
  @media only screen and (max-width: 300px) {
  .prev, .next,.text {font-size: 11px}
  }
</code>```

This is the css-code, already online before added the slide-show css-code:

```<code>*{
    margin: 0px;
    padding: 0px;
}
body {
    font-family:Verdana;
    font-size:10px;
}
#wrapper{
    width:1000px;overflow:hidden;
    margin:0 auto 10px auto;background-image: url(./grafics/bg.gif);background-repeat:repeat-y;
}
/*-------------------------------------------------------------------*/
/*                          font-size                                */
/*-------------------------------------------------------------------*/
h1 {
   font-size: 25px;
}
h2 {
   font-size: 19px;
}
h3{
    font-size:18px;
    color:#660033;
}
h4, h5, h6 {
   font-size: 16px;
}
p{
    font-size: 14px;
    margin-right:20px;
}
h2, h3, h4, h5, p{
    margin-bottom:10px;
}
h5{

}
/*-------------------------------------------------------------------*/
/*                          links                                    */
/*-------------------------------------------------------------------*/
a:link, a:visited, a:active, a:hover{
    text-decoration:none;
    color:#634142;
    font-size:12px;
    font-weight:bold;
}
a:active, a:hover{
    text-decoration:underline;
}
/*-------------------------------------------------------------------*/
/*                          header                                   */
/*-------------------------------------------------------------------*/
#header {
    width:968px;
    height:161px;
    margin:0 13px 0 13px;
    border:3px solid #000;
    background-color: #000;
}
#header2{
    width:974px;
    height:65px;
    padding:5px 0 0 0;
    margin:0 13px 0 13px;
    background:#fff;
    clear:both;
}
#logo {
    width:222px;
    margin: 0 0 0 0;
    padding: 0 5px 0 0;
    float: left;
    overflow: hidden;
}
#header-title {
    height: 160px;
    background: transparent url(banner_2.jpg) no-repeat 0 0;
    float:left;
}

#ueberschrift {
    padding:60px 0 0 20px;
    color:#fff;
}
#ueberschrift p{
    font-size:16px;
}
#content-header{
    width:990px;height:60px;
    padding:0 0 20px 10px;
}
#like{
    width:77px;
    margin:5px 30px 0 10px;
    float:left;
}
#kaktus-banner{
    width:468px;
    margin:5px 0 0 129px;
    float:left;
}
#wobinich{
    width:964px;height:16px;
    margin:0 13px 0 13px;
    font-size:12px;
    border-bottom:1px solid #000;
    background:#fff;
    float:left;padding:0 0 0 10px;

}
h2.title{
    text-align:center;
    height:40px;
    font-size:30px;
    background: transparent url(./grafics/bg-title1.gif) no-repeat 0px 35px;
}
h2.title2{

    height:40px;
    font-size:30px;
    background: transparent url(./grafics/bg-title3.gif) no-repeat 0px 35px;
}
h2.gb{
    height:30px;
    background: transparent url(./grafics/bg-title3.gif) no-repeat 0px 25px;
}
/*-------------------------------------------------------------------*/
/*                          content                                  */
/*-------------------------------------------------------------------*/

#content {
    width:974px;
    margin:0 13px 0 13px;
    background:#fff;
    float:left;
}
#content p{
    line-height:24px;
}
#links{
    width:185px;
    margin:0 0 0 0;
    float:left;
}
#mitte{
    width:609px; /*609px*/
    padding:10px 10px 0 10px;
    float:left;
}
#mitte_a-z{
    width:873px;
    padding:10px 0 0 20px;
}
#mitte1{
    width:767px;
    padding:10px 10px 0 10px;
    float:left;
}
#rechts{
    width:160px;
    margin:0 0px 10px 0;
    float:right;
}
#film{
    margin:10px 0 10px 182px;
}

#footer{
    width:974px;height:30px;

    font-size:12px;
    line-height: 27px;
    text-align:center;
    color:#000;
    border-top:1px solid #000;background:#fff;border-bottom:1px solid #000;background:#fff;
    float:left;
}
#footer a{
    font-weight:normal;
    color:#000;
}
/*-------------------------------------------------------------------*/
/*                          navigation                               */
/*-------------------------------------------------------------------*/
.navtitle{
    margin:0px;
    background:#7fb37f;
    text-align:center;
}
#navigationsleiste{
    margin:0 16px 20px 0;padding:0 0 10px 0;
    width:185px;background:#a5e8a5;
}
#navigationsleiste a{
    display: block;
    height: 20px;
    padding:8px 0 0 19px;

    color: #000;
    text-decoration: none;
}
#navigationsleiste a:hover{
    background: transparent url(./grafics/liste.gif) no-repeat 5px 12px;

}
#navigationsleiste a.aktiv{
    background: transparent url(./grafics/liste.gif) no-repeat 5px 12px;

}
.link{
    /*margin:0 16px -2000px 0;padding-bottom:2000px;*/
    width: 185px;background:#a5e8a5;
}
.link a{
    display: block;
    height: 20px;
    margin:2px;
    padding:10px 0 10px 9px;
    font-size:12px;
}
.link-re{
    /*margin:0 0px -2500px 0;padding:0 0 2500px 0;*/
    width: 160px;background:#a5e8a5;
}
.link-re a{
    display: block;
    height: 20px;
    margin:0px;
    padding:2px 0 0 20px;
    font-size:12px;
    font-weight:bold;

}
#zapp{
    width:964px;height:20px;
    margin:0 13px 0 13px;
    font-size:12px;
    background:#fff;
    border-bottom:1px solid #000;
    padding:10px 0 0 10px;
    float:left;

}
.up{
    margin:10px 0 10px 0px;
    text-align:right;

}
.up a{
    font-weight:bold;
}
.back{
    margin:0 60px 0 0;
    float:left
}
.zurueck{
    float:left;
}
.ist{
    float:left;
    color:#a5a5a5;
    margin-left:30px;
}
.vor{
    margin:0 0 0 30px;
    float:left;
}
/*-------------------------------------------------------------------*/
/*                          listenelemente                           */
/*-------------------------------------------------------------------*/
ul{
    list-style-type:none;
}
li{

}
#mitte ul{
    list-style-type:disc;
    margin-left:15px;
}
#mitte li a{

}
ol{
    font-size:14px;
    margin:0 0 0 20px;
    line-height:24px;
}
.cb{
    clear:both;
}
img{

}
#table{
}
p.hn {
  color: #870B0B;
}

p.se {
  color:#057C11;
}

p.nanl {
  color:#64057C;
}

p.bild {
    float:left;
    }
</code>```

答:
Remove height:20px form this style

```<code>.link a{
    display: block;
    height: 20px;
    margin:2px;
    padding:10px 0 10px 9px;
    font-size:12px;
}
</code>```

Body:
one page of my website is locking like that:
http://www.pflanzspass.bplaced.net/

Yesterdy I tried to integrate a slideshow:
http://www.pflanzspass.bplaced.net/indextest.php

The slideshow is working, but now there are some new layout problems:

now:

before:

I don't know why.

This is my new css-Code for the slideshow:

  * {box-sizing: border-box}
  /*body {
  font-family: Verdana, sans-serif;
  margin:0
  }*/
  .mySlides {display: none}
  img {vertical-align: middle;}
  .slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
  }
  /* Next & previous buttons */
  .prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
  }
  /* Position the "next button" to the right */
  .next {
  right: 0;
  border-radius: 3px 0 0 3px;
  }
  /* On hover, add a black background color with a little bit see-through */
  .prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
  }
  /* Caption text */
  .text {
  color: #ffffff;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
  }
  /* Number text (1/3 etc) */
  .numbertext {
  color: #ffffff;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
  }
  /* The dots/bullets/indicators */
  .dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #999999;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
  }
  .active, .dot:hover {
  background-color: #111111;
  }
  /* Fading animation */
  .fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
  }
  @-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
  }
  @keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
  }
  /* On smaller screens, decrease text size */
  @media only screen and (max-width: 300px) {
  .prev, .next,.text {font-size: 11px}
  }

This is the css-code, already online before added the slide-show css-code:

*{
    margin: 0px;
    padding: 0px;
}
body {
    font-family:Verdana;
    font-size:10px;
}
#wrapper{
    width:1000px;overflow:hidden;
    margin:0 auto 10px auto;background-image: url(./grafics/bg.gif);background-repeat:repeat-y;
}
/*-------------------------------------------------------------------*/
/*                          font-size                                */
/*-------------------------------------------------------------------*/
h1 {
   font-size: 25px;
}
h2 {
   font-size: 19px;
}
h3{
    font-size:18px;
    color:#660033;
}
h4, h5, h6 {
   font-size: 16px;
}
p{
    font-size: 14px;
    margin-right:20px;
}
h2, h3, h4, h5, p{
    margin-bottom:10px;
}
h5{

}
/*-------------------------------------------------------------------*/
/*                          links                                    */
/*-------------------------------------------------------------------*/
a:link, a:visited, a:active, a:hover{
    text-decoration:none;
    color:#634142;
    font-size:12px;
    font-weight:bold;
}
a:active, a:hover{
    text-decoration:underline;
}
/*-------------------------------------------------------------------*/
/*                          header                                   */
/*-------------------------------------------------------------------*/
#header {
    width:968px;
    height:161px;
    margin:0 13px 0 13px;
    border:3px solid #000;
    background-color: #000;
}
#header2{
    width:974px;
    height:65px;
    padding:5px 0 0 0;
    margin:0 13px 0 13px;
    background:#fff;
    clear:both;
}
#logo {
    width:222px;
    margin: 0 0 0 0;
    padding: 0 5px 0 0;
    float: left;
    overflow: hidden;
}
#header-title {
    height: 160px;
    background: transparent url(banner_2.jpg) no-repeat 0 0;
    float:left;
}

#ueberschrift {
    padding:60px 0 0 20px;
    color:#fff;
}
#ueberschrift p{
    font-size:16px;
}
#content-header{
    width:990px;height:60px;
    padding:0 0 20px 10px;
}
#like{
    width:77px;
    margin:5px 30px 0 10px;
    float:left;
}
#kaktus-banner{
    width:468px;
    margin:5px 0 0 129px;
    float:left;
}
#wobinich{
    width:964px;height:16px;
    margin:0 13px 0 13px;
    font-size:12px;
    border-bottom:1px solid #000;
    background:#fff;
    float:left;padding:0 0 0 10px;

}
h2.title{
    text-align:center;
    height:40px;
    font-size:30px;
    background: transparent url(./grafics/bg-title1.gif) no-repeat 0px 35px;
}
h2.title2{

    height:40px;
    font-size:30px;
    background: transparent url(./grafics/bg-title3.gif) no-repeat 0px 35px;
}
h2.gb{
    height:30px;
    background: transparent url(./grafics/bg-title3.gif) no-repeat 0px 25px;
}
/*-------------------------------------------------------------------*/
/*                          content                                  */
/*-------------------------------------------------------------------*/

#content {
    width:974px;
    margin:0 13px 0 13px;
    background:#fff;
    float:left;
}
#content p{
    line-height:24px;
}
#links{
    width:185px;
    margin:0 0 0 0;
    float:left;
}
#mitte{
    width:609px; /*609px*/
    padding:10px 10px 0 10px;
    float:left;
}
#mitte_a-z{
    width:873px;
    padding:10px 0 0 20px;
}
#mitte1{
    width:767px;
    padding:10px 10px 0 10px;
    float:left;
}
#rechts{
    width:160px;
    margin:0 0px 10px 0;
    float:right;
}
#film{
    margin:10px 0 10px 182px;
}

#footer{
    width:974px;height:30px;

    font-size:12px;
    line-height: 27px;
    text-align:center;
    color:#000;
    border-top:1px solid #000;background:#fff;border-bottom:1px solid #000;background:#fff;
    float:left;
}
#footer a{
    font-weight:normal;
    color:#000;
}
/*-------------------------------------------------------------------*/
/*                          navigation                               */
/*-------------------------------------------------------------------*/
.navtitle{
    margin:0px;
    background:#7fb37f;
    text-align:center;
}
#navigationsleiste{
    margin:0 16px 20px 0;padding:0 0 10px 0;
    width:185px;background:#a5e8a5;
}
#navigationsleiste a{
    display: block;
    height: 20px;
    padding:8px 0 0 19px;

    color: #000;
    text-decoration: none;
}
#navigationsleiste a:hover{
    background: transparent url(./grafics/liste.gif) no-repeat 5px 12px;

}
#navigationsleiste a.aktiv{
    background: transparent url(./grafics/liste.gif) no-repeat 5px 12px;

}
.link{
    /*margin:0 16px -2000px 0;padding-bottom:2000px;*/
    width: 185px;background:#a5e8a5;
}
.link a{
    display: block;
    height: 20px;
    margin:2px;
    padding:10px 0 10px 9px;
    font-size:12px;
}
.link-re{
    /*margin:0 0px -2500px 0;padding:0 0 2500px 0;*/
    width: 160px;background:#a5e8a5;
}
.link-re a{
    display: block;
    height: 20px;
    margin:0px;
    padding:2px 0 0 20px;
    font-size:12px;
    font-weight:bold;

}
#zapp{
    width:964px;height:20px;
    margin:0 13px 0 13px;
    font-size:12px;
    background:#fff;
    border-bottom:1px solid #000;
    padding:10px 0 0 10px;
    float:left;

}
.up{
    margin:10px 0 10px 0px;
    text-align:right;

}
.up a{
    font-weight:bold;
}
.back{
    margin:0 60px 0 0;
    float:left
}
.zurueck{
    float:left;
}
.ist{
    float:left;
    color:#a5a5a5;
    margin-left:30px;
}
.vor{
    margin:0 0 0 30px;
    float:left;
}
/*-------------------------------------------------------------------*/
/*                          listenelemente                           */
/*-------------------------------------------------------------------*/
ul{
    list-style-type:none;
}
li{

}
#mitte ul{
    list-style-type:disc;
    margin-left:15px;
}
#mitte li a{

}
ol{
    font-size:14px;
    margin:0 0 0 20px;
    line-height:24px;
}
.cb{
    clear:both;
}
img{

}
#table{
}
p.hn {
  color: #870B0B;
}

p.se {
  color:#057C11;
}

p.nanl {
  color:#64057C;
}

p.bild {
    float:left;
    }

Body:
Remove height:20px form this style

.link a{
    display: block;
    height: 20px;
    margin:2px;
    padding:10px 0 10px 9px;
    font-size:12px;
}


问:
Using User Profile automatically load information into form fields
In my pervious question I asked how I can automatically save the user submitting the form. I found the form_valid method to be the best in that case. However in my models I also have a user profile model like this

models.py

```<code>....
class Profile(models.Model):
  user = models.OneToOneField(User,on_delete=models.CASCADE)
  title = models.CharField(max_length=24)
  first_name = models.CharField(max_length=35)
  last_name = models.CharField(max_length=35)
  email = models.EmailField(max_length=64)
  phone_number = models.CharField(max_length=12)
  department = models.ForeignKey(Department,null=True,on_delete=models.SET_NULL)
  supervisor = models.ForeignKey('self',blank=True,null=True,on_delete=models.SET_NULL)
...
</code>```

As you can see I used the One to One method to make my UserProfile

As before in my models.py I have my reports model

```<code>...
class Report(models.Model):
  id = models.UUIDField(primary_key=True,default=uuid.uuid1,editable=False)
  department = models.ForeignKey(Company,null=True,on_delete=models.SET_NULL)
  user= models.ForeignKey(User,on_delete=models.PROTECT)
  submission_date= models.DateField(auto_now=True) #invisible to user
  submission_time = models.TimeField(auto_now=True) #invisible to ,user
  date = models.DateField(default=now,blank=False)
  time = models.TimeField(default=now,blank=False,help_text="hh:mm:ss")
  location = PlainLocationField()
  building = models.ForeignKey(bld,null=True,on_delete=models.SET_NULL)
  size = models.PositiveIntegerField()
  notes = models.TextField(blank=True)
   def __str__(self):
     return f'{self.date} {self.time} ({self.department})
...
</code>```

My question how I can make it so that the department field will load from the user profile? I would hope to eventually make it possible for users in the same department to be able to view and update each others Reports.

As before:

form.py

```<code>class ReportForm(forms.ModelForm):
    class Meta:
        model = Report
        fields = '__all__'
        location = PlainLocationField()
    def redirect():
        return redirect("Report")
</code>```

views.py

```<code>class ReportCreate(LoginRequiredMixin,CreateView):
    Template = "templates\reports\Report.html"
    model = Report
    fields = '__all__'
    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.save()
        return super(ReportCreate, self).form_valid(form)
    def get_success_url(self):
        return reverse('Report')
    def get_absolute_url(self):
        return reverse('Report', kwargs={'pk':self.pk})
</code>```

答:
Here are some steps to help you autofill some fields:

Get the user from self.request.user. How to access current user in Django class based view

Get the profile: get user profile in django

Pass the required fields as context variables: https://www.geeksforgeeks.org/how-to-pass-additional-context-into-a-class-based-view-django/

Pass it into javascript. How can I pass my context variables to a javascript file in Django?

Set the value like this: Set the value of an input field

DONE!

Body:
In my pervious question I asked how I can automatically save the user submitting the form. I found the form_valid method to be the best in that case. However in my models I also have a user profile model like this

models.py

....
class Profile(models.Model):
  user = models.OneToOneField(User,on_delete=models.CASCADE)
  title = models.CharField(max_length=24)
  first_name = models.CharField(max_length=35)
  last_name = models.CharField(max_length=35)
  email = models.EmailField(max_length=64)
  phone_number = models.CharField(max_length=12)
  department = models.ForeignKey(Department,null=True,on_delete=models.SET_NULL)
  supervisor = models.ForeignKey('self',blank=True,null=True,on_delete=models.SET_NULL)
...

As you can see I used the One to One method to make my UserProfile

As before in my models.py I have my reports model

...
class Report(models.Model):
  id = models.UUIDField(primary_key=True,default=uuid.uuid1,editable=False)
  department = models.ForeignKey(Company,null=True,on_delete=models.SET_NULL)
  user= models.ForeignKey(User,on_delete=models.PROTECT)
  submission_date= models.DateField(auto_now=True) #invisible to user
  submission_time = models.TimeField(auto_now=True) #invisible to ,user
  date = models.DateField(default=now,blank=False)
  time = models.TimeField(default=now,blank=False,help_text="hh:mm:ss")
  location = PlainLocationField()
  building = models.ForeignKey(bld,null=True,on_delete=models.SET_NULL)
  size = models.PositiveIntegerField()
  notes = models.TextField(blank=True)
   def __str__(self):
     return f'{self.date} {self.time} ({self.department})
...

My question how I can make it so that the department field will load from the user profile? I would hope to eventually make it possible for users in the same department to be able to view and update each others Reports.

As before:

form.py

class ReportForm(forms.ModelForm):
    class Meta:
        model = Report
        fields = '__all__'
        location = PlainLocationField()
    def redirect():
        return redirect("Report")

views.py

class ReportCreate(LoginRequiredMixin,CreateView):
    Template = "templates\reports\Report.html"
    model = Report
    fields = '__all__'
    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.save()
        return super(ReportCreate, self).form_valid(form)
    def get_success_url(self):
        return reverse('Report')
    def get_absolute_url(self):
        return reverse('Report', kwargs={'pk':self.pk})


问:
TSQL: Query items which their max version is have state Failed
I have an SQL database with below rules:

There are items with same name but different versions.

Status of item production is stored inside a column State.

The structure of  table log inside test database is like below:

id
Name
Ver
State

1
A
1
OK

2
B
1
Failed

3
C
1
OK

4
D
1
OK

5
A
2
OK

6
B
2
OK

7
C
2
Failed

8
D
2
OK

9
A
3
Failed

According to our production rules, the last version made from an item should have state OK (not Failed). So I want a query to grab list of unacceptable items with below constraints:

Name of items which their last version state is 'Failed'

In my sample data, the query should return A and C since Max version of A is 3 but its state is 'Failed' and max version of C is 2 but its state is Failed.

B and D are OK since their last version is 2 and the state of the version 2 for these items is OK.

How can I write query to bring list of items which their last version is failed (and not OK)?

答:
Ah, yes, super rusty. Yet, you can definitely do this with a subquery:

```<code>SELECT mytable.name, mytable.ver, mytable.state
from
(SELECT NAME, VER
FROM TABLE GROUP BY NAME
HAVING VER = max(VER)) subq
INNER JOIN table on subq.name = mytable.name and subq.ver = mytable.ver
WHERE mytable.STATE = 'failed'
</code>```

This is not a performant answer.

Body:
Ah, yes, super rusty. Yet, you can definitely do this with a subquery:

SELECT mytable.name, mytable.ver, mytable.state
from
(SELECT NAME, VER
FROM TABLE GROUP BY NAME
HAVING VER = max(VER)) subq
INNER JOIN table on subq.name = mytable.name and subq.ver = mytable.ver
WHERE mytable.STATE = 'failed'

This is not a performant answer.