问:
How to make radar spider chart with pentagon grid using matplotlib and python?
I have a radar chart. Need to change the grid from circle-form to pentagon-form. Currently, I have this output:

Whereas I expect smth like this:

Here's the info about the system i have: Windows 10 (64-bit); Python - 3.8.0 (32-bit); matplotlib - 3.3.3.
This question i've seen here: How to make a polygon radar (spider) chart in python but it doesn't resolve my question.
But it doesn't work for me and i can't understand why. I can simply copy the code, but the result is - outer border changes to pentagon-form, but the inner gridlines remain circular. But it works for other people!

The code of the program is below:

import numpy as np

import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
from matplotlib.spines import Spine
from matplotlib.transforms import Affine2D

def radar_factory(num_vars, frame='circle'):
    """Create a radar chart with `num_vars` axes.

    This function creates a RadarAxes projection and registers it.

    Parameters
    ----------
    num_vars : int
        Number of variables for radar chart.
    frame : {'circle' | 'polygon'}
        Shape of frame surrounding axes.

    """
    # calculate evenly-spaced axis angles
    theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)

    class RadarAxes(PolarAxes):

        name = 'radar'

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # rotate plot such that the first axis is at the top
            self.set_theta_zero_location('N')

        def fill(self, *args, closed=True, **kwargs):
            """Override fill so that line is closed by default"""
            return super().fill(closed=closed, *args, **kwargs)

        def plot(self, *args, **kwargs):
            """Override plot so that line is closed by default"""
            lines = super().plot(*args, **kwargs)
            for line in lines:
                self._close_line(line)

        def _close_line(self, line):
            x, y = line.get_data()
            # FIXME: markers at x[0], y[0] get doubled-up
            if x[0] != x[-1]:
                x = np.concatenate((x, [x[0]]))
                y = np.concatenate((y, [y[0]]))
                line.set_data(x, y)

        def set_varlabels(self, labels):
            self.set_thetagrids(np.degrees(theta), labels)

        def _gen_axes_patch(self):
            # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
            # in axes coordinates.
            if frame == 'circle':
                return Circle((0.5, 0.5), 0.5)
            elif frame == 'polygon':
                return RegularPolygon((0.5, 0.5), num_vars, radius=0.5, edgecolor="k")
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

        def draw(self, renderer):
            """ Draw. If frame is polygon, make gridlines polygon-shaped """
            if frame == 'polygon':
                gridlines = self.yaxis.get_gridlines()
                for gl in gridlines:
                    gl.get_path()._interpolation_steps = num_vars
            super().draw(renderer)

        def _gen_axes_spines(self):
            if frame == 'circle':
                return super()._gen_axes_spines()
            elif frame == 'polygon':
                # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.
                spine = Spine(axes=self,
                              spine_type='circle',
                              path=Path.unit_regular_polygon(num_vars))
                # unit_regular_polygon gives a polygon of radius 1 centered at
                # (0, 0) but we want a polygon of radius 0.5 centered at (0.5,
                # 0.5) in axes coordinates.
                spine.set_transform(Affine2D().scale(.5).translate(.5, .5)
                                    + self.transAxes)
                return {'polar': spine}
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

    register_projection(RadarAxes)
    return theta

data = [['O1', 'O2', 'O3', 'O4', 'O5'],
        ('Title', [
                    [4, 3.5, 4, 2, 3,],
                    [1.07, 5.95, 2.04, 1.05, 0.00,],
                  ]
        )]

N = len(data[0])
theta = radar_factory(N, frame='polygon')                                     # polygon  !!!

spoke_labels = data.pop(0)
title, case_data = data[0]
fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(projection='radar'))
fig.subplots_adjust(top=0.85, bottom=0.05)
ax.set_rgrids([0, 1, 2.0, 3.0, 4.0, 5.0, 6])
ax.set_title(title,  position=(0.5, 1.1), ha='center')

for d in case_data:
    line = ax.plot(theta, d)
    ax.fill(theta, d,  alpha=0.25)
ax.set_varlabels(spoke_labels)

plt.show()

```

答:
As mentioned by @joao-neves the docs will be updated in this PR. The working code for your example would be

import numpy as np

import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
from matplotlib.spines import Spine
from matplotlib.transforms import Affine2D

def radar_factory(num_vars, frame='circle'):
    """Create a radar chart with `num_vars` axes.

    This function creates a RadarAxes projection and registers it.

    Parameters
    ----------
    num_vars : int
        Number of variables for radar chart.
    frame : {'circle' | 'polygon'}
        Shape of frame surrounding axes.

    """
    # calculate evenly-spaced axis angles
    theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)

    class RadarTransform(PolarAxes.PolarTransform):
        def transform_path_non_affine(self, path):
            # Paths with non-unit interpolation steps correspond to gridlines,
            # in which case we force interpolation (to defeat PolarTransform's
            # autoconversion to circular arcs).
            if path._interpolation_steps > 1:
                path = path.interpolated(num_vars)
            return Path(self.transform(path.vertices), path.codes)

    class RadarAxes(PolarAxes):

        name = 'radar'
        PolarTransform = RadarTransform

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # rotate plot such that the first axis is at the top
            self.set_theta_zero_location('N')

        def fill(self, *args, closed=True, **kwargs):
            """Override fill so that line is closed by default"""
            return super().fill(closed=closed, *args, **kwargs)

        def plot(self, *args, **kwargs):
            """Override plot so that line is closed by default"""
            lines = super().plot(*args, **kwargs)
            for line in lines:
                self._close_line(line)

        def _close_line(self, line):
            x, y = line.get_data()
            # FIXME: markers at x[0], y[0] get doubled-up
            if x[0] != x[-1]:
                x = np.concatenate((x, [x[0]]))
                y = np.concatenate((y, [y[0]]))
                line.set_data(x, y)

        def set_varlabels(self, labels):
            self.set_thetagrids(np.degrees(theta), labels)

        def _gen_axes_patch(self):
            # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
            # in axes coordinates.
            if frame == 'circle':
                return Circle((0.5, 0.5), 0.5)
            elif frame == 'polygon':
                return RegularPolygon((0.5, 0.5), num_vars, radius=0.5, edgecolor="k")
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

        def draw(self, renderer):
            """ Draw. If frame is polygon, make gridlines polygon-shaped """
            if frame == 'polygon':
                gridlines = self.yaxis.get_gridlines()
                for gl in gridlines:
                    gl.get_path()._interpolation_steps = num_vars
            super().draw(renderer)

        def _gen_axes_spines(self):
            if frame == 'circle':
                return super()._gen_axes_spines()
            elif frame == 'polygon':
                # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.
                spine = Spine(axes=self,
                              spine_type='circle',
                              path=Path.unit_regular_polygon(num_vars))
                # unit_regular_polygon gives a polygon of radius 1 centered at
                # (0, 0) but we want a polygon of radius 0.5 centered at (0.5,
                # 0.5) in axes coordinates.
                spine.set_transform(Affine2D().scale(.5).translate(.5, .5)
                                    + self.transAxes)
                return {'polar': spine}
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

    register_projection(RadarAxes)
    return theta

data = [['O1', 'O2', 'O3', 'O4', 'O5'],
        ('Title', [
                    [4, 3.5, 4, 2, 3,],
                    [1.07, 5.95, 2.04, 1.05, 0.00,],
                  ]
        )]

N = len(data[0])
theta = radar_factory(N, frame='polygon')

spoke_labels = data.pop(0)
title, case_data = data[0]
fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(projection='radar'))
fig.subplots_adjust(top=0.85, bottom=0.05)
ax.set_rgrids([0, 1, 2.0, 3.0, 4.0, 5.0, 6])
ax.set_title(title,  position=(0.5, 1.1), ha='center')

for d in case_data:
    line = ax.plot(theta, d)
    ax.fill(theta, d, alpha=0.25, label='_nolegend_')
ax.set_varlabels(spoke_labels)

plt.show()
```


来源: stackexchange

问:
javascript create dictionary from array
I have an array like this

```<code>propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: ????
        },
        enabled: true
    }
]
</code>```

In the places array there are objects with id, name, etc. Now I want to create a dictionary placesDict that should look like {place1.id: 0, place2.id: 0, ...}, so all values will be set to 0. How can I do that?

答:
Better option in modern JS (>2019) is to use. It requires to have an Array of tuples (Array of Arrays). In following call I am extending Array with the map function which constructs the "nested array".

```<code>> const x = ["a", "b", "3"];
> Object.fromEntries(x.map(i => [i, undefined]));|
{ '3': undefined, a: undefined, b: undefined }
</code>```

You can use the spread operator with following result:

```<code>> x = [1,2,3]
[ 1, 2, 3 ]
> {...x}
{ '0': 1, '1': 2, '2': 3 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: javascript create dictionary from array

Body:
I have an array like this

propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: ????
        },
        enabled: true
    }
]

In the places array there are objects with id, name, etc. Now I want to create a dictionary placesDict that should look like {place1.id: 0, place2.id: 0, ...}, so all values will be set to 0. How can I do that?

Body:
Better option in modern JS (>2019) is to use. It requires to have an Array of tuples (Array of Arrays). In following call I am extending Array with the map function which constructs the "nested array".

> const x = ["a", "b", "3"];
> Object.fromEntries(x.map(i => [i, undefined]));|
{ '3': undefined, a: undefined, b: undefined }

You can use the spread operator with following result:

> x = [1,2,3]
[ 1, 2, 3 ]
> {...x}
{ '0': 1, '1': 2, '2': 3 }

ContentLicense: CC BY-SA 4.0


问:
HOW TO run pose estimation on single image with TensorFlow-Lite?
I recently used this sample of great TensorFlow lite in android.

I can use this project correctly, but I want to estimate poses on single images too (not just in real time mode). so I tried to reach my goal! but unfortunately I couldn't! and those disappointing codes are here:

```<code>private fun runOnSimpleImage() {
    val detector = MoveNet.create(this, device, ModelType.Lightning)
    detector.let { detector ->
        simpleDetector = detector
    }
    simpleDetector?.estimatePoses(templateBitmap)?.let {persons->
        VisualizationUtils.drawBodyKeypoints(
            templateBitmap,
            persons, false
        )
    }

    showOutputBitmap(templateBitmap)
}
</code>```

Also I search it and found this. but I couldn't solve my problem yet.
and my result is something like this:

答:
Fortunately my code is not wrong! and it works correctly. and you can use it!

The problem was in method that I used to convert my drawable image to Bitmap.

I used to use these codes:

```<code>val drawable = ResourcesCompat.getDrawable(resources, R.drawable.resized,theme)

templateBitmap = (drawable as BitmapDrawable).bitmap
</code>```

But when I changed those to something like this:

```<code> templateBitmap = BitmapFactory.decodeResource(resources,R.drawable.resized)
</code>```

my problem solved.

Body:
I recently used this sample of great TensorFlow lite in android.

I can use this project correctly, but I want to estimate poses on single images too (not just in real time mode). so I tried to reach my goal! but unfortunately I couldn't! and those disappointing codes are here:

private fun runOnSimpleImage() {
    val detector = MoveNet.create(this, device, ModelType.Lightning)
    detector.let { detector ->
        simpleDetector = detector
    }
    simpleDetector?.estimatePoses(templateBitmap)?.let {persons->
        VisualizationUtils.drawBodyKeypoints(
            templateBitmap,
            persons, false
        )
    }

    showOutputBitmap(templateBitmap)
}

Also I search it and found this. but I couldn't solve my problem yet.
and my result is something like this:

Body:
Fortunately my code is not wrong! and it works correctly. and you can use it!

The problem was in method that I used to convert my drawable image to Bitmap.

I used to use these codes:

val drawable = ResourcesCompat.getDrawable(resources, R.drawable.resized,theme)

templateBitmap = (drawable as BitmapDrawable).bitmap

But when I changed those to something like this:

 templateBitmap = BitmapFactory.decodeResource(resources,R.drawable.resized)

my problem solved.


问:
Android Concurrency issue
I have strictly separated the layers between different parts of my Android application.
At some point of execution I am updating my data from xml service on Internet. That updating takes up about 10 seconds and is done completely in the background - meaning the user interface of an application works fine. However further calls to my class (later - DataManager) which is responsible for data updating (after update has been started but not yet finished) makes my application crash. NullPointerException is thrown with objects which NEVER are null.

So I assume that only one Thread can use my DataManager at one time and calls to DataManager from other threads ends up in exceptions.

I tried various combinations of putting 'synchronized' keywords near sensitive methods but it seems that when update is executing - NOTHING can use ANYTHING from my DataManager.

BTW other classes which are related to DataManager during the execution also seem to hold null objects.

I guess I am just missing some kind of design pattern which is used to deal with concurrency problems and maybe anyone can suggest me something?

答:
I had trouble dealing with using the Apache http client because of threading issues and I think your issue could be similar in that respect.  What I ended up doing was setting up a callback scheme.  This may or may not work for you, of course.

This may seem a bit Rube Goldberg-like to you, but it worked for me.

I would have my UI thread call my data manager object with a method that spawned a thread to go and acquire the data.  The method's return value is an object that would EVENTUALLY have the data in it.  I would have my activity extend an interface, something like "DataCallbackInterface", with a method that the thread would call after it acquired the data (i.e. the last line in run()).  Since that call will inherently be within another thread, you'll need to use a Handler to run anything useful in your implementation of the DataCallbackInterface method.  When that method is called, you will know for a fact that the data is there and not rely on any strange synchronization flags to get it right.

Title: Android Concurrency issue


问:
Getting errors from Monaco editor
I would like to get hold of the errors created by default by Monaco editor.

答:
This is a simple sample to log errors:

import * as monaco from 'monaco-editor'

// ...

monaco.editor.onDidChangeMarkers(([uri]) => {
  const markers = monaco.editor.getModelMarkers({resource: uri})
  console.log('markers:', markers.map(
    ({ message, startLineNumber, startColumn, endLineNumber, endColumn }) =>
      `${message} [${startLineNumber}:${startColumn}-${endLineNumber}:${endColumn}]`,
  ))
})
```

Title: Getting errors from Monaco editor


问:
Error: Must use import to load ES Module: D:\node_modules\react-markdown\index.js require() of ES modules is not supported
Currently I'm using "react": "17.0.2" and I have installed "react-markdown": "^7.0.1" via npm i react-markdown I'm using this package to display my rich text that I'm fetching from my Strapi CMS. I have used the following code to display the content:

```<code>import ReactMarkdown from "react-markdown";

export default function name({ posts }) {
  return (
    <>
      <div>
        <div>
          {posts.Title}
        </div>
      </div>
      <div>
        <ReactMarkdown source={posts.Content} escapeHtml={false} />
      </div>
    </>
  );
}

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/blogs");
  const posts = await res.json();

  return {
    props: { posts },
  };
}
</code>```

But when I run this it gives me the following error:

I'm using node v14.17.0 and have tried adding "type": "module".

My package.json:

{
  "name": "passportlegacy",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "babel-plugin-inline-react-svg": "^2.0.1",
    "next": "11.0.1",
    "next-images": "^1.8.1",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-map-gl": "^6.1.16",
    "react-markdown": "^7.0.1",
  },
  "devDependencies": {
    "@svgr/webpack": "^5.5.0",
    "@types/react": "17.0.16",
    "eslint": "7.32.0",
    "eslint-config-next": "11.0.1",
    "typescript": "4.3.5"
  }
}
```

答:
Use this version

```<code>"dependencies": {
    "react-markdown": "^6.0.0"
  }
</code>```

Then issue

```<code>npm install
</code>```

Body:
Currently I'm using "react": "17.0.2" and I have installed "react-markdown": "^7.0.1" via npm i react-markdown I'm using this package to display my rich text that I'm fetching from my Strapi CMS. I have used the following code to display the content:

import ReactMarkdown from "react-markdown";

export default function name({ posts }) {
  return (
    <>

          {posts.Title}

        <ReactMarkdown source={posts.Content} escapeHtml={false} />

    </>
  );
}

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/blogs");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

But when I run this it gives me the following error:

I'm using node v14.17.0 and have tried adding "type": "module".

My package.json:

{
  "name": "passportlegacy",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "babel-plugin-inline-react-svg": "^2.0.1",
    "next": "11.0.1",
    "next-images": "^1.8.1",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-map-gl": "^6.1.16",
    "react-markdown": "^7.0.1",
  },
  "devDependencies": {
    "@svgr/webpack": "^5.5.0",
    "@types/react": "17.0.16",
    "eslint": "7.32.0",
    "eslint-config-next": "11.0.1",
    "typescript": "4.3.5"
  }
}

Body:
Use this version

"dependencies": {
    "react-markdown": "^6.0.0"
  }

Then issue

npm install


问:
How to move to last empty row in DataGridView in C# programmatically
I am removing a row from DataGridView in WinForms. I want to move to the last empty row using code. For removing I am using this line

```<code>  OrderItemsGridView.Rows.RemoveAt(e.RowIndex);
</code>```

I tried to use this line

```<code>  OrderItemsGridView.FirstDisplayedScrollingRowIndex = OrderItemsGridView.RowCount;
</code>```

but it is out of range because I think it does not count the empty one. If I change it to (RowCount -1) then it will take the last row (not the empty one)

Any suggestion?

This is similar to this question, but it has not been answered.
question
I hope if someone has any suggestion

答:
You can select the first cell of the last row and begin editing like this:

```<code>dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.NewRowIndex].Cells[0];
dataGridView1.BeginEdit(true);
</code>```

Using NewRowIndex property you know what's the index of the last row. Then using CurrentCell property you can set the current cell, and finally using BeginEdit method you can start editing.

Body:
I am removing a row from DataGridView in WinForms. I want to move to the last empty row using code. For removing I am using this line

  OrderItemsGridView.Rows.RemoveAt(e.RowIndex);

I tried to use this line

  OrderItemsGridView.FirstDisplayedScrollingRowIndex = OrderItemsGridView.RowCount;

but it is out of range because I think it does not count the empty one. If I change it to (RowCount -1) then it will take the last row (not the empty one)

Any suggestion?

This is similar to this question, but it has not been answered.
question
I hope if someone has any suggestion

Body:
You can select the first cell of the last row and begin editing like this:

dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.NewRowIndex].Cells[0];
dataGridView1.BeginEdit(true);

Using NewRowIndex property you know what's the index of the last row. Then using CurrentCell property you can set the current cell, and finally using BeginEdit method you can start editing.


问:
Sometimes the jumping mechanic doesnt work
recently I started working on a 2d Unity local coop platformer game, with a simple code of movement. The problem is that sometimes when I try to jump it doesnt work, its not a keyboard problem, I tried in different computers.

Heres the code:

```<code>using System.Collections.Generic;
using UnityEngine;

public class Player1Movement : MonoBehaviour
{
    //Movement

    public float speed;
    public float jump;
    float moveVelocity;
    public Rigidbody2D rb;
    bool isGrounded;

    void Update()
    {
        //Grounded?
        if (isGrounded == true)
        {
            //jumping
            if (Input.GetKeyDown(KeyCode.W))
            {

                GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jump);
            }

        }

        moveVelocity = 0;

        //Left Right Movement
        if (Input.GetKey(KeyCode.A))
        {
            moveVelocity = -speed;
        }
        if (Input.GetKey(KeyCode.D))
        {
            moveVelocity = speed;
        }

        GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, GetComponent<Rigidbody2D>().velocity.y);

    }
    void OnCollisionEnter2D(Collision2D col)
    {
        Debug.Log("OnCollisionEnter2D");
        isGrounded = true;
    }
    void OnCollisionExit2D(Collision2D col)
    {
        Debug.Log("OnCollisionExit2D");
        isGrounded = false;
    }
}```
```

答:
If you take this code

```<code>//jumping
        if (Input.GetKeyDown(KeyCode.W))
        {

            GetComponent<Rigidbody2D>().velocity = new
Vector2(GetComponent<Rigidbody2D>().velocity.x, jump);
        }
</code>```

Out of the isGrounded if statement, does the jump work consistently? If so, the issue is with your isGrounded logic.

As for the ground check, I would switch to a raycast approach as, assuming you're using tiles, you will be flicking off and on isGrounded as you move between tiles.

Also, to increase performance, if you add this into an awake function

```<code> Rb = GetComponent<RigidBody2D>();
</code>```

And replace all of your getcomponents with rb.

Body:
recently I started working on a 2d Unity local coop platformer game, with a simple code of movement. The problem is that sometimes when I try to jump it doesnt work, its not a keyboard problem, I tried in different computers.

Heres the code:

using System.Collections.Generic;
using UnityEngine;

public class Player1Movement : MonoBehaviour
{
    //Movement

    public float speed;
    public float jump;
    float moveVelocity;
    public Rigidbody2D rb;
    bool isGrounded;

    void Update()
    {
        //Grounded?
        if (isGrounded == true)
        {
            //jumping
            if (Input.GetKeyDown(KeyCode.W))
            {

                GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jump);
            }

        }

        moveVelocity = 0;

        //Left Right Movement
        if (Input.GetKey(KeyCode.A))
        {
            moveVelocity = -speed;
        }
        if (Input.GetKey(KeyCode.D))
        {
            moveVelocity = speed;
        }

        GetComponent<Rigidbody2D>().velocity = new Vector2(moveVelocity, GetComponent<Rigidbody2D>().velocity.y);

    }
    void OnCollisionEnter2D(Collision2D col)
    {
        Debug.Log("OnCollisionEnter2D");
        isGrounded = true;
    }
    void OnCollisionExit2D(Collision2D col)
    {
        Debug.Log("OnCollisionExit2D");
        isGrounded = false;
    }
}```

Body:
If you take this code

//jumping
        if (Input.GetKeyDown(KeyCode.W))
        {

            GetComponent<Rigidbody2D>().velocity = new
Vector2(GetComponent<Rigidbody2D>().velocity.x, jump);
        }

Out of the isGrounded if statement, does the jump work consistently? If so, the issue is with your isGrounded logic.

As for the ground check, I would switch to a raycast approach as, assuming you're using tiles, you will be flicking off and on isGrounded as you move between tiles.

Also, to increase performance, if you add this into an awake function

 Rb = GetComponent<RigidBody2D>();

And replace all of your getcomponents with rb.


问:
How can I change the user on Git Bash?

I want to sign out an actual user so I can sign in with another user.

What I see in Git bash is:

```<code>MINGW64 ~/Documents/NetBeansProjects/ConstructorJava (master)
git push -u origin/master
remote: Permission to Fre1234/ConstructorJava.git denied to Fre123.
Fatal: unable to access https://github.com/Fre1234/ConstructorJava.git/": The requested URL returned error: 403
</code>```

答:
WINDOWS

Looks like there are already plenty of solutions here but I thought I'd share mine anyway, which is a spin on this from Vonc:

The OP Fre1234 adds in the comments:

I finally found the solution. Go to: Control Panel -> User Accounts ->
Manage your credentials -> Windows Credentials

Under Generic Credentials there are some credentials related to
Github, Click on them and click "Remove".

Instead of deleting the credential for the first account, I just created a new PAT on GitHub for the second account, and clicked on Add a generic credential.

Then filled it out like this:

I don't know exactly what permissions it needs, so I just used these:

I can now clone and push with no problems, but MAKE SURE TO CHANGE YOUR EMAIL TO THE ONE YOU USE FOR THE SECOND ACCOUNT. Otherwise, it will look like your commits were made with your first account.

```<code>$ git config --global user.email "SECONDACCOUNT@EMAIL.COM"
</code>```

I personally don't bother changing user.name, from my little experimenting it seems GitHub uses the email to fetch the username and avatar anyway, and only uses the name if the email is invalid.

Title: How can I change the user on Git Bash?

Body:
I want to sign out an actual user so I can sign in with another user.

What I see in Git bash is:

MINGW64 ~/Documents/NetBeansProjects/ConstructorJava (master)
git push -u origin/master
remote: Permission to Fre1234/ConstructorJava.git denied to Fre123.
Fatal: unable to access https://github.com/Fre1234/ConstructorJava.git/": The requested URL returned error: 403

Body:
WINDOWS

Looks like there are already plenty of solutions here but I thought I'd share mine anyway, which is a spin on this from Vonc:

The OP Fre1234 adds in the comments:

I finally found the solution. Go to: Control Panel -> User Accounts ->
Manage your credentials -> Windows Credentials

Under Generic Credentials there are some credentials related to
Github, Click on them and click "Remove".

Instead of deleting the credential for the first account, I just created a new PAT on GitHub for the second account, and clicked on Add a generic credential.

Then filled it out like this:

I don't know exactly what permissions it needs, so I just used these:

I can now clone and push with no problems, but MAKE SURE TO CHANGE YOUR EMAIL TO THE ONE YOU USE FOR THE SECOND ACCOUNT. Otherwise, it will look like your commits were made with your first account.

$ git config --global user.email "SECONDACCOUNT@EMAIL.COM"

I personally don't bother changing user.name, from my little experimenting it seems GitHub uses the email to fetch the username and avatar anyway, and only uses the name if the email is invalid.


问:
How to add a row to a dataframe modifying only some columns
In order to prepare the data for plotting I need to add a new row to the data:

I have this dataframe:

```<code>df <- data.frame(
  test_id = c(1, 1, 1, 1),
  test_nr = c(1, 1, 1, 1),
  region = c("A", "B", "C", "D"),
  test_value = c(3, 1, 1, 2)
)

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2
</code>```

I would like to add a row to this dataframe so the desired output should be:

```<code>  test_id test_nr region test_value
1       1       1      A       3.00
2       1       1      B       1.00
3       1       1      C       1.00
4       1       1      D       2.00
5       1       1   mean       1.75
</code>```

As you can see: column 1 and column 2 are the same value, column 3 changed to 'mean' and column 4 is the mean of row1-4.

I have tried to use add_row from tibble package which gives an error:

```<code>library(dpylr)
library(tibble)

df %>%
  mutate(mean1 = mean(test_value)) %>%
  add_row(test_id = test_id[1], test_nr=test_nr[1],region="mean", test_value=mean(test_value))

Error in eval_tidy(xs[[j]], mask) : object 'test_id' not found
</code>```

答:
You could do

library(dplyr)

df %>%
  add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))
#>   test_id test_nr region test_value
#> 1       1       1      A       3.00
#> 2       1       1      B       1.00
#> 3       1       1      C       1.00
#> 4       1       1      D       2.00
#> 5       1       1   mean       1.75
```

Body:
In order to prepare the data for plotting I need to add a new row to the data:

I have this dataframe:

df <- data.frame(
  test_id = c(1, 1, 1, 1),
  test_nr = c(1, 1, 1, 1),
  region = c("A", "B", "C", "D"),
  test_value = c(3, 1, 1, 2)
)

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2

I would like to add a row to this dataframe so the desired output should be:

  test_id test_nr region test_value
1       1       1      A       3.00
2       1       1      B       1.00
3       1       1      C       1.00
4       1       1      D       2.00
5       1       1   mean       1.75

As you can see: column 1 and column 2 are the same value, column 3 changed to 'mean' and column 4 is the mean of row1-4.

I have tried to use add_row from tibble package which gives an error:

library(dpylr)
library(tibble)

df %>%
  mutate(mean1 = mean(test_value)) %>%
  add_row(test_id = test_id[1], test_nr=test_nr[1],region="mean", test_value=mean(test_value))

Error in eval_tidy(xs[[j]], mask) : object 'test_id' not found


问:
How to find the title of an URL using VBA in MS Excel
I am working on a VBA project to get Page title and created date from an URL. I found this code online but it's not working since IE is not available. Is there any way I can get the title without IE?

```<code>Function GetPageTitle(a As String)

Set ie = CreateObject("InternetExplorer.Application")
With ie
    .Visible = False
    .Navigate a
    Do Until .ReadyState = 4
        DoEvents
    Loop
    GetPageTitle = .document.Title
    .Quit
End With

End Function
</code>```

I have tried to use Edge as Internet Explorer but it's not working.
I have tried this code also HTML Page Title in Excel VBA

答:
Get Webpage Title

Option Explicit

Sub GetPageTitleTEST()
    Const URL As String = "https://www.google.com"
    Dim PageTitle As String: PageTitle = GetPageTitle(URL)
    If Len(PageTitle) > 0 Then
        Debug.Print PageTitle
    Else
        Debug.Print "Nope."
    End If
End Sub

Function GetPageTitle( ByVal URL As String) As String
    Dim Response As String
    On Error GoTo ClearError

    With CreateObject("MSXML2.ServerXMLHTTP")
        .Open "Get", URL, False
        .send
        Response = .responseText
    End With

    With CreateObject("htmlfile")
        .body.innerHTML = Response
        GetPageTitle = .getElementsByTagName("title")(0).innerText
    End With

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'GetPageTitle' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function
```

Body:
I am working on a VBA project to get Page title and created date from an URL. I found this code online but it's not working since IE is not available. Is there any way I can get the title without IE?

Function GetPageTitle(a As String)

Set ie = CreateObject("InternetExplorer.Application")
With ie
    .Visible = False
    .Navigate a
    Do Until .ReadyState = 4
        DoEvents
    Loop
    GetPageTitle = .document.Title
    .Quit
End With

End Function

I have tried to use Edge as Internet Explorer but it's not working.
I have tried this code also HTML Page Title in Excel VBA


问:
Remove "plus" sing from date
How can I convert timestamp with timezone into normal "datetime" type?
When I print the df.dtypes of my df I get "object" as a type for this column not a "date time"

I have data frame:

```<code>| Resource | timestamp                       |
| -------- | --------------                  |
| 112      | 2011-10-01 00:38:44.546000+02:00|
| 113      | 2011-10-02 00:38:44.546000+02:00|
| 112      | 2011-10-03 00:38:44.546000+02:00|
| 115      | 2011-10-04 00:38:44.546000+02:00|
| 114      | 2011-10-05 00:38:44.546000+02:00|
</code>```

I used

```<code>df_log['time:timestamp'] = df_log['time:timestamp'].apply(lambda x: dt.strftime(dt.fromisoformat(str(x)),'%Y-%m-%d.%H:%M:%S'))
</code>```

It has removed the '+' sign and gave me the date and time part, but I feel I am doing it wrong because i don't have good knowledge from datetime processing!
My goal is to just get date and time like "2011-10-01 00:38:44" and the type be "datetime" not object as I am still getting!

答:
After spending some time, these lines solved my problem:

Apply the timezone to the column and convert timestamp to date and time only:

```<code>df['timestamp'] = pd.to_datetime(df['timestamp'], utc=True).dt.tz_convert(None)
</code>```

Remove the timezone without applying it to the column: (My favorite)

```<code>df['timestamp'] = pd.to_datetime(df['timestamp']).apply(lambda t: t.replace(tzinfo=None))
</code>```

OR

```<code>df['timestamp'] = pd.to_datetime(df['timestamp']).apply(lambda d: d.strftime('%Y-%m-%d %H:%M:%S'))
</code>```

You should iterate through each row by using apply function with a lambda expression to use replace function because replace function work with pandas.tslib.Timestampobject not with pandas.core.series.Series. Otherwise, you will end up with this error: TypeError: replace() got an unexpected keyword argument 'tzinfo'

Title: Remove "plus" sing from date

Body:
How can I convert timestamp with timezone into normal "datetime" type?
When I print the df.dtypes of my df I get "object" as a type for this column not a "date time"

I have data frame:

| Resource | timestamp                       |
| -------- | --------------                  |
| 112      | 2011-10-01 00:38:44.546000+02:00|
| 113      | 2011-10-02 00:38:44.546000+02:00|
| 112      | 2011-10-03 00:38:44.546000+02:00|
| 115      | 2011-10-04 00:38:44.546000+02:00|
| 114      | 2011-10-05 00:38:44.546000+02:00|

I used

df_log['time:timestamp'] = df_log['time:timestamp'].apply(lambda x: dt.strftime(dt.fromisoformat(str(x)),'%Y-%m-%d.%H:%M:%S'))

It has removed the '+' sign and gave me the date and time part, but I feel I am doing it wrong because i don't have good knowledge from datetime processing!
My goal is to just get date and time like "2011-10-01 00:38:44" and the type be "datetime" not object as I am still getting!

Body:
After spending some time, these lines solved my problem:

Apply the timezone to the column and convert timestamp to date and time only:

df['timestamp'] = pd.to_datetime(df['timestamp'], utc=True).dt.tz_convert(None)

Remove the timezone without applying it to the column: (My favorite)

df['timestamp'] = pd.to_datetime(df['timestamp']).apply(lambda t: t.replace(tzinfo=None))

OR

df['timestamp'] = pd.to_datetime(df['timestamp']).apply(lambda d: d.strftime('%Y-%m-%d %H:%M:%S'))

You should iterate through each row by using apply function with a lambda expression to use replace function because replace function work with pandas.tslib.Timestampobject not with pandas.core.series.Series. Otherwise, you will end up with this error: TypeError: replace() got an unexpected keyword argument 'tzinfo'


问:
Do all STL containers return their elements by reference?
I am learning STL these days and I was wondering if STL containers return by reference?

e.g:

```<code>vector.first();
map[key];
*vector.begin();
Or any possible return that ends with element (or value type) of container
</code>```

e.g:

```<code>std::vector<int> elements;
elements.push_back(20);
elements[0]=60; // this will also change the value
elements.front() = 23; // even the functions also behave same way like subscript operator
</code>```

is this the case with all containers? or there are some points to consider which I didn't show?

答:
Yes the overloaded [] operator for stl containers return a reference. So in your examples above the values in m and elements will be altered.

From http://www.cplusplus.com/reference/stl/vector/operator%5B%5D/ :

The definition or operator[] for vector is:

```<code>reference operator[] ( size_type n );
const_reference operator[] ( size_type n ) const;
</code>```

Where 'Member types reference and const_reference are the reference types to the elements of the vector container (generally defined as T& and const T& respectively in most storage allocation models).'

Edit: Be aware that not all stl containers have an overloaded [] operator. Those that don't are: list, multimap, multiset, priority_queue, queue, set and stack.

Body:
I am learning STL these days and I was wondering if STL containers return by reference?

e.g:

vector.first();
map[key];
*vector.begin();
Or any possible return that ends with element (or value type) of container

e.g:

std::vector<int> elements;
elements.push_back(20);
elements[0]=60; // this will also change the value
elements.front() = 23; // even the functions also behave same way like subscript operator

is this the case with all containers? or there are some points to consider which I didn't show?

Body:
Yes the overloaded [] operator for stl containers return a reference. So in your examples above the values in m and elements will be altered.

From http://www.cplusplus.com/reference/stl/vector/operator%5B%5D/ :

The definition or operator[] for vector is:

reference operator[] ( size_type n );
const_reference operator[] ( size_type n ) const;

Where 'Member types reference and const_reference are the reference types to the elements of the vector container (generally defined as T& and const T& respectively in most storage allocation models).'

Edit: Be aware that not all stl containers have an overloaded [] operator. Those that don't are: list, multimap, multiset, priority_queue, queue, set and stack.


问:
Is there a way to make nextjs Image have fixed height and responsive width?
I want to render an image with a fixed height and have its width be responsive. With a normal image you just set the height and it will respond

```<code><img src={image} style={{height: 48}} />
</code>```

I was having trouble achieving this with nextjs Image component. I tried some solutions such as these:

```<code><div>
  <Image
    src={image}
    layout="responsive" - only has responsive height
    height={48}
    width={48}
  />
</div>

<div style={{position: "relative"}}> - wasnt responsive and its position was unpredictable
  <Image
    src={image}
    layout="fill"
    objectFit="contain"
    height={48}
  />
</div>
</code>```

Another solution that seemed promising was this but it does not fill the width.

```<code>.company_logo {
  position: relative !important;
  object-fit: contain;
  width: unset !important;
  height: 48px;
}

.company_image {
  width: 100% !important;
}
.company_image div {
  position: unset !important;
}

<Image
  className={styles.company_image}
  src={image}
  alt=""
  layout="fill"
  quality={100}
  priority
/>
</code>```

I'm playing around with a solution using js where I use an image and a ref with 0 opacity, get the dimensions of the image then set to a basic image with dynamic height and width, which should work fine but I'm assuming there is a much simpler solution to this

```<code>const imageRef = useRef(),
      [imageDimensions, setImageDimensions] = useState({ height: 0, width: 0 })

useEffect(() => {
  let height = imageRef.current?.naturalHeight,
      width = imageRef.current?.naturalWidth

  setImageDimensions({ height, width })
}, [])

<img ref={imageRef} src={image} style={{opacity: 0}} />

<Image
  src={image}
  height={imageDimensions.height}
  width={imageDimensions.width}
  quality={100}
  priority
/>
</code>```

答:
Next doesn't provide an method of declaring only an image's height dimension (so that width will be automatically calculated). This makes sense if layout shift in the x-direction is to be prevented, because, otherwise, it would require Next to load the data for every image in order to determine its intrinsic dimensions before it could calculate the width and respond to the requesting user.

A solution to that would be for you to do it yourself if preventing layout shift is that important to you.

If you pursue this, you can optimize the responses by caching each image's dimensions: because you said that you are storing images uploaded by users, you can calculate each image's intrinsic dimensions when you receive it, and then store the image data and its metadata: ID, dimensions, etc. (The ID strategy is up to you, but perhaps it is a hash of the image data.)

Then, when you want to load an image using only a specified height, you can retrieve the dimension metadata for that image and use it to calculate fixed dimensions in your component based on that specified height (using an aspect ratio function). This should be much faster than preloading each image in order to determine its dimensions when requested.

You can calculate the required dimensions from the intrinsic dimensions like this:

TS Playground

type Dimensions = [width: number, height: number];

type DimensionProps = {
  height: number;
  width: number;
};

function getDimensionsFromHeight (
  intrinsicDimensions: Dimensions,
  targetHeight: number,
  roundingStrategy?: 'ceil' | 'floor' | 'round',
): Dimensions {
  const [w, h] = intrinsicDimensions;
  const width = targetHeight * w / h;
  const targetWidth = roundingStrategy ? Math[roundingStrategy](width) : width;
  return [targetWidth, targetHeight];
}

function asProps ([width, height]: Dimensions): DimensionProps {
  return {width, height};
}

// Use:

const {width, height} = asProps(getDimensionsFromHeight([1920, 1080], 48));

```

Body:
I want to render an image with a fixed height and have its width be responsive. With a normal image you just set the height and it will respond

I was having trouble achieving this with nextjs Image component. I tried some solutions such as these:

  <Image
    src={image}
    layout="responsive" - only has responsive height
    height={48}
    width={48}
  />

 - wasnt responsive and its position was unpredictable
  <Image
    src={image}
    layout="fill"
    objectFit="contain"
    height={48}
  />

Another solution that seemed promising was this but it does not fill the width.

.company_logo {
  position: relative !important;
  object-fit: contain;
  width: unset !important;
  height: 48px;
}

.company_image {
  width: 100% !important;
}
.company_image div {
  position: unset !important;
}

<Image
  className={styles.company_image}
  src={image}
  alt=""
  layout="fill"
  quality={100}
  priority
/>

I'm playing around with a solution using js where I use an image and a ref with 0 opacity, get the dimensions of the image then set to a basic image with dynamic height and width, which should work fine but I'm assuming there is a much simpler solution to this

const imageRef = useRef(),
      [imageDimensions, setImageDimensions] = useState({ height: 0, width: 0 })

useEffect(() => {
  let height = imageRef.current?.naturalHeight,
      width = imageRef.current?.naturalWidth

  setImageDimensions({ height, width })
}, [])

<Image
  src={image}
  height={imageDimensions.height}
  width={imageDimensions.width}
  quality={100}
  priority
/>

Body:
Next doesn't provide an method of declaring only an image's height dimension (so that width will be automatically calculated). This makes sense if layout shift in the x-direction is to be prevented, because, otherwise, it would require Next to load the data for every image in order to determine its intrinsic dimensions before it could calculate the width and respond to the requesting user.

A solution to that would be for you to do it yourself if preventing layout shift is that important to you.

If you pursue this, you can optimize the responses by caching each image's dimensions: because you said that you are storing images uploaded by users, you can calculate each image's intrinsic dimensions when you receive it, and then store the image data and its metadata: ID, dimensions, etc. (The ID strategy is up to you, but perhaps it is a hash of the image data.)

Then, when you want to load an image using only a specified height, you can retrieve the dimension metadata for that image and use it to calculate fixed dimensions in your component based on that specified height (using an aspect ratio function). This should be much faster than preloading each image in order to determine its dimensions when requested.

You can calculate the required dimensions from the intrinsic dimensions like this:

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true&ssl=27&ssc=1&pln=1&pc=1#code/C4TwDgpgBAIglgWwgOwM5wPZqgXigbQHc4ATYACwC4pkBXBAIwgCcAaKciOAc3OGrqMWAXQDcAKHGhIsRCnRYACswxhUuKAG9xUDl178a9Jswm7iZKkaGnxAXwniAZrWQBjYJmRRuEYPCQ0L1QAMRUEAAl9PigACh0oOGRgZiT0NwD5YOpMoKxUVgTgAENmX2Aonj4BYxZC3RVXEiTuAGUU4uAIbhAAfmoAcjcuABsBqAAfKAGnEYwMZnGpgcbkEgHCgEocuTzsbV03fOACQnZyYQ0klLS4DN2FNDMoI7QTiwoNErK-SoMoABUUEIUAA9Bxnq9UCdvuUAOqkT54VbNZBtDpdHpQXpQACynXI+BRLXazE63RAwliH3Imyg1Bpz2YflozG8+FhfgRlnYnIq0WAYnskhc7k8WCgxVQylU6liRER5HOAuEO0Cj1Q21k6q8MrUWgSzOArO8mhpyqqwAcwskoPBAFVUBBKJIoSczYqLQY7BopXrULFyrkNWEMJEBfKAIwATgATAAGdiR+MADnjwnYABYU5tNo5xHaoAAVCDQ1Au5yuDxeSWoJ3MYAAUQAjrRiiN1AAeIsAPlixQ8bZG1CL7AgAA9IB4ICQR1qAG4YUgG3RwJxxAfG9tQACEODwE6nXRIdIOuigFBUIOQEBBjeYKmYsQABgA1du0Us0DAnCCt9sADrII2k4QNOs5QAAJJoh5gcedhAQASmBXDzjO1DQZuQ52M+eYJHYNpuokySpEEbhqlk+QaPgMYJkmqbphIRF8n8MR4NmjiitWErwoqcTEmipLkj0-RQIopTFEgXTMKgnbSBAGDrkGDzBKG4aWj2+CxsIp6GiybI+H4waqeErHALE1ykekvKlOUZnsAJ6JkpiICbPgjE2lK9ZNv+HaBlyiqxJs7CxCmACsUAANRxJGYJQAAzLmeFeSwPlDgGvGWLEKwYE0AzBVA4XJXWqUtul-nANyFDZbM8yLAVRUSClDZle2GUBVlQyjPl7ApgAbHhUIYCMEAAHRzNw2UAPIANY7vlEhAA" rel="nofollow noreferrer">TS Playground

type Dimensions = [width: number, height: number];

type DimensionProps = {
  height: number;
  width: number;
};

function getDimensionsFromHeight (
  intrinsicDimensions: Dimensions,
  targetHeight: number,
  roundingStrategy?: 'ceil' | 'floor' | 'round',
): Dimensions {
  const [w, h] = intrinsicDimensions;
  const width = targetHeight * w / h;
  const targetWidth = roundingStrategy ? Math[roundingStrategy](width) : width;
  return [targetWidth, targetHeight];
}

function asProps ([width, height]: Dimensions): DimensionProps {
  return {width, height};
}

// Use:

const {width, height} = asProps(getDimensionsFromHeight([1920, 1080], 48));


问:
Isn't findAll() iterator inefficient to assert an unprecedented case in the Database?
I am a newbie constructing persistence APIs with Spring Boot, so I came about this doubt. I don't want the user to be able to register two different Accounts with the same Email. But I also don't want to use Email as primary key in the repo. So, I think the logic is quite self-explanatory.

```<code>private static boolean isRegisteredEmail(String email, AccountRepository accountRepository) {
    for ( Account account : accountRepository.findAll() ) {
        if ( account.getEmail().equals(email) ) {
            return true;
        }
    }
    return false;
}
</code>```

This works, but I start to wonder: if you get a real-case situation, like Facebook's DB in which you have almost 3 billion registers, how do you deal with this scenario? Am I overconcerning, or there's really no chance this can keep being done efficiently?

答:
The method findAll() is indeed inefficient to assert an unprecedented case in the database. To understand why it is so, we have to understand in terms of performance.

Performance of any application has many facets to it. But lets tone it down to Time and Space for now.

Issue in the implementation

Loop (Time): The implementation has a condition check inside the loop. So the condition is validated till it finds a match. If match is not found it loops till the list is exhausted. So, best case O(1) but it can reach to O(N) for no match. It can increase further if we have multiple condition checks.

Database (Space): After the database call all the records are kept in memory till we are processing. Fetching only the email ids from database could have helped but here we have the complete Account data stored in memory.

Query (Time & Space): The code is fetching records with the query whenever anyone tries to register. Let say if 100K register everyday, then almost similar data is fetched every time.

Improvements

Query for Unique Emails Ids: Query should fetch only unique email Ids. By this we will save space as well as time. Less space because only Email id is saved rather than whole Account data. For this you can use either JPA or native query.

Repository layer

```<code>    String findByEmailId(String emailId);
</code>```
```<code>    @Query(nativeQuery = true, value="select email_Id from account a where a.email_Id = :emailId")
    String findEmailId(String emailId);
</code>```

  But above depends on database performance too.

Cache: Database operations are costly. It always good to maintain a Cache. Rather than fetching data from DB every time. Cache should have a refresh time and should be updated when a new record is inserted in DB. Cache operation is O(1).

Unique Constraint: It's not always optimal to perform validation in code because we have to query all the records and loop on them to validate. This uses a lot of network traffic and space. So, its good to have a unique constraint, because Database can check and return response very fast whenever constraint is violated.

Loop a list or Map: If our use case requires us to perform a loop, then its better to loop in List or Map because O(1) time complexity is for both list.indexOf(obj) and map.get(obj).

```<code>    List<String> emailIdList = accountRepository.findAllByEmailId();
    if(emailIdList.indexOf(email)> 0) return true;
</code>```

Database Type: If it is mandatory to fetch data every time from Db, then its good to query from a No-Sql db as they have very fast retrieval time. The data is stored based on index. Many have Tree type data structure for storage.

Body:
I am a newbie constructing persistence APIs with Spring Boot, so I came about this doubt. I don't want the user to be able to register two different Accounts with the same Email. But I also don't want to use Email as primary key in the repo. So, I think the logic is quite self-explanatory.

private static boolean isRegisteredEmail(String email, AccountRepository accountRepository) {
    for ( Account account : accountRepository.findAll() ) {
        if ( account.getEmail().equals(email) ) {
            return true;
        }
    }
    return false;
}

This works, but I start to wonder: if you get a real-case situation, like Facebook's DB in which you have almost 3 billion registers, how do you deal with this scenario? Am I overconcerning, or there's really no chance this can keep being done efficiently?

Body:
The method findAll() is indeed inefficient to assert an unprecedented case in the database. To understand why it is so, we have to understand in terms of performance.

Performance of any application has many facets to it. But lets tone it down to Time and Space for now.

Issue in the implementation

Loop (Time): The implementation has a condition check inside the loop. So the condition is validated till it finds a match. If match is not found it loops till the list is exhausted. So, best case O(1) but it can reach to O(N) for no match. It can increase further if we have multiple condition checks.

Database (Space): After the database call all the records are kept in memory till we are processing. Fetching only the email ids from database could have helped but here we have the complete Account data stored in memory.

Query (Time & Space): The code is fetching records with the query whenever anyone tries to register. Let say if 100K register everyday, then almost similar data is fetched every time.

Improvements

Query for Unique Emails Ids: Query should fetch only unique email Ids. By this we will save space as well as time. Less space because only Email id is saved rather than whole Account data. For this you can use either JPA or native query.

Repository layer

    String findByEmailId(String emailId);

    @Query(nativeQuery = true, value="select email_Id from account a where a.email_Id = :emailId")
    String findEmailId(String emailId);

  But above depends on database performance too.

Cache: Database operations are costly. It always good to maintain a Cache. Rather than fetching data from DB every time. Cache should have a refresh time and should be updated when a new record is inserted in DB. Cache operation is O(1).

Unique Constraint: It's not always optimal to perform validation in code because we have to query all the records and loop on them to validate. This uses a lot of network traffic and space. So, its good to have a unique constraint, because Database can check and return response very fast whenever constraint is violated.

Loop a list or Map: If our use case requires us to perform a loop, then its better to loop in List or Map because O(1) time complexity is for both list.indexOf(obj) and map.get(obj).

    List<String> emailIdList = accountRepository.findAllByEmailId();
    if(emailIdList.indexOf(email)> 0) return true;

Database Type: If it is mandatory to fetch data every time from Db, then its good to query from a No-Sql db as they have very fast retrieval time. The data is stored based on index. Many have Tree type data structure for storage.


问:
WPF binding window title to a checkbox state
I have a checkbox which looks something like this (have removed many things to make it short) -

<CheckBox IsChecked="{Binding functionABC, Mode=TwoWay}">

</CheckBox>
```

Now, I have to map the window title of app to 2 different values depending on checked or unchecked. I could have done it normally, but there is a trigger set already for both states, and I don't know how to work around it.

答:
You can use an special IValueConverter

```<code>public class BooleanToCustomConverter : MarkupExtension, IValueConverter
{
    public string? TrueValue { get; set; }
    public string? FalseValue { get; set; }

    public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool b)
            return b ? TrueValue : FalseValue;
        return Binding.DoNothing;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}
</code>```

and use that within your Binding

<Window
  ...
  Title="{Binding functionABC, Mode=OneWay, Converter={local:BooleanToCustomConverter TrueValue='True Value', FalseValue='False Value'}}"
  ...>

  ...

</Window>
```

sample project on github

Body:
I have a checkbox which looks something like this (have removed many things to make it short) -

<CheckBox IsChecked="{Binding functionABC, Mode=TwoWay}">

</CheckBox>

Now, I have to map the window title of app to 2 different values depending on checked or unchecked. I could have done it normally, but there is a trigger set already for both states, and I don't know how to work around it.

Body:
You can use an special IValueConverter

public class BooleanToCustomConverter : MarkupExtension, IValueConverter
{
    public string? TrueValue { get; set; }
    public string? FalseValue { get; set; }

    public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool b)
            return b ? TrueValue : FalseValue;
        return Binding.DoNothing;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

and use that within your Binding

<Window
  ...
  Title="{Binding functionABC, Mode=OneWay, Converter={local:BooleanToCustomConverter TrueValue='True Value', FalseValue='False Value'}}"
  ...>

  ...

</Window>

sample project on github


问:
ffmpeg timeout with rtsp
I have script that capture image from wifi camera with ffmpeg.
It works fine until camera is not reachable due to network troubles.
The script stuck in ffmpeg capture and never exit. Is it possible to have some kind of timeout? -stimeout (in miliseconds) seems not working.

There is part of script that capture images. (there are some manipulation after that)

```<code>#!/bin/bash
week="$(date '+%Y_%U')"
ts="$(date '+%Y-%m-%d_%H:%M:%S')"
ffmpeg -rtsp_transport tcp -y -i "rtsp://192.168.64.101" -frames:v 1 $week/$ts.jpg -stimeout 3000 -y
</code>```

I did test on other camera and results are:

```<code>ffmpeg -y -i "rtsp://192.168.64.112:8554/profile0" -frames:v 1 Ilatest.jpg
</code>```

Does work OK, but with timeout of 5 seconds as

```<code>ffmpeg -timeout 5000000 -y -i "rtsp://192.168.64.112:8554/profile0" -frames:v 1 Ilatest.jpg
</code>```

doesn't and I got error report as:

```<code>ffmpeg version 4.2.4-1ubuntu0.1 Copyright (c) 2000-2020 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-10ubuntu2)
...
...
[rtsp @ 0x55d250488740] Unable to open RTSP for listening
rtsp://192.168.64.112:8554/profile0: Cannot assign requested address
</code>```

答:
RTSP Protocol Documentation indicates there is timeout option. I'd try:

```<code>ffmpeg -rtsp_transport tcp -stimeout 3000 -y -i "rtsp://192.168.64.101" ...
</code>```

Title: ffmpeg timeout with rtsp

Body:
I have script that capture image from wifi camera with ffmpeg.
It works fine until camera is not reachable due to network troubles.
The script stuck in ffmpeg capture and never exit. Is it possible to have some kind of timeout? -stimeout (in miliseconds) seems not working.

There is part of script that capture images. (there are some manipulation after that)

#!/bin/bash
week="$(date '+%Y_%U')"
ts="$(date '+%Y-%m-%d_%H:%M:%S')"
ffmpeg -rtsp_transport tcp -y -i "rtsp://192.168.64.101" -frames:v 1 $week/$ts.jpg -stimeout 3000 -y

I did test on other camera and results are:

ffmpeg -y -i "rtsp://192.168.64.112:8554/profile0" -frames:v 1 Ilatest.jpg

Does work OK, but with timeout of 5 seconds as

ffmpeg -timeout 5000000 -y -i "rtsp://192.168.64.112:8554/profile0" -frames:v 1 Ilatest.jpg

doesn't and I got error report as:

ffmpeg version 4.2.4-1ubuntu0.1 Copyright (c) 2000-2020 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-10ubuntu2)
...
...
[rtsp @ 0x55d250488740] Unable to open RTSP for listening
rtsp://192.168.64.112:8554/profile0: Cannot assign requested address

Body:
RTSP Protocol Documentation indicates there is timeout option. I'd try:

ffmpeg -rtsp_transport tcp -stimeout 3000 -y -i "rtsp://192.168.64.101" ...


问:
java.lang.NoSuchMethodError: 'com.google.common.collect.ImmutableMap error when trying to execute tests using Chromedriver and Maven
I am new to selenium tests and I am currently watching some youtube videos using maven.

Today I tried a few codes and worked fine but when accessing one store page and trying to search a product it gives me "Access Denied" message
So I tried a few ways to open chrome instead of chromedriver.

But I gave up and was willing to try another webpage. But now chromedriver wont open (gives error message). operadriver, geckodriver and etc will immediately close after launch.

I am getting this error:

```<code>java.lang.NoSuchMethodError: 'com.google.common.collect.ImmutableMap com.google.common.collect.ImmutableMap.of(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)'
</code>```

I tried looking in a lot of places but most said it was guava version, I dont use guava, even though I tried adding it to dependencies...

My code is this:

```<code>public class TestYoutubeClass {
    WebDriver driver;
    @Before
    public void runDriver(){
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.kabum.com.br");
</code>```

I tried starting from the beginning and nothing worked.
I am using IntelliJ
On pom.xml I added: junit; selenium-java and webdrivermanager.

Every help is really appreciated.

答:
This error message...

```<code>java.lang.NoSuchMethodError: 'com.google.common.collect.ImmutableMap com.google.common.collect.ImmutableMap.of(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)'
</code>```

...implies that there is NoSuchMethod as com.google.common.collect.ImmutableMap which indicates it might be corrupted or there is some incompatibility between the version of the binaries you are using specifically with the guava version / dependency (maven).

You need to take care of a couple of things as follows:

You need to add the System.setProperty():

```<code>System.setProperty("webdriver.gecko.driver","C:\\Program Files\\Java\\jre1.8.0_231\\lib\\ext\\geckodriver.exe");
</code>```

Use only a single instance of WebDriver, either from the class scope or from the method scope.

Effectively, you line of code will be;

```<code>public class TestYoutubeClass {
    WebDriver driver;
    @Before
    public void runDriver(){
        System.setProperty("webdriver.chrome.driver","/path/to/chromedriver");
        driver = new ChromeDriver();
        driver.get("http://www.kabum.com.br");
</code>```

Incase you are using maven deleting the corrupt/incompatible .m2 folder can solve your issue.

Body:
I am new to selenium tests and I am currently watching some youtube videos using maven.

Today I tried a few codes and worked fine but when accessing one store page and trying to search a product it gives me "Access Denied" message
So I tried a few ways to open chrome instead of chromedriver.

But I gave up and was willing to try another webpage. But now chromedriver wont open (gives error message). operadriver, geckodriver and etc will immediately close after launch.

I am getting this error:

java.lang.NoSuchMethodError: 'com.google.common.collect.ImmutableMap com.google.common.collect.ImmutableMap.of(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)'

I tried looking in a lot of places but most said it was guava version, I dont use guava, even though I tried adding it to dependencies...

My code is this:

public class TestYoutubeClass {
    WebDriver driver;
    @Before
    public void runDriver(){
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.kabum.com.br");

I tried starting from the beginning and nothing worked.
I am using IntelliJ
On pom.xml I added: junit; selenium-java and webdrivermanager.

Every help is really appreciated.

Body:
This error message...

java.lang.NoSuchMethodError: 'com.google.common.collect.ImmutableMap com.google.common.collect.ImmutableMap.of(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)'

...implies that there is NoSuchMethod as com.google.common.collect.ImmutableMap which indicates it might be corrupted or there is some incompatibility between the version of the binaries you are using specifically with the guava version / dependency (maven).

You need to take care of a couple of things as follows:

You need to add the System.setProperty():

System.setProperty("webdriver.gecko.driver","C:\\Program Files\\Java\\jre1.8.0_231\\lib\\ext\\geckodriver.exe");

Use only a single instance of WebDriver, either from the class scope or from the method scope.

Effectively, you line of code will be;

public class TestYoutubeClass {
    WebDriver driver;
    @Before
    public void runDriver(){
        System.setProperty("webdriver.chrome.driver","/path/to/chromedriver");
        driver = new ChromeDriver();
        driver.get("http://www.kabum.com.br");

Incase you are using maven deleting the corrupt/incompatible .m2 folder can solve your issue.


问:
Add rows to Google Sheets sheet if not enough
I have a bunch of data that I routinely use a Python script to back up into a Google Sheets sheet. It's currently at 5385 rows filled with 6041 total. I know that if I try to upload more than 6041 rows the update will fail, but I know that I can fix this by opening up the sheet, scrolling all the way to the bottom, and then clicking "All 1000 more rows at bottom" a few times.

Is there a way for googleapiclient to automatically make sure that there's room in the sheet?

Edit:

```<code>        cells = 'Backup!A{}:{}{}'.format(start_ind, self._excel_column_index(len(headers)), start_ind + len(to_cache) + 1)

        values = self._excel_serialize_arb_array(to_cache, headers)
        data = {'values':values}
        self.sheet.values().update(spreadsheetId=self.spreadsheet_ids['FOO'],
                        range=cells, valueInputOption='USER_ENTERED',
                        body=data).execute()
</code>```

答:
Here's my solution coded up.</p>
```<code>def get_and_update_sheet_properties(self, min_rows):
    ''' Ensure we have enough rows for our arbs cache. '''
    sized_sheets = self.sheet.get(spreadsheetId=self.spreadsheet_ids['FOO'],
                                  fields="sheets(properties(title,gridProperties(columnCount,rowCount)))").execute()
    arb_sheet = [sized_sheet for sized_sheet in sized_sheets['sheets'] if sized_sheet['properties']['title'] == 'BAR'][0]
    cur_rows = arb_sheet['properties']['gridProperties']['rowCount']
    padded_rows = min_rows - (min_rows % 100) + 200
    if padded_rows > cur_rows:
        requests = {
                "updateSheetProperties": {
                    "properties": {
                        "sheetId": 1922941665,
                        'gridProperties': {
                          'rowCount': padded_rows,
                          'columnCount': 26
                        },
                    },
                    "fields": "gridProperties",
                }
            }
        body = {
            'requests': requests
        }
        self.sheet.batchUpdate(spreadsheetId=self.spreadsheet_ids['FOO'], body=body).execute()
        return True
    else:
        return False
</code>```

Body:
I have a bunch of data that I routinely use a Python script to back up into a Google Sheets sheet. It's currently at 5385 rows filled with 6041 total. I know that if I try to upload more than 6041 rows the update will fail, but I know that I can fix this by opening up the sheet, scrolling all the way to the bottom, and then clicking "All 1000 more rows at bottom" a few times.

Is there a way for googleapiclient to automatically make sure that there's room in the sheet?

Edit:

        cells = 'Backup!A{}:{}{}'.format(start_ind, self._excel_column_index(len(headers)), start_ind + len(to_cache) + 1)

        values = self._excel_serialize_arb_array(to_cache, headers)
        data = {'values':values}
        self.sheet.values().update(spreadsheetId=self.spreadsheet_ids['FOO'],
                        range=cells, valueInputOption='USER_ENTERED',
                        body=data).execute()

Body:
Here's my solution coded up.

def get_and_update_sheet_properties(self, min_rows):
    ''' Ensure we have enough rows for our arbs cache. '''
    sized_sheets = self.sheet.get(spreadsheetId=self.spreadsheet_ids['FOO'],
                                  fields="sheets(properties(title,gridProperties(columnCount,rowCount)))").execute()
    arb_sheet = [sized_sheet for sized_sheet in sized_sheets['sheets'] if sized_sheet['properties']['title'] == 'BAR'][0]
    cur_rows = arb_sheet['properties']['gridProperties']['rowCount']
    padded_rows = min_rows - (min_rows % 100) + 200
    if padded_rows > cur_rows:
        requests = {
                "updateSheetProperties": {
                    "properties": {
                        "sheetId": 1922941665,
                        'gridProperties': {
                          'rowCount': padded_rows,
                          'columnCount': 26
                        },
                    },
                    "fields": "gridProperties",
                }
            }
        body = {
            'requests': requests
        }
        self.sheet.batchUpdate(spreadsheetId=self.spreadsheet_ids['FOO'], body=body).execute()
        return True
    else:
        return False


问:
c++ code structure into html files
I work on unix.
I have my complete source code in unix in the form of building blocks and modules.
Like headers,sources files,make files etc.
I can copy all the files with the same directory structure to windows.
I need some tool which will convert all the source to html tags with all the links to functions,variables,classes,headers.There should be some tool to do this easily.
by this way it would be easy for debugging the code in a fast way.

Is anybody aware of such tool?

答:
The term you're probably looking for is "documentation generator".  You're specifically interested in ones that output HTML files.

Doxygen is popular, but if you want a master comparison list of documentation generators Wikipedia has a summary:

http://en.wikipedia.org/wiki/Comparison_of_documentation_generators

Looking at the output generated by the different programs (on projects that use them) will probably inform your choice of which meets your needs.

Title: c++ code structure into html files


问:
Creating or using a telegram bot that forward messages received from a bot to another account
I'm new to telegram bot (especially programming one).

Is there a bot that can forward a message from another bot to a second account?
Where the second account is not the admin of the bot writing.

Alternatevely, is there a way to create one?
I'm pretty skilled in Python but I get a little bit lost on using a Python script to make a bot work.

I'm working on a Windows 11 environment

答:
Install Telethon

```<code>python3 -m pip install --upgrade pip
python3 -m pip install --upgrade telethon
</code>```

Obtain your API_ID and API_TOKEN from Telegram

And then replace your values and run the code:

from telethon import TelegramClient, events
import asyncio
import logging
logging.basicConfig(level=logging.WARNING)

api_id = # don't forget to fill this
api_hash = '' # don't forget to fill this

client = TelegramClient("forwarder", api_id, api_hash)
client.start()

from_chat_id = # don't forget to fill this
to_chat_id = "me"

async def get_chat_id(title):
    async for dialog in client.iter_dialogs():
        if dialog.title == title:
            return dialog.id

@client.on(events.NewMessage)
async def my_event_handler(event):
    chat = await event.get_chat()
    if chat.id == from_chat_id:
        await client.forward_messages(to_chat_id, event.message)

# asyncio.get_event_loop().run_until_complete(get_chat_id("YOUR CHAT TITLE"))
asyncio.get_event_loop().run_forever()

```
<p><code>from_chat_id</code> will be the chat id of the bot you want to forward message from.</p>
<p><code>to_chat_id</code> will be the destination chat id. using <code>'me'</code> would forward the message to your saved messages.</p>
<p>Another thing to note is this code:</p>
<pre class="lang-py prettyprint-override"><code>asyncio.get_event_loop().run_until_complete(get_chat_id("YOUR CHAT TITLE"))
</code>```

if you want to get the id of a chat you can uncomment this line and pass your chat title.

Body:
Install Telethon

python3 -m pip install --upgrade pip
python3 -m pip install --upgrade telethon

Obtain your API_ID and API_TOKEN from Telegram

And then replace your values and run the code:

from telethon import TelegramClient, events
import asyncio
import logging
logging.basicConfig(level=logging.WARNING)

api_id = # don't forget to fill this
api_hash = '' # don't forget to fill this

client = TelegramClient("forwarder", api_id, api_hash)
client.start()

from_chat_id = # don't forget to fill this
to_chat_id = "me"

async def get_chat_id(title):
    async for dialog in client.iter_dialogs():
        if dialog.title == title:
            return dialog.id

@client.on(events.NewMessage)
async def my_event_handler(event):
    chat = await event.get_chat()
    if chat.id == from_chat_id:
        await client.forward_messages(to_chat_id, event.message)

# asyncio.get_event_loop().run_until_complete(get_chat_id("YOUR CHAT TITLE"))
asyncio.get_event_loop().run_forever()

from_chat_id will be the chat id of the bot you want to forward message from.

to_chat_id will be the destination chat id. using 'me' would forward the message to your saved messages.

Another thing to note is this code:

asyncio.get_event_loop().run_until_complete(get_chat_id("YOUR CHAT TITLE"))

if you want to get the id of a chat you can uncomment this line and pass your chat title.


问:
How can I resolve the tailscale HTTPS error "SSL_ERROR_RX_RECORD_TOO_LONG"
I just setup MagicDNS and HTTPS on my tailscale account.
Then I ssh'ed into my nas and issued a tls certificate with

```<code>sudo tailscale cert "machinename.tailnetalias.ts.net"
</code>```

Response was:

```<code>Wrote private key to machinename.tailnetalias.ts.net.crt
Wrote private key to machinename.tailnetalias.ts.net.key
</code>```

Now when I try to access the web interface of my nas via https:// in a browser, I get an error. Firefox for example says "SSL_ERROR_RX_RECORD_TOO_LONG".

What can I do about this?

答:
The tailscale cert command doesn't know where the certificate files should be installed (it doesn't even know what you were planning to do with them). So the first question is: did you move those files somewhere to install them? If not, the certificate getting SSL_ERROR_RX_RECORD_TOO_LONG is likely some other cert file which was already there.

If the tailscale cert files did get installed, I think the next step would be to click on the lock icon in Firefox on the left side of the URL. It will have a bunch of information about the TLS connection, in particular:

if the certificate had something wrong with it

in the Technical Details section, it will say what TLS version was used (SSL2, SSL3, TLS1.0, TLS1.1, TLS1.2, TLS1.3).

The SSL_ERROR_RX_RECORD_TOO_LONG error was mostly a problem in older versions of TLS like 1.1 and before. If the TLS version is one of those, it may be necessary to figure out how to get the NAS to stop offering the older versions and only offer 1.2 and 1.3.

Body:
I just setup MagicDNS and HTTPS on my tailscale account.
Then I ssh'ed into my nas and issued a tls certificate with

sudo tailscale cert "machinename.tailnetalias.ts.net"

Response was:

Wrote private key to machinename.tailnetalias.ts.net.crt
Wrote private key to machinename.tailnetalias.ts.net.key

Now when I try to access the web interface of my nas via https:// in a browser, I get an error. Firefox for example says "SSL_ERROR_RX_RECORD_TOO_LONG".

What can I do about this?


问:
how can i redirect my error message from console to file in Python
I need to redirect my error message from the console to a file. For this example, I need to insert the error message into a file:

```<code>Traceback (most recent call last):
  File "C:/Users/", line 5, in <module>
    1/0
ZeroDivisionError: division by zero"
</code>```

I have already tried to do something like this:

```<code>from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    with redirect_stdout(f):
        1/0
        print('here is my error')
</code>```

答:
Note: This assumes you're using Bash. I see that you are using Windows, so it's likely that you aren't using Bash. But from what I've read, this should still be applicable if you are using Cmd.exe, it's just that the syntax might be slightly different.

I think it's better to handle error message output outside of your script. Your script should attempt to do the "happy path" work and print an error to stderr if something goes wrong. This is what should happen by default in every programming language. Python gets this right.

Here is an example script:

print("Dividing by 0 now, I sure hope this works!")

1/0

print("Holy cow, it worked!")
```
<p>If I run this script, the first line prints to stdout, and then the ZeroDivisionError output prints to stderr:</p>
```$ python /tmp/script.py
Dividing by 0 now, I sure hope this works!
Traceback (most recent call last):
  File "/tmp/script.py", line 3, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero
```
<p>If I want to run the script and collect any error output in a file, I can use redirection in my shell when I run the command:</p>
```$ python /tmp/script.py 2> /tmp/errors.txt
Dividing by 0 now, I sure hope this works!

$ cat /tmp/errors.txt
Traceback (most recent call last):
  File "/tmp/script.py", line 3, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero
```

Body:
I need to redirect my error message from the console to a file. For this example, I need to insert the error message into a file:

Traceback (most recent call last):
  File "C:/Users/", line 5, in <module>
    1/0
ZeroDivisionError: division by zero"

I have already tried to do something like this:

from contextlib import redirect_stdout

with open('error.txt', 'w') as f:
    with redirect_stdout(f):
        1/0
        print('here is my error')

Body:
Note: This assumes you're using Bash. I see that you are using Windows, so it's likely that you aren't using Bash. But from what I've read, this should still be applicable if you are using Cmd.exe, it's just that the syntax might be slightly different.

I think it's better to handle error message output outside of your script. Your script should attempt to do the "happy path" work and print an error to stderr if something goes wrong. This is what should happen by default in every programming language. Python gets this right.

Here is an example script:

print("Dividing by 0 now, I sure hope this works!")

1/0

print("Holy cow, it worked!")

If I run this script, the first line prints to stdout, and then the ZeroDivisionError output prints to stderr:

$ python /tmp/script.py
Dividing by 0 now, I sure hope this works!
Traceback (most recent call last):
  File "/tmp/script.py", line 3, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

If I want to run the script and collect any error output in a file, I can use redirection in my shell when I run the command:

$ python /tmp/script.py 2> /tmp/errors.txt
Dividing by 0 now, I sure hope this works!

$ cat /tmp/errors.txt
Traceback (most recent call last):
  File "/tmp/script.py", line 3, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero


问:
Set environment variable in kubernetes secret
When using Kubernetes .yml files, I can do the following:

$ cat configmap.yml

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  foo: ${FOO}
  bar: ${BAR}
  static: doesNotChange

$ export FOO=myFooVal
$ export BAR=myBarVal
$ cat configmap.yml | envsubst | kubectl apply -f -
```

This would replace ${FOO} and ${BAR} in the configmap.yml file before actually applying the file to the cluster.

How could I achieve the very same behavior with a Kubernetes secret which has it's data values base64 encoded?

I would need to read all the keys in the data: field, decode the values, apply the environment variables and encode it again.

A tool to decode and encode the data: values inplace would be much appreciated.

答:
It is actually possible, to store the secret.yml with stringData instead of data which allows to keep the files in plain text (SOPS encryption is still possible and encouraged)

```<code>$ cat secret.yml

apiVersion: v1
kind: Secret
metadata:
  name: test-secret
  namespace: default
type: Opaque
stringData:
  dotenv: |
    DATABASE_URL="postgresql://test:test@localhost:5432/test?schema=public"
    API_PORT=${PORT}
    FOO=${FOO}
    BAR=${BAR}

$ export PORT=80
$ export FOO=myFooValue
$ export BAR=myBarValue
$ cat secret.yml | envsubst | kubectl apply -f -
</code>```

A plus is for sure, that this not only allows for creation of the secret, but updating is also possible.

Just for documentation, here would be the full call with SOPS:

```<code>$ sops --decrypt secret.enc.yml | envsubst | kubectl apply -f -
</code>```

Body:
When using Kubernetes .yml files, I can do the following:

$ cat configmap.yml

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  foo: ${FOO}
  bar: ${BAR}
  static: doesNotChange

$ export FOO=myFooVal
$ export BAR=myBarVal
$ cat configmap.yml | envsubst | kubectl apply -f -

This would replace ${FOO} and ${BAR} in the configmap.yml file before actually applying the file to the cluster.

How could I achieve the very same behavior with a Kubernetes secret which has it's data values base64 encoded?

I would need to read all the keys in the data: field, decode the values, apply the environment variables and encode it again.

A tool to decode and encode the data: values inplace would be much appreciated.

Body:
It is actually possible, to store the secret.yml with stringData instead of data which allows to keep the files in plain text (SOPS encryption is still possible and encouraged)

$ cat secret.yml

apiVersion: v1
kind: Secret
metadata:
  name: test-secret
  namespace: default
type: Opaque
stringData:
  dotenv: |
    DATABASE_URL="postgresql://test:test@localhost:5432/test?schema=public"
    API_PORT=${PORT}
    FOO=${FOO}
    BAR=${BAR}

$ export PORT=80
$ export FOO=myFooValue
$ export BAR=myBarValue
$ cat secret.yml | envsubst | kubectl apply -f -

A plus is for sure, that this not only allows for creation of the secret, but updating is also possible.

Just for documentation, here would be the full call with SOPS:

$ sops --decrypt secret.enc.yml | envsubst | kubectl apply -f -


问:
Plugin not reloading in development mode
I am having a weird problem with a plugin I wrote. What is weird is that I have one other plugin that opens various ActiveRecord classes and it has no problems auto-reloading.

In the plugins init.rb file I have

```<code>User.class_eval do
  has_one :reputation
  include Karma
  alias :rep :reputation
end
</code>```

If I run it in production mode or in rails console there are no issues. When I run it in development it does load it once, but never again unless I restart the server.

I couldn't find anything special in the other plugin I am using(acts_as_readable) and it opens User in the same manner.

Edit:

I did:

```<code>ActiveRecord::Base.class_eval do
  class << self
    def has_karma_values
      has_one :reputation
      alias :rep :reputation
    end
  end
end
</code>```

in the plugiin's init.rb file and did

```<code>class User < ActiveRecord::Base
...
has_karma_values
...
end
</code>```

And get the same error about has_karma_values not existing. The plugin hasn't been loaded at this point.

What is confusing is that acts-as-readable has no issues at all with

```<code>User.class_eval do
  has_many :readings
end

ActiveRecord::Base.send :include, ActiveRecord::Acts::Readable
</code>```

but yet mine does.

Here is my complete init.rb file

```<code>require 'reputation'
require 'karma_name'
require 'karma_tag'
require 'karma_title'
require 'acts_as_karmable'
require 'karma'
require File.expand_path('../lib/generators/karma_generator', __FILE__)

KarmaTitle.setup 'Default'

ActiveRecord::Base.class_eval do
  class << self
    def has_karma_values
      has_one :reputation
      alias :rep :reputation
    end
  end
end

ActiveRecord::Base.send :include, ActiveRecord::Acts::Karmable
</code>```

Here is the error /home/david/apps/ruby/lib/ruby/gems/1.9.1/gems/activerecord-3.0.9/lib/active_record/base.rb:1014:inmethod_missing': undefined local variable or method has_karma_values' for #<Class:0x9ad1b24> (NameError)

答:
The init file is loaded once, you should not access your models from your plugin, it should be the other way around, your init file should probably be like this:

```<code>ActiveRecord::Base.class_eval do
  class << self
    def acts_as_readable
      has_one :reputation
      include Karma
      alias :rep :reputation
    end
  end
end
</code>```

And at your user.rb file you should do it like this:

```<code>class User < ActiveRecord::Base
  acts_as_readable
end
</code>```

And this should give you the functionality you expect.

Body:
I am having a weird problem with a plugin I wrote. What is weird is that I have one other plugin that opens various ActiveRecord classes and it has no problems auto-reloading.

In the plugins init.rb file I have

User.class_eval do
  has_one :reputation
  include Karma
  alias :rep :reputation
end

If I run it in production mode or in rails console there are no issues. When I run it in development it does load it once, but never again unless I restart the server.

I couldn't find anything special in the other plugin I am using(acts_as_readable) and it opens User in the same manner.

Edit:

I did:

ActiveRecord::Base.class_eval do
  class << self
    def has_karma_values
      has_one :reputation
      alias :rep :reputation
    end
  end
end

in the plugiin's init.rb file and did

class User < ActiveRecord::Base
...
has_karma_values
...
end

And get the same error about has_karma_values not existing. The plugin hasn't been loaded at this point.

What is confusing is that acts-as-readable has no issues at all with

User.class_eval do
  has_many :readings
end

ActiveRecord::Base.send :include, ActiveRecord::Acts::Readable

but yet mine does.

Here is my complete init.rb file

require 'reputation'
require 'karma_name'
require 'karma_tag'
require 'karma_title'
require 'acts_as_karmable'
require 'karma'
require File.expand_path('../lib/generators/karma_generator', __FILE__)

KarmaTitle.setup 'Default'

ActiveRecord::Base.class_eval do
  class << self
    def has_karma_values
      has_one :reputation
      alias :rep :reputation
    end
  end
end

ActiveRecord::Base.send :include, ActiveRecord::Acts::Karmable

Here is the error /home/david/apps/ruby/lib/ruby/gems/1.9.1/gems/activerecord-3.0.9/lib/active_record/base.rb:1014:inmethod_missing': undefined local variable or method has_karma_values' for #<Class:0x9ad1b24> (NameError)

Body:
The init file is loaded once, you should not access your models from your plugin, it should be the other way around, your init file should probably be like this:

ActiveRecord::Base.class_eval do
  class << self
    def acts_as_readable
      has_one :reputation
      include Karma
      alias :rep :reputation
    end
  end
end

And at your user.rb file you should do it like this:

class User < ActiveRecord::Base
  acts_as_readable
end

And this should give you the functionality you expect.


问:
What's the default number of clients camel application can handle
I have a spring boot application that uses cxf camel routes, I didn't do any special configurations, entry point is http://0.0.0.0. My question is what is the maximum number of clients that my application is able to handle concurrently without any customizations? And what should I do and where if for example the defaults are insufficient?</p>

答:
It s about your web server. if you are use quarkus + camel  quarkus use vert.x in background. you must configure vert.x and this parameters are  vertx.eventloops.poolsize and vert.worker thread size. if you are use quarkus+spring boot. spring boot uses tomcat in default . u can use undertow or jetty.its tomcat parameters</p>
```<code>server:
  tomcat:
    threads:
      max: 300
      min-spare: 60
</code>```

Body:
It s about your web server. if you are use quarkus + camel  quarkus use vert.x in background. you must configure vert.x and this parameters are  vertx.eventloops.poolsize and vert.worker thread size. if you are use quarkus+spring boot. spring boot uses tomcat in default . u can use undertow or jetty.its tomcat parameters

server:
  tomcat:
    threads:
      max: 300
      min-spare: 60


问:
How do I extract a jpeg's EXIF thumbnail using ImageSharp?
I am trying to extract thumbnails from source jpegs and save them to the file system, using the C# ImageSharp library. I see there is some mention of it in the intellisense for the component:
SixLabors.ImageSharp.Image.Metadata.ExifProfile.CreateThumbnail()

...but I can't seem to find any documentation for it or examples to call it correctly.

I did find this:

```<code>using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

//method code:
Image<TPixel> thumbnail = image.Metadata.ExifProfile.CreateThumbnail<TPixel>();
</code>```

https://docs.sixlabors.com/api/ImageSharp/SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifProfile.html

...but I need to find where the TPixel type is to get it to work. VisualStudio doesn't recognize it and I can't seem to find a namespace or use it correctly:

"The type or namespace name 'TPixel' could not be found (are you missing a using directive or an assembly reference?)"

Legacy Windows .NET Framework could do this for System.Drawing.Image.Image.GetThumbnailImage() and it worked pretty well.

EDIT: Using tocsoft's answer, I changed the code to:

```<code>if (image.Metadata.ExifProfile != null)
{
    Image<Rgba32> thumbnail = image.Metadata.ExifProfile.CreateThumbnail<Rgba32>();

    thumbnail.Save(thumbnailPath, encoder);
}
</code>```

...however, the image.Metadata.ExifProfile is null, which is unexpected since I know these source images have EXIF data.

EDIT: Actually, it's working now. Success! Thank you!

答:
TPixel would be any of the pixel formats in the SixLabors.ImageSharp.PixelFormats namespace. But unless you are planning on interoperating with other systems that require the pixel data layed out in memory in specific ways you will likely just want to use Rgba32

```<code>Image<Rgba32> thumbnail = image.Metadata.ExifProfile.CreateThumbnail<Rgba32>();
</code>```

Body:
I am trying to extract thumbnails from source jpegs and save them to the file system, using the C# ImageSharp library. I see there is some mention of it in the intellisense for the component:
SixLabors.ImageSharp.Image.Metadata.ExifProfile.CreateThumbnail()

...but I can't seem to find any documentation for it or examples to call it correctly.

I did find this:

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

//method code:
Image<TPixel> thumbnail = image.Metadata.ExifProfile.CreateThumbnail<TPixel>();

https://docs.sixlabors.com/api/ImageSharp/SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifProfile.html

...but I need to find where the TPixel type is to get it to work. VisualStudio doesn't recognize it and I can't seem to find a namespace or use it correctly:

"The type or namespace name 'TPixel' could not be found (are you missing a using directive or an assembly reference?)"

Legacy Windows .NET Framework could do this for System.Drawing.Image.Image.GetThumbnailImage() and it worked pretty well.

EDIT: Using tocsoft's answer, I changed the code to:

if (image.Metadata.ExifProfile != null)
{
    Image<Rgba32> thumbnail = image.Metadata.ExifProfile.CreateThumbnail<Rgba32>();

    thumbnail.Save(thumbnailPath, encoder);
}

...however, the image.Metadata.ExifProfile is null, which is unexpected since I know these source images have EXIF data.

EDIT: Actually, it's working now. Success! Thank you!

Body:
TPixel would be any of the pixel formats in the SixLabors.ImageSharp.PixelFormats namespace. But unless you are planning on interoperating with other systems that require the pixel data layed out in memory in specific ways you will likely just want to use Rgba32

Image<Rgba32> thumbnail = image.Metadata.ExifProfile.CreateThumbnail<Rgba32>();


问:
Finding confidence interval for the second level of a categorical variable in R commander
I am going to determine the confidence interval for the proportion based on dataset "CES11" dataset which is included in R. The variable that I have used for the test is Abortion and the values are "No" and "Yes". I want to find the confidence interval for the proportion of "Yes", but R does a hypothesis test and provides a confidence interval for the first level which is "No". How can I change it such that results corresponds to level equal to "Yes"?</p>
```<code>Frequency counts (test is for first level):
abortion
 No  Yes
1818  413

   1-sample proportions test without continuity correction

data:  rbind(.Table), null probability 0.5
X-squared = 884.82, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.7982282 0.8304517
sample estimates:
       p
0.8148812
</code>```

答:
A quick way in base R is to reverse the tabulation vector order:

cts_abortion <- table(carData::CES11$abortion)

## p is for rate of "No"
prop.test(cts_abortion)
##  1-sample proportions test with continuity correction
##
## data:  cts_abortion, null probability 0.5
## X-squared = 883.56, df = 1, p-value < 2.2e-16
## alternative hypothesis: true p is not equal to 0.5
## 95 percent confidence interval:
##  0.7979970 0.8306679
## sample estimates:
##        p
## 0.8148812

## p is for rate of "Yes"
prop.test(rev(cts_abortion))
##  1-sample proportions test with continuity correction
##
## data:  rev(cts_abortion), null probability 0.5
## X-squared = 883.56, df = 1, p-value < 2.2e-16
## alternative hypothesis: true p is not equal to 0.5
## 95 percent confidence interval:
##  0.1693321 0.2020030
## sample estimates:
##         p
## 0.1851188
```
<p>Otherwise, you can likely just relevel the factor:</p>
<pre class="lang-r prettyprint-override"><code>df_ces11 <- carData::CES11
df_ces11$abortion <- factor(df_ces11$abortion, levels=c("Yes", "No"))
</code>```

Body:
I am going to determine the confidence interval for the proportion based on dataset "CES11" dataset which is included in R. The variable that I have used for the test is Abortion and the values are "No" and "Yes". I want to find the confidence interval for the proportion of "Yes", but R does a hypothesis test and provides a confidence interval for the first level which is "No". How can I change it such that results corresponds to level equal to "Yes"?

Frequency counts (test is for first level):
abortion
 No  Yes
1818  413

   1-sample proportions test without continuity correction

data:  rbind(.Table), null probability 0.5
X-squared = 884.82, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.7982282 0.8304517
sample estimates:
       p
0.8148812

Body:
A quick way in base R is to reverse the tabulation vector order:

cts_abortion <- table(carData::CES11$abortion)

## p is for rate of "No"
prop.test(cts_abortion)
##  1-sample proportions test with continuity correction
##
## data:  cts_abortion, null probability 0.5
## X-squared = 883.56, df = 1, p-value < 2.2e-16
## alternative hypothesis: true p is not equal to 0.5
## 95 percent confidence interval:
##  0.7979970 0.8306679
## sample estimates:
##        p
## 0.8148812

## p is for rate of "Yes"
prop.test(rev(cts_abortion))
##  1-sample proportions test with continuity correction
##
## data:  rev(cts_abortion), null probability 0.5
## X-squared = 883.56, df = 1, p-value < 2.2e-16
## alternative hypothesis: true p is not equal to 0.5
## 95 percent confidence interval:
##  0.1693321 0.2020030
## sample estimates:
##         p
## 0.1851188

Otherwise, you can likely just relevel the factor:

df_ces11 <- carData::CES11
df_ces11$abortion <- factor(df_ces11$abortion, levels=c("Yes", "No"))