问:
Ordering bars AND stacks in a horizontal ggplot bar chart
Similar questions have been asked before but this question relates to the case when I wish to order the bars and the stacks in a ggplot bar chart simultaneously.

Here is my data:

```<code>data = data.frame(gender = c("Female", "Female", "Female", "Male", "Male", "Male"),
                  BMI = c("Healthy", "Obese", "Overweight", "Healthy", "Obese", "Overweight"),
                  Value = c(10,20,30,25,35,45),
                  Colour = c("#009698", "#ed1651", "#f26522", "#009698", "#ed1651", "#f26522"))
</code>```

The colour column corresponds to the BMI column.

I would like to plot a horizontal bar chart with the "Female" bar at the top and the "Male" bar underneath.  Further I would like the stacks of the bar to be in the following order: Healthy, Overweight, Obese, with healthy to the left then overweight, then obese.  And further still I would like each stack to have a specific colour as defined in the Colour column of the data frame.  Ideally I would like to have the legend in the following order: Healthy, Overweight, Obese.

So far I have managed to order the gender as I want it and order the stacks within each bar but I do not like the approach.  I'm in danger of mis-labelling the graphic.  I am ordering using factors.  Is there a better way?

```<code>x = c("Male", "Female")
data$gender = factor(data$gender,levels=x)
# Order the bmi categories so we have them in a specific order
x = c("Obese", "Overweight", "Healthy")
data$BMI = factor(data$BMI, levels=x)

p=ggplot(data=data, aes(x=gender, y=proportion, fill=data$BMI)) +
  geom_bar(position="stack", stat="identity") +
  scale_y_continuous(labels = scales::percent, limits=c(0,1)) +
  geom_text(aes(label = count), size=2, angle=0, position=position_stack(vjust=0.1)) +
  coord_flip() +
  xlab("") + ylab("") +
  theme(legend.title = element_blank(), legend.position="bottom")
</code>```

This code gives this except the labels are different to those I supplied in the data frame above.

I am finding it very easy to mis-plot (numbers not corresponding to what is plotted) this graph and I need to get it right.

Could anyone help?  Thank you
Phil,

答:
TL;DR

Use position_fill() in place of position_stack(), remove the limits= argument from scale_y_continuous(), and use reverse=TRUE to reverse the ordering of stacking in the bars so that it matches the order you see in the legend.

The Details

First of all, the approach OP uses to change the order of the bars and stacking is correct.  Re-leveling a factor or defining the levels prior to plotting is really the best way to ensure the order when plotted will be as you wish them to be.

It's not altogether clear from the OP's question what is meant by "in danger of mis-labelling the graphic", but there is one graphical difficulty with the plot that can cause some confusion, with is the the order of stacking does not match the order we see in the legend.  In other words, in the legend it is ordered as we would want it to appear: "Obese", "Overweight", "Healthy" (left-to-right).  However, in the bar geom in the plot, the order is reversed: "Healthy", "Overweight", and "Obese" (left-to-right).  I'll fix that.

Here's the plot code again.  Note that I've changed a few things (syntax), but also I'm using position_fill() in place of position_stack().  Both are similar, but position_fill() will stretch the bars to be the same length based on proportion.  This is what we want here, so I'm using that both in geom_bar() and geom_text() places.  I'm also using geom_col() in place of geom_bar(), since it's more succint: geom_col() is essentially the wrapper for geom_bar(stat="identity").  One final note is that we need to remove the limits= argument from scale_y_continuous() or we won't see anything.

```<code>p=ggplot(data=data, aes(x=gender, y=Value, fill=BMI)) +
  geom_col(position=position_fill()) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = Value), size=2, angle=0, position=position_fill(vjust=0.1)) +
  coord_flip() +
  xlab("") + ylab("") +
  theme(legend.title = element_blank(), legend.position="bottom")
p
</code>```

To switch the order we see in the plot, you can use reverse=TRUE within position_fill().  We just need to be sure to do this in both places (or the text will not align with the bars).

```<code>p=ggplot(data=data, aes(x=gender, y=Value, fill=BMI)) +
  geom_col(position=position_fill(reverse=TRUE)) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = Value), size=2, angle=0, position=position_fill(vjust=0.1, reverse=TRUE)) +
  coord_flip() +
  xlab("") + ylab("") +
  theme(legend.title = element_blank(), legend.position="bottom")
p
</code>```

Body:
Similar questions have been asked before but this question relates to the case when I wish to order the bars and the stacks in a ggplot bar chart simultaneously.

Here is my data:

data = data.frame(gender = c("Female", "Female", "Female", "Male", "Male", "Male"),
                  BMI = c("Healthy", "Obese", "Overweight", "Healthy", "Obese", "Overweight"),
                  Value = c(10,20,30,25,35,45),
                  Colour = c("#009698", "#ed1651", "#f26522", "#009698", "#ed1651", "#f26522"))

The colour column corresponds to the BMI column.

I would like to plot a horizontal bar chart with the "Female" bar at the top and the "Male" bar underneath.  Further I would like the stacks of the bar to be in the following order: Healthy, Overweight, Obese, with healthy to the left then overweight, then obese.  And further still I would like each stack to have a specific colour as defined in the Colour column of the data frame.  Ideally I would like to have the legend in the following order: Healthy, Overweight, Obese.

So far I have managed to order the gender as I want it and order the stacks within each bar but I do not like the approach.  I'm in danger of mis-labelling the graphic.  I am ordering using factors.  Is there a better way?

x = c("Male", "Female")
data$gender = factor(data$gender,levels=x)
# Order the bmi categories so we have them in a specific order
x = c("Obese", "Overweight", "Healthy")
data$BMI = factor(data$BMI, levels=x)

p=ggplot(data=data, aes(x=gender, y=proportion, fill=data$BMI)) +
  geom_bar(position="stack", stat="identity") +
  scale_y_continuous(labels = scales::percent, limits=c(0,1)) +
  geom_text(aes(label = count), size=2, angle=0, position=position_stack(vjust=0.1)) +
  coord_flip() +
  xlab("") + ylab("") +
  theme(legend.title = element_blank(), legend.position="bottom")

This code gives this except the labels are different to those I supplied in the data frame above.

I am finding it very easy to mis-plot (numbers not corresponding to what is plotted) this graph and I need to get it right.

Could anyone help?  Thank you
Phil,

Body:
TL;DR

Use position_fill() in place of position_stack(), remove the limits= argument from scale_y_continuous(), and use reverse=TRUE to reverse the ordering of stacking in the bars so that it matches the order you see in the legend.

The Details

First of all, the approach OP uses to change the order of the bars and stacking is correct.  Re-leveling a factor or defining the levels prior to plotting is really the best way to ensure the order when plotted will be as you wish them to be.

It's not altogether clear from the OP's question what is meant by "in danger of mis-labelling the graphic", but there is one graphical difficulty with the plot that can cause some confusion, with is the the order of stacking does not match the order we see in the legend.  In other words, in the legend it is ordered as we would want it to appear: "Obese", "Overweight", "Healthy" (left-to-right).  However, in the bar geom in the plot, the order is reversed: "Healthy", "Overweight", and "Obese" (left-to-right).  I'll fix that.

Here's the plot code again.  Note that I've changed a few things (syntax), but also I'm using position_fill() in place of position_stack().  Both are similar, but position_fill() will stretch the bars to be the same length based on proportion.  This is what we want here, so I'm using that both in geom_bar() and geom_text() places.  I'm also using geom_col() in place of geom_bar(), since it's more succint: geom_col() is essentially the wrapper for geom_bar(stat="identity").  One final note is that we need to remove the limits= argument from scale_y_continuous() or we won't see anything.

p=ggplot(data=data, aes(x=gender, y=Value, fill=BMI)) +
  geom_col(position=position_fill()) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = Value), size=2, angle=0, position=position_fill(vjust=0.1)) +
  coord_flip() +
  xlab("") + ylab("") +
  theme(legend.title = element_blank(), legend.position="bottom")
p

To switch the order we see in the plot, you can use reverse=TRUE within position_fill().  We just need to be sure to do this in both places (or the text will not align with the bars).

p=ggplot(data=data, aes(x=gender, y=Value, fill=BMI)) +
  geom_col(position=position_fill(reverse=TRUE)) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = Value), size=2, angle=0, position=position_fill(vjust=0.1, reverse=TRUE)) +
  coord_flip() +
  xlab("") + ylab("") +
  theme(legend.title = element_blank(), legend.position="bottom")
p


来源: stackexchange

问:
Can I execute a pipeline from other pipeline in bitbucket pipelines?
I has the two repositories in bitbucket pipelines, both with pipelines enable.

How to execute the pipeline after the other pipeline complete?

答:
Just confirming that the above answers work, but we found out (after a lot of trial and error) that the user executing the pipeline must have WRITE permissions on the repo where the pipeline is invoked (even though his app password permissions were set to "WRITE").

Also, this works for executing pipelines in Bitbucket's cloud or on-premise, through local runners.

(Answering as I am lacking reputation for commenting)

ContentLicense: CC BY-SA 4.0


问:
How do I setup messaging and session middleware in a Django RequestFactory during unit testing
I have a function I need to test which takes a request as its argument. It is not exposed as a view by URL so I cannot test it with the test client.

I need to pass a request object to it, and the request object needs to have the messaging middleware enabled because messaging middleware is used in the function.

I am using the RequestFactory to create my request. The documentation says:

It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.

How do I setup the messaging middleware with the RequestFactory? I think I will also need the session middleware to make the messaging middleware work

This is the error my test currently produces when using the vanilla RequestFactory.

```<code>MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
</code>```

This is my function under test, in case it helps with understanding this problem:

```<code>from django.contrib import messages as django_messages

def store_to_request(self, request):
        """
        Place all the messages stored in this class into message storage in
        the request object supplied.
        :param request: The request object to which we should store all the messages
        :return: Does not return anything
        """
        for message in self._messages:
            django_messages.add_message(request, message.level, message.message, message.extra_tags,
                                    message.fail_silently)
</code>```

答:
An effictively equivalent method to Danag's anwer would be to pass the request object through the process_request methods of the session and message middlewares (in that order) before passing it to the view/function:

```<code>from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.messages.middleware import MessageMiddleware

request = request_factory.get()
sm = SessionMiddleware()
sm.process_request(request)
mm = MessageMiddleware()
mm.process_request(request)
</code>```

You can do the above in a method for convenience:

```<code>class MessageDependentTests(TestCase):

    def setUp(self):
        self.rf = RequestFactory()
        self.sm = SessionMiddleware()
        self.mm = MessageMiddleware()
        return super().setUp()

    def prepare_request(self, request):
        self.sm.process_request(request)
        self.mm.process_request(request)

    def test_something(self):
        request = self.rf.get('/')
        self.prepare_request(request)
        response = my_view(request)
        # test response below
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a function I need to test which takes a request as its argument. It is not exposed as a view by URL so I cannot test it with the test client.

I need to pass a request object to it, and the request object needs to have the messaging middleware enabled because messaging middleware is used in the function.

I am using the RequestFactory to create my request. The documentation says:

It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.

How do I setup the messaging middleware with the RequestFactory? I think I will also need the session middleware to make the messaging middleware work

This is the error my test currently produces when using the vanilla RequestFactory.

MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware

This is my function under test, in case it helps with understanding this problem:

from django.contrib import messages as django_messages

def store_to_request(self, request):
        """
        Place all the messages stored in this class into message storage in
        the request object supplied.
        :param request: The request object to which we should store all the messages
        :return: Does not return anything
        """
        for message in self._messages:
            django_messages.add_message(request, message.level, message.message, message.extra_tags,
                                    message.fail_silently)

Body:
An effictively equivalent method to Danag's anwer would be to pass the request object through the process_request methods of the session and message middlewares (in that order) before passing it to the view/function:

from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.messages.middleware import MessageMiddleware

request = request_factory.get()
sm = SessionMiddleware()
sm.process_request(request)
mm = MessageMiddleware()
mm.process_request(request)

You can do the above in a method for convenience:

class MessageDependentTests(TestCase):

    def setUp(self):
        self.rf = RequestFactory()
        self.sm = SessionMiddleware()
        self.mm = MessageMiddleware()
        return super().setUp()

    def prepare_request(self, request):
        self.sm.process_request(request)
        self.mm.process_request(request)

    def test_something(self):
        request = self.rf.get('/')
        self.prepare_request(request)
        response = my_view(request)
        # test response below


问:
Spring Data Query into Elastic search for exact match
I am learning elasticsearch with spring data so can someone help me understand better what elasticsearch query is doing here.  I am trying to return back only a set of results based off of a certain value, in this case env.  It seems to me that this JPQL query, is not making a difference to only return what I ask for.  I have also used an @Query with no difference.

-- here is part of my repository class

```<code>public interface MyFormRepo extends ElasticsearchRepository<MyForm, String> {
//??? these function calls are not effecting my return

@Query("{\"bool\": {\"must\": [{\"match\": {\"env\": \"?0\"}}]}}")
Page<MyForm> getAllByEnv(String env, Pageable pageable);

Page<MyForm> findAllByEnv(String env, Pageable pageable);
</code>```

-- Here is part of my entity class

```<code>@Document(indexName = "my_form")
public class MyForm {

@Id
private String id;
@Field(type = Text)
private String schema;
@Field(type = Long)
private long version;
@Field(type = Text)
private String env;
</code>```

答: Here is what I understand.  Elasticsearch has this concept called Fuzziness (https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness) so in it's searches which is based on Levenshtein distance (https://en.wikipedia.org/wiki/Levenshtein_distance).  Spring data does not allow us to modify this out of the box and is considered Fuzziness.AUTO by default. https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.misc.  As for the queries neither of them will do anything different.  Both findByAllEnv and getAllBeEnv has a fuziness.AUTO, as for the @Query I found a good reason stated at this site:  What is difference between match and bool must match query in Elasticsearch.  What I ended up finding is that I must implemented a custom repo for that I have found this example/explaination How to query Elastic with Spring-data-elastic.</p>

Body:
I am learning elasticsearch with spring data so can someone help me understand better what elasticsearch query is doing here.  I am trying to return back only a set of results based off of a certain value, in this case env.  It seems to me that this JPQL query, is not making a difference to only return what I ask for.  I have also used an @Query with no difference.

-- here is part of my repository class

public interface MyFormRepo extends ElasticsearchRepository<MyForm, String> {
//??? these function calls are not effecting my return

@Query("{\"bool\": {\"must\": [{\"match\": {\"env\": \"?0\"}}]}}")
Page<MyForm> getAllByEnv(String env, Pageable pageable);

Page<MyForm> findAllByEnv(String env, Pageable pageable);

-- Here is part of my entity class

@Document(indexName = "my_form")
public class MyForm {

@Id
private String id;
@Field(type = Text)
private String schema;
@Field(type = Long)
private long version;
@Field(type = Text)
private String env;


问:
get values from json request
i have this json response

2022-02-08 14:01:56,048 sdc-web-sockets-pp
/moe.com/SMART/logs/srf/srf-web-sockets.log: 2022-02-08 14:01:50,308
srf-web-sockets-pp-1 INFO  [null:-1] (executor-thread-19) Op16 -
Station : id-00003:vdeURRi8v8evU8AZWEnIwtbrucvjdeZyJL42,
MessageId: a8a3e920-88e7-11ec-8f9b-c904565fadef, request message:
{"action":"Boot","messageId":"a8d3r920-88e7-11ec-8f9b-c9074d5fadef","type":"CALL","uniqueId":"a8a3e920-88e7-11ec-8f9b-c9074d5fadef","payload":"{"Vendor":"vendorname","PointModel":"pointname","PointSerialNumber":"123456789","firmwareVersion":"1.1.1.8"}"}

I need to get the specific vars.

ex:

vendname=vendorname

model= pointname

modelsn= 123456789

firmversion=1.1.1.8

Can someone help me get these values from the request?

this is what i have so far

```<code>def getvalboot(e):
        jsrqs = e.widget.get("1.0", "end-1c")
        if "BOOT" in jsrqs.upper():
            j1,j2ff = jsrqs.split(r"payload")
            j2f = j2ff.replace("\\", "")
            j2a = j2f[3:]
            size = len(j2a)
            j2 = j2a[:size - 2]
            stud_obj = json.loads(j2)
            print("1: ",stud_obj['Vendor'])
</code>```

Ok, this works but im pretty sure there is a better way to do this, any idea?

答:
You could use the json libary wich comes defualt in built inn with python. The json libary can be used to convert the json file to a dictionary.

import json

f = open(r"file path", "r")
jsonf = f.read()
dict = json.loads(jsonf)
f.close()```

Title: get values from json request

Body:
i have this json response

2022-02-08 14:01:56,048 sdc-web-sockets-pp
/moe.com/SMART/logs/srf/srf-web-sockets.log: 2022-02-08 14:01:50,308
srf-web-sockets-pp-1 INFO  [null:-1] (executor-thread-19) Op16 -
Station : id-00003:vdeURRi8v8evU8AZWEnIwtbrucvjdeZyJL42,
MessageId: a8a3e920-88e7-11ec-8f9b-c904565fadef, request message:
{"action":"Boot","messageId":"a8d3r920-88e7-11ec-8f9b-c9074d5fadef","type":"CALL","uniqueId":"a8a3e920-88e7-11ec-8f9b-c9074d5fadef","payload":"{"Vendor":"vendorname","PointModel":"pointname","PointSerialNumber":"123456789","firmwareVersion":"1.1.1.8"}"}

I need to get the specific vars.

ex:

vendname=vendorname

model= pointname

modelsn= 123456789

firmversion=1.1.1.8

Can someone help me get these values from the request?

this is what i have so far

def getvalboot(e):
        jsrqs = e.widget.get("1.0", "end-1c")
        if "BOOT" in jsrqs.upper():
            j1,j2ff = jsrqs.split(r"payload")
            j2f = j2ff.replace("\\", "")
            j2a = j2f[3:]
            size = len(j2a)
            j2 = j2a[:size - 2]
            stud_obj = json.loads(j2)
            print("1: ",stud_obj['Vendor'])

Ok, this works but im pretty sure there is a better way to do this, any idea?


问:
I have a problem of wordpress theme and elementor
Why does this happen?

Why does this happen?
#elementor_theme_builder #hello-elementor

答:
Go to settings en check "Hide titel"

Click left icon for settings


问:
Secure ConnectionString in WinForm Applications
How Can I Secure my ConnectionString in WinForm Application?</p>

答:
You can't. Although you can encrypt the connection string in the app.config file, the application needs to be able to decrypt it and it is, therefore, always possible to retrieve the unencrypted connection string, especially with a managed application (perhaps not for your typical end user, but any skilled developer, or hacker can do this, and even end users can figure this out after a little bit of googling).

The solution to this is to not lean on security by obscurity. Use Windows Integrated Security when connecting to the database using the Windows user account and give the user the minimum amount of rights in the database.

Often though that is still not enough, because it is very hard to secure the database enough when end users are directly connected to the database (often because you need row-level security). For this to work you need to deny access to tables and views and completely fall back to stored procedures.

A better approach, however, is to prevent the desktop application from communicating directly with the database. Instead, use a web service as intermediate layer. In that case you have full control over the security and you can store the connection string securely on the (web) server.


问:
Firebase crashlytics still pending flutter
I want to track my flutter Android/IOS crashes in firebase crashlytics , but there is a problem with tracking the first crash on the app and it's still listening to the first crash.

in pubspec.yaml

```<code>firebase_crashlytics:
firebase_analytics:
firebase_core: ^1.7.0
</code>```

in app build.gradle

```<code>apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'io.fabric'
</code>```

in build.gradle

```<code>buildscript {
    repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.fabric.io/public'
        }
    }

    dependencies {
        classpath 'com.google.gms:google-services:4.3.0'
        classpath 'io.fabric.tools:gradle:1.26.1'
        classpath 'com.android.tools.build:gradle:4.1.0'
    }
}
</code>```

and in the flutter main.dart :

```<code>WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await FirebaseCrashlytics.instance
      .setCrashlyticsCollectionEnabled(true);
  FirebaseCrashlytics.instance.setUserIdentifier("51");
  FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
  FirebaseCrashlytics.instance.crash();
</code>```

I even tried android native example crash  throw new RuntimeExeption("test Firebase crash");
but firebase is still listening for the first app crash.

UPDATE

Firebase Crashlytics page is just like bellow after 48 hours

pending image

答:
I think you can use this line in your code .because of this line I think you can't get the crash report. I'm facing the same issue ..and below code is working perfectly fine

```<code>implementation 'com.google.firebase:firebase-crashlytics:17.3.1'
</code>```

use this code in app.build.gradle

```<code>dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.billingclient:billing:3.0.2'
    implementation platform('com.google.firebase:firebase-bom:29.0.4')
    implementation 'com.google.firebase:firebase-analytics'
}
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'com.google.gms.google-services'
</code>```

in Android.build.gradle

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:4.1.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
    classpath 'com.google.gms:google-services:4.3.5'
}
</code>```

in you main.dart use this code

```<code>Future main() async{
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();

    FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
    runApp(
        MyApp(),
    );
}
</code>```

and I put this line to crash the app in Splash init function .you can
use this line where you find suitable

```<code>FirebaseCrashlytics.instance.crash();
</code>```

Body:
I want to track my flutter Android/IOS crashes in firebase crashlytics , but there is a problem with tracking the first crash on the app and it's still listening to the first crash.

in pubspec.yaml

firebase_crashlytics:
firebase_analytics:
firebase_core: ^1.7.0

in app build.gradle

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'io.fabric'

in build.gradle

buildscript {
    repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.fabric.io/public'
        }
    }

    dependencies {
        classpath 'com.google.gms:google-services:4.3.0'
        classpath 'io.fabric.tools:gradle:1.26.1'
        classpath 'com.android.tools.build:gradle:4.1.0'
    }
}

and in the flutter main.dart :

WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await FirebaseCrashlytics.instance
      .setCrashlyticsCollectionEnabled(true);
  FirebaseCrashlytics.instance.setUserIdentifier("51");
  FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
  FirebaseCrashlytics.instance.crash();

I even tried android native example crash  throw new RuntimeExeption("test Firebase crash");
but firebase is still listening for the first app crash.

UPDATE

Firebase Crashlytics page is just like bellow after 48 hours

pending image

Body:
I think you can use this line in your code .because of this line I think you can't get the crash report. I'm facing the same issue ..and below code is working perfectly fine

implementation 'com.google.firebase:firebase-crashlytics:17.3.1'

use this code in app.build.gradle

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.billingclient:billing:3.0.2'
    implementation platform('com.google.firebase:firebase-bom:29.0.4')
    implementation 'com.google.firebase:firebase-analytics'
}
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'com.google.gms.google-services'

in Android.build.gradle

dependencies {
    classpath 'com.android.tools.build:gradle:4.1.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
    classpath 'com.google.gms:google-services:4.3.5'
}

in you main.dart use this code

Future main() async{
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();

    FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
    runApp(
        MyApp(),
    );
}

and I put this line to crash the app in Splash init function .you can
use this line where you find suitable

FirebaseCrashlytics.instance.crash();


问:
Update table with items where the date is the maximum
MySQL
I need to update only the rows in a table that have the maximum date grouped by an another column.

Table Objectversions

```<code>id, ObjectID, objectdatetime, Linktime, othercolumns
</code>```

I have tried

```<code>UPDATE Objectversions
    SET Linktime = 1
WHERE id IN (
                SELECT id
                FROM Objectversions
                WHERE Objectdatetime IN (
                        SELECT MAX(Objectdatetime)
                        FROM Objectversions
                        GROUP BY ObjectID
                    )
        );
</code>```

I get an error You can't specify target table Objectversions for update in FROM clause.

I have looked at other solutions and cannot work out how to do this. I'll be grateful for any ideas.

答:
Even though I prefer @sagi solution another way of doing it is wrapp the subquery in an outer query.

```<code>UPDATE Objectversions
    SET Linktime = 1
WHERE id IN ( SELECT t1.id FROM (SELECT id
                                 FROM Objectversions
                                 WHERE Objectdatetime IN (
                                                           SELECT MAX(Objectdatetime)
                                                           FROM Objectversions
                                                           GROUP BY ObjectID
                                                           )

                                 ) as t1
            );
</code>```

You will find a detailed explanation in the documentation about the error You can't specify target table 'items' for update in FROM clause

Body:
MySQL
I need to update only the rows in a table that have the maximum date grouped by an another column.

Table Objectversions

id, ObjectID, objectdatetime, Linktime, othercolumns

I have tried

UPDATE Objectversions
    SET Linktime = 1
WHERE id IN (
                SELECT id
                FROM Objectversions
                WHERE Objectdatetime IN (
                        SELECT MAX(Objectdatetime)
                        FROM Objectversions
                        GROUP BY ObjectID
                    )
        );

I get an error You can't specify target table Objectversions for update in FROM clause.

I have looked at other solutions and cannot work out how to do this. I'll be grateful for any ideas.

Body:
Even though I prefer @sagi solution another way of doing it is wrapp the subquery in an outer query.

UPDATE Objectversions
    SET Linktime = 1
WHERE id IN ( SELECT t1.id FROM (SELECT id
                                 FROM Objectversions
                                 WHERE Objectdatetime IN (
                                                           SELECT MAX(Objectdatetime)
                                                           FROM Objectversions
                                                           GROUP BY ObjectID
                                                           )

                                 ) as t1
            );

You will find a detailed explanation in the documentation about the error You can't specify target table 'items' for update in FROM clause


问:
Installing Jenssegers/MongoDB in a Laravel Sail 8.0 environment
So I've managed to do a clean install of Laravel in Windows using WSL2. One of the requirements of my project is to have two databases running at the same time mysql and mongodb.

I added an image of MongoDB in my docker-compose.yml as the dock-hub tells me, but when I try to add the jenssegers/laravel-mongodb package sail tells me I don't have the correct requirements.

How do I connect both containers properly, so I can install the package without any issues?

Logs:

```<code>~/example-app$ sail composer require jenssegers/mongodb:"^3.8"
./composer.json has been updated
Running composer update jenssegers/mongodb
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
    - jenssegers/mongodb[v3.8.0, ..., v3.8.1] require mongodb/mongodb ^1.6 -> satisfiable by mongodb/mongodb[1.6.0, ..., 1.9.x-dev (alias of dev-master)].
    - mongodb/mongodb 1.9.x-dev is an alias of mongodb/mongodb dev-master and thus requires it to be installed too.
    - mongodb/mongodb[dev-master, 1.8.0-RC1, ..., v1.8.x-dev] require ext-mongodb ^1.8.1 -> it is missing from your system. Install or enable PHP's mongodb extension.
    - mongodb/mongodb[1.6.0, ..., v1.6.x-dev] require php ^5.6 || ^7.0 -> your php version (8.0.0) does not satisfy that requirement.
    - mongodb/mongodb[1.7.0-beta1, ..., v1.7.x-dev] require php ^7.0 -> your php version (8.0.0) does not satisfy that requirement.
    - Root composer.json requires jenssegers/mongodb ^3.8 -> satisfiable by jenssegers/mongodb[v3.8.0, v3.8.1].

To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/8.0/cli/php.ini
    - /etc/php/8.0/cli/conf.d/10-mysqlnd.ini
    - /etc/php/8.0/cli/conf.d/10-opcache.ini
    - /etc/php/8.0/cli/conf.d/10-pdo.ini
    - /etc/php/8.0/cli/conf.d/15-xml.ini
    - /etc/php/8.0/cli/conf.d/20-bcmath.ini
    - /etc/php/8.0/cli/conf.d/20-calendar.ini
    - /etc/php/8.0/cli/conf.d/20-ctype.ini
    - /etc/php/8.0/cli/conf.d/20-curl.ini
    - /etc/php/8.0/cli/conf.d/20-dom.ini
    - /etc/php/8.0/cli/conf.d/20-exif.ini
    - /etc/php/8.0/cli/conf.d/20-ffi.ini
    - /etc/php/8.0/cli/conf.d/20-fileinfo.ini
    - /etc/php/8.0/cli/conf.d/20-ftp.ini
    - /etc/php/8.0/cli/conf.d/20-gd.ini
    - /etc/php/8.0/cli/conf.d/20-gettext.ini
    - /etc/php/8.0/cli/conf.d/20-iconv.ini
    - /etc/php/8.0/cli/conf.d/20-igbinary.ini
    - /etc/php/8.0/cli/conf.d/20-imap.ini
    - /etc/php/8.0/cli/conf.d/20-intl.ini
    - /etc/php/8.0/cli/conf.d/20-ldap.ini
    - /etc/php/8.0/cli/conf.d/20-mbstring.ini
    - /etc/php/8.0/cli/conf.d/20-msgpack.ini
    - /etc/php/8.0/cli/conf.d/20-mysqli.ini
    - /etc/php/8.0/cli/conf.d/20-pdo_mysql.ini
    - /etc/php/8.0/cli/conf.d/20-pdo_pgsql.ini
    - /etc/php/8.0/cli/conf.d/20-pdo_sqlite.ini
    - /etc/php/8.0/cli/conf.d/20-pgsql.ini
    - /etc/php/8.0/cli/conf.d/20-phar.ini
    - /etc/php/8.0/cli/conf.d/20-posix.ini
    - /etc/php/8.0/cli/conf.d/20-readline.ini
    - /etc/php/8.0/cli/conf.d/20-redis.ini
    - /etc/php/8.0/cli/conf.d/20-shmop.ini
    - /etc/php/8.0/cli/conf.d/20-simplexml.ini
    - /etc/php/8.0/cli/conf.d/20-soap.ini
    - /etc/php/8.0/cli/conf.d/20-sockets.ini
    - /etc/php/8.0/cli/conf.d/20-sqlite3.ini
    - /etc/php/8.0/cli/conf.d/20-sysvmsg.ini
    - /etc/php/8.0/cli/conf.d/20-sysvsem.ini
    - /etc/php/8.0/cli/conf.d/20-sysvshm.ini
    - /etc/php/8.0/cli/conf.d/20-tokenizer.ini
    - /etc/php/8.0/cli/conf.d/20-xmlreader.ini
    - /etc/php/8.0/cli/conf.d/20-xmlwriter.ini
    - /etc/php/8.0/cli/conf.d/20-xsl.ini
    - /etc/php/8.0/cli/conf.d/20-zip.ini
    - /etc/php/8.0/cli/conf.d/25-memcached.ini
    - /etc/php/8.0/cli/conf.d/99-sail.ini
You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
</code>```

My docker-compose.yml

```<code># For more information: https://laravel.com/docs/sail
version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.0
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.0/app
        ports:
            - '${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - mongo
            # - selenium

    # ...

    mysql:
        image: 'mysql:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
        volumes:
            - 'sailmysql:/var/lib/mysql'
        networks:
            - sail

    mongo:
        image: mongo
        restart: always
        environment:
            MONGO_INITDB_ROOT_USERNAME: root
            MONGO_INITDB_ROOT_PASSWORD: example

    mongo-express:
        image: mongo-express
        restart: always
        ports:
        - 8081:8081
        environment:
            ME_CONFIG_MONGODB_ADMINUSERNAME: root
            ME_CONFIG_MONGODB_ADMINPASSWORD: example
networks:
    sail:
        driver: bridge
volumes:
    sailmysql:
        driver: local
    sailredis:
        driver: local
</code>```

答:
<pre class="lang-sh prettyprint-override"><code>#Step 1
#edit vendor/laravel/sail/runtimes/[PHP VERSION]/Dockerfile
#Ex: ./vendor/laravel/sail/runtimes/8.1/Dockerfile

#Step 2
#Add the command at Dockerfile file
RUN apt-get install -y php8.1-mongodb

#Step 3
#Save it and then run ./vendor/bin/sail build and ./vendor/bin/sail up -d
./vendor/bin/sail build && ./vendor/bin/sail up -d

</code>```

Body:
So I've managed to do a clean install of Laravel in Windows using WSL2. One of the requirements of my project is to have two databases running at the same time mysql and mongodb.

I added an image of MongoDB in my docker-compose.yml as the dock-hub tells me, but when I try to add the jenssegers/laravel-mongodb package sail tells me I don't have the correct requirements.

How do I connect both containers properly, so I can install the package without any issues?

Logs:

~/example-app$ sail composer require jenssegers/mongodb:"^3.8"
./composer.json has been updated
Running composer update jenssegers/mongodb
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
    - jenssegers/mongodb[v3.8.0, ..., v3.8.1] require mongodb/mongodb ^1.6 -> satisfiable by mongodb/mongodb[1.6.0, ..., 1.9.x-dev (alias of dev-master)].
    - mongodb/mongodb 1.9.x-dev is an alias of mongodb/mongodb dev-master and thus requires it to be installed too.
    - mongodb/mongodb[dev-master, 1.8.0-RC1, ..., v1.8.x-dev] require ext-mongodb ^1.8.1 -> it is missing from your system. Install or enable PHP's mongodb extension.
    - mongodb/mongodb[1.6.0, ..., v1.6.x-dev] require php ^5.6 || ^7.0 -> your php version (8.0.0) does not satisfy that requirement.
    - mongodb/mongodb[1.7.0-beta1, ..., v1.7.x-dev] require php ^7.0 -> your php version (8.0.0) does not satisfy that requirement.
    - Root composer.json requires jenssegers/mongodb ^3.8 -> satisfiable by jenssegers/mongodb[v3.8.0, v3.8.1].

To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/8.0/cli/php.ini
    - /etc/php/8.0/cli/conf.d/10-mysqlnd.ini
    - /etc/php/8.0/cli/conf.d/10-opcache.ini
    - /etc/php/8.0/cli/conf.d/10-pdo.ini
    - /etc/php/8.0/cli/conf.d/15-xml.ini
    - /etc/php/8.0/cli/conf.d/20-bcmath.ini
    - /etc/php/8.0/cli/conf.d/20-calendar.ini
    - /etc/php/8.0/cli/conf.d/20-ctype.ini
    - /etc/php/8.0/cli/conf.d/20-curl.ini
    - /etc/php/8.0/cli/conf.d/20-dom.ini
    - /etc/php/8.0/cli/conf.d/20-exif.ini
    - /etc/php/8.0/cli/conf.d/20-ffi.ini
    - /etc/php/8.0/cli/conf.d/20-fileinfo.ini
    - /etc/php/8.0/cli/conf.d/20-ftp.ini
    - /etc/php/8.0/cli/conf.d/20-gd.ini
    - /etc/php/8.0/cli/conf.d/20-gettext.ini
    - /etc/php/8.0/cli/conf.d/20-iconv.ini
    - /etc/php/8.0/cli/conf.d/20-igbinary.ini
    - /etc/php/8.0/cli/conf.d/20-imap.ini
    - /etc/php/8.0/cli/conf.d/20-intl.ini
    - /etc/php/8.0/cli/conf.d/20-ldap.ini
    - /etc/php/8.0/cli/conf.d/20-mbstring.ini
    - /etc/php/8.0/cli/conf.d/20-msgpack.ini
    - /etc/php/8.0/cli/conf.d/20-mysqli.ini
    - /etc/php/8.0/cli/conf.d/20-pdo_mysql.ini
    - /etc/php/8.0/cli/conf.d/20-pdo_pgsql.ini
    - /etc/php/8.0/cli/conf.d/20-pdo_sqlite.ini
    - /etc/php/8.0/cli/conf.d/20-pgsql.ini
    - /etc/php/8.0/cli/conf.d/20-phar.ini
    - /etc/php/8.0/cli/conf.d/20-posix.ini
    - /etc/php/8.0/cli/conf.d/20-readline.ini
    - /etc/php/8.0/cli/conf.d/20-redis.ini
    - /etc/php/8.0/cli/conf.d/20-shmop.ini
    - /etc/php/8.0/cli/conf.d/20-simplexml.ini
    - /etc/php/8.0/cli/conf.d/20-soap.ini
    - /etc/php/8.0/cli/conf.d/20-sockets.ini
    - /etc/php/8.0/cli/conf.d/20-sqlite3.ini
    - /etc/php/8.0/cli/conf.d/20-sysvmsg.ini
    - /etc/php/8.0/cli/conf.d/20-sysvsem.ini
    - /etc/php/8.0/cli/conf.d/20-sysvshm.ini
    - /etc/php/8.0/cli/conf.d/20-tokenizer.ini
    - /etc/php/8.0/cli/conf.d/20-xmlreader.ini
    - /etc/php/8.0/cli/conf.d/20-xmlwriter.ini
    - /etc/php/8.0/cli/conf.d/20-xsl.ini
    - /etc/php/8.0/cli/conf.d/20-zip.ini
    - /etc/php/8.0/cli/conf.d/25-memcached.ini
    - /etc/php/8.0/cli/conf.d/99-sail.ini
You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

My docker-compose.yml

# For more information: https://laravel.com/docs/sail
version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.0
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.0/app
        ports:
            - '${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - mongo
            # - selenium

    # ...

    mysql:
        image: 'mysql:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
        volumes:
            - 'sailmysql:/var/lib/mysql'
        networks:
            - sail

    mongo:
        image: mongo
        restart: always
        environment:
            MONGO_INITDB_ROOT_USERNAME: root
            MONGO_INITDB_ROOT_PASSWORD: example

    mongo-express:
        image: mongo-express
        restart: always
        ports:
        - 8081:8081
        environment:
            ME_CONFIG_MONGODB_ADMINUSERNAME: root
            ME_CONFIG_MONGODB_ADMINPASSWORD: example
networks:
    sail:
        driver: bridge
volumes:
    sailmysql:
        driver: local
    sailredis:
        driver: local


问:
C++ and STL refresher course
I know C and C++ quite well. I know in much detail about pointers and well versed with pointer arithmetic and worked on Win32 API and a bit of MFC as well in my university days. In my previous job, I had no chance to look on these matters and worked in some other domain. Now what I want is a crash or refresher course in:

C++

STL

I do not want to go through 500+ pages of books because I know C#, Java, Ruby, Python and even x86 Assembly as well. What I want is to cover advanced and dark corners of C++ and intermediate STL.

Can anyone point out good links about it?
I know about Google! ;-)
But an intelligent human recommendation is something else yet Google has not implemented.

答: SGI has a pretty nice reference for STL.</p>

OwnerDisplayName: Mohsin Hijazee

Title: C++ and STL refresher course

LastEditorDisplayName: Ferruccio

OwnerDisplayName: Brian

ContentLicense: CC BY-SA 2.5


问:
Twitter Bot how can i get callback url
This is my first attempt to make a bot application on twitter

but there are some requirements to connect api and i don't understand..

there need callback url, where can i get callback url?
can it use localhost?

答: You will only need a functional callback URL if you plan on building an app that users will log in to. If you already are able to get the access token and key for your bot account then you can use http://localhost in the callback URL field.

Title: Twitter Bot how can i get callback url


问:
Trying to disable submit button when there is zero input
I am just a mere beginner. I am trying to use typescript and html to disable the submit button when a user does not enter in a part number. I am having some issues as I get the error when attempting to do so,

```<code> "Cannot find name 'partNumber'".
</code>```

If any advice could be spared it would greatly be appreciated. Here is all the code that pertains to this....

```<code><div>
    <button id="submitButton"
        :class="{ disabled:partNumber == -1 }"<--error here-->
        :disabled="partNumber == -1" <--and here-->
        @click="submitItem"
    >
        <span>Submit</span>
        <i class="fas fa-send"></i>
    </button>
</div>
</code>```

Here is the typscript.js

```<code> mounted() {
    for (let element of this.partStore.partEntries as PartDefinition[]) {
      if (element.id == parseInt(this.$route.params.id.toString())) {
        this.localPartEntry.partNumber = element.partNumber;
        this.localPartEntry.variant = element.variant;
        this.localPartEntry.revision = element.revision;
        this.localPartEntry.description = element.description;
        this.localPartEntry.supplier = element.supplier;
        this.localPartEntry.previewImagePath = element.previewImagePath;
        this.localPartEntry.previewImageDateTime = element.previewImageDateTime;
        this.localPartEntry.obsolete = element.obsolete;
        this.localPartEntry.internalOnly = element.internalOnly;
        break;
      }
    }
  },
</code>```

答:
As per your script, your partNumber is stored in this.localPartEntry.partNumber.

So the disable condition should be :disabled="localPartEntry.partNumber == -1" instead of :disabled="partNumber == -1".

So the template will be

```<code><div>
    <button id="submitButton"
        :class="{ disabled: localPartEntry.partNumber == -1 }""
        :disabled="localPartEntry.partNumber == -1"
        @click="submitItem"
    >
        <span>Submit</span>
        <i class="fas fa-send"></i>
    </button>
</div>
</code>```

Body:
I am just a mere beginner. I am trying to use typescript and html to disable the submit button when a user does not enter in a part number. I am having some issues as I get the error when attempting to do so,

 "Cannot find name 'partNumber'".

If any advice could be spared it would greatly be appreciated. Here is all the code that pertains to this....

    <button id="submitButton"
        :class="{ disabled:partNumber == -1 }"<--error here-->
        :disabled="partNumber == -1" <--and here-->
        @click="submitItem"
    >
        Submit

    </button>

Here is the typscript.js

 mounted() {
    for (let element of this.partStore.partEntries as PartDefinition[]) {
      if (element.id == parseInt(this.$route.params.id.toString())) {
        this.localPartEntry.partNumber = element.partNumber;
        this.localPartEntry.variant = element.variant;
        this.localPartEntry.revision = element.revision;
        this.localPartEntry.description = element.description;
        this.localPartEntry.supplier = element.supplier;
        this.localPartEntry.previewImagePath = element.previewImagePath;
        this.localPartEntry.previewImageDateTime = element.previewImageDateTime;
        this.localPartEntry.obsolete = element.obsolete;
        this.localPartEntry.internalOnly = element.internalOnly;
        break;
      }
    }
  },

Body:
As per your script, your partNumber is stored in this.localPartEntry.partNumber.

So the disable condition should be :disabled="localPartEntry.partNumber == -1" instead of :disabled="partNumber == -1".

So the template will be

<div>
    <button id="submitButton"
        :class="{ disabled: localPartEntry.partNumber == -1 }""
        :disabled="localPartEntry.partNumber == -1"
        @click="submitItem"
    >
        <span>Submit</span>
        <i class="fas fa-send"></i>
    </button>
</div>


问:
MySQL skip first 10 results
Is there a way in MySQL to have the first 10 result from a SELECT query skipped?
I'd like it to work something like LIMIT.</p>

答:
To skip first 10 rows use OFFSET 10, but LIMIT is also required,

If you want to get all the rows and only skip first 10 rows try using a big number like 999999999 or as per your choice

```<code>SELECT * FROM table LIMIT 999999 OFFSET 10
</code>```

Title: MySQL skip first 10 results

Body:
To skip first 10 rows use OFFSET 10, but LIMIT is also required,

If you want to get all the rows and only skip first 10 rows try using a big number like 999999999 or as per your choice

SELECT * FROM table LIMIT 999999 OFFSET 10


问:
filter until some condition is met for the first time
It's not a real world example, I over-simplified it. Giving this array:

```<code>const a = [1,2,3,4,5,6,7,8,4,5]; // Etc. Random numbers after.
</code>```

I want to filter it to have only those matching a pattern (let's say greater than 3 for this trivial example) until something appends for the first time (let's say element is greater than 7)

So for this example, I just want: [4,5,6,7]. But with filter, I would have the trailing 4 and 5:

```<code>const a = [1,2,3,4,5,6,7,8,4,5].filter((v) => v > 3)
// returns: [4, 5, 6, 7, 8, 4, 5]
</code>```

So I want to get item from an array and definitively stop after a condition. How can I filter then stop after the first time a condition is not met? (without for loop, I want to keep it "functional-like")

```<code>const a = [1,2,3,4,5,6,7,8,4,5,1,2,976,-1].awsome_function();
// returns: [4, 5, 6, 7, 8] because it stopped after the first 8.
</code>```

答:
Another way of keeping it functional style is to use reduce.

Array.prototype.filterUntil = function(fn, stopFn) {
  const { result } = this.reduce(
    ({ result, isStopped }, item) => {
      isStopped = isStopped || stopFn(item);
      return {
        result: !isStopped && fn(item) ? [...result, item] : result,
        isStopped,
      };
    },
    { result: [], isStopped: false }
  );
  return result;
};

console.log(
  [1,2,3,4,5,6,7,8,4,5].filterUntil(e => e > 3, e => e > 7)
);```

Body:
It's not a real world example, I over-simplified it. Giving this array:

const a = [1,2,3,4,5,6,7,8,4,5]; // Etc. Random numbers after.

I want to filter it to have only those matching a pattern (let's say greater than 3 for this trivial example) until something appends for the first time (let's say element is greater than 7)

So for this example, I just want: [4,5,6,7]. But with filter, I would have the trailing 4 and 5:

const a = [1,2,3,4,5,6,7,8,4,5].filter((v) => v > 3)
// returns: [4, 5, 6, 7, 8, 4, 5]

So I want to get item from an array and definitively stop after a condition. How can I filter then stop after the first time a condition is not met? (without for loop, I want to keep it "functional-like")

const a = [1,2,3,4,5,6,7,8,4,5,1,2,976,-1].awsome_function();
// returns: [4, 5, 6, 7, 8] because it stopped after the first 8.


问:
Attributed String Foreground color not working in Swift
I am using the following code to change the foreground color and font of a attribute string using Swift. But the Font changing perfectly without any problem but the foreground color is not changing

```<code>var checklistText = NSMutableAttributedString()
        checklistText = NSMutableAttributedString(string: "\(lblChecklistName.text!),\(checklistName)")
        checklistText.addAttribute(NSFontAttributeName,
                                   value: UIFont(
                                    name: "Helvetica",
                                    size: 11.0)!,
                                   range: NSRange(location: lblChecklistName.text!.length(), length: checklistName.length()))
        checklistText.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location: lblChecklistName.text!.length(), length: checklistName.length()+1))
        lblChecklistName.attributedText = checklistText
</code>```

答:
for UIButton this issue solves by:</p>
```<code>let bin = UIButton(type: .system)
btn.setTitleColor(nil, for: .normal)
</code>```

Body:
I am using the following code to change the foreground color and font of a attribute string using Swift. But the Font changing perfectly without any problem but the foreground color is not changing

var checklistText = NSMutableAttributedString()
        checklistText = NSMutableAttributedString(string: "\(lblChecklistName.text!),\(checklistName)")
        checklistText.addAttribute(NSFontAttributeName,
                                   value: UIFont(
                                    name: "Helvetica",
                                    size: 11.0)!,
                                   range: NSRange(location: lblChecklistName.text!.length(), length: checklistName.length()))
        checklistText.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location: lblChecklistName.text!.length(), length: checklistName.length()+1))
        lblChecklistName.attributedText = checklistText

Body:
for UIButton this issue solves by:

let bin = UIButton(type: .system)
btn.setTitleColor(nil, for: .normal)


问:
Azure AD: code flow with PKCE: id_token is not enabled for the application
I'm trying to integrate a React single-page app (SPA) with Azure AD. I'm following the docs (e.g. scenario) and using the samples from react-aad-msal to see if things work at a basic level.

But, I get the following error when attempting to reach the Microsoft login page:

AADSTS700054: response_type 'id_token' is not enabled for the application.

Now, the docs are pretty clear that for SPAs, auth code flow with PKCE is the way to go, and you shouldn't use the implicit grant flow because it's insecure. This means that existing answers to similar questions (such as this one or this other one), which suggest blindly turning on a setting for the implicit flow, are inadequate.

Is it possible to enable login (ID tokens) and API access (access tokens) for an SPA without using the implicit flow?

(I'm not sure yet, but it's also possible that react-aad-msal is using the implicit flow. I haven't found any setting that tells it which flow to use.)

答:
I ran into this building Blazor WASM (.NET 6 with all up to date libraries), but I think my resolution may still apply for some folks.

After following the tutorial here as closely as possible, I was still getting the "id_token is not enabled" message. One thing I noticed that confused me big time was this part of the tutorial regarding registering your client application :

But if you look in the Azure Portal the actual checkboxes seem to state the opposite :

I chalked this up to an error in the tutorial and left them unchecked thinking that should allow me to use auth code flow. Tried everything and was still getting the same message. Ready to punt on the whole issue, I enabled both Access Tokens and ID Tokens.

Things started working! But looking at the network traffic, it was actually calling the /authorize endpoint multiple times when hitting the application. The first time with response_type=id_token and then after that with response_type=code.

Eventually realized this was caused by the /authsettings resource deployed on the app service. Azure was trying to authenticate me to the app service itself using response_type=id_token.

After moving to a fresh app service without any authentication settings, and just relying on the application's configuration to redirect unauthenticated users, auth code flow worked, and the check boxes in the app registration were unchecked.


问:
Communication betwen local programms in C#
I'm surching for a way to communicate betwen two local c# Programms in an effective and very fast way. The best would be if it is possible to trigger a method of the "main" program with the second one and recive the result like a getter and setter. is there a something i that dosnt need 2 install a local server or something like that?

if more details needed. I am writing a little Programm for some Audio management and have a Device that has some dials and and an SDK for Plugins. The plan is to change some settings in the Programm if i have the Device connected to my PC and show some of the results on it. And the reason for not dooing all of it as a Plugin is that the Programm should be able to run on its own.

i would be glad for some simple exaples to start with.

答:
I've successfully used Unosquare's Embed.IO (no affiliation) before now to make a program host a small web server. You can see examples of setup on their home page

You might set up some AudioController class:

```<code>class AudioController: WebApiController{

    [Route(HttpVerbs.Get, "/api/samplerate/{rate}")]
    public object SetSampleRate(int rate)
    {
       //set the rate?
       Properties.Settings.Default.SamplingRate = rate;

       return true;
    }

}
</code>```

And then in the client you might poke that endpoint:

```<code>var wc = new WebClient();
wc.DownloadString("http://localhost:1234/api/samplerate/44100");
</code>```

Perhaps you want a more complex request object:

```<code>class RecorderSettings{
    public int SampleRate{get;set;}
    public int Bits{get;set;}
}

class AudioController: WebApiController{

    [Route(HttpVerbs.Post, "/api/setMulti")]
    public async Task<object> SetMultiple()
    {
       var x = await HttpContext.GetRequestDataAsync<RecorderSettings>();

       Properties.Settings.Default.SamplingRate = x.SampleRate;
       Properties.Settings.Default.Bitness = x.Bits;

       return ...;
    }

}
</code>```

And some client poking it with json:

```<code>     //client is some static HttpClient

     HttpResponseMessage response = await client.PostAsync(
       "http://localhost:1234/api/setMulti",
       new StringContent(
         JsonConvert.Serialize(new { SampleRate = 44100, Bits = 16}),
         Encoding.UTF8,
         MediaTypeNames.Application.Json
       )
     );
</code>```

Body:
I've successfully used Unosquare's Embed.IO (no affiliation) before now to make a program host a small web server. You can see examples of setup on their home page

You might set up some AudioController class:

class AudioController: WebApiController{

    [Route(HttpVerbs.Get, "/api/samplerate/{rate}")]
    public object SetSampleRate(int rate)
    {
       //set the rate?
       Properties.Settings.Default.SamplingRate = rate;

       return true;
    }

}

And then in the client you might poke that endpoint:

var wc = new WebClient();
wc.DownloadString("http://localhost:1234/api/samplerate/44100");

Perhaps you want a more complex request object:

class RecorderSettings{
    public int SampleRate{get;set;}
    public int Bits{get;set;}
}

class AudioController: WebApiController{

    [Route(HttpVerbs.Post, "/api/setMulti")]
    public async Task<object> SetMultiple()
    {
       var x = await HttpContext.GetRequestDataAsync<RecorderSettings>();

       Properties.Settings.Default.SamplingRate = x.SampleRate;
       Properties.Settings.Default.Bitness = x.Bits;

       return ...;
    }

}

And some client poking it with json:

     //client is some static HttpClient

     HttpResponseMessage response = await client.PostAsync(
       "http://localhost:1234/api/setMulti",
       new StringContent(
         JsonConvert.Serialize(new { SampleRate = 44100, Bits = 16}),
         Encoding.UTF8,
         MediaTypeNames.Application.Json
       )
     );


问:
Multiple GLSurfaceView moving at the same time
I am facing an strange issue not sure why this is happening.

I have a Java based Activity which has a LinearLayout. This LinearLayout consists of two GLSurfaceView. All the associated methods of GLSurfaceView like OnDraw, SurfaceChanged etc are moving call down to JNI layer. Inside the JNI layer I am drawing a cube using OpenGLES. I have also created a touch listener and have associated it with first GLSurfaceView. Once I get a touch event I move the call to JNI layer and randomly rotate the first cube.

Problem is when I rotate my first cube both the cubes rotates at exactly same angle. I have debugged this issue for last four hours and I am pretty sure there is nothing wrong in my logic. But for some unknown reason when I make change in one GLSurfaceView other cube changes automatically.

Any ideas? Similar issues? Guess?

Update

I am using same context i.e. my activity for both GLSurfaceView. Basically I have a class inside C++ which draws cube through opengles. Now I am successfully creating two cubes and displaying them simultaneously. Both cubes have different texture on them which I am passing via Java layer. My c++ class has a method which randomly rotates the cube. Problem is if I call method of one cube to rotate it other automatically rotates at same angle no make what I do.

答: Say that your first GLSurfaceView is on the first left side of your screen, and the second is on the second right half. One idea is to check what side the coordinates x, y of the motionEvent belongs to. And then pass rotation and translation accordingly.</p>


问:
How to use colors and titles inside flutter lists and maps
enter image description here

enter image description here

Help post .... As you can see in the flutter code. I was trying to figure out how to see apps with colors and titles with a map inside a list, but I could see the titles. There was a problem with the colors. How can I fix this? So that I can see my color and title

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

class HomePage extends StatelessWidget {
  final myCatagory = [
    {
      'title': 'Samsung',
      'color': Colors.pink[800],
    },
    {
      'title': 'Symphony',
      'color': Colors.tealAccent[800],
    },
    {
      'title': 'MI',
      'color': Colors.amberAccent[800],
    },
    {
      'title': 'Oppo',
      'color': Colors.blue[800],
    },
    {
      'title': 'Vivo',
      'color': Colors.redAccent[800],
    },
    {
      'title': 'Iphone',
      'color': Colors.greenAccent[800],
    },
  ];

  // final catagoryColors = [
  //   Colors.red,
  //   Colors.green,
  //   Colors.black87,
  // ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        title: const Text('My Blog'),
        backgroundColor: Colors.redAccent,
      ),
      body: Container(
        height: 150,
        child: ListView.builder(
          itemCount: myCatagory.length,
          shrinkWrap: true,
          primary: false,
          physics: BouncingScrollPhysics(),
          scrollDirection: Axis.horizontal,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(
                left: 10,
                top: 10,
              ),
              color: myCatagory[index]['color'], **The problem in this line**
              height: 200,
              width: 100,
              child: Text(
                '${myCatagory[index]['title']}',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 15,
                  fontWeight: FontWeight.w400,
                ),
              ),
            );
          },
        ),
      ),
    );
  }enter image description here

enter code here
</code>```

答:
You can add it as a hex value and parse it to int like:</p>
```<code> {
      'title': 'Symphony',
      'color': '0xFFB74093',
    },
</code>```
```<code>color:  Color(int.parse(myCatagory[index]['color'].toString())),
</code>```

Body:
enter image description here

enter image description here

Help post .... As you can see in the flutter code. I was trying to figure out how to see apps with colors and titles with a map inside a list, but I could see the titles. There was a problem with the colors. How can I fix this? So that I can see my color and title

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  final myCatagory = [
    {
      'title': 'Samsung',
      'color': Colors.pink[800],
    },
    {
      'title': 'Symphony',
      'color': Colors.tealAccent[800],
    },
    {
      'title': 'MI',
      'color': Colors.amberAccent[800],
    },
    {
      'title': 'Oppo',
      'color': Colors.blue[800],
    },
    {
      'title': 'Vivo',
      'color': Colors.redAccent[800],
    },
    {
      'title': 'Iphone',
      'color': Colors.greenAccent[800],
    },
  ];

  // final catagoryColors = [
  //   Colors.red,
  //   Colors.green,
  //   Colors.black87,
  // ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        title: const Text('My Blog'),
        backgroundColor: Colors.redAccent,
      ),
      body: Container(
        height: 150,
        child: ListView.builder(
          itemCount: myCatagory.length,
          shrinkWrap: true,
          primary: false,
          physics: BouncingScrollPhysics(),
          scrollDirection: Axis.horizontal,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(
                left: 10,
                top: 10,
              ),
              color: myCatagory[index]['color'], **The problem in this line**
              height: 200,
              width: 100,
              child: Text(
                '${myCatagory[index]['title']}',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 15,
                  fontWeight: FontWeight.w400,
                ),
              ),
            );
          },
        ),
      ),
    );
  }enter image description here

enter code here

Body:
You can add it as a hex value and parse it to int like:

 {
      'title': 'Symphony',
      'color': '0xFFB74093',
    },

color:  Color(int.parse(myCatagory[index]['color'].toString())),


问:
How to properly iterate Bigquery TableResult in Java
I am trying to iterate the rows from TableResult using getValues() as below.
if I use getValues(), it's retrieving only the first page rows. I want to iterate all the rows using getValues() and NOT using iterateAll().
In the below code, the problem is its going infinite time. not ending. while(results.hasNextPage()) is not ending. what is the problem in the below code?

```<code>    {
    query = "select from aa.bb.cc";
    QueryJobConfiguration queryConfig =
            QueryJobConfiguration.newBuilder(query)
                    .setPriority(QueryJobConfiguration.Priority.BATCH)
                    .build();
    TableResult results = bigquery.query(queryConfig);

    int i = 0;
    int j=0;
    while(results.hasNextPage()) {
        j++;
        System.out.println("page " + j);
        System.out.println("Data Extracted::" + i + " records");
        for (FieldValueList row : results.getNextPage().getValues()) {
            i++;
        }
    }
    System.out.println("Total Count::" + results.getTotalRows());
    System.out.println("Data Extracted::" + i + " records");
}
</code>```

I have only 200,000 records in the source table. below is the out put and I forcefully stopped the process.

```<code>page 1
Data Extracted::0 records
page 2
Data Extracted::85242 records
page 3
Data Extracted::170484 records
page 4
Data Extracted::255726 records
page 5
Data Extracted::340968 records
page 6
Data Extracted::426210 records
page 7
Data Extracted::511452 records
page 8
Data Extracted::596694 records
.......
.......
.......
.......
</code>```

答:
In short, you need to update TableResults variable with your getNextPage()  variable. If you don't update it you will always be looping the same results over and over. Thats why you are getting tons of records in your output.

If you check the following samples: Bigquery Pagination and Using Java Client Library. There are ways that we can deal with pagination results. Although not specific for single run queries.

As show on the code below, which is partially based on pagination sample, you need to use the output of getNextPage() to update results variable and proceed to perform the next iteration inside the while up until it iterates all pages but the last.

QueryRun.Java

```<code>package com.projects;

// [START bigquery_query]
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.TableResult;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobId;
import com.google.cloud.bigquery.FieldValueList;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.BigQuery.QueryResultsOption;
import java.util.UUID;

import sun.jvm.hotspot.debugger.Page;

public class QueryRun {

  public static void main(String[] args) {

    String projectId = "bigquery-public-data";
    String datasetName = "covid19_ecdc_eu";
    String tableName = "covid_19_geographic_distribution_worldwide";
    String query =
        "SELECT * "
            + " FROM `"
            + projectId
            + "."
            + datasetName
            + "."
            + tableName
            + "`"
            + " LIMIT 100";
    System.out.println(query);
    query(query);
  }

  public static void query(String query) {
    try {
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
      QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(query).build();

      // Create a job ID so that we can safely retry.
      JobId jobId = JobId.of(UUID.randomUUID().toString());
      Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

      TableResult results = queryJob.getQueryResults(QueryResultsOption.pageSize(10));

      int i = 0;
      int j =0;

      // get all paged data except last line
      while(results.hasNextPage()) {
        j++;
        for (FieldValueList row : results.getValues()) {
            i++;
        }
        results = results.getNextPage();
        print_msg(i,j);
      }

      // last line run
      j++;
      for (FieldValueList row : results.getValues()) {
        i++;
      }
      print_msg(i,j);

      System.out.println("Query performed successfully.");
    } catch (BigQueryException | InterruptedException e) {
      System.out.println("Query not performed \n" + e.toString());
    }
  }

  public static void print_msg(int i,int j)
  {
    System.out.println("page " + j);
    System.out.println("Data Extracted::" + i + " records");
  }

}
// [END bigquery_query]
</code>```

output:

```<code>SELECT *  FROM `bigquery-public-data.covid19_ecdc_eu.covid_19_geographic_distribution_worldwide` LIMIT 100
page 1
Data Extracted::10 records
page 2
Data Extracted::20 records
page 3
Data Extracted::30 records
page 4
Data Extracted::40 records
page 5
Data Extracted::50 records
page 6
Data Extracted::60 records
page 7
Data Extracted::70 records
page 8
Data Extracted::80 records
page 9
Data Extracted::90 records
page 10
Data Extracted::100 records
Query performed successfully.
</code>```

As a final note, there are not official sample about pagination for queries so I'm not totally sure of the recommended way to handle pagination with java. Its not quite clear on the BigQuery for Java documentation page. If you can update your question with your approach to pagination I would appreciate.

If you have issues running the attached sample please see Using the BigQuery Java client sample, its github page and its pom.xml file inside of it and check if you are in compliance with it.

Body:
I am trying to iterate the rows from TableResult using getValues() as below.
if I use getValues(), it's retrieving only the first page rows. I want to iterate all the rows using getValues() and NOT using iterateAll().
In the below code, the problem is its going infinite time. not ending. while(results.hasNextPage()) is not ending. what is the problem in the below code?

    {
    query = "select from aa.bb.cc";
    QueryJobConfiguration queryConfig =
            QueryJobConfiguration.newBuilder(query)
                    .setPriority(QueryJobConfiguration.Priority.BATCH)
                    .build();
    TableResult results = bigquery.query(queryConfig);

    int i = 0;
    int j=0;
    while(results.hasNextPage()) {
        j++;
        System.out.println("page " + j);
        System.out.println("Data Extracted::" + i + " records");
        for (FieldValueList row : results.getNextPage().getValues()) {
            i++;
        }
    }
    System.out.println("Total Count::" + results.getTotalRows());
    System.out.println("Data Extracted::" + i + " records");
}

I have only 200,000 records in the source table. below is the out put and I forcefully stopped the process.

page 1
Data Extracted::0 records
page 2
Data Extracted::85242 records
page 3
Data Extracted::170484 records
page 4
Data Extracted::255726 records
page 5
Data Extracted::340968 records
page 6
Data Extracted::426210 records
page 7
Data Extracted::511452 records
page 8
Data Extracted::596694 records
.......
.......
.......
.......

Body:
In short, you need to update TableResults variable with your getNextPage()  variable. If you don't update it you will always be looping the same results over and over. Thats why you are getting tons of records in your output.

If you check the following samples: Bigquery Pagination and Using Java Client Library. There are ways that we can deal with pagination results. Although not specific for single run queries.

As show on the code below, which is partially based on pagination sample, you need to use the output of getNextPage() to update results variable and proceed to perform the next iteration inside the while up until it iterates all pages but the last.

QueryRun.Java

package com.projects;

// [START bigquery_query]
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.TableResult;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobId;
import com.google.cloud.bigquery.FieldValueList;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.BigQuery.QueryResultsOption;
import java.util.UUID;

import sun.jvm.hotspot.debugger.Page;

public class QueryRun {

  public static void main(String[] args) {

    String projectId = "bigquery-public-data";
    String datasetName = "covid19_ecdc_eu";
    String tableName = "covid_19_geographic_distribution_worldwide";
    String query =
        "SELECT * "
            + " FROM `"
            + projectId
            + "."
            + datasetName
            + "."
            + tableName
            + "`"
            + " LIMIT 100";
    System.out.println(query);
    query(query);
  }

  public static void query(String query) {
    try {
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
      QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(query).build();

      // Create a job ID so that we can safely retry.
      JobId jobId = JobId.of(UUID.randomUUID().toString());
      Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

      TableResult results = queryJob.getQueryResults(QueryResultsOption.pageSize(10));

      int i = 0;
      int j =0;

      // get all paged data except last line
      while(results.hasNextPage()) {
        j++;
        for (FieldValueList row : results.getValues()) {
            i++;
        }
        results = results.getNextPage();
        print_msg(i,j);
      }

      // last line run
      j++;
      for (FieldValueList row : results.getValues()) {
        i++;
      }
      print_msg(i,j);

      System.out.println("Query performed successfully.");
    } catch (BigQueryException | InterruptedException e) {
      System.out.println("Query not performed \n" + e.toString());
    }
  }

  public static void print_msg(int i,int j)
  {
    System.out.println("page " + j);
    System.out.println("Data Extracted::" + i + " records");
  }

}
// [END bigquery_query]

output:

SELECT *  FROM `bigquery-public-data.covid19_ecdc_eu.covid_19_geographic_distribution_worldwide` LIMIT 100
page 1
Data Extracted::10 records
page 2
Data Extracted::20 records
page 3
Data Extracted::30 records
page 4
Data Extracted::40 records
page 5
Data Extracted::50 records
page 6
Data Extracted::60 records
page 7
Data Extracted::70 records
page 8
Data Extracted::80 records
page 9
Data Extracted::90 records
page 10
Data Extracted::100 records
Query performed successfully.

As a final note, there are not official sample about pagination for queries so I'm not totally sure of the recommended way to handle pagination with java. Its not quite clear on the BigQuery for Java documentation page. If you can update your question with your approach to pagination I would appreciate.

If you have issues running the attached sample please see Using the BigQuery Java client sample, its github page and its pom.xml file inside of it and check if you are in compliance with it.


问:
Can i do two jpa queries in one?
Im devloping a crud application in spring-boot and i was wondering if i can do these two queries and methods in one:

package com.celulaweb.crud.repository;

import com.celulaweb.crud.domain.Cidade;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface CidadeRepository extends JpaRepository<Cidade, Long> {

    @Query("select c from Cidade c where c.estado is null or c.estado = :estado")
    Page<Cidade> listarPorEstado(@Param("estado") String estado, Pageable pageable);

    @Query("select c from Cidade c where c.nome is null or c.nome like :nome")
    Page<Cidade> listarPorNomeTendo(@Param("nome") String nome, Pageable pageable);

}
```

These are queries from org.springframework.data.jpa.repository.Query
How can i merge these two?

答:
If you have the same Pageable on this methods try this

```<code>    @Query("""
        select c from Cidade c
        where (c.estado is null or (c.estado = :estado))
        and (c.nome is null or (c.nome like :nome))
     """
    )
    Page<Cidade> listarEntries(
        @Param("estado") estado: String,
        @Param("nome") nome: String,
        pageable: Pageable
    )
</code>```

Title: Can i do two jpa queries in one?

Body:
Im devloping a crud application in spring-boot and i was wondering if i can do these two queries and methods in one:

package com.celulaweb.crud.repository;

import com.celulaweb.crud.domain.Cidade;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface CidadeRepository extends JpaRepository<Cidade, Long> {

    @Query("select c from Cidade c where c.estado is null or c.estado = :estado")
    Page<Cidade> listarPorEstado(@Param("estado") String estado, Pageable pageable);

    @Query("select c from Cidade c where c.nome is null or c.nome like :nome")
    Page<Cidade> listarPorNomeTendo(@Param("nome") String nome, Pageable pageable);

}

These are queries from org.springframework.data.jpa.repository.Query
How can i merge these two?

Body:
If you have the same Pageable on this methods try this

    @Query("""
        select c from Cidade c
        where (c.estado is null or (c.estado = :estado))
        and (c.nome is null or (c.nome like :nome))
     """
    )
    Page<Cidade> listarEntries(
        @Param("estado") estado: String,
        @Param("nome") nome: String,
        pageable: Pageable
    )


问:
Trigger step in Bitbucket pipelines
I have a CI pipeline in Bitbucket which is building, testing and deploying an application.
The thing is that after the deploy I want to run selenium tests.
Selenium tests are in an another repository in Bitbucket and they have their own pipeline.

Is there a trigger step in the Bitbucket pipeline to trigger a pipeline when a previous one has finished?

I do not want to do a fake push to the test repository to trigger those tests.

答:
Top answers (this and this) are correct, they work.

Just adding that we found out (after a LOT of trial and error) that the user executing the pipeline must have WRITE permissions on the repo where the pipeline is invoked (even though his app password permissions were set to "WRITE" for repos and pipelines...)

Also, this works for executing pipelines in Bitbucket's cloud or on-premise, through local runners.

(Answering as I am lacking reputation for commenting)

Title: Trigger step in Bitbucket pipelines


问:
Unity3D get an Object in start Method
Hey im trying to get an object which is referenced in another script (dictionary).
But when i try to get the object in the start method it seems like the dictionary isnt populated jet.
Error: NullReferenceException: Object reference not set to an instance of an object

If I run this line of code in the update method it works completely fine.

Is there an easy way to let this line run after the dictionary is populated?

Grid Manager Script

Camera Movement Script

答:
Both your code snippets run in Start.

There is no way to predict in which order these two Start messages will be invoked (at least not from the user perspective).

To solve this kind of race conditions (see Order of execution for event functions).

The Awake function is called on all objects in the Scene before any object's Start function is called.

my general thumb-rule is:

Use Awake

to initialize the component itself where it doesn't depend on values
from other components.

E.g. initializing your fields, filling your collections, using GetComponent etc to initialize references (but stop there)

Use Start to then initialize things where you do depend on other components being already initialized.

Like in your case access the collections of the other component

This usually covers most of the cases.

In your case simply converting GridManager.Start to GridManager.Awake should already solve the issue.

Where this is not enough you either can start and tweak the Script Execution Order and basically enforce a certain order in which the event methods get invoked or implement a more complex event based initialization system

Title: Unity3D get an Object in start Method


问:
How to give a .tf file as input in Terraform Apply command?
I'm a beginner in Terraform.

I have a directory which contains 2 .tf files.

Now I want to run Terraform Apply on a selected .tf file & neglect the other one.

Can I do that? If yes, how? If no, why & what is the best practice?

答:
If you cant have terraform files in different folders like the other answers stated. You can try using my script GitHub repo for script

Which is a script that runs throughout a specific terraform file and outputs adds "-target=" to all modules names.


问:
Why my code is not showing the answer when i click button "Show Answer"
EDIT: Add a new 'Show answer' button to display the correct answer to the question. The answer is not visible when the question is retrieved but is only displayed when the 'Show answer' button is pressed. Make only one fetch request / question and you can display the answer using conditional rendering, for example. HELP NEEDED

const Trivia = () => {

```<code> const [question, setQuestion] = React.useState();
 const [showAnswer, setShowAnswer] = React.useState(false);

 const fetchQuestion = () => {
     fetch("https://opentdb.com/api.php?amount=1")
     .then((response) => response.json())
     .then((data) => {
      setQuestion(data.results[0].question);

     });
   };

    const answerToggler = () => setShowAnswer(prevAns => !prevAns)
     React.useEffect(() => {
         fetchQuestion();
     }, []);

 return(

 <div>
 <p> {question}</p>
 <button onClick={fetchQuestion}>New Question</button>
 {showAnswer && <h3>Correct Answer</h3>} **<= This is just an example because i don't know what i put there**
<button onClick={answerToggler}>Show Answer </button>

</div>
     );
</code>```

};

The idea is that the code retrieves the answer to the question by pressing the "show answer" button using only one fetch request. It should look like this:

答:
EDIT: I think your logic to show the answer is not correct.

Change this:

{showAnswer &&
Correct Answer
}

For this

{showAnswer ? (
Correct Answer
) : ""}

This is a conditional operator which is like an if. It is saying if(showAnswer === true) show the correct answer, else dont show anything

Body:
EDIT: Add a new 'Show answer' button to display the correct answer to the question. The answer is not visible when the question is retrieved but is only displayed when the 'Show answer' button is pressed. Make only one fetch request / question and you can display the answer using conditional rendering, for example. HELP NEEDED

const Trivia = () => {

 const [question, setQuestion] = React.useState();
 const [showAnswer, setShowAnswer] = React.useState(false);

 const fetchQuestion = () => {
     fetch("https://opentdb.com/api.php?amount=1")
     .then((response) => response.json())
     .then((data) => {
      setQuestion(data.results[0].question);

     });
   };

    const answerToggler = () => setShowAnswer(prevAns => !prevAns)
     React.useEffect(() => {
         fetchQuestion();
     }, []);

 return(

 {question}

 <button onClick={fetchQuestion}>New Question</button>
 {showAnswer &&
Correct Answer
} **<= This is just an example because i don't know what i put there**
<button onClick={answerToggler}>Show Answer </button>

     );

};

The idea is that the code retrieves the answer to the question by pressing the "show answer" button using only one fetch request. It should look like this:

Body:
EDIT: I think your logic to show the answer is not correct.

Change this:

{showAnswer && <h3>Correct Answer</h3>}

For this

{showAnswer ? (<h3>Correct Answer</h3>) : ""}

This is a conditional operator which is like an if. It is saying if(showAnswer === true) show the correct answer, else dont show anything


问:
implicit ansible file exists remote
I want to execute tasks only if a file exists on the target.

I can do that, of course, with

- ansible.builtin.stat:
  path: <remote_file>
  register: remote_file

- name: ...
  something:
  when: remote_file.stat.exists
```
<p>but is there something smaller?</p>
<p>You can, for example, check files on the host with</p>
<pre class="lang-yaml prettyprint-override"><code>when: '/tmp/file.txt' is file
</code>```

But that only checks files on host.

Is there also something like that available for files on remotes?

Added, as according the comment section I need to be bit more specific.

I want to run tasks on the target, and on the next run, they shouldn´t be executed again. So I thought to put a file somewhere on the target, and on the next run, when this file exists, the tasks should not be executed anymore.

- name: do big stuff
  bigsgtuff:
  when: not <file> exists
```

They should be executed, if the file does not exists.

答:
I am not aware of a way to let the Control Node know during templating or compile time if there exist a specific file on Remote Node(s).

I understand your question that you

... want to execute tasks on the target ...

only if a certain condition is met on the target.

This sounds to be impossible without taking a look on the target before or do a lookup somewhere else, in example in a Configuration Management Database (CMDB).

... is there something smaller?

It will depend on your task, what you try to achieve and how do you like to declare a configuration state.

In example, if you you like to declare the absence of a file, there is no need to check if it exists before. Just make sure it becomes deleted.

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: Remove file
    shell:
      cmd: "rm /home/{{ ansible_user }}/test.txt"
      warn: false
    register: result
    changed_when: result.rc != 1
    failed_when: result.rc != 0 and result.rc != 1

  - name: Show result
    debug:
      msg: "{{ result }}"
```
<p>As you see, it will be necessary to Defining failure and control how the task behaves. Another example for showing the content.</p>
<pre class="lang-yaml prettyprint-override"><code>---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: Gather file content
    shell:
      cmd: "cat /home/{{ ansible_user }}/test.txt"
    register: result
    changed_when: false
    failed_when: result.rc != 0 and result.rc != 1

  - name: Show result
    debug:
      msg: "{{ result.stdout }}"
</code>```

Please take note, for the given example tasks there are already specific Ansible modules available which do the job better.

According the additional given information in your comments I understand that you like to install or configure "something" and like to leave that fact left on the remote node(s). You like to run the task the next time on the remote node(s) in fact only if it is wasn't successful performed before.

To do so, you may have a look into Ansible facts and Discovering variables: facts and magic variables, especially into Adding custom facts.

What your installation or configuration tasks could do, is leaving a custom .fact file with meaningful keys and values after they were successful running.

During next playbook execution and if gather_facts: true, the information would be gathered from the setup module and you can than let tasks run based on conditions in ansible_local.

Further Q&A

How Ansible gather_facts and sets variables

An introduction to Ansible facts

Loading custom facts

Whereby the host facts can be considered as kind of distributed CMDB, by using facts Cache

```<code>fact_caching            = yaml
fact_caching_connection = /tmp/ansible/facts_cache
fact_caching_timeout    = 129600
</code>```

you can have the information also available on the Control Node. It might even be possible to organize it in host_vars and group_vars.

Title: implicit ansible file exists remote

Body:
I want to execute tasks only if a file exists on the target.

I can do that, of course, with

- ansible.builtin.stat:
  path: <remote_file>
  register: remote_file

- name: ...
  something:
  when: remote_file.stat.exists

but is there something smaller?

You can, for example, check files on the host with

when: '/tmp/file.txt' is file

But that only checks files on host.

Is there also something like that available for files on remotes?

Added, as according the comment section I need to be bit more specific.

I want to run tasks on the target, and on the next run, they shouldn´t be executed again. So I thought to put a file somewhere on the target, and on the next run, when this file exists, the tasks should not be executed anymore.

- name: do big stuff
  bigsgtuff:
  when: not <file> exists

They should be executed, if the file does not exists.

Body:
I am not aware of a way to let the Control Node know during templating or compile time if there exist a specific file on Remote Node(s).

I understand your question that you

... want to execute tasks on the target ...

only if a certain condition is met on the target.

This sounds to be impossible without taking a look on the target before or do a lookup somewhere else, in example in a Configuration Management Database (CMDB).

... is there something smaller?

It will depend on your task, what you try to achieve and how do you like to declare a configuration state.

In example, if you you like to declare the absence of a file, there is no need to check if it exists before. Just make sure it becomes deleted.

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: Remove file
    shell:
      cmd: "rm /home/{{ ansible_user }}/test.txt"
      warn: false
    register: result
    changed_when: result.rc != 1
    failed_when: result.rc != 0 and result.rc != 1

  - name: Show result
    debug:
      msg: "{{ result }}"

As you see, it will be necessary to Defining failure and control how the task behaves. Another example for showing the content.

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: Gather file content
    shell:
      cmd: "cat /home/{{ ansible_user }}/test.txt"
    register: result
    changed_when: false
    failed_when: result.rc != 0 and result.rc != 1

  - name: Show result
    debug:
      msg: "{{ result.stdout }}"

Please take note, for the given example tasks there are already specific Ansible modules available which do the job better.

According the additional given information in your comments I understand that you like to install or configure "something" and like to leave that fact left on the remote node(s). You like to run the task the next time on the remote node(s) in fact only if it is wasn't successful performed before.

To do so, you may have a look into Ansible facts and Discovering variables: facts and magic variables, especially into Adding custom facts.

What your installation or configuration tasks could do, is leaving a custom .fact file with meaningful keys and values after they were successful running.

During next playbook execution and if gather_facts: true, the information would be gathered from the setup module and you can than let tasks run based on conditions in ansible_local.

Further Q&A

How Ansible gather_facts and sets variables

An introduction to Ansible facts

Loading custom facts

Whereby the host facts can be considered as kind of distributed CMDB, by using facts Cache

fact_caching            = yaml
fact_caching_connection = /tmp/ansible/facts_cache
fact_caching_timeout    = 129600

you can have the information also available on the Control Node. It might even be possible to organize it in host_vars and group_vars.


问:
How to use angular library locally with hot reload? [Error: Cannot read properties of null (reading 'firstCreatePass')]
I have two angular projects locally, the first one is for the custom library (createApplication=false) and the second one is test-app;

Now I want to use custom library's components inside test-app, with hot reload;

What I am doing is:

Run npm run build --watch inside library

Run npm install ../library/dist/test-library inside test-app

Everything is fine except one run time error inside console: ERROR TypeError: Cannot read properties of null (reading 'firstCreatePass')

I am using this article as a guide: link

答:
You have only one last step to handle : config in angular.json.
Follow this article and you should be fine :

https://medium.com/@maravondra/angular-component-in-locale-usage-8536d91fc844

"preserveSymlinks": true
```


问:
variable declaration (implicit and explicit and advantages & disadvantages)
"What are explicit declaration & implicit declaration of variables in programming language concepts  and their advantages and disadvantages?"</p>

答:
Explicit variable declaration means that the type of the variable is declared before or when the variable is set. Implicit variable declaration means the type of the variable is assumed by the operators, but any data can be put in it.

In C,
int x = 5; printf(x-5); x = "test"; printf(x-5);
returns a compile time error when you set x to test

but in Python,
x = 5; print(x-5); x = "test"; print(x-5);
will "compile" (python doesn't compile, but it will run the program) and give you a runt time error when you try to subtract from the string.

One advantage of Implicit variables is that it makes it easier to write code without worrying about the behind the scenes data type, the compiler should pick the appropriate one based on its future usage.

Another advantage is that you can flexibly type a variable to hold different things that may not even share a parent class. Doing this is risky, as you have no guarantees that the objects will be interpreted correctly by following code.

One disadvantage is that Implicit variables have no guarantees of what they are. A function that computes the difference between two numbers will not return an compile time error if the variables have strings in them. You passed in two variables, it is up to you to ensure they are the right type. It also makes reading code harder in some ways. var nextLocation = LeftHandedSmokeShifter(3.3) is completely legitimate code, but You have to look up the function to even guess what it is doing. string nextLocation  = LeftHandedSmokeShifter(3.3) at least tells me that I should be using the output for mathematical operations.

Type heavy languages are always explicitly declared and typed, but type weak languages are mostly implicitly typed. If you can set a variable to "Var" it is likely an implicitly typed language.