问:
Why can I click on a link outside of its text element?
I'm building a forum and I have a link that can be clicked outside of its text, how can I undo it?
I also have an image inside a tag that can be clicked outside of its image, I want to undo that too.
I have tried - position: relative; but it didn't work.

Here is the HTML code of the image.

```<code><div class="nav-list">
       <a class="home_A"href="Home.php">
          <img class="homeIcon" src="photos/icon.png">
       </a>
</div>
</code>```

CSS of the image

```<code>.homeIcon{
    width: 200px;
    display:block;
    margin:auto;
    margin: 0 auto;
}
</code>```

CSS of the  link

```<code>.signinForm a{
margin: auto;
display:block;
text-align:center;
margin-top: 7px;
color: #006db6;
font-size: 20px;
}
</code>```

HTML of the  link

```<code><form method="POST" class="signinForm">
<ul>
    <li> <h1 class="signinH1">sign in</h1></li>
    <li> <input type="text" placeholder="User name"name="username_login"class="username" value="<?php if(isset($_POST['username_login'])){echo $_POST['username_login'];}?>" required></li>
    <li> <input type="password" placeholder="Password" name="password_login" class="password" value="<?php  if(isset($_POST['password_login'])){echo $_POST['password_login'];}?>" required></li>
    <li> <input type="submit" value="Log in"class="signinbutton"></li>
    <li><a href="signUp.php">Sign up</a></li>
</ul>

</form>
</code>```

Thanks all.

答:
Try with something like:</p>
```<code>img.homeIcon {
  display: inline-block;
}

div.home_A {
align-content:center;
margin: 0 auto;
text-align: center; // Not mandatory but useful
}
</code>```

Body:
I'm building a forum and I have a link that can be clicked outside of its text, how can I undo it?
I also have an image inside a tag that can be clicked outside of its image, I want to undo that too.
I have tried - position: relative; but it didn't work.

Here is the HTML code of the image.

CSS of the image

.homeIcon{
    width: 200px;
    display:block;
    margin:auto;
    margin: 0 auto;
}

CSS of the  link

.signinForm a{
margin: auto;
display:block;
text-align:center;
margin-top: 7px;
color: #006db6;
font-size: 20px;
}

HTML of the  link

<form method="POST" class="signinForm">

sign in

 <input type="text" placeholder="User name"name="username_login"class="username" value="<?php if(isset($_POST['username_login'])){echo $_POST['username_login'];}?>" required>

 <input type="password" placeholder="Password" name="password_login" class="password" value="<?php  if(isset($_POST['password_login'])){echo $_POST['password_login'];}?>" required>

 <input type="submit" value="Log in"class="signinbutton">

Sign up

</form>

Thanks all.

Body:
Try with something like:

img.homeIcon {
  display: inline-block;
}

div.home_A {
align-content:center;
margin: 0 auto;
text-align: center; // Not mandatory but useful
}


来源: stackexchange

问:
Which version of ECMAScript does the Google Apps Script V8 Runtime use?
When you crate a new Google Apps Script, it seems to support the v8 runtime by default. The documentation states:

Apps Script supports two JavaScript runtimes: the modern V8 runtime and an older one powered by Mozilla's Rhino JavaScript interpreter.

The V8 runtime supports modern ECMAScript syntax and features.

The V8 runtime documentation states:

You can use modern ECMAScript syntax in scripts that are powered by the V8 runtime. This syntax includes let, const, and many other popular features.

In both cases, they are very vague as to which ECMAScript version is supported, simply stating "modern ECMAScript syntax". This is problematic because there are 7 versions that were released between 2015 and 2021. Thus "modern" could refer to any one of these versions.

For example, I could easily assume that "modern" refers to the latest, 12th edition (2022) of ECMAScript, and end up writing code like this:

```<code>let a = 1_000;
</code>```

However, attempting to use that syntax leads to the error:

Syntax error: ParseError: Unexpected token ILLEGAL line: ...

Rather than manually go through each of the remaining 6 versions until I find the latest one supported, it would be great to find documentation that explicitly states which ECMAScript version is supported.

Note: The previous related question (Which Edition of ECMA-262 Does Google Apps Script Support?) is not helpful since those answers also refer to "modern ECMAScript" rather than a definitive, specific version.

Which version of ECMAScript is supported by the V8 runtime?

答:
There is some nuance here:

Which version of V8 does Google Apps Script use?

A reasonably recent version, and it gets updated every so often. I believe the idea is to track or slightly lag behind stable Chrome releases, but (as with any large project updating its dependencies) there may occasionally be hiccups/delays. Right now it should be somewhere in the 9.x version range. (For future readers: I expect this statement to be outdated before 2022 is over!)

Which version of ECMAScript does the Google Apps Script V8 Runtime Support?

I suppose if there was a simple answer to this, you'd find that in the documentation. As @Kaiido said in comments, JavaScript engines implement new JavaScript features one by one (rather than EcmaScript versions). So, for browsers just like for environments like GAS, it usually makes more sense to ask "is feature X supported?", because it may well be that some, say, ES2020 features are still missing but some ES2021 features are already available.

Why does let a = 1_000; produce a Syntax Error?

Well, the V8 version that GAS uses is sufficiently new (by at least two years) to support it; but the overall GAS experience depends on more than V8: the editor is parsing the entered source in order to provide help or highlighting or error checking or whatnot. It looks like the GAS team is aware that certain features aren't supported yet by the components responsible for that, and is actively working to remedy that. (I have no idea what the timeline is.)

ContentLicense: CC BY-SA 4.0

Body:
When you crate a new Google Apps Script, it seems to support the v8 runtime by default. The documentation states:

Apps Script supports two JavaScript runtimes: the modern V8 runtime and an older one powered by Mozilla's Rhino JavaScript interpreter.

The V8 runtime supports modern ECMAScript syntax and features.

The V8 runtime documentation states:

You can use modern ECMAScript syntax in scripts that are powered by the V8 runtime. This syntax includes let, const, and many other popular features.

In both cases, they are very vague as to which ECMAScript version is supported, simply stating "modern ECMAScript syntax". This is problematic because there are 7 versions that were released between 2015 and 2021. Thus "modern" could refer to any one of these versions.

For example, I could easily assume that "modern" refers to the latest, 12th edition (2022) of ECMAScript, and end up writing code like this:

let a = 1_000;

However, attempting to use that syntax leads to the error:

Syntax error: ParseError: Unexpected token ILLEGAL line: ...

Rather than manually go through each of the remaining 6 versions until I find the latest one supported, it would be great to find documentation that explicitly states which ECMAScript version is supported.

Note: The previous related question (Which Edition of ECMA-262 Does Google Apps Script Support?) is not helpful since those answers also refer to "modern ECMAScript" rather than a definitive, specific version.

Which version of ECMAScript is supported by the V8 runtime?


问:
How to save ChainMap objects?
I have a list of ChainMap objects in python that I'm using for analysis. I need to save them to disk somehow for later use. Is there any possibility to do this?

答:
You can use the pickle lib. Here is a toy example that saves cm.pickle as a binary file and reads it again as the unpickled variable.

```<code>from collections import ChainMap
import pickle

nums = {"one": 1, "two": 2}
lets = {"a": "A", "b": "B"}

cm = ChainMap(nums, lets)

with open('cm.pickle', 'wb') as f:
    pickle.dump(cm, f)

with open('cm.pickle', 'rb') as f:
    unpickled = pickle.load(f)

print(unpickled)
ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})
</code>```

Title: How to save ChainMap objects?

Body:
You can use the pickle lib. Here is a toy example that saves cm.pickle as a binary file and reads it again as the unpickled variable.

from collections import ChainMap
import pickle

nums = {"one": 1, "two": 2}
lets = {"a": "A", "b": "B"}

cm = ChainMap(nums, lets)

with open('cm.pickle', 'wb') as f:
    pickle.dump(cm, f)

with open('cm.pickle', 'rb') as f:
    unpickled = pickle.load(f)

print(unpickled)
ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})


问:
How to test if an instance of a django model was created?
I am testing an api for a game and have some issues with a model.

This is my model:

models.py

```<code>class Gamesession(models.Model):
    gamemode = models.ForeignKey(Gamemode, on_delete=models.CASCADE, null=True)
    user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    gametype = models.ForeignKey(Gametype, on_delete=models.CASCADE)
    created = models.DateTimeField(editable=False)

    objects = models.Manager()
</code>```

This is the test suite:

test_models.py

```<code>    def setUp(self):
        self.user = CustomUser.objects.create(id=1, username="carina")
        self.gametype = Gametype.objects.create(id=1, name="NewGame", rounds=5, round_duration=60, enabled=True)
        self.gamesession_user = self.user
        self.gamesession_gametype = self.gametype
        self.gamesession_created = datetime.utcnow().replace(tzinfo=pytz.UTC)
        self.gamesession = Gamesession.objects.create(id=1,
                                                      user=self.gamesession_user,
                                                      gametype=self.gamesession_gametype,
                                                      created=self.gamesession_created)

    def test_create_gamesession(self):
        gamesession = Gamesession.objects.create(gametype=self.gametype)
        assert gamesession.gametype == self.gamesession_gametype

</code>```

Running my tests keeps retrieving the error: GamesessionTests::test_create_gamesession - django.db.utils.IntegrityError: null value in column "created" of relation "frontend_games

How can I solve this? Is there a better way to test if an instance of the model is created?

答:
This happens because you defined created as a field that is not null=True and without any default=…, so that means that it does not assign a proper value to it. You thus can construct the object with:

```<code>def test_create_gamesession(self):
    gamesession = Gamesession.objects.create(
        gametype=self.gametype,
        <strong>gamesession_created=self.gamesession_created</strong>
    )
    assert gamesession.gametype == self.gamesession_gametype</code>```

You probably do not want to specify a value anyway, you can make use of auto_now_add=True [Django-doc] to specify that Django should fill in the timestamp when creating the object:

```<code>class Gamesession(models.Model):
    # …
    created = models.DateTimeField(<strong>auto_now_add=True</strong>)</code>```

this will also make the field non-editable.

Body:
I am testing an api for a game and have some issues with a model.

This is my model:

models.py

class Gamesession(models.Model):
    gamemode = models.ForeignKey(Gamemode, on_delete=models.CASCADE, null=True)
    user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    gametype = models.ForeignKey(Gametype, on_delete=models.CASCADE)
    created = models.DateTimeField(editable=False)

    objects = models.Manager()

This is the test suite:

test_models.py

    def setUp(self):
        self.user = CustomUser.objects.create(id=1, username="carina")
        self.gametype = Gametype.objects.create(id=1, name="NewGame", rounds=5, round_duration=60, enabled=True)
        self.gamesession_user = self.user
        self.gamesession_gametype = self.gametype
        self.gamesession_created = datetime.utcnow().replace(tzinfo=pytz.UTC)
        self.gamesession = Gamesession.objects.create(id=1,
                                                      user=self.gamesession_user,
                                                      gametype=self.gamesession_gametype,
                                                      created=self.gamesession_created)

    def test_create_gamesession(self):
        gamesession = Gamesession.objects.create(gametype=self.gametype)
        assert gamesession.gametype == self.gamesession_gametype

Running my tests keeps retrieving the error: GamesessionTests::test_create_gamesession - django.db.utils.IntegrityError: null value in column "created" of relation "frontend_games

How can I solve this? Is there a better way to test if an instance of the model is created?

Body:
This happens because you defined created as a field that is not null=True and without any default=…, so that means that it does not assign a proper value to it. You thus can construct the object with:

def test_create_gamesession(self):
    gamesession = Gamesession.objects.create(
        gametype=self.gametype,
        gamesession_created=self.gamesession_created
    )
    assert gamesession.gametype == self.gamesession_gametype

You probably do not want to specify a value anyway, you can make use of auto_now_add=True [Django-doc] to specify that Django should fill in the timestamp when creating the object:

class Gamesession(models.Model):
    # …
    created = models.DateTimeField(auto_now_add=True)

this will also make the field non-editable.


问:
Cannot upload image by PHP CURL to Cloudflare
When I run the curl command below, I receive success response and the image can upload as normal:

```<code>curl -X POST -F file=@/myFolder/pic.png -H "Authorization: Bearer {tokenX}" https://api.cloudflare.com/client/v4/accounts/{accountX}/images/v1
</code>```

But when I use PHP to exec curl by the code below:

```<code>// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/accounts/{accountX}/images/v1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'file' => '@' .realpath('/myFolder/pic.png'));

$headers = array();
$headers[] = 'Authorization: Bearer {tokenX}';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

</code>```

Cloudflare return an error: ERROR 9422: Decode error: image failed to be decoded: Uploaded image must have image/jpeg or image/png content type

I run curl command and PHP code on the same local server.

What did I do wrong?

答: echo json_decode(shell_exec('curl -X POST -F file=@./Rectangle36.png -H "Authorization: Bearer {{token}}" https://api.cloudflare.com/client/v4/accounts/{{account}}/images/v1'))->result->variants[0];</p>

Body:
When I run the curl command below, I receive success response and the image can upload as normal:

curl -X POST -F file=@/myFolder/pic.png -H "Authorization: Bearer {tokenX}" https://api.cloudflare.com/client/v4/accounts/{accountX}/images/v1

But when I use PHP to exec curl by the code below:

// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/accounts/{accountX}/images/v1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'file' => '@' .realpath('/myFolder/pic.png'));

$headers = array();
$headers[] = 'Authorization: Bearer {tokenX}';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

Cloudflare return an error: ERROR 9422: Decode error: image failed to be decoded: Uploaded image must have image/jpeg or image/png content type

I run curl command and PHP code on the same local server.

What did I do wrong?


问:
typing in two inputs using same keypad
i have an HTML and javasscript Keypad to typing Numbers into input using keypad im trying to add more inputs this keypad working good with only one input

How i make my code javascript work with second input too when i focused on it the keypad should be able to typing in second input using same keypad?

        function resetNumber()
      {
          document.getElementById("field").value = '';
      }

      function setNumber(number) {
        document.getElementById("field").value = document.getElementById("field").value === number ?  '' : document.getElementById("field").value += number;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
    <html>
<body>
    <button onclick="resetNumber()">Reset</button>
   <button onclick="setNumber(0)">0</button>
    <button onclick="setNumber(1)">1</button>
    <button onclick="setNumber(2)">2</button>
    <button onclick="setNumber(3)">3</button>
    <button onclick="setNumber(4)">4</button>
    <button onclick="setNumber(5)">5</button>
    <button onclick="setNumber(6)">6</button>
    <button onclick="setNumber(7)">7</button>
    <button onclick="setNumber(8)">8</button>
    <button onclick="setNumber(9)">9</button>
    <br />
        <input type="text" id="field" />
        <input type="text" id="second" />
</body>
</html></code>```

答:
I would suggest storing the active input in a variable when one of them is focused:</p>
```<code>let activeInput;

document.querySelector("#field").addEventListener("focus", (event) => {
  activeInput = event.target;
});

document.querySelector("#second").addEventListener("focus", (event) => {
  activeInput = event.target;
});

function resetNumber() {
  if (!activeInput) {
    console.log("select an input!");
    return;
  }
  activeInput.value = "";
}
function setNumber(number) {
  if (!activeInput) {
    console.log("select an input!");
    return;
  }
  activeInput.value = activeInput.value === number ? "" : (activeInput.value += number);
}

</code>```

Title: typing in two inputs using same keypad

Body:
i have an HTML and javasscript Keypad to typing Numbers into input using keypad im trying to add more inputs this keypad working good with only one input

How i make my code javascript work with second input too when i focused on it the keypad should be able to typing in second input using same keypad?

        function resetNumber()
      {
          document.getElementById("field").value = '';
      }

      function setNumber(number) {
        document.getElementById("field").value = document.getElementById("field").value === number ?  '' : document.getElementById("field").value += number;
      }

    <button onclick="resetNumber()">Reset</button>
   <button onclick="setNumber(0)">0</button>
    <button onclick="setNumber(1)">1</button>
    <button onclick="setNumber(2)">2</button>
    <button onclick="setNumber(3)">3</button>
    <button onclick="setNumber(4)">4</button>
    <button onclick="setNumber(5)">5</button>
    <button onclick="setNumber(6)">6</button>
    <button onclick="setNumber(7)">7</button>
    <button onclick="setNumber(8)">8</button>
    <button onclick="setNumber(9)">9</button>

        <input type="text" id="field" />
        <input type="text" id="second" />

Body:
I would suggest storing the active input in a variable when one of them is focused:

let activeInput;

document.querySelector("#field").addEventListener("focus", (event) => {
  activeInput = event.target;
});

document.querySelector("#second").addEventListener("focus", (event) => {
  activeInput = event.target;
});

function resetNumber() {
  if (!activeInput) {
    console.log("select an input!");
    return;
  }
  activeInput.value = "";
}
function setNumber(number) {
  if (!activeInput) {
    console.log("select an input!");
    return;
  }
  activeInput.value = activeInput.value === number ? "" : (activeInput.value += number);
}


问:
play as many sounds as loop count in python
I want the alarm.play() function to repeat for the number of loops and ring 10 times as in the example, but it just keeps ringing once every time I try or change it. How can I fix this? And does it make more sense to use for instead of while ?</p>
```<code>import time
import vlc

alarm = vlc.MediaPlayer("path")
m=0

while m<=10:
   alarm.play()
   time.sleep(1)
   m +=1

</code>```

答:
just stop the alarm at the end of loop and befor stop it create loop for stop executing while the sound is playing

```<code>import time
import vlc

alarm = vlc.MediaPlayer("path")
m = 0

while m <= 10:
    alarm.play()
    time.sleep(1)
    m += 1
    while alarm.is_playing():
        pass
    alarm.stop()
</code>```

Body:
I want the alarm.play() function to repeat for the number of loops and ring 10 times as in the example, but it just keeps ringing once every time I try or change it. How can I fix this? And does it make more sense to use for instead of while ?

import time
import vlc

alarm = vlc.MediaPlayer("path")
m=0

while m<=10:
   alarm.play()
   time.sleep(1)
   m +=1

Body:
just stop the alarm at the end of loop and befor stop it create loop for stop executing while the sound is playing

import time
import vlc

alarm = vlc.MediaPlayer("path")
m = 0

while m <= 10:
    alarm.play()
    time.sleep(1)
    m += 1
    while alarm.is_playing():
        pass
    alarm.stop()


问:
Is it better to send AJAX calls to a PHP script? Or use PHP in the page?
I'm wondering if I should let one php script do all of the sqli interactions and access the information with AJAX calls, or if I should handle those interactions as needed on the same page. Are there any security issues with either. What is best practice?</p>

答:
In addition to the excellent answer from @bumperbox.....

With the Ajax model where transitions are via Javascript changing the content on the page (commonly referred to as a Single Page Application or SPA) rather than a refresh of the base HTML, there is a significant risk of memory leaks. Diagnosing behaviour remotely or even just collecting analytics is a PITA.

Conversely it's rare to see a web page that doesn't contain Javascript and CSS - loading and processing these is a major performance bottleneck. If they are only loaded once (i.e. in a SPA) then that bottleneck is eliminated on subsequent pseudo-navigation events.

Just to confuse things even more - pjax combines the benefits of both approaches while eliminating some of the disadvantages.


问:
Bitbucket pipeline zipped files without directories
This is my script:

```<code>image: python:3.5.7

pipelines:
  default:
    - step:
        script:
          - apt-get update
          - apt-get -qq install zip curl
          - mkdir $BITBUCKET_REPO_SLUG

          - export VERSION_LABEL=$(date +%Y-%m-%d_%H:%M:%S)
          - export ZIP_FILE=update_$BITBUCKET_REPO_SLUG_$VERSION_LABEL.zip
          - export FILES=$(git diff-tree --no-commit-id --name-only -r HEAD^^..HEAD)

          - echo "Repo name is $BITBUCKET_REPO_SLUG & version is $VERSION_LABEL"
          - echo $FILES

          - cp -R $FILES $BITBUCKET_REPO_SLUG/

          - rm -f $BITBUCKET_REPO_SLUG/bitbucket-pipelines.yml
          - rm -f $BITBUCKET_REPO_SLUG/.gitignore

          - zip -r $ZIP_FILE $BITBUCKET_REPO_SLUG/
</code>```

Why all files in zip are in root and not in directories as I see then when I echo them?
What is the problem?

答:
I fixed my problem with copy command to this:</p>
```<code>cp -R --parents $FILES $BITBUCKET_REPO_SLUG/
</code>```

Body:
This is my script:

image: python:3.5.7

pipelines:
  default:
    - step:
        script:
          - apt-get update
          - apt-get -qq install zip curl
          - mkdir $BITBUCKET_REPO_SLUG

          - export VERSION_LABEL=$(date +%Y-%m-%d_%H:%M:%S)
          - export ZIP_FILE=update_$BITBUCKET_REPO_SLUG_$VERSION_LABEL.zip
          - export FILES=$(git diff-tree --no-commit-id --name-only -r HEAD^^..HEAD)

          - echo "Repo name is $BITBUCKET_REPO_SLUG & version is $VERSION_LABEL"
          - echo $FILES

          - cp -R $FILES $BITBUCKET_REPO_SLUG/

          - rm -f $BITBUCKET_REPO_SLUG/bitbucket-pipelines.yml
          - rm -f $BITBUCKET_REPO_SLUG/.gitignore

          - zip -r $ZIP_FILE $BITBUCKET_REPO_SLUG/

Why all files in zip are in root and not in directories as I see then when I echo them?
What is the problem?

Body:
I fixed my problem with copy command to this:

cp -R --parents $FILES $BITBUCKET_REPO_SLUG/


问:
Change the Cursor explictly without MouseRegion in Flutter
Is it possible to change the appearance of the cursor in a windows and web app without doing so with a MouseRegion? I currently have a custom widget which uses a CustomPainter to paint multiple shapes on the canvas and with a MouseRegion I'm listening to the mouse events (enter/exit) to determine which shapes is the mouse hovering on. My problem is if I use a Mouse Region to wrap the CustomPainter, it will change the cursor even if the user is not on a shape on the canvas but rather is hovering in the space between the shapes.

Is there a way I can explicitly tell flutter to change the cursor to something when I need it, something along the line of, for example Mouse.of(context) = SystemMouseCursor.text?

答:
You could try something like this where you just wrap your entire view in a MouseRegion and then change the cursor with a setState:

```<code>import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; // <----

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  SystemMouseCursor cursor = SystemMouseCursors.zoomIn; // <----

  @override
  Widget build(BuildContext context) {
    return MouseRegion( // <----
        cursor: cursor, // <----
        child: Scaffold(
          body: Center(
            child: TextButton(onPressed: () {
              cursor = SystemMouseCursors.grab; // <----
              setState(() {});                  // <----
            }, child: const Text("Change Cursor")),
          ),
        ),
      );
  }
}
</code>```

Hope it helps

Body:
You could try something like this where you just wrap your entire view in a MouseRegion and then change the cursor with a setState:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; // <----

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  SystemMouseCursor cursor = SystemMouseCursors.zoomIn; // <----

  @override
  Widget build(BuildContext context) {
    return MouseRegion( // <----
        cursor: cursor, // <----
        child: Scaffold(
          body: Center(
            child: TextButton(onPressed: () {
              cursor = SystemMouseCursors.grab; // <----
              setState(() {});                  // <----
            }, child: const Text("Change Cursor")),
          ),
        ),
      );
  }
}

Hope it helps


问:
Firebase sendPasswordResetEmail never completes
I'm trying to send a password reset email with firebase but it doesn't work. It doesn't throw any exceptions either. It just never completes, and I see no errors in the console. I tried debugging it and I saw that the parameter action code is null, is it supposed to be? All guides covering this don't add any action codesettings. I've tried signing out the user first but that doesn't seem to work. What to do?

This await firebaseAuth.sendPasswordResetEmail(email: currentEmail); is nested in a try-catch block that's all.

Console output:

```<code>W/System  (  757): Ignoring header X-Firebase-Locale because its value was null.
I/System.out(  757): isEmailSend:POST
I/System.out(  757): port:443
D/GraphicBuffer(  757): register, handle(0x8240d540) (w:720 h:1504 s:720 f:0x1 u:f02)
I/System.out(  757): Check isMmsSendPdu
I/System.out(  757): [OkHttp] sendRequest<<
</code>```

This is all I see. The future just never completes.

答:
Please check if your emulator is connected to the internet. Sometimes the wifi is on but does not connected to the internet.

and also make sure you email/password sign-in method on firebase is enabled

and if that doesn't work then add this line: android:usesCleartextTraffic="true" to your android > app > src > main > AndroidMaifest.xml

Body:
I'm trying to send a password reset email with firebase but it doesn't work. It doesn't throw any exceptions either. It just never completes, and I see no errors in the console. I tried debugging it and I saw that the parameter action code is null, is it supposed to be? All guides covering this don't add any action codesettings. I've tried signing out the user first but that doesn't seem to work. What to do?

This await firebaseAuth.sendPasswordResetEmail(email: currentEmail); is nested in a try-catch block that's all.

Console output:

W/System  (  757): Ignoring header X-Firebase-Locale because its value was null.
I/System.out(  757): isEmailSend:POST
I/System.out(  757): port:443
D/GraphicBuffer(  757): register, handle(0x8240d540) (w:720 h:1504 s:720 f:0x1 u:f02)
I/System.out(  757): Check isMmsSendPdu
I/System.out(  757): [OkHttp] sendRequest<<

This is all I see. The future just never completes.


问:
The Odin Project - Fundamentals 4 Exercises - sumAll
I am stuck in the sumAll exercise from the Fundamentals 4 portion of the Odin Project. I managed to pass the test in which I need the result to be ‘ERROR’. However, I cannot figure out the correct code to pass the other tests. Where did I go wrong?

This is the exercise:

```<code>const sumAll = require(’./sumAll’)

describe(‘sumAll’, function() {
it(‘sums numbers within the range’, function() {
expect(sumAll(1, 4)).toEqual(10);
});
it(‘works with large numbers’, function() {
expect(sumAll(1, 4000)).toEqual(8002000);
});
it(‘works with larger number first’, function() {
expect(sumAll(123, 1)).toEqual(7626);
});
it(‘returns ERROR with negative numbers’, function() {
expect(sumAll(-10, 4)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, “90”)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, [90, 1])).toEqual(‘ERROR’);
});
});
</code>```

My code:

```<code>const sumAll = function(a, b) {
const arr = [];
if (a < b) {
while (a <= b) {
arr.push(a++);
}
} else if (b < a) {
while (b <= a) {
arr.push(b++);
}
} else {
arr.push(a);
}

if (a < 0 || b < 0) {
return “ERROR”;
} else if (typeof a !== NaN || typeof b !== NaN) {
return “ERROR”;
}
return arr.reduce((a, b) => a + b);
}

module.exports = sumAll
</code>```

答:
That's how i did it. Quite similar but i avoided using for loops.

```<code>const sumAll = function(n,m) {
if (n<0 || m<0 || typeof(m) !== 'number' || typeof(n) !== 'number'){
return 'ERROR'
}else {
if(n<m){
n1 = n
n2 = m
}else{
    n1 = m
    n2 = n
}
return (n1+n2)*(n2/2)}
};
</code>```

I first checked whether the input is valid, then decided the values of the two variables depending on which is bigger and finally calculated the sum.

Body:
I am stuck in the sumAll exercise from the Fundamentals 4 portion of the Odin Project. I managed to pass the test in which I need the result to be ‘ERROR’. However, I cannot figure out the correct code to pass the other tests. Where did I go wrong?

This is the exercise:

const sumAll = require(’./sumAll’)

describe(‘sumAll’, function() {
it(‘sums numbers within the range’, function() {
expect(sumAll(1, 4)).toEqual(10);
});
it(‘works with large numbers’, function() {
expect(sumAll(1, 4000)).toEqual(8002000);
});
it(‘works with larger number first’, function() {
expect(sumAll(123, 1)).toEqual(7626);
});
it(‘returns ERROR with negative numbers’, function() {
expect(sumAll(-10, 4)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, “90”)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, [90, 1])).toEqual(‘ERROR’);
});
});

My code:

const sumAll = function(a, b) {
const arr = [];
if (a < b) {
while (a <= b) {
arr.push(a++);
}
} else if (b < a) {
while (b <= a) {
arr.push(b++);
}
} else {
arr.push(a);
}

if (a < 0 || b < 0) {
return “ERROR”;
} else if (typeof a !== NaN || typeof b !== NaN) {
return “ERROR”;
}
return arr.reduce((a, b) => a + b);
}

module.exports = sumAll

Body:
That's how i did it. Quite similar but i avoided using for loops.

const sumAll = function(n,m) {
if (n<0 || m<0 || typeof(m) !== 'number' || typeof(n) !== 'number'){
return 'ERROR'
}else {
if(n<m){
n1 = n
n2 = m
}else{
    n1 = m
    n2 = n
}
return (n1+n2)*(n2/2)}
};

I first checked whether the input is valid, then decided the values of the two variables depending on which is bigger and finally calculated the sum.


问:
Check for boolean and set variable value or default without using ELSE in Laravel 8 controller
I need to calculate points based on boolean selections and I'd like to reduce the amount of code by eliminating the ELSE part of my statements.

Is there anyway to compress this statement down?

```<code>...
if ($this->track) {
   $trackPTS = 20;
} else {
   $trackPTS = 0;
}
...
</code>```

答:
something like this:

$trackPTS = $this->track ? 20 : 0;

Body:
I need to calculate points based on boolean selections and I'd like to reduce the amount of code by eliminating the ELSE part of my statements.

Is there anyway to compress this statement down?

...
if ($this->track) {
   $trackPTS = 20;
} else {
   $trackPTS = 0;
}
...


问:
Referential integrity errors when building Blazor in Azure Web App
We are working on our first Blazor app to be hosted as an Azure web app.  It builds and runs perfectly on the local machine.  If we build locally and publish from the local machine to the web app on Azure, that works fine as well.  However, when we use the deployment system in Azure to deploy from a Bitbucket repository, we get referential integrity errors after the build is done.

I've read about issues with referential integrity errors related to building locally and pushing the compiled objects up to a repository, but that is not what we are doing.  The repository holds only the source code.  I've looked at the deployment logs and it appears to be building on the remote server itself and then deploying into the wwwroot folder on that server, so there should not be an issue with the line endings getting changed.

Can anyone give us some advice about this?  The development is being done in Visual Studio 2022 if that makes a difference.

This is the message we see in the console (site name removed):

Failed to find a valid digest in the 'integrity' attribute for resource 'https://***.azurewebsites.net/_framework/icudt_EFIGS.dat' with computed SHA-256 integrity '47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='. The resource has been blocked.

答:
This is caused by the checksum validation on the files. I had the same issue hosting in github pages. The cause is files that had crlf being converted to cr. The checksum changes. Solution

prevent the conversion. People suggested various ways, I could not get it to work (gitattributes to force binary file type for example)

turn off the chekcsumming. THis is what I did

add this change

```<code>    // edit to prevent integrity checks messed up by github pages
    .map(asset => new Request(asset.url, {/* integrity: asset.hash, */cache: 'no-cache' }));
</code>```

to service-worker.published.js.

In the back of my mind I think there was another change but cant find it. If this doesnt 100% fix then I will look again

Body:
This is caused by the checksum validation on the files. I had the same issue hosting in github pages. The cause is files that had crlf being converted to cr. The checksum changes. Solution

prevent the conversion. People suggested various ways, I could not get it to work (gitattributes to force binary file type for example)

turn off the chekcsumming. THis is what I did

add this change

    // edit to prevent integrity checks messed up by github pages
    .map(asset => new Request(asset.url, {/* integrity: asset.hash, */cache: 'no-cache' }));

to service-worker.published.js.

In the back of my mind I think there was another change but cant find it. If this doesnt 100% fix then I will look again


问:
sed Extract unique characters within each line
I want to get unique chars within each line using regular expressions in a Shell Script (sh).
In other words, I want to remove any further occurrence of a char within each line.

I'm trying to answer this question:
"What characters do appears in each line?"

For example, I'm trying to do something like this:

echo '1.Hi
2.This is
3.a huge file
4.with repeated chars
5.per
6.line' | sed 's/MYSTERIOUS_REGEX/MYSTERIOUS_REPLACE/g'
```
<p>And the expected output is:</p>
```1.Hi
2.This
3.a hugefil
4.with repadcs
5.per
6.line
```
<p>This is the explanation:</p>
<ul>
<li>Line 1: <strong>there isn't any repeated chars</strong></li>
<li>Line 2: '<code>i</code>', '<code>s</code>' <strong>repeated</strong></li>
<li>Line 3: '<code> </code>', '<code>e</code>' <strong>repeated</strong></li>
<li>Line 4: '<code>e</code>', '<code>a</code>', '<code>t</code>', '<code>e</code>', '<code>d</code>', '<code> </code>', '<code>c</code>', '<code>h</code>', '<code>a</code>', '<code>r</code>' <strong>repeated</strong></li>
<li>Line 5: <strong>there isn't any repeated chars</strong></li>
<li>Line 6: <strong>there isn't any repeated chars</strong></li>
</ul>
<p><strong>OBS</strong>:</p>
<ul>
<li>If you achieve this using <code>sh</code> and <code>sed</code> you obtain 5⭐s</li>
<li>If you achieve this using  other tools (<code>bash</code>, <code>awk</code> etc), you obtain 3⭐s</li>
</ul>
<hr />
<p>̶D̶i̶s̶t̶r̶a̶c̶t̶o̶r̶ ̶ <strong>HINT</strong>:</p>
<p>The following regex matches lines which don't have repeated chars: <strong><code>^(?:([A-Za-z])(?!.*\1))*$</code></strong></p>
<pre class="lang-sh prettyprint-override"><code>echo "bleh" | grep -P '^(?:([A-Za-z])(?!.*\1))*$'
</code>```

ble

echo "fooo" | grep -P '^(?:([A-Za-z])(?!.*\1))*$'
```

(empty)

答:
With your shown samples, please try following awk code. Written and tested in GNU awk.

```<code>awk -v FS="" '
{
  delete seen
  for(i=1;i<=NF;i++){
    if(!seen[$i]++){
      val=(i>1?val:"") $i
    }
  }
  print val
}
'  Input_file
</code>```

Explanation: Adding detailed explanation for above.

```<code>awk -v FS="" '              ##Starting awk program from here and setting field separator as NULL here.
{
  delete seen               ##Deleting seen array here.
  for(i=1;i<=NF;i++){       ##Traversing through all field of current line here.
    if(!seen[$i]++){        ##checking condition if current field value is NOT present in seen.
      val=(i>1?val:"")$i ##Then add its value in val variable and keep concatenating these kind of values, if they pass above condition.
    }
  }
  print val                 ##Printing val here.
}
'  Input_file               ##Mentioning Input_file name here.
</code>```

Body:
I want to get unique chars within each line using regular expressions in a Shell Script (sh).
In other words, I want to remove any further occurrence of a char within each line.

I'm trying to answer this question:
"What characters do appears in each line?"

For example, I'm trying to do something like this:

echo '1.Hi
2.This is
3.a huge file
4.with repeated chars
5.per
6.line' | sed 's/MYSTERIOUS_REGEX/MYSTERIOUS_REPLACE/g'

And the expected output is:

1.Hi
2.This
3.a hugefil
4.with repadcs
5.per
6.line

This is the explanation:

Line 1: there isn't any repeated chars

Line 2: 'i', 's' repeated

Line 3: ' ', 'e' repeated

Line 4: 'e', 'a', 't', 'e', 'd', ' ', 'c', 'h', 'a', 'r' repeated

Line 5: there isn't any repeated chars

Line 6: there isn't any repeated chars

OBS:

If you achieve this using sh and sed you obtain 5⭐s

If you achieve this using  other tools (bash, awk etc), you obtain 3⭐s

̶D̶i̶s̶t̶r̶a̶c̶t̶o̶r̶ ̶ HINT:

The following regex matches lines which don't have repeated chars: ^(?:([A-Za-z])(?!.*\1))*$

echo "bleh" | grep -P '^(?:([A-Za-z])(?!.*\1))*$'

ble

echo "fooo" | grep -P '^(?:([A-Za-z])(?!.*\1))*$'

(empty)

Body:
With your shown samples, please try following awk code. Written and tested in GNU awk.

awk -v FS="" '
{
  delete seen
  for(i=1;i<=NF;i++){
    if(!seen[$i]++){
      val=(i>1?val:"") $i
    }
  }
  print val
}
'  Input_file

Explanation: Adding detailed explanation for above.

awk -v FS="" '              ##Starting awk program from here and setting field separator as NULL here.
{
  delete seen               ##Deleting seen array here.
  for(i=1;i<=NF;i++){       ##Traversing through all field of current line here.
    if(!seen[$i]++){        ##checking condition if current field value is NOT present in seen.
      val=(i>1?val:"")$i ##Then add its value in val variable and keep concatenating these kind of values, if they pass above condition.
    }
  }
  print val                 ##Printing val here.
}
'  Input_file               ##Mentioning Input_file name here.


问:
What are the arguments against the use of the "<?="?

Possible Duplicate:

  Are PHP short tags acceptable to use?

The <?= is one of the very few elegant things about PHP, IMO. Yet, there are people that deliberately avoid it (in favor of the much longer <?php echo). Why would they do that?

答:
Many servers has got that <? "shortform" turned off.

The only sure way to have your php executed is using the <?php form. so you have to use <?php echo in code you're going to distribute or reuse.

ContentLicense: CC BY-SA 3.0


问:
plt doesn't change xticks, yticks, xlabel and ylabel to bold
I am trying to convert xticks, yticks, xlabel and ylabel to bold, but nothing work. I attached a screenshot of the output graph.

# visualize the loss as the network trained
fig = plt.figure(figsize=(5,5))
plt.plot(range(1,len(All_end_eopch_training_loss)+1),All_end_eopch_training_loss, label='Training Loss')
plt.plot(range(1,len(All_end_eopch_validation_loss)+1),All_end_eopch_validation_loss,label='Validation Loss')

# find position of lowest validation loss
minposs = All_end_eopch_validation_loss.index(min(All_end_eopch_validation_loss))+1
plt.axvline(minposs, linestyle='--', color='r',label='Early Stopping Checkpoint')

mod_size = 20

plt.xlabel('epochs',fontsize=mod_size, fontweight='bold')
plt.ylabel('loss', fontsize=mod_size, fontweight='bold')
plt.ylim(0,0.3) # consistent scale
plt.xlim(0, len(All_end_eopch_training_loss)+1) # consistent scale
plt.xticks(fontsize=mod_size)
plt.yticks(fontsize=mod_size)
plt.grid(True)
plt.legend(fontsize=10)
plt.tight_layout()

plt.show()

fig.savefig(f'LOSS_ACC_Files/{tensor_baord_variable}_loss_plot.pdf',format="pdf", dpi= 400, bbox_inches='tight')
```

答:
I think you used LaTeX for all text in a figure. Perhaps you have set matplotlib.rc('text', usetex=True) before.

You can change xticks, yticks, xlabel and ylabel to bold by doing something like:

```<code>plt.rc('xtick', weight = 'bold')
plt.rc('ytick', weight = 'bold')
plt.xlabel(r'\textbf{epochs}')
plt.ylabel(r'\textbf{loss}')
</code>```

Body:
I think you used LaTeX for all text in a figure. Perhaps you have set matplotlib.rc('text', usetex=True) before.

You can change xticks, yticks, xlabel and ylabel to bold by doing something like:

plt.rc('xtick', weight = 'bold')
plt.rc('ytick', weight = 'bold')
plt.xlabel(r'\textbf{epochs}')
plt.ylabel(r'\textbf{loss}')


问:
Flutter won't initialise a video from disk
I've downloaded a video to disk but it won't initialise using Video Player (https://pub.dev/packages/video_player).

```<code>final future = Downloader.shared
            .getVideoPathFor(
          url: url,
          themeName: themeName,
        )
            .then(
          (value) {
            dLog('file path: $value');
            final file = File(value);
            final videoController = VideoPlayerController.file(file);
            return videoController.initialize().then(
              (value) {
                dLog('video controller initialized');
                return videoController;
              },
            );
          },
        );
</code>```

It downloads the file fine and the file path becomes something like:
Application/9E6FD935-A424-4C1E-99CC-D5834448E45E/Library/Caches/videos/Clean water/clean_water_video.mp4

So I know the file exists and I can see it in Finder if I run this on Simulator.

If I use VideoController.contentUri() then it appears to work but it tells me I'm not allowed to use that on iOS and I can only use it on Android.

I know I can use VideoController.network() but I can't keep downloading the same video over and over across multiple screens like this.

What am I doing wrong?

Even when I do load the video like this (which I got from this video: https://youtu.be/uz4xRnE-UIw?t=596):

```<code>final filePath =
        "<path>/Caches/videos/Clean water/clean_water_video.mp4";
    final file = File(filePath);
    controller = VideoPlayerController.file(file)
      ..addListener(() {
        setState(() {});
      })
    ..setLooping(true)
    ..initialize().then((value) {
      controller.play();
    });
</code>```

the initialise never happens.

答: It turns out that it can't load a file if folders have spaces in the name.</p>

Body:
I've downloaded a video to disk but it won't initialise using Video Player (https://pub.dev/packages/video_player).

final future = Downloader.shared
            .getVideoPathFor(
          url: url,
          themeName: themeName,
        )
            .then(
          (value) {
            dLog('file path: $value');
            final file = File(value);
            final videoController = VideoPlayerController.file(file);
            return videoController.initialize().then(
              (value) {
                dLog('video controller initialized');
                return videoController;
              },
            );
          },
        );

It downloads the file fine and the file path becomes something like:
Application/9E6FD935-A424-4C1E-99CC-D5834448E45E/Library/Caches/videos/Clean water/clean_water_video.mp4

So I know the file exists and I can see it in Finder if I run this on Simulator.

If I use VideoController.contentUri() then it appears to work but it tells me I'm not allowed to use that on iOS and I can only use it on Android.

I know I can use VideoController.network() but I can't keep downloading the same video over and over across multiple screens like this.

What am I doing wrong?

Even when I do load the video like this (which I got from this video: https://youtu.be/uz4xRnE-UIw?t=596):

final filePath =
        "<path>/Caches/videos/Clean water/clean_water_video.mp4";
    final file = File(filePath);
    controller = VideoPlayerController.file(file)
      ..addListener(() {
        setState(() {});
      })
    ..setLooping(true)
    ..initialize().then((value) {
      controller.play();
    });

the initialise never happens.


问:
how to open the .ipynb file in readable format
I have got downloaded a file that got downloaded in a format .ipynb extension but its not in a readable format. Can anyone help me to figure out how to make it in a readable format? Attaching a screenshot of the file when I tried opening it in notepad.

how to open it in readable format

答:
One of the easiest ways to just view a notebook file that is also 100% secure in case what you are being sent is sensitive: nbpreview.

When you go there it asks you to choose a local file. The file isn't uploaded anywhere. It remains in your browser's local cache so it is useful for sensitive stuff that cannot be public.

Similarly, you can upload it to the notebook{sharing}space which is billed as "the fastest way to share your notebooks". It would provide you with a link to view the notebook you have and can be private if you limit sharing the link.

If the notebook can be posted to Github (repository or gist) or online, you can point nbviewer at it and have it rendered nicely. In fact, although it is technically 'static', nbviewer can render some interactive Plotly plots and widget controls that enable playing back animations comprised of frames. This rendering form is also very nice for sharing with non-programmers as the GitHub cruft is not surrounding the content.

You can use Jupyter running in your browser and backed by a free Jupyter community-run service to view the notebook file as an active notebook, on what is equivalent to a temporary remote machine.

Go to Try Jupyter and select either 'JupyterLab' or 'Jupyter Notebook' from the offerings presented. I'd suggest JupyterLab as the steps outline below are made easier as you have the file navigation pane on the left.

After your session spins up in your browser, if you chose JupyterLab, drag your file from your local machine into the file navigation pane on the left side. It will get a gray dashed line around it when you have dragged it to the right place. Drop it in and let it upload. Now double click on it to open it.

If you don't want to drag-and-drop or you chose Jupyter notebooks (classic notebook interface) make a text file and paste in the content you showed. (It's json format as that is the underlying .ipynb format presently.) Save that file with an .ipynb extension. You should then be able to open it the Jupyter Dashboard. (Note the following in the rest of this section was written before the 'Try Jupyter' offerings were switched to using the exerpimental JupyterLite and so your mileage may vary. If you drag-and-drop into JupyterLite, it actually is in your machine; however, it is in a virtual system in your browser that your local file system cannot access directly. To get what this section was specifically written for now, go here and click on the launch binder badge to trigger a session on a true remote machine served by MyBinder.) You used to click on the logo in the upper left to get to the dashboard but it will now take you to JupyterLab and you can double click to open your notebook file. If you really need the classic dashboard, change the end of the URL to change /lab to /tree.

Note because the environment backing your notebook hasn't been set up to handle everything, you'll be out of luck for now trying to run it. You'd have to add your pokemon.csv and install anything else besides pandas. There are ways to use the MyBinder system to handle that as well; however, probably best learned about later this stage.

The MyBinder session is temporary and unique to you. It will close after 10 minutes of inactivity and no longer be accessible. You can always open another session later and redo the steps. Or learn about other options eventually.

Related:

Nbpreview and a lot of the related tools mentioned here are also covered in Sharing R code in Jupyter notebooks.

(These following suggestions mostly assume the notebook is already online, usually at Github. You can still use a local notebook by uploading it to the session as I suggest above. They do though provide additional ways to learn about using MyBinder to serve active notebooks in your browser.)

How to save code file on GitHub and run on Jupyter notebook?

Run a Jupyter notebook directly online (without downloading it locally)


问:
How to convert RGBA bytes to PNG image?
How do I speed this up?
My image is composed of binary RGBA colours.

```<code>from PIL import Image
redOffset = 0
blueOffset = 2

byte = open("ALWAYSLOADED_384_00.PTX", "rb").read()
width = 256
height = 256
img = Image.new('RGBA', (width, height))
index = 0
for y in range(0, height):
    for x in range(0, width):
        img.putpixel((x,y), (byte[index + redOffset],byte[index + 1],byte[index + blueOffset], byte[index + 3]))
        index += 4

img.save("ALWAYSLOADED_384_00.PNG")
</code>```

答:
Instead of creating a new image, let PIL operate directly on your buffer.

```<code>data = open("ALWAYSLOADED_384_00.PTX", "rb").read()
img = Image.frombuffer("RGBA", (256, 256), data, "raw", "RGBA", 0, 1)
img.save("ALWAYSLOADED_384_00.PNG")
</code>```

Documentation: PIL.Image.frombuffer.

Title: How to convert RGBA bytes to PNG image?

Body:
How do I speed this up?
My image is composed of binary RGBA colours.

from PIL import Image
redOffset = 0
blueOffset = 2

byte = open("ALWAYSLOADED_384_00.PTX", "rb").read()
width = 256
height = 256
img = Image.new('RGBA', (width, height))
index = 0
for y in range(0, height):
    for x in range(0, width):
        img.putpixel((x,y), (byte[index + redOffset],byte[index + 1],byte[index + blueOffset], byte[index + 3]))
        index += 4

img.save("ALWAYSLOADED_384_00.PNG")

Body:
Instead of creating a new image, let PIL operate directly on your buffer.

data = open("ALWAYSLOADED_384_00.PTX", "rb").read()
img = Image.frombuffer("RGBA", (256, 256), data, "raw", "RGBA", 0, 1)
img.save("ALWAYSLOADED_384_00.PNG")

Documentation: PIL.Image.frombuffer.


问:
list files pattern select date
Hello I have a set of daily meteo data, using the expression :

```<code>f <- list.files(getwd(), include.dirs=TRUE, recursive=TRUE, pattern= "PREC")
</code>```

I select only the files of Precipitation

I wonder how to select only files for example  of January, the one for example named 20170103 (yyyymmdd) ,  so the one named yyyy01dd....

the files are named in this way: "PREC_20010120.grd".

答:
Resolved with:</p>
```<code>f <- list.files(getwd(), include.dirs=TRUE, recursive=TRUE, pattern='PREC_\\d{4}01.*')
</code>```

Title: list files pattern select date

Body:
Hello I have a set of daily meteo data, using the expression :

f <- list.files(getwd(), include.dirs=TRUE, recursive=TRUE, pattern= "PREC")

I select only the files of Precipitation

I wonder how to select only files for example  of January, the one for example named 20170103 (yyyymmdd) ,  so the one named yyyy01dd....

the files are named in this way: "PREC_20010120.grd".

Body:
Resolved with:

f <- list.files(getwd(), include.dirs=TRUE, recursive=TRUE, pattern='PREC_\\d{4}01.*')


问:
How do i convert Open weather map json format to pandas dataframe?
I want to convert a Open Weather Map Json format to pandas dataframe. I read some questions about this issue in stackoverflow like 1 and 2  but no one answer my question.
My Json format is like the below example:

```<code>{'coord': {'lon': 36.5707, 'lat': -113.7909}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'broken clouds', 'icon': '04n'}], 'base': 'stations', 'main': {'temp': 272.49, 'feels_like': 272.49, 'temp_min': 272.49, 'temp_max': 272.49, 'pressure': 1025, 'humidity': 89, 'sea_level': 1025, 'grnd_level': 817}, 'visibility': 10000, 'wind': {'speed': 0.94, 'deg': 305, 'gust': 1.68}, 'clouds': {'all': 55}, 'dt': 1644685756, 'sys': {'country': 'US', 'sunrise': 1644636899, 'sunset': 1644675906}, 'timezone': 12600, 'id': 14256, 'name': 'xxx', 'cod': 200}
</code>```

I know that i should use json_normalize function of pandas.
But i don't know how to use it.

I try this:

```<code>import pandas as pd
import json
import requests

url = "http://api.openweathermap.org/data/2.5/weather?lat=36.7&lon=-113.5707&APPID="

  response = requests.get(url)
data = response.text
dicts = json.loads(data)
jsont = json.dumps(dicts)
df = pd.read_json(jsont, lines=True)
js =[]
js.append(json.loads(jsont))
print(js)
x =pd.json_normalize(js)
x.to_csv('E:/testjson.csv')
</code>```

But i does not work.
I want to convert all keys of json to columns.

答:
You can use pandas.json_normalize to transform JSON data into a flat table.

```<code>>>> import pandas as pd
>>> data = {'coord': {'lon': 36.5707, 'lat': -113.7909}}
>>> df = pd.json_normalize(data)
>>> df.columns
Index(['coord.lon', 'coord.lat'], dtype='object')
</code>```

Body:
I want to convert a Open Weather Map Json format to pandas dataframe. I read some questions about this issue in stackoverflow like 1 and 2  but no one answer my question.
My Json format is like the below example:

{'coord': {'lon': 36.5707, 'lat': -113.7909}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'broken clouds', 'icon': '04n'}], 'base': 'stations', 'main': {'temp': 272.49, 'feels_like': 272.49, 'temp_min': 272.49, 'temp_max': 272.49, 'pressure': 1025, 'humidity': 89, 'sea_level': 1025, 'grnd_level': 817}, 'visibility': 10000, 'wind': {'speed': 0.94, 'deg': 305, 'gust': 1.68}, 'clouds': {'all': 55}, 'dt': 1644685756, 'sys': {'country': 'US', 'sunrise': 1644636899, 'sunset': 1644675906}, 'timezone': 12600, 'id': 14256, 'name': 'xxx', 'cod': 200}

I know that i should use json_normalize function of pandas.
But i don't know how to use it.

I try this:

import pandas as pd
import json
import requests

url = "http://api.openweathermap.org/data/2.5/weather?lat=36.7&lon=-113.5707&APPID="

  response = requests.get(url)
data = response.text
dicts = json.loads(data)
jsont = json.dumps(dicts)
df = pd.read_json(jsont, lines=True)
js =[]
js.append(json.loads(jsont))
print(js)
x =pd.json_normalize(js)
x.to_csv('E:/testjson.csv')

But i does not work.
I want to convert all keys of json to columns.

Body:
You can use pandas.json_normalize to transform JSON data into a flat table.

>>> import pandas as pd
>>> data = {'coord': {'lon': 36.5707, 'lat': -113.7909}}
>>> df = pd.json_normalize(data)
>>> df.columns
Index(['coord.lon', 'coord.lat'], dtype='object')


问:
Removing the .0 from a double
I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0

example: display 5.5 as 5.5 and 5.0 as 5

This is what I have so far: (answer is a double)

```<code>double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);
System.out.println(output);
</code>```

this work's fine up to about 1e18 then will error out because of the maximum size of a Long.
So how would I achieve this on bigger numbers like 5.43e86

答:
Look at
http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

you would want just DecimalFormat("0.0")

Title: Removing the .0 from a double

Body:
I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0

example: display 5.5 as 5.5 and 5.0 as 5

This is what I have so far: (answer is a double)

double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);
System.out.println(output);

this work's fine up to about 1e18 then will error out because of the maximum size of a Long.
So how would I achieve this on bigger numbers like 5.43e86


问:
Start CloudSQL Proxy on Python Dataflow / Apache Beam
I am currently working on a ETL Dataflow job (using the Apache Beam Python SDK) which queries data from CloudSQL (with psycopg2 and a custom ParDo) and writes it to BigQuery. My goal is to create a Dataflow template which I can start from a AppEngine using a Cron job.

I have a version which works locally using the DirectRunner. For that I use the CloudSQL (Postgres) proxy client so that I can connect to the database on 127.0.0.1 .

When using the DataflowRunner with custom commands to start the proxy within a setup.py script, the job won't execute.
It stucks with repeating this log-message:

Setting node annotation to enable volume controller attach/detach

A part of my setup.py looks the following:

```<code>CUSTOM_COMMANDS = [
['echo', 'Custom command worked!'],
['wget', 'https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64', '-O', 'cloud_sql_proxy'],
['echo', 'Proxy downloaded'],
['chmod', '+x', 'cloud_sql_proxy']]

class CustomCommands(setuptools.Command):
  """A setuptools Command class able to run arbitrary commands."""

  def initialize_options(self):
    pass

  def finalize_options(self):
    pass

  def RunCustomCommand(self, command_list):
    print('Running command: %s' % command_list)
    logging.info("Running custom commands")
    p = subprocess.Popen(
        command_list,
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    # Can use communicate(input='y\n'.encode()) if the command run requires
    # some confirmation.
    stdout_data, _ = p.communicate()
    print('Command output: %s' % stdout_data)
    if p.returncode != 0:
      raise RuntimeError(
          'Command %s failed: exit code: %s' % (command_list, p.returncode))

  def run(self):
    for command in CUSTOM_COMMANDS:
      self.RunCustomCommand(command)
    subprocess.Popen(['./cloud_sql_proxy', '-instances=bi-test-1:europe-west1:test-animal=tcp:5432'])
</code>```

I added the last line as separate subprocess.Popen() within run() after reading this issue on Github from sthomp  and this discussion on Stackoverflo. I also tried to play around with some parameters of subprocess.Popen.

Another mentioned solution from brodin was to allow access from every IP address and to connect via username and password. In my understanding he does not claim this as best practice.

Thank you in advance for you help.

!!! Workaround solution at bottom of this post !!!

Update - Logfiles

These are the logs on error level which occur during a job:

```<code>E  EXT4-fs (dm-0): couldn't mount as ext3 due to feature incompatibilities
E  Image garbage collection failed once. Stats initialization may not have completed yet: unable to find data for container /
E  Failed to check if disk space is available for the runtime: failed to get fs info for "runtime": unable to find data for container /
E  Failed to check if disk space is available on the root partition: failed to get fs info for "root": unable to find data for container /
E  [ContainerManager]: Fail to get rootfs information unable to find data for container /
E  Could not find capacity information for resource storage.kubernetes.io/scratch
E  debconf: delaying package configuration, since apt-utils is not installed
E    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
E                                   Dload  Upload   Total   Spent    Left  Speed
E
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  3698  100  3698    0     0  25674      0 --:--:-- --:--:-- --:--:-- 25860

#-- HERE IS WHEN setup.py FOR MY JOB IS EXECUTED ---

E  debconf: delaying package configuration, since apt-utils is not installed
E  insserv: warning: current start runlevel(s) (empty) of script `stackdriver-extractor' overrides LSB defaults (2 3 4 5).
E  insserv: warning: current stop runlevel(s) (0 1 2 3 4 5 6) of script `stackdriver-extractor' overrides LSB defaults (0 1 6).
E  option = Interval; value = 60.000000;
E  option = FQDNLookup; value = false;
E  Created new plugin context.
E  option = PIDFile; value = /var/run/stackdriver-agent.pid;
E  option = Interval; value = 60.000000;
E  option = FQDNLookup; value = false;
E  Created new plugin context.
</code>```

Here you can find are all logs after the start of my custom setup.py (log-level: any; all logs):

https://jpst.it/1gk2Z

Update logfiles 2

Job logs (I manually canceled the job after not stucking for a while):

```<code> 2018-06-08 (08:02:20) Autoscaling is enabled for job 2018-06-07_23_02_20-5917188751755240698. The number of workers will b...
 2018-06-08 (08:02:20) Autoscaling was automatically enabled for job 2018-06-07_23_02_20-5917188751755240698.
 2018-06-08 (08:02:24) Checking required Cloud APIs are enabled.
 2018-06-08 (08:02:24) Checking permissions granted to controller Service Account.
 2018-06-08 (08:02:25) Worker configuration: n1-standard-1 in europe-west1-b.
 2018-06-08 (08:02:25) Expanding CoGroupByKey operations into optimizable parts.
 2018-06-08 (08:02:25) Combiner lifting skipped for step Save new watermarks/Write/WriteImpl/GroupByKey: GroupByKey not fol...
 2018-06-08 (08:02:25) Combiner lifting skipped for step Group watermarks: GroupByKey not followed by a combiner.
 2018-06-08 (08:02:25) Expanding GroupByKey operations into optimizable parts.
 2018-06-08 (08:02:26) Lifting ValueCombiningMappingFns into MergeBucketsMappingFns
 2018-06-08 (08:02:26) Annotating graph with Autotuner information.
 2018-06-08 (08:02:26) Fusing adjacent ParDo, Read, Write, and Flatten operations
 2018-06-08 (08:02:26) Fusing consumer Get rows from CloudSQL tables into Begin pipeline with watermarks/Read
 2018-06-08 (08:02:26) Fusing consumer Group watermarks/Write into Group watermarks/Reify
 2018-06-08 (08:02:26) Fusing consumer Group watermarks/GroupByWindow into Group watermarks/Read
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/WriteBundles/WriteBundles into Save new watermar...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/GroupByKey/GroupByWindow into Save new watermark...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/GroupByKey/Reify into Save new watermarks/Write/...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/GroupByKey/Write into Save new watermarks/Write/...
 2018-06-08 (08:02:26) Fusing consumer Write to BQ into Get rows from CloudSQL tables
 2018-06-08 (08:02:26) Fusing consumer Group watermarks/Reify into Write to BQ
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/Map(<lambda at iobase.py:926>) into Convert dict...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/WindowInto(WindowIntoFn) into Save new watermark...
 2018-06-08 (08:02:26) Fusing consumer Convert dictionary list to single dictionary and json into Remove "watermark" label
 2018-06-08 (08:02:26) Fusing consumer Remove "watermark" label into Group watermarks/GroupByWindow
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/InitializeWrite into Save new watermarks/Write/W...
 2018-06-08 (08:02:26) Workflow config is missing a default resource spec.
 2018-06-08 (08:02:26) Adding StepResource setup and teardown to workflow graph.
 2018-06-08 (08:02:26) Adding workflow start and stop steps.
 2018-06-08 (08:02:26) Assigning stage ids.
 2018-06-08 (08:02:26) Executing wait step start25
 2018-06-08 (08:02:26) Executing operation Save new watermarks/Write/WriteImpl/DoOnce/Read+Save new watermarks/Write/WriteI...
 2018-06-08 (08:02:26) Executing operation Save new watermarks/Write/WriteImpl/GroupByKey/Create
 2018-06-08 (08:02:26) Starting worker pool setup.
 2018-06-08 (08:02:26) Executing operation Group watermarks/Create
 2018-06-08 (08:02:26) Starting 1 workers in europe-west1-b...
 2018-06-08 (08:02:27) Value "Group watermarks/Session" materialized.
 2018-06-08 (08:02:27) Value "Save new watermarks/Write/WriteImpl/GroupByKey/Session" materialized.
 2018-06-08 (08:02:27) Executing operation Begin pipeline with watermarks/Read+Get rows from CloudSQL tables+Write to BQ+Gr...
 2018-06-08 (08:02:36) Autoscaling: Raised the number of workers to 0 based on the rate of progress in the currently runnin...
 2018-06-08 (08:02:46) Autoscaling: Raised the number of workers to 1 based on the rate of progress in the currently runnin...
 2018-06-08 (08:03:05) Workers have started successfully.
 2018-06-08 (08:11:37) Cancel request is committed for workflow job: 2018-06-07_23_02_20-5917188751755240698.
 2018-06-08 (08:11:38) Cleaning up.
 2018-06-08 (08:11:38) Starting worker pool teardown.
 2018-06-08 (08:11:38) Stopping worker pool...
 2018-06-08 (08:12:30) Autoscaling: Reduced the number of workers to 0 based on the rate of progress in the currently runni...
</code>```

Stack Traces:

```<code>No errors have been received in this time period.
</code>```

Update: Workaround Solution can be found in my answer below

答:
The easy and right thing to do in 2022 is to use the cloud sql connector which will work with postgres, sqlserver, and mysql running on gcloud sql.

https://cloud.google.com/sql/docs/mysql/connect-connectors#python_1

https://pypi.org/project/cloud-sql-python-connector/

No need to white list IPs, manually load certificates, or leave your database wide open.

You use this format for the host: "project:region:instance" and connect as usual.

Body:
I am currently working on a ETL Dataflow job (using the Apache Beam Python SDK) which queries data from CloudSQL (with psycopg2 and a custom ParDo) and writes it to BigQuery. My goal is to create a Dataflow template which I can start from a AppEngine using a Cron job.

I have a version which works locally using the DirectRunner. For that I use the CloudSQL (Postgres) proxy client so that I can connect to the database on 127.0.0.1 .

When using the DataflowRunner with custom commands to start the proxy within a setup.py script, the job won't execute.
It stucks with repeating this log-message:

Setting node annotation to enable volume controller attach/detach

A part of my setup.py looks the following:

CUSTOM_COMMANDS = [
['echo', 'Custom command worked!'],
['wget', 'https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64', '-O', 'cloud_sql_proxy'],
['echo', 'Proxy downloaded'],
['chmod', '+x', 'cloud_sql_proxy']]

class CustomCommands(setuptools.Command):
  """A setuptools Command class able to run arbitrary commands."""

  def initialize_options(self):
    pass

  def finalize_options(self):
    pass

  def RunCustomCommand(self, command_list):
    print('Running command: %s' % command_list)
    logging.info("Running custom commands")
    p = subprocess.Popen(
        command_list,
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    # Can use communicate(input='y\n'.encode()) if the command run requires
    # some confirmation.
    stdout_data, _ = p.communicate()
    print('Command output: %s' % stdout_data)
    if p.returncode != 0:
      raise RuntimeError(
          'Command %s failed: exit code: %s' % (command_list, p.returncode))

  def run(self):
    for command in CUSTOM_COMMANDS:
      self.RunCustomCommand(command)
    subprocess.Popen(['./cloud_sql_proxy', '-instances=bi-test-1:europe-west1:test-animal=tcp:5432'])

I added the last line as separate subprocess.Popen() within run() after reading this issue on Github from sthomp  and this discussion on Stackoverflo. I also tried to play around with some parameters of subprocess.Popen.

Another mentioned solution from brodin was to allow access from every IP address and to connect via username and password. In my understanding he does not claim this as best practice.

Thank you in advance for you help.

!!! Workaround solution at bottom of this post !!!

Update - Logfiles

These are the logs on error level which occur during a job:

E  EXT4-fs (dm-0): couldn't mount as ext3 due to feature incompatibilities
E  Image garbage collection failed once. Stats initialization may not have completed yet: unable to find data for container /
E  Failed to check if disk space is available for the runtime: failed to get fs info for "runtime": unable to find data for container /
E  Failed to check if disk space is available on the root partition: failed to get fs info for "root": unable to find data for container /
E  [ContainerManager]: Fail to get rootfs information unable to find data for container /
E  Could not find capacity information for resource storage.kubernetes.io/scratch
E  debconf: delaying package configuration, since apt-utils is not installed
E    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
E                                   Dload  Upload   Total   Spent    Left  Speed
E
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  3698  100  3698    0     0  25674      0 --:--:-- --:--:-- --:--:-- 25860

#-- HERE IS WHEN setup.py FOR MY JOB IS EXECUTED ---

E  debconf: delaying package configuration, since apt-utils is not installed
E  insserv: warning: current start runlevel(s) (empty) of script `stackdriver-extractor' overrides LSB defaults (2 3 4 5).
E  insserv: warning: current stop runlevel(s) (0 1 2 3 4 5 6) of script `stackdriver-extractor' overrides LSB defaults (0 1 6).
E  option = Interval; value = 60.000000;
E  option = FQDNLookup; value = false;
E  Created new plugin context.
E  option = PIDFile; value = /var/run/stackdriver-agent.pid;
E  option = Interval; value = 60.000000;
E  option = FQDNLookup; value = false;
E  Created new plugin context.

Here you can find are all logs after the start of my custom setup.py (log-level: any; all logs):

https://jpst.it/1gk2Z

Update logfiles 2

Job logs (I manually canceled the job after not stucking for a while):

 2018-06-08 (08:02:20) Autoscaling is enabled for job 2018-06-07_23_02_20-5917188751755240698. The number of workers will b...
 2018-06-08 (08:02:20) Autoscaling was automatically enabled for job 2018-06-07_23_02_20-5917188751755240698.
 2018-06-08 (08:02:24) Checking required Cloud APIs are enabled.
 2018-06-08 (08:02:24) Checking permissions granted to controller Service Account.
 2018-06-08 (08:02:25) Worker configuration: n1-standard-1 in europe-west1-b.
 2018-06-08 (08:02:25) Expanding CoGroupByKey operations into optimizable parts.
 2018-06-08 (08:02:25) Combiner lifting skipped for step Save new watermarks/Write/WriteImpl/GroupByKey: GroupByKey not fol...
 2018-06-08 (08:02:25) Combiner lifting skipped for step Group watermarks: GroupByKey not followed by a combiner.
 2018-06-08 (08:02:25) Expanding GroupByKey operations into optimizable parts.
 2018-06-08 (08:02:26) Lifting ValueCombiningMappingFns into MergeBucketsMappingFns
 2018-06-08 (08:02:26) Annotating graph with Autotuner information.
 2018-06-08 (08:02:26) Fusing adjacent ParDo, Read, Write, and Flatten operations
 2018-06-08 (08:02:26) Fusing consumer Get rows from CloudSQL tables into Begin pipeline with watermarks/Read
 2018-06-08 (08:02:26) Fusing consumer Group watermarks/Write into Group watermarks/Reify
 2018-06-08 (08:02:26) Fusing consumer Group watermarks/GroupByWindow into Group watermarks/Read
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/WriteBundles/WriteBundles into Save new watermar...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/GroupByKey/GroupByWindow into Save new watermark...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/GroupByKey/Reify into Save new watermarks/Write/...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/GroupByKey/Write into Save new watermarks/Write/...
 2018-06-08 (08:02:26) Fusing consumer Write to BQ into Get rows from CloudSQL tables
 2018-06-08 (08:02:26) Fusing consumer Group watermarks/Reify into Write to BQ
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/Map(<lambda at iobase.py:926>) into Convert dict...
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/WindowInto(WindowIntoFn) into Save new watermark...
 2018-06-08 (08:02:26) Fusing consumer Convert dictionary list to single dictionary and json into Remove "watermark" label
 2018-06-08 (08:02:26) Fusing consumer Remove "watermark" label into Group watermarks/GroupByWindow
 2018-06-08 (08:02:26) Fusing consumer Save new watermarks/Write/WriteImpl/InitializeWrite into Save new watermarks/Write/W...
 2018-06-08 (08:02:26) Workflow config is missing a default resource spec.
 2018-06-08 (08:02:26) Adding StepResource setup and teardown to workflow graph.
 2018-06-08 (08:02:26) Adding workflow start and stop steps.
 2018-06-08 (08:02:26) Assigning stage ids.
 2018-06-08 (08:02:26) Executing wait step start25
 2018-06-08 (08:02:26) Executing operation Save new watermarks/Write/WriteImpl/DoOnce/Read+Save new watermarks/Write/WriteI...
 2018-06-08 (08:02:26) Executing operation Save new watermarks/Write/WriteImpl/GroupByKey/Create
 2018-06-08 (08:02:26) Starting worker pool setup.
 2018-06-08 (08:02:26) Executing operation Group watermarks/Create
 2018-06-08 (08:02:26) Starting 1 workers in europe-west1-b...
 2018-06-08 (08:02:27) Value "Group watermarks/Session" materialized.
 2018-06-08 (08:02:27) Value "Save new watermarks/Write/WriteImpl/GroupByKey/Session" materialized.
 2018-06-08 (08:02:27) Executing operation Begin pipeline with watermarks/Read+Get rows from CloudSQL tables+Write to BQ+Gr...
 2018-06-08 (08:02:36) Autoscaling: Raised the number of workers to 0 based on the rate of progress in the currently runnin...
 2018-06-08 (08:02:46) Autoscaling: Raised the number of workers to 1 based on the rate of progress in the currently runnin...
 2018-06-08 (08:03:05) Workers have started successfully.
 2018-06-08 (08:11:37) Cancel request is committed for workflow job: 2018-06-07_23_02_20-5917188751755240698.
 2018-06-08 (08:11:38) Cleaning up.
 2018-06-08 (08:11:38) Starting worker pool teardown.
 2018-06-08 (08:11:38) Stopping worker pool...
 2018-06-08 (08:12:30) Autoscaling: Reduced the number of workers to 0 based on the rate of progress in the currently runni...

Stack Traces:

No errors have been received in this time period.

Update: Workaround Solution can be found in my answer below


问:
React remove bootstrap.tsx
Hello i have created new react app

there is index.tsx in src   and all it contains is

```<code> import("./bootstrap")
</code>```

if i remove this import or modify it the app stops working

the bootstrap.tsx file contains this

```<code>import React from 'react';
import { render } from 'react-dom';
import App from './App';

const Root: React.FC = () => <App />;

render(<Root />, document.getElementById('root'));
</code>```

how can i remove it ?

i would like to if my index.tsx would containt

something like this

```<code>ReactDOM.render(
    <BrowserRouter>
      <App />
    </BrowserRouter>,

  document.getElementById('root')
</code>```

app.tsx

```<code>

interface AppProps {
  appPath?: string;
}

const App: React.FC<AppProps> = () => {
  return (
    <HashRouter>
      <Route path="/" exact component={View1Component} />
    </HashRouter>
  );
};

export default App;

</code>```

答:
I just came across this problem.

To remove bootstrap simply run the command below in your terminal or cmd

```<code>npm uninstall bootstrap
</code>```

This will automatically uninstall bootstrap from your dependencies

Title: React remove bootstrap.tsx

Body:
Hello i have created new react app

there is index.tsx in src   and all it contains is

 import("./bootstrap")

if i remove this import or modify it the app stops working

the bootstrap.tsx file contains this

import React from 'react';
import { render } from 'react-dom';
import App from './App';

const Root: React.FC = () => <App />;

render(<Root />, document.getElementById('root'));

how can i remove it ?

i would like to if my index.tsx would containt

something like this

ReactDOM.render(
    <BrowserRouter>
      <App />
    </BrowserRouter>,

  document.getElementById('root')

app.tsx

interface AppProps {
  appPath?: string;
}

const App: React.FC<AppProps> = () => {
  return (
    <HashRouter>
      <Route path="/" exact component={View1Component} />
    </HashRouter>
  );
};

export default App;

Body:
I just came across this problem.

To remove bootstrap simply run the command below in your terminal or cmd

npm uninstall bootstrap

This will automatically uninstall bootstrap from your dependencies


问:
Keep Flutter app layout LTR but using RTL language
I have a blog app, I need to keep the layout of my app in LTR (because i like the app in English style) but I need to make the language of my posts in RTL only.

How to make the full app using RTL style for posts?

答:
If you want to force LTR directionality even when the language is RTL, you can wrap your whole widget tree under MaterialApp using Directionality widget. Try this:

```<code>MaterialApp(
  ...
  builder: (context, child) {
    return Directionality(textDirection: TextDirection.ltr, child: child!);
  },
);
</code>```

Body:
If you want to force LTR directionality even when the language is RTL, you can wrap your whole widget tree under MaterialApp using Directionality widget. Try this:

MaterialApp(
  ...
  builder: (context, child) {
    return Directionality(textDirection: TextDirection.ltr, child: child!);
  },
);


问:
Flutter Unable to instantiate activity ComponentInfo Main Activity
I'm using vs code (to code) and android studio (to get virtual device).
I just merged and pulled the project I'm working on this morning, and first, have a very long time to wait to build my project. So i stopped all, uninstalled my app from my virtual device, then cleaned and run by "flutter run". Now I have these errors:

```<code>Using hardware rendering with device AOSP on IA Emulator. If you notice graphics artifacts, consider enabling software rendering with
"--enable-software-rendering".
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...                              6,0s
√  Built build\app\outputs\flutter-apk\app-debug.apk.
E/AndroidRuntime(11190): FATAL EXCEPTION: main
E/AndroidRuntime(11190): Process: com.example.coming_soon, PID: 11190
E/AndroidRuntime(11190): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.coming_soon/com.example.coming_soon.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.coming_soon.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/lib/x86, /data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/base.apk!/lib/x86, /system/lib]]
E/AndroidRuntime(11190):        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
E/AndroidRuntime(11190):        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
E/AndroidRuntime(11190):        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
E/AndroidRuntime(11190):        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
E/AndroidRuntime(11190):        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
E/AndroidRuntime(11190):        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
E/AndroidRuntime(11190):        at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(11190):        at android.os.Looper.loop(Looper.java:193)
E/AndroidRuntime(11190):        at android.app.ActivityThread.main(ActivityThread.java:6669)
E/AndroidRuntime(11190):        at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(11190):        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/AndroidRuntime(11190):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/AndroidRuntime(11190): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.coming_soon.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/lib/x86, /data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/base.apk!/lib/x86, /system/lib]]
E/AndroidRuntime(11190):        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
E/AndroidRuntime(11190):        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
E/AndroidRuntime(11190):        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime(11190):        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
E/AndroidRuntime(11190):        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
E/AndroidRuntime(11190):        at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
E/AndroidRuntime(11190):        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
E/AndroidRuntime(11190):        ... 11 more
</code>```

Here is my flutter doctor -v

```<code>
[√] Flutter (Channel stable, 2.5.3, on Microsoft Windows [version 10.0.19043.1348], locale fr-FR)
    • Flutter version 2.5.3 at C:\Users\Johanne\Development\sdks\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 18116933e7 (5 weeks ago), 2021-10-15 10:46:35 -0700
    • Engine revision d3ea636dc5
    • Dart version 2.14.4

[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at C:\Users\Johanne\AppData\Local\Android\sdk
    • Platform android-31, build-tools 31.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 2020.3)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[√] VS Code (version 1.62.2)
    • VS Code at C:\Users\Johanne\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.28.0

[√] Connected device (3 available)
    • AOSP on IA Emulator (mobile) • emulator-5556 • android-x86    • Android 9 (API 28) (emulator)
    • Chrome (web)                 • chrome        • web-javascript • Google Chrome 95.0.4638.69
    • Edge (web)                   • edge          • web-javascript • Microsoft Edge 95.0.1020.44

• No issues found!

</code>```

Here is my android.manifest :

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.coming_soon">
    <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    <uses-permission android:name="android.permission.VIBRATE" />
<application
        android:label="coming_soon"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

</code>```

I already searched and found similar issues, but I wasn't able to solve my problem.
I tried to create a MainActivity.java file, but got new errors, so I deleted it.
Did I miss something?

答: For me, the solution was to simply run flutter clean and flutter pub get in the project directory.

Body:
I'm using vs code (to code) and android studio (to get virtual device).
I just merged and pulled the project I'm working on this morning, and first, have a very long time to wait to build my project. So i stopped all, uninstalled my app from my virtual device, then cleaned and run by "flutter run". Now I have these errors:

Using hardware rendering with device AOSP on IA Emulator. If you notice graphics artifacts, consider enabling software rendering with
"--enable-software-rendering".
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...                              6,0s
√  Built build\app\outputs\flutter-apk\app-debug.apk.
E/AndroidRuntime(11190): FATAL EXCEPTION: main
E/AndroidRuntime(11190): Process: com.example.coming_soon, PID: 11190
E/AndroidRuntime(11190): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.coming_soon/com.example.coming_soon.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.coming_soon.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/lib/x86, /data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/base.apk!/lib/x86, /system/lib]]
E/AndroidRuntime(11190):        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
E/AndroidRuntime(11190):        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
E/AndroidRuntime(11190):        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
E/AndroidRuntime(11190):        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
E/AndroidRuntime(11190):        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
E/AndroidRuntime(11190):        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
E/AndroidRuntime(11190):        at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(11190):        at android.os.Looper.loop(Looper.java:193)
E/AndroidRuntime(11190):        at android.app.ActivityThread.main(ActivityThread.java:6669)
E/AndroidRuntime(11190):        at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(11190):        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/AndroidRuntime(11190):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/AndroidRuntime(11190): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.coming_soon.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/lib/x86, /data/app/com.example.coming_soon-g9Xk6gs-AdO4Khd-H_dR3g==/base.apk!/lib/x86, /system/lib]]
E/AndroidRuntime(11190):        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
E/AndroidRuntime(11190):        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
E/AndroidRuntime(11190):        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime(11190):        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
E/AndroidRuntime(11190):        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
E/AndroidRuntime(11190):        at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
E/AndroidRuntime(11190):        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
E/AndroidRuntime(11190):        ... 11 more

Here is my flutter doctor -v

[√] Flutter (Channel stable, 2.5.3, on Microsoft Windows [version 10.0.19043.1348], locale fr-FR)
    • Flutter version 2.5.3 at C:\Users\Johanne\Development\sdks\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 18116933e7 (5 weeks ago), 2021-10-15 10:46:35 -0700
    • Engine revision d3ea636dc5
    • Dart version 2.14.4

[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at C:\Users\Johanne\AppData\Local\Android\sdk
    • Platform android-31, build-tools 31.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 2020.3)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[√] VS Code (version 1.62.2)
    • VS Code at C:\Users\Johanne\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.28.0

[√] Connected device (3 available)
    • AOSP on IA Emulator (mobile) • emulator-5556 • android-x86    • Android 9 (API 28) (emulator)
    • Chrome (web)                 • chrome        • web-javascript • Google Chrome 95.0.4638.69
    • Edge (web)                   • edge          • web-javascript • Microsoft Edge 95.0.1020.44

• No issues found!

Here is my android.manifest :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.coming_soon">
    <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    <uses-permission android:name="android.permission.VIBRATE" />
<application
        android:label="coming_soon"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />

            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

I already searched and found similar issues, but I wasn't able to solve my problem.
I tried to create a MainActivity.java file, but got new errors, so I deleted it.
Did I miss something?


问:
How to open a block of comments on PgAdmin query editor?
There are 2 ways to mark comment in pgAdmin - PostgreSQL:
the

-- bla bla

and the:

/* bla bla
bla bla*/

for the first one i use ctrl+k as short hot key.
is there a hot key for the 2nd one? i know ctrl+k can be applied on muliple lines if i mark them but it will add -- for all lines which isn't what I'm looking for.

答:
On Ubuntu GNU/LInux (PgAdmin4), select a block of code with the mouse cursor.

Comment

Ctrl + }

UNcomment

Ctrl + Shift + }