问:
Having trouble reaching PouchDB in my html WebApp
I want to use pouchDB in my WebApp so that when I click on a button, the data from a JSON file would be saved to pouchDB. In my index.html I imported these at first:

```<code><script type="module" src="pouchdb/packages/node_modules/pouchdb/src/pouchdb.js"></script>
<script type="module" src="pouchdb-load/dist/pouchdb.load.js"></script>
<script src="js/pdb.js"></script>
</code>```

I cloned pouchDB to my working html folder so the path should be fine. But in my js file it started to throw error from this line var PouchDB = require('pouchdb'); stating 'Uncaught ReferenceError: require is not defined', which I think it means that my WebApp failed to reach pouchDB from the src.

What I've tried:

Use  in the html file instead of using pouchdb.js in the js folder as the source.

This is also the only source this PouchDB official guide uses in its todo demo. This demo worked perfectly on my laptop, but when it comes to my own WebApp it no longer works and still throws the same error.

Another problem for this method is that even if the cdn link worked and I could reach pouchdb.min.js, I still need the pouchdb.load.js to be able to work since I want data in the JSON file to be saved to pouch.

In the PouchDB official guide, it doesn't even included this line var PouchDB = require('pouchdb'); in its app.js, but directly says var db = new PouchDB('todos');. But when I attempted to do it this way, a new error occurred: 'ReferenceError: PouchDB is not defined'.

I also tried npm install pouchdb-browser and then in the js file I wrote:

```<code>var PouchDB = require('pouchdb-browser');
var pouchdb = PouchDB.default.defaults();
</code>```

but it throws the same error associated with require.

I think the problem is still that the sources in the html failed to created this connection between pouchdb.js with my WebApp. Meanwhile everything seems fine when I followed the official guide to make the todo Demo. Any idea what might have caused this problem and how to solve it?

答:
I think you're mixing up client side and server side programming. You can't do "require" natively in client-side JavaScript code. Here's a very simple example of taking data from a form and writing it to local PouchDB:

```<code><html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/pouchdb@7.2.1/dist/pouchdb.min.js"></script>
  </head>
  <body>

     <textarea id="doc" rows="10">
{
  "a": 1
}
     </textarea>
     <br>
     <button onclick="save()">Save</button>
     <div id="response"></div>
     <script>

       const db = new PouchDB('todos')

       const save = async function() {
         const el = document.getElementById('doc')
         const doc = JSON.parse(el.value)
         const response = await db.post(doc)
         document.getElementById('response').innerHTML = JSON.stringify(response)
       }
     </script>
  </body>
</html>
</code>```

It gets PouchDB from the CDN - notice that I'm using https:// instead of // as the protocol because we always want to fetch PouchDB using https even if the hosted page is served out on http.

Once PouchDB is loaded, we write the document to PouchDB database using the post function and write the response back to the page.

Body:
I want to use pouchDB in my WebApp so that when I click on a button, the data from a JSON file would be saved to pouchDB. In my index.html I imported these at first:

I cloned pouchDB to my working html folder so the path should be fine. But in my js file it started to throw error from this line var PouchDB = require('pouchdb'); stating 'Uncaught ReferenceError: require is not defined', which I think it means that my WebApp failed to reach pouchDB from the src.

What I've tried:

Use  in the html file instead of using pouchdb.js in the js folder as the source.

This is also the only source this PouchDB official guide uses in its todo demo. This demo worked perfectly on my laptop, but when it comes to my own WebApp it no longer works and still throws the same error.

Another problem for this method is that even if the cdn link worked and I could reach pouchdb.min.js, I still need the pouchdb.load.js to be able to work since I want data in the JSON file to be saved to pouch.

In the PouchDB official guide, it doesn't even included this line var PouchDB = require('pouchdb'); in its app.js, but directly says var db = new PouchDB('todos');. But when I attempted to do it this way, a new error occurred: 'ReferenceError: PouchDB is not defined'.

I also tried npm install pouchdb-browser and then in the js file I wrote:

var PouchDB = require('pouchdb-browser');
var pouchdb = PouchDB.default.defaults();

but it throws the same error associated with require.

I think the problem is still that the sources in the html failed to created this connection between pouchdb.js with my WebApp. Meanwhile everything seems fine when I followed the official guide to make the todo Demo. Any idea what might have caused this problem and how to solve it?

Body:
I think you're mixing up client side and server side programming. You can't do "require" natively in client-side JavaScript code. Here's a very simple example of taking data from a form and writing it to local PouchDB:

<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/pouchdb@7.2.1/dist/pouchdb.min.js"></script>
  </head>
  <body>

     <textarea id="doc" rows="10">
{
  "a": 1
}
     </textarea>
     <br>
     <button onclick="save()">Save</button>
     <div id="response"></div>
     <script>

       const db = new PouchDB('todos')

       const save = async function() {
         const el = document.getElementById('doc')
         const doc = JSON.parse(el.value)
         const response = await db.post(doc)
         document.getElementById('response').innerHTML = JSON.stringify(response)
       }
     </script>
  </body>
</html>

It gets PouchDB from the CDN - notice that I'm using https:// instead of // as the protocol because we always want to fetch PouchDB using https even if the hosted page is served out on http.

Once PouchDB is loaded, we write the document to PouchDB database using the post function and write the response back to the page.


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: np.loadtxt: could not convert string to float

Body:
I have the following textfile:

13,1980,0,1,0,0,14,0,1.1975401639938354,1
13,1981,0,2,0,0,14,1,1.853060007095337,4
13,1982,0,3,0,0,14,0,1.3444616794586182,9
13,1983,0,4,0,0,14,0,1.4332133531570435,16
13,1984,0,5,0,0,14,0,1.5681251287460327,25
13,1985,0,6,0,0,14,0,1.6998909711837769,36
13,1986,0,7,0,0,14,0,-0.7202625870704651,49

When I try to load it into Jupyter Notebook in python:

data = np.loadtxt("/filepath/wagepan.txt")

I get the following error:

ValueError: could not convert string to float: '13,1980,0,1,0,0,14,0,1.1975401639938354,1'

Does anyone have any idea how to fix this? I tried looking at other posts, but the issue was not similar.

Body:
Use the delimiter argument to define the delimiter.

import numpy as np

data = np.loadtxt("data.dat", delimiter=",")

print(data)

Output:

[[ 1.30000000e+01  1.98000000e+03  0.00000000e+00  1.00000000e+00
   0.00000000e+00  0.00000000e+00  1.40000000e+01  0.00000000e+00
   1.19754016e+00  1.00000000e+00]
 [ 1.30000000e+01  1.98100000e+03  0.00000000e+00  2.00000000e+00
   0.00000000e+00  0.00000000e+00  1.40000000e+01  1.00000000e+00
   1.85306001e+00  4.00000000e+00]
 [ 1.30000000e+01  1.98200000e+03  0.00000000e+00  3.00000000e+00
   0.00000000e+00  0.00000000e+00  1.40000000e+01  0.00000000e+00
   1.34446168e+00  9.00000000e+00]
 [ 1.30000000e+01  1.98300000e+03  0.00000000e+00  4.00000000e+00
   0.00000000e+00  0.00000000e+00  1.40000000e+01  0.00000000e+00
   1.43321335e+00  1.60000000e+01]
 [ 1.30000000e+01  1.98400000e+03  0.00000000e+00  5.00000000e+00
   0.00000000e+00  0.00000000e+00  1.40000000e+01  0.00000000e+00
   1.56812513e+00  2.50000000e+01]
 [ 1.30000000e+01  1.98500000e+03  0.00000000e+00  6.00000000e+00
   0.00000000e+00  0.00000000e+00  1.40000000e+01  0.00000000e+00
   1.69989097e+00  3.60000000e+01]
 [ 1.30000000e+01  1.98600000e+03  0.00000000e+00  7.00000000e+00
   0.00000000e+00  0.00000000e+00  1.40000000e+01  0.00000000e+00
  -7.20262587e-01  4.90000000e+01]]


问:
How to make Linux executable file on Windows using PyInstaller?
I have made a PyQt5 app in Python. This app supports both Windows and Linux. Now the problem is, I want to Compile this Python app to Windows and Linux Executable. I can create Windows executable file from my windows PC. But to Create a Linux Executable I need to move to Linux. I use Kali Linux Live version. and to boot into Linux, It takes sometimes. But I want to make Linux executable from Windows using pyinstaller.

答:
You can't. You need to compile it on a linux system and it's most likely not backwards compatible. It is recommended that you use a VM.

From the documentation:

If you need to distribute your application for more than one OS, for example both Windows and Mac OS X, you must install PyInstaller on each platform and bundle your app separately on each.

You can do this from a single machine using virtualization. The free virtualBox or the paid VMWare and Parallels allow you to run another complete operating system as a “guest”. You set up a virtual machine for each “guest” OS. In it you install Python, the support packages your application needs, and PyInstaller.


问:
Is it possible to reference a cell in Microsoft Excel using the intersect of two named ranges?
In a spreadsheet I'm making for my Thermodynamics class, I created an appendix with important values for certain molecules, such as the molar mass of Ethane. I have named the rows to the molecule names and columns to the important variables.

I want to be able to simply type some version of =Ethane_molarmass or something like that to call the specific cell. Is this possible, and how?

答:
Try:

```<code>=INTERSECT(ColumnRangeName, RowRangeName)
</code>```

or without the named ranges, for example,

```<code>=INTERSECT(B:B,2:2)  for the value in Col B, Row 2
</code>```

or dynamically (not ideal):

```<code>=INTERSECT(INDIRECT("ColumnRangeName"),INDIRECT("RowRangeName"))
</code>```

Body:
Try:

=INTERSECT(ColumnRangeName, RowRangeName)

or without the named ranges, for example,

=INTERSECT(B:B,2:2)  for the value in Col B, Row 2

or dynamically (not ideal):

=INTERSECT(INDIRECT("ColumnRangeName"),INDIRECT("RowRangeName"))


问:
Replace for loop that indexes two arrays and applies a function on each row
I have a for-loop that works on two values and I would like to apply it in a faster way or vectorise it if possible. My original for-loop looks something like this

```<code>import numpy as np

x = [1,2,3]
y = [0,0,0]

for i in range(len(x)):

    # index value in each element
    xi = x[i]
    yi = y[i]

    # apply function some bivariate function
    print(np.sum(xi,yi))
</code>```

I was thinking maybe I could use the list approach but the output came out as below.

```<code>x = [1,2,3]
y = [0,0,0]

[np.sum(i, j) for i in x for j in y]
</code>```
```<code># output
[1, 1, 1, 2, 2, 2, 3, 3, 3]
</code>```

What are better methods to replace the initial for-loop statement? My actual function is not a sum as in the initial example, that is just a dummy function.

答:
Here you go. - Use the zip function in such cases

```<code>list_sum = [np.sum(x,y) for x,y in zip(x,y)]
</code>```

Body:
I have a for-loop that works on two values and I would like to apply it in a faster way or vectorise it if possible. My original for-loop looks something like this

import numpy as np

x = [1,2,3]
y = [0,0,0]

for i in range(len(x)):

    # index value in each element
    xi = x[i]
    yi = y[i]

    # apply function some bivariate function
    print(np.sum(xi,yi))

I was thinking maybe I could use the list approach but the output came out as below.

x = [1,2,3]
y = [0,0,0]

[np.sum(i, j) for i in x for j in y]

# output
[1, 1, 1, 2, 2, 2, 3, 3, 3]

What are better methods to replace the initial for-loop statement? My actual function is not a sum as in the initial example, that is just a dummy function.

Body:
Here you go. - Use the zip function in such cases

list_sum = [np.sum(x,y) for x,y in zip(x,y)]


问:
How to navigate from fragment in one activity to fragment in another activity?
I want to add back navigation to toolbar. I need to get from a fragment in an activity to a specific fragment in another activity.

It looks a little like this, where every orange line means navigating to a new activity or fragment:

How do I move from fragment B to fragment A from OtherActivity?

答:
To navigate from one Activity to another Activity's Fragment, with Kotlin version 1.4.0 and, for example, calling a click listener on a button it works so:</p>
```<code> binding.yourButton.setOnClickListener {
        supportFragmentManager.beginTransaction().replace(R.id.yourLayout, NameOfYourFragment()).commit()
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To navigate from one Activity to another Activity's Fragment, with Kotlin version 1.4.0 and, for example, calling a click listener on a button it works so:

 binding.yourButton.setOnClickListener {
        supportFragmentManager.beginTransaction().replace(R.id.yourLayout, NameOfYourFragment()).commit()
    }


问:
Datashader integration for polygons in plotly mapbox
I'm using plotly's Scattermapbox to overlay a map with a shaded image of polygons created by datashader's shade function (based on https://plotly.com/python/datashader/), but the projections do not seem to align, see picture below. Any suggestions how I can overcome this problem using plotly's Scattermapbox and datashader?

Reproducible example:

```<code>import geopandas as gpd
import plotly.graph_objects as go
import spatialpandas as spd
import datashader as ds
from colorcet import fire
import datashader.transfer_functions as tf

# load data
world = gpd.read_file(
    gpd.datasets.get_path('naturalearth_lowres')
)
# world = world.to_crs(epsg=3857)
# create spatialpandas DataFrame
df_world = spd.GeoDataFrame(world)
# create datashader canvas and aggregate
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.polygons(df_world, geometry='geometry', agg=ds.mean('pop_est'))
# create shaded image
tf.shade(agg, cmap=fire)
</code>```

shaded image

```<code># create shaded image and convert to Python image
img = tf.shade(agg, cmap=fire)[::-1].to_pil()

coords_lat, coords_lon = agg.coords["y"].values, agg.coords["x"].values
# Corners of the image, which need to be passed to mapbox
coordinates = [
    [coords_lon[0], coords_lat[0]],
    [coords_lon[-1], coords_lat[0]],
    [coords_lon[-1], coords_lat[-1]],
    [coords_lon[0], coords_lat[-1]],
]

fig = go.Figure(go.Scattermapbox())
fig.update_layout(
    mapbox_style="open-street-map",
    mapbox_layers=[
        {
            "sourcetype": "image",
            "source": img,
            "coordinates": coordinates,
        }
    ]
)
fig.show()
</code>```

overlayed map

I read that Scattermapbox only supports Mercator projection which I found confusing as the examples in plotly's documentation seem to be in long/lat format, but I tried converting the coordinates of the GeoDataFrame to epsg 3857, see

```<code># world = world.to_crs(epsg=3857)
</code>```

The results is that the shaded image becomes invisible. Any help would be highly appreciated.

答:
Have you tried with epsg:4326? In my case, I use this one and the geometries are placed correctly.

On the other hand, with geopandas to convert the geometry column of the dataframe you have to use the parameter "inplace=True".

Body:
I'm using plotly's Scattermapbox to overlay a map with a shaded image of polygons created by datashader's shade function (based on https://plotly.com/python/datashader/), but the projections do not seem to align, see picture below. Any suggestions how I can overcome this problem using plotly's Scattermapbox and datashader?

Reproducible example:

import geopandas as gpd
import plotly.graph_objects as go
import spatialpandas as spd
import datashader as ds
from colorcet import fire
import datashader.transfer_functions as tf

# load data
world = gpd.read_file(
    gpd.datasets.get_path('naturalearth_lowres')
)
# world = world.to_crs(epsg=3857)
# create spatialpandas DataFrame
df_world = spd.GeoDataFrame(world)
# create datashader canvas and aggregate
cvs = ds.Canvas(plot_width=1000, plot_height=1000)
agg = cvs.polygons(df_world, geometry='geometry', agg=ds.mean('pop_est'))
# create shaded image
tf.shade(agg, cmap=fire)

shaded image

# create shaded image and convert to Python image
img = tf.shade(agg, cmap=fire)[::-1].to_pil()

coords_lat, coords_lon = agg.coords["y"].values, agg.coords["x"].values
# Corners of the image, which need to be passed to mapbox
coordinates = [
    [coords_lon[0], coords_lat[0]],
    [coords_lon[-1], coords_lat[0]],
    [coords_lon[-1], coords_lat[-1]],
    [coords_lon[0], coords_lat[-1]],
]

fig = go.Figure(go.Scattermapbox())
fig.update_layout(
    mapbox_style="open-street-map",
    mapbox_layers=[
        {
            "sourcetype": "image",
            "source": img,
            "coordinates": coordinates,
        }
    ]
)
fig.show()

overlayed map

I read that Scattermapbox only supports Mercator projection which I found confusing as the examples in plotly's documentation seem to be in long/lat format, but I tried converting the coordinates of the GeoDataFrame to epsg 3857, see

# world = world.to_crs(epsg=3857)

The results is that the shaded image becomes invisible. Any help would be highly appreciated.


问:
React router v6 how to use `navigate` redirection in axios interceptor
```<code>import axios from "axios";
import { useNavigate } from "react-router-dom";

export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/",
  headers: {
    "content-type": "application/json",
  },
});

api.interceptors.response.use(
  function (response) {
    return response;
  },
  function (er) {
    if (axios.isAxiosError(er)) {
      if (er.response) {
        if (er.response.status == 401) {

          // Won't work
          useNavigate()("/login");

        }
      }
    }

    return Promise.reject(er);
  }
);
</code>```

答:
I have solved this problem by creating a component for the interceptor:

```<code>import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { axiosInstance } from '../custom-axios';

export const ResponseInterceptor = () => {
  const { onLogout } = useAuth();
  const { addError } = useAPIError();
  const navigate = useNavigate()

  const interceptorId = useRef<number | null>(null);

  useEffect(() => {
    interceptorId.current = axiosInstance.interceptors.response.use(undefined, (error) => {
      switch (error.response.status) {
        case 401:
          navigate('/login');
          break;
      }
    });

    return () => {
      axiosInstance.interceptors.response.eject(interceptorId.current as number);
    };
  }, []);

  return null;
};

</code>```

And connected it to the App component:

```<code>const App = () => {
  return (
    <AuthProvider>
      <APIErrorProvider>
        <AppRoutes />
        <ResponseInterceptor />
        <APIErrorNotification />
      </APIErrorProvider>
    </AuthProvider>
  );
};
export default App;

</code>```

Body:
I have solved this problem by creating a component for the interceptor:

import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { axiosInstance } from '../custom-axios';

export const ResponseInterceptor = () => {
  const { onLogout } = useAuth();
  const { addError } = useAPIError();
  const navigate = useNavigate()

  const interceptorId = useRef<number | null>(null);

  useEffect(() => {
    interceptorId.current = axiosInstance.interceptors.response.use(undefined, (error) => {
      switch (error.response.status) {
        case 401:
          navigate('/login');
          break;
      }
    });

    return () => {
      axiosInstance.interceptors.response.eject(interceptorId.current as number);
    };
  }, []);

  return null;
};

And connected it to the App component:

const App = () => {
  return (
    <AuthProvider>
      <APIErrorProvider>
        <AppRoutes />
        <ResponseInterceptor />
        <APIErrorNotification />
      </APIErrorProvider>
    </AuthProvider>
  );
};
export default App;


问:
Why does toast shows with delay
When I run the code which looks like:

```<code>Toast.makeText(MainActivity.this,"Toast 1", Toast.LENGTH_SHORT).show();
Log.i("MyLog","Log 1");

try {
   Thread.sleep( 5000);
} catch (InterruptedException e) {
   e.printStackTrace();
}

Toast.makeText(MainActivity.this,"Toast 2", Toast.LENGTH_SHORT).show();
Log.i("MyLog","Log 2");
</code>```

It shows Log1 then make 5 sec delay then show Log2, Toast1, Toast2. Could anybody help me to understand why Toast1 does not appear befor delay?

Whole class is:

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn = findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Toast.makeText(MainActivity.this,"Toast 1", Toast.LENGTH_SHORT).show();
            Log.i("MyLog","Log 1");
            try {
                Thread.sleep( 5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Toast.makeText(MainActivity.this,"Toast 2", Toast.LENGTH_SHORT).show();
            Log.i("MyLog","Log 2");
        }
    });
}
</code>```

}

答:
Thread.sleep( 5000) blocks your UI thread. The whole UI doesn't do anything for 5 seconds. So even if the first Toast has been created, the process of showing the Toast can get interrupted.
You should move the delay to a background thread and start the second toast from the background thread.

A low effort solution would be to use Handler:

```<code>Toast.makeText(requireContext(), "Toast 1", Toast.LENGTH_SHORT).show()
Log.i("MyLog", "Log 1")

Handler().run {
    try {
        Thread.sleep(5000)
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }
    Toast.makeText(requireContext(), "Toast 2", Toast.LENGTH_SHORT).show()
    Log.i("MyLog", "Log 2")
}
</code>```

Note: This example is written in Kotlin.

Title: Why does toast shows with delay

Body:
When I run the code which looks like:

Toast.makeText(MainActivity.this,"Toast 1", Toast.LENGTH_SHORT).show();
Log.i("MyLog","Log 1");

try {
   Thread.sleep( 5000);
} catch (InterruptedException e) {
   e.printStackTrace();
}

Toast.makeText(MainActivity.this,"Toast 2", Toast.LENGTH_SHORT).show();
Log.i("MyLog","Log 2");

It shows Log1 then make 5 sec delay then show Log2, Toast1, Toast2. Could anybody help me to understand why Toast1 does not appear befor delay?

Whole class is:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn = findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Toast.makeText(MainActivity.this,"Toast 1", Toast.LENGTH_SHORT).show();
            Log.i("MyLog","Log 1");
            try {
                Thread.sleep( 5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Toast.makeText(MainActivity.this,"Toast 2", Toast.LENGTH_SHORT).show();
            Log.i("MyLog","Log 2");
        }
    });
}

}

Body:
Thread.sleep( 5000) blocks your UI thread. The whole UI doesn't do anything for 5 seconds. So even if the first Toast has been created, the process of showing the Toast can get interrupted.
You should move the delay to a background thread and start the second toast from the background thread.

A low effort solution would be to use Handler:

Toast.makeText(requireContext(), "Toast 1", Toast.LENGTH_SHORT).show()
Log.i("MyLog", "Log 1")

Handler().run {
    try {
        Thread.sleep(5000)
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }
    Toast.makeText(requireContext(), "Toast 2", Toast.LENGTH_SHORT).show()
    Log.i("MyLog", "Log 2")
}

Note: This example is written in Kotlin.


问:
Calling functions with variables multiple times
I'm making a program for a school project and I'm having an issue.

I have defined a function called DidThisWork like so:

```<code>def DidThisWork():
    global DidThisWork
    DidThisWork = input('\n\nDid this solution work? - ').lower()
</code>```

Throughout my code, I want to call this function multiple times, however, I'm not able to. Is there a way, to call it multiple times, and like reset the DidThisWork variable inside the function after I used it in if statements?

答:
You define a function def DidThisWork(): then within that very function you overwrite the newly created DidThisWork variable (which points to the function) to the result of your input(..) call.

So at the first call to DidThisWork(), the DidThisWork variable no longer points to the function, rather to the string returned by input(...).

If you rename either the function or the variable storing the string returned by input() it should work.

By the way, there are some naming conventions in Python you may want to look into https://www.python.org/dev/peps/pep-0008/#id30. Typically you'd use snake_case instead of camelCase and not only start a class with an upper case letter

```<code>worked = None

def did_this_work():
    global worked
    worked = input('\n\nDid this solution work? - ').lower()

print(worked)
did_this_work()
print(worked)
did_this_work()
print(worked)
</code>```

Body:
I'm making a program for a school project and I'm having an issue.

I have defined a function called DidThisWork like so:

def DidThisWork():
    global DidThisWork
    DidThisWork = input('\n\nDid this solution work? - ').lower()

Throughout my code, I want to call this function multiple times, however, I'm not able to. Is there a way, to call it multiple times, and like reset the DidThisWork variable inside the function after I used it in if statements?

Body:
You define a function def DidThisWork(): then within that very function you overwrite the newly created DidThisWork variable (which points to the function) to the result of your input(..) call.

So at the first call to DidThisWork(), the DidThisWork variable no longer points to the function, rather to the string returned by input(...).

If you rename either the function or the variable storing the string returned by input() it should work.

By the way, there are some naming conventions in Python you may want to look into https://www.python.org/dev/peps/pep-0008/#id30. Typically you'd use snake_case instead of camelCase and not only start a class with an upper case letter

worked = None

def did_this_work():
    global worked
    worked = input('\n\nDid this solution work? - ').lower()

print(worked)
did_this_work()
print(worked)
did_this_work()
print(worked)


问:
Error : only integer scalar arrays can be converted to a scalar index How to solve?
I try to convert breast canser dataset to a dataframe and to use it
but i got following error;

TypeError: only integer scalar arrays can be converted to a scalar
index

```<code>#Import library
from sklearn.datasets import load_breast_cancer
import pandas as pd
#Load dataset
cancer = load_breast_cancer()
#Convert the sklearn.dataset cancer to a DataFrame.
df=pd.DataFrame(cancer.data,columns =[cancer.feature_names])
df['target']=pd.Series(data=cancer.target,index=df.index)
display(df['target'])
</code>```

答:
The dataset converts to a dataframe correctly. It seems to be an indexing issue, so I changed the last line to

```<code>df[["target"]]
</code>```

and it worked for me.

Body:
I try to convert breast canser dataset to a dataframe and to use it
but i got following error;

TypeError: only integer scalar arrays can be converted to a scalar
index

#Import library
from sklearn.datasets import load_breast_cancer
import pandas as pd
#Load dataset
cancer = load_breast_cancer()
#Convert the sklearn.dataset cancer to a DataFrame.
df=pd.DataFrame(cancer.data,columns =[cancer.feature_names])
df['target']=pd.Series(data=cancer.target,index=df.index)
display(df['target'])

Body:
The dataset converts to a dataframe correctly. It seems to be an indexing issue, so I changed the last line to

df[["target"]]

and it worked for me.


问:
Loader animation in pure CSS
I try to code loader animation inspired by this dribbble: https://dribbble.com/shots/14420202-Processing-Animation
and in comment section I found codepen with similar animation, but it is made all in JS: https://codepen.io/AbubakerSaeed/full/yLaQVdq

```<code>tl2
  .set(".dC-1", { rotate: 0 })
  .set(".dC-2", { rotate: 30 })
  .set(".dC-3", { rotate: 60 })
  .set(".dC-4", { rotate: 90 })
  .set(".dC-5", { rotate: 120 })
  .set(".dC-6", { rotate: 150 })
  .set(".dC-7", { rotate: 180 })
  .set(".dC-8", { rotate: 210 })
  .set(".dC-9", { rotate: 240 })
  .set(".dC-10", { rotate: 270 })
  .set(".dC-11", { rotate: 300 })
  .set(".dC-12", { rotate: 330 })
  .to(".dC-1", {
  delay: s,
  duration: s,
    rotate: 30,
})
</code>```

I try to make pure CSS animation from it but I don't understand how to do it. Can someone explain for me how to make these two timelines in SCSS, how to translate JS code into SCSS?

答:
Thanks so much Lars. I am developing it for 12 blocks but animation goes wild. Maybe I am calculating time or percentages wrong?

Here is my code (in scss for more clarity):

```<code>.spinner {
  animation: 5s linear infinite spin;
}

$rotation: 0deg;

    .static {
      @for $i from 1 to 12 {
        .b#{$i} {
          transform: rotate($rotation) translateX($loader-size / 2);
          animation: 10s ease-in-out infinite hide-#{$i};
        }

        $rotation: $rotation + 30deg;
      }
    }

    $rotation: 0deg;

    .spinner {
      @for $i from 1 to 12 {
        .b#{$i} {
          transform: rotate($rotation) translateX($loader-size / 2);
          animation: 10s linear infinite go-in-out-#{$i};
        }

        $rotation: $rotation + 30deg;
      }
    }

    @keyframes spin {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }

    $first: 0;
    $second: 4;
    $third: 50;
    $fourth: 54;
    $fifth: 54.1;

    @for $i from 1 to 12 {
      @keyframes go-in-out-#{$i} {
        #{$first * 1%} {
          transform: translateX($loader-size / 2);
          opacity: 1;
        }

        #{$second * 1%},
        #{$third * 1%} {
          transform: translateX($block-size * ($i - 1));
          opacity: 1;
        }

        #{$fourth * 1%} {
          transform: translateX($loader-size / 2);
          opacity: 1;
        }

        #{$fifth * 1%},
        100% {
          transform: translateX($loader-size / 2);
          opacity: 0;
        }
      }

      $first: $first + 4;
      $second: $second + 4;
      $third: $third - 4;
      $fourth: $fourth - 4;
      $fifth: $fifth - 4;
    }

    $first-2: 0;
    $second-2: 4;
    $third-2: 50;
    $fourth-2: 50.1;

    @for $i from 1 to 12 {
      @keyframes hide-#{$i} {
        #{$first-2 * 1%} {
          opacity: 0;
        }

        #{$second-2 * 1%},
        #{$third-2 * 1%} {
          opacity: 0;
        }

        #{$fourth-2 * 1%},
        100% {
          opacity: 1;
        }
      }

      $first-2: $first-2 + 4;
      $second-2: $second-2 + 4;
      $third-2: $third-2 + 4;
      $fourth-2: $fourth-2 + 4;
    }
</code>```

Title: Loader animation in pure CSS

Body:
I try to code loader animation inspired by this dribbble: https://dribbble.com/shots/14420202-Processing-Animation
and in comment section I found codepen with similar animation, but it is made all in JS: https://codepen.io/AbubakerSaeed/full/yLaQVdq

tl2
  .set(".dC-1", { rotate: 0 })
  .set(".dC-2", { rotate: 30 })
  .set(".dC-3", { rotate: 60 })
  .set(".dC-4", { rotate: 90 })
  .set(".dC-5", { rotate: 120 })
  .set(".dC-6", { rotate: 150 })
  .set(".dC-7", { rotate: 180 })
  .set(".dC-8", { rotate: 210 })
  .set(".dC-9", { rotate: 240 })
  .set(".dC-10", { rotate: 270 })
  .set(".dC-11", { rotate: 300 })
  .set(".dC-12", { rotate: 330 })
  .to(".dC-1", {
  delay: s,
  duration: s,
    rotate: 30,
})

I try to make pure CSS animation from it but I don't understand how to do it. Can someone explain for me how to make these two timelines in SCSS, how to translate JS code into SCSS?

Body:
Thanks so much Lars. I am developing it for 12 blocks but animation goes wild. Maybe I am calculating time or percentages wrong?

Here is my code (in scss for more clarity):

.spinner {
  animation: 5s linear infinite spin;
}

$rotation: 0deg;

    .static {
      @for $i from 1 to 12 {
        .b#{$i} {
          transform: rotate($rotation) translateX($loader-size / 2);
          animation: 10s ease-in-out infinite hide-#{$i};
        }

        $rotation: $rotation + 30deg;
      }
    }

    $rotation: 0deg;

    .spinner {
      @for $i from 1 to 12 {
        .b#{$i} {
          transform: rotate($rotation) translateX($loader-size / 2);
          animation: 10s linear infinite go-in-out-#{$i};
        }

        $rotation: $rotation + 30deg;
      }
    }

    @keyframes spin {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }

    $first: 0;
    $second: 4;
    $third: 50;
    $fourth: 54;
    $fifth: 54.1;

    @for $i from 1 to 12 {
      @keyframes go-in-out-#{$i} {
        #{$first * 1%} {
          transform: translateX($loader-size / 2);
          opacity: 1;
        }

        #{$second * 1%},
        #{$third * 1%} {
          transform: translateX($block-size * ($i - 1));
          opacity: 1;
        }

        #{$fourth * 1%} {
          transform: translateX($loader-size / 2);
          opacity: 1;
        }

        #{$fifth * 1%},
        100% {
          transform: translateX($loader-size / 2);
          opacity: 0;
        }
      }

      $first: $first + 4;
      $second: $second + 4;
      $third: $third - 4;
      $fourth: $fourth - 4;
      $fifth: $fifth - 4;
    }

    $first-2: 0;
    $second-2: 4;
    $third-2: 50;
    $fourth-2: 50.1;

    @for $i from 1 to 12 {
      @keyframes hide-#{$i} {
        #{$first-2 * 1%} {
          opacity: 0;
        }

        #{$second-2 * 1%},
        #{$third-2 * 1%} {
          opacity: 0;
        }

        #{$fourth-2 * 1%},
        100% {
          opacity: 1;
        }
      }

      $first-2: $first-2 + 4;
      $second-2: $second-2 + 4;
      $third-2: $third-2 + 4;
      $fourth-2: $fourth-2 + 4;
    }


问:
How can we keep unique id, if me make primary key any other column
I want to use default generation ID as well and make another field a primary key..
Can I do that with django ?.

this is my object::

```<code>{
    "platform_subscriber_id": "XXXXXXXXXXXXXXX",#this is custom primary key.
    "platform_subscriber_entity": "loop",
    "platform_subscriber_secret_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "is_remove": false,
    "update_time": "2022-02-09T09:18:28.991032Z",
    "create_time": "2022-02-09T09:18:28.991038Z",
    "platform_subscriber_owner": 1
},
</code>```

i want old one unique ID too..

```<code>{
        "id":1,#this is default one i want back
        "platform_subscriber_id": "XXXXXXXXXXXXXXX",#this is custom primary key.
        "platform_subscriber_entity": "loop",
        "platform_subscriber_secret_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "is_remove": false,
        "update_time": "2022-02-09T09:18:28.991032Z",
        "create_time": "2022-02-09T09:18:28.991038Z",
        "platform_subscriber_owner": 1
    }
</code>```

this is how my model looks like:

```<code>class Project(models.Model):
    platform_subscriber_owner = models.ForeignKey(User, verbose_name=_("project owner"),db_column="platform_user_id", on_delete=models.CASCADE,null=True,blank=True)
    platform_subscriber_id = models.CharField(_("Project Key"), db_column="platform_subscriber_key", max_length=64,primary_key=True, blank=True)
    platform_subscriber_entity = models.CharField(_("Project Names"), max_length=64,blank=True)
    platform_subscriber_secret_key = models.CharField(_("Project Secret Key"), max_length=64,blank=True)
    is_remove = models.BooleanField(_("Remove"),default=False)
    update_time = models.DateTimeField(_("Updated Time"), default = timezone.now)
    create_time = models.DateTimeField(_("Created Time"), default = timezone.now)
</code>```

答:
No. Only single-column primary keys are supported. You can make it unique=True instead of primary_key=True would that solve your problem
check this

But this isn’t an issue in practice, because there’s nothing stopping you from adding other constraints (using the unique_together model option or creating the constraint directly in your database), and enforcing the uniqueness at that level.

Body:
I want to use default generation ID as well and make another field a primary key..
Can I do that with django ?.

this is my object::

{
    "platform_subscriber_id": "XXXXXXXXXXXXXXX",#this is custom primary key.
    "platform_subscriber_entity": "loop",
    "platform_subscriber_secret_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "is_remove": false,
    "update_time": "2022-02-09T09:18:28.991032Z",
    "create_time": "2022-02-09T09:18:28.991038Z",
    "platform_subscriber_owner": 1
},

i want old one unique ID too..

{
        "id":1,#this is default one i want back
        "platform_subscriber_id": "XXXXXXXXXXXXXXX",#this is custom primary key.
        "platform_subscriber_entity": "loop",
        "platform_subscriber_secret_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "is_remove": false,
        "update_time": "2022-02-09T09:18:28.991032Z",
        "create_time": "2022-02-09T09:18:28.991038Z",
        "platform_subscriber_owner": 1
    }

this is how my model looks like:

class Project(models.Model):
    platform_subscriber_owner = models.ForeignKey(User, verbose_name=_("project owner"),db_column="platform_user_id", on_delete=models.CASCADE,null=True,blank=True)
    platform_subscriber_id = models.CharField(_("Project Key"), db_column="platform_subscriber_key", max_length=64,primary_key=True, blank=True)
    platform_subscriber_entity = models.CharField(_("Project Names"), max_length=64,blank=True)
    platform_subscriber_secret_key = models.CharField(_("Project Secret Key"), max_length=64,blank=True)
    is_remove = models.BooleanField(_("Remove"),default=False)
    update_time = models.DateTimeField(_("Updated Time"), default = timezone.now)
    create_time = models.DateTimeField(_("Created Time"), default = timezone.now)


问:
How do I verify that an Android apk is signed with a release certificate?
How can I check that an Android apk is signed with a release and not debug cert?</p>

答:
Use this command : (Jarsigner is in your Java bin folder goto java->jdk->bin path in cmd prompt)

```<code>$ jarsigner -verify my_signed.apk
</code>```

If the .apk is signed properly, Jarsigner prints "jar verified"

Body:
Use this command : (Jarsigner is in your Java bin folder goto java->jdk->bin path in cmd prompt)

$ jarsigner -verify my_signed.apk

If the .apk is signed properly, Jarsigner prints "jar verified"


问:
PG Error could not connect to server: Connection refused Is the server running on port 5432?
I recently updated my machine (MacBook Pro running Mountain Lion) and ever since then, whenever I set up a rails project, my machine craps out and cannot connect to PG. Currently, this is the error I am getting when I try to go to localhost;

PG::ERROR could not connect to server: Connection refused Is the server running on host "localhost"

  (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection

  refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (fe80::1) and accepting TCP/IP connections on port 5432?

Here is a checklist, and list of things I have tried;

PostgreSQL version is 9.3.4

I have it installed through HomeBrew

I have host: localhost in my database.yml file

Rails version 4.1.1, ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.5.0]

Ran brew uninstall postgresql then brew install postgresql

Tried to access my postgres.conf file but wasn't allowed through PGAdmin and command line

Ran locate pg_hba.conf and terminal shot this out;

```<code>WARNING: The locate database (/var/db/locate.database) does not exist.
</code>```

I have also tried using rails 4.0 but I still get the problem

I can still work on other projects on my machine that were started/finished before I updated my computer.

When I run psql from my terminal I get
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

I am really lost here, and am not sure what else to do. Any help would be much appreciated.

UPDATE:

Thanks to this question, all was resolved by simply downloading Postgres.app for Mac. Everything works great now.

答:
if you have installed through brew</p>
```<code>$ brew services stop postgresql
#adjust below  path accordingly to your machine
$ rm /usr/local/var/postgres/postmaster.pid
$ brew services start postgresql
</code>```

Body:
I recently updated my machine (MacBook Pro running Mountain Lion) and ever since then, whenever I set up a rails project, my machine craps out and cannot connect to PG. Currently, this is the error I am getting when I try to go to localhost;

PG::ERROR could not connect to server: Connection refused Is the server running on host "localhost"

  (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection

  refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (fe80::1) and accepting TCP/IP connections on port 5432?

Here is a checklist, and list of things I have tried;

PostgreSQL version is 9.3.4

I have it installed through HomeBrew

I have host: localhost in my database.yml file

Rails version 4.1.1, ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.5.0]

Ran brew uninstall postgresql then brew install postgresql

Tried to access my postgres.conf file but wasn't allowed through PGAdmin and command line

Ran locate pg_hba.conf and terminal shot this out;

WARNING: The locate database (/var/db/locate.database) does not exist.

I have also tried using rails 4.0 but I still get the problem

I can still work on other projects on my machine that were started/finished before I updated my computer.

When I run psql from my terminal I get
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

I am really lost here, and am not sure what else to do. Any help would be much appreciated.

UPDATE:

Thanks to this question, all was resolved by simply downloading Postgres.app for Mac. Everything works great now.

Body:
if you have installed through brew

$ brew services stop postgresql
#adjust below  path accordingly to your machine
$ rm /usr/local/var/postgres/postmaster.pid
$ brew services start postgresql


问:
PermissionError: [WinError 5] Access is denied: 'foldername/ Error while S3 subfolder file download window system
I am trying to download the s3 folder files into my windows system and I am getting Permission Error while executing the my python script in windows system.
Any help will be highly Appreciate.

```<code># creating folder but no data.
import boto3
import os
from pathlib import Path

s3 = boto3.resource('s3')

bucket = s3.Bucket('mybucketname')

key = 'foldername1'
objs = list(bucket.objects.filter(Prefix=key))

for obj in objs:
    # print(obj.key)

    # remove the file name from the object key
    obj_path = os.path.dirname(obj.key)

    # create nested directory structure
    Path(obj_path).mkdir(parents=True, exist_ok=True)

    # save file with full path locally
    bucket.download_file(obj.key, obj.key)
</code>```

Error I am getting below:

```<code>Traceback (most recent call last):
  File "C:\MSA\EO projects\FEB 2022 WORKS\REMOTE AWZ\d6.py", line 23, in <module>
    bucket.download_file(obj.key, obj.key)
  File "C:\Program Files\Python37\lib\site-packages\boto3\s3\inject.py", line 246, in bucket_download_file
    ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
  File "C:\Program Files\Python37\lib\site-packages\boto3\s3\inject.py", line 172, in download_file
    extra_args=ExtraArgs, callback=Callback)
  File "C:\Program Files\Python37\lib\site-packages\boto3\s3\transfer.py", line 307, in download_file
    future.result()
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\futures.py", line 106, in result
    return self._coordinator.result()
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\futures.py", line 265, in result
    raise self._exception
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\tasks.py", line 126, in __call__
    return self._execute_main(kwargs)
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\tasks.py", line 150, in _execute_main
    return_value = self._main(**kwargs)
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\download.py", line 601, in _main
    osutil.rename_file(fileobj.name, final_filename)
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\utils.py", line 273, in rename_file
    rename_file(current_filename, new_filename)
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\compat.py", line 25, in rename_file
    os.remove(new_filename)
PermissionError: [WinError 5] Access is denied: 'foldername1/'
</code>```

答:
When the Create Folder button is used in the Amazon S3 console, it creates a 'folder'. However, Amazon S3 does not use folders. Instead, it creates a zero-length object with the name of the folder. In this case, it created an object called folder1/.

However, when your code attempted to download this object as a file, your Operating System did not like the idea of creating a file with a name ending in a slash (/). In fact, you do not need to download this folder since the code is already using mkdir() to create the directory.

Therefore, the code can simply skip-over such objects, like this:

for obj in objs:
    if not obj.key.endswith('/'):
        # Your existing code here
```
<p>Alternatively, it could skip-over zero-length objects with:</p>
```    if obj.size > 0:
```

Body:
I am trying to download the s3 folder files into my windows system and I am getting Permission Error while executing the my python script in windows system.
Any help will be highly Appreciate.

# creating folder but no data.
import boto3
import os
from pathlib import Path

s3 = boto3.resource('s3')

bucket = s3.Bucket('mybucketname')

key = 'foldername1'
objs = list(bucket.objects.filter(Prefix=key))

for obj in objs:
    # print(obj.key)

    # remove the file name from the object key
    obj_path = os.path.dirname(obj.key)

    # create nested directory structure
    Path(obj_path).mkdir(parents=True, exist_ok=True)

    # save file with full path locally
    bucket.download_file(obj.key, obj.key)

Error I am getting below:

Traceback (most recent call last):
  File "C:\MSA\EO projects\FEB 2022 WORKS\REMOTE AWZ\d6.py", line 23, in <module>
    bucket.download_file(obj.key, obj.key)
  File "C:\Program Files\Python37\lib\site-packages\boto3\s3\inject.py", line 246, in bucket_download_file
    ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
  File "C:\Program Files\Python37\lib\site-packages\boto3\s3\inject.py", line 172, in download_file
    extra_args=ExtraArgs, callback=Callback)
  File "C:\Program Files\Python37\lib\site-packages\boto3\s3\transfer.py", line 307, in download_file
    future.result()
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\futures.py", line 106, in result
    return self._coordinator.result()
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\futures.py", line 265, in result
    raise self._exception
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\tasks.py", line 126, in __call__
    return self._execute_main(kwargs)
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\tasks.py", line 150, in _execute_main
    return_value = self._main(**kwargs)
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\download.py", line 601, in _main
    osutil.rename_file(fileobj.name, final_filename)
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\utils.py", line 273, in rename_file
    rename_file(current_filename, new_filename)
  File "C:\Program Files\Python37\lib\site-packages\s3transfer\compat.py", line 25, in rename_file
    os.remove(new_filename)
PermissionError: [WinError 5] Access is denied: 'foldername1/'

Body:
When the Create Folder button is used in the Amazon S3 console, it creates a 'folder'. However, Amazon S3 does not use folders. Instead, it creates a zero-length object with the name of the folder. In this case, it created an object called folder1/.

However, when your code attempted to download this object as a file, your Operating System did not like the idea of creating a file with a name ending in a slash (/). In fact, you do not need to download this folder since the code is already using mkdir() to create the directory.

Therefore, the code can simply skip-over such objects, like this:

for obj in objs:
    if not obj.key.endswith('/'):
        # Your existing code here

Alternatively, it could skip-over zero-length objects with:

    if obj.size > 0:


问:
How do I differentiate b/w a ipfs url/path (content-addressed) from normal-url (location-addressed)?
I am trying to fetch nft-metadata for the nfts added on my platform. Some Nfts contains ipfs-urls as their tokenURIs and I need a mechanism to differentiate them from normal-urls (location-addressed urls).

I was using is-ipfs, but it gives false returns even for valid ipfs-urls!

```<code>if (mtokenUri) {
  var res;
  var data;

  console.log("### ipfs url check ###");
  console.log(
    isIPFS.urlOrPath(
      "ipfs://bafybeihbsysdkemc3kyylegtfopkrcfiih4exnasoql2q36fb4zawlrwhy/volcano.json",
    ),
  );
  // false for "ipfs://bafybeihbsysdkemc3kyylegtfopkrcfiih4exnasoql2q36fb4zawlrwhy/volcano.json"

  //this is not very reliable
  if (isIPFS.urlOrPath(mtokenUri)) {
    //gives false even for a valid ipfs-url
    console.log("inside erc721 ipfs: ");

    isIpfsUrl = true;
    console.log("*** 721 isIpfs url ***");
    console.log(isIPFS.urlOrPath(mtokenUri));
    // example ccid = 'QmPzhc9ezphJ85qJWfVVpeHkPieDJznpYduGhMYD7Z4Ac9'
    const cid_eg2 =
      "bafybeihbsysdkemc3kyylegtfopkrcfiih4exnasoql2q36fb4zawlrwhy/volcano.json";
    try {
      res = await ipfs.cat(mtokenUri);
      // data = await res.json()
      console.log(res);
    } catch (error) {
      console.log(error);
    }

    //shows:cat {<suspended>}
  } else {
    //do normal fetch

    try {
      res = await fetch(mtokenUri);
      data = await res.json();

      console.log("erc721 normal fetch");
      console.log("*** Normal fetch data *** ");

      console.log(data);
      _imageUrl = data.image;
      _name = data.name;
      _description = data.description;
    } catch (error) {
      console.log(error);
    }
  }
}
</code>```

When I try to fetch a ipfs-url using 'fetch', it shows-

Is there any way to do this efficiently/reliably?

答:
Thanks to @AKX for the input.
Using this for now-</p>
```<code>  if (
      isIPFS.urlOrPath(theUri) ||
      mtokenUri.startsWith('ipfs://') ||
      mtokenUri.includes('/ipfs/') ||
      mtokenUri.includes('/bafy')
     ) {
       // parse/cat ipfs-url
       } else {
        // parse/fetch normal-non-ipfs-url
       }
</code>```

Body:
I am trying to fetch nft-metadata for the nfts added on my platform. Some Nfts contains ipfs-urls as their tokenURIs and I need a mechanism to differentiate them from normal-urls (location-addressed urls).

I was using is-ipfs, but it gives false returns even for valid ipfs-urls!

if (mtokenUri) {
  var res;
  var data;

  console.log("### ipfs url check ###");
  console.log(
    isIPFS.urlOrPath(
      "ipfs://bafybeihbsysdkemc3kyylegtfopkrcfiih4exnasoql2q36fb4zawlrwhy/volcano.json",
    ),
  );
  // false for "ipfs://bafybeihbsysdkemc3kyylegtfopkrcfiih4exnasoql2q36fb4zawlrwhy/volcano.json"

  //this is not very reliable
  if (isIPFS.urlOrPath(mtokenUri)) {
    //gives false even for a valid ipfs-url
    console.log("inside erc721 ipfs: ");

    isIpfsUrl = true;
    console.log("*** 721 isIpfs url ***");
    console.log(isIPFS.urlOrPath(mtokenUri));
    // example ccid = 'QmPzhc9ezphJ85qJWfVVpeHkPieDJznpYduGhMYD7Z4Ac9'
    const cid_eg2 =
      "bafybeihbsysdkemc3kyylegtfopkrcfiih4exnasoql2q36fb4zawlrwhy/volcano.json";
    try {
      res = await ipfs.cat(mtokenUri);
      // data = await res.json()
      console.log(res);
    } catch (error) {
      console.log(error);
    }

    //shows:cat {<suspended>}
  } else {
    //do normal fetch

    try {
      res = await fetch(mtokenUri);
      data = await res.json();

      console.log("erc721 normal fetch");
      console.log("*** Normal fetch data *** ");

      console.log(data);
      _imageUrl = data.image;
      _name = data.name;
      _description = data.description;
    } catch (error) {
      console.log(error);
    }
  }
}

When I try to fetch a ipfs-url using 'fetch', it shows-

Is there any way to do this efficiently/reliably?

Body:
Thanks to @AKX for the input.
Using this for now-

  if (
      isIPFS.urlOrPath(theUri) ||
      mtokenUri.startsWith('ipfs://') ||
      mtokenUri.includes('/ipfs/') ||
      mtokenUri.includes('/bafy')
     ) {
       // parse/cat ipfs-url
       } else {
        // parse/fetch normal-non-ipfs-url
       }


问:
Getting elements from an array where next element greater than previous by 1
I have an array:

```<code>int[] arr = {-4, -2, -1, 0, 1, 3, 4, 5, 6, 9, 10, 12, 13, 14, 18};
</code>```

The array is ordered in ascending order.
The main idea is to get elements and group them, where next element is greater than a previous by 1. The minimum length of such elements should be equal 3.

In output, I have to get a string:

```<code>"-4, (-2-1), (3-6), 9, 10, (12-14), 18"
</code>```

The first interval is:
-2, -1, 0, 1 - it should looks like range i.e -2-1

The next interval is:
3, 4, 5, 6 - it should looks like range i.e 3-6

9, 10 - the length is less than 3

So the last interval is:

12, 13, 14  it should looks like range i.e 12-14

答:
this answer was pre-edit.

You are printing input[i] but you are expecting the values in  input[i] - 1

when you run this in the debugger you can see it finds -1 (which has -2 before it, and equals -2 + 1). You then print the -1 you found.

If you want the output to contain the -2 , you should print input[i - 1]

post-edit:

you have grouped elements by braces which means you are looking for a sequence. This will require you to keep the start number somewhere. the code you originally posted (simple loop that checks left) will need a bit more work.

In rough terms:

```<code>if (continuing a range)
    if(this number is still in range / +1) continue
    else: stop the range and print it (start point plus current -1). if current -1 is the start point, don't use braces and range indicator. if it is different use braces and - between start and end)
else
    start a range. (keep track of the number you are on and continue.
</code>```

that's what you need in pseudocode

Body:
I have an array:

int[] arr = {-4, -2, -1, 0, 1, 3, 4, 5, 6, 9, 10, 12, 13, 14, 18};

The array is ordered in ascending order.
The main idea is to get elements and group them, where next element is greater than a previous by 1. The minimum length of such elements should be equal 3.

In output, I have to get a string:

"-4, (-2-1), (3-6), 9, 10, (12-14), 18"

The first interval is:
-2, -1, 0, 1 - it should looks like range i.e -2-1

The next interval is:
3, 4, 5, 6 - it should looks like range i.e 3-6

9, 10 - the length is less than 3

So the last interval is:

12, 13, 14  it should looks like range i.e 12-14

Body:
this answer was pre-edit.

You are printing input[i] but you are expecting the values in  input[i] - 1

when you run this in the debugger you can see it finds -1 (which has -2 before it, and equals -2 + 1). You then print the -1 you found.

If you want the output to contain the -2 , you should print input[i - 1]

post-edit:

you have grouped elements by braces which means you are looking for a sequence. This will require you to keep the start number somewhere. the code you originally posted (simple loop that checks left) will need a bit more work.

In rough terms:

if (continuing a range)
    if(this number is still in range / +1) continue
    else: stop the range and print it (start point plus current -1). if current -1 is the start point, don't use braces and range indicator. if it is different use braces and - between start and end)
else
    start a range. (keep track of the number you are on and continue.

that's what you need in pseudocode


问:
Property 'getFrameworkComponentInstance' does not exist on type 'ICellRendererComp'
I'm trying to get the instance of cell renderer (Angular component) on rowSelected event handler:

```<code>onRowSelected($event) {
    var selectedRow = this.gridApi.getDisplayedRowAtIndex($event.rowIndex);
    var params = { columns: ['added'], rowNodes: [selectedRow]};
    var instances = this.gridApi.getCellRendererInstances(params);
    if (instances.length > 0) {
        var wrapperInstance = instances[0].getFrameworkComponentInstance();
    }
}
</code>```

Unfortunately I get the error during the compilation of angular application (ts):

Property 'getFrameworkComponentInstance' does not exist on type 'ICellRendererComp'

The implementation comes from official documentation at https://www.ag-grid.com/javascript-grid-cell-rendering-components/ (find Accessing Cell Renderer Instances).

Here is possible factory method which define public getFrameworkComponentInstance.

It's unexpected situation because when I debug this method I can get the renderer with method getFrameworkComponentInstance on instances[0].

答:
From v27 of AG Grid

You no longer need to use the method getFrameworkComponentInstance(), as your Angular component will be returned directly from getCellRendererInstances(). So you can loop through the components and call their methods directly.

```<code>const instances = this.gridApi.getCellRendererInstances(params) as MyComponent[];

instances.forEach((instance) => {
  instance.myComponentFunction();
});

</code>```

See updated documentation here: Component Cell Renderer

Body:
I'm trying to get the instance of cell renderer (Angular component) on rowSelected event handler:

onRowSelected($event) {
    var selectedRow = this.gridApi.getDisplayedRowAtIndex($event.rowIndex);
    var params = { columns: ['added'], rowNodes: [selectedRow]};
    var instances = this.gridApi.getCellRendererInstances(params);
    if (instances.length > 0) {
        var wrapperInstance = instances[0].getFrameworkComponentInstance();
    }
}

Unfortunately I get the error during the compilation of angular application (ts):

Property 'getFrameworkComponentInstance' does not exist on type 'ICellRendererComp'

The implementation comes from official documentation at https://www.ag-grid.com/javascript-grid-cell-rendering-components/ (find Accessing Cell Renderer Instances).

Here is possible factory method which define public getFrameworkComponentInstance.

It's unexpected situation because when I debug this method I can get the renderer with method getFrameworkComponentInstance on instances[0].

Body:
From v27 of AG Grid

You no longer need to use the method getFrameworkComponentInstance(), as your Angular component will be returned directly from getCellRendererInstances(). So you can loop through the components and call their methods directly.

const instances = this.gridApi.getCellRendererInstances(params) as MyComponent[];

instances.forEach((instance) => {
  instance.myComponentFunction();
});

See updated documentation here: Component Cell Renderer


问:
Magento separate price.phtml
How can I add a new price template to the category view (template/catalog/product/list.phtml) without changing the price template that is used in (template/catalog/product/view.phtml)? Both files uses the template/catalog/product/price.phtml, but I need a separate price template in template/catalog/product/list.phtml.</p>

答:
It is not a really nice solution, but you could copy price.phtml to your custom theme and then check whether you are on a category page with:</p>

```<code>$handles = $this->getLayout()->getUpdate()->getHandles();
if (array_search('catalog_category_view', $handles)) {
    echo 'here you can do other things';
}
</code>```

Title: Magento separate price.phtml

Body:
It is not a really nice solution, but you could copy price.phtml to your custom theme and then check whether you are on a category page with:

$handles = $this->getLayout()->getUpdate()->getHandles();
if (array_search('catalog_category_view', $handles)) {
    echo 'here you can do other things';
}


问:
"Only numeric data" error on logs-base metric GCP
I have use Ops agent to send log to Cloud Logging
Uploaded logs
And then I used these logs to create logs-base metric with field name is jsonPayload.data
Create logs-base metric
After that, I review logs of that metric to make sure input data is correct
Review input data
But finally, the result is Cloud metric show error Only numeric data can be drawn as a line chart. I have checked at "review logs" step and make sure that input data is numeric. Can anyone help me explain that?
Error

Sorry, I'm new to stackoverflow, so I can't upload image directly.

答: You can see the Metric by changing the aligner to percentile.


问:
Void function required to return value?
I wrote a function as follows which is used to create pthread:

```<code>void *downloadfile(void *arg)
{
  char *req_path = NULL;
  char local_path[PATH_BUFFER_SIZE];
  int returncode = 0;
  gfcrequest_t *gfr = NULL;
  FILE *file = NULL;
  int i = 0;

  /* Build your queue of requests here */
  for (i = 0; i < nrequests; i++) {
    // pthread mutex locking
    // doing something
    // pthread mutex unlocking

    localPath(req_path, local_path);

    file = openFile(local_path);

    gfr = gfc_create();
    gfc_set_server(&gfr, server);
    gfc_set_path(&gfr, req_path);
    gfc_set_port(&gfr, port);
    gfc_set_writefunc(&gfr, writecb);
    gfc_set_writearg(&gfr, file);

    fprintf(stdout, "Requesting %s%s\n", server, req_path);

    if (0 > (returncode = gfc_perform(&gfr))) {
      fprintf(stdout, "gfc_perform returned an error %d\n", returncode);
      fclose(file);
      if (0 > unlink(local_path))
        fprintf(stderr, "warning: unlink failed on %s\n", local_path);
    } else {
      fclose(file);
    }

    if (gfc_get_status(&gfr) != GF_OK) {
      if (0 > unlink(local_path))
        fprintf(stderr, "warning: unlink failed on %s\n", local_path);
    }

    fprintf(stdout, "Status: %s\n", gfc_strstatus(gfc_get_status(&gfr)));
    fprintf(stdout, "Received %zu of %zu bytes\n", gfc_get_bytesreceived(&gfr),
            gfc_get_filelen(&gfr));

    gfc_cleanup(&gfr);
    req_path = NULL;
  }
//  return 0;
}
</code>```

I commented out the "return 0;" statement because this is a void function thus should not return any value.  But the compiler complains that

error: control reaches end of non-void function

If I uncomment the "return 0;" statement, the error goes away.  I am so puzzled.  How can the compiler require a void function to return value?  Could somebody please help out?

答:
because this is a void function

No it isn't. It is a function returning a void*. Pthreads only work with functions of the signature void* f (void*). That's the only kind of function you can use, as per pthread library design. You don't get to chose anything else.

error: control reaches end of non-void function

This is a nice error to get since your code without the return statement contains undefined behavior. Specifically C17 6.9.1/12 says:

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

As in, if you didn't use return and the caller checks the result - which will happen here inside the pthreads lib, then anything can happen. It is a bug.

If you aren't interested in returning anything from the function, you must return NULL; or the equivalent return 0;.

Notably, the difference between returning void and void* is fundamental C - it is something you should have studied at a much earlier stage before moving on to multi-threading, which is a more advanced topic.

Title: Void function required to return value?

Body:
I wrote a function as follows which is used to create pthread:

void *downloadfile(void *arg)
{
  char *req_path = NULL;
  char local_path[PATH_BUFFER_SIZE];
  int returncode = 0;
  gfcrequest_t *gfr = NULL;
  FILE *file = NULL;
  int i = 0;

  /* Build your queue of requests here */
  for (i = 0; i < nrequests; i++) {
    // pthread mutex locking
    // doing something
    // pthread mutex unlocking

    localPath(req_path, local_path);

    file = openFile(local_path);

    gfr = gfc_create();
    gfc_set_server(&gfr, server);
    gfc_set_path(&gfr, req_path);
    gfc_set_port(&gfr, port);
    gfc_set_writefunc(&gfr, writecb);
    gfc_set_writearg(&gfr, file);

    fprintf(stdout, "Requesting %s%s\n", server, req_path);

    if (0 > (returncode = gfc_perform(&gfr))) {
      fprintf(stdout, "gfc_perform returned an error %d\n", returncode);
      fclose(file);
      if (0 > unlink(local_path))
        fprintf(stderr, "warning: unlink failed on %s\n", local_path);
    } else {
      fclose(file);
    }

    if (gfc_get_status(&gfr) != GF_OK) {
      if (0 > unlink(local_path))
        fprintf(stderr, "warning: unlink failed on %s\n", local_path);
    }

    fprintf(stdout, "Status: %s\n", gfc_strstatus(gfc_get_status(&gfr)));
    fprintf(stdout, "Received %zu of %zu bytes\n", gfc_get_bytesreceived(&gfr),
            gfc_get_filelen(&gfr));

    gfc_cleanup(&gfr);
    req_path = NULL;
  }
//  return 0;
}

I commented out the "return 0;" statement because this is a void function thus should not return any value.  But the compiler complains that

error: control reaches end of non-void function

If I uncomment the "return 0;" statement, the error goes away.  I am so puzzled.  How can the compiler require a void function to return value?  Could somebody please help out?


问:
Why does mutableStateOf without remember work sometimes?
I've been playing with Jetpack Compose Desktop. I noticed something I really don't understand:

```<code>import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

@Composable
@Preview
fun App() {
    var text by mutableStateOf("Hello, World!")

    MaterialTheme {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}
</code>```

Why am I able to change the text in the TextField? I thought, that on every recompose the mutable state get reinstanciated with the initial Value: so the Text should not be able to change

```<code>import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

@Composable
@Preview
fun App() {
    var text by mutableStateOf("Hello, World!")

    Column {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}
</code>```

However, if you replace the MaterialTheme with an Column it suddendly works as expected and you aren't able to change the text in the TextField.

Why is that? Is that a bug or a feature?

答:
It's a feature of Compose about scoping and smart recomposition. You can check my detailed answer here.

What really makes your whole Composable to recompose  is Column having inline keyword.

```<code>@Composable
inline fun Column(
    modifier: Modifier = Modifier,
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    content: @Composable ColumnScope.() -> Unit
) {
    val measurePolicy = columnMeasurePolicy(verticalArrangement, horizontalAlignment)
    Layout(
        content = { ColumnScopeInstance.content() },
        measurePolicy = measurePolicy,
        modifier = modifier
    )
}
</code>```

Let's say you have a Composable  sets background color initially at composition and changes at each recomposition which creates its own scope. Lambda without inline is considered a scope.

```<code>@Composable
fun RandomColorColumn(content: @Composable () -> Unit) {

    Column(
        modifier = Modifier
            .padding(4.dp)
            .shadow(1.dp, shape = CutCornerShape(topEnd = 8.dp))
            .background(getRandomColor())
            .padding(4.dp)
    ) {
        content()
    }
}
</code>```

With

```<code>@Composable
fun App2() {
    var text by mutableStateOf("Hello, World!")

    RandomColorColumn {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}
</code>```

And one with Column

```<code>@Composable
fun App() {
    var text by mutableStateOf("Hello, World!")

    Column(modifier = Modifier.background(getRandomColor())) {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}
</code>```

Random color function

```<code>fun getRandomColor() =  Color(
    red = Random.nextInt(256),
    green = Random.nextInt(256),
    blue = Random.nextInt(256),
    alpha = 255
)
</code>```

You will see that Column background color will change every time you change text but not with App2()

Body:
I've been playing with Jetpack Compose Desktop. I noticed something I really don't understand:

import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

@Composable
@Preview
fun App() {
    var text by mutableStateOf("Hello, World!")

    MaterialTheme {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}

Why am I able to change the text in the TextField? I thought, that on every recompose the mutable state get reinstanciated with the initial Value: so the Text should not be able to change

import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

@Composable
@Preview
fun App() {
    var text by mutableStateOf("Hello, World!")

    Column {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

fun main() = application {
    Window(onCloseRequest = ::exitApplication) {
        App()
    }
}

However, if you replace the MaterialTheme with an Column it suddendly works as expected and you aren't able to change the text in the TextField.

Why is that? Is that a bug or a feature?

Body:
It's a feature of Compose about scoping and smart recomposition. You can check my detailed answer here.

What really makes your whole Composable to recompose  is Column having inline keyword.

@Composable
inline fun Column(
    modifier: Modifier = Modifier,
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    content: @Composable ColumnScope.() -> Unit
) {
    val measurePolicy = columnMeasurePolicy(verticalArrangement, horizontalAlignment)
    Layout(
        content = { ColumnScopeInstance.content() },
        measurePolicy = measurePolicy,
        modifier = modifier
    )
}

Let's say you have a Composable  sets background color initially at composition and changes at each recomposition which creates its own scope. Lambda without inline is considered a scope.

@Composable
fun RandomColorColumn(content: @Composable () -> Unit) {

    Column(
        modifier = Modifier
            .padding(4.dp)
            .shadow(1.dp, shape = CutCornerShape(topEnd = 8.dp))
            .background(getRandomColor())
            .padding(4.dp)
    ) {
        content()
    }
}

With

@Composable
fun App2() {
    var text by mutableStateOf("Hello, World!")

    RandomColorColumn {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

And one with Column

@Composable
fun App() {
    var text by mutableStateOf("Hello, World!")

    Column(modifier = Modifier.background(getRandomColor())) {
        TextField(text, onValueChange = { text = it })
        Button(onClick = {
            text = "Hello, Desktop!"
        }) {
            Text(text)
        }
    }
}

Random color function

fun getRandomColor() =  Color(
    red = Random.nextInt(256),
    green = Random.nextInt(256),
    blue = Random.nextInt(256),
    alpha = 255
)

You will see that Column background color will change every time you change text but not with App2()


问:
MVC - View word document in iframe window
I have iframe tag in MVC razor file. I am able to load text, pdf files in iframe. here, iframe source is nothing but blob path. here blob is nothing but data from azure blob storage. but I am not able to see word document after rendering is complete , iframe shows blank.

below is  iframe window-

```<code><iframe id="frm" src="<blob path>"></iframe>
</code>```

is iframe compatible with word document? if not, what are other ways we can show word document file in an MVC application.

答:
Hi there you can use Google Document viewer for this like below :

```<code><iframe src="https://docs.google.com/gview?url=http://remote.url.tld/path/to/document.doc&embedded=true"></iframe>
</code>```

or Office 365 viewer :

```<code><iframe src='https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc' width='1366px' height='623px' frameborder='0'>This is an embedded <a target='_blank' href='http://office.com'>Microsoft Office</a> document, powered by <a target='_blank' href='http://office.com/webapps'>Office Online</a>.</iframe>
</code>```

Regards

Body:
I have iframe tag in MVC razor file. I am able to load text, pdf files in iframe. here, iframe source is nothing but blob path. here blob is nothing but data from azure blob storage. but I am not able to see word document after rendering is complete , iframe shows blank.

below is  iframe window-

<iframe id="frm" src="<blob path>">

is iframe compatible with word document? if not, what are other ways we can show word document file in an MVC application.

Body:
Hi there you can use Google Document viewer for this like below :

<iframe src="https://docs.google.com/gview?url=http://remote.url.tld/path/to/document.doc&embedded=true"></iframe>

or Office 365 viewer :

<iframe src='https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc' width='1366px' height='623px' frameborder='0'>This is an embedded <a target='_blank' href='http://office.com'>Microsoft Office</a> document, powered by <a target='_blank' href='http://office.com/webapps'>Office Online</a>.</iframe>

Regards


问:
Not able to upload/get the AWS bucket files in gov-cloud account
I'm able to access the s3 files in the normal AWS account but while migrating to gov-cloud the same code throws following errors for upload/get the contents of the bucket

```<code>InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records.
</code>```

and

```<code>code: 'Forbidden',
region: null,
time: 2022-01-31T16:13:56.658Z,
requestId: 'VJEF4741265DQNA3DF',
extendedRequestId: 'i6cztQJ5u/u9u0a0UZS412365789yshyGmplnn4Ph4qhabm52145f8i8sCITROMYx52Y65oAKE=',
cfId: undefined,
statusCode: 403,
retryable: false,
retryDelay: 53.65986294598015
</code>```

All the keys and policies are configured but no idea where's it getting failed

Here is the code snippet:

const AWS = require('aws-sdk');
const fs = require('fs');

const s3 = new AWS.S3({
  accessKeyId: 'ACCESS_KEY',
  secretAccessKey: 'SECRET_KEY',
});
const fileName="Capture.png"
const fileContent = fs.readFileSync(fileName);

const params = {
  Bucket: 'upload', // pass your bucket name
  Key: `test.jpg`,
  Body: fileContent,
  ACL: 'public-read',
};
s3.headObject(
  {
    Bucket: 'upload',
    Key: `KEY`,
  },
  (err, data) => {
    if(err){
      console.log(err)
    }
    else{
      console.log("data",data)
    }
  })
s3.upload(params, function(err, data) {
  if (err) {
    throw err;
  }
  console.log(`File uploaded successfully. ${data.Location}`);
});
```

Please suggest any solution for the above error if have any.

Thanks in Advance

答:
Had similar issue with GovCloud S3 when using aws cli (not SDK) but I assume it's the same.
For me adding region parameter (with relevant value us-gov-west-1 / us-gov-east-1 )to command, which wasn't necessary in other AWS regions, solved it.
try adding region to your new AWS.S3() config

https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/cli-and-api-access.html

Body:
I'm able to access the s3 files in the normal AWS account but while migrating to gov-cloud the same code throws following errors for upload/get the contents of the bucket

InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records.

and

code: 'Forbidden',
region: null,
time: 2022-01-31T16:13:56.658Z,
requestId: 'VJEF4741265DQNA3DF',
extendedRequestId: 'i6cztQJ5u/u9u0a0UZS412365789yshyGmplnn4Ph4qhabm52145f8i8sCITROMYx52Y65oAKE=',
cfId: undefined,
statusCode: 403,
retryable: false,
retryDelay: 53.65986294598015

All the keys and policies are configured but no idea where's it getting failed

Here is the code snippet:

const AWS = require('aws-sdk');
const fs = require('fs');

const s3 = new AWS.S3({
  accessKeyId: 'ACCESS_KEY',
  secretAccessKey: 'SECRET_KEY',
});
const fileName="Capture.png"
const fileContent = fs.readFileSync(fileName);

const params = {
  Bucket: 'upload', // pass your bucket name
  Key: `test.jpg`,
  Body: fileContent,
  ACL: 'public-read',
};
s3.headObject(
  {
    Bucket: 'upload',
    Key: `KEY`,
  },
  (err, data) => {
    if(err){
      console.log(err)
    }
    else{
      console.log("data",data)
    }
  })
s3.upload(params, function(err, data) {
  if (err) {
    throw err;
  }
  console.log(`File uploaded successfully. ${data.Location}`);
});

Please suggest any solution for the above error if have any.

Thanks in Advance


问:
Error occuring while using win32 in vs code (in python )
I am trying to convert text to speech in Python 3.10.2 using the code:

import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")
```
<p>But there is continuously occuring an error:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):   File "d:\Program\Python programing\tempCodeRunnerFile.py", line 1, in <module>
    import win32com.client   File "C:\Users\ASUS\AppData\Roaming\Python\Python310\site-packages\win32com\client\__init__.py",
line 10, in <module>
    from . import dynamic   File "C:\Users\ASUS\AppData\Roaming\Python\Python310\site-packages\win32com\client\dynamic.py",
line 24, in <module>
    from . import build   File "C:\Users\ASUS\AppData\Roaming\Python\Python310\site-packages\win32com\client\build.py",
line 638, in <module>
    valid_identifier_chars = string.ascii_letters + string.digits + "_" AttributeError: module 'string' has no attribute 'ascii_letters'
</code>```

答:
you wrote two lines of code in the same line
Try this

```<code>import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")
</code>```

or try to put a semicolon after the first line of code
Try this

```<code>import win32com.client; speaker =win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")
</code>```

either way should work

Body:
I am trying to convert text to speech in Python 3.10.2 using the code:

import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")

But there is continuously occuring an error:

Traceback (most recent call last):   File "d:\Program\Python programing\tempCodeRunnerFile.py", line 1, in <module>
    import win32com.client   File "C:\Users\ASUS\AppData\Roaming\Python\Python310\site-packages\win32com\client\__init__.py",
line 10, in <module>
    from . import dynamic   File "C:\Users\ASUS\AppData\Roaming\Python\Python310\site-packages\win32com\client\dynamic.py",
line 24, in <module>
    from . import build   File "C:\Users\ASUS\AppData\Roaming\Python\Python310\site-packages\win32com\client\build.py",
line 638, in <module>
    valid_identifier_chars = string.ascii_letters + string.digits + "_" AttributeError: module 'string' has no attribute 'ascii_letters'

Body:
you wrote two lines of code in the same line
Try this

import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")

or try to put a semicolon after the first line of code
Try this

import win32com.client; speaker =win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("Hello, it works!")

either way should work


问:
MultiIndex DataFrame: Delete non-consecutive indices and re-index
I have a MultiIndex DataFrame, that looks like this:

```<code>                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
                3          6         6         6
                5          7         7         7
                6          8         8         8

</code>```

Now I want to drop all rows that have no direct preceding index and no direct subsequent index, e.g. row with index (1,3). The resulting DataFrame would look like this:

```<code>                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
                5          7         7         7
                6          8         8         8
</code>```

Afterwards I want to reindex the DataFrame so that each SecondIdx with no predecessor increments the FirstIdx and the SecondIdx starts to count from 0:

```<code>                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
       2        0          7         7         7
                1          8         8         8
</code>```

Does pandas implement any convenient and fast way to do these 2 operations (maybe combined in one step)?

Thanks!

答:
You can create columns by MultiIndex and then processing - get consecutive values by differencies per groups, create new groups g and for levels of MultiIndex use GroupBy.ngroup and GroupBy.cumcount:

```<code>df = df.reset_index()

g = df.groupby('FirstIdx')['SecondIdx'].diff().gt(1).cumsum()
df = df[df.groupby(['FirstIdx', g])['SecondIdx'].transform('size').gt(1)]

df['FirstIdx'] = df.groupby(['FirstIdx', g]).ngroup()
df['SecondIdx'] = df.groupby(['FirstIdx', g]).cumcount()

df = df.set_index(['FirstIdx','SecondIdx'])
print (df)
                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
0        0                 0         0         0
         1                 1         1         1
         2                 2         2         2
         3                 3         3         3
1        0                 4         4         4
         1                 5         5         5
2        0                 7         7         7
         1                 8         8         8
</code>```

Body:
I have a MultiIndex DataFrame, that looks like this:

                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
                3          6         6         6
                5          7         7         7
                6          8         8         8

Now I want to drop all rows that have no direct preceding index and no direct subsequent index, e.g. row with index (1,3). The resulting DataFrame would look like this:

                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
                5          7         7         7
                6          8         8         8

Afterwards I want to reindex the DataFrame so that each SecondIdx with no predecessor increments the FirstIdx and the SecondIdx starts to count from 0:

                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
       2        0          7         7         7
                1          8         8         8

Does pandas implement any convenient and fast way to do these 2 operations (maybe combined in one step)?

Thanks!

Body:
You can create columns by MultiIndex and then processing - get consecutive values by differencies per groups, create new groups g and for levels of MultiIndex use GroupBy.ngroup and GroupBy.cumcount:

df = df.reset_index()

g = df.groupby('FirstIdx')['SecondIdx'].diff().gt(1).cumsum()
df = df[df.groupby(['FirstIdx', g])['SecondIdx'].transform('size').gt(1)]

df['FirstIdx'] = df.groupby(['FirstIdx', g]).ngroup()
df['SecondIdx'] = df.groupby(['FirstIdx', g]).cumcount()

df = df.set_index(['FirstIdx','SecondIdx'])
print (df)
                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
0        0                 0         0         0
         1                 1         1         1
         2                 2         2         2
         3                 3         3         3
1        0                 4         4         4
         1                 5         5         5
2        0                 7         7         7
         1                 8         8         8


问:
Getting id of PHP 8 Socket
With the new socket instance returning from socket_create() in php 8, how do we get a numeric or unique reference to this socket in the way casting to int would work in earlier versions. This is used for many things, including connection tracking in log files and storing metadata about connections when they are passed into/return from socket_select().

Before php 8:

```<code>$socket_resource = socket_create(...);
$socket_id = (int)$socket_resource;
</code>```

After php 8

```<code>$socket_instance = socket_create(...);
$socket_id = (int)$socket_instance; // PHP Warning:  Object of class Socket could not be converted to int
</code>```

There is a new function in php 8 get_resource_id($resource) which looks the same as casting to int, but this does not work on sockets.

答: You can use spl_object_id() with any object. It's an arbitrary value that can be reused, but so are resource IDs.</p>

Title: Getting id of PHP 8 Socket

Body:
With the new socket instance returning from socket_create() in php 8, how do we get a numeric or unique reference to this socket in the way casting to int would work in earlier versions. This is used for many things, including connection tracking in log files and storing metadata about connections when they are passed into/return from socket_select().

Before php 8:

$socket_resource = socket_create(...);
$socket_id = (int)$socket_resource;

After php 8

$socket_instance = socket_create(...);
$socket_id = (int)$socket_instance; // PHP Warning:  Object of class Socket could not be converted to int

There is a new function in php 8 get_resource_id($resource) which looks the same as casting to int, but this does not work on sockets.


问:
How do I get the key from Map in a List and do a get rest request in Java
I want to do a get request and want to get all the jobs who have the "teacher" in it. In this case the map value 2 and 3.

How do I get there if I execute the code below then I only get the value from the Map 2. The best way is over a List? But how do I do it?

I have this method.

```<code>@GET
@Path("jobs")
public Job getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())) {
            System.out.println("I DID IT");
            System.out.println(entry.getKey());
            return berufe.get(entry.getKey());
        }

    }
    return berufe.get(id);
}
</code>```

and this Map:

```<code>jobs.put(1, new jobs(1, 1337, "student"));
jobs.put(2, new jobs(2, 420, "teacher"));
jobs.put(3, new jobs(3, 69, "schoolteacher"));
</code>```

---------------------------------EDIT----------------------------------

If I do this:

```<code>@GET
@Path("jobs")
public Collection<Job> getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    final Set<Beruf> result = new HashSet<>();

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase()) == true) {

            result.add(jobs.get(entry.getKey()));
        } else {
          return jobs.values();
        }

    }
    return result;
}
</code>```

I get with a discription all Map values back and without I get an Error.

What do I do wrong here?

答:
Your method getJobsId() returns on the first item it finds (inside the if statement), that's why you only get one result.

The usual pattern to collect a number of results would be to instantiate a suitable Collection before the for loop, and add each item that is found to this collection. Then, after the for loop, return the collection. I don't understand your code completely, but it would be something similar to the below (I'm sure it won't work if you just copy-paste, so read and understand what is going on ;-) ):

Set<Beruf> result = new HashSet<>();
for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
  if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())) {
    result.add(berufe.get(entry.getKey()));
  }
}
return result;
```
<p>Since Java 8, it has been much more concise (readable) to use the <code>Streams</code> interface and call <code>.filter</code> (and maybe <code>.map</code>) on it, then <code>.collect</code> the stream to a suitable collection and return that. Something similar to:</p>
<pre class="lang-java prettyprint-override"><code>return jobs.entrySet().stream()
  .filter(entry -> (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())))
  .map(entry -> berufe.get(entry.getKey()))
  .collect(Collectors.toSet());
</code>```

Body:
I want to do a get request and want to get all the jobs who have the "teacher" in it. In this case the map value 2 and 3.

How do I get there if I execute the code below then I only get the value from the Map 2. The best way is over a List? But how do I do it?

I have this method.

@GET
@Path("jobs")
public Job getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())) {
            System.out.println("I DID IT");
            System.out.println(entry.getKey());
            return berufe.get(entry.getKey());
        }

    }
    return berufe.get(id);
}

and this Map:

jobs.put(1, new jobs(1, 1337, "student"));
jobs.put(2, new jobs(2, 420, "teacher"));
jobs.put(3, new jobs(3, 69, "schoolteacher"));

---------------------------------EDIT----------------------------------

If I do this:

@GET
@Path("jobs")
public Collection<Job> getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    final Set<Beruf> result = new HashSet<>();

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase()) == true) {

            result.add(jobs.get(entry.getKey()));
        } else {
          return jobs.values();
        }

    }
    return result;
}

I get with a discription all Map values back and without I get an Error.

What do I do wrong here?

Body:
Your method getJobsId() returns on the first item it finds (inside the if statement), that's why you only get one result.

The usual pattern to collect a number of results would be to instantiate a suitable Collection before the for loop, and add each item that is found to this collection. Then, after the for loop, return the collection. I don't understand your code completely, but it would be something similar to the below (I'm sure it won't work if you just copy-paste, so read and understand what is going on ;-) ):

Set<Beruf> result = new HashSet<>();
for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
  if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())) {
    result.add(berufe.get(entry.getKey()));
  }
}
return result;

Since Java 8, it has been much more concise (readable) to use the Streams interface and call .filter (and maybe .map) on it, then .collect the stream to a suitable collection and return that. Something similar to:

return jobs.entrySet().stream()
  .filter(entry -> (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())))
  .map(entry -> berufe.get(entry.getKey()))
  .collect(Collectors.toSet());


问:
ffmpeg vstats command
I want to dump the bit rate per frame of a video. I am trying to get this information using -vstats command. When I run this command -

```<code>ffmpeg -i input.mp4 -vstats
</code>```

it shows at least one file should be defined.

I would really appreciate if anyone could suggest me any approach to get bit rate per frame.

Thanks

答: You'll want to use ffprobe, here, which just dumps the info about a video without trying to write an output.

Title: ffmpeg vstats command

Body:
I want to dump the bit rate per frame of a video. I am trying to get this information using -vstats command. When I run this command -

ffmpeg -i input.mp4 -vstats

it shows at least one file should be defined.

I would really appreciate if anyone could suggest me any approach to get bit rate per frame.

Thanks


问:
Changing color of column header in DBGrid with Theme settings on
Is it possible to change background color of Title in TDBGrid if i have some project appearance style, for example Iceberg Classico?

This code works fine when i turn off project appearance and change Grids drawing style to classic

```<code> DBGrid1.DrawingStyle := gdsClassic;
 DBGrid1.Columns[0].Title.Color := clRed;
</code>```

Otherwise this is not working.

Can the color be changed without changing drawing style and appearance?

答:
All you need to do is to change the DBGrid
DrawingStyle properity to gdsGradient & then change the gradentEndColor & gradentStartColor to be the same color ..

Body:
Is it possible to change background color of Title in TDBGrid if i have some project appearance style, for example Iceberg Classico?

This code works fine when i turn off project appearance and change Grids drawing style to classic

 DBGrid1.DrawingStyle := gdsClassic;
 DBGrid1.Columns[0].Title.Color := clRed;

Otherwise this is not working.

Can the color be changed without changing drawing style and appearance?