问:
Migrating data from live RDS database instance associated with one AWS account to a new RDS database instance associated with another AWS account
I am working with a Sprint boot application hosted on AWS. Application data gets stored in AWS RDS. Now I have set up another AWS account where I would like to migrate the data from the RDS instance associated with the current AWS account.

In this regard, after going through several posts here, it seems, the steps to do the same are as follows:

```<code>1. Create a snapshot of the database in the RDS database instance associated with the current AWS account.
2. Share the snapshot with the new AWS account.
3. Import the data from this snapshot to the RDS instance associated with the new AWS account.
</code>```

One problem with this approach is: I have to make the application unavailable to the end-users until all the steps are completed as well as the application with the database hosted in the new AWS account starts running, otherwise there will be always some delta remaining to be migrated.

But, I would like to migrate the data from an existing instance to the new instance without making the application unavailable to end-users, I did not find any suitable approach to achieve the same.

Could anyone please help here? Thanks.

答:
Good article on how to setup cross-account replication:
https://aws.amazon.com/premiumsupport/knowledge-center/rds-mysql-cross-region-replica/

Another way is using AWS Database Migration Services (AWS DMS).

You can create a migration task, and set the original database as the source endpoint, and the new database as a destination endpoint.

Next create a task with "Full load, ongoing replication" settings.

Some caveats: make sure to enable replication on the source database and it uses RAW bin log format for MySQL/MariaDB. More details here: https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.MySQL.html
It also damaged the destination tables structure in my case.

Body:
I am working with a Sprint boot application hosted on AWS. Application data gets stored in AWS RDS. Now I have set up another AWS account where I would like to migrate the data from the RDS instance associated with the current AWS account.

In this regard, after going through several posts here, it seems, the steps to do the same are as follows:

1. Create a snapshot of the database in the RDS database instance associated with the current AWS account.
2. Share the snapshot with the new AWS account.
3. Import the data from this snapshot to the RDS instance associated with the new AWS account.

One problem with this approach is: I have to make the application unavailable to the end-users until all the steps are completed as well as the application with the database hosted in the new AWS account starts running, otherwise there will be always some delta remaining to be migrated.

But, I would like to migrate the data from an existing instance to the new instance without making the application unavailable to end-users, I did not find any suitable approach to achieve the same.

Could anyone please help here? Thanks.


来源: stackexchange

问:
Angular TypeScript: waiting for a void method to run before another method
I have a method in an Angular component that pulls data via HttpClient subscription, and assigns it to an attributes this.allData, then instantiates an empty dictionary of parameters based on this, to pass to a second function:

```<code>export class TestComponent implements OnInit {

  allData: object[] = []
  activeData: object = {}

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.getData()
    this.makeRequestBasedOnData()
  }

  getData() {
    this.http.get(this.url).subscribe(res => {
      for (let datum of res["data"]) {
        this.allData.push({
          "key": Object.keys(datum)[0],
          "values": Object.values(datum)[0]
        })
        this.activeData[Object.keys(datum)[0]] = ""
      }
    })
  }

  makeRequestBasedOnData() {
    let testParams = this.activeData
    console.log(testParam)
  }

}
</code>```

I need these steps to happen sequentially. At the moment, logging the testParams in makeRequestBasedOnData() simply shows an empty object {}. When I try to return arbitrarily in the first method, I get a TypeScript error that you cannot assign a promise to type void.

How do I enforce synchronicity here even though neither method actually returns anything?

答:
You can return Observable from getData method and proceed with any other methods within subscribe:

```<code>ngOnInit(): void {
  this.getData().subscribe(() => this.makeRequestBasedOnData());
}

getData() {
  return this.http.get(this.url).pipe(
    tap(res => {
      // update allData
    })
  );
}
</code>```

where:

pipe method allows us to provide any kind of transformation with the data returned from http.get(...) call.

tap is a rxjs operator for side-effects, meaning that we can do everything we want with the response without modifying Observable flow.

ContentLicense: CC BY-SA 4.0

Body:
I have a method in an Angular component that pulls data via HttpClient subscription, and assigns it to an attributes this.allData, then instantiates an empty dictionary of parameters based on this, to pass to a second function:

export class TestComponent implements OnInit {

  allData: object[] = []
  activeData: object = {}

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.getData()
    this.makeRequestBasedOnData()
  }

  getData() {
    this.http.get(this.url).subscribe(res => {
      for (let datum of res["data"]) {
        this.allData.push({
          "key": Object.keys(datum)[0],
          "values": Object.values(datum)[0]
        })
        this.activeData[Object.keys(datum)[0]] = ""
      }
    })
  }

  makeRequestBasedOnData() {
    let testParams = this.activeData
    console.log(testParam)
  }

}

I need these steps to happen sequentially. At the moment, logging the testParams in makeRequestBasedOnData() simply shows an empty object {}. When I try to return arbitrarily in the first method, I get a TypeScript error that you cannot assign a promise to type void.

How do I enforce synchronicity here even though neither method actually returns anything?

Body:
You can return Observable from getData method and proceed with any other methods within subscribe:

ngOnInit(): void {
  this.getData().subscribe(() => this.makeRequestBasedOnData());
}

getData() {
  return this.http.get(this.url).pipe(
    tap(res => {
      // update allData
    })
  );
}

where:

pipe method allows us to provide any kind of transformation with the data returned from http.get(...) call.

tap is a rxjs operator for side-effects, meaning that we can do everything we want with the response without modifying Observable flow.


问:
Reusing getStaticProps in Next.js
I'm creating a blog with Next.js and GraphCMS, and I have an ArticleList component that appears on multiple pages (e.g. on my homepage, under each article as a recommendation, etc.).

However, since the article list is being populated from my CMS, I'm using getStaticProps. And since I can't use getStaticProps on the component-level, I'm re-writing the same getStaticProps function on every single page. Is there any way for me to easily reuse this code and share it across pages?

Would love to know if there are any best practices for this.

答:
You could define your getStaticProps function in a separate file, using a re-export, for example:

```<code>// lib/getStaticProps.js

export function getStaticProps(context) {
  return {
    props: {
      // some cool props
    },
  }
}
</code>```
```<code>// pages/index.js

export default function Page(props) {
  // ...
}

export { getStaticProps } from "../lib/getStaticProps"
</code>```

Title: Reusing getStaticProps in Next.js

Body:
You could define your getStaticProps function in a separate file, using a re-export, for example:

// lib/getStaticProps.js

export function getStaticProps(context) {
  return {
    props: {
      // some cool props
    },
  }
}

// pages/index.js

export default function Page(props) {
  // ...
}

export { getStaticProps } from "../lib/getStaticProps"


问:
Pointer events firing at the wrong time
I am running into a problem where mousing over one object in my scene causes all of the onPointerOver listeners in the scene to fire at once, sometimes randomly. I think this is because of the way that I am adding components to the scene, but I'm not sure.

What could be causing this behavior? Here is an example of my code for reference.

I have a SampleObject constructor like this, which takes an image path and a mouseOver function as props:

```<code>const SampleObject = ({ image, mouseOver }) => {
    const ref = useRef();
    const texture = useLoader(TextureLoader, image);
    return (<mesh ref={ref} onMouseOver={mouseOver}>
       <planeBufferGeometry attach="geometry" />
       <meshPhongMaterial attach="material" map={texture}/>
    </mesh>)
}
export default React.memo(SampleObject);
</code>```

And in the render, I am loading it using Suspense because it involves loading an image. The onPointerOver listener updates a state:

```<code><Suspense fallback={null}>
    <SampleObject image={ images(`./image.png`).default } onPointerOver={() => {  setMiscState(true)  }} />
    <SampleObject image={ images(`./image.png`).default } onPointerOver={() => {  setMiscState(false)  }} />
</Suspense>
</code>```

Therefore, when the state changes, all of these SampleObject components re-render. Is that what's causing the onPointerOver events to fire at the wrong times?

答:
This problem occurs in an outdated version of react-three-fiber. Update the package to fix it.

Otherwise, to prevent this problem, enclose each object in a separate Suspense wrapper:

```<code>[

<Suspense key='suspense1' fallback={null}>
    <SampleObject image={ images(`./image.png`).default } onPointerOver={() => {  setMiscState(true)  }} />
</Suspense>,

<Suspense key='suspense2' fallback={null}>
    <SampleObject image={ images(`./image.png`).default } onPointerOver={() => {  setMiscState(false)  }} />
</Suspense>

]
</code>```

Title: Pointer events firing at the wrong time

Body:
I am running into a problem where mousing over one object in my scene causes all of the onPointerOver listeners in the scene to fire at once, sometimes randomly. I think this is because of the way that I am adding components to the scene, but I'm not sure.

What could be causing this behavior? Here is an example of my code for reference.

I have a SampleObject constructor like this, which takes an image path and a mouseOver function as props:

const SampleObject = ({ image, mouseOver }) => {
    const ref = useRef();
    const texture = useLoader(TextureLoader, image);
    return (<mesh ref={ref} onMouseOver={mouseOver}>
       <planeBufferGeometry attach="geometry" />
       <meshPhongMaterial attach="material" map={texture}/>
    </mesh>)
}
export default React.memo(SampleObject);

And in the render, I am loading it using Suspense because it involves loading an image. The onPointerOver listener updates a state:

<Suspense fallback={null}>
    <SampleObject image={ images(`./image.png`).default } onPointerOver={() => {  setMiscState(true)  }} />
    <SampleObject image={ images(`./image.png`).default } onPointerOver={() => {  setMiscState(false)  }} />
</Suspense>

Therefore, when the state changes, all of these SampleObject components re-render. Is that what's causing the onPointerOver events to fire at the wrong times?

Body:
This problem occurs in an outdated version of react-three-fiber. Update the package to fix it.

Otherwise, to prevent this problem, enclose each object in a separate Suspense wrapper:

[

<Suspense key='suspense1' fallback={null}>
    <SampleObject image={ images(`./image.png`).default } onPointerOver={() => {  setMiscState(true)  }} />
</Suspense>,

<Suspense key='suspense2' fallback={null}>
    <SampleObject image={ images(`./image.png`).default } onPointerOver={() => {  setMiscState(false)  }} />
</Suspense>

]


问:
Receive message from MQTT in android service
I have to create an Android app that can receive message from a sensor and send a notification to the user when a message is received. I have to do this with out using service like Google Firebase because all the system must run locally. I thought to use MQTT in a service, but when I kill the app, it disconnect from the broker. If the app is running in background this implementation works but I need to keep the connection alive also when app is killed.

This is my implementation of the service:

```<code>package it.unisalento.sonoff.helper;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.net.wifi.aware.AttachCallback;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.ArrayList;
import java.util.List;

import it.unisalento.sonoff.R;
import it.unisalento.sonoff.view.MainActivity;

public class Service extends android.app.Service {
    private Looper serviceLooper;
    private ServiceHandler serviceHandler;
    private List ids = new ArrayList();
    private MqttHelper mqttHelper;

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }
    @Override
    public void handleMessage(Message msg) {
        showNotification("Aggiornamento di stato", String.valueOf(msg.arg1));
    }
}

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    serviceLooper = thread.getLooper();
    serviceHandler = new ServiceHandler(serviceLooper);
    mqttHelper = new MqttHelper(getApplicationContext());

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

    mqttHelper = new MqttHelper(getApplicationContext());
    mqttHelper.setCallback(new MqttCallbackExtended() {
        @Override
        public void connectComplete(boolean reconnect, String serverURI) {

        }

        @Override
        public void connectionLost(Throwable cause) {

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Message msg = serviceHandler.obtainMessage();
            msg.arg1 = startId;
            serviceHandler.sendMessage(msg);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });
    mqttHelper.connect();

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    // We don't provide binding, so return null
    return null;
}

@Override
public void onDestroy() {
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}

private void showNotification(String title, String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    String channelId = "notification_channel";
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setPriority(Notification.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, "lock", NotificationManager.IMPORTANCE_HIGH);
        channel.enableVibration(true);
        notificationManager.createNotificationChannel(channel);
    }
    int id;
    if(ids.isEmpty()){
        id=0;
    }
    else{
        id = ids.size();
    }
    ids.add(id);
    notificationManager.notify(id , notificationBuilder.build());
}
</code>```

}

And here my manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="it.unisalento.sonoff">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme.FullScreen"
    android:usesCleartextTraffic="true">

    <!-- MqttService -->
    <service android:name="org.eclipse.paho.android.service.MqttService" />
    <service android:name=".helper.Service"
        android:exported="false"
        android:stopWithTask="false"/>
    <activity android:name=".view.DashboardActivity"/>
    <activity
        android:name=".view.LoginActivity"
        android:exported="true"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".view.MainActivity"/>
</application>
</code>```

答: You need to use Foreground Services and pass the notification you built in startForeground method.

Body:
I have to create an Android app that can receive message from a sensor and send a notification to the user when a message is received. I have to do this with out using service like Google Firebase because all the system must run locally. I thought to use MQTT in a service, but when I kill the app, it disconnect from the broker. If the app is running in background this implementation works but I need to keep the connection alive also when app is killed.

This is my implementation of the service:

package it.unisalento.sonoff.helper;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.net.wifi.aware.AttachCallback;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.ArrayList;
import java.util.List;

import it.unisalento.sonoff.R;
import it.unisalento.sonoff.view.MainActivity;

public class Service extends android.app.Service {
    private Looper serviceLooper;
    private ServiceHandler serviceHandler;
    private List ids = new ArrayList();
    private MqttHelper mqttHelper;

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }
    @Override
    public void handleMessage(Message msg) {
        showNotification("Aggiornamento di stato", String.valueOf(msg.arg1));
    }
}

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    serviceLooper = thread.getLooper();
    serviceHandler = new ServiceHandler(serviceLooper);
    mqttHelper = new MqttHelper(getApplicationContext());

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

    mqttHelper = new MqttHelper(getApplicationContext());
    mqttHelper.setCallback(new MqttCallbackExtended() {
        @Override
        public void connectComplete(boolean reconnect, String serverURI) {

        }

        @Override
        public void connectionLost(Throwable cause) {

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Message msg = serviceHandler.obtainMessage();
            msg.arg1 = startId;
            serviceHandler.sendMessage(msg);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });
    mqttHelper.connect();

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    // We don't provide binding, so return null
    return null;
}

@Override
public void onDestroy() {
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}

private void showNotification(String title, String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    String channelId = "notification_channel";
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setPriority(Notification.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, "lock", NotificationManager.IMPORTANCE_HIGH);
        channel.enableVibration(true);
        notificationManager.createNotificationChannel(channel);
    }
    int id;
    if(ids.isEmpty()){
        id=0;
    }
    else{
        id = ids.size();
    }
    ids.add(id);
    notificationManager.notify(id , notificationBuilder.build());
}

}

And here my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="it.unisalento.sonoff">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme.FullScreen"
    android:usesCleartextTraffic="true">

    <service android:name="org.eclipse.paho.android.service.MqttService" />
    <service android:name=".helper.Service"
        android:exported="false"
        android:stopWithTask="false"/>
    <activity android:name=".view.DashboardActivity"/>
    <activity
        android:name=".view.LoginActivity"
        android:exported="true"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".view.MainActivity"/>
</application>


问:
How to set value if object exists - if not intialize and set object in javascript?
I have the following result:

```<code>const mainResult = { result: 1234}
</code>```

I have the following also:

```<code>const allResults = {};
</code>```

I want to set allResults.results.mainResult = mainResult;

However I won't know if allResults.results exists or not.  How do I create allResults.results as an object if it doesn't exist and set it to mainResults - or just set it if allResults.results.mainResults exists?

Is there a way to do this in one line?

答:
Wondering why this won't work? Since we just want to write/overwrite it and not expand the object if it exists.</p>
```<code>const mainResult = { result: 1234 };
const allResults = {};
allResults.results = { mainResult };
console.log(allResults);
</code>```

Body:
I have the following result:

const mainResult = { result: 1234}

I have the following also:

const allResults = {};

I want to set allResults.results.mainResult = mainResult;

However I won't know if allResults.results exists or not.  How do I create allResults.results as an object if it doesn't exist and set it to mainResults - or just set it if allResults.results.mainResults exists?

Is there a way to do this in one line?

Body:
Wondering why this won't work? Since we just want to write/overwrite it and not expand the object if it exists.

const mainResult = { result: 1234 };
const allResults = {};
allResults.results = { mainResult };
console.log(allResults);


问:
Drag parent, but select text on child?
I want the parent div to be draggable, but text in the child span to be selectable:

```<code><aside draggable="true" id="dragme">
    This is an aside, drag me. <span id="copyme" draggable="false">But copy me!</span>
</aside>
</code>```

There is already a similar question here, but jQuery is used there. In do not use jQuery, just html5.

I have tried to stop the event from dragging, but nothing happens unless I use preventDefault - and then I can't select either:

```<code>function dontdrag(ev) {
    ev.preventDefault();
    ev.stopPropagation();
    ev.stopImmadiatePropagation();
    return false;
}
</code>```

There is a fiddle here: http://jsfiddle.net/lborgman/8NvAT/6/

Can anyone see a solution to this today?

UPDATE: There might be a solution, please see the updated fiddle: http://jsfiddle.net/lborgman/8NvAT/7/

It behaves a bit strange, but it works. Can anyone make a solution that is better out of this new fiddle?

答: I solved this same type of problem by using dedicated drag-handle areas. So instead of adding draggable="true" to some arbitrary parent, I put an absolutely-positioned drag handle square in one of the corners of the parent. This might not be the best solution for when you want to hide the draggable implementation (or just make it look better), but it certainly makes it easier for the drag events.

ContentLicense: CC BY-SA 3.0

Title: Drag parent, but select text on child?

Body:
I want the parent div to be draggable, but text in the child span to be selectable:

    This is an aside, drag me. But copy me!

There is already a similar question here, but jQuery is used there. In do not use jQuery, just html5.

I have tried to stop the event from dragging, but nothing happens unless I use preventDefault - and then I can't select either:

function dontdrag(ev) {
    ev.preventDefault();
    ev.stopPropagation();
    ev.stopImmadiatePropagation();
    return false;
}

There is a fiddle here: http://jsfiddle.net/lborgman/8NvAT/6/

Can anyone see a solution to this today?

UPDATE: There might be a solution, please see the updated fiddle: http://jsfiddle.net/lborgman/8NvAT/7/

It behaves a bit strange, but it works. Can anyone make a solution that is better out of this new fiddle?


问:
Big O Problem: What if the variable with the largest exponent has negative coefficient?
Here's an example from Wikipedia:
Let f(x) = 6x^4 - 2x^3 + 5, then f(x) is a "big O" of x^4.

Then I swap the coefficients between x^3 and x^4. Now that f(x) = -2x^4 + 6x^3 + 5. Will f(x) still be a "big O" of x^4? I assume not, since f(x) will take less time as x becomes larger. My question is:

What is the big-o complexity of the above equation? At the moment, I'm ignoring -2x^4, which makes f(x) is a "big O" of x^3, but I'm not sure about that.

答: The expression -2x^4 + 6x^3 + 5 is still O(x^4), because the leading constant is not part of the big-O expression.  Empirically, it should be clear that as x gets arbitrarily large, the x^3 term will basically become irrelevant.  Whether the x^4 terms becomes a very large positive or negative number has no bearing on the running time.


答:
Big-O and related asymptotic classes are usually defined in terms of the absolute value of the function, so that it doesn't matter whether it is increasing or decreasing asymptotically.

So it would still be Theta(x^4), which also implies O(x^4).

In context of time complexity analysis this isn't really relevant though, since you cannot have a program/algorithm taking negative time, so the function you are asking about cannot be a function describing the execution time of a program/algorithm.

Title: Big O Problem: What if the variable with the largest exponent has negative coefficient?

Body:
Here's an example from Wikipedia:
Let f(x) = 6x^4 - 2x^3 + 5, then f(x) is a "big O" of x^4.

Then I swap the coefficients between x^3 and x^4. Now that f(x) = -2x^4 + 6x^3 + 5. Will f(x) still be a "big O" of x^4? I assume not, since f(x) will take less time as x becomes larger. My question is:

What is the big-o complexity of the above equation? At the moment, I'm ignoring -2x^4, which makes f(x) is a "big O" of x^3, but I'm not sure about that.


问:
How to allow null, but forbid undefined?
e.g. for database rows, we may need nullable properties that must not be undefined:

class DbRow {
  @IsNumber()
  id!: number;

  @IsNumber()
  numNullable!: number | null;
}
```

So numNullable can be a number or null - but it must never be undefined.

How can we express this in class-validator?

adding @Optional() does not work, because that would also allow undefined

I also had no luck with a custom validator

答:
Here is my solution:

import { ValidationOptions, ValidateIf } from 'class-validator';
export function IsNullable(validationOptions?: ValidationOptions) {
  return ValidateIf((_object, value) => value !== null, validationOptions);
}
```
<p><strong>Usage</strong></p>
<pre class="lang-js prettyprint-override"><code>import { plainToClass } from 'class-transformer';
import { IsNumber, validateSync } from 'class-validator';
import { IsNullable } from 'src/common/utils/is-nullable.decorator';
class SampleDto {
  @IsNullable()
  @IsNumber()
  foo: number | null;
}
describe('IsNullable', () => {
  it('should disable other validators when given property is null', () => {
    expect(validateSync(plainToClass(SampleDto, { foo: null }))).toEqual([]);
  });
  it('should allow other validators to work when given property is not null', () => {
    expect(validateSync(plainToClass(SampleDto, { foo: 1 }))).toEqual([]);
    expect(validateSync(plainToClass(SampleDto, { foo: '1' }))[0].constraints.isNumber).toMatch('foo must be a number');
  });
  it('should not allow undefined', () => {
    expect(validateSync(plainToClass(SampleDto, { foo: undefined })).length).toBeGreaterThan(0);
  });
});
</code>```

Body:
e.g. for database rows, we may need nullable properties that must not be undefined:

class DbRow {
  @IsNumber()
  id!: number;

  @IsNumber()
  numNullable!: number | null;
}

So numNullable can be a number or null - but it must never be undefined.

How can we express this in class-validator?

adding @Optional() does not work, because that would also allow undefined

I also had no luck with a custom validator

Body:
Here is my solution:

import { ValidationOptions, ValidateIf } from 'class-validator';
export function IsNullable(validationOptions?: ValidationOptions) {
  return ValidateIf((_object, value) => value !== null, validationOptions);
}

Usage

import { plainToClass } from 'class-transformer';
import { IsNumber, validateSync } from 'class-validator';
import { IsNullable } from 'src/common/utils/is-nullable.decorator';
class SampleDto {
  @IsNullable()
  @IsNumber()
  foo: number | null;
}
describe('IsNullable', () => {
  it('should disable other validators when given property is null', () => {
    expect(validateSync(plainToClass(SampleDto, { foo: null }))).toEqual([]);
  });
  it('should allow other validators to work when given property is not null', () => {
    expect(validateSync(plainToClass(SampleDto, { foo: 1 }))).toEqual([]);
    expect(validateSync(plainToClass(SampleDto, { foo: '1' }))[0].constraints.isNumber).toMatch('foo must be a number');
  });
  it('should not allow undefined', () => {
    expect(validateSync(plainToClass(SampleDto, { foo: undefined })).length).toBeGreaterThan(0);
  });
});


问:
I have updated angular version from 8 to 13, everything is working properly. But only during first time load its giving 505 error to some font files
I have updated angular version from 8 to 13, everything is working properly. But only during first time load its giving 505 error to some font files

Code Snippet Of index.html:

```<code><base href="/">
....
....
</code>```

Code Snippet Of master.css:

```<code>/* Font */
@font-face{font-family:'ClearSans-Medium';src:url(../fonts/ClearSans/ClearSans-Medium.eot);src:url(../fonts/ClearSans/ClearSans-Medium.eot?#iefix) format("embedded-opentype"), url(../fonts/ClearSans/ClearSans-Medium.woff2) format("woff2"), url(../fonts/ClearSans/ClearSans-Medium.woff) format("woff"), url(../fonts/ClearSans/ClearSans-Medium.ttf) format("truetype");font-weight:500;font-style:normal}
@font-face{font-family:'ClearSans-Regular';src:url(../fonts/ClearSans/ClearSans.eot);src:url(../fonts/ClearSans/ClearSans.eot?#iefix) format("embedded-opentype"), url(../fonts/ClearSans/ClearSans.woff2) format("woff2"), url(../fonts/ClearSans/ClearSans.woff) format("woff"), url(../fonts/ClearSans/ClearSans.ttf) format("truetype");font-weight:400;font-style:normal}
@font-face{font-family:'ClearSans-Light';src:url(../fonts/ClearSans/ClearSans-Light.eot);src:url(../fonts/ClearSans/ClearSans-Light.eot?#iefix) format("embedded-opentype"), url(../fonts/ClearSans/ClearSans-Light.woff2) format("woff2"), url(../fonts/ClearSans/ClearSans-Light.woff) format("woff"), url(../fonts/ClearSans/ClearSans-Light.ttf) format("truetype");font-weight:300;font-style:normal}
@font-face{font-family:'ClearSans-Bold';src:url(../fonts/ClearSans/ClearSans-Bold.eot);src:url(../fonts/ClearSans/ClearSans-Bold.eot?#iefix) format("embedded-opentype"), url(../fonts/ClearSans/ClearSans-Bold.woff2) format("woff2"), url(../fonts/ClearSans/ClearSans-Bold.woff) format("woff"), url(../fonts/ClearSans/ClearSans-Bold.ttf) format("truetype");font-weight:700;font-style:normal}
body{font-family:'ClearSans-Regular';color:#000;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:18px;line-height:normal}
</code>```

.htaccess code:

```<code>RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
</code>```

Build Done with:

```<code>Angular CLI: 13.0.4
Node: 16.13.1
Package Manager: npm 8.1.2
</code>```

During first-time application load, Its showing "net::ERR_ABORTED 500 (Internal Server Error)" console errors for these fonts. All font files are present at the given path. Also working properly, but its showing errors in console.

Please suggest me the changes for this issue.

答:
I was also facing same problem, I solved it by adding following code in angular.json:

```<code>"configurations": {
  "production": {
      //other code
      "optimization": {
           "scripts": true,
           "styles": {
                "minify": true,
                "inlineCritical": false
           },
           "fonts": false
      }
  }
}
</code>```

after adding above code, restart your application: npm start

Body:
I have updated angular version from 8 to 13, everything is working properly. But only during first time load its giving 505 error to some font files

Code Snippet Of index.html:

<base href="/">
....
....

Code Snippet Of master.css:

/* Font */
@font-face{font-family:'ClearSans-Medium';src:url(../fonts/ClearSans/ClearSans-Medium.eot);src:url(../fonts/ClearSans/ClearSans-Medium.eot?#iefix) format("embedded-opentype"), url(../fonts/ClearSans/ClearSans-Medium.woff2) format("woff2"), url(../fonts/ClearSans/ClearSans-Medium.woff) format("woff"), url(../fonts/ClearSans/ClearSans-Medium.ttf) format("truetype");font-weight:500;font-style:normal}
@font-face{font-family:'ClearSans-Regular';src:url(../fonts/ClearSans/ClearSans.eot);src:url(../fonts/ClearSans/ClearSans.eot?#iefix) format("embedded-opentype"), url(../fonts/ClearSans/ClearSans.woff2) format("woff2"), url(../fonts/ClearSans/ClearSans.woff) format("woff"), url(../fonts/ClearSans/ClearSans.ttf) format("truetype");font-weight:400;font-style:normal}
@font-face{font-family:'ClearSans-Light';src:url(../fonts/ClearSans/ClearSans-Light.eot);src:url(../fonts/ClearSans/ClearSans-Light.eot?#iefix) format("embedded-opentype"), url(../fonts/ClearSans/ClearSans-Light.woff2) format("woff2"), url(../fonts/ClearSans/ClearSans-Light.woff) format("woff"), url(../fonts/ClearSans/ClearSans-Light.ttf) format("truetype");font-weight:300;font-style:normal}
@font-face{font-family:'ClearSans-Bold';src:url(../fonts/ClearSans/ClearSans-Bold.eot);src:url(../fonts/ClearSans/ClearSans-Bold.eot?#iefix) format("embedded-opentype"), url(../fonts/ClearSans/ClearSans-Bold.woff2) format("woff2"), url(../fonts/ClearSans/ClearSans-Bold.woff) format("woff"), url(../fonts/ClearSans/ClearSans-Bold.ttf) format("truetype");font-weight:700;font-style:normal}
body{font-family:'ClearSans-Regular';color:#000;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:18px;line-height:normal}

.htaccess code:

RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

Build Done with:

Angular CLI: 13.0.4
Node: 16.13.1
Package Manager: npm 8.1.2

During first-time application load, Its showing "net::ERR_ABORTED 500 (Internal Server Error)" console errors for these fonts. All font files are present at the given path. Also working properly, but its showing errors in console.

Please suggest me the changes for this issue.

Body:
I was also facing same problem, I solved it by adding following code in angular.json:

"configurations": {
  "production": {
      //other code
      "optimization": {
           "scripts": true,
           "styles": {
                "minify": true,
                "inlineCritical": false
           },
           "fonts": false
      }
  }
}

after adding above code, restart your application: npm start


问:
Resizing Icons in jQuery-UI
I find the icons in jquery UI to be a bit small for my application.   Adjusting the sizes on .ui-icon doesn't help of course, because the images are loaded from a single image file and so it will just show portions of other icons.

Is there any way to adjust the icon sizes without having to resize the icon image files for each size I'd like to use?

答:
here is my solution

use any png icon you want (inthis example - resize class replacing)

```<code>.ui-icon-gripsmall-diagonal-se
{
background-color:#fff!important;
border-radius: 50%; -moz-border-radius: 50%; -webkit-border-radius: 50%; -khtml-border-radius: 50%;
background-image:url('resize.png')!important;
background-position:center center;
background-size: cover!important;
-ms-transform: scale(2);
-webkit-transform: scale(2);
transform: scale(2);
}
</code>```

scale it x2 and put hires icon with cover mode

Title: Resizing Icons in jQuery-UI

Body:
here is my solution

use any png icon you want (inthis example - resize class replacing)

.ui-icon-gripsmall-diagonal-se
{
background-color:#fff!important;
border-radius: 50%; -moz-border-radius: 50%; -webkit-border-radius: 50%; -khtml-border-radius: 50%;
background-image:url('resize.png')!important;
background-position:center center;
background-size: cover!important;
-ms-transform: scale(2);
-webkit-transform: scale(2);
transform: scale(2);
}

scale it x2 and put hires icon with cover mode


问:
How to map a subarray
I am using a sample I found online to map a subarray and can't seem to get it to work.

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-map-subarray',
  templateUrl: './map-subarray.component.html',
  styleUrls: ['./map-subarray.component.css']
})
export class MapSubarrayComponent implements OnInit {

  books: any[] = [
    {
      title: 'Books by Nigerian authors',
      // An array of books in shelves
      shelves: [
        {
          id: 1,
          category: 'Fiction',
          title: 'Things fall Apart',
          author: 'Chinua Achebe'
        },
        {
          id: 2,
          category: 'drama',
          title: 'Under the Udala trees',
          author: 'Chinelo Okparanta'
        }
      ]
    }
  ];
  categories: any[] = [];

  constructor() { }

  ngOnInit(): void {
    // Gets the selves from the books array
    this.categories = this.books.map((book) => this.books.shelves);

    // Gets the list of categories on the shelves
    this.categories = this.books.map((book) => book.shelves.map((shelf) => shelf.category);
  }

}
</code>```

But I get an error in the first map on shelves:

And an error on shelf for the second mapping line. Perhaps fixing the 1st map will lead to fixing the second.

jitendra's answer works fine.

But I am curious why using the map for shelves gives me back an array which I cannot apparently use - ie. shelves.title. And it doesn't work in the template with the *ngFor.

But the index one does work.

Does that have something to do with flattening?

答:
It's always a good idea to type your objects in Angular, which uses TypeScript - in your case, since your books aren't types, the compiler gives it an any type if it can't infer the types. If you have strict mode turned on, you will see errors.

If you were to type your book, you may have something like:

```<code>// You can use a Class or Type if you prefer
interface Book{
    title: string,
    shelves: {
          id: number,
          category: string,
          title: string,
          author: string
        }[]
}
</code>```

This way, even using the Array.map method, you should not see the "implicit any" warning

Title: How to map a subarray

Body:
I am using a sample I found online to map a subarray and can't seem to get it to work.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-map-subarray',
  templateUrl: './map-subarray.component.html',
  styleUrls: ['./map-subarray.component.css']
})
export class MapSubarrayComponent implements OnInit {

  books: any[] = [
    {
      title: 'Books by Nigerian authors',
      // An array of books in shelves
      shelves: [
        {
          id: 1,
          category: 'Fiction',
          title: 'Things fall Apart',
          author: 'Chinua Achebe'
        },
        {
          id: 2,
          category: 'drama',
          title: 'Under the Udala trees',
          author: 'Chinelo Okparanta'
        }
      ]
    }
  ];
  categories: any[] = [];

  constructor() { }

  ngOnInit(): void {
    // Gets the selves from the books array
    this.categories = this.books.map((book) => this.books.shelves);

    // Gets the list of categories on the shelves
    this.categories = this.books.map((book) => book.shelves.map((shelf) => shelf.category);
  }

}

But I get an error in the first map on shelves:

And an error on shelf for the second mapping line. Perhaps fixing the 1st map will lead to fixing the second.

jitendra's answer works fine.

But I am curious why using the map for shelves gives me back an array which I cannot apparently use - ie. shelves.title. And it doesn't work in the template with the *ngFor.

But the index one does work.

Does that have something to do with flattening?

Body:
It's always a good idea to type your objects in Angular, which uses TypeScript - in your case, since your books aren't types, the compiler gives it an any type if it can't infer the types. If you have strict mode turned on, you will see errors.

If you were to type your book, you may have something like:

// You can use a Class or Type if you prefer
interface Book{
    title: string,
    shelves: {
          id: number,
          category: string,
          title: string,
          author: string
        }[]
}

This way, even using the Array.map method, you should not see the "implicit any" warning


问:
How to solve this "parse and balance angle brackets" problem? (Javascript)
I am struggling with an algorithm problem I saw (and failed). Now, I am trying to understand how to solve the problem.

Question:
  Given a string of angle brackets, write a function that add brackets at the beginning and end of the string to make all brackets match. The angle brackets match if for every < there is a corresponding > and for every > there is a corresponding <.

The example input string : ><<><

The output string is <><<><>>

My main problem is how to handle multiple < characters in the input string, like <<.  Based on the example given, I will end up with some nested angle brackets, but I am not currently able to figure out how to do this.

I can solve the example input, but when I give it other inputs, the output is not always what I am expecting (input #2 and input #6).  Help would be appreciated.

```<code>const process = (strInput) => {

  let strOutput = [];
  let stack = [];
  let popped ='';

  for (let i = 0; i < strInput.length; i++) {

    if (strInput[i] === '>') {
      if (stack[stack.length - 1] === '<') {
        popped = stack.pop();
        strOutput.push(popped);
        strOutput.push(strInput[i]);
      } else {
        strOutput.push('<');
        strOutput.push(strInput[i]);
      }
    } else {
        if (stack[stack.length - 1] === '<') {
            strOutput.push('<');
            stack.push(strInput[i]);
        } else {
            stack.push(strInput[i]);
        }

    }
  }

// After string has been read, check the stack for <

  for (let i = 0; i < stack.length; i++) {
    strOutput.push('>');
  }

  return strOutput.join('');
};

let result = '';

console.log('Input 1: ><<><');

result = process('><<><');

console.log('Output 1: ' + result);
console.log('Expected Output 1: ' + '<><<><>>');

console.log('Input 2: <><<');

result = process('<><<');

console.log('Output 2: ' + result);

console.log('Expected Output 2: ' + '<><<>>');

console.log('Input 3: <><<<>');

result = process('<><<<>');

console.log('Output 3: ' + result);

console.log('Expected Output 3: ' + '<><<<>>>');

console.log('Input 4: <><<<><');

result = process('<><<<><');

console.log('Output 4: ' + result);

console.log('Expected Output 4: ' + '<><<<><>>>');

console.log('Input 5: ><<>');

result = process('><<>');

console.log('Output 5: ' + result);

console.log('Expected Output 5: ' + '<><<>>');

console.log('Input 6: ><<<');

result = process('><<<');

console.log('Output 6: ' + result);

console.log('Expected Output 6: ' + '<><<<>>>');

console.log('Input 7: >>>');

result = process('>>>');

console.log('Output 7: ' + result);

console.log('Expected Output 7: ' + '<<<>>>');
</code>```

答:
Java Version</p>
```<code>public static void main(String[] args) {

    String s = "><<><";

    int openCount = 0;
    int additionalLeadingOpenTags = 0;

    for (char c : s.toCharArray()) {
        if (c == '>') {
            if (openCount == 0) {
                additionalLeadingOpenTags++;
            } else {
                openCount--;
            }
        } else {
            openCount++;
        }
    }

    StringBuilder result = new StringBuilder();
    while (additionalLeadingOpenTags > 0) {
        result.append("<");
        additionalLeadingOpenTags--;
    }
    result.append(s);
    while (openCount > 0) {
        result.append(">");
        openCount--;
    }

    System.out.println(result.toString());
}
</code>```

Body:
I am struggling with an algorithm problem I saw (and failed). Now, I am trying to understand how to solve the problem.

Question:
  Given a string of angle brackets, write a function that add brackets at the beginning and end of the string to make all brackets match. The angle brackets match if for every < there is a corresponding > and for every > there is a corresponding <.

The example input string : ><<><

The output string is <><<><>>

My main problem is how to handle multiple < characters in the input string, like <<.  Based on the example given, I will end up with some nested angle brackets, but I am not currently able to figure out how to do this.

I can solve the example input, but when I give it other inputs, the output is not always what I am expecting (input #2 and input #6).  Help would be appreciated.

const process = (strInput) => {

  let strOutput = [];
  let stack = [];
  let popped ='';

  for (let i = 0; i < strInput.length; i++) {

    if (strInput[i] === '>') {
      if (stack[stack.length - 1] === '<') {
        popped = stack.pop();
        strOutput.push(popped);
        strOutput.push(strInput[i]);
      } else {
        strOutput.push('<');
        strOutput.push(strInput[i]);
      }
    } else {
        if (stack[stack.length - 1] === '<') {
            strOutput.push('<');
            stack.push(strInput[i]);
        } else {
            stack.push(strInput[i]);
        }

    }
  }

// After string has been read, check the stack for <

  for (let i = 0; i < stack.length; i++) {
    strOutput.push('>');
  }

  return strOutput.join('');
};

let result = '';

console.log('Input 1: ><<><');

result = process('><<><');

console.log('Output 1: ' + result);
console.log('Expected Output 1: ' + '<><<><>>');

console.log('Input 2: <><<');

result = process('<><<');

console.log('Output 2: ' + result);

console.log('Expected Output 2: ' + '<><<>>');

console.log('Input 3: <><<<>');

result = process('<><<<>');

console.log('Output 3: ' + result);

console.log('Expected Output 3: ' + '<><<<>>>');

console.log('Input 4: <><<<><');

result = process('<><<<><');

console.log('Output 4: ' + result);

console.log('Expected Output 4: ' + '<><<<><>>>');

console.log('Input 5: ><<>');

result = process('><<>');

console.log('Output 5: ' + result);

console.log('Expected Output 5: ' + '<><<>>');

console.log('Input 6: ><<<');

result = process('><<<');

console.log('Output 6: ' + result);

console.log('Expected Output 6: ' + '<><<<>>>');

console.log('Input 7: >>>');

result = process('>>>');

console.log('Output 7: ' + result);

console.log('Expected Output 7: ' + '<<<>>>');

Body:
Java Version

public static void main(String[] args) {

    String s = "><<><";

    int openCount = 0;
    int additionalLeadingOpenTags = 0;

    for (char c : s.toCharArray()) {
        if (c == '>') {
            if (openCount == 0) {
                additionalLeadingOpenTags++;
            } else {
                openCount--;
            }
        } else {
            openCount++;
        }
    }

    StringBuilder result = new StringBuilder();
    while (additionalLeadingOpenTags > 0) {
        result.append("<");
        additionalLeadingOpenTags--;
    }
    result.append(s);
    while (openCount > 0) {
        result.append(">");
        openCount--;
    }

    System.out.println(result.toString());
}


问:
How do I move data from RDS of one AWS account to another account
We have our web services and database set up on AWS a while back and application is now in production. For some reason, we need to terminate the old AWS and move everything under a newly created AWS account. Application and all the infrastructure are pretty straightforward. It is trickier for data though. The current database is still receiving lots of data on daily basis. So it is best to migrate the data after we turn off the old application and switch on new platform.

Both source RDS and target RDS are Postgres. We have about 40GB data to transfer. There are three approaches I could think of and they all have drawbacks.

Take a snapshot of the first RDS and restore it in second one. Problem is I don't need to transfer all the data from source to destination. Probably just records after 10/01 is enough. Also snapshot works best to restore in an empty rds that is just created. For our case, the new RDS will start receiving data already after the cutoff. Only after that, the data will be transferred from old account to new account otherwise we will lose data.

Dump data from tables in old RDS and backup in new RDS. This will have the same problem as #1. Also, if I dump data to local machine and then back up from local, the network speed is bottleneck.

Export table data to csv files and import to new RDS. The advantage is this method allows pick and choose and some data cleaning as well. But it takes forever to export a big fact table to local csv file. Another problem is, for some of the tables, I have surrogate row IDs which are serial (auto-incremental). The row IDs of exported csv may conflicting with existing data in new RDS tables.

I wonder if there is a better way to do it. Maybe some ETL tool AWS has which does point to point direct transfer without involving using local computer as the middle point.

答:
In 2022 the simplest way to achieve this task is using AWS Database Migration Services (AWS DMS).

You can create a migration task, and set the original database as the source endpoint, and the new database as a destination endpoint.

Next create a task with "Full load, ongoing replication" settings.

More details here: https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.PostgreSQL.html


问:
Why do I have to import traceback if it already exists?
If I write something in Python and things go awry, I automatically get a traceback.

For example:

```<code>#!/usr/bin/env python

print("this will raise a division by zero exception")
print(2/0)
</code>```

It automatically throws a traceback with the exception

```<code>>>> %Run test.py
this will raise a division by zero exception
Traceback (most recent call last):
  File "/home/pi/Desktop/test.py", line 4, in <module>
    print(2/0)
ZeroDivisionError: division by zero
>>>
</code>```

Now, let's assume that I don't want the program to crash-and-burn, but I want to handle the exception gracefully - say I need to close files or whatever.

Viz.:

```<code>#!/usr/bin/env python
import sys

try:
    print("Assume I'm doing something with a resource, like a file")
    print(". . . and something goes wrong\n")
    print("(This will raise a division by zero exception when I try to \"print(2/0)\")\n")
    print(2/0)

except BaseException as e:
    print(". . . and I want to handle the exception gracefully:\n")
    print("Oops! Something happened! (",e, ")\n")
    sys.exit(0)
</code>```

Which gets me the expected:

```<code>>>> %Run test.py
Assume I'm doing something with a resource, like a file
. . . and something goes wrong

(This will raise a division by zero exception when I try to "print(2/0)")

. . . and I want to handle the exception gracefully:

Oops! Something happened! ( division by zero )

─────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>>
</code>```

However, if I try to handle the exception manually, I am told that in order to get the system provided traceback, (the call stack and location of the error), I have to import traceback.

When I do that, I can get all the information I want.

```<code>#!/usr/bin/env python
import sys
import traceback

try:
    print("Assume I'm doing something with a resource, like a file")
    print(". . . and something goes wrong\n")
    print("(This will raise a division by zero exception when I try to \"print(2/0)\")\n")
    print(2/0)

except BaseException as e:
    print(". . . and I want to handle the exception gracefully:\n")
    print("Oops! Something happened! (",e, ")\n")
    traceback.print_exc()
    sys.exit(0)
</code>```

And the expected result:

```<code>────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>> %Run test.py
Assume I'm doing something with a resource, like a file
. . . and something goes wrong

(This will raise a division by zero exception when I try to "print(2/0)")

. . . and I want to handle the exception gracefully:

Oops! Something happened! ( division by zero )

Traceback (most recent call last):
  File "/home/pi/Desktop/test.py", line 9, in <module>
    print(2/0)
ZeroDivisionError: division by zero

─────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>>
</code>```

"Traceback" appears to already exist as the traceback is automatic on unhandled exceptions

Why do I have to import traceback if I use a try/except block, but don't if I don't?

答: The default behavior of Python when an exception is raised that isn't caught in a try...except is to print a traceback and exit. If you do catch it, then the default doesn't happen. You have to decide what to do with it. If you decide to print the traceback you now have to explicitly do it by importing the traceback module and using the methods there. However, that's not strictly necessary as you could just inspect the current traceback object (from sys.exc_info()), and write your own formatter.

Body:
If I write something in Python and things go awry, I automatically get a traceback.

For example:

#!/usr/bin/env python

print("this will raise a division by zero exception")
print(2/0)

It automatically throws a traceback with the exception

>>> %Run test.py
this will raise a division by zero exception
Traceback (most recent call last):
  File "/home/pi/Desktop/test.py", line 4, in <module>
    print(2/0)
ZeroDivisionError: division by zero
>>>

Now, let's assume that I don't want the program to crash-and-burn, but I want to handle the exception gracefully - say I need to close files or whatever.

Viz.:

#!/usr/bin/env python
import sys

try:
    print("Assume I'm doing something with a resource, like a file")
    print(". . . and something goes wrong\n")
    print("(This will raise a division by zero exception when I try to \"print(2/0)\")\n")
    print(2/0)

except BaseException as e:
    print(". . . and I want to handle the exception gracefully:\n")
    print("Oops! Something happened! (",e, ")\n")
    sys.exit(0)

Which gets me the expected:

>>> %Run test.py
Assume I'm doing something with a resource, like a file
. . . and something goes wrong

(This will raise a division by zero exception when I try to "print(2/0)")

. . . and I want to handle the exception gracefully:

Oops! Something happened! ( division by zero )

─────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>>

However, if I try to handle the exception manually, I am told that in order to get the system provided traceback, (the call stack and location of the error), I have to import traceback.

When I do that, I can get all the information I want.

#!/usr/bin/env python
import sys
import traceback

try:
    print("Assume I'm doing something with a resource, like a file")
    print(". . . and something goes wrong\n")
    print("(This will raise a division by zero exception when I try to \"print(2/0)\")\n")
    print(2/0)

except BaseException as e:
    print(". . . and I want to handle the exception gracefully:\n")
    print("Oops! Something happened! (",e, ")\n")
    traceback.print_exc()
    sys.exit(0)

And the expected result:

────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>> %Run test.py
Assume I'm doing something with a resource, like a file
. . . and something goes wrong

(This will raise a division by zero exception when I try to "print(2/0)")

. . . and I want to handle the exception gracefully:

Oops! Something happened! ( division by zero )

Traceback (most recent call last):
  File "/home/pi/Desktop/test.py", line 9, in <module>
    print(2/0)
ZeroDivisionError: division by zero

─────────────────────────────────────────────────────────────────────────────────────────────────
Python 3.7.3 (/usr/bin/python3)
>>>

"Traceback" appears to already exist as the traceback is automatic on unhandled exceptions

Why do I have to import traceback if I use a try/except block, but don't if I don't?


答:
"Traceback" appears to already exist as the traceback is automatic on unhandled exceptions

What you're seeing is the default behavior of sys.excepthook, which is to print a traceback out to stderr anyway, just before the program exits from an unhandled exception.

See for yourself with:

```<code># example.py
import sys
sys.excepthook = lambda *args: None
print("before")
1/0
print("after")
</code>```

The script above will exit non-zero, but no traceback will be printed since the hook was replaced with a no-op. And "after" will not get printed, because the process will have already exited. So, it is not quite that a traceback is "automatic" on unhandled exceptions, but rather that is the default configuration.

By calling sys.exit(0) you're intentionally suppressing the ZeroDivisionError exception. The interpreter will exit with a zero return code, and as far as the except hook is concerned you have "handled" the ZeroDivisionError and are opting out of the traceback printing (src).

Title: Why do I have to import traceback if it already exists?

Body:
"Traceback" appears to already exist as the traceback is automatic on unhandled exceptions

What you're seeing is the default behavior of sys.excepthook, which is to print a traceback out to stderr anyway, just before the program exits from an unhandled exception.

See for yourself with:

# example.py
import sys
sys.excepthook = lambda *args: None
print("before")
1/0
print("after")

The script above will exit non-zero, but no traceback will be printed since the hook was replaced with a no-op. And "after" will not get printed, because the process will have already exited. So, it is not quite that a traceback is "automatic" on unhandled exceptions, but rather that is the default configuration.

By calling sys.exit(0) you're intentionally suppressing the ZeroDivisionError exception. The interpreter will exit with a zero return code, and as far as the except hook is concerned you have "handled" the ZeroDivisionError and are opting out of the traceback printing (src).


问:
Classic ASP & JavaScript
Can anyone help me on my query. I have a page which has a button

```<code><button id="btnStudents" name="btnStudents" style="width:90px;cursor:default;" title="Click to add/update/delete Student records" onClick="javascript:fn_ShowHide('lyrStudents', this.id)">
                <table width="100%" cellpadding=0 cellspacing=0>
                  <tr>
                    <td height="25">
                      <div align="center"><img src="../images/icons/student.gif" hspace="0" align="absmiddle" width="32" height="32" vspace="10"><font class="BodyHDRFontBold"></font></div>
                    </td>
                  </tr>
                  <tr>
                    <td height="25">
                      <div align="center"> <font class="BodyHDRFontBold"><b>Manage
                        Students</b></font></div>
                    </td>
                  </tr>
                </table>
                </button>
</code>```

and whenever this button is clicked, a small layer should open right under the button. I tried to do it using button's left and top but it did not work in all the browsers.
Layer code is below. Layer by default will be hidden unless user clicks on the button.

```<code>                    <div id="lyrStudents" style="position:absolute; left:749px; top:412px; width:183px; height:148px; z-index:1; background-color: #FFFFFF; layer-background-color: #FFFFFF; border: 1px none #000000;">
                  <table width="100%" border="0" cellspacing="0" cellpadding="0" class="tblBorder">
                    <tr>
                      <td colspan="2" class="bgColorBar" height="25">
                        <div align="center"><font class="BodyFontNormal"><b>::
                          Students Menu ::</b></font></div>
                      </td>
                    </tr>
                    <tr>
                      <td colspan="2"><img src="../images/supporting/b3b3ff_line.png" width="100%" height="1"></td>
                    </tr>
                    <tr>
                      <td width="12%"> </td>
                      <td width="88%"> </td>
                    </tr>
                    <tr>
                      <td width="12%"> </td>
                      <td width="88%"> </td>
                    </tr>
                    <tr>
                      <td width="12%"> </td>
                      <td width="88%"> </td>
                    </tr>
                  </table>
                </div>
</code>```

Appreciate your help.

答:
Thanks everyone for your direct / indirect help. I have managed to get the issue resolved from external sources.</p>

```<code>function fn_Reposition(strFieldName, lyrName )
{
var intLeft, intTop, intBtnHeight, obj;

obj = document.getElementById(strFieldName);
intBtnHeight = document.getElementById(strFieldName).clientHeight;

document.getElementById(lyrName).style.top = getElTop(obj) + intBtnHeight;
document.getElementById(lyrName).style.left = getElLeft(obj)
}

// Many thanks to Paul Hayman
// Code Source: http://www.geekzilla.co.uk/ViewContent.aspx?ContentID=252
function getElLeft(el)
{
if (ns4)
{
    return el.pageX;
}
else
{
    xPos = el.offsetLeft;
    tempEl = el.offsetParent;
    while (tempEl != null)
    {
        xPos += tempEl.offsetLeft;
        tempEl = tempEl.offsetParent;
    }
    return xPos;
}
}
function getElTop(el)
{
if (ns4)
{
    return el.pageY;
}
else
{
    yPos = el.offsetTop;
    tempEl = el.offsetParent;
    while (tempEl != null)
    {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}
}
</code>```

Title: Classic ASP & JavaScript

Body:
Can anyone help me on my query. I have a page which has a button

<button id="btnStudents" name="btnStudents" style="width:90px;cursor:default;" title="Click to add/update/delete Student records" onClick="javascript:fn_ShowHide('lyrStudents', this.id)">

 Manage
                        Students

                </button>

and whenever this button is clicked, a small layer should open right under the button. I tried to do it using button's left and top but it did not work in all the browsers.
Layer code is below. Layer by default will be hidden unless user clicks on the button.

::
                          Students Menu ::

Appreciate your help.

Body:
Thanks everyone for your direct / indirect help. I have managed to get the issue resolved from external sources.

function fn_Reposition(strFieldName, lyrName )
{
var intLeft, intTop, intBtnHeight, obj;

obj = document.getElementById(strFieldName);
intBtnHeight = document.getElementById(strFieldName).clientHeight;

document.getElementById(lyrName).style.top = getElTop(obj) + intBtnHeight;
document.getElementById(lyrName).style.left = getElLeft(obj)
}

// Many thanks to Paul Hayman
// Code Source: http://www.geekzilla.co.uk/ViewContent.aspx?ContentID=252
function getElLeft(el)
{
if (ns4)
{
    return el.pageX;
}
else
{
    xPos = el.offsetLeft;
    tempEl = el.offsetParent;
    while (tempEl != null)
    {
        xPos += tempEl.offsetLeft;
        tempEl = tempEl.offsetParent;
    }
    return xPos;
}
}
function getElTop(el)
{
if (ns4)
{
    return el.pageY;
}
else
{
    yPos = el.offsetTop;
    tempEl = el.offsetParent;
    while (tempEl != null)
    {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }
    return yPos;
}
}


问:
How to delete react app & open existing one
I am beginner for React-App. I have an existing project folder.

Step I took:

```<code>npm install -g create-react app
cd C:\Users\MyFolder\Documents\MyName\CS50\Project\Project1
npm start
</code>```

**
"This automatically create a folder called "start" inside my Project1 with folders & files below:

```<code>node_modules
public
src
.gitignore
package.json
package-lock.json
README.md
</code>```

**

Actually I already have all the files inside Project1, eg:

```<code>.gitignore
assets folder
utils folder
.babelrc
.watchmanconfig
App.js
app.json
package.json
README.md
</code>```

How can I delete the start folder inside C:\Users\MyFolder\Documents\MyName\CS50\Project\Project1
and I want to open the Project1 folder to work on the assignment given by a course I am attending online. This is my 1st time doing it.

Please advise.

Thanks.

Regards,

Micheale

答:
Delete and remove the react-app Files faster in a seconds using

```<code>rm -rf <nameOfTheFolder> // or name of the project
</code>```

This 100% work, upvote it coz otherwise it takes, lot of time to remove using simple delete from the terminal.

Save all programmers time #GivingBackToCommunity thanks

Body:
I am beginner for React-App. I have an existing project folder.

Step I took:

npm install -g create-react app
cd C:\Users\MyFolder\Documents\MyName\CS50\Project\Project1
npm start

**
"This automatically create a folder called "start" inside my Project1 with folders & files below:

node_modules
public
src
.gitignore
package.json
package-lock.json
README.md

**

Actually I already have all the files inside Project1, eg:

.gitignore
assets folder
utils folder
.babelrc
.watchmanconfig
App.js
app.json
package.json
README.md

How can I delete the start folder inside C:\Users\MyFolder\Documents\MyName\CS50\Project\Project1
and I want to open the Project1 folder to work on the assignment given by a course I am attending online. This is my 1st time doing it.

Please advise.

Thanks.

Regards,

Micheale

Body:
Delete and remove the react-app Files faster in a seconds using

rm -rf <nameOfTheFolder> // or name of the project

This 100% work, upvote it coz otherwise it takes, lot of time to remove using simple delete from the terminal.

Save all programmers time #GivingBackToCommunity thanks


问:
Using List Comprehension for a number sequence (1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1 .....) in Python
I'm doing exercise questions from A Practical Introduction to Python Programming by Brian Heinold (pg 83) and there was a simpler question:

Using a for loop, create the list below, which consists of ones separated by increasingly many
zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

```<code># Question 11
L = [1]
for i in range(11):
  if i == 0:
    L.append(1)
  else:
    for j in range(i):
      L.append(0)
    L.append(1)
print(L)
</code>```

Use a list comprehension to create the list below, which consists of ones separated by increasingly many zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

I'm having difficulty with converting it into one line using list comprehension. Best I could do was

```<code># Question 15
L = [[1, [0]*i] for i in range(11)]
print(L)
L = [j for row in L for j in row]
print(L)
</code>```

Which would print:

```<code>[[1, []], [1, [0]], [1, [0, 0]], [1, [0, 0, 0]], [1, [0, 0, 0, 0]], [1, [0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]
[1, [], 1, [0], 1, [0, 0], 1, [0, 0, 0], 1, [0, 0, 0, 0], 1, [0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
</code>```

Flattening the list any further would result in a TypeError: 'int' object is not iterable and I would have to add another 1 at the end of the list using a seperate command which I guess would be fine. To add the code for flattening the list kinda goes over my head.

This is a second attempt using if/else statements, that gives the produces the same output and gives the same TypeError for when I try to flatten it completely.

```<code>L = [1 if i%2 == 0 else [0]*(i//2) for i in range(22)]
L = [j for row in L for j in row]
print(L)
</code>```

I just want this as output:

```<code>[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
</code>```

Thanks!

答:
You could use a nested comprehension that produces an increasing number of values that you convert to 0s and 1s by returning 0s for all but the last of each group:

```<code>n = 10
r = [1]+[b//z for z in range(1,n+2) for b in range(1,z+1)]
print(r)
[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
</code>```

If you want to avoid the need to add the initial [1], you could use a similar approach starting z at -1 instead of 1:

```<code>r = [ 1-(b<z) for z in range(-1,n+1) for b in range(z+1 or 1)]
</code>```

Body:
I'm doing exercise questions from A Practical Introduction to Python Programming by Brian Heinold (pg 83) and there was a simpler question:

Using a for loop, create the list below, which consists of ones separated by increasingly many
zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

# Question 11
L = [1]
for i in range(11):
  if i == 0:
    L.append(1)
  else:
    for j in range(i):
      L.append(0)
    L.append(1)
print(L)

Use a list comprehension to create the list below, which consists of ones separated by increasingly many zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

I'm having difficulty with converting it into one line using list comprehension. Best I could do was

# Question 15
L = [[1, [0]*i] for i in range(11)]
print(L)
L = [j for row in L for j in row]
print(L)

Which would print:

[[1, []], [1, [0]], [1, [0, 0]], [1, [0, 0, 0]], [1, [0, 0, 0, 0]], [1, [0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]
[1, [], 1, [0], 1, [0, 0], 1, [0, 0, 0], 1, [0, 0, 0, 0], 1, [0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

Flattening the list any further would result in a TypeError: 'int' object is not iterable and I would have to add another 1 at the end of the list using a seperate command which I guess would be fine. To add the code for flattening the list kinda goes over my head.

This is a second attempt using if/else statements, that gives the produces the same output and gives the same TypeError for when I try to flatten it completely.

L = [1 if i%2 == 0 else [0]*(i//2) for i in range(22)]
L = [j for row in L for j in row]
print(L)

I just want this as output:

[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

Thanks!

Body:
You could use a nested comprehension that produces an increasing number of values that you convert to 0s and 1s by returning 0s for all but the last of each group:

n = 10
r = [1]+[b//z for z in range(1,n+2) for b in range(1,z+1)]
print(r)
[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

If you want to avoid the need to add the initial [1], you could use a similar approach starting z at -1 instead of 1:

r = [ 1-(b<z) for z in range(-1,n+1) for b in range(z+1 or 1)]


问:
Babel package name convention on npm
Babel seems to offer two sets of packages on npm. One is named with a '@' prefix and '/' separator such as @babel/core. The other is named without a '@' prefix and with '-' separator such as babel-core. Is it because they changed the naming convention since version 7 or due to another reason?

Thanks,

答: Looks like they changed the naming convention since version 7.</p>

Title: Babel package name convention on npm


答: The traceback  exists, and the interpreter can use it  (e.g. print it) ,  but you can only use it if you import it. If you do not use a try/except block you do not have a chance to import it.</p>


问:
Removing spatial interpolation or compression in GIFs created with imageio or PIL
I am trying to create GIFs using imageio. This is fairly straightforward; however, the quality of the images is poor. They appear to be interpolated. See the figures below.

I am creating the GIF using the code shown below. I've tried tracing the the how the image is produced inside the source code and the issue seems to be coming from PIL.

```<code>from PIL import Image
import imageio
import numpy as np
import matplotlib.pyplot as plt

outdir = r"where/you/want/it/to/go.gif"
frames = np.round(100+20*np.random.randn(10, 40, 40)).astype(np.uint8)

# Create single gif frame with PIL
im = Image.fromarray(frames[0])
im.save(outdir)

# Create gif with imageio
imageio.mimsave(outdir, frames)
</code>```

I want a GIF that looks like the image on top (no interpolation) which I produced with matplotlib. The image on the bottom is a single frame produced using imageio.

答:
I tried to reproduce the problem but - as far as I can tell - there is no interpolation happening inside of either ImageIO or Pillow:

from PIL import Image
import imageio as iio
import numpy as np
import io

for _ in range(100):
    expected_frames = np.round(100+20*np.random.randn(10, 40, 40)).astype(np.uint8)

    # test writing with pillow
    pil_buffer = io.BytesIO()
    im = Image.fromarray(expected_frames[0])
    gif_bytes = im.save(pil_buffer, format="GIF")
    actual_pil = iio.v3.imread(pil_buffer, mode="L")
    assert np.all(actual_pil == expected_frames[0])

    # test writing with ImageIO
    gif_bytes = iio.v3.imwrite("<bytes>", expected_frames, format="GIF")
    actual_iio = iio.v3.imread(gif_bytes, index=None, mode="L")
    assert np.all(actual_iio == expected_frames)

print("No roundtrip modified any pixels.")
```

So I think that either

There may have been a bug in Pillow or ImageIO that has since been fixed (it has been 3 years)

The tool/application you used to display the second image interpolates as you zoom into the image (since that image is 200x200 px instead of being 40x40 pixels)

Body:
I am trying to create GIFs using imageio. This is fairly straightforward; however, the quality of the images is poor. They appear to be interpolated. See the figures below.

I am creating the GIF using the code shown below. I've tried tracing the the how the image is produced inside the source code and the issue seems to be coming from PIL.

from PIL import Image
import imageio
import numpy as np
import matplotlib.pyplot as plt

outdir = r"where/you/want/it/to/go.gif"
frames = np.round(100+20*np.random.randn(10, 40, 40)).astype(np.uint8)

# Create single gif frame with PIL
im = Image.fromarray(frames[0])
im.save(outdir)

# Create gif with imageio
imageio.mimsave(outdir, frames)

I want a GIF that looks like the image on top (no interpolation) which I produced with matplotlib. The image on the bottom is a single frame produced using imageio.

Body:
I tried to reproduce the problem but - as far as I can tell - there is no interpolation happening inside of either ImageIO or Pillow:

from PIL import Image
import imageio as iio
import numpy as np
import io

for _ in range(100):
    expected_frames = np.round(100+20*np.random.randn(10, 40, 40)).astype(np.uint8)

    # test writing with pillow
    pil_buffer = io.BytesIO()
    im = Image.fromarray(expected_frames[0])
    gif_bytes = im.save(pil_buffer, format="GIF")
    actual_pil = iio.v3.imread(pil_buffer, mode="L")
    assert np.all(actual_pil == expected_frames[0])

    # test writing with ImageIO
    gif_bytes = iio.v3.imwrite("<bytes>", expected_frames, format="GIF")
    actual_iio = iio.v3.imread(gif_bytes, index=None, mode="L")
    assert np.all(actual_iio == expected_frames)

print("No roundtrip modified any pixels.")

So I think that either

There may have been a bug in Pillow or ImageIO that has since been fixed (it has been 3 years)

The tool/application you used to display the second image interpolates as you zoom into the image (since that image is 200x200 px instead of being 40x40 pixels)


问:
How to make eChart responsive?
I've never really worked with JavaScript so I'm probably doing something stupid. But for some reason the echart I am using isn't responsive in line with how a div resizes upon screen size. I'm using bootstrap for CSS.

I think I have followed the documentation correctly on the official documentation.

But for me it doesn't resize or seem to be anchored to a div.

```<code><div class="col-sm-12 col-md-3 col-lg-3 col-xl-2">
    <div class="card custom-card">
        <div class="card-body">
            <div class="card-item">
                <div class="card-item-icon card-icon">
                    <svg class="text-primary" xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect height="14" opacity=".3" width="14" x="5" y="5"/><g><rect fill="none" height="24" width="24"/><g><path d="M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h14c1.1,0,2-0.9,2-2V5C21,3.9,20.1,3,19,3z M19,19H5V5h14V19z"/><rect height="5" width="2" x="7" y="12"/><rect height="10" width="2" x="15" y="7"/><rect height="3" width="2" x="11" y="14"/><rect height="2" width="2" x="11" y="10"/></g></g></g></svg>
                </div>
                <div class="card-item-title mb-2">
                    <label class="main-content-label tx-13 font-weight-bold mb-1">Chart</label>
                    <span class="d-block tx-12 mb-0 text-muted">Current</span>
                </div>
                <div class="card-item-body">
                    <div class="card-item-stat">
                        <div id="main" style="width: 200px;height:200px;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```
```<code><script type="text/javascript">
    var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom, 'dark');
var option;

option = {
    series: [
        {
            type: 'gauge',
            startAngle: 180,
            endAngle: 0,
            min: 0,
            max: 1,
            splitNumber: 4,

            axisLine: {
                lineStyle: {
                    width: 6,
                    color: [
                        [0.33, '#FF6E76'],
                        [0.66, '#FDDD60'],
                        [0.75, '#58D9F9'],
                        [1, '#7CFFB2']
                    ]
                }
            },
            pointer: {
                icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
                length: '50%',
                width: 20,
                offsetCenter: [0, '-30%'],
                itemStyle: {
                    color: 'auto'
                }
            },
            axisTick: {
                length: 12,
                lineStyle: {
                    color: 'auto',
                    width: 2
                }
            },
            splitLine: {
                length: 20,
                lineStyle: {
                    color: 'auto',
                    width: 2
                }
            },
            axisLabel: {
                color: '#464646',
                fontSize: 10,
                distance: -60,
                formatter: function (value) {
                    if (value === 0.875) {
                        return 'A';
                    } else if (value === 0.625) {
                        return 'B';
                    } else if (value === 0.375) {
                        return 'C';
                    } else if (value === 0.125) {
                        return 'D';
                    }
                    return '';
                }
            },
            title: {
                offsetCenter: [0, '-20%'],
                fontSize: 30
            },
            detail: {
                fontSize: 15,
                offsetCenter: [0, '0%'],
                valueAnimation: true,
                formatter: function (value) {
                    return Math.round(value * 100) + '分';
                },
                color: 'auto'
            },
            data: [
                {
                    value: 0.7,
                }
            ]
        }
    ]
};

option && myChart.setOption(option);
</code>```

答:
Your <svg> element has fixed width and height attributes.

Removing these will make your svg resize according to your parent element's size:

.card-icon{
  width:50%;
  position:relative;
  resize:both;
  overflow:auto;
  border: 1px solid #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card-item-icon card-icon">
  <svg class="text-primary" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" >
    <g>
      <rect height="14" opacity=".3" width="14" x="5" y="5" />
      <g>
        <rect fill="none" height="24" width="24" />
        <g>
          <path d="M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h14c1.1,0,2-0.9,2-2V5C21,3.9,20.1,3,19,3z M19,19H5V5h14V19z" />
          <rect height="5" width="2" x="7" y="12" />
          <rect height="10" width="2" x="15" y="7" />
          <rect height="3" width="2" x="11" y="14" />
          <rect height="2" width="2" x="11" y="10" />
        </g>
      </g>
    </g>
  </svg>
</div>
<p>Try resizing</p></code>```

Title: How to make eChart responsive?

Body:
I've never really worked with JavaScript so I'm probably doing something stupid. But for some reason the echart I am using isn't responsive in line with how a div resizes upon screen size. I'm using bootstrap for CSS.

I think I have followed the documentation correctly on the official documentation.

But for me it doesn't resize or seem to be anchored to a div.

                    <svg class="text-primary" xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect height="14" opacity=".3" width="14" x="5" y="5"/><g><rect fill="none" height="24" width="24"/><g><path d="M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h14c1.1,0,2-0.9,2-2V5C21,3.9,20.1,3,19,3z M19,19H5V5h14V19z"/><rect height="5" width="2" x="7" y="12"/><rect height="10" width="2" x="15" y="7"/><rect height="3" width="2" x="11" y="14"/><rect height="2" width="2" x="11" y="10"/></g></g></g></svg>

                    Chart
                    Current

Body:
Your <svg> element has fixed width and height attributes.

Removing these will make your svg resize according to your parent element's size:

.card-icon{
  width:50%;
  position:relative;
  resize:both;
  overflow:auto;
  border: 1px solid #ccc;
}

<div class="card-item-icon card-icon">
  <svg class="text-primary" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" >
    <g>
      <rect height="14" opacity=".3" width="14" x="5" y="5" />
      <g>
        <rect fill="none" height="24" width="24" />
        <g>
          <path d="M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h14c1.1,0,2-0.9,2-2V5C21,3.9,20.1,3,19,3z M19,19H5V5h14V19z" />
          <rect height="5" width="2" x="7" y="12" />
          <rect height="10" width="2" x="15" y="7" />
          <rect height="3" width="2" x="11" y="14" />
          <rect height="2" width="2" x="11" y="10" />
        </g>
      </g>
    </g>
  </svg>
</div>
<p>Try resizing</p>


问:
Android RecycleView how to disable manual scroll but allow item clicked
I am working on an idea, which is make a RecyclerView auto scrolling but allow user to click item without stop scrolling.

First, I create a custom LayoutManager to disable manual scroll, also change the speed of scroll to a certain position

```<code>class CustomLayoutManager(context: Context, countOfColumns: Int) :
GridLayoutManager(context, countOfColumns) {

// Custom smooth scroller
private val smoothScroller = object : LinearSmoothScroller(context) {
    override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float =
        500f / displayMetrics.densityDpi
}

// Disable manual scroll
override fun canScrollVertically(): Boolean = false

// Using custom smooth scroller to control the duration of smooth scroll to a certain position
override fun smoothScrollToPosition(
    recyclerView: RecyclerView,
    state: RecyclerView.State?,
    position: Int
) {
    smoothScroller.targetPosition = position
    startSmoothScroll(smoothScroller)
}
}
</code>```

Then I do the initial work for the RecyclerView and start smooth scroll after 1 sec

```<code>viewBinding.list.apply {
        // initial recycler view
        setHasFixedSize(true)
        customLayoutManager = CustomLayoutManager(context = context, countOfColumns = 2)
        layoutManager = customLayoutManager

        // data list
        val dataList = mutableListOf<TestModel>()
        repeat(times = 100) { dataList.add(TestModel(position = it, clicked = false)) }

        // adapter
        testAdapter =
            TestAdapter(clickListener = { testAdapter.changeVhColorByPosition(position = it) })
        adapter = testAdapter
        testAdapter.submitList(dataList)

        // automatically scroll after 1 sec
        postDelayed({ smoothScrollToPosition(dataList.lastIndex) }, 1000)
    }
</code>```

Everything goes as my expected until I found that the auto scrolling stopped when I clicked on any item on the RecycelerView, the function when clickListener triggered just change background color of the view holder in TestAdapter

```<code>fun changeVhColor(position: Int) {
    position
        .takeIf { it in 0..itemCount }
        ?.also { getItem(it).clicked = true }
        ?.also { notifyItemChanged(it) }
}
</code>```

here is the screen recording screen recording

issues I encounter

auto scrolling stopped when I tap any item on the ReycelerView

first tap make scrolling stopped, second tap trigger clickListener, but I expect to trigger clickListener by one tap

Can anybody to tell me how to resolve this? Thanks in advance.

答:
After tried several ways, found that the key of keep recycler view scrolling automatically is override onInterceptTouchEvent

Example

```<code>class MyRecyclerView @JvmOverloads constructor(
     context: Context,
     attrs: AttributeSet? = null,
     defStyle: Int = 0
 ) : RecyclerView(context, attrs, defStyle) {
     override fun onInterceptTouchEvent(e: MotionEvent?): Boolean = false
}
</code>```

that will make the custom RecyclerView ignore all touch event

Body:
I am working on an idea, which is make a RecyclerView auto scrolling but allow user to click item without stop scrolling.

First, I create a custom LayoutManager to disable manual scroll, also change the speed of scroll to a certain position

class CustomLayoutManager(context: Context, countOfColumns: Int) :
GridLayoutManager(context, countOfColumns) {

// Custom smooth scroller
private val smoothScroller = object : LinearSmoothScroller(context) {
    override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float =
        500f / displayMetrics.densityDpi
}

// Disable manual scroll
override fun canScrollVertically(): Boolean = false

// Using custom smooth scroller to control the duration of smooth scroll to a certain position
override fun smoothScrollToPosition(
    recyclerView: RecyclerView,
    state: RecyclerView.State?,
    position: Int
) {
    smoothScroller.targetPosition = position
    startSmoothScroll(smoothScroller)
}
}

Then I do the initial work for the RecyclerView and start smooth scroll after 1 sec

viewBinding.list.apply {
        // initial recycler view
        setHasFixedSize(true)
        customLayoutManager = CustomLayoutManager(context = context, countOfColumns = 2)
        layoutManager = customLayoutManager

        // data list
        val dataList = mutableListOf<TestModel>()
        repeat(times = 100) { dataList.add(TestModel(position = it, clicked = false)) }

        // adapter
        testAdapter =
            TestAdapter(clickListener = { testAdapter.changeVhColorByPosition(position = it) })
        adapter = testAdapter
        testAdapter.submitList(dataList)

        // automatically scroll after 1 sec
        postDelayed({ smoothScrollToPosition(dataList.lastIndex) }, 1000)
    }

Everything goes as my expected until I found that the auto scrolling stopped when I clicked on any item on the RecycelerView, the function when clickListener triggered just change background color of the view holder in TestAdapter

fun changeVhColor(position: Int) {
    position
        .takeIf { it in 0..itemCount }
        ?.also { getItem(it).clicked = true }
        ?.also { notifyItemChanged(it) }
}

here is the screen recording screen recording

issues I encounter

auto scrolling stopped when I tap any item on the ReycelerView

first tap make scrolling stopped, second tap trigger clickListener, but I expect to trigger clickListener by one tap

Can anybody to tell me how to resolve this? Thanks in advance.

Body:
After tried several ways, found that the key of keep recycler view scrolling automatically is override onInterceptTouchEvent

Example

class MyRecyclerView @JvmOverloads constructor(
     context: Context,
     attrs: AttributeSet? = null,
     defStyle: Int = 0
 ) : RecyclerView(context, attrs, defStyle) {
     override fun onInterceptTouchEvent(e: MotionEvent?): Boolean = false
}

that will make the custom RecyclerView ignore all touch event


问:
Returning address only in English from reverseGeocodeLocation
My app is geolocation based app and each entry in tableview has location of the entry. The weird thing I found is that when users are from outside of US, the location is written in their language. For example, there was one user from Vietnam and the address was written in Vietnamese.
I'm using reverseGeocodeLocation like below to retrieve the address of an entry's location. Is there a way to get results only in English? I tried the code out there in other stackoverflow questions, but did not work. </p>

<p>And I am first getting geopoint using Parse. I do not need to do this way, but I just decided to do. </p>

```<code> PFGeoPoint.geoPointForCurrentLocationInBackground {
                (geoPoint: PFGeoPoint?, error: NSError?) -> Void in
    var location = CLLocation(latitude: GlobalVariable.userLocation!.latitude, longitude: GlobalVariable.userLocation!.longitude)

 CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
    if error != nil {
    print("Reverse geocoder failed with error" + error!.localizedDescription, terminator: "")
                            return}
 if placemarks!.count > 0 {
 let pm = placemarks![0] as CLPlacemark
GlobalVariable.detailedLocation =  "\(pm.subLocality)," + " \(pm.locality)," + " \(pm.ISOcountryCode)" }
</code>```

答:
you can pass parameter "preferredLocale" to specific language</p>
```<code>let locale = Locale(identifier: "en_US")
CLGeocoder().reverseGeocodeLocation(location, preferredLocale: locale, completionHandler: {(placemarks, error) in

})
</code>```

Body:
My app is geolocation based app and each entry in tableview has location of the entry. The weird thing I found is that when users are from outside of US, the location is written in their language. For example, there was one user from Vietnam and the address was written in Vietnamese.
I'm using reverseGeocodeLocation like below to retrieve the address of an entry's location. Is there a way to get results only in English? I tried the code out there in other stackoverflow questions, but did not work.

And I am first getting geopoint using Parse. I do not need to do this way, but I just decided to do.

 PFGeoPoint.geoPointForCurrentLocationInBackground {
                (geoPoint: PFGeoPoint?, error: NSError?) -> Void in
    var location = CLLocation(latitude: GlobalVariable.userLocation!.latitude, longitude: GlobalVariable.userLocation!.longitude)

 CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
    if error != nil {
    print("Reverse geocoder failed with error" + error!.localizedDescription, terminator: "")
                            return}
 if placemarks!.count > 0 {
 let pm = placemarks![0] as CLPlacemark
GlobalVariable.detailedLocation =  "\(pm.subLocality)," + " \(pm.locality)," + " \(pm.ISOcountryCode)" }

Body:
you can pass parameter "preferredLocale" to specific language

let locale = Locale(identifier: "en_US")
CLGeocoder().reverseGeocodeLocation(location, preferredLocale: locale, completionHandler: {(placemarks, error) in

})