问:
In Laravel/mySQL query, how to select users by comparing arrays (or how to incorporate array_diff in where clause)?
Qn in simpler terms: I am searching as a user for other users. All users have set preferred languages and fluent languages. I need to select users whose fluent languages match with this user's preferred languages. Both fluent languages and preferred languages are array (text fields in DB but through JSON cast). How to do that? (Also, fluent language is just one of many conditions in the query. So the query structure itself cannot be modified now.)

Details on what has been tried: I am getting a list of users into $users. One of the conditions require me to compare preferredLanguages (This is an array->collection1) with fluentLanguages (This is also is an array->collection2). All values of preferredLanguages needs to be present in fluentLanguage. So, I am using array_diff and checking if the result is null.

The issue is how do I use this within the where clause? I can use array_diff in, say, an if condition, but I don't know to use it within the where clause.

I tried everything I can think of, but nothing works so far! Can someone please help?

```<code>$collection1=$preferrences->preferredLanguages;
$collection2='user_details.fluentLanguages';

$diff= array_diff($collection1, $collection1);

$users->where(function (Builder $query) use ($matchPref) {
        $query
           ->where($diff, '[]');  //I need to check if $diff is null/empty. I tried everything I can think of here.
    });
</code>```

Edit: I tried something else as siggested by Kenny below. I believe this might work but didnt quite solved it yet. Any help is appreciated.

```<code>$users->filter(function ($user, $key) use ($preferrences->preferredLanguages)){
            return ! array_diff($user['fluentLanguages'], $preferrences->preferredLanguages);
        });
</code>```

I also tried with where but it did not work out as well.

```<code>$users->where(array_diff('user_details.fluentLanguages', $preferrences->preferredLanguages)->IsEmpty(), true)
</code>```

答:
One strategy that comes to my mind could be:

Get the fluentLanguageof each user.

```<code>$candidates = User::select('id', 'fluentLanguage')->get();
</code>```

Filter them according to the condition.

```<code>$filtered = $candidates
                ->filter(function ($candidate, $key) use ($matchFluentIn) {
                    return ! array_diff($candidate['fluentLanguage'], $matchFluentIn);
                })
                ->pluck('id')
                ->all();
</code>```

Get full details of these filetered list of users:

```<code>$users = User::whereIn('id', $filtered)->get();
</code>```

Hope this helps.

Body:
Qn in simpler terms: I am searching as a user for other users. All users have set preferred languages and fluent languages. I need to select users whose fluent languages match with this user's preferred languages. Both fluent languages and preferred languages are array (text fields in DB but through JSON cast). How to do that? (Also, fluent language is just one of many conditions in the query. So the query structure itself cannot be modified now.)

Details on what has been tried: I am getting a list of users into $users. One of the conditions require me to compare preferredLanguages (This is an array->collection1) with fluentLanguages (This is also is an array->collection2). All values of preferredLanguages needs to be present in fluentLanguage. So, I am using array_diff and checking if the result is null.

The issue is how do I use this within the where clause? I can use array_diff in, say, an if condition, but I don't know to use it within the where clause.

I tried everything I can think of, but nothing works so far! Can someone please help?

$collection1=$preferrences->preferredLanguages;
$collection2='user_details.fluentLanguages';

$diff= array_diff($collection1, $collection1);

$users->where(function (Builder $query) use ($matchPref) {
        $query
           ->where($diff, '[]');  //I need to check if $diff is null/empty. I tried everything I can think of here.
    });

Edit: I tried something else as siggested by Kenny below. I believe this might work but didnt quite solved it yet. Any help is appreciated.

$users->filter(function ($user, $key) use ($preferrences->preferredLanguages)){
            return ! array_diff($user['fluentLanguages'], $preferrences->preferredLanguages);
        });

I also tried with where but it did not work out as well.

$users->where(array_diff('user_details.fluentLanguages', $preferrences->preferredLanguages)->IsEmpty(), true)

Body:
One strategy that comes to my mind could be:

Get the fluentLanguageof each user.

$candidates = User::select('id', 'fluentLanguage')->get();

Filter them according to the condition.

$filtered = $candidates
                ->filter(function ($candidate, $key) use ($matchFluentIn) {
                    return ! array_diff($candidate['fluentLanguage'], $matchFluentIn);
                })
                ->pluck('id')
                ->all();

Get full details of these filetered list of users:

$users = User::whereIn('id', $filtered)->get();

Hope this helps.


来源: stackexchange

答:
Since Spark 2.4, you could also compute this using the higher order function aggregate:

import org.apache.spark.sql.functions.{expr, max}
val df = Seq(
  ("rr", "gg", "20171103", 2),
  ("hh", "jj", "20171103", 3),
  ("rr", "gg", "20171104", 4),
  ("hh", "jj", "20171104", 5),
  ("rr", "gg", "20171105", 6),
  ("hh", "jj", "20171105", 7)
).toDF("A", "B", "date", "val")

val result = df
  .groupBy("A", "B")
  .agg(
    max($"date").as("date"),
    expr("""
   aggregate(
     collect_list(val),
     cast(1 as bigint),
     (acc, x) -> acc * x)""").alias("val")
  )
```

ContentLicense: CC BY-SA 4.0

Title: Cumulative product in Spark

Body:
I try to implement a cumulative product in Spark Scala, but I really don't know how to it. I have the following dataframe:

Input data:
+--+--+--------+----+
|A |B | date   | val|
+--+--+--------+----+
|rr|gg|20171103| 2  |
|hh|jj|20171103| 3  |
|rr|gg|20171104| 4  |
|hh|jj|20171104| 5  |
|rr|gg|20171105| 6  |
|hh|jj|20171105| 7  |
+-------+------+----+

And I would like to have the following output:

Output data:
+--+--+--------+-----+
|A |B | date   | val |
+--+--+--------+-----+
|rr|gg|20171105| 48  | // 2 * 4 * 6
|hh|jj|20171105| 105 | // 3 * 5 * 7
+-------+------+-----+


问:
AngularJs : How to declare an app & multiple controllers, serves, etc, using an IFFE?
John Papa's famous Angular 1 Style Guide says to use IIFEs, to avoid the likes of  var myApp = angular.module('myApp',[]);
 and polluting the global namespace.

The example given is:

logger.js

```<code>(function() {
    'use strict';

    angular
        .module('app')
        .factory('logger', logger);

    function logger() { }
})();
</code>```

storage.js

```<code>(function() {
    'use strict';

    angular
        .module('app')
        .factory('storage', storage);

    function storage() { }
})();
</code>```

How does this work? Do I not need to declare the module at least once? E.g with angular.module('app',[]); (wrapped in an IIFE? (instead of var app = angular.module('app',[]); to avoid a global variable))?

However, the two usages of angular.module('app') in the example , do not declare, but will then evaluate angular.module('app') twice, which surely cannot be A Good Thing (in fact, I read a highly upvoted S.O. question earlier which said that this is A Bad Thing, and that there should be a single reference - but that would be a global, which is also A Bad Thing).

Which is it to be? Or can I declare my angular.module('app'), plus a few controllers, serves, factories, directives, in separate files, in separate IIFEs? If so, how?

答:
Do I not need to declare the module at least once?

Yes, the module needs to be created with dependencies first:

app.js

```<code>angular.module('app',['ngRoute']);
</code>```

This must be done before any subsequent scripts add to it. It need not be enclosed in an IIFE because it doesn't declare any global variables.

To avoid pollution of the global namespace, the following needs to be enclosed in an IIFE:

logger.js

```<code>(function() {
    'use strict';

    angular
        .module('app')
        .factory('logger', logger);

    function logger() { }
})();
</code>```

On the other hand

storage.js

```<code>'use strict';

angular.module('app')
.service('storage', function storage() {
    var value;
    this.get = function() { return value; };
    this.set = function(val) {
        value = val;
    };
})
</code>```

This does not need an IIFE because it does not declare any global variables or functions.

Both examples avoid polluting the global namespace.

For more information, see

AngularJS angular.module Method API Reference

Body:
John Papa's famous Angular 1 Style Guide says to use IIFEs, to avoid the likes of  var myApp = angular.module('myApp',[]);
 and polluting the global namespace.

The example given is:

logger.js

(function() {
    'use strict';

    angular
        .module('app')
        .factory('logger', logger);

    function logger() { }
})();

storage.js

(function() {
    'use strict';

    angular
        .module('app')
        .factory('storage', storage);

    function storage() { }
})();

How does this work? Do I not need to declare the module at least once? E.g with angular.module('app',[]); (wrapped in an IIFE? (instead of var app = angular.module('app',[]); to avoid a global variable))?

However, the two usages of angular.module('app') in the example , do not declare, but will then evaluate angular.module('app') twice, which surely cannot be A Good Thing (in fact, I read a highly upvoted S.O. question earlier which said that this is A Bad Thing, and that there should be a single reference - but that would be a global, which is also A Bad Thing).

Which is it to be? Or can I declare my angular.module('app'), plus a few controllers, serves, factories, directives, in separate files, in separate IIFEs? If so, how?

Body:
Do I not need to declare the module at least once?

Yes, the module needs to be created with dependencies first:

app.js

angular.module('app',['ngRoute']);

This must be done before any subsequent scripts add to it. It need not be enclosed in an IIFE because it doesn't declare any global variables.

To avoid pollution of the global namespace, the following needs to be enclosed in an IIFE:

logger.js

(function() {
    'use strict';

    angular
        .module('app')
        .factory('logger', logger);

    function logger() { }
})();

On the other hand

storage.js

'use strict';

angular.module('app')
.service('storage', function storage() {
    var value;
    this.get = function() { return value; };
    this.set = function(val) {
        value = val;
    };
})

This does not need an IIFE because it does not declare any global variables or functions.

Both examples avoid polluting the global namespace.

For more information, see

AngularJS angular.module Method API Reference


问:
Wait for kubernetes job to complete on either failure/success using command line
What is the best way to wait for kubernetes job to be complete?  I noticed a lot of suggestions to use:

```<code>kubectl wait --for=condition=complete job/myjob
</code>```

but i think that only works if the job is successful. if it fails, i have to do something like:

```<code>kubectl wait --for=condition=failed job/myjob
</code>```

is there a way to wait for both conditions using wait?  if not, what is the best way to wait for a job to either succeed or fail?

答:
Run the first wait condition as a subprocess and capture its PID. If the condition is met, this process will exit with an exit code of 0.

kubectl wait --for=condition=complete job/myjob &
completion_pid=$!
```
<p>Do the same for the failure wait condition. The trick here is to add <code>&& exit 1</code> so that the subprocess returns a non-zero exit code when the job fails.</p>
<pre class="lang-bash prettyprint-override"><code>kubectl wait --for=condition=failed job/myjob && exit 1 &
failure_pid=$!
</code>```

Then use the Bash builtin wait -n $PID1 $PID2 to wait for one of the conditions to succeed. The command will capture the exit code of the first process to exit:

MAC USERS! Note that wait -n [...PID] requires Bash version 4.3 or higher. MacOS is forever stuck on version 3.2 due to license issues. Please see this Stackoverflow Post on how to install the latest version.

wait -n $completion_pid $failure_pid
```
<p>Finally, you can check the actual exit code of <code>wait -n</code> to see whether the job failed or not:</p>
<pre class="lang-bash prettyprint-override"><code>exit_code=$?

if (( $exit_code == 0 )); then
  echo "Job completed"
else
  echo "Job failed with exit code ${exit_code}, exiting..."
fi

exit $exit_code
</code>```

Complete example:

# wait for completion as background process - capture PID
kubectl wait --for=condition=complete job/myjob &
completion_pid=$!

# wait for failure as background process - capture PID
kubectl wait --for=condition=failed job/myjob && exit 1 &
failure_pid=$!

# capture exit code of the first subprocess to exit
wait -n $completion_pid $failure_pid

# store exit code in variable
exit_code=$?

if (( $exit_code == 0 )); then
  echo "Job completed"
else
  echo "Job failed with exit code ${exit_code}, exiting..."
fi

exit $exit_code
```

Body:
What is the best way to wait for kubernetes job to be complete?  I noticed a lot of suggestions to use:

kubectl wait --for=condition=complete job/myjob

but i think that only works if the job is successful. if it fails, i have to do something like:

kubectl wait --for=condition=failed job/myjob

is there a way to wait for both conditions using wait?  if not, what is the best way to wait for a job to either succeed or fail?

Body:
Run the first wait condition as a subprocess and capture its PID. If the condition is met, this process will exit with an exit code of 0.

kubectl wait --for=condition=complete job/myjob &
completion_pid=$!

Do the same for the failure wait condition. The trick here is to add && exit 1 so that the subprocess returns a non-zero exit code when the job fails.

kubectl wait --for=condition=failed job/myjob && exit 1 &
failure_pid=$!

Then use the Bash builtin wait -n $PID1 $PID2 to wait for one of the conditions to succeed. The command will capture the exit code of the first process to exit:

MAC USERS! Note that wait -n [...PID] requires Bash version 4.3 or higher. MacOS is forever stuck on version 3.2 due to license issues. Please see this Stackoverflow Post on how to install the latest version.

wait -n $completion_pid $failure_pid

Finally, you can check the actual exit code of wait -n to see whether the job failed or not:

exit_code=$?

if (( $exit_code == 0 )); then
  echo "Job completed"
else
  echo "Job failed with exit code ${exit_code}, exiting..."
fi

exit $exit_code

Complete example:

# wait for completion as background process - capture PID
kubectl wait --for=condition=complete job/myjob &
completion_pid=$!

# wait for failure as background process - capture PID
kubectl wait --for=condition=failed job/myjob && exit 1 &
failure_pid=$!

# capture exit code of the first subprocess to exit
wait -n $completion_pid $failure_pid

# store exit code in variable
exit_code=$?

if (( $exit_code == 0 )); then
  echo "Job completed"
else
  echo "Job failed with exit code ${exit_code}, exiting..."
fi

exit $exit_code


问:
Flutter - how can i update the data to the realtime datebase on firebase and find those keys if i dont know it

I am new to flutter, I am wondering how I can update the data in realtime datebase on firebase if i dont know those keys.
For example, I want to change the partStatus from "In progress" to "delivered" either dynamically or individually when i dont know those keys.

答:
You have to make sure that whenever you add a new item to your database and autoId has been generated, the database-generated-id should be the id of the model class you use to hold the data in your project. So whenever an update is made, referencing the id as database key can be able to get you to the product you want to update.

See the below sample code:

```<code>...
//fetching logic here
 Future<void> fetchAndSetOrders() async {
    final url = 'https://<*firebase-project-name*>.firebaseio.com/orderList.json?auth=$authToken';
    //add try and catch errors
    try {
      final response = await http.get(url);
      final responseData = json.decode(response.body) as Map<String, dynamic>;
      if (responseData == null) {
        return;
      }
      List<OrderItem> loadedOrders = [];
      responseData.forEach(
        (orderId, orderData) => loadedOrders.add(
          OrderItem(
            orderNo: orderData['orderNo'],
            partNo: orderData['partNo'],
            status: orderData['partStatus'],
            qty: orderData['qty'],
            //**here id of order item is the orderId attached to the response
            id: orderId,
          ),
        ),
      );
      _items = loadedOrders;
      notifyListeners();
    } catch (error) {
      //
    }
  }
...
</code>```

Now to update the order.. since each order has an id equal to the key of the dataitem in the database

```<code>...
Future<void> updateOrder(String orderId, OrderItem order) async {
    //note that i added the orderId to the url string
    final url = 'https://<*firebase-project-name*>.firebaseio.com/orderList/$orderId.json?auth=$authToken';
    await http.patch(
      url,
      body: json.encode({
        'orderNo': order.orderNo,
        'partNo': order.partNo,
        'partStatus': order.status,
        'qty': order.qty,
      }),
    );
  }
...
</code>```

Happy Coding D:)

Body:
You have to make sure that whenever you add a new item to your database and autoId has been generated, the database-generated-id should be the id of the model class you use to hold the data in your project. So whenever an update is made, referencing the id as database key can be able to get you to the product you want to update.

See the below sample code:

...
//fetching logic here
 Future<void> fetchAndSetOrders() async {
    final url = 'https://<*firebase-project-name*>.firebaseio.com/orderList.json?auth=$authToken';
    //add try and catch errors
    try {
      final response = await http.get(url);
      final responseData = json.decode(response.body) as Map<String, dynamic>;
      if (responseData == null) {
        return;
      }
      List<OrderItem> loadedOrders = [];
      responseData.forEach(
        (orderId, orderData) => loadedOrders.add(
          OrderItem(
            orderNo: orderData['orderNo'],
            partNo: orderData['partNo'],
            status: orderData['partStatus'],
            qty: orderData['qty'],
            //**here id of order item is the orderId attached to the response
            id: orderId,
          ),
        ),
      );
      _items = loadedOrders;
      notifyListeners();
    } catch (error) {
      //
    }
  }
...

Now to update the order.. since each order has an id equal to the key of the dataitem in the database

...
Future<void> updateOrder(String orderId, OrderItem order) async {
    //note that i added the orderId to the url string
    final url = 'https://<*firebase-project-name*>.firebaseio.com/orderList/$orderId.json?auth=$authToken';
    await http.patch(
      url,
      body: json.encode({
        'orderNo': order.orderNo,
        'partNo': order.partNo,
        'partStatus': order.status,
        'qty': order.qty,
      }),
    );
  }
...

Happy Coding D:)


问:
How to return specific rows first and then randomize the rest in MySQL?
I have this table where I have about 250 rows. What I want is to return all the rows, but first I want to display the six rows where the field spazio = 'auditorium' and then display all the remaining rows in a random order.
I've tried something like

```<code>SELECT * FROM table ORDER BY case when spazio = 'auditorium' then case spazio != 'auditorium' RAND()
</code>```

But it's not returning what I want.

答:
You need an ELSE, a THEN, and an END. You also need to assign a number to your first THEN, which I'm going to say should be 0 so it's the first in an ASC order.

ORDER BY is reducing everything to a number value to put them in order. The CASE statement needs to give it a number back. Not to mention that RAND returns a number between 0 and 1, so a decimal. In fact, it could return 0 also, so it's safer to add 1.

SELECT * FROM `table` ORDER BY CASE WHEN `spazio` = "auditorium" THEN 0 ELSE RAND() + 1 END ASC

Body:
I have this table where I have about 250 rows. What I want is to return all the rows, but first I want to display the six rows where the field spazio = 'auditorium' and then display all the remaining rows in a random order.
I've tried something like

SELECT * FROM table ORDER BY case when spazio = 'auditorium' then case spazio != 'auditorium' RAND()

But it's not returning what I want.


问:
swift - how call app's code from another app and return data
I need to implement next scheme:

1) App1 has some UI like signin/signup, and user's profile. But main functionality is creating specific http request to get/update token.

2)when tapping button at App2 - App2 calls App1, then App1 execute only http request, and return token to App2, like callback. And this actions should be invisible for user, maybe like empty screen with spinner

What is the best way to make it real? Is it possible for iOS?

To share data between apps I suppose use App Group and shared UserDefaults, but how to call some class/function?

答:
some addition to @hobbsome answer

here is some useful info

and here is sample project with two apps, that communicate in-two-direction using x-callback-url protocol

you can parse your link at AppDelegate class, then redirect to ViewController and update its UI - check this answer


问:
NoSuchMethodError Using an API to connect to server
I am back into Android. It has been many years since I have tried to do programming for Android. I have years of experience for Java, but when it comes to Android I consider myself a newbie.

I have gotten a simple Android App up and running using an Emulator with Android Studio.

When I try to use our inhouse API to connect to a server, I am getting an error that I do not see when using the API in a Java App.

```<code>2020-02-18 10:49:08.723 11033-11033/com.company.monitor E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.company.monitor, PID: 11033
    java.lang.NoSuchMethodError: No static method metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; in class Ljava/lang/invoke/LambdaMetafactory; or its super classes (declaration of 'java.lang.invoke.LambdaMetafactory' appears in /apex/com.android.runtime/javalib/core-oj.jar)
        at com.company.client.api.PingPongSender.setupExecutorThread(PingPongSender.java:68)
        at com.company.client.api.PingPongSender.<init>(PingPongSender.java:64)
        at com.company.client.api.ServiceContext.<init>(ServiceContext.java:34)
        at com.company.monitor.MainActivity.onCreate(MainActivity.java:35)
        at android.app.Activity.performCreate(Activity.java:7802)
</code>```

The PingPongSender.java:68 is calling an ExecutorService. It is a class that is responsible for sending Ping to the server and receives Pong back. The API sends and receives Google Protobuf messages.

```<code>executor = Executors.newSingleThreadExecutor(new ThreadFactory("Executor"));
executor.execute(() -> {
    boolean doRun = true;
    while (doRun) {
        try {
            Runnable task = jobQueue.take();
            task.run();
        } catch (InterruptedException e) {
            logger.log(Level.WARN, "Failed to execute runnable or service was interrupted.", e);
            doRun = false;
        }
    }
});
</code>```

Running Android Studio 3.5.3. Emulator "Nexus 5X API 29 x86", Java 8.

Edit: The PingPongSender at pastebin https://pastebin.com/5YH51iv5

Edit: Found a similar question that had an answer which got me to recheck if my App was using Java 8 compatibility. I should have seen it sooner. I used several search phrases, but alas no results previously.
No static method metafactory

答:
AFAIU There seems to be 2 types of newSingleThreadExecutor as mentioned below

public static ExecutorService newSingleThreadExecutor ()
https://developer.android.com/reference/java/util/concurrent/Executors#newSingleThreadExecutor()

public static ExecutorService newSingleThreadExecutor (ThreadFactory threadFactory)
https://developer.android.com/reference/java/util/concurrent/Executors#newSingleThreadExecutor(java.util.concurrent.ThreadFactory)

Solution could be change your

```<code>executor = Executors.newSingleThreadExecutor("Executor");
</code>```

to

```<code>executor = Executors.newSingleThreadExecutor();
</code>```

Body:
I am back into Android. It has been many years since I have tried to do programming for Android. I have years of experience for Java, but when it comes to Android I consider myself a newbie.

I have gotten a simple Android App up and running using an Emulator with Android Studio.

When I try to use our inhouse API to connect to a server, I am getting an error that I do not see when using the API in a Java App.

2020-02-18 10:49:08.723 11033-11033/com.company.monitor E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.company.monitor, PID: 11033
    java.lang.NoSuchMethodError: No static method metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; in class Ljava/lang/invoke/LambdaMetafactory; or its super classes (declaration of 'java.lang.invoke.LambdaMetafactory' appears in /apex/com.android.runtime/javalib/core-oj.jar)
        at com.company.client.api.PingPongSender.setupExecutorThread(PingPongSender.java:68)
        at com.company.client.api.PingPongSender.<init>(PingPongSender.java:64)
        at com.company.client.api.ServiceContext.<init>(ServiceContext.java:34)
        at com.company.monitor.MainActivity.onCreate(MainActivity.java:35)
        at android.app.Activity.performCreate(Activity.java:7802)

The PingPongSender.java:68 is calling an ExecutorService. It is a class that is responsible for sending Ping to the server and receives Pong back. The API sends and receives Google Protobuf messages.

executor = Executors.newSingleThreadExecutor(new ThreadFactory("Executor"));
executor.execute(() -> {
    boolean doRun = true;
    while (doRun) {
        try {
            Runnable task = jobQueue.take();
            task.run();
        } catch (InterruptedException e) {
            logger.log(Level.WARN, "Failed to execute runnable or service was interrupted.", e);
            doRun = false;
        }
    }
});

Running Android Studio 3.5.3. Emulator "Nexus 5X API 29 x86", Java 8.

Edit: The PingPongSender at pastebin https://pastebin.com/5YH51iv5

Edit: Found a similar question that had an answer which got me to recheck if my App was using Java 8 compatibility. I should have seen it sooner. I used several search phrases, but alas no results previously.
No static method metafactory

Body:
AFAIU There seems to be 2 types of newSingleThreadExecutor as mentioned below

public static ExecutorService newSingleThreadExecutor ()
https://developer.android.com/reference/java/util/concurrent/Executors#newSingleThreadExecutor()

public static ExecutorService newSingleThreadExecutor (ThreadFactory threadFactory)
https://developer.android.com/reference/java/util/concurrent/Executors#newSingleThreadExecutor(java.util.concurrent.ThreadFactory)

Solution could be change your

executor = Executors.newSingleThreadExecutor("Executor");

to

executor = Executors.newSingleThreadExecutor();


问:
Flask - change the column type in existing database
I have following Model in existing db:

```<code>class Advert(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime, nullable=False, default = datetime.utcnow)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable = False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    category = db.Column(db.String(50), nullable=False, unique=True)
</code>```

I just want to remove unique=True from my Model. How to do that?

答:
I would like to suggest using Alembic for the database migration.

Let say if you want to alter the table. Just create an empty scheme migration alembic revision -m "alter table"

then you can add the alter here:

```<code>from alembic import op
import sqlalchemy as sa

revision = 'xxx'
down_revision = 'xxx'

def upgrade():
    op.execute('ALTER TABLE xx ... ')
    # Add the ALTER query here

def downgrade():
    pass
    # Add the ALTER query here
</code>```

Body:
I have following Model in existing db:

class Advert(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime, nullable=False, default = datetime.utcnow)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable = False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    category = db.Column(db.String(50), nullable=False, unique=True)

I just want to remove unique=True from my Model. How to do that?

Body:
I would like to suggest using Alembic for the database migration.

Let say if you want to alter the table. Just create an empty scheme migration alembic revision -m "alter table"

then you can add the alter here:

from alembic import op
import sqlalchemy as sa

revision = 'xxx'
down_revision = 'xxx'

def upgrade():
    op.execute('ALTER TABLE xx ... ')
    # Add the ALTER query here

def downgrade():
    pass
    # Add the ALTER query here


问:
Overriding method in C++
I am trying to override function add() in the inherited class NumericInput. But when I call add() on a NumericInput object the add() function in the base class is called. Why is this?

```<code>#include <iostream>
#include <string>

class TextInput
{
public:
    std::string cur;
    void add(char c)
   {
        cur += c;
        std::cout<<"input is: "<<c<<'\n';
   }

   std::string getValue() {return cur;}
};

class NumericInput : public TextInput
{
   public:
   void add(char c)
   {
    if(c>=48 && c <= 57)
    {
        std::cout<<"input is a digit: "<< c <<'\n';
        cur += c;
    }
    else
    {
        std::cout<<"input is not digit"<<'\n';}
    }
};

int main()
{
    TextInput* input = new NumericInput();
    input->add('1');
    input->add('a');
    input->add('0');
    std::cout << input->getValue();
}
</code>```

答:
I would suggest using :

```<code>bool my_isdigit(char ch)
{
    return std::isdigit(static_cast<unsigned char>(ch));
}
</code>```

in order to verify that your char is digit or not

ContentLicense: CC BY-SA 3.0

Title: Overriding method in C++

Body:
I am trying to override function add() in the inherited class NumericInput. But when I call add() on a NumericInput object the add() function in the base class is called. Why is this?

#include <iostream>
#include <string>

class TextInput
{
public:
    std::string cur;
    void add(char c)
   {
        cur += c;
        std::cout<<"input is: "<<c<<'\n';
   }

   std::string getValue() {return cur;}
};

class NumericInput : public TextInput
{
   public:
   void add(char c)
   {
    if(c>=48 && c <= 57)
    {
        std::cout<<"input is a digit: "<< c <<'\n';
        cur += c;
    }
    else
    {
        std::cout<<"input is not digit"<<'\n';}
    }
};

int main()
{
    TextInput* input = new NumericInput();
    input->add('1');
    input->add('a');
    input->add('0');
    std::cout << input->getValue();
}

Body:
I would suggest using :

bool my_isdigit(char ch)
{
    return std::isdigit(static_cast<unsigned char>(ch));
}

in order to verify that your char is digit or not


问:
How to make word triangle in c++ with for loop
how can I make this type of triangle:
where the size of triangle n = 5;

```<code>Five Four Three Two One
Five Four Three Two
Five Four Three
Five Four
Five
</code>```

Here's what I've tried:

```<code>int n;
cout<<"Enter Size of triangle: ";
cin>>n;

for(int i = n; i >= 1; i--){
    for(int j = n; j >= i; j--){
        cout<<j<<" ";
    }
    cout<<endl;
}
</code>```

答:
I suppose you can get the loop right yourself, so what is left is map numbers to strings. There is no automatic way to do that, but you have to define this mapping yourself. Perhaps the easiest is to use a

```<code>std::vector<std::string> numbers{ "One", "Two", "Three", "Four", "put" ,"more", "numbers", "here" };
</code>```

And then instead of printing the number j you print numbers[j]. Just take care of indexing: Vector uses zero-based indexing, but the first element is "One".

Body:
how can I make this type of triangle:
where the size of triangle n = 5;

Five Four Three Two One
Five Four Three Two
Five Four Three
Five Four
Five

Here's what I've tried:

int n;
cout<<"Enter Size of triangle: ";
cin>>n;

for(int i = n; i >= 1; i--){
    for(int j = n; j >= i; j--){
        cout<<j<<" ";
    }
    cout<<endl;
}

Body:
I suppose you can get the loop right yourself, so what is left is map numbers to strings. There is no automatic way to do that, but you have to define this mapping yourself. Perhaps the easiest is to use a

std::vector<std::string> numbers{ "One", "Two", "Three", "Four", "put" ,"more", "numbers", "here" };

And then instead of printing the number j you print numbers[j]. Just take care of indexing: Vector uses zero-based indexing, but the first element is "One".


问:
how i can implement a get method to a api what needs "Temporary Headers"?
I made an api using Net.Core 'https://localhost:44351/api/usuarios' with Authorize attribute for use a validation token for access to this api. This token is generated by another api and works well.
When i use Postman for acess to api 'https://localhost:44351/api/usuarios' i need put in the Authorization tab the token previously generated (see https://i.ibb.co/Lg7rD4N/2.png) and this way i get access for the api (see https://i.ibb.co/0BqnPhR/3.png)

But the huge problem is when i try from a JAVASCRIPT CLIENT use method GET using FETCH. I know need to do a object like this for make correct request

```<code>let params= {   method: 'GET',
                headers: {"X-Auth-Token": "5f5fe128570248a9bd198add1a5b25e4"}
            };
</code>```

So my question is how i can implement the attributte  'Temporary-Headers' in the object 'params' like Postman does ( https://i.ibb.co/0BqnPhR/3.png)?

答:
"Temporary Headers" are just like any other Header, those are just values auto-generated by the web client. I believe your problem relies on how you send your Header if you are using the fetch API modify your parameters like the following.

```<code>{
  method: 'GET',
  headers: {
    "Authorization": "Bearer <replace with your token>"
  }
}
</code>```

This is how postman is sending the request as seen in the screenshots you provide.

Body:
I made an api using Net.Core 'https://localhost:44351/api/usuarios' with Authorize attribute for use a validation token for access to this api. This token is generated by another api and works well.
When i use Postman for acess to api 'https://localhost:44351/api/usuarios' i need put in the Authorization tab the token previously generated (see https://i.ibb.co/Lg7rD4N/2.png) and this way i get access for the api (see https://i.ibb.co/0BqnPhR/3.png)

But the huge problem is when i try from a JAVASCRIPT CLIENT use method GET using FETCH. I know need to do a object like this for make correct request

let params= {   method: 'GET',
                headers: {"X-Auth-Token": "5f5fe128570248a9bd198add1a5b25e4"}
            };

So my question is how i can implement the attributte  'Temporary-Headers' in the object 'params' like Postman does ( https://i.ibb.co/0BqnPhR/3.png)?

Body:
"Temporary Headers" are just like any other Header, those are just values auto-generated by the web client. I believe your problem relies on how you send your Header if you are using the fetch API modify your parameters like the following.

{
  method: 'GET',
  headers: {
    "Authorization": "Bearer <replace with your token>"
  }
}

This is how postman is sending the request as seen in the screenshots you provide.


问:
Error: Unable to generate deps.json, it may have been already generated. when adding a Service reference to Xamarin forms
I have a Xamarin forms v3.1 project with the .NET standard approach.
I tried to add a reference to a web service I have using
"add connected service" and then from the pop up, I choose Microsoft web service reference provider.

I add the web service link, Visual Studio (2017 v15.8) discovers its structure, and then when I click finish, it takes a while but then shows this error:

Unable to generate deps.json, it may have been already generated.

You can specify the "-d" option before the tool name for diagnostic

output  (for example, "dotnet -d ":  C:\Program

Files\dotnet\sdk\2.1.400\Sdks\Microsoft.NET.Sdk\targets\GenerateDeps\GenerateDeps.proj

Done.

Any idea why this is happening and how to solve this issue?

答: What worked for me was running the "dotnet restore" command in VS 2019.</p>


问:
How to get the control that is clicked?
How can I get the name of control that was clicked in ASP.NET? (e.g., a LinkBottun)</p>

答: Assign an OnClick event to it and handle it server-side.</p>

Title: How to get the control that is clicked?


问:
Why would successful login via a long established B2C tenant start to result in unauthenticated user principals?
We've had an .NET Framework 4.6/Asp.NET MVC app secured for some time with Azure B2C, enabling sign in with social providers and with a workplace Azure AD account. We configured this more than a year ago with custom policies, when the Identity Experience Framework was quite new, and it has worked successfully ever since.

In about mid-January, some users started experiencing an issue. Sign in with B2C would complete correctly (and be logged as a success in the audit trail), but the user identity would remain unauthenticated. This has now spread, with many users affected, signing in with social providers and/or the linked external AD, but with some users not affected at all (suggesting perhaps an issue with new cookies, whereas old unexpired ones are good?).

The issue can be replicated in testing, and a clean browser will fail to log in multiple times, then succeed perhaps once, or twice, before returning to failing. The success rate is perhaps 1/20, and seems higher with VS 2019 in debugging mode, suggesting perhaps some kind of timing issue.

The fact that it does work very occasionally seems to suggest there isn't anything wrong with the configuration. All traces to Application Insights, as well as the B2C audit log, show successful logins, but the user identity in the Asp.NET site remains unauthenticated. We've tried stepping back in Git as far as the middle of last year, and those older builds experience the same issue, although the code has been functioning in production all this time.

One further oddity. When I inspected the Azure B2C tenant to confirm no keys had expired and no other changes had been made (none had), I discovered it was no longer associated with our subscription - a warning message directed me to attach it. We had certainly done this previously, as we could not have used the Identity Experience Framework otherwise. We don't understand how it could have been removed from our subscription - no such action appears in the activity log. Reattaching it, however, has not fixed the issue above.

What could be happening here? Why would a previously solid app begin malfunctioning in mid-January? How can we debug this when all the logs show a successful authentication? How did the tenant remove itself from our subscription?

Happy to post code if it will help, but I would emphasise that a) this was working previously; and b) it still does work intermittently.

Update A long and helpful screen-share with Azure support has confirmed that the B2C login process is working correctly, but something (unknown) is going wrong when redirecting back to the application. The JWT looks good. What could this be?

Further Update Two escalations and further long debugging, and this still isn't fixed. It seems the login completes absolutely correctly, but then the Asp.Net application somehow doesn't trust the result. The JWT looks good, but the user in the app remains unauthenticated (or somehow loses authenticated status at once). Has anyone else hit this kind of issue? What could be going wrong?

答:
With help from the Microsoft Asp.Net support team, we managed to diagnose this as an instance of Katana bug #197 as described here: Application stops generating login cookies

The solution was the well-known app.UseKentorOwinCookieSaver();

https://github.com/KentorIT/owin-cookie-saver

Although we had implemented this fix previously on our Azure AD secured Asp.Net sites, we hadn't needed it previously on a B2C site. We're still not clear why this issue reared its head suddenly on a site that had otherwise been operational and stable for more than a year.


问:
stop all async Task when they fails over threshold?
I'm using Monix Task for async control.

scenario

tasks are executed in parallel

if failure occurs over X times

stop all tasks that are not yet in complete status (as quick as better)

my solution

I come up the ideas that race between 1. result and 2. error counter, and cancel the loser.

Via Task.race if the error-counter get to threshold first, then the tasks would be canceled by Task.race.

experiment

on Ammonite REPL

```<code>{
  import $ivy.`io.monix::monix:3.1.0`
  import monix.eval.Task
  import monix.execution.atomic.Atomic
  import scala.concurrent.duration._
  import monix.execution.Scheduler
  //import monix.execution.Scheduler.Implicits.global
  implicit val s = Scheduler.fixedPool("race", 2) // pool size

  val taskSize = 100
  val errCounter = Atomic(0)
  val threshold = 3

  val tasks = (1 to taskSize).map(_ => Task.sleep(100.millis).map(_ => errCounter.increment()))
  val guard = Task(f"stop because too many error: ${errCounter.get()}")
    .restartUntil(_ => errCounter.get() >= threshold)

  val race = Task
    .race(guard, Task.gather(tasks))
    .runToFuture
    .onComplete { case x => println(x); println(f"completed task: ${errCounter.get()}") }
}
</code>```

issue

The outcome is depends on thread pool size !?

For pool size 1

the outcome is almost always a task success i.e. no stop.

```<code>Success(Right(.........))
completed task: 100 // all task success !
</code>```

For pool size 2

it is very un-deterministic between success and failure and the cancelling is not accurate.
for example:

```<code>Success(Left(stop because too many error: 1))
completed task: 98
</code>```

the canceling is as late as 98 tasks has completed.

the error count is weird small to threshold.

The default global scheduler get this same outcome behavior.

For pool size 200

it is more deterministic and the stopping is earlier thus more accurate in sense that less task was completed.

```<code>Success(Left(stop because too many error: 2))
completed task: 8
</code>```

the larger of the pool size the better.

If I change Task.gather to Task.sequence execution, all issues disappeared!

What is the cause for this dependency on pool size ?
How to improve it or is there better alternative for stopping tasks once too many error occurs ?

答:
What you're seeing is likely an effect of the monix scheduler and how it aims for fairness. It's a fairly complex topic but the documentation and scaladocs are excellent (see: https://monix.io/docs/3x/execution/scheduler.html#execution-model)

When you have only one thread (or few) it takes a while until the "guard" Task gets another turn to check. With Task.gather you start 100 tasks at once, so the scheduler is very busy and the "guard" cannot check again until the other tasks are already done.
If you have one thread per task the scheduler cannot guarantee fairness and therefore the "guard" unfairly checks much more frequently and can finish sooner.

If you use Task.sequence those 100 tasks are executed sequentially, which is why the "guard" task gets much more opportunities to finish as soon as needed. If you want to keep your code the way it is, you could use Task.gatherN(parallelism = 4) which will limit the parallelism and therefore allow your "guard" to check more often (a middleground between Task.sequence and Task.gather).

It seems a bit like Go code to me (using Task.race like Go's select) and you're also using side-effects unconstrained which further complicates understanding what's going on. I've tried to rewrite your program in a way that's more idiomatic and for complicated concurrency I usually reach for streams like Observable:

import cats.effect.concurrent.Ref
import monix.eval.Task
import monix.execution.Scheduler
import monix.reactive.Observable

import scala.concurrent.duration._

object ErrorThresholdDemo extends App {

  //import monix.execution.Scheduler.Implicits.global
  implicit val s: Scheduler = Scheduler.fixedPool("race", 2) // pool size

  val taskSize  = 100
  val threshold = 30

  val program = for {
    errCounter <- Ref[Task].of(0)

    tasks = (1 to taskSize).map(n => Task.sleep(100.millis).flatMap(_ => errCounter.update(_ + (n % 2))))

    tasksFinishedCount <- Observable
      .fromIterable(tasks)
      .mapParallelUnordered(parallelism = 4) { task =>
        task
      }
      .takeUntilEval(errCounter.get.restartUntil(_ >= threshold))
      .map(_ => 1)
      .sumL

    errorCount <- errCounter.get
    _          <- Task(println(f"completed tasks: $tasksFinishedCount, errors: $errorCount"))
  } yield ()

  program.runSyncUnsafe()
}
```

As you can see I no longer use global mutable side-effects but instead Ref which interally also uses Atomic but provides a functional api which we can use with Task.
For demonstration purposes I also changed the threshold to 30 and only every other task will "error". So the expected output is always around completed tasks: 60, errors: 30 no matter the thread-pool size.

I'm still using polling with errCounter.get.restartUntil(_ >= threshold) which might burn a bit too much CPU for my taste but it's close to your original idea and works well.

Usually I don't create a list of tasks up front but instead throw the inputs into the Observable and create the tasks inside of .mapParallelUnordered. This code keeps your list which is why there is no real mapping involved (it already contains tasks).

You can choose your desired parallelism much like with Task.gatherN which is pretty nice imo.

Let me know if anything is still unclear :)

Body:
I'm using Monix Task for async control.

scenario

tasks are executed in parallel

if failure occurs over X times

stop all tasks that are not yet in complete status (as quick as better)

my solution

I come up the ideas that race between 1. result and 2. error counter, and cancel the loser.

Via Task.race if the error-counter get to threshold first, then the tasks would be canceled by Task.race.

experiment

on Ammonite REPL

{
  import $ivy.`io.monix::monix:3.1.0`
  import monix.eval.Task
  import monix.execution.atomic.Atomic
  import scala.concurrent.duration._
  import monix.execution.Scheduler
  //import monix.execution.Scheduler.Implicits.global
  implicit val s = Scheduler.fixedPool("race", 2) // pool size

  val taskSize = 100
  val errCounter = Atomic(0)
  val threshold = 3

  val tasks = (1 to taskSize).map(_ => Task.sleep(100.millis).map(_ => errCounter.increment()))
  val guard = Task(f"stop because too many error: ${errCounter.get()}")
    .restartUntil(_ => errCounter.get() >= threshold)

  val race = Task
    .race(guard, Task.gather(tasks))
    .runToFuture
    .onComplete { case x => println(x); println(f"completed task: ${errCounter.get()}") }
}

issue

The outcome is depends on thread pool size !?

For pool size 1

the outcome is almost always a task success i.e. no stop.

Success(Right(.........))
completed task: 100 // all task success !

For pool size 2

it is very un-deterministic between success and failure and the cancelling is not accurate.
for example:

Success(Left(stop because too many error: 1))
completed task: 98

the canceling is as late as 98 tasks has completed.

the error count is weird small to threshold.

The default global scheduler get this same outcome behavior.

For pool size 200

it is more deterministic and the stopping is earlier thus more accurate in sense that less task was completed.

Success(Left(stop because too many error: 2))
completed task: 8

the larger of the pool size the better.

If I change Task.gather to Task.sequence execution, all issues disappeared!

What is the cause for this dependency on pool size ?
How to improve it or is there better alternative for stopping tasks once too many error occurs ?

Body:
What you're seeing is likely an effect of the monix scheduler and how it aims for fairness. It's a fairly complex topic but the documentation and scaladocs are excellent (see: https://monix.io/docs/3x/execution/scheduler.html#execution-model)

When you have only one thread (or few) it takes a while until the "guard" Task gets another turn to check. With Task.gather you start 100 tasks at once, so the scheduler is very busy and the "guard" cannot check again until the other tasks are already done.
If you have one thread per task the scheduler cannot guarantee fairness and therefore the "guard" unfairly checks much more frequently and can finish sooner.

If you use Task.sequence those 100 tasks are executed sequentially, which is why the "guard" task gets much more opportunities to finish as soon as needed. If you want to keep your code the way it is, you could use Task.gatherN(parallelism = 4) which will limit the parallelism and therefore allow your "guard" to check more often (a middleground between Task.sequence and Task.gather).

It seems a bit like Go code to me (using Task.race like Go's select) and you're also using side-effects unconstrained which further complicates understanding what's going on. I've tried to rewrite your program in a way that's more idiomatic and for complicated concurrency I usually reach for streams like Observable:

import cats.effect.concurrent.Ref
import monix.eval.Task
import monix.execution.Scheduler
import monix.reactive.Observable

import scala.concurrent.duration._

object ErrorThresholdDemo extends App {

  //import monix.execution.Scheduler.Implicits.global
  implicit val s: Scheduler = Scheduler.fixedPool("race", 2) // pool size

  val taskSize  = 100
  val threshold = 30

  val program = for {
    errCounter <- Ref[Task].of(0)

    tasks = (1 to taskSize).map(n => Task.sleep(100.millis).flatMap(_ => errCounter.update(_ + (n % 2))))

    tasksFinishedCount <- Observable
      .fromIterable(tasks)
      .mapParallelUnordered(parallelism = 4) { task =>
        task
      }
      .takeUntilEval(errCounter.get.restartUntil(_ >= threshold))
      .map(_ => 1)
      .sumL

    errorCount <- errCounter.get
    _          <- Task(println(f"completed tasks: $tasksFinishedCount, errors: $errorCount"))
  } yield ()

  program.runSyncUnsafe()
}

As you can see I no longer use global mutable side-effects but instead Ref which interally also uses Atomic but provides a functional api which we can use with Task.
For demonstration purposes I also changed the threshold to 30 and only every other task will "error". So the expected output is always around completed tasks: 60, errors: 30 no matter the thread-pool size.

I'm still using polling with errCounter.get.restartUntil(_ >= threshold) which might burn a bit too much CPU for my taste but it's close to your original idea and works well.

Usually I don't create a list of tasks up front but instead throw the inputs into the Observable and create the tasks inside of .mapParallelUnordered. This code keeps your list which is why there is no real mapping involved (it already contains tasks).

You can choose your desired parallelism much like with Task.gatherN which is pretty nice imo.

Let me know if anything is still unclear :)


问:
optimization in gpflow 2: Why set autograph=False?
in the current notebook tutorials (gpflow 2.0), all @tf.function tags include the option
autograph=False, e.g. (https://gpflow.readthedocs.io/en/2.0.0-rc1/notebooks/advanced/gps_for_big_data.html):

```<code>@tf.function(autograph=False)
def optimization_step(optimizer, model: gpflow.models.SVGP, batch):
    with tf.GradientTape(watch_accessed_variables=False) as tape:
        tape.watch(model.trainable_variables)
        objective = - model.elbo(*batch)
        grads = tape.gradient(objective, model.trainable_variables)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))
    return objective
</code>```

Does anyone know why that is the case, or what the reasoning behind this is?
As far as I understood, autograph=True simply allows for python control flow to be translated to a graph structure. Does setting/leaving it to true, even if the functionality is not required, have any drawbacks?

My guess would have been that its just a small overhead at compile time of the graph, but should be negligible. Is that wrong?

Thanks

答:
The reason we set autograph to False in most of the tf.function wrapped objectives is because GPflow makes use a multi-dispatch Dispatcher which internally uses generators. TensorFlow, however, can not deal with generator objects in autograph mode (see Capabilities and Limitations of AutoGraph), which leads to these warning:

WARNING:tensorflow:Entity <bound method Dispatcher.dispatch_iter of <dispatched sample_conditional>> appears to be a generator function. It will not be converted by AutoGraph.
WARNING: Entity <bound method Dispatcher.dispatch_iter of <dispatched sample_conditional>> appears to be a generator function. It will not be converted by AutoGraph.
WARNING:tensorflow:Entity <bound method Dispatcher.dispatch_iter of <dispatched conditional>> appears to be a generator function. It will not be converted by AutoGraph.
WARNING: Entity <bound method Dispatcher.dispatch_iter of <dispatched conditional>> appears to be a generator function. It will not be converted by AutoGraph.
```

We've know about this issue for a while but haven't got around to actually fixing it - thanks for bringing this back to our attention. I've just created a PR which fixes this issue and does not require you to set autograph to False anymore. I expect this PR to be merged fairly soon.

Body:
in the current notebook tutorials (gpflow 2.0), all @tf.function tags include the option
autograph=False, e.g. (https://gpflow.readthedocs.io/en/2.0.0-rc1/notebooks/advanced/gps_for_big_data.html):

@tf.function(autograph=False)
def optimization_step(optimizer, model: gpflow.models.SVGP, batch):
    with tf.GradientTape(watch_accessed_variables=False) as tape:
        tape.watch(model.trainable_variables)
        objective = - model.elbo(*batch)
        grads = tape.gradient(objective, model.trainable_variables)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))
    return objective

Does anyone know why that is the case, or what the reasoning behind this is?
As far as I understood, autograph=True simply allows for python control flow to be translated to a graph structure. Does setting/leaving it to true, even if the functionality is not required, have any drawbacks?

My guess would have been that its just a small overhead at compile time of the graph, but should be negligible. Is that wrong?

Thanks

Body:
The reason we set autograph to False in most of the tf.function wrapped objectives is because GPflow makes use a multi-dispatch Dispatcher which internally uses generators. TensorFlow, however, can not deal with generator objects in autograph mode (see Capabilities and Limitations of AutoGraph), which leads to these warning:

WARNING:tensorflow:Entity <bound method Dispatcher.dispatch_iter of <dispatched sample_conditional>> appears to be a generator function. It will not be converted by AutoGraph.
WARNING: Entity <bound method Dispatcher.dispatch_iter of <dispatched sample_conditional>> appears to be a generator function. It will not be converted by AutoGraph.
WARNING:tensorflow:Entity <bound method Dispatcher.dispatch_iter of <dispatched conditional>> appears to be a generator function. It will not be converted by AutoGraph.
WARNING: Entity <bound method Dispatcher.dispatch_iter of <dispatched conditional>> appears to be a generator function. It will not be converted by AutoGraph.

We've know about this issue for a while but haven't got around to actually fixing it - thanks for bringing this back to our attention. I've just created a PR which fixes this issue and does not require you to set autograph to False anymore. I expect this PR to be merged fairly soon.


问:
Need to Mirror Video Orientation and Handle Rotation When Using Front Camera
I can't quite figure out how to handle front facing camera video capture orientations. I have all rotations handled for the back camera when capturing video and pictures and all rotations handled for the front camera when taking pictures, as well as saving the captured videos and pictures with the correct orientations as well, except for the front camera video capture.

The first problem is when in either landscape mode, the video is not saved correctly with the correct orientation. The second problem is that the saved video is mirrored. Although i know how to handle this mirroring effect for picture using the front camera, I am not sure what to call to handle it for videos.

I had a lot of trouble trying to find anything specifically for this one issue and failed to do so. If anybody could point me to a thread that addresses this specific issue, that would be great.

Either way, here is the method that is called that handles video orientation when device orientation changes. I am not sure exactly what to add to my code if the front camera is being used.

```<code>/**************************************************************************
    DEVICE ORIENTATION DID CHANGE
    **************************************************************************/
    func deviceOrientationDidChange() {

        println("DEVICE ORIENTATION DID CHANGE CALLED")

        let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation

        //------ IGNORE THESE ORIENTATIONS ------
        if orientation == UIDeviceOrientation.FaceUp || orientation == UIDeviceOrientation.FaceDown || orientation == UIDeviceOrientation.Unknown || orientation == UIDeviceOrientation.PortraitUpsideDown || self.currentOrientation == orientation {

            println("device orientation does not need to change --- returning...")

            return
        }

        self.currentOrientation = orientation

        //------ APPLY A ROTATION USING THE STANDARD ROTATION TRANSFORMATION MATRIX in R3 ------

        /*

            x       y       z
            ---           ---
        x | cosø    sinø    0 |
        y | -sinø   consø   0 |
        z | 0       0       1 |
            ---           ---

        */

        //----- PERFORM BUTTON AND VIDEO DATA BUFFER ROTATIONS ------
        switch orientation {

        case UIDeviceOrientation.Portrait:

            rotateButtons(self.degrees0)

            if self.usingFrontCamera == true {

            }
            else {

            }

            println("Device Orientation Portrait")

            break

        case UIDeviceOrientation.LandscapeLeft:

            println("Device Orientation LandScapeLeft")

            rotateButtons(self.degrees90)

            if self.usingFrontCamera == true {

                println("Using front camera, rotation in landscape left")

//                if let connection = self.captureConnection {
//
//                    connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
//
//                    println("Capture connection Orientation is LandScape Right")
//                }
//                else {
//
//                    println("Capture connection is nil, could not change video orientation")
//                }
            }
            else {

                if let connection = self.captureConnection {

                    connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight

                    println("Capture connection Orientation is LandScape Right")
                }
                else {

                    println("Capture connection is nil, could not change video orientation")
                }
            }

            break

        case UIDeviceOrientation.LandscapeRight:

            println("Device Orientation LandscapeRight")

            rotateButtons(-self.degrees90)

            if self.usingFrontCamera == true {

                println("Using front camera, rotation in landscape right")

//                if let connection = self.captureConnection {
//
//                    connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
//
//                    println("Capture connection Orientation is LandScape Left")
//                }
//                else {
//
//                    println("Capture connection is nil, could not change video orientation")
//                }
            }
            else {

                if let connection = self.captureConnection {

                    connection.videoOrientation = AVCaptureVideoOrientation.LandscapeLeft

                    println("Capture connection Orientation is LandScape Left")
                }
                else {

                    println("Capture connection is nil, could not change video orientation")
                }
            }

            break

        default:

            break
        }
    }
</code>```

答:
Kesong's comment in Sam's answer works for transforming the video itself and not just the preview.  Make sure to check if videoMirroring is supported first and make sure to disable automatically adjusting video mirroring before setting the isVideoMirrored property or the app can crash.

The below code works for Swift 5.  You can use this code after attaching your AVCaptureSession to your AVCaptureMovieFileOutput.

```<code>  if let videoConnection = movieFileOutput.connection(with: .video) {
        if  videoConnection.isVideoMirroringSupported {
            if frontCamera { //For selfie camera, flip the output video so it doesn't appear mirrored
              videoConnection.automaticallyAdjustsVideoMirroring = false
              videoConnection.isVideoMirrored = true
            } else {
              videoConnection.automaticallyAdjustsVideoMirroring = true
            }
        }
    }
</code>```

Body:
I can't quite figure out how to handle front facing camera video capture orientations. I have all rotations handled for the back camera when capturing video and pictures and all rotations handled for the front camera when taking pictures, as well as saving the captured videos and pictures with the correct orientations as well, except for the front camera video capture.

The first problem is when in either landscape mode, the video is not saved correctly with the correct orientation. The second problem is that the saved video is mirrored. Although i know how to handle this mirroring effect for picture using the front camera, I am not sure what to call to handle it for videos.

I had a lot of trouble trying to find anything specifically for this one issue and failed to do so. If anybody could point me to a thread that addresses this specific issue, that would be great.

Either way, here is the method that is called that handles video orientation when device orientation changes. I am not sure exactly what to add to my code if the front camera is being used.

/**************************************************************************
    DEVICE ORIENTATION DID CHANGE
    **************************************************************************/
    func deviceOrientationDidChange() {

        println("DEVICE ORIENTATION DID CHANGE CALLED")

        let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation

        //------ IGNORE THESE ORIENTATIONS ------
        if orientation == UIDeviceOrientation.FaceUp || orientation == UIDeviceOrientation.FaceDown || orientation == UIDeviceOrientation.Unknown || orientation == UIDeviceOrientation.PortraitUpsideDown || self.currentOrientation == orientation {

            println("device orientation does not need to change --- returning...")

            return
        }

        self.currentOrientation = orientation

        //------ APPLY A ROTATION USING THE STANDARD ROTATION TRANSFORMATION MATRIX in R3 ------

        /*

            x       y       z
            ---           ---
        x | cosø    sinø    0 |
        y | -sinø   consø   0 |
        z | 0       0       1 |
            ---           ---

        */

        //----- PERFORM BUTTON AND VIDEO DATA BUFFER ROTATIONS ------
        switch orientation {

        case UIDeviceOrientation.Portrait:

            rotateButtons(self.degrees0)

            if self.usingFrontCamera == true {

            }
            else {

            }

            println("Device Orientation Portrait")

            break

        case UIDeviceOrientation.LandscapeLeft:

            println("Device Orientation LandScapeLeft")

            rotateButtons(self.degrees90)

            if self.usingFrontCamera == true {

                println("Using front camera, rotation in landscape left")

//                if let connection = self.captureConnection {
//
//                    connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
//
//                    println("Capture connection Orientation is LandScape Right")
//                }
//                else {
//
//                    println("Capture connection is nil, could not change video orientation")
//                }
            }
            else {

                if let connection = self.captureConnection {

                    connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight

                    println("Capture connection Orientation is LandScape Right")
                }
                else {

                    println("Capture connection is nil, could not change video orientation")
                }
            }

            break

        case UIDeviceOrientation.LandscapeRight:

            println("Device Orientation LandscapeRight")

            rotateButtons(-self.degrees90)

            if self.usingFrontCamera == true {

                println("Using front camera, rotation in landscape right")

//                if let connection = self.captureConnection {
//
//                    connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
//
//                    println("Capture connection Orientation is LandScape Left")
//                }
//                else {
//
//                    println("Capture connection is nil, could not change video orientation")
//                }
            }
            else {

                if let connection = self.captureConnection {

                    connection.videoOrientation = AVCaptureVideoOrientation.LandscapeLeft

                    println("Capture connection Orientation is LandScape Left")
                }
                else {

                    println("Capture connection is nil, could not change video orientation")
                }
            }

            break

        default:

            break
        }
    }

Body:
Kesong's comment in Sam's answer works for transforming the video itself and not just the preview.  Make sure to check if videoMirroring is supported first and make sure to disable automatically adjusting video mirroring before setting the isVideoMirrored property or the app can crash.

The below code works for Swift 5.  You can use this code after attaching your AVCaptureSession to your AVCaptureMovieFileOutput.

  if let videoConnection = movieFileOutput.connection(with: .video) {
        if  videoConnection.isVideoMirroringSupported {
            if frontCamera { //For selfie camera, flip the output video so it doesn't appear mirrored
              videoConnection.automaticallyAdjustsVideoMirroring = false
              videoConnection.isVideoMirrored = true
            } else {
              videoConnection.automaticallyAdjustsVideoMirroring = true
            }
        }
    }


问:
Need resources and suggestions on how Payments work (authorization settlement clearing) from a cryptographic perspective
I am trying to understand how transactions, credit cards (magstripes, chips, ..), e-commerce,.. work from a cryptographic perspective.
What kind of algorithms are used, how to ensure Confidentiality, Integrity, authentication, ...
Thank you in advance </p>

答:
That's a mighty big subject, much too large to adequately handle here.

However, Bruce Schneier is one of the world's foremost authorities on security and he has over the years written quite a number of very approachable books.  Here's a link to a list of all his current books:

https://www.goodreads.com/author/list/175417.Bruce_Schneier

In addition, the payment processing industries have a requirement called "PCI Compliance" which all participants must comply with.  Their web-site has materials that are introductory, as well:

https://www.pcicomplianceguide.org/

Hope this helps!

As you're approaching your understanding of this subject, bear in mind that the requirement is not simply that "the data in transit must not be understood," but that the parties must know (a) who it is that they are talking to, and (b) that each message is received "exactly as tendered," and with no messages inserted nor left out.  And, the total requirement quickly goes well beyond cryptography, to the underlying protocols that are employed across these cryptographically-secure connections.  Quite a big subject.


问:
Fastest way to calculate the last working page for scraping
I'm trying to scrape a website and I don't want to be forced to recursively scrape every page until the "end".

I want to be able to just get the last page, or any page in between.

This isn't an issue most of the time, but this webpage is different. For example:

I do a search query on: "Logitech"

The website returns the following information I want to use:

Total amount of products found: 15.000

Products per page: 30

Pagination: 1, 2, 3, 4, ...500 (15.000/30 = 500)

However it seems like the Total amount of products found is false information, and so is the pagination, because when I try to access https://website.com/products?q=Logitech&page=500 there are no products. This also applies on lower values like: 499, 498, 450, 400, 350, etc.

So I tried "calculating" possible page numbers in my head, and I came down to the actual last page number: 166

I "calculated" this by checking if there were results:

If there were results: increment value by amount x

If there were no results: decrement value by amount x

So I made a test script to sort of replicate my method of finding the page number (repl.it link):
https://repl.it/@SaltyPotato1/LastPageCalculator

But I have two problems with his script (and I hope you guys can help me out):

This script "knows" the right value (166), so it can use > and < operators, when I'm scraping; It can only check if there is a result in this case: products. This means that there are only 2 options:

If there is a result it will mean that: the page number is either too low or it's in fact the last page number.

If there is no result it will mean that: the page number is too high.

I have a feeling the script/calculating could be improved, since some values are emitted twice.

What can I do to determine if it is in fact the last page number instead of a page number "under" the actual last page. And how could I minimize the amount of requests that are going to be made to calculate this.

I'm looking forward to your answers/help!

答:
In general, you are not supposed to know all the page numbers for all kind of products. What you need is use the binary search algorithm to find the correct max page count. For which I suggest using HTTP Head request just to check whether that route exists, if the server doesn't support that method, you may try to do get request and just check the response's http status code, this way you don't need to do complex computation / dom query just for finding out correct max page count.

There will be slight change to your code.

```<code>function findMaxPageCount(totalProductCount = 1000, productPerPage = 1){
  const lo = 1;
  const hi = totalProductCount/productPage;
  let mid;
  let actualMaxPage = -1;
  while(lo <= hi){
    mid = Math.floor((lo + hi)/2.0);

    if(pageExists(mid)){
      actualMaxPage = mid;
      lo = mid + 1;
    }else{
      hi = mid - 1;
    }
  }

  return actualMaxPage;
}
</code>```

The above method, will not search same page again, so read count is minimal and at most Math.ceil(log2(totalProductCount/productPage)).

Body:
In general, you are not supposed to know all the page numbers for all kind of products. What you need is use the binary search algorithm to find the correct max page count. For which I suggest using HTTP Head request just to check whether that route exists, if the server doesn't support that method, you may try to do get request and just check the response's http status code, this way you don't need to do complex computation / dom query just for finding out correct max page count.

There will be slight change to your code.

function findMaxPageCount(totalProductCount = 1000, productPerPage = 1){
  const lo = 1;
  const hi = totalProductCount/productPage;
  let mid;
  let actualMaxPage = -1;
  while(lo <= hi){
    mid = Math.floor((lo + hi)/2.0);

    if(pageExists(mid)){
      actualMaxPage = mid;
      lo = mid + 1;
    }else{
      hi = mid - 1;
    }
  }

  return actualMaxPage;
}

The above method, will not search same page again, so read count is minimal and at most Math.ceil(log2(totalProductCount/productPage)).


问:
How can I mock a container-provided object (e.g HttpSession) when Unit testing a GWT app?
I am currently trying to unit test my Service layer (all *Impl.java classes) in a GWT app. Well the problem is that in the code, I have a dependency which targets an object provided by the Httpsession. Actually, I'm storing a User object (the currently logged in user) in the httpSession.

In order to get it back from the HttpSession (in the *Impl.java class), I am using this :

User user = ServiceUtil.getUser(getThreadLocalRequest().getSession());

How can I mock this object from my Unit test code ?

thanks a lot,

答:
I recommend you change the structure of your application so that the service layer doesn't depend on such things as a session (context agnostic) but instead the methods which need a user object of some kind get it injected (via parameter or however). So actually you include a very thin presentation layer (or however you may call it) which handles things such as responding to HTTP requests, logging a user in and putting the user object in the session and just calls service layer methods.

That way you can mock your user object in the unit test, pass it to your service layer and don't need any mock framework.


问:
Display XML Schema in SQL Query Result
I'm brand new to SQL and SQL Server Management Studio, so bear with me. Here's a shortened version of my query:

```<code>SELECT *
FROM [dbo].[BranchLocations] WHERE NOT (PropertyOwnerType IS NULL)
FOR XML PATH('LocationData'), ROOT('MainRoot')
</code>```

This gives me exactly what I need except for the schema. I don't want to automatically generate a schema because the service to which I upload the XML data only accepts a specific schema structure, and I would prefer to control it.

My schema looks similar to this:

```<code><xs:schema id="LocationData_ds" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="LocationData_ds" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
        <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element name="LocationData">
            <xs:complexType>
                <xs:sequence>
                <xs:element name="EntityID" type="xs:string" />
                <xs:element name="AddressLine" type="xs:string" minOccurs="0" />
                <xs:element name="Locality" type="xs:string" minOccurs="0" />
                <xs:element name="AdminDistrict" type="xs:string" minOccurs="0" />
                <xs:element name="PostalCode" type="xs:string" minOccurs="0" />
                <xs:element name="CountryRegion" type="xs:string" minOccurs="0" />
                <xs:element name="Latitude" type="xs:double" minOccurs="0" />
                <xs:element name="Longitude" type="xs:double" minOccurs="0" />
                </xs:sequence>
            </xs:complexType>
            </xs:element>
        </xs:choice>
        </xs:complexType>
        <xs:unique name="Constraint1" msdata:PrimaryKey="true">
        <xs:selector xpath=".//LocationData" />
        <xs:field xpath="EntityID" />
        </xs:unique>
    </xs:element>
</xs:schema>
</code>```

My query returns this:

```<code><MainRoot>
  <LocationData>
    <EntityID>10010000</EntityID>
    <AddressLine>1234 address<\/AddressLine>
    <Locality>Converse</Locality>
    <AdminDistrict>TX</AdminDistrict>
    <PostalCode>12345</PostalCode>
    <CountryRegion>US</CountryRegion>
  </LocationData>
  <LocationData>
    <EntityID>70390000</EntityID>
    <AddressLine>1234 address<\/AddressLine>
    <Locality>Denver</Locality>
    <AdminDistrict>CO</AdminDistrict>
    <PostalCode>12345</PostalCode>
    <CountryRegion>US</CountryRegion>
  </LocationData>
...
<MainRoot>
</code>```

And what I need is this:

(and I need ti include<?xml version="1.0" encoding="utf-8" standalone="yes"?> at the top as well)

```<code><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<MainRoot>
    <xs:schema id="LocationData_ds" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
        <xs:element name="LocationData_ds" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
            <xs:complexType>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:element name="LocationData">
                <xs:complexType>
                    <xs:sequence>
                    <xs:element name="EntityID" type="xs:string" />
                    <xs:element name="AddressLine" type="xs:string" minOccurs="0" />
                    <xs:element name="Locality" type="xs:string" minOccurs="0" />
                    <xs:element name="AdminDistrict" type="xs:string" minOccurs="0" />
                    <xs:element name="PostalCode" type="xs:string" minOccurs="0" />
                    <xs:element name="CountryRegion" type="xs:string" minOccurs="0" />
                    <xs:element name="Latitude" type="xs:double" minOccurs="0" />
                    <xs:element name="Longitude" type="xs:double" minOccurs="0" />
                    </xs:sequence>
                </xs:complexType>
                </xs:element>
            </xs:choice>
            </xs:complexType>
            <xs:unique name="Constraint1" msdata:PrimaryKey="true">
            <xs:selector xpath=".//LocationData" />
            <xs:field xpath="EntityID" />
            </xs:unique>
        </xs:element>
    </xs:schema>
<LocationData>
    <EntityID>10010000</EntityID>
    <AddressLine>1234 address<\/AddressLine>
    <Locality>Converse</Locality>
    <AdminDistrict>TX</AdminDistrict>
    <PostalCode>12345</PostalCode>
    <CountryRegion>US</CountryRegion>
  </LocationData>
  <LocationData>
    <EntityID>70390000</EntityID>
    <AddressLine>1234 address<\/AddressLine>
    <Locality>Denver</Locality>
    <AdminDistrict>CO</AdminDistrict>
    <PostalCode>12345</PostalCode>
    <CountryRegion>US</CountryRegion>
  </LocationData>
...
<MainRoot>
</code>```

Looking through the documentation has led me here:

https://learn.microsoft.com/en-us/sql/t-sql/xml/insert-xml-dml?view=sql-server-ver15

It isn't working, but I think I might be on the right track.

These answers only relate to generating a schema:

convert database table into XML schema file
how to create XML schema from an existing database in SQL Server 2008

答:
What you are looking for is called an Inline XSD Schema.
Here is BOL link: Generate an Inline XSD Schema

Unfortunately, it is very limited: "...You can specify XMLSCHEMA only in RAW and AUTO mode, not in EXPLICIT mode...". Same with the PATH mode.

Additional limitation is that SQL Server keeps XML as UTF-16, and strips an XML prolog from any XML data type internally.

To achieve what you need everything needs to be done manually, i.e. stitch together a prolog, XML Schema, and actual XML.

Title: Display XML Schema in SQL Query Result

Body:
I'm brand new to SQL and SQL Server Management Studio, so bear with me. Here's a shortened version of my query:

SELECT *
FROM [dbo].[BranchLocations] WHERE NOT (PropertyOwnerType IS NULL)
FOR XML PATH('LocationData'), ROOT('MainRoot')

This gives me exactly what I need except for the schema. I don't want to automatically generate a schema because the service to which I upload the XML data only accepts a specific schema structure, and I would prefer to control it.

My schema looks similar to this:

<xs:schema id="LocationData_ds" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="LocationData_ds" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
        <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element name="LocationData">
            <xs:complexType>
                <xs:sequence>
                <xs:element name="EntityID" type="xs:string" />
                <xs:element name="AddressLine" type="xs:string" minOccurs="0" />
                <xs:element name="Locality" type="xs:string" minOccurs="0" />
                <xs:element name="AdminDistrict" type="xs:string" minOccurs="0" />
                <xs:element name="PostalCode" type="xs:string" minOccurs="0" />
                <xs:element name="CountryRegion" type="xs:string" minOccurs="0" />
                <xs:element name="Latitude" type="xs:double" minOccurs="0" />
                <xs:element name="Longitude" type="xs:double" minOccurs="0" />
                </xs:sequence>
            </xs:complexType>
            </xs:element>
        </xs:choice>
        </xs:complexType>
        <xs:unique name="Constraint1" msdata:PrimaryKey="true">
        <xs:selector xpath=".//LocationData" />
        <xs:field xpath="EntityID" />
        </xs:unique>
    </xs:element>
</xs:schema>

My query returns this:

<MainRoot>
  <LocationData>
    <EntityID>10010000</EntityID>
    <AddressLine>1234 address<\/AddressLine>
    <Locality>Converse</Locality>
    <AdminDistrict>TX</AdminDistrict>
    <PostalCode>12345</PostalCode>
    <CountryRegion>US</CountryRegion>
  </LocationData>
  <LocationData>
    <EntityID>70390000</EntityID>
    <AddressLine>1234 address<\/AddressLine>
    <Locality>Denver</Locality>
    <AdminDistrict>CO</AdminDistrict>
    <PostalCode>12345</PostalCode>
    <CountryRegion>US</CountryRegion>
  </LocationData>
...
<MainRoot>

And what I need is this:

(and I need ti include<?xml version="1.0" encoding="utf-8" standalone="yes"?> at the top as well)

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<MainRoot>
    <xs:schema id="LocationData_ds" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
        <xs:element name="LocationData_ds" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
            <xs:complexType>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:element name="LocationData">
                <xs:complexType>
                    <xs:sequence>
                    <xs:element name="EntityID" type="xs:string" />
                    <xs:element name="AddressLine" type="xs:string" minOccurs="0" />
                    <xs:element name="Locality" type="xs:string" minOccurs="0" />
                    <xs:element name="AdminDistrict" type="xs:string" minOccurs="0" />
                    <xs:element name="PostalCode" type="xs:string" minOccurs="0" />
                    <xs:element name="CountryRegion" type="xs:string" minOccurs="0" />
                    <xs:element name="Latitude" type="xs:double" minOccurs="0" />
                    <xs:element name="Longitude" type="xs:double" minOccurs="0" />
                    </xs:sequence>
                </xs:complexType>
                </xs:element>
            </xs:choice>
            </xs:complexType>
            <xs:unique name="Constraint1" msdata:PrimaryKey="true">
            <xs:selector xpath=".//LocationData" />
            <xs:field xpath="EntityID" />
            </xs:unique>
        </xs:element>
    </xs:schema>
<LocationData>
    <EntityID>10010000</EntityID>
    <AddressLine>1234 address<\/AddressLine>
    <Locality>Converse</Locality>
    <AdminDistrict>TX</AdminDistrict>
    <PostalCode>12345</PostalCode>
    <CountryRegion>US</CountryRegion>
  </LocationData>
  <LocationData>
    <EntityID>70390000</EntityID>
    <AddressLine>1234 address<\/AddressLine>
    <Locality>Denver</Locality>
    <AdminDistrict>CO</AdminDistrict>
    <PostalCode>12345</PostalCode>
    <CountryRegion>US</CountryRegion>
  </LocationData>
...
<MainRoot>

Looking through the documentation has led me here:

https://learn.microsoft.com/en-us/sql/t-sql/xml/insert-xml-dml?view=sql-server-ver15

It isn't working, but I think I might be on the right track.

These answers only relate to generating a schema:

convert database table into XML schema file
how to create XML schema from an existing database in SQL Server 2008


问:
FFMPEG - Stream to RTMP output and save to MP4 at same time - with reconnect
I'm trying to setup a pipeline where I can take an input and save to MP4 whilst at the same time streaming to an RTMP server.

So far I've been able to use a tee filter to achieve this and also using the onfail=ignore to make sure the pipeline stays up in the event of the RTMP/Recording failing.

Which is great!

However, I don't want the RTMP to just give up if it were to drop or be disconnected, I'd like it to keep attempting to reconnect and resume the stream.

I don't think FFMPEG has something like this, so I'd need to write it in a bash script or something that keeps restarting the process in the event of a drop.

I just have no idea how to achieve this!

Has anybody got any ideas or tackled this before?

Thanks,

Matt

答:
Use fifo format, which can reconnect.

My working example:

```<code>-f fifo -fifo_format flv \
-drop_pkts_on_overflow 1 -attempt_recovery 1 -recover_any_error 1 \
rtmp://bla.bla/bla
</code>```

Body:
Use fifo format, which can reconnect.

My working example:

-f fifo -fifo_format flv \
-drop_pkts_on_overflow 1 -attempt_recovery 1 -recover_any_error 1 \
rtmp://bla.bla/bla