问:
Invalid hook call. Hooks can only be called inside of the body of a function component React,JS
hello everyone I have this call within a hooks I need the lat and lng variables to be saved in the state as I am currently doing it shows me the following error, I hope someone can help me
Error: Invalid hook call. Hooks can only be called inside the body of a function component. This could happen for one of the following reasons:

```<code>useEffect(() => {
    const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=.....`;
    const http = new XMLHttpRequest();
    http.open("POST", url);
    http.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
       const data = JSON.parse(this.responseText);
       const {location: {lat, lng}} = data;
       const result = {lat, lng} ;
       const  [locations, setLocation] = useState({
            loaded: true,
            coordinates: {
                lat: result.lat,
                lng: result.lng,
            },
            aceptacion:1
        });
        console.log(setLocation);
       return result;
      }
    }
    http.send();
}, []);

return location;
</code>```

};

答:
Move useState initialization outside useEffect hook.</p>
```<code>const [locations, setLocation] = useState({
    loaded: true,
    coordinates: null,
    aceptacion: null,
});

useEffect(() => {
    const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=.....`;
    const http = new XMLHttpRequest();
    http.open("POST", url);
    http.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
       const data = JSON.parse(this.responseText);
       const {location: {lat, lng}} = data;
       const result = {lat, lng} ;
       setLocation({
            loaded: true,
            coordinates: {
                lat: result.lat,
                lng: result.lng,
            },
            aceptacion:1
        });
        console.log(setLocation);
        return result;
      }
    }
    http.send();
}, []);

return locations;
</code>```

Body:
hello everyone I have this call within a hooks I need the lat and lng variables to be saved in the state as I am currently doing it shows me the following error, I hope someone can help me
Error: Invalid hook call. Hooks can only be called inside the body of a function component. This could happen for one of the following reasons:

useEffect(() => {
    const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=.....`;
    const http = new XMLHttpRequest();
    http.open("POST", url);
    http.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
       const data = JSON.parse(this.responseText);
       const {location: {lat, lng}} = data;
       const result = {lat, lng} ;
       const  [locations, setLocation] = useState({
            loaded: true,
            coordinates: {
                lat: result.lat,
                lng: result.lng,
            },
            aceptacion:1
        });
        console.log(setLocation);
       return result;
      }
    }
    http.send();
}, []);

return location;

};

Body:
Move useState initialization outside useEffect hook.

const [locations, setLocation] = useState({
    loaded: true,
    coordinates: null,
    aceptacion: null,
});

useEffect(() => {
    const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=.....`;
    const http = new XMLHttpRequest();
    http.open("POST", url);
    http.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
       const data = JSON.parse(this.responseText);
       const {location: {lat, lng}} = data;
       const result = {lat, lng} ;
       setLocation({
            loaded: true,
            coordinates: {
                lat: result.lat,
                lng: result.lng,
            },
            aceptacion:1
        });
        console.log(setLocation);
        return result;
      }
    }
    http.send();
}, []);

return locations;


来源: stackexchange

问:
Printing a multidimensional array in C
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

```<code>#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}
</code>```

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6

答:
Array designators used in expressions with rare exceptions are implicitly converted to pointers to their first elements.

The type of the array elements of this array

```<code>int arr[2][3];
</code>```

is int [3]. So a pointer to the first element of the array has the type int ( * )[3].

This assignment

```<code>p = arr;
</code>```

where p has the type int * is incorrect because the operands of the assignment have incompatible pointer types.

At least you need to cast the right expression to the type int * like

```<code>p = ( int * )arr;
</code>```

The same casting you need to use in the condition in the for loop. That is instead of

```<code>p <= arr+6
</code>```

you have to write

```<code>p < ( int * )arr+6
</code>```

Below there is a demonstration program that shows how to output a two-dimensional array as a two-dimensional array using pointers.

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

int main( void )
{
    int arr[2][3] = {{1,2,3},{4,5,6}};

    for ( int ( *p )[3] = arr; p != arr + 2; p++ )
    {
        for ( int *q = *p; q != *p + 3; ++q )
        {
            printf( "%d ", *q );
        }
        putchar( '\n' );
    }

    return 0;
}
</code>```

If you want to output the two-dimensional array as a one-dimensional array then you can write

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

int main( void )
{
    int arr[2][3] = {{1,2,3},{4,5,6}};

    for ( int *p = ( int * )arr; p != ( int * )arr + 6; p++ )
    {
        printf( "%d ", *p );
    }
    putchar( '\n' );

    return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Printing a multidimensional array in C

Body:
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6

Body:
Array designators used in expressions with rare exceptions are implicitly converted to pointers to their first elements.

The type of the array elements of this array

int arr[2][3];

is int [3]. So a pointer to the first element of the array has the type int ( * )[3].

This assignment

p = arr;

where p has the type int * is incorrect because the operands of the assignment have incompatible pointer types.

At least you need to cast the right expression to the type int * like

p = ( int * )arr;

The same casting you need to use in the condition in the for loop. That is instead of

p <= arr+6

you have to write

p < ( int * )arr+6

Below there is a demonstration program that shows how to output a two-dimensional array as a two-dimensional array using pointers.

#include <stdio.h>

int main( void )
{
    int arr[2][3] = {{1,2,3},{4,5,6}};

    for ( int ( *p )[3] = arr; p != arr + 2; p++ )
    {
        for ( int *q = *p; q != *p + 3; ++q )
        {
            printf( "%d ", *q );
        }
        putchar( '\n' );
    }

    return 0;
}

If you want to output the two-dimensional array as a one-dimensional array then you can write

#include <stdio.h>

int main( void )
{
    int arr[2][3] = {{1,2,3},{4,5,6}};

    for ( int *p = ( int * )arr; p != ( int * )arr + 6; p++ )
    {
        printf( "%d ", *p );
    }
    putchar( '\n' );

    return 0;
}


问:
VSCode/TextMate syntax highlighting grammar -- matching code until end of line
I am writing a TextMate grammar to implement syntax highlighting in VSCode for a custom flavor of Markdown. I would like everything on the same line after @@$  to be highlighted as Javascript.

This is what I came up with:

"majsdown_execute_statement": {
    "begin": "(.*?)(@@\\$)",
    "name": "test",
    "end": "(\\r\\n|\\r|\\n)",
    "beginCaptures": {
        "2": {
            "name": "keyword.control.majsdown"
        }
    },
    "patterns": [
        {
            "include": "source.js"
        }
    ]
},
```
<p>That <em>almost</em> works:</p>
<p><img src="https://i.stack.imgur.com/41lsU.png" alt="what happens" /></p>
<p>But I would like the <code>@@$</code> part to always be highlighted as a keyword. Here's a mockup (edited image) of my desired result:</p>
<p><img src="https://i.stack.imgur.com/NWrZM.png" alt="what I would like" /></p>
<p>I've tried a lot of different combinations of <code>"begin"</code> and <code>"end"</code>, and I've also tried many nested patterns like the following one:</p>
<pre class="lang-json prettyprint-override"><code>"patterns": [
    {
        "begin": "\\s",
        "while": "^(\\r\\n|\\r|\\n)",
        "patterns": [
            {
                "include": "source.js"
            }
        ]
    }
]
</code>```

Unfortunately, nothing provides the result I desire. How can I achieve my desired result?

答:
To handle multiline constructs, I think you'll have to provide modified embedded language(JavaScript) definition as well. Easiest way to do it would be to make @@$ a comment in JavaScript, so it'll not mess up existing constructs.

I have no idea about VScode syntax highlighting. I'll try to demonstrate the idea using HighlightJs. It has very similar way of defining a language.

Demo: View in full page mode.

hljs.debugMode();

    // default code for the demo
    src.innerText = `
My custom markdown highlighted with custom rules.
Here is how javascript code looks:
@@$ function test()
@@$ {
@@$   // TODO: stuff
@@$   let rand = Math
@@$                  .random()
@@$                  .toFixed(2);
@@$ }
@@$ var string = "hello";
@@$ const string2 = \`some long
@@$ string\`;

Leave one empty line to get out of the code block.
Here is some more code:
@@$ var rand = Math.random();
@@$ console.log(rand);

We are out of the second code block now.
`;

    // define our markup language, say 'mdown'
    let langDef = {
      name: 'Mdown',
      aliases: ['mdown'],
      case_insensitive: true,
      contains: [
        {
          className: 'mscript',
          begin: /@@/,
          end: /\$/,
          keywords: { name: 'mscript' },
          contains: [],
          starts: {
            end: /^\s*$/, // end on empty line
            returnEnd: true,
            subLanguage: ['js'],  //embedded language
          },
        },
      ],
    };
    hljs.registerLanguage('mscript', () => langDef);

    // patch javascript multiline structures
    let js = hljs.getLanguage('javascript');
    for (let c of js.contains) {
      if (c.begin === "`") {  // handle templet literals
        c.contains.unshift({
          begin: /^@@/,
          "relevance": 0,
          end: /\$/,
          contains: [],
          scope: 'mscripttag'
        })
      }
    }
    // console.log(js);

    // make '@@$' a comment :)
    // So it'll not mess existing styling
    js.contains.push(hljs.COMMENT(/@@/, /\$/, { scope: 'mscripttag', relevance: 10 }));

    // for demo update highlighted code on user input
    let handleChange = (event) => {
      let html = hljs.highlight(src.innerText, { language: 'mscript', ignoreIllegals: true }).value;
      code.innerHTML = html;
    };
    // javascript patching done

    document.addEventListener('DOMContentLoaded', handleChange);
    src.addEventListener('input', handleChange);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-size: .8rem; }

.input {
  width: 46%;
  background-color: #eee;
  display: inline-block;
  overflow: auto;
}

.output {
  width: 50%;
  display: block;
  float: right;
  background-color: #ccc;
}

/* add extra theme for our tag @@$ */
.hljs { color: #bbb !important; }

.hljs-mscript,
.hljs-mscripttag { color: red; }</code>```

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/base16/snazzy.min.css" />

Edit below markdown code.

```

<pre class="output"><code id="code" class="javascript hljs">abcd</code>``````

In case the library not available, here is how the output looks like:

In above code I have defined @@$ <jscontent> \n as a tag in our markdown language definition. And the content will be processed according to the embedded language JavaScript.
Next I've modified the default JS language definition and added @@$ as a comment so it'll be harmless to exiting syntax.
 Now we just need to handle template literals which are multiline. In the literal definition I've added @@$ as a part of the literal, but with different scope/name/styleOption msscripttag.

I hope you'll be able to define similar syntax in TextMate for VSCode.

Body:
I am writing a TextMate grammar to implement syntax highlighting in VSCode for a custom flavor of Markdown. I would like everything on the same line after @@$  to be highlighted as Javascript.

This is what I came up with:

"majsdown_execute_statement": {
    "begin": "(.*?)(@@\\$)",
    "name": "test",
    "end": "(\\r\\n|\\r|\\n)",
    "beginCaptures": {
        "2": {
            "name": "keyword.control.majsdown"
        }
    },
    "patterns": [
        {
            "include": "source.js"
        }
    ]
},

That almost works:

But I would like the @@$ part to always be highlighted as a keyword. Here's a mockup (edited image) of my desired result:

I've tried a lot of different combinations of "begin" and "end", and I've also tried many nested patterns like the following one:

"patterns": [
    {
        "begin": "\\s",
        "while": "^(\\r\\n|\\r|\\n)",
        "patterns": [
            {
                "include": "source.js"
            }
        ]
    }
]

Unfortunately, nothing provides the result I desire. How can I achieve my desired result?

Body:
To handle multiline constructs, I think you'll have to provide modified embedded language(JavaScript) definition as well. Easiest way to do it would be to make @@$ a comment in JavaScript, so it'll not mess up existing constructs.

I have no idea about VScode syntax highlighting. I'll try to demonstrate the idea using HighlightJs. It has very similar way of defining a language.

Demo: View in full page mode.

hljs.debugMode();

    // default code for the demo
    src.innerText = `
My custom markdown highlighted with custom rules.
Here is how javascript code looks:
@@$ function test()
@@$ {
@@$   // TODO: stuff
@@$   let rand = Math
@@$                  .random()
@@$                  .toFixed(2);
@@$ }
@@$ var string = "hello";
@@$ const string2 = \`some long
@@$ string\`;

Leave one empty line to get out of the code block.
Here is some more code:
@@$ var rand = Math.random();
@@$ console.log(rand);

We are out of the second code block now.
`;

    // define our markup language, say 'mdown'
    let langDef = {
      name: 'Mdown',
      aliases: ['mdown'],
      case_insensitive: true,
      contains: [
        {
          className: 'mscript',
          begin: /@@/,
          end: /\$/,
          keywords: { name: 'mscript' },
          contains: [],
          starts: {
            end: /^\s*$/, // end on empty line
            returnEnd: true,
            subLanguage: ['js'],  //embedded language
          },
        },
      ],
    };
    hljs.registerLanguage('mscript', () => langDef);

    // patch javascript multiline structures
    let js = hljs.getLanguage('javascript');
    for (let c of js.contains) {
      if (c.begin === "`") {  // handle templet literals
        c.contains.unshift({
          begin: /^@@/,
          "relevance": 0,
          end: /\$/,
          contains: [],
          scope: 'mscripttag'
        })
      }
    }
    // console.log(js);

    // make '@@$' a comment :)
    // So it'll not mess existing styling
    js.contains.push(hljs.COMMENT(/@@/, /\$/, { scope: 'mscripttag', relevance: 10 }));

    // for demo update highlighted code on user input
    let handleChange = (event) => {
      let html = hljs.highlight(src.innerText, { language: 'mscript', ignoreIllegals: true }).value;
      code.innerHTML = html;
    };
    // javascript patching done

    document.addEventListener('DOMContentLoaded', handleChange);
    src.addEventListener('input', handleChange);

body { font-size: .8rem; }

.input {
  width: 46%;
  background-color: #eee;
  display: inline-block;
  overflow: auto;
}

.output {
  width: 50%;
  display: block;
  float: right;
  background-color: #ccc;
}

/* add extra theme for our tag @@$ */
.hljs { color: #bbb !important; }

.hljs-mscript,
.hljs-mscripttag { color: red; }

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/base16/snazzy.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/highlight.min.js"></script>

<div>Edit below markdown code.</div>
<pre class="input"><div id="src" contenteditable></div></pre>

<pre class="output"><code id="code" class="javascript hljs">abcd</code></pre>

In case the library not available, here is how the output looks like:

In above code I have defined @@$ <jscontent> \n as a tag in our markdown language definition. And the content will be processed according to the embedded language JavaScript.
Next I've modified the default JS language definition and added @@$ as a comment so it'll be harmless to exiting syntax.
 Now we just need to handle template literals which are multiline. In the literal definition I've added @@$ as a part of the literal, but with different scope/name/styleOption msscripttag.

I hope you'll be able to define similar syntax in TextMate for VSCode.


问:
Most efficient way to search for object in an array by a specific property's value
What would be the fastest, most efficient way to implement a search method that will return an object with a qualifying id?

Sample object array:

```<code>$array = [
    (object) ['id' => 'one', 'color' => 'white'],
    (object) ['id' => 'two', 'color' => 'red'],
    (object) ['id' => 'three', 'color' => 'blue']
];
</code>```

What do I write inside of:

```<code>function findObjectById($id){

}
</code>```

The desired result would return the object at $array[0] if I called:

```<code>$obj = findObjectById('one')
</code>```

Otherwise, it would return false if I passed 'four' as the parameter.

答:
You can iterate that objects:

```<code>function findObjectById($id){
    $array = array( /* your array of objects */ );

    foreach ( $array as $element ) {
        if ( $id == $element->id ) {
            return $element;
        }
    }

    return false;
}
</code>```

Edit:

Faster way is to have an array with keys equals to objects' ids (if unique);

Then you can build your function as follow:

```<code>function findObjectById($id){
    $array = array( /* your array of objects with ids as keys */ );

    if ( isset( $array[$id] ) ) {
        return $array[$id];
    }

    return false;
}
</code>```

Body:
What would be the fastest, most efficient way to implement a search method that will return an object with a qualifying id?

Sample object array:

$array = [
    (object) ['id' => 'one', 'color' => 'white'],
    (object) ['id' => 'two', 'color' => 'red'],
    (object) ['id' => 'three', 'color' => 'blue']
];

What do I write inside of:

function findObjectById($id){

}

The desired result would return the object at $array[0] if I called:

$obj = findObjectById('one')

Otherwise, it would return false if I passed 'four' as the parameter.

Body:
You can iterate that objects:

function findObjectById($id){
    $array = array( /* your array of objects */ );

    foreach ( $array as $element ) {
        if ( $id == $element->id ) {
            return $element;
        }
    }

    return false;
}

Edit:

Faster way is to have an array with keys equals to objects' ids (if unique);

Then you can build your function as follow:

function findObjectById($id){
    $array = array( /* your array of objects with ids as keys */ );

    if ( isset( $array[$id] ) ) {
        return $array[$id];
    }

    return false;
}

ContentLicense: CC BY-SA 3.0


问:
While converting ViewBag.JsonData from View in JavaScript, getting The length of the string exceeds the value set on the maxJsonLength property
I'm working on a project where I've to pass a huge list of data (500 000 records or more) through ViewBag. From my controller, I'm sending data shown as below.

```<code>public ActionResult Index()
{
  var list = new List<DropdownList>();

  for (int i = 0; i < 500000; i++)
  {
     list.Add(new DropdownList() { id = i, text = "Test Data-" + i });
  }
  ViewBag.JsonData = JsonConvert.SerializeObject(list);
  return View();
}
</code>```

And from my view, I'm using the following code to parse that data in JavaScript. While trying this code getting the maxJsonLength exceeds the error.

```<code><script>
$(document).ready(function(){
   @Html.Raw(Json.Encode(@ViewBag.JsonData));
});
</script>
</code>```

I also tried this & It's working with 500k records while data does not contain special characters. If data contain some special character then it's not working.

```<code><script>
$(document).ready(function(){
   JSON.parse('@ViewBag.JsonData');
});
</script>
</code>```

Note: I'm not getting error in .cs (c# code) file cause this solution already implemented in my project.

答:
You are getting the error in "C# code". This is not a JavaScript issue.

If editing web.config doesn't help, you can try using an instance of a JavascriptSerializer and setting the MaxJsonLength property manually:

```<code>@{
   var serializer = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

   var jsonData = serializer.Serialize(@ViewBag.JsonData);
}
</code>```

See more here and here.

Body:
I'm working on a project where I've to pass a huge list of data (500 000 records or more) through ViewBag. From my controller, I'm sending data shown as below.

public ActionResult Index()
{
  var list = new List<DropdownList>();

  for (int i = 0; i < 500000; i++)
  {
     list.Add(new DropdownList() { id = i, text = "Test Data-" + i });
  }
  ViewBag.JsonData = JsonConvert.SerializeObject(list);
  return View();
}

And from my view, I'm using the following code to parse that data in JavaScript. While trying this code getting the maxJsonLength exceeds the error.

I also tried this & It's working with 500k records while data does not contain special characters. If data contain some special character then it's not working.

Note: I'm not getting error in .cs (c# code) file cause this solution already implemented in my project.

Body:
You are getting the error in "C# code". This is not a JavaScript issue.

If editing web.config doesn't help, you can try using an instance of a JavascriptSerializer and setting the MaxJsonLength property manually:

@{
   var serializer = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

   var jsonData = serializer.Serialize(@ViewBag.JsonData);
}

See more here and here.


问:
Powershell script for Test-path is not working
I am passing a list of folders comma separated in the first parameter. The script works fine on windows 2012 server but does not working on windows 2008. This script on 2008 works if a single folder is passed but with multiple folders it does not enters the if condition with testpath

Param1:
C:\inetpub\logs,C:\temp\Logs\Management,E:\IIS-Logs,E:\VerifyLogs\FraudChecker

Param2: test

```<code>param([String] $LogClearDownPaths,[String] $ServerType)

    $IISLogPath = $LogClearDownPaths.Split(",")

    foreach($path in $IISLogPath)
    {
          if (Test-Path -Path $path)
          {
            Write-Host "testing is done here"
          }
    }
</code>```

答:
If you're using Powershell 3.0 on the 2008 server I believe you need to use the following syntax:

$IISLogPath = $LogClearDownPaths -Split ","

I'm not 100% sure because I can't find the relevant documentation but I think using $var.Split() is unique to Powershell 5.0 and up.

Body:
I am passing a list of folders comma separated in the first parameter. The script works fine on windows 2012 server but does not working on windows 2008. This script on 2008 works if a single folder is passed but with multiple folders it does not enters the if condition with testpath

Param1:
C:\inetpub\logs,C:\temp\Logs\Management,E:\IIS-Logs,E:\VerifyLogs\FraudChecker

Param2: test

param([String] $LogClearDownPaths,[String] $ServerType)

    $IISLogPath = $LogClearDownPaths.Split(",")

    foreach($path in $IISLogPath)
    {
          if (Test-Path -Path $path)
          {
            Write-Host "testing is done here"
          }
    }


问:
Flutter Web RawKeyboardListener 'escape' not working in Fullscreen
I want to use the 'escape' key in Flutter web to change the widget. The issue that I have is, when in fullscreen my RawKeyboardListener doesn't detect the escape key pressed, unlike when not in fullscreen. I was wondering how to rectify this:

Here is my fullscreen function:

```<code>  void goFullScreen() {
    document.documentElement!.requestFullscreen();

  }
</code>```

Here is my RawKeyboardListener:

```<code>RawKeyboardListener(
      autofocus: true,
      focusNode: FocusNode(),
      onKey: (event){
        if (event.isKeyPressed(LogicalKeyboardKey.exit)) {
          print('escape pressed');
        }
      },
</code>```

答:
Had a similar problem with this as well, what helped is listening to the document onFullscreenchange events:

```<code> document.documentElement?.onFullscreenChange.listen((event) {

      if (document.fullscreenElement==null) {
        print("do something");
      }
    });
</code>```

It's in the documentation for the fullscreenElement on the mozilla website. When the full screen is existed the fullscreenElement variable is set to null.

Body:
I want to use the 'escape' key in Flutter web to change the widget. The issue that I have is, when in fullscreen my RawKeyboardListener doesn't detect the escape key pressed, unlike when not in fullscreen. I was wondering how to rectify this:

Here is my fullscreen function:

  void goFullScreen() {
    document.documentElement!.requestFullscreen();

  }

Here is my RawKeyboardListener:

RawKeyboardListener(
      autofocus: true,
      focusNode: FocusNode(),
      onKey: (event){
        if (event.isKeyPressed(LogicalKeyboardKey.exit)) {
          print('escape pressed');
        }
      },

Body:
Had a similar problem with this as well, what helped is listening to the document onFullscreenchange events:

 document.documentElement?.onFullscreenChange.listen((event) {

      if (document.fullscreenElement==null) {
        print("do something");
      }
    });

It's in the documentation for the fullscreenElement on the mozilla website. When the full screen is existed the fullscreenElement variable is set to null.


问:
Flutter Stack is not Getting Full Height
I want to overlay container to 1st one container in Stack. But when doing, it works but when i give to height first one it just take this height and second container just stucks and didn't take full height.

I want this but "THIS IS MY TEXT" container should take full height but it won't?

But when i use fit : StackFit.expand. it does work what i want but first one got behind it.

here's my code

```<code>   double topHeightPadding = MediaQuery.of(context).padding.top;
    double heightForStack = (MediaQuery.of(context).size.height - 90);
    return Scaffold(
      body: Stack(
        fit : StackFit.expand,
        children: <Widget>[
          Container(
            height: topHeightPadding + 120,
            decoration: const BoxDecoration(
              color: Color(0xFF141D38),
            ),
            child: const Center(
                child: Text(
              "SOMETEXT.COM",
              style: TextStyle(color: Colors.white),
              textScaleFactor: 1.4,
            )),
          ),
          Positioned(
              top: topHeightPadding + 90,
              left: 0.1,
              right: 0.1,
              bottom: 0,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: heightForStack,
                decoration: const BoxDecoration(
                  // color: Colors.red,
                  color: Color(0xFFFFFFFF),
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(35),
                      topRight: Radius.circular(35)),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0xE6808080),
                      spreadRadius: 5,
                      blurRadius: 5,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: const Center(
                  child: Text('THIS IS MY TEXT')
                ),
              ))
        ],
      ),
    );
</code>```

Any help would be Appreciated.

答:
Answering Own Question : https://stackoverflow.com/help/self-answer

I just got how to do it by Adding one more container with height double.infinity.

Code:

```<code>  double topHeightPadding = MediaQuery.of(context).padding.top;
    double heightForStack = (MediaQuery.of(context).size.height - 90);
    return Scaffold(
      body: Stack(
        // fit : StackFit.expand,
        children: <Widget>[
          Container(height: double.infinity,),
          Container(
            height: topHeightPadding + 120,
            decoration: const BoxDecoration(
              color: Color(0xFF141D38),
            ),
            child: const Center(
                child: Text(
              "SOMETEXT.COM",
              style: TextStyle(color: Colors.white),
              textScaleFactor: 1.4,
            )),
          ),
          Positioned(
              top: topHeightPadding + 90,
              left: 0.1,
              right: 0.1,
              bottom: 0,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: heightForStack,
                decoration: const BoxDecoration(
                  // color: Colors.red,
                  color: Color(0xFFFFFFFF),
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(35),
                      topRight: Radius.circular(35)),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0xE6808080),
                      spreadRadius: 5,
                      blurRadius: 5,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: const Center(
                  child: Text('THIS IS MY TEXT')
                ),
              ))
        ],
      ),
    );
</code>```

Body:
I want to overlay container to 1st one container in Stack. But when doing, it works but when i give to height first one it just take this height and second container just stucks and didn't take full height.

I want this but "THIS IS MY TEXT" container should take full height but it won't?

But when i use fit : StackFit.expand. it does work what i want but first one got behind it.

here's my code

   double topHeightPadding = MediaQuery.of(context).padding.top;
    double heightForStack = (MediaQuery.of(context).size.height - 90);
    return Scaffold(
      body: Stack(
        fit : StackFit.expand,
        children: <Widget>[
          Container(
            height: topHeightPadding + 120,
            decoration: const BoxDecoration(
              color: Color(0xFF141D38),
            ),
            child: const Center(
                child: Text(
              "SOMETEXT.COM",
              style: TextStyle(color: Colors.white),
              textScaleFactor: 1.4,
            )),
          ),
          Positioned(
              top: topHeightPadding + 90,
              left: 0.1,
              right: 0.1,
              bottom: 0,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: heightForStack,
                decoration: const BoxDecoration(
                  // color: Colors.red,
                  color: Color(0xFFFFFFFF),
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(35),
                      topRight: Radius.circular(35)),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0xE6808080),
                      spreadRadius: 5,
                      blurRadius: 5,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: const Center(
                  child: Text('THIS IS MY TEXT')
                ),
              ))
        ],
      ),
    );

Any help would be Appreciated.

Body:
Answering Own Question : https://stackoverflow.com/help/self-answer

I just got how to do it by Adding one more container with height double.infinity.

Code:

  double topHeightPadding = MediaQuery.of(context).padding.top;
    double heightForStack = (MediaQuery.of(context).size.height - 90);
    return Scaffold(
      body: Stack(
        // fit : StackFit.expand,
        children: <Widget>[
          Container(height: double.infinity,),
          Container(
            height: topHeightPadding + 120,
            decoration: const BoxDecoration(
              color: Color(0xFF141D38),
            ),
            child: const Center(
                child: Text(
              "SOMETEXT.COM",
              style: TextStyle(color: Colors.white),
              textScaleFactor: 1.4,
            )),
          ),
          Positioned(
              top: topHeightPadding + 90,
              left: 0.1,
              right: 0.1,
              bottom: 0,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: heightForStack,
                decoration: const BoxDecoration(
                  // color: Colors.red,
                  color: Color(0xFFFFFFFF),
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(35),
                      topRight: Radius.circular(35)),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0xE6808080),
                      spreadRadius: 5,
                      blurRadius: 5,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: const Center(
                  child: Text('THIS IS MY TEXT')
                ),
              ))
        ],
      ),
    );


问:
Java Generics, why is it illegal to use inheritance in generics?
I have this structure:

```<code>///Creep.java///
public interface Creep extends Movable<Position2D> {
  ...
}

///Movable.java///
public interface Movable<T extends Position2D> {
        ...
    void setMovementStrategy(MovementStrategy<Movable<T>> movementStrategy);
    MovementStrategy<Movable<T>> getMovementStrategy();
}

///MovementStrategy.java///
public interface MovementStrategy<T extends Movable<? extends Position2D>> {
  void executeMovement(T movable);
}

///CreepImpl.java///
public class CreepImpl implements Creep {
...

 @Override
 public void setMovementStrategy(MovementStrategy<Creep> movementStrategy) {
    // TODO Auto-generated method stub

 }

 @Override
 public MovementStrategy<Creep> getMovementStrategy() {
    return null;
 }

}
</code>```

My problem is that generics doesn't like MovementStrategy<Creep> but it does accept MovementStrategy<Movable<Position2D>> Which i think is strange as Creep extends Movable<Position2D>. This in the context of the methods public MovementStrategy<Creep> getMovementStrategy() and public MovementStrategy<Creep> getMovementStrategy()

Isn't this possible? or maybe im doing something wrong?

Any help is appreciated!

EDIT

Forgot to include MovementStrategy source.. doh!

答:
Your problem is that Creep implements the interface Movable<Position2D>,  and Movable<Position2D> expect the methods setMovementStrategy(MovementStrategy<Movable<Position2D>> movementStrategy) and MovementStrategy<Movable<T>> getMovementStrategy().

Look at this simple non-generic example:

```<code>public interface iTest() {
  doSomething(Object o);
}

public class Test implements iTest {
  @Overide
  doSomething(Test t) {
    //error
  }
}
</code>```

As you can see, doSomething(Test t) only implements a small part of the iTest interface. If somebody writes the folling code, there is no method in Test to execute it:

```<code>public class TestImpl {
  public static void main(String[] args) {
    iTest t = new Test();
    t.doSomething("Hi"); // valid, because iTest.doSomething() expects a Object, and String is a Object.
    Test t2 = new Test();
    t2.doSomething("Hi"); // invalid, Test does not have a doSomething(String).
  }
}
</code>```

Body:
I have this structure:

///Creep.java///
public interface Creep extends Movable<Position2D> {
  ...
}

///Movable.java///
public interface Movable<T extends Position2D> {
        ...
    void setMovementStrategy(MovementStrategy<Movable<T>> movementStrategy);
    MovementStrategy<Movable<T>> getMovementStrategy();
}

///MovementStrategy.java///
public interface MovementStrategy<T extends Movable<? extends Position2D>> {
  void executeMovement(T movable);
}

///CreepImpl.java///
public class CreepImpl implements Creep {
...

 @Override
 public void setMovementStrategy(MovementStrategy<Creep> movementStrategy) {
    // TODO Auto-generated method stub

 }

 @Override
 public MovementStrategy<Creep> getMovementStrategy() {
    return null;
 }

}

My problem is that generics doesn't like MovementStrategy<Creep> but it does accept MovementStrategy<Movable<Position2D>> Which i think is strange as Creep extends Movable<Position2D>. This in the context of the methods public MovementStrategy<Creep> getMovementStrategy() and public MovementStrategy<Creep> getMovementStrategy()

Isn't this possible? or maybe im doing something wrong?

Any help is appreciated!

EDIT

Forgot to include MovementStrategy source.. doh!

Body:
Your problem is that Creep implements the interface Movable<Position2D>,  and Movable<Position2D> expect the methods setMovementStrategy(MovementStrategy<Movable<Position2D>> movementStrategy) and MovementStrategy<Movable<T>> getMovementStrategy().

Look at this simple non-generic example:

public interface iTest() {
  doSomething(Object o);
}

public class Test implements iTest {
  @Overide
  doSomething(Test t) {
    //error
  }
}

As you can see, doSomething(Test t) only implements a small part of the iTest interface. If somebody writes the folling code, there is no method in Test to execute it:

public class TestImpl {
  public static void main(String[] args) {
    iTest t = new Test();
    t.doSomething("Hi"); // valid, because iTest.doSomething() expects a Object, and String is a Object.
    Test t2 = new Test();
    t2.doSomething("Hi"); // invalid, Test does not have a doSomething(String).
  }
}


问:
ChartJS: datalabels: show percentage value in Pie piece
I have a piechart with four labels:

```<code>var data = [{
    data: [50, 55, 60, 33],
    labels: ["India", "China", "US", "Canada"],
    backgroundColor: [
        "#4b77a9",
        "#5f255f",
        "#d21243",
        "#B27200"
    ],
    borderColor: "#fff"
}];
</code>```

Using chartjs-plugin-datalabels plugin I wanted to show percentage value in each Pie piece with below code:

```<code>formatter: (value, ctx) => {

        let datasets = ctx.chart.data.datasets;

        if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
            let sum = 0;
            datasets.map(dataset => {
                sum += dataset.data[ctx.dataIndex];
            });
            let percentage = Math.round((value / sum) * 100) + '%';
            return percentage;
        } else {
            return percentage;
        }
    },
    color: '#fff',
}
</code>```

I am getting 100% value for all the pie pieces, instead of respective percentages.
Here is the JSFiddle (https://jsfiddle.net/kingBethal/a1Lvn4eb/7/)

答:
I am using ChartJS v3.7.0 and chartjs-plugin-datalabels v2.0.0 and this answer:

https://stackoverflow.com/a/59403435/6830478

does not really work for me, while I just wanted to keep the percentages up to date, also when hiding elements. It seems that ctx.dataset._meta is not available anymore. I came up with some ugly monkey patch:

formatter: function(value, context) {
    var hiddens = context.chart._hiddenIndices;
    var total = 0;
    var datapoints = context.dataset.data;
    datapoints.forEach((val, i) => {
        if (hiddens[i] != undefined) {
            if (!hiddens[i]) {
                total += val;
            }
        } else {
            total += val;
        }
    });
    var percentage = (value / total * 100).toFixed(2) + '%';
    var out = context.chart.data.labels[context.dataIndex] + '\n' + percentage;
    return out;
}
```

Hopw this might help anybody. Cheers.

Body:
I have a piechart with four labels:

var data = [{
    data: [50, 55, 60, 33],
    labels: ["India", "China", "US", "Canada"],
    backgroundColor: [
        "#4b77a9",
        "#5f255f",
        "#d21243",
        "#B27200"
    ],
    borderColor: "#fff"
}];

Using chartjs-plugin-datalabels plugin I wanted to show percentage value in each Pie piece with below code:

formatter: (value, ctx) => {

        let datasets = ctx.chart.data.datasets;

        if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
            let sum = 0;
            datasets.map(dataset => {
                sum += dataset.data[ctx.dataIndex];
            });
            let percentage = Math.round((value / sum) * 100) + '%';
            return percentage;
        } else {
            return percentage;
        }
    },
    color: '#fff',
}

I am getting 100% value for all the pie pieces, instead of respective percentages.
Here is the JSFiddle (https://jsfiddle.net/kingBethal/a1Lvn4eb/7/)

Body:
I am using ChartJS v3.7.0 and chartjs-plugin-datalabels v2.0.0 and this answer:

https://stackoverflow.com/a/59403435/6830478

does not really work for me, while I just wanted to keep the percentages up to date, also when hiding elements. It seems that ctx.dataset._meta is not available anymore. I came up with some ugly monkey patch:

formatter: function(value, context) {
    var hiddens = context.chart._hiddenIndices;
    var total = 0;
    var datapoints = context.dataset.data;
    datapoints.forEach((val, i) => {
        if (hiddens[i] != undefined) {
            if (!hiddens[i]) {
                total += val;
            }
        } else {
            total += val;
        }
    });
    var percentage = (value / total * 100).toFixed(2) + '%';
    var out = context.chart.data.labels[context.dataIndex] + '\n' + percentage;
    return out;
}

Hopw this might help anybody. Cheers.


问:
multiple arguments in sqflite flutter
I want to search database based on the keyword. if it title or content contains the keyword then return the data. but it send backs nothing.

```<code>
  static Future<List<Note>> searchDocuments(String? keyword) async {
    final database = await DatabaseHelper.database();

    List<Map<String, dynamic>> allDocuments = await database.rawQuery(
        'SELECT * FROM docs WHERE title=? and content=?',
        ['$keyword%', '$keyword%']);

</code>```

checked - doesn't work.

答:
```<code>  await database.rawQuery(
        'SELECT * FROM docs WHERE title="$keyword" AND content="$keyword"');
</code>```

Title: multiple arguments in sqflite flutter

Body:
I want to search database based on the keyword. if it title or content contains the keyword then return the data. but it send backs nothing.

  static Future<List<Note>> searchDocuments(String? keyword) async {
    final database = await DatabaseHelper.database();

    List<Map<String, dynamic>> allDocuments = await database.rawQuery(
        'SELECT * FROM docs WHERE title=? and content=?',
        ['$keyword%', '$keyword%']);

checked - doesn't work.


问:
How do I make my bulma progress bar not go over the whole screen?
This is my current code:

<progress class="progress is-warning" value="25" max="100">25%</progress>

I would want the progress bar to be shorter, meaning it not being as wide.

答:
Add max-width: <size>;, f.e. to adjust your progress bar width.

/* progress wrapper to show adjusted progress size */
.progress-wrapper {
  background-color: #ff6a0075;
  padding: .2rem;
}

.progress {
  /* width prop added for example purpose, to simulate wide bar */
  width: 100%;
  max-width: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="progress-wrapper">
  <progress class="progress is-warning" value="25" max="100">25%</progress>
</div></code>```

Body:
Add max-width: <size>;, f.e. to adjust your progress bar width.

/* progress wrapper to show adjusted progress size */
.progress-wrapper {
  background-color: #ff6a0075;
  padding: .2rem;
}

.progress {
  /* width prop added for example purpose, to simulate wide bar */
  width: 100%;
  max-width: 200px;
}

<div class="progress-wrapper">
  <progress class="progress is-warning" value="25" max="100">25%</progress>
</div>


问:
How to count special characters, Alphabets and numbers from a string in python?
```<code>string = '98 people are present @ seminar'

def count(string):
    d={}
    for t in string:
        d[t] = string.count(t)
    for k in sorted(d):
        print(k+':' +  str(d[k]))
count(string)
</code>```

here I want to add counters for special characters and numbers. also want to get user input for string. how do I do that?

答:
To ask for userinput for the string use

variableName = input(PROMPT)

To have a count make a list of nums, list of letters and the rest will be special chars
Then loop through the list and use an if statement to check if the letter is in the string with .contains()

The code would look something like this:

```<code>letters = "abcdefghijklmnopqrstuvwxyz"
numbers = "0123456789"
def countString(inputString,characterType):#inputString is the string you want to check characterType is what you want to check for
    count = 0
    inputString = inputString.lower()
    if characterType == "numbers":
        for i in inputString:
            if not(numbers.count(i) == 0):
                count += 1
    elif characterType == "letters":
        for i in inputString:
            if not(letters.count(i) == 0):
                count += 1
    elif characterType == "specialChars":
        for i in inputString:
            if numbers.count(i) == 0 and letters.count(i) == 0 and not(i == " ") :
                count += 1
    return count
</code>```

Body:
string = '98 people are present @ seminar'

def count(string):
    d={}
    for t in string:
        d[t] = string.count(t)
    for k in sorted(d):
        print(k+':' +  str(d[k]))
count(string)

here I want to add counters for special characters and numbers. also want to get user input for string. how do I do that?

Body:
To ask for userinput for the string use

variableName = input(PROMPT)

To have a count make a list of nums, list of letters and the rest will be special chars
Then loop through the list and use an if statement to check if the letter is in the string with .contains()

The code would look something like this:

letters = "abcdefghijklmnopqrstuvwxyz"
numbers = "0123456789"
def countString(inputString,characterType):#inputString is the string you want to check characterType is what you want to check for
    count = 0
    inputString = inputString.lower()
    if characterType == "numbers":
        for i in inputString:
            if not(numbers.count(i) == 0):
                count += 1
    elif characterType == "letters":
        for i in inputString:
            if not(letters.count(i) == 0):
                count += 1
    elif characterType == "specialChars":
        for i in inputString:
            if numbers.count(i) == 0 and letters.count(i) == 0 and not(i == " ") :
                count += 1
    return count


问:
Find first maximum value in a 2d array - Python
I am using a nested for loop to find the coordinates of the maximum value in a 2d array, like the one in the example. In case the value is repeated the loop breaks after the first one is found. It works like this, but I am not good at writing code and I need a more efficient way to do it, because when the 2d array is big (let's say a (880x1024 matrix)) it takes long time to find the value.
Any suggestions? Is there a much easier way to find the coordinates I need?

```<code>example = np.array([[10, 20, 30], [40, 50, 60], [70, 101, 90], [101, 101, 101], [61, 62, 101], [71, 72, 73]])
count_i = 0
count_j = 0
for i in example:
    count_i += 1
    for j in i:
        count_j += 1
        if j == np.max(example):
            print('value found', j)
            print('row coordinate', count_i)
            col = matrix.shape[1] - ((matrix.shape[1] * count_i) - count_j)
            print('colum coordinate', col)
            break
    else:
        continue
    break
</code>```

答:
Try this with numpy.

Get the argument containing the maximum value of a flattened bi-dimensional array with max_unidimensional_index = np.argmax(bidim_array, axis=None)

Map the max_unidimensional_index to the original bi-dimensional  shape array with np.unravel

bidim_index = np.unravel_index(max_unidimensional_index, bidim_array.shape)

```<code>import numpy as np

bidim_index = np.unravel_index(np.argmax(example, axis=None), example.shape)
</code>```

Body:
I am using a nested for loop to find the coordinates of the maximum value in a 2d array, like the one in the example. In case the value is repeated the loop breaks after the first one is found. It works like this, but I am not good at writing code and I need a more efficient way to do it, because when the 2d array is big (let's say a (880x1024 matrix)) it takes long time to find the value.
Any suggestions? Is there a much easier way to find the coordinates I need?

example = np.array([[10, 20, 30], [40, 50, 60], [70, 101, 90], [101, 101, 101], [61, 62, 101], [71, 72, 73]])
count_i = 0
count_j = 0
for i in example:
    count_i += 1
    for j in i:
        count_j += 1
        if j == np.max(example):
            print('value found', j)
            print('row coordinate', count_i)
            col = matrix.shape[1] - ((matrix.shape[1] * count_i) - count_j)
            print('colum coordinate', col)
            break
    else:
        continue
    break

Body:
Try this with numpy.

Get the argument containing the maximum value of a flattened bi-dimensional array with max_unidimensional_index = np.argmax(bidim_array, axis=None)

Map the max_unidimensional_index to the original bi-dimensional  shape array with np.unravel

bidim_index = np.unravel_index(max_unidimensional_index, bidim_array.shape)

import numpy as np

bidim_index = np.unravel_index(np.argmax(example, axis=None), example.shape)


问:
Can every recursive process be transformed into an iterative process?
I was reading the book, Structure and Interpretation of Computer Programs, where in it tells about the distinction between a recursive procedure and recursive process, and similarly between iterative procedure and iterative process. So, a recursive procedure could still generate an iterative process.

My question is: given a procedure which generates a recursive process, can you always write another procedure that achieves the same result but generates an iterative process?

The specific problem that I was trying to solve was to write a procedure which does an in-order traversal of a binary search tree but generates an iterative process. I know how you can use a stack to get an iterative procedure for this problem. However, that still generates a recursive process (correct me if I am wrong here).

Thanks,

Abhinav.

答:
Some tasks are truly impossible to solve with linear iterative processes (e.g. tree recursion, which is impossible to convert to tail recursion). You either have to use the stack built into your platform, or re-create it yourself within the language (usually a much less efficient and uglier solution).
So if you define 'recursion' as 'using a stack to store different invocations of the same code', then yes, recursion sometimes is absolutely required.

If you define 'recursion' as 'a function in my language (eventually) calling itself', then you can get by without explicit recursion by re-implementing recursiveness yourself, as describes above. This is only useful if your language doesn't provide recursive procedures, or not enough stack space, or has similar limitations. (For instance, early Fortran's didn't have recursive procedures. Of course, they also didn't have the dynamic data structures that you would need to simulate them! Personally, I have never come across an actual example where implementing pseudo-recursion was the right solution.)


问:
Quartz, setting up postgres schema, what should JOB_DATA be?
I'm using liquibase to setup the database tables for quartz as per Bert R recipe.

What is the correct type for the JOB_DATA columns for postgres?

The raw error is

```<code>Caused by: org.quartz.JobPersistenceException: Couldn't retrieve trigger: 2
at org.quartz.impl.jdbcjobstore.JobStoreSupport.retrieveTrigger(JobStoreSupport.java:1538)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 2
at org.postgresql.util.PGbytea.toBytes(PGbytea.java:76)
</code>```

The base error is in PostgreSQlDelegate.java trying to read the JOB_DATA column from the qrtz_triggers table. This column does have just \x in it.

I have changed the above liquibase file to change the type from BLOB to BYTEA as I was getting an error

```<code>column "job_data" is of type oid but expression is of type bytea
</code>```

The quartz properties file includes the following settings for the Job Store

```<code># Job Store
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass =
org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
</code>```

答: For those like me who struggled to find the quartz db creation schema, you can also find in the github repo under main/resources/org/quartz/impl/jdbcjobstore/.

Body:
I'm using liquibase to setup the database tables for quartz as per Bert R recipe.

What is the correct type for the JOB_DATA columns for postgres?

The raw error is

Caused by: org.quartz.JobPersistenceException: Couldn't retrieve trigger: 2
at org.quartz.impl.jdbcjobstore.JobStoreSupport.retrieveTrigger(JobStoreSupport.java:1538)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 2
at org.postgresql.util.PGbytea.toBytes(PGbytea.java:76)

The base error is in PostgreSQlDelegate.java trying to read the JOB_DATA column from the qrtz_triggers table. This column does have just \x in it.

I have changed the above liquibase file to change the type from BLOB to BYTEA as I was getting an error

column "job_data" is of type oid but expression is of type bytea

The quartz properties file includes the following settings for the Job Store

# Job Store
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass =
org.quartz.impl.jdbcjobstore.PostgreSQLDelegate


问:
How to use Hive without hadoop
I am a new to NoSQL solutions and want to play with Hive. But installing HDFS/Hadoop takes a lot of resources and time (maybe without experience but I got no time to do this).

Are there ways to install and use Hive on a local machine without HDFS/Hadoop?

答:
Top answer works for me. But need few more setups. I spend a quite some time search around to fix multiple problems until I finally set it up. Here I summarize the steps from scratch:

Download hive, decompress it

Download hadoop,  decompress it, put it in the same parent folder as hive

Setup hive-env.sh

$ cd hive/conf
$ cp hive-env.sh.template hive-env.sh
```
Add following environment in <code>hive-env.sh</code> (change path accordingly based
on actual java/hadoop version)
<pre class="lang-sh prettyprint-override"><code>JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_281.jdk/Contents/Home
export path=$JAVA_HOME/bin:$path
export HADOOP_HOME=${bin}/../../hadoop-3.3.1
</code>```

setup hive-site.xml
```<code>$ cd hive/conf
$ cp hive-default.xml.template hive-site.xml
</code>```
Replace all the variable ${system:***} with constant paths (Not sure why this is not recognized in my system).
Set database path to local with following attributes (copied from top answer)
```<code><configuration>
    <property>
       <name>hive.metastore.schema.verification</name>
       <value>false</value>
    </property>
   <property>
    <!-- this should eventually be deprecated since the metastore should supply this -->
      <name>hive.metastore.warehouse.dir</name>
      <value>file:///tmp</value>
      <description></description>
   </property>
   <property>
      <name>fs.default.name</name>
      <value>file:///tmp</value>
   </property>
  </configuration>
</code>```

setup hive-log4j2.properties (optional, good for troubleshooting)

cp hive-log4j2.properties.template hive-log4j2.properties
```
Replace all the variable <code>${sys:***}</code> to constant path</li>
<li>Setup <code>metastore_db</code>
If you directly run <code>hive</code>, when do any DDL, you will got error of:
<pre class="lang-sh prettyprint-override"><code>FAILED: HiveException org.apache.hadoop.hive.ql.metadata.HiveException:MetaException(message:Hive metastore database is not initialized. Please use schematool (e.g. ./schematool -initSchema -dbType ...) to create the schema. If needed, don't forget to include the option to auto-create the underlying database in your JDBC connection string (e.g. ? createDatabaseIfNotExist=true for mysql))
</code>```
In that case we need to recreate metastore_db with following command
```<code>$ cd hive/bin
$ rm -rf metastore_db
$ ./schematool -initSchema -dbType derby
</code>```

Start hive

$ cd hive/bin
$ ./hive
```

Now you should be able run hive on you local file system. One thing to note, the metastore_db will always be created on you current directory. If you start hive in a different directory, you need to recreate it again.

Title: How to use Hive without hadoop

Body:
Top answer works for me. But need few more setups. I spend a quite some time search around to fix multiple problems until I finally set it up. Here I summarize the steps from scratch:

Download hive, decompress it

Download hadoop,  decompress it, put it in the same parent folder as hive

Setup hive-env.sh

$ cd hive/conf
$ cp hive-env.sh.template hive-env.sh

Add following environment in hive-env.sh (change path accordingly based
on actual java/hadoop version)

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_281.jdk/Contents/Home
export path=$JAVA_HOME/bin:$path
export HADOOP_HOME=${bin}/../../hadoop-3.3.1

setup hive-site.xml

$ cd hive/conf
$ cp hive-default.xml.template hive-site.xml

Replace all the variable ${system:***} with constant paths (Not sure why this is not recognized in my system).
Set database path to local with following attributes (copied from top answer)

<configuration>
    <property>
       <name>hive.metastore.schema.verification</name>
       <value>false</value>
    </property>
   <property>
    <!-- this should eventually be deprecated since the metastore should supply this -->
      <name>hive.metastore.warehouse.dir</name>
      <value>file:///tmp</value>
      <description></description>
   </property>
   <property>
      <name>fs.default.name</name>
      <value>file:///tmp</value>
   </property>
  </configuration>

setup hive-log4j2.properties (optional, good for troubleshooting)

cp hive-log4j2.properties.template hive-log4j2.properties

Replace all the variable ${sys:***} to constant path

Setup metastore_db
If you directly run hive, when do any DDL, you will got error of:

FAILED: HiveException org.apache.hadoop.hive.ql.metadata.HiveException:MetaException(message:Hive metastore database is not initialized. Please use schematool (e.g. ./schematool -initSchema -dbType ...) to create the schema. If needed, don't forget to include the option to auto-create the underlying database in your JDBC connection string (e.g. ? createDatabaseIfNotExist=true for mysql))

In that case we need to recreate metastore_db with following command

$ cd hive/bin
$ rm -rf metastore_db
$ ./schematool -initSchema -dbType derby

Start hive

$ cd hive/bin
$ ./hive

Now you should be able run hive on you local file system. One thing to note, the metastore_db will always be created on you current directory. If you start hive in a different directory, you need to recreate it again.


问:
Retrieve the PyTorch model from a PyTorch lightning model
I have trained a PyTorch lightning model that looks like this:

```<code>In [16]: MLP
Out[16]:
DecoderMLP(
  (loss): RMSE()
  (logging_metrics): ModuleList(
    (0): SMAPE()
    (1): MAE()
    (2): RMSE()
    (3): MAPE()
    (4): MASE()
  )
  (input_embeddings): MultiEmbedding(
    (embeddings): ModuleDict(
      (LCLid): Embedding(5, 4)
      (sun): Embedding(5, 4)
      (day_of_week): Embedding(7, 5)
      (month): Embedding(12, 6)
      (year): Embedding(3, 3)
      (holidays): Embedding(2, 1)
      (BusinessDay): Embedding(2, 1)
      (day): Embedding(31, 11)
      (hour): Embedding(24, 9)
    )
  )
  (mlp): FullyConnectedModule(
    (sequential): Sequential(
      (0): Linear(in_features=60, out_features=435, bias=True)
      (1): ReLU()
      (2): Dropout(p=0.13371112461182535, inplace=False)
      (3): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (4): Linear(in_features=435, out_features=435, bias=True)
      (5): ReLU()
      (6): Dropout(p=0.13371112461182535, inplace=False)
      (7): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (8): Linear(in_features=435, out_features=435, bias=True)
      (9): ReLU()
      (10): Dropout(p=0.13371112461182535, inplace=False)
      (11): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (12): Linear(in_features=435, out_features=435, bias=True)
      (13): ReLU()
      (14): Dropout(p=0.13371112461182535, inplace=False)
      (15): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (16): Linear(in_features=435, out_features=435, bias=True)
      (17): ReLU()
      (18): Dropout(p=0.13371112461182535, inplace=False)
      (19): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (20): Linear(in_features=435, out_features=435, bias=True)
      (21): ReLU()
      (22): Dropout(p=0.13371112461182535, inplace=False)
      (23): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (24): Linear(in_features=435, out_features=435, bias=True)
      (25): ReLU()
      (26): Dropout(p=0.13371112461182535, inplace=False)
      (27): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (28): Linear(in_features=435, out_features=435, bias=True)
      (29): ReLU()
      (30): Dropout(p=0.13371112461182535, inplace=False)
      (31): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (32): Linear(in_features=435, out_features=435, bias=True)
      (33): ReLU()
      (34): Dropout(p=0.13371112461182535, inplace=False)
      (35): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (36): Linear(in_features=435, out_features=1, bias=True)
    )
  )
)
</code>```

I need the corresponding PyTorch model to use in one of my other applications.

Is there a simple way to do that?

I thought of saving the checkpoint but then I don't know how to do it.

Can you please help?
Thanks

答:
You can manually save the weights of the torch.nn.Modules in the LightningModule. Something like:

trainer.fit(model, trainloader, valloader)

torch.save(
    model.input_embeddings.state_dict(),
    "input_embeddings.pt"
)
torch.save(model.mlp.state_dict(), "mlp.pt")
```
<p>Then to load without needing Lightning:</p>
<pre class="lang-py prettyprint-override"><code># create the "blank" networks like they
# were created in the Lightning Module
input_embeddings = MultiEmbedding(...)
mlp = FullyConnectedModule(...)

# Load the models for inference
input_embeddings.load_state_dict(
    torch.load("input_embeddings.pt")
)
input_embeddings.eval()

mlp.load_state_dict(
    torch.load("mlp.pt")
)
mlp.eval()
</code>```

For more information about saving and loading PyTorch Modules see Saving and Loading Models: Saving & Loading Model for Inference in the PyTorch documentation.

Since Lightning automatically saves checkpoints to disk (check the lightning_logs folder if using the default Tensorboard logger), you can also load a pretrained LightningModule and then save the state dicts without needing to repeat all the training. Instead of calling trainer.fit in the previous code, try

model = DecoderMLP.load_from_checkpoint("path/to/checkpoint.ckpt")
```

Body:
I have trained a PyTorch lightning model that looks like this:

In [16]: MLP
Out[16]:
DecoderMLP(
  (loss): RMSE()
  (logging_metrics): ModuleList(
    (0): SMAPE()
    (1): MAE()
    (2): RMSE()
    (3): MAPE()
    (4): MASE()
  )
  (input_embeddings): MultiEmbedding(
    (embeddings): ModuleDict(
      (LCLid): Embedding(5, 4)
      (sun): Embedding(5, 4)
      (day_of_week): Embedding(7, 5)
      (month): Embedding(12, 6)
      (year): Embedding(3, 3)
      (holidays): Embedding(2, 1)
      (BusinessDay): Embedding(2, 1)
      (day): Embedding(31, 11)
      (hour): Embedding(24, 9)
    )
  )
  (mlp): FullyConnectedModule(
    (sequential): Sequential(
      (0): Linear(in_features=60, out_features=435, bias=True)
      (1): ReLU()
      (2): Dropout(p=0.13371112461182535, inplace=False)
      (3): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (4): Linear(in_features=435, out_features=435, bias=True)
      (5): ReLU()
      (6): Dropout(p=0.13371112461182535, inplace=False)
      (7): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (8): Linear(in_features=435, out_features=435, bias=True)
      (9): ReLU()
      (10): Dropout(p=0.13371112461182535, inplace=False)
      (11): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (12): Linear(in_features=435, out_features=435, bias=True)
      (13): ReLU()
      (14): Dropout(p=0.13371112461182535, inplace=False)
      (15): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (16): Linear(in_features=435, out_features=435, bias=True)
      (17): ReLU()
      (18): Dropout(p=0.13371112461182535, inplace=False)
      (19): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (20): Linear(in_features=435, out_features=435, bias=True)
      (21): ReLU()
      (22): Dropout(p=0.13371112461182535, inplace=False)
      (23): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (24): Linear(in_features=435, out_features=435, bias=True)
      (25): ReLU()
      (26): Dropout(p=0.13371112461182535, inplace=False)
      (27): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (28): Linear(in_features=435, out_features=435, bias=True)
      (29): ReLU()
      (30): Dropout(p=0.13371112461182535, inplace=False)
      (31): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (32): Linear(in_features=435, out_features=435, bias=True)
      (33): ReLU()
      (34): Dropout(p=0.13371112461182535, inplace=False)
      (35): LayerNorm((435,), eps=1e-05, elementwise_affine=True)
      (36): Linear(in_features=435, out_features=1, bias=True)
    )
  )
)

I need the corresponding PyTorch model to use in one of my other applications.

Is there a simple way to do that?

I thought of saving the checkpoint but then I don't know how to do it.

Can you please help?
Thanks

Body:
You can manually save the weights of the torch.nn.Modules in the LightningModule. Something like:

trainer.fit(model, trainloader, valloader)

torch.save(
    model.input_embeddings.state_dict(),
    "input_embeddings.pt"
)
torch.save(model.mlp.state_dict(), "mlp.pt")

Then to load without needing Lightning:

# create the "blank" networks like they
# were created in the Lightning Module
input_embeddings = MultiEmbedding(...)
mlp = FullyConnectedModule(...)

# Load the models for inference
input_embeddings.load_state_dict(
    torch.load("input_embeddings.pt")
)
input_embeddings.eval()

mlp.load_state_dict(
    torch.load("mlp.pt")
)
mlp.eval()

For more information about saving and loading PyTorch Modules see Saving and Loading Models: Saving & Loading Model for Inference in the PyTorch documentation.

Since Lightning automatically saves checkpoints to disk (check the lightning_logs folder if using the default Tensorboard logger), you can also load a pretrained LightningModule and then save the state dicts without needing to repeat all the training. Instead of calling trainer.fit in the previous code, try

model = DecoderMLP.load_from_checkpoint("path/to/checkpoint.ckpt")


问:
Make Image Clickable on Slide Show
I'm using this code for slide show. I can't seem to get the image clickable without losing the name in the 'name' div.

What I'm after is to be able to click on a picture on the slide show and be able to go to the details page. Whenever I get the image clickable, the name does not display in the 'name' div; and if I remove the link, then the name will display.

I don't know how to solve this problem.

Here's the code I'm using.

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>JQuery Cycle Plugin - Pager Demo with Prev/Next Controls</title>
<link rel="stylesheet" type="text/css" media="screen" href="../jq.css" />
<link rel="stylesheet" type="text/css" media="screen" href="cycle.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/chili-1.7.pack.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.cycle.all.js"></script>

<style type="text/css">
#main { margin: 20px }
#nav { margin: 10px; position: relative }
#nav li { float: left; list-style: none}
#nav a { margin: 5px; padding: 3px 5px; border: 1px solid #ccc; background: #fc0; text-decoration: none }
#nav li.activeSlide a { background: #faa; color: black }
#nav a:focus { outline: none; }

</style>

<script type="text/javascript">
$(document).ready(function() {
     $('#slideshow').cycle({
          prev:    '.prev', // Setup prev links
          next:    '.next', // Setup next links
          pager:   '.nav',       // Setup pager navs
          before: function () {
          $("#name").text(this.alt);     }
     });
});
</script>

<style type="text/css">
#left, #slideshow, #right { float: left; width: 200px; }
</style>
</head>
<body>

<!-- left nav bar -->
<div id="left">
    <a href="#"><span class="prev">Prev</span></a>
    <a href="#"><span class="next">Next</span></a>

    <ul class="nav"></ul>
</div>

<!-- slideshow -->
<div id="slideshow">

 <?php
                 mysql_connect("localhost", "root", "")or die("cannot connect");
                 mysql_select_db($db_name)or die("cannot select DB");

                 $data = mysql_query("SELECT * FROM people") or die(mysql_error());
                 while($info = mysql_fetch_array( $data )){
    <!--HERE ON THIS LINE---- > echo "<a href=\"show.php?id=".$info['id']."\"><img src=\"http://localhost:8080/about/images/".$info['photo'] . "\" alt=\"".$info['name'] ."\"/>";
  }
?>

</div>

 <div id="name">

 </div>
 <!-- right nav bar -->
 <div id="right">
     <a href="#"><span class="prev">Prev</span></a>
     <a href="#"><span class="next">Next</span></a>
     <ul class="nav"></ul>
 </div>

 </div>

</body>
</html>
</code>```

Thanks for your assistance

答:
Problem comes from your before parameter in the cycle definition

```<code>function () { $("#name").text(this.alt); }
</code>```

It should be something like

```<code>function () { $("#name").text($(this).children("img").attr("alt")); }
</code>```

I can't test it right now, though.

Title: Make Image Clickable on Slide Show

Body:
I'm using this code for slide show. I can't seem to get the image clickable without losing the name in the 'name' div.

What I'm after is to be able to click on a picture on the slide show and be able to go to the details page. Whenever I get the image clickable, the name does not display in the 'name' div; and if I remove the link, then the name will display.

I don't know how to solve this problem.

Here's the code I'm using.

<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>JQuery Cycle Plugin - Pager Demo with Prev/Next Controls</title>
<link rel="stylesheet" type="text/css" media="screen" href="../jq.css" />
<link rel="stylesheet" type="text/css" media="screen" href="cycle.css" />

    Prev
    Next

 <?php
                 mysql_connect("localhost", "root", "")or die("cannot connect");
                 mysql_select_db($db_name)or die("cannot select DB");

                 $data = mysql_query("SELECT * FROM people") or die(mysql_error());
                 while($info = mysql_fetch_array( $data )){

     Prev
     Next

Thanks for your assistance

Body:
Problem comes from your before parameter in the cycle definition

function () { $("#name").text(this.alt); }

It should be something like

function () { $("#name").text($(this).children("img").attr("alt")); }

I can't test it right now, though.


问:
How to freeze parts of T5 transformer model
I know that T5 has K, Q and V vectors in each layer. It also has a feedforward network. I would like to freeze K, Q and V vectors and only train the feedforward layers on each layer of T5. I use Pytorch library. The model could be a wrapper for huggingface T5 model or a modified version of it. I know how to freeze all parameters using the following code:

tokenizer = AutoTokenizer.from_pretrained(underlying_model_name)
model = T5ForConditionalGeneration.from_pretrained(underlying_model_name)

for p in model.parameters():
    p.requires_grad = False # freezing
```

Could you please guide me how can I do this?

This github project probably could be helpful but it's for Roberta and GPT, could I adapt it for T5?

答:
I've adapted a solution based on this discussion from the Huggingface forums.
Basically, you have to specify the names of the modules/pytorch layers that you want to freeze.

In your particular case of T5, I started by looking at the model summary:

from transformers import T5ModelForConditionalGeneration

model = T5ModelForConditionalGeneration.from_pretrained("t5-small")
print(model)
```
<p>This gives the following (abbreviated output):</p>
```T5ForConditionalGeneration(
  (shared): Embedding(32128, 512)
  (encoder): T5Stack(
    (embed_tokens): Embedding(32128, 512)
    (block): ModuleList(
      (0): T5Block(
        (layer): ModuleList(
          (0): T5LayerSelfAttention(
            (SelfAttention): T5Attention(
              (q): Linear(in_features=512, out_features=512, bias=False)
              (k): Linear(in_features=512, out_features=512, bias=False)
              (v): Linear(in_features=512, out_features=512, bias=False)
              (o): Linear(in_features=512, out_features=512, bias=False)
              (relative_attention_bias): Embedding(32, 8)
            )
            (layer_norm): T5LayerNorm()
            (dropout): Dropout(p=0.1, inplace=False)
          )
          (1): T5LayerFF(
            (DenseReluDense): T5DenseReluDense(
              (wi): Linear(in_features=512, out_features=2048, bias=False)
              (wo): Linear(in_features=2048, out_features=512, bias=False)
              (dropout): Dropout(p=0.1, inplace=False)
            )
            (layer_norm): T5LayerNorm()
            (dropout): Dropout(p=0.1, inplace=False)
          )
        )
      )
[...]  # abbreviated output
```
<p>with this, we can then generate a list of modules that we want to freeze. In particular, I decided to freeze the entire <code>T5LayerSelfAttention</code> block for the encoder (and, additionally, the <code>T5LayerCrossAttention</code> for the decoder):</p>
<pre class="lang-py prettyprint-override"><code># All modules in the
modules_to_freeze = [model.encoder.block[i].layer[0] for i in range(len(model.encoder.block))]
# And the decoder modules, which has both a SelfAttention (layer[0])
modules_to_freeze.extend([model.decoder.block[i].layer[0] for i in range(len(model.decoder.block))])
# and CrossAttention (layer[1]) block
modules_to_freeze.extend([model.decoder.block[i].layer[1] for i in range(len(model.decoder.block))])
</code>```

And then simply freeze all the parameters in the respective modules:

for module in modules_to_freeze:
    for param in module.parameters():
        param.requires_grad = False  # Actual freezing operation
```
<p>You can verify that these are actually frozen in your model by running the following:</p>
<pre class="lang-py prettyprint-override"><code>for param in model.parameters():
    print(param.requires_grad)
</code>```

which should print quite a few False as well. If you really only want to freeze K, Q and V, you can adapt the above process to just sub-select the modules you want.

Body:
I know that T5 has K, Q and V vectors in each layer. It also has a feedforward network. I would like to freeze K, Q and V vectors and only train the feedforward layers on each layer of T5. I use Pytorch library. The model could be a wrapper for huggingface T5 model or a modified version of it. I know how to freeze all parameters using the following code:

tokenizer = AutoTokenizer.from_pretrained(underlying_model_name)
model = T5ForConditionalGeneration.from_pretrained(underlying_model_name)

for p in model.parameters():
    p.requires_grad = False # freezing

Could you please guide me how can I do this?

This github project probably could be helpful but it's for Roberta and GPT, could I adapt it for T5?

Body:
I've adapted a solution based on this discussion from the Huggingface forums.
Basically, you have to specify the names of the modules/pytorch layers that you want to freeze.

In your particular case of T5, I started by looking at the model summary:

from transformers import T5ModelForConditionalGeneration

model = T5ModelForConditionalGeneration.from_pretrained("t5-small")
print(model)

This gives the following (abbreviated output):

T5ForConditionalGeneration(
  (shared): Embedding(32128, 512)
  (encoder): T5Stack(
    (embed_tokens): Embedding(32128, 512)
    (block): ModuleList(
      (0): T5Block(
        (layer): ModuleList(
          (0): T5LayerSelfAttention(
            (SelfAttention): T5Attention(
              (q): Linear(in_features=512, out_features=512, bias=False)
              (k): Linear(in_features=512, out_features=512, bias=False)
              (v): Linear(in_features=512, out_features=512, bias=False)
              (o): Linear(in_features=512, out_features=512, bias=False)
              (relative_attention_bias): Embedding(32, 8)
            )
            (layer_norm): T5LayerNorm()
            (dropout): Dropout(p=0.1, inplace=False)
          )
          (1): T5LayerFF(
            (DenseReluDense): T5DenseReluDense(
              (wi): Linear(in_features=512, out_features=2048, bias=False)
              (wo): Linear(in_features=2048, out_features=512, bias=False)
              (dropout): Dropout(p=0.1, inplace=False)
            )
            (layer_norm): T5LayerNorm()
            (dropout): Dropout(p=0.1, inplace=False)
          )
        )
      )
[...]  # abbreviated output

with this, we can then generate a list of modules that we want to freeze. In particular, I decided to freeze the entire T5LayerSelfAttention block for the encoder (and, additionally, the T5LayerCrossAttention for the decoder):

# All modules in the
modules_to_freeze = [model.encoder.block[i].layer[0] for i in range(len(model.encoder.block))]
# And the decoder modules, which has both a SelfAttention (layer[0])
modules_to_freeze.extend([model.decoder.block[i].layer[0] for i in range(len(model.decoder.block))])
# and CrossAttention (layer[1]) block
modules_to_freeze.extend([model.decoder.block[i].layer[1] for i in range(len(model.decoder.block))])

And then simply freeze all the parameters in the respective modules:

for module in modules_to_freeze:
    for param in module.parameters():
        param.requires_grad = False  # Actual freezing operation

You can verify that these are actually frozen in your model by running the following:

for param in model.parameters():
    print(param.requires_grad)

which should print quite a few False as well. If you really only want to freeze K, Q and V, you can adapt the above process to just sub-select the modules you want.


问:
python I got a complex multiple nested JSON file, how to convert to csv file
Here is my code, It can only convert part of the JSON file, it fails to flatten all JSON，Unable to convert all files

```<code>import pandas as pd
import json
all_data = []
add_header = True
with open('C:\\Users\\jeri\\Desktop\\1.json',encoding='utf-8') as f_json:
    for line in f_json:
        line = line.strip()
        if line:
            all_data.append(json.loads(line))
df = pd.json_normalize(all_data)
df.to_csv('C:\\Users\\jeri\\Desktop\\11.csv', index=False,encoding='utf-8',header=add_header)
add_header = False

</code>```

my json file

```<code>
{"id":"aa","sex":"male","name":[{"Fn":"jeri","Ln":"teri"}],"age":45,"info":[{"address":{"State":"NY","City":"new york"},"start_date":"2001-09","title":{"name":"Doctor","Exp":"head"},"year":"2001","month":"05"}],"other":null,"Hobby":[{"smoking":null,"gamble":null}],"connect":[{"phone":"123456789","email":"info@gmail.com"}],"Education":"MBA","School":{"State":"NY","City":"new york"}}
{"id":"aa","sex":"female","name":[{"Fn":"lo","Ln":"li"}],"age":34,"info":[{"address":{"State":"NY","City":"new york"},"start_date":"2008-11","title":{"name":"Doctor","Exp":"hand"},"year":"2008","month":"02"}],"other":null,"Hobby":[{"smoking":null,"gamble":null}],"connect":[{"phone":"123456789","email":"info@gmail.com"}],"Education":"MBA","School":{"State":"NY","City":"new york"}}

</code>```

The result of the conversion is below,Not all json files are converted，this is not what i want，I need to flatten and convert all files,

```<code>id,sex,name,age,info,other,Hobby,connect,Education,School.State,School.City
aa,male,"[{'Fn': 'jeri', 'Ln': 'teri'}]",45,"[{'address': {'State': 'NY', 'City': 'new york'}, 'start_date': '2001-09', 'title': {'name': 'Doctor', 'Exp': 'head'}, 'year': '2001', 'month': '05'}]",,"[{'smoking': None, 'gamble': None}]","[{'phone': '123456789', 'email': 'info@gmail.com'}]",MBA,NY,new york
aa,female,"[{'Fn': 'lo', 'Ln': 'li'}]",34,"[{'address': {'State': 'NY', 'City': 'new york'}, 'start_date': '2008-11', 'title': {'name': 'Doctor', 'Exp': 'hand'}, 'year': '2008', 'month': '02'}]",,"[{'smoking': None, 'gamble': None}]","[{'phone': '123456789', 'email': 'info@gmail.com'}]",MBA,NY,new york

</code>```

new code

```<code>import pandas as pd
import json
data = []
add_header = True
with open('C:\\Users\\jeri\\Desktop\\1.json',encoding='utf-8') as f_json:
    for line in f_json:
        line = line.strip()
        if line:
            data.append(json.loads(line))
df = pd.json_normalize(data)
dfe = explode('name').explode('info').explode("Hobby"),pd.concat([df, pd.json_normalize(df.name),
                                                                  pd.json_normalize(df.info),
                                                                  pd.json_normalize(df.Hobby)], axis=1)
dfe.to_csv('C:\\Users\\jeri\\Desktop\\11.csv', index=False,encoding='utf-8',header=add_header)
add_header = False

</code>```

output

```<code>id,sex,age,other,Education,School,Fn,Ln,start_date,year,month,address.State,address.City,title.name,title.Exp,phone,email,smoking,gamble
aa,male,45,,MBA,"{'State': 'NY', 'City': 'new york'}",jeri,teri,2001-09,2001,05,NY,new york,Doctor,head,123456789,info@gmail.com,,
aa,female,34,,MBA,"{'State': 'NY', 'City': 'new york'}",lo,li,2008-11,2008,02,NY,new york,Doctor,hand,123456789,info@gmail.com,,

</code>```

答:
pd.json_normalize flattens the dictionary to columns. When you have list, you need to explode the list that transform the list into rows.
If you have dictionary inside the list, you need to apply the json_normalize again on the exploded column.

import pandas as pd

data = []
# read_json normalizes the top layer.
df_it = pd.read_json('C:\\Users\\jeri\\Desktop\\1.json', encoding='utf-8', lines=True, chunksize=100000)
for sub in df_it:
    data.append(sub)

df = pd.concat(data)

# You just need to flatten the list of dict additionally.
# If you are using pandas >= 1.3.0, df = df.explode(['name', 'info', 'Hobby'])
# Otherwise, explode only takes 1 column at a time.
df = df.explode('name').explode('info').explode("Hobby")
df = pd.concat([df.reset_index(drop=True),
                pd.json_normalize(df.name),
                # info is reserved keyword (dataframe function name, you cannot use df.info),
                # change it to accessing by df['info']
                pd.json_normalize(df['info']),
                pd.json_normalize(df.Hobby)], axis=1)
# Drop the exploded column, the contents inside the column is extracted to columns already
df = df.drop(['name', 'info', 'Hobby'], axis=1)

df.to_csv('C:\\Users\\jeri\\Desktop\\11.csv', index=False, encoding='utf-8')
```

Another thing to consider is when you have multiple json_normalize, you need to make sure that key in each dict column is not shared amongst the other columns you try to json_normalize. In your sample, I didn't see any of same key name, so I did concat and json_normalize in 1 shot.

However, if you have same key name in dict, you need to take step by step. Do json_normalize on 1 exploded column and rename column(s), then do another json_normalize on another exploded column.

Body:
Here is my code, It can only convert part of the JSON file, it fails to flatten all JSON，Unable to convert all files

import pandas as pd
import json
all_data = []
add_header = True
with open('C:\\Users\\jeri\\Desktop\\1.json',encoding='utf-8') as f_json:
    for line in f_json:
        line = line.strip()
        if line:
            all_data.append(json.loads(line))
df = pd.json_normalize(all_data)
df.to_csv('C:\\Users\\jeri\\Desktop\\11.csv', index=False,encoding='utf-8',header=add_header)
add_header = False

my json file

{"id":"aa","sex":"male","name":[{"Fn":"jeri","Ln":"teri"}],"age":45,"info":[{"address":{"State":"NY","City":"new york"},"start_date":"2001-09","title":{"name":"Doctor","Exp":"head"},"year":"2001","month":"05"}],"other":null,"Hobby":[{"smoking":null,"gamble":null}],"connect":[{"phone":"123456789","email":"info@gmail.com"}],"Education":"MBA","School":{"State":"NY","City":"new york"}}
{"id":"aa","sex":"female","name":[{"Fn":"lo","Ln":"li"}],"age":34,"info":[{"address":{"State":"NY","City":"new york"},"start_date":"2008-11","title":{"name":"Doctor","Exp":"hand"},"year":"2008","month":"02"}],"other":null,"Hobby":[{"smoking":null,"gamble":null}],"connect":[{"phone":"123456789","email":"info@gmail.com"}],"Education":"MBA","School":{"State":"NY","City":"new york"}}

The result of the conversion is below,Not all json files are converted，this is not what i want，I need to flatten and convert all files,

id,sex,name,age,info,other,Hobby,connect,Education,School.State,School.City
aa,male,"[{'Fn': 'jeri', 'Ln': 'teri'}]",45,"[{'address': {'State': 'NY', 'City': 'new york'}, 'start_date': '2001-09', 'title': {'name': 'Doctor', 'Exp': 'head'}, 'year': '2001', 'month': '05'}]",,"[{'smoking': None, 'gamble': None}]","[{'phone': '123456789', 'email': 'info@gmail.com'}]",MBA,NY,new york
aa,female,"[{'Fn': 'lo', 'Ln': 'li'}]",34,"[{'address': {'State': 'NY', 'City': 'new york'}, 'start_date': '2008-11', 'title': {'name': 'Doctor', 'Exp': 'hand'}, 'year': '2008', 'month': '02'}]",,"[{'smoking': None, 'gamble': None}]","[{'phone': '123456789', 'email': 'info@gmail.com'}]",MBA,NY,new york

new code

import pandas as pd
import json
data = []
add_header = True
with open('C:\\Users\\jeri\\Desktop\\1.json',encoding='utf-8') as f_json:
    for line in f_json:
        line = line.strip()
        if line:
            data.append(json.loads(line))
df = pd.json_normalize(data)
dfe = explode('name').explode('info').explode("Hobby"),pd.concat([df, pd.json_normalize(df.name),
                                                                  pd.json_normalize(df.info),
                                                                  pd.json_normalize(df.Hobby)], axis=1)
dfe.to_csv('C:\\Users\\jeri\\Desktop\\11.csv', index=False,encoding='utf-8',header=add_header)
add_header = False

output

id,sex,age,other,Education,School,Fn,Ln,start_date,year,month,address.State,address.City,title.name,title.Exp,phone,email,smoking,gamble
aa,male,45,,MBA,"{'State': 'NY', 'City': 'new york'}",jeri,teri,2001-09,2001,05,NY,new york,Doctor,head,123456789,info@gmail.com,,
aa,female,34,,MBA,"{'State': 'NY', 'City': 'new york'}",lo,li,2008-11,2008,02,NY,new york,Doctor,hand,123456789,info@gmail.com,,

Body:
pd.json_normalize flattens the dictionary to columns. When you have list, you need to explode the list that transform the list into rows.
If you have dictionary inside the list, you need to apply the json_normalize again on the exploded column.

import pandas as pd

data = []
# read_json normalizes the top layer.
df_it = pd.read_json('C:\\Users\\jeri\\Desktop\\1.json', encoding='utf-8', lines=True, chunksize=100000)
for sub in df_it:
    data.append(sub)

df = pd.concat(data)

# You just need to flatten the list of dict additionally.
# If you are using pandas >= 1.3.0, df = df.explode(['name', 'info', 'Hobby'])
# Otherwise, explode only takes 1 column at a time.
df = df.explode('name').explode('info').explode("Hobby")
df = pd.concat([df.reset_index(drop=True),
                pd.json_normalize(df.name),
                # info is reserved keyword (dataframe function name, you cannot use df.info),
                # change it to accessing by df['info']
                pd.json_normalize(df['info']),
                pd.json_normalize(df.Hobby)], axis=1)
# Drop the exploded column, the contents inside the column is extracted to columns already
df = df.drop(['name', 'info', 'Hobby'], axis=1)

df.to_csv('C:\\Users\\jeri\\Desktop\\11.csv', index=False, encoding='utf-8')

Another thing to consider is when you have multiple json_normalize, you need to make sure that key in each dict column is not shared amongst the other columns you try to json_normalize. In your sample, I didn't see any of same key name, so I did concat and json_normalize in 1 shot.

However, if you have same key name in dict, you need to take step by step. Do json_normalize on 1 exploded column and rename column(s), then do another json_normalize on another exploded column.


问:
django form doesn't display labels
I'm new in django. I try to create a simple form based on the model.
Imputs are displayed fine but i have problem with the labels.They don't appears on the page.
I can't figure out where is my mistake. For my it should be working fine.
Any idea what's is wrong here?

```<code>class RecForm (ModelForm):
    class Meta:
        model = Rec
        fields = ['name', 'kind',]
        labels = {
            'name': 'Here put your name',
        }
</code>```

home.html

```<code><form action="addrec" method="post">
    {% csrf_token %}
{% for i in form %}
 {{ i }}
    <br><br>
{% endfor %}

    <input type="submit" value="Submit">

{% endblock %}
</code>```

答:
You're rendering the field in your template as {{ i }}, with i being an instance of a BoundField (code). BoundField.__str__ calls widget.render (code) and returns the output. widget.render renders the value of of the widget's template (see widget templates here https://github.com/django/django/tree/4.0.2/django/forms/templates/django/forms/widgets). None of these templates include the label tag.

To render the label tag your should call {{ i.label_tag }} (code), which will render the tag with all attributes Django knows about. Extra attributes may require adjustments.

Title: django form doesn't display labels

Body:
I'm new in django. I try to create a simple form based on the model.
Imputs are displayed fine but i have problem with the labels.They don't appears on the page.
I can't figure out where is my mistake. For my it should be working fine.
Any idea what's is wrong here?

class RecForm (ModelForm):
    class Meta:
        model = Rec
        fields = ['name', 'kind',]
        labels = {
            'name': 'Here put your name',
        }

home.html

<form action="addrec" method="post">
    {% csrf_token %}
{% for i in form %}
 {{ i }}

{% endfor %}

    <input type="submit" value="Submit">

{% endblock %}


问:
Printing a multidimensional array in C
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

```<code>#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}
</code>```

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6

答:
Could you tell me where I am wrong

The elements of arr are not integers, but arrays of 3 integers. So arr+6 is surely a different address than what you expect, since pointer arithmetic works in multiples of the size of the type in the array.

You'll always be better off using nested loops to iterate over a multidimensional array; treating it as one single-dimensional array of int  leads to exactly the kinds of confusion you see here. The code is harder to understand and verify, it won't be any slower.

Title: Printing a multidimensional array in C

Body:
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6


问:
Is it possible to set a post date for checks?
I'm trying to use checks in the XRP ledger (https://xrpl.org/use-checks.html) from post dated checks use case where the receiver can only pull the payment after a specific date.

Anyone knows if this is possible?

答:
This is not possible with built-in Checks functionality at present.

Depending on your use case, you may be able to use a time-held Escrow.

Alternatively, if users are willing to trust an external service, you could write an app that only creates the Check (or Payment) after a specific date.