问:
How to solve the error: Not allowed to start service Intent : app is in background uid?
I have a service which started by on booted completed event it, but the app crashes with the error message as in above. Please help on how can I start my Service on BroadCast receiver event of Boot_Completed.

MyService.kt

```<code>class MyService : Service() {

    override fun onCreate() {
        Log.d(TAG, "onCreate")
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        Log.d(TAG, "DO SOME STAFF")
    }
}
</code>```

MyBroadCaster.kt

```<code>class StartRelayServiceAtBootReceiver : BroadcastReceiver() {
     override fun onReceive(context: Context, intent: Intent) {

        if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
            val serviceIntent = Intent(context, MyService::class.java)
            context.startService(serviceIntent)
        }
    }
}
</code>```

答:
There are limitations on apps in the background. Obviously, if the device just booted, all apps are "in the background". You cannot start a Service from a background app. You probably need to use JobScheduler to to what you want.

See this document for a discussion about the limitations on background apps and how to migrate to other solutions that are allowed:

https://developer.android.com/about/versions/oreo/background

Body:
I have a service which started by on booted completed event it, but the app crashes with the error message as in above. Please help on how can I start my Service on BroadCast receiver event of Boot_Completed.

MyService.kt

class MyService : Service() {

    override fun onCreate() {
        Log.d(TAG, "onCreate")
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        Log.d(TAG, "DO SOME STAFF")
    }
}

MyBroadCaster.kt

class StartRelayServiceAtBootReceiver : BroadcastReceiver() {
     override fun onReceive(context: Context, intent: Intent) {

        if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
            val serviceIntent = Intent(context, MyService::class.java)
            context.startService(serviceIntent)
        }
    }
}


来源: stackexchange

问:
Waiting for client side Javascript to load with Axios GET request
What I'm trying to do is sync my work schedule with my Google Calendar. Now there isn't an API available so that's not an option, unfortunately. I'm able to successfully log in to my account and redirect to the page with the content. The only problem is that the site relies on client-side javascript that loads in the dates, etc.

Is there any way to have Axios wait a few seconds so the dates can load in and then return the body contents? I've been looking around the internet but couldn't find any answers to my question.

This is the code I'm using right now.

```<code>axios.post('link here', {
    Username: 0,
    Password: 0
}).then((res) => {
    axios.get('link here', {headers: {
        "Cookie":res.headers['set-cookie']}}, {}).then((res) => {
        console.log(res.data)
    });
});
</code>```

So I'm looking for a way to let it load the page and then return res.data.

答:
This is not possible with axios.
What the browser does is it fetches the html (like your get call) and renders any dynamic content by executing the javascript linked to the html

Axios will simply return the raw html and since it is not a browser you won't get anything else.

If you are absolutely sure there aren't any api integrations ala: https://developers.google.com/calendar, you can use https://github.com/puppeteer/puppeteer instead.

Puppeteer, unlike axios, will render the page and run any linked javascript for you. Its a headhless chrome browser that you can control via javascript. That's the right tool for this job.

Alternatively, instead of fetching the raw HTML, you can figure out what calls the javascript function is executing instead (probably a get call to another link)

ContentLicense: CC BY-SA 4.0

Body:
What I'm trying to do is sync my work schedule with my Google Calendar. Now there isn't an API available so that's not an option, unfortunately. I'm able to successfully log in to my account and redirect to the page with the content. The only problem is that the site relies on client-side javascript that loads in the dates, etc.

Is there any way to have Axios wait a few seconds so the dates can load in and then return the body contents? I've been looking around the internet but couldn't find any answers to my question.

This is the code I'm using right now.

axios.post('link here', {
    Username: 0,
    Password: 0
}).then((res) => {
    axios.get('link here', {headers: {
        "Cookie":res.headers['set-cookie']}}, {}).then((res) => {
        console.log(res.data)
    });
});

So I'm looking for a way to let it load the page and then return res.data.


问:
How to convert a targeting code in python to kotlin?
I am developing an image segmentation application that will use watersheds. For that, I found a code that I will need to use in python. However, I'm having a hard time converting to kotlin, as the Mat Mat () doesn't have the zero_likes function, just the zero function. I am using opencv 3.31. How do I do this check in kotlin:

```<code>marked[marked == 1] = 0
marked[marked > 1] = 255
</code>```

Code python:

```<code>import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load the image
img = cv2.imread("/path/to/image.png", 3)

# Create a blank image of zeros (same dimension as img)
# It should be grayscale (1 color channel)
marker = np.zeros_like(img[:,:,0]).astype(np.int32)

# This step is manual. The goal is to find the points
# which create the result we want. I suggest using a
# tool to get the pixel coordinates.

# Dictate the background and set the markers to 1
marker[204][95] = 1
marker[240][137] = 1
marker[245][444] = 1
marker[260][427] = 1
marker[257][378] = 1
marker[217][466] = 1

# Dictate the area of interest
# I used different values for each part of the car (for visibility)
marker[235][370] = 255    # car body
marker[135][294] = 64     # rooftop
marker[190][454] = 64     # rear light
marker[167][458] = 64     # rear wing
marker[205][103] = 128    # front bumper

# rear bumper
marker[225][456] = 128
marker[224][461] = 128
marker[216][461] = 128

# front wheel
marker[225][189] = 192
marker[240][147] = 192

# rear wheel
marker[258][409] = 192
marker[257][391] = 192
marker[254][421] = 192

# Now we have set the markers, we use the watershed
# algorithm to generate a marked image
marked = cv2.watershed(img, marker)

# Plot this one. If it does what we want, proceed;
# otherwise edit your markers and repeat
plt.imshow(marked, cmap='gray')
plt.show()

# Make the background black, and what we want to keep white
marked[marked == 1] = 0
marked[marked > 1] = 255

# Use a kernel to dilate the image, to not lose any detail on the outline
# I used a kernel of 3x3 pixels
kernel = np.ones((3,3),np.uint8)
dilation = cv2.dilate(marked.astype(np.float32), kernel, iterations = 1)

# Plot again to check whether the dilation is according to our needs
# If not, repeat by using a smaller/bigger kernel, or more/less iterations
plt.imshow(dilation, cmap='gray')
plt.show()

# Now apply the mask we created on the initial image
final_img = cv2.bitwise_and(img, img, mask=dilation.astype(np.uint8))

# cv2.imread reads the image as BGR, but matplotlib uses RGB
# BGR to RGB so we can plot the image with accurate colors
b, g, r = cv2.split(final_img)
final_img = cv2.merge([r, g, b])

# Plot the final result
plt.imshow(final_img)
plt.show()
</code>```

code kotlin:

```<code> // Load the image
   val srcOriginal = Imgcodecs.imread(currentPhotoPath)

    // Create a blank image of zeros (same dimension as img)
    // It should be grayscale (1 color channel)
    val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32S)

    // This step is manual. The goal is to find the points
    // which create the result we want. I suggest using a
    // tool to get the pixel coordinates.

    // Dictate the area of interest
    for(x in my_canvas.pointsToDrawX.indices) {
        for(y in my_canvas.pointsToDrawY.indices) {
            markers.put(
                my_canvas.pointsToDrawX.get(x).toInt(),
                my_canvas.pointsToDrawY.get(y).toInt(),
                255.0
            )
        }
    }
    //Now we have set the markers, we use the watershed
    //algorithm to generate a marked image
    Imgproc.watershed(srcOriginal, markers)
    val marker_tempo = Mat()
    markers.convertTo(marker_tempo, CvType.CV_8U)
    // Plot this one. If it does what we want, proceed;
    // otherwise edit your markers and repeat
    //Create Bitmap
    val bmpOut = Bitmap.createBitmap(srcOriginal.cols(), srcOriginal.rows(), Bitmap.Config.RGB_565)
    Utils.matToBitmap(marker_tempo, bmpOut)
    val mPath = Environment.getExternalStorageDirectory().toString() + "/gray.png"
    Imgcodecs.imwrite(mPath,marker_tempo)
    //Make the background black, and what we want to keep white

    //Use a kernel to dilate the image, to not lose any detail on the outline
    //I used a kernel of 3x3 pixels
    val kernel = Mat(3, 3, CvType.CV_8U)
    val dilatation = Imgproc.dilate(marker_tempo, marker_tempo, kernel)
    val mPath1 = Environment.getExternalStorageDirectory().toString() + "/dilation.png"
    Imgcodecs.imwrite(mPath1,marker_tempo)
    //Now apply the mask we created on the initial image
    val final_image = Core.bitwise_and(srcOriginal, srcOriginal, dilatation)
    //cv2.imread reads the image as BGR, but matplotlib uses RGB
    //BGR to RGB so we can plot the image with accurate colors
</code>```

In pointsToDrawX and pointsToDrawY I'm saving all the x, y coordinates of the user's touch event on the screen. It is from these coordinates that I will pass to the watershed algorithm to perform the segmentation and remove the background from the image. Can someone help me convert this code?

答:
numpy.zeros_like basically creates an array the same shape as the input with all zeros in it.

https://numpy.org/doc/stable/reference/generated/numpy.zeros_like.html

In this case, you have a simple 2d array so you could roll your own just by indexing through the whole array (all dimensions) and setting everything to zero.

```<code>var marker = Array(srcOriginal.rows()) {Array(srcOriginal.cols()) {0} }
</code>```

Body:
I am developing an image segmentation application that will use watersheds. For that, I found a code that I will need to use in python. However, I'm having a hard time converting to kotlin, as the Mat Mat () doesn't have the zero_likes function, just the zero function. I am using opencv 3.31. How do I do this check in kotlin:

marked[marked == 1] = 0
marked[marked > 1] = 255

Code python:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load the image
img = cv2.imread("/path/to/image.png", 3)

# Create a blank image of zeros (same dimension as img)
# It should be grayscale (1 color channel)
marker = np.zeros_like(img[:,:,0]).astype(np.int32)

# This step is manual. The goal is to find the points
# which create the result we want. I suggest using a
# tool to get the pixel coordinates.

# Dictate the background and set the markers to 1
marker[204][95] = 1
marker[240][137] = 1
marker[245][444] = 1
marker[260][427] = 1
marker[257][378] = 1
marker[217][466] = 1

# Dictate the area of interest
# I used different values for each part of the car (for visibility)
marker[235][370] = 255    # car body
marker[135][294] = 64     # rooftop
marker[190][454] = 64     # rear light
marker[167][458] = 64     # rear wing
marker[205][103] = 128    # front bumper

# rear bumper
marker[225][456] = 128
marker[224][461] = 128
marker[216][461] = 128

# front wheel
marker[225][189] = 192
marker[240][147] = 192

# rear wheel
marker[258][409] = 192
marker[257][391] = 192
marker[254][421] = 192

# Now we have set the markers, we use the watershed
# algorithm to generate a marked image
marked = cv2.watershed(img, marker)

# Plot this one. If it does what we want, proceed;
# otherwise edit your markers and repeat
plt.imshow(marked, cmap='gray')
plt.show()

# Make the background black, and what we want to keep white
marked[marked == 1] = 0
marked[marked > 1] = 255

# Use a kernel to dilate the image, to not lose any detail on the outline
# I used a kernel of 3x3 pixels
kernel = np.ones((3,3),np.uint8)
dilation = cv2.dilate(marked.astype(np.float32), kernel, iterations = 1)

# Plot again to check whether the dilation is according to our needs
# If not, repeat by using a smaller/bigger kernel, or more/less iterations
plt.imshow(dilation, cmap='gray')
plt.show()

# Now apply the mask we created on the initial image
final_img = cv2.bitwise_and(img, img, mask=dilation.astype(np.uint8))

# cv2.imread reads the image as BGR, but matplotlib uses RGB
# BGR to RGB so we can plot the image with accurate colors
b, g, r = cv2.split(final_img)
final_img = cv2.merge([r, g, b])

# Plot the final result
plt.imshow(final_img)
plt.show()

code kotlin:

 // Load the image
   val srcOriginal = Imgcodecs.imread(currentPhotoPath)

    // Create a blank image of zeros (same dimension as img)
    // It should be grayscale (1 color channel)
    val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32S)

    // This step is manual. The goal is to find the points
    // which create the result we want. I suggest using a
    // tool to get the pixel coordinates.

    // Dictate the area of interest
    for(x in my_canvas.pointsToDrawX.indices) {
        for(y in my_canvas.pointsToDrawY.indices) {
            markers.put(
                my_canvas.pointsToDrawX.get(x).toInt(),
                my_canvas.pointsToDrawY.get(y).toInt(),
                255.0
            )
        }
    }
    //Now we have set the markers, we use the watershed
    //algorithm to generate a marked image
    Imgproc.watershed(srcOriginal, markers)
    val marker_tempo = Mat()
    markers.convertTo(marker_tempo, CvType.CV_8U)
    // Plot this one. If it does what we want, proceed;
    // otherwise edit your markers and repeat
    //Create Bitmap
    val bmpOut = Bitmap.createBitmap(srcOriginal.cols(), srcOriginal.rows(), Bitmap.Config.RGB_565)
    Utils.matToBitmap(marker_tempo, bmpOut)
    val mPath = Environment.getExternalStorageDirectory().toString() + "/gray.png"
    Imgcodecs.imwrite(mPath,marker_tempo)
    //Make the background black, and what we want to keep white

    //Use a kernel to dilate the image, to not lose any detail on the outline
    //I used a kernel of 3x3 pixels
    val kernel = Mat(3, 3, CvType.CV_8U)
    val dilatation = Imgproc.dilate(marker_tempo, marker_tempo, kernel)
    val mPath1 = Environment.getExternalStorageDirectory().toString() + "/dilation.png"
    Imgcodecs.imwrite(mPath1,marker_tempo)
    //Now apply the mask we created on the initial image
    val final_image = Core.bitwise_and(srcOriginal, srcOriginal, dilatation)
    //cv2.imread reads the image as BGR, but matplotlib uses RGB
    //BGR to RGB so we can plot the image with accurate colors

In pointsToDrawX and pointsToDrawY I'm saving all the x, y coordinates of the user's touch event on the screen. It is from these coordinates that I will pass to the watershed algorithm to perform the segmentation and remove the background from the image. Can someone help me convert this code?

Body:
numpy.zeros_like basically creates an array the same shape as the input with all zeros in it.

https://numpy.org/doc/stable/reference/generated/numpy.zeros_like.html

In this case, you have a simple 2d array so you could roll your own just by indexing through the whole array (all dimensions) and setting everything to zero.

var marker = Array(srcOriginal.rows()) {Array(srcOriginal.cols()) {0} }


问:
Swift: How to get shadow working on UITextView from ViewDidLoad?
I'm unable to get the shadow on UITextView which is inside of a UIImageView.

I tried many possible ways. The constrain is, I cannot override layoutMethods as they are not accessible for some reason. So, for a demonstration, I've put the same code in viewDidLoad to debug but couldn't figure it out. Please explain what I'm doing wrong here.

```<code>    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .black
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "guitar")
        imageView.layer.cornerRadius = 15
        imageView.clipsToBounds = true

        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.heightAnchor.constraint(equalToConstant: 240).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 240).isActive = true
        imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        let textView = UITextView(frame: CGRect.zero)
        textView.text = "This is a Sample text. This is a Sample text. This is a Sample text. This is a Sample text. This is a Sample text. "
        textView.isEditable = false
        textView.textAlignment = .left
        textView.isSelectable = false
        textView.backgroundColor = .systemBlue
        textView.textColor = UIColor.white
        textView.sizeToFit()
        textView.isScrollEnabled = false
        textView.textContainerInset = UIEdgeInsets(top: 6, left: 7, bottom: 6, right: 7)
        textView.clipsToBounds = false
        textView.layer.shadowColor = UIColor.gray.cgColor
        textView.layer.shadowRadius = 10
        textView.layer.opacity = 1
        textView.layer.shadowOffset = .zero
        textView.layer.shadowPath = UIBezierPath(rect: textView.bounds).cgPath
        textView.layer.masksToBounds = false

        imageView.addSubview(textView)
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.leftAnchor.constraint(equalTo: imageView.leftAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true
        textView.rightAnchor.constraint(equalTo: imageView.rightAnchor).isActive = true
    }
</code>```

答:
You set the LAYER opacity to 1:

```<code>textView.layer.opacity = 1
</code>```

but you need to set the layer's shadowOpacity:

```<code>//textView.layer.opacity = 1

textView.layer.shadowOpacity = 1
</code>```

That should fix the issue.

By the way, you get the same result with or without the .shadowPath (since the "default" shadow path is the bounds / rect of the view).

Body:
I'm unable to get the shadow on UITextView which is inside of a UIImageView.

I tried many possible ways. The constrain is, I cannot override layoutMethods as they are not accessible for some reason. So, for a demonstration, I've put the same code in viewDidLoad to debug but couldn't figure it out. Please explain what I'm doing wrong here.

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .black
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "guitar")
        imageView.layer.cornerRadius = 15
        imageView.clipsToBounds = true

        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.heightAnchor.constraint(equalToConstant: 240).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 240).isActive = true
        imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        let textView = UITextView(frame: CGRect.zero)
        textView.text = "This is a Sample text. This is a Sample text. This is a Sample text. This is a Sample text. This is a Sample text. "
        textView.isEditable = false
        textView.textAlignment = .left
        textView.isSelectable = false
        textView.backgroundColor = .systemBlue
        textView.textColor = UIColor.white
        textView.sizeToFit()
        textView.isScrollEnabled = false
        textView.textContainerInset = UIEdgeInsets(top: 6, left: 7, bottom: 6, right: 7)
        textView.clipsToBounds = false
        textView.layer.shadowColor = UIColor.gray.cgColor
        textView.layer.shadowRadius = 10
        textView.layer.opacity = 1
        textView.layer.shadowOffset = .zero
        textView.layer.shadowPath = UIBezierPath(rect: textView.bounds).cgPath
        textView.layer.masksToBounds = false

        imageView.addSubview(textView)
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.leftAnchor.constraint(equalTo: imageView.leftAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true
        textView.rightAnchor.constraint(equalTo: imageView.rightAnchor).isActive = true
    }

Body:
You set the LAYER opacity to 1:

textView.layer.opacity = 1

but you need to set the layer's shadowOpacity:

//textView.layer.opacity = 1

textView.layer.shadowOpacity = 1

That should fix the issue.

By the way, you get the same result with or without the .shadowPath (since the "default" shadow path is the bounds / rect of the view).


问:
Number of rows UPDATED and INSERTED from the same procedure in PL/SQL
I have a procedure that does the INSERT INTO and then the UPDATE of some fields (both in the same procedure), I'm using this answer from @Clive Number of rows affected by an UPDATE in PL/SQLto know the amount of data that has been updated to put in a log, but it brings me the total number of rows instead of just the records that have been updated.

Is that the right way to know?

What I need is to know how many rows were INSERTED from the INSERT STATEMENT and how many rows were UPDATED from the UPDATE STATEMENT.

My query:

```<code>CREATE OR REPLACE PROCEDURE OWNER.TABLE_NAME
AS

 -- VARIABLE
 v_qtd_regs  number := 0;
 v_code      number;
 v_errm      VARCHAR2(500);
 start_time  pls_integer;
 end_time    pls_integer;
 elapse_time number;
 proc_name   varchar2(100);
 i NUMBER;

BEGIN
   proc_name := 'PRDWBI_CGA_D_COLUMNS';
   start_time := dbms_utility.get_time;
   DS_FUNCESP.PRDSBI_GRAVA_LOG( 'I', 'DataWarehouse', proc_name, 'Início Carga' );

   -- INSERT INTO TABLE:
   INSERT INTO OWNER.TABLE_NAME
   (COLUMN_ID, COLUMNS_NAME, COLUMN_NAME2)
   (SELECT 1 AS COLUMN_ID, 'TEST' AS COLUMN_NAME, SYSDATE AS COLUMN_NAME2 FROM DUAL);

   COMMIT;

  -- UPDATE SOME COLUMNS I NEED
   UPDATE OWNER.TABLE_NAME y
   SET (y.COLUMNS_NAME, y.COLUMN_NAME2) =
               (SELECT 'TEST2' AS COLUMN_NAME, SYSDATE AS COLUMN_NAME2 FROM DUAL x WHERE x.COLUMN_ID = y.COLUMN_ID)
   WHERE EXISTS (SELECT 'TEST2' AS COLUMN_NAME, SYSDATE AS COLUMN_NAME2 FROM DUAL x WHERE x.COLUMN_ID = y.COLUMN_ID);

   -- TO KNOW HOW MANY ROWS WERE UPDATED
   i := SQL%rowcount;

   COMMIT;

   --dbms_output.Put_line(i);

   SELECT COUNT(1) INTO v_qtd_regs FROM OWNER.TABLE_NAME where LinData >= TRUNC(SYSDATE);
   end_time := dbms_utility.get_time;
   elapse_time := ((end_time - start_time)/100);
   v_errm := SUBSTR(SQLERRM, 1 , 500);
   DS_FUNCESP.PRDSBI_GRAVA_LOG('T', 'DataWarehouse', proc_name, v_errm, v_qtd_regs, elapse_time );

   COMMIT;

EXCEPTION
   WHEN OTHERS THEN
      v_code := SQLCODE;
      v_errm := SUBSTR(SQLERRM, 1 , 500);
      DS_FUNCESP.PRDSBI_GRAVA_LOG('E', 'Error', proc_name, v_errm);

END;
</code>```

QUESTION EDITED TO SHOW A REAL EXAMPLE:

I created a table that takes data from "SYS.DBA_TAB_COLUMNS" just to use as an example, as shown below:

```<code>  CREATE TABLE "DW_FUNCESP"."D_TEST"
    (
        "ID_COLUMN" NUMBER(10,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1
        START WITH 1 CACHE 20 NOORDER NOCYCLE NOKEEP NOSCALE NOT NULL ENABLE,
        "NM_OWNER"  VARCHAR2(500 CHAR) NOT NULL ENABLE                       ,
        "NM_TABLE"  VARCHAR2(500 CHAR) NOT NULL ENABLE                       ,
        "CD_COLUMN" NUMBER(20,0) NOT NULL ENABLE                             ,
        "NM_COLUMN" VARCHAR2(500 CHAR) NOT NULL ENABLE                       ,
        "DS_COLUMN" VARCHAR2(500 CHAR) NOT NULL ENABLE                       ,
        "LINDATE"   DATE DEFAULT SYSDATE NOT NULL ENABLE                     ,
        "LINORIGIN" VARCHAR2(100 CHAR) NOT NULL ENABLE
    )
</code>```

Then I created a procedure to identify the inserted and updated records, as below:

```<code>CREATE OR REPLACE PROCEDURE DW_FUNCESP.PRDWBI_CGA_D_TEST
AS

 -- variaveis de suporte as informações que deve gravar
 rows_inserted integer;
 rows_updated  integer;

BEGIN

   -- Insert Into table
   INSERT INTO DW_Funcesp.D_TEST
   (NM_OWNER, NM_TABLE, CD_COLUMN, NM_COLUMN, DS_COLUMN, LINDATE, LINORIGIN)
   (SELECT
      NVL(x.NM_OWNER ,'NOT FOUND')      AS NM_OWNER     ,
      NVL(x.NM_TABLE ,'NOT FOUND')      AS NM_TABLE     ,
      NVL(x.CD_COLUMN ,-1)              AS CD_COLUMN    ,
      NVL(x.NM_COLUMN ,'NOT FOUND')     AS NM_COLUMN    ,
      NVL(x.DS_COLUMN ,x.NM_COLUMN)     AS DS_COLUMN    ,
      SYSDATE                           AS LINDATE      ,
      'SYS.DBA_TAB_COLUMNS'             AS LINORIGIN
    FROM
      (
        SELECT
          d.OWNER       AS NM_OWNER ,
          d.TABLE_NAME  AS NM_TABLE ,
          d.COLUMN_ID   AS CD_COLUMN,
          d.COLUMN_NAME AS NM_COLUMN,
          e.COMMENTS    AS DS_COLUMN
        FROM SYS.DBA_TAB_COLUMNS d
        LEFT JOIN SYS.DBA_COL_COMMENTS e
          ON e.OWNER           = d.OWNER
          AND e.TABLE_NAME  = d.TABLE_NAME
          AND e.COLUMN_NAME = d.COLUMN_NAME
        WHERE d.OWNER = 'DW_FUNCESP'
       ) x
    LEFT JOIN DW_FUNCESP.D_TEST y
      ON  y.NM_OWNER = x.NM_OWNER
      AND y.NM_TABLE = x.NM_TABLE
      AND y.NM_COLUMN = x.NM_COLUMN
    WHERE y.ID_COLUMN IS NULL);

    rows_inserted := sql%rowcount;

  -- Update the table
   UPDATE DW_FUNCESP.D_TEST z
   SET (z.NM_COLUMN, z.DS_COLUMN, z.LINDATE) =
                  (SELECT
                      NVL(x.NM_COLUMN ,'NOT FOUND')     AS NM_COLUMN    ,
                      NVL(x.DS_COLUMN ,x.NM_COLUMN)     AS DS_COLUMN    ,
                      SYSDATE                           AS LINDATE
                    FROM
                      (
                        SELECT
                          d.OWNER       AS NM_OWNER ,
                          d.TABLE_NAME  AS NM_TABLE ,
                          d.COLUMN_ID   AS CD_COLUMN,
                          d.COLUMN_NAME AS NM_COLUMN,
                          e.COMMENTS    AS DS_COLUMN
                        FROM SYS.DBA_TAB_COLUMNS d
                        LEFT JOIN SYS.DBA_COL_COMMENTS e
                          ON e.OWNER           = d.OWNER
                          AND e.TABLE_NAME  = d.TABLE_NAME
                          AND e.COLUMN_NAME = d.COLUMN_NAME
                        WHERE d.OWNER = 'DW_FUNCESP'
                       ) x
                    WHERE z.NM_OWNER = x.NM_OWNER
                      AND z.NM_TABLE = x.NM_TABLE
                      AND z.CD_COLUMN = x.CD_COLUMN)
   WHERE EXISTS (SELECT
                      NVL(x.NM_COLUMN ,'NOT FOUND')     AS NM_COLUMN    ,
                      NVL(x.DS_COLUMN ,x.NM_COLUMN)     AS DS_COLUMN    ,
                      SYSDATE                           AS LINDATE
                    FROM
                      (
                        SELECT
                          d.OWNER       AS NM_OWNER ,
                          d.TABLE_NAME  AS NM_TABLE ,
                          d.COLUMN_ID   AS CD_COLUMN,
                          d.COLUMN_NAME AS NM_COLUMN,
                          e.COMMENTS    AS DS_COLUMN
                        FROM SYS.DBA_TAB_COLUMNS d
                        LEFT JOIN SYS.DBA_COL_COMMENTS e
                          ON e.OWNER           = d.OWNER
                          AND e.TABLE_NAME  = d.TABLE_NAME
                          AND e.COLUMN_NAME = d.COLUMN_NAME
                        WHERE d.OWNER = 'DW_FUNCESP'
                       ) x
                    WHERE z.NM_OWNER = x.NM_OWNER
                      AND z.NM_TABLE = x.NM_TABLE
                      AND z.CD_COLUMN = x.CD_COLUMN);

   rows_updated := sql%rowcount;

   dbms_output.Put_line('inserted=>' || to_char(rows_inserted) || ', updated=>' || to_char(rows_updated));

   COMMIT;

EXCEPTION
   WHEN OTHERS THEN
      RAISE;

END;
</code>```

So my first insert output was:

inserted=>2821, updated=>2821

So I chose a data to be changed and it was updated, I made the following select to choose which data should be updated to bring in the DBMS output again:

```<code>SELECT * FROM DW_FUNCESP.D_TEST WHERE NM_TABLE = 'D_TEST';
</code>```

I commented in a column as shown in the image, to bring in the update:

```<code>COMMENT ON COLUMN DW_FUNCESP.D_TEST.LINORIGIN IS 'The origin of the data';
</code>```

I ran the procedure again, and the output was:

inserted=>0, updated=>2821

The result for that update:

Shouldn't you have brought just 1 updated data in the output, as only 1 updated? And not all the rows?

e.g.: inserted=>0, updated=>1

So my question remains, am I asking it correctly? Is it possible to obtain this result in the same procedure? Is it the update that is incorrect (despite having updated the data)?

答:
I would use ORA_SCN as the other answers suggest if you are interested what rows have been inserted or updated. But you want only to know how many, so I would leave the counting to Oracle (might be timeconsuming for larger number of rows).

Please have a look at the data dictionary view USER_TAB_MODIFICATIONS (or ALL_TAB_MODIFICATIONS if the table is in another schema than the procedure.

```<code>CREATE TABLE d (
  id  NUMBER GENERATED ALWAYS AS IDENTITY,
  dt  DATE DEFAULT SYSDATE,
  foo VARCHAR2(128 BYTE)
);
</code>```

Gathering the table statistics will reset the modifications view:

```<code>EXEC DBMS_STATS.GATHER_TABLE_STATS(NULL,'D');
</code>```

Now after your INSERT, the modifications view will have the number of inserted rows:

```<code>INSERT INTO d(foo) SELECT object_name FROM all_objects;
67,141 rows inserted.

SELECT inserts, updates, deletes FROM user_tab_modifications WHERE table_name='D';
INSERTS UPDATES DELETES
  67141       0       0
</code>```

Likewise, after the UPDATE, the updated rows:

```<code>UPDATE d SET foo=lower(foo),dt=SYSDATE WHERE mod(id,10)=0;
6,714 rows updated.

SELECT inserts, updates, deletes FROM user_tab_modifications WHERE table_name='D';
INSERTS UPDATES DELETES
  67141    6714       0
</code>```

For clarity, I've used SQL instead of PL/SQL. You might have to grant some special privs to the schema containing the procedure. Add a comment with my name if you run into problems with that.

Body:
I have a procedure that does the INSERT INTO and then the UPDATE of some fields (both in the same procedure), I'm using this answer from @Clive Number of rows affected by an UPDATE in PL/SQLto know the amount of data that has been updated to put in a log, but it brings me the total number of rows instead of just the records that have been updated.

Is that the right way to know?

What I need is to know how many rows were INSERTED from the INSERT STATEMENT and how many rows were UPDATED from the UPDATE STATEMENT.

My query:

CREATE OR REPLACE PROCEDURE OWNER.TABLE_NAME
AS

 -- VARIABLE
 v_qtd_regs  number := 0;
 v_code      number;
 v_errm      VARCHAR2(500);
 start_time  pls_integer;
 end_time    pls_integer;
 elapse_time number;
 proc_name   varchar2(100);
 i NUMBER;

BEGIN
   proc_name := 'PRDWBI_CGA_D_COLUMNS';
   start_time := dbms_utility.get_time;
   DS_FUNCESP.PRDSBI_GRAVA_LOG( 'I', 'DataWarehouse', proc_name, 'Início Carga' );

   -- INSERT INTO TABLE:
   INSERT INTO OWNER.TABLE_NAME
   (COLUMN_ID, COLUMNS_NAME, COLUMN_NAME2)
   (SELECT 1 AS COLUMN_ID, 'TEST' AS COLUMN_NAME, SYSDATE AS COLUMN_NAME2 FROM DUAL);

   COMMIT;

  -- UPDATE SOME COLUMNS I NEED
   UPDATE OWNER.TABLE_NAME y
   SET (y.COLUMNS_NAME, y.COLUMN_NAME2) =
               (SELECT 'TEST2' AS COLUMN_NAME, SYSDATE AS COLUMN_NAME2 FROM DUAL x WHERE x.COLUMN_ID = y.COLUMN_ID)
   WHERE EXISTS (SELECT 'TEST2' AS COLUMN_NAME, SYSDATE AS COLUMN_NAME2 FROM DUAL x WHERE x.COLUMN_ID = y.COLUMN_ID);

   -- TO KNOW HOW MANY ROWS WERE UPDATED
   i := SQL%rowcount;

   COMMIT;

   --dbms_output.Put_line(i);

   SELECT COUNT(1) INTO v_qtd_regs FROM OWNER.TABLE_NAME where LinData >= TRUNC(SYSDATE);
   end_time := dbms_utility.get_time;
   elapse_time := ((end_time - start_time)/100);
   v_errm := SUBSTR(SQLERRM, 1 , 500);
   DS_FUNCESP.PRDSBI_GRAVA_LOG('T', 'DataWarehouse', proc_name, v_errm, v_qtd_regs, elapse_time );

   COMMIT;

EXCEPTION
   WHEN OTHERS THEN
      v_code := SQLCODE;
      v_errm := SUBSTR(SQLERRM, 1 , 500);
      DS_FUNCESP.PRDSBI_GRAVA_LOG('E', 'Error', proc_name, v_errm);

END;

QUESTION EDITED TO SHOW A REAL EXAMPLE:

I created a table that takes data from "SYS.DBA_TAB_COLUMNS" just to use as an example, as shown below:

  CREATE TABLE "DW_FUNCESP"."D_TEST"
    (
        "ID_COLUMN" NUMBER(10,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1
        START WITH 1 CACHE 20 NOORDER NOCYCLE NOKEEP NOSCALE NOT NULL ENABLE,
        "NM_OWNER"  VARCHAR2(500 CHAR) NOT NULL ENABLE                       ,
        "NM_TABLE"  VARCHAR2(500 CHAR) NOT NULL ENABLE                       ,
        "CD_COLUMN" NUMBER(20,0) NOT NULL ENABLE                             ,
        "NM_COLUMN" VARCHAR2(500 CHAR) NOT NULL ENABLE                       ,
        "DS_COLUMN" VARCHAR2(500 CHAR) NOT NULL ENABLE                       ,
        "LINDATE"   DATE DEFAULT SYSDATE NOT NULL ENABLE                     ,
        "LINORIGIN" VARCHAR2(100 CHAR) NOT NULL ENABLE
    )

Then I created a procedure to identify the inserted and updated records, as below:

CREATE OR REPLACE PROCEDURE DW_FUNCESP.PRDWBI_CGA_D_TEST
AS

 -- variaveis de suporte as informações que deve gravar
 rows_inserted integer;
 rows_updated  integer;

BEGIN

   -- Insert Into table
   INSERT INTO DW_Funcesp.D_TEST
   (NM_OWNER, NM_TABLE, CD_COLUMN, NM_COLUMN, DS_COLUMN, LINDATE, LINORIGIN)
   (SELECT
      NVL(x.NM_OWNER ,'NOT FOUND')      AS NM_OWNER     ,
      NVL(x.NM_TABLE ,'NOT FOUND')      AS NM_TABLE     ,
      NVL(x.CD_COLUMN ,-1)              AS CD_COLUMN    ,
      NVL(x.NM_COLUMN ,'NOT FOUND')     AS NM_COLUMN    ,
      NVL(x.DS_COLUMN ,x.NM_COLUMN)     AS DS_COLUMN    ,
      SYSDATE                           AS LINDATE      ,
      'SYS.DBA_TAB_COLUMNS'             AS LINORIGIN
    FROM
      (
        SELECT
          d.OWNER       AS NM_OWNER ,
          d.TABLE_NAME  AS NM_TABLE ,
          d.COLUMN_ID   AS CD_COLUMN,
          d.COLUMN_NAME AS NM_COLUMN,
          e.COMMENTS    AS DS_COLUMN
        FROM SYS.DBA_TAB_COLUMNS d
        LEFT JOIN SYS.DBA_COL_COMMENTS e
          ON e.OWNER           = d.OWNER
          AND e.TABLE_NAME  = d.TABLE_NAME
          AND e.COLUMN_NAME = d.COLUMN_NAME
        WHERE d.OWNER = 'DW_FUNCESP'
       ) x
    LEFT JOIN DW_FUNCESP.D_TEST y
      ON  y.NM_OWNER = x.NM_OWNER
      AND y.NM_TABLE = x.NM_TABLE
      AND y.NM_COLUMN = x.NM_COLUMN
    WHERE y.ID_COLUMN IS NULL);

    rows_inserted := sql%rowcount;

  -- Update the table
   UPDATE DW_FUNCESP.D_TEST z
   SET (z.NM_COLUMN, z.DS_COLUMN, z.LINDATE) =
                  (SELECT
                      NVL(x.NM_COLUMN ,'NOT FOUND')     AS NM_COLUMN    ,
                      NVL(x.DS_COLUMN ,x.NM_COLUMN)     AS DS_COLUMN    ,
                      SYSDATE                           AS LINDATE
                    FROM
                      (
                        SELECT
                          d.OWNER       AS NM_OWNER ,
                          d.TABLE_NAME  AS NM_TABLE ,
                          d.COLUMN_ID   AS CD_COLUMN,
                          d.COLUMN_NAME AS NM_COLUMN,
                          e.COMMENTS    AS DS_COLUMN
                        FROM SYS.DBA_TAB_COLUMNS d
                        LEFT JOIN SYS.DBA_COL_COMMENTS e
                          ON e.OWNER           = d.OWNER
                          AND e.TABLE_NAME  = d.TABLE_NAME
                          AND e.COLUMN_NAME = d.COLUMN_NAME
                        WHERE d.OWNER = 'DW_FUNCESP'
                       ) x
                    WHERE z.NM_OWNER = x.NM_OWNER
                      AND z.NM_TABLE = x.NM_TABLE
                      AND z.CD_COLUMN = x.CD_COLUMN)
   WHERE EXISTS (SELECT
                      NVL(x.NM_COLUMN ,'NOT FOUND')     AS NM_COLUMN    ,
                      NVL(x.DS_COLUMN ,x.NM_COLUMN)     AS DS_COLUMN    ,
                      SYSDATE                           AS LINDATE
                    FROM
                      (
                        SELECT
                          d.OWNER       AS NM_OWNER ,
                          d.TABLE_NAME  AS NM_TABLE ,
                          d.COLUMN_ID   AS CD_COLUMN,
                          d.COLUMN_NAME AS NM_COLUMN,
                          e.COMMENTS    AS DS_COLUMN
                        FROM SYS.DBA_TAB_COLUMNS d
                        LEFT JOIN SYS.DBA_COL_COMMENTS e
                          ON e.OWNER           = d.OWNER
                          AND e.TABLE_NAME  = d.TABLE_NAME
                          AND e.COLUMN_NAME = d.COLUMN_NAME
                        WHERE d.OWNER = 'DW_FUNCESP'
                       ) x
                    WHERE z.NM_OWNER = x.NM_OWNER
                      AND z.NM_TABLE = x.NM_TABLE
                      AND z.CD_COLUMN = x.CD_COLUMN);

   rows_updated := sql%rowcount;

   dbms_output.Put_line('inserted=>' || to_char(rows_inserted) || ', updated=>' || to_char(rows_updated));

   COMMIT;

EXCEPTION
   WHEN OTHERS THEN
      RAISE;

END;

So my first insert output was:

inserted=>2821, updated=>2821

So I chose a data to be changed and it was updated, I made the following select to choose which data should be updated to bring in the DBMS output again:

SELECT * FROM DW_FUNCESP.D_TEST WHERE NM_TABLE = 'D_TEST';

I commented in a column as shown in the image, to bring in the update:

COMMENT ON COLUMN DW_FUNCESP.D_TEST.LINORIGIN IS 'The origin of the data';

I ran the procedure again, and the output was:

inserted=>0, updated=>2821

The result for that update:

Shouldn't you have brought just 1 updated data in the output, as only 1 updated? And not all the rows?

e.g.: inserted=>0, updated=>1

So my question remains, am I asking it correctly? Is it possible to obtain this result in the same procedure? Is it the update that is incorrect (despite having updated the data)?

Body:
I would use ORA_SCN as the other answers suggest if you are interested what rows have been inserted or updated. But you want only to know how many, so I would leave the counting to Oracle (might be timeconsuming for larger number of rows).

Please have a look at the data dictionary view USER_TAB_MODIFICATIONS (or ALL_TAB_MODIFICATIONS if the table is in another schema than the procedure.

CREATE TABLE d (
  id  NUMBER GENERATED ALWAYS AS IDENTITY,
  dt  DATE DEFAULT SYSDATE,
  foo VARCHAR2(128 BYTE)
);

Gathering the table statistics will reset the modifications view:

EXEC DBMS_STATS.GATHER_TABLE_STATS(NULL,'D');

Now after your INSERT, the modifications view will have the number of inserted rows:

INSERT INTO d(foo) SELECT object_name FROM all_objects;
67,141 rows inserted.

SELECT inserts, updates, deletes FROM user_tab_modifications WHERE table_name='D';
INSERTS UPDATES DELETES
  67141       0       0

Likewise, after the UPDATE, the updated rows:

UPDATE d SET foo=lower(foo),dt=SYSDATE WHERE mod(id,10)=0;
6,714 rows updated.

SELECT inserts, updates, deletes FROM user_tab_modifications WHERE table_name='D';
INSERTS UPDATES DELETES
  67141    6714       0

For clarity, I've used SQL instead of PL/SQL. You might have to grant some special privs to the schema containing the procedure. Add a comment with my name if you run into problems with that.


问:
git report files changed on which I did not work
git status reports a large set of file to be “new”, “modified” and “deleted” in a directory tree I never worked in. In Subversion  I would do a svn revert --recursive iPhone (I don't work on the iPhone version of the App) and be done with. But with Git things are not easy. With Git everything it is always complicated.

So I am in bit of a panic because the iPhone team would tear me apart if I mess up there code. And it would be a mayor mess as more then 50 files are reported changed.

Can anybody help me?

答:
If you're afraid of losing work, you should be able to use git stash to squirrel away your local changes in case you need them later. This will give you a clean working directory and still allow you to access your uncommitted changes if you need them later. From the man page:

Use git stash when you want to record
  the current state of the working
  directory and the index, but want to
  go back to a clean working directory.
  The command saves your local
  modifications away and reverts the
  working directory to match the HEAD
  commit.

The modifications stashed away by this
  command can be listed with git stash
  list, inspected with git stash show,
  and restored (potentially on top of a
  different commit) with git stash
  apply. Calling git stash without any
  arguments is equivalent to git stash
  save. A stash is by default listed as
  "WIP on branchname …", but you can
  give a more descriptive message on the
  command line when you create one.

The latest stash you created is stored
  in refs/stash; older stashes are found
  in the reflog of this reference and
  can be named using the usual reflog
  syntax (e.g. stash@{0} is the most
  recently created stash, stash@{1} is
  the one before it, stash@{2.hours.ago}
  is also possible).

ContentLicense: CC BY-SA 3.0


问:
didDetermineStateForRegion not fired when restarting bluetooth
I'm trying to fix a bug that occurs when, running my app (ionic 4) on an android device and monitoring for beacons regions i turn off the device bluetooth and then turn it on again.

This the process:

run my app with bluetooth on

startMonitoringForRegion

didDetermineStateForRegion --> works

Turn Off device bluetooth

stopMonitoringForRegion

Turn On device bluetooth

didDetermineStateForRegion is not fired

IMPORTANT --> Ugly solution with setTimeout --> SOLVE THE ISSUE
--> Here a stackoverflow with this workaround.

---------- HERE MY BEACONS OBJECT

```<code>this.beaconsFromJson = [
  {
    identifier: 'Mini S/N 018727',
    uuid: 'my-beacon-uuid',
    major: 1,
    minor: 18727,
    notifyEntryStateOnDisplay: false
  },
  {
    identifier: 'Mini S/N 018730',
    uuid: 'my-beacon-uuid',
    major: 1,
    minor: 18730,
    notifyEntryStateOnDisplay: false
  }
];
</code>```

---------- HERE MY SCAN FUNCTION

```<code>scan() {

_.forEach( this.beaconsFromJson, beacon => {

  const beaconRegion = this.ibeacon.BeaconRegion(
    beacon.identifier,
    beacon.uuid,
    beacon.major,
    beacon.minor,
    beacon.notifyEntryStateOnDisplay
  )

  this.ibeacon.startMonitoringForRegion(beaconRegion).then(
    () => console.log('Start monitoring' + beaconRegion.identifier),
    (error) =>
      console.error('Native layer failed to begin monitoring: ', error)
  );

}) // end foreach

setTimeout( () => {
  this.delegate.didDetermineStateForRegion().subscribe((data: IBeaconPluginResult) => {
    switch (data.state) {
      case 'CLRegionStateInside':
        this.beacons.push(data.region);
        this.loadingService.loading$.next({status: false});
        break;
      case 'CLRegionStateOutside':
        this.loadingService.loading$.next({status: false});
        this.beacons = this.beacons.filter(beacon => beacon.identifier !== data.region.identifier);
        break;
      default:
        break;
    }
  })
}, 1); // Ugly but it works --> https://stackoverflow.com/a/25211343/4197536
}
</code>```

When i start my app with bluetooth OFF and then i turn it ON -> It
works as expected.

When i start my app with bluetooth ON and then i turn it OFF and ON
again --> Cannot read property 'subscribe' of undefined (that
subscription i do to didDetermineStateForRegion())

Nb: This script works, but i'm looking for a better solution!

答:
The question describes this sequence:

stopMonitoringForRegion

Turn On device bluetooth

didDetermineStateForRegion is not fired

The last bullet point is expected because monitoring was stopped in the first bullet point.  In order to get a didDetermineStateForRegion callback, monitoring must be started.

Body:
I'm trying to fix a bug that occurs when, running my app (ionic 4) on an android device and monitoring for beacons regions i turn off the device bluetooth and then turn it on again.

This the process:

run my app with bluetooth on

startMonitoringForRegion

didDetermineStateForRegion --> works

Turn Off device bluetooth

stopMonitoringForRegion

Turn On device bluetooth

didDetermineStateForRegion is not fired

IMPORTANT --> Ugly solution with setTimeout --> SOLVE THE ISSUE
--> Here a stackoverflow with this workaround.

---------- HERE MY BEACONS OBJECT

this.beaconsFromJson = [
  {
    identifier: 'Mini S/N 018727',
    uuid: 'my-beacon-uuid',
    major: 1,
    minor: 18727,
    notifyEntryStateOnDisplay: false
  },
  {
    identifier: 'Mini S/N 018730',
    uuid: 'my-beacon-uuid',
    major: 1,
    minor: 18730,
    notifyEntryStateOnDisplay: false
  }
];

---------- HERE MY SCAN FUNCTION

scan() {

_.forEach( this.beaconsFromJson, beacon => {

  const beaconRegion = this.ibeacon.BeaconRegion(
    beacon.identifier,
    beacon.uuid,
    beacon.major,
    beacon.minor,
    beacon.notifyEntryStateOnDisplay
  )

  this.ibeacon.startMonitoringForRegion(beaconRegion).then(
    () => console.log('Start monitoring' + beaconRegion.identifier),
    (error) =>
      console.error('Native layer failed to begin monitoring: ', error)
  );

}) // end foreach

setTimeout( () => {
  this.delegate.didDetermineStateForRegion().subscribe((data: IBeaconPluginResult) => {
    switch (data.state) {
      case 'CLRegionStateInside':
        this.beacons.push(data.region);
        this.loadingService.loading$.next({status: false});
        break;
      case 'CLRegionStateOutside':
        this.loadingService.loading$.next({status: false});
        this.beacons = this.beacons.filter(beacon => beacon.identifier !== data.region.identifier);
        break;
      default:
        break;
    }
  })
}, 1); // Ugly but it works --> https://stackoverflow.com/a/25211343/4197536
}

When i start my app with bluetooth OFF and then i turn it ON -> It
works as expected.

When i start my app with bluetooth ON and then i turn it OFF and ON
again --> Cannot read property 'subscribe' of undefined (that
subscription i do to didDetermineStateForRegion())

Nb: This script works, but i'm looking for a better solution!


问:
Reactive nesting forms. Getting error cannot read property 'hasError' of undefined
I used reactive nesting forms of angular 8 with angular material.

in component.ts file

```<code>this.dataForm = this.formBuilder.group({
     name: [null, Validators.required],
     user: this.formBuilder.group({
        firstname: [null, Validators.required],
        lastname: [null, Validators.required]
     })
});

get dataControls() {
  return this.dataForm.controls;
}
</code>```

In component.html file

```<code><form [formGroup]="dataForm">
  <mat-form-field>
     <mat-label>Name</mat-label>
     <input matInput type="text" formControlName="name" required>
     <mat-error *ngIf="dataControls.name.hasError('required')">Name required</mat-error>
  </mat-form-field>
  <div formGroupName="user">
  <mat-form-field>
     <mat-label>First Name</mat-label>
     <input matInput type="text" formControlName="firstname" required>
     <mat-error *ngIf="dataControls.firstname.hasError('required')">Firstname required</mat-error>
  </mat-form-field>
  <mat-form-field>
     <mat-label>Last Name</mat-label>
     <input matInput type="text" formControlName="lastname" required>
     <mat-error *ngIf="dataControls.lastname.hasError('required')">Lastname required</mat-error>
  </mat-form-field>
  </div>
</form>
</code>```

Getting error cannot read property 'hasError' of undefined. I tried like

<mat-error *ngIf="dataControls.user.firstname.hasError('required')">Firstname required</mat-error>

But not work

答:
You have a FormGroup in a FormGroup so:

```<code>*ngIf="dataControls.user.controls.firstname.hasError('required')"
</code>```

In typescript, you will need to cast (to avoid syntax error) :

```<code>(<FormGroup>this.dataControls.user).controls.firstname.hasError('required')
</code>```

EDIT:

There is a better way, typescript side:

```<code>this.dataControls.user.get('firstname').hasError('required');
</code>```

Body:
I used reactive nesting forms of angular 8 with angular material.

in component.ts file

this.dataForm = this.formBuilder.group({
     name: [null, Validators.required],
     user: this.formBuilder.group({
        firstname: [null, Validators.required],
        lastname: [null, Validators.required]
     })
});

get dataControls() {
  return this.dataForm.controls;
}

In component.html file

<form [formGroup]="dataForm">
  <mat-form-field>
     <mat-label>Name</mat-label>
     <input matInput type="text" formControlName="name" required>
     <mat-error *ngIf="dataControls.name.hasError('required')">Name required</mat-error>
  </mat-form-field>

  <mat-form-field>
     <mat-label>First Name</mat-label>
     <input matInput type="text" formControlName="firstname" required>
     <mat-error *ngIf="dataControls.firstname.hasError('required')">Firstname required</mat-error>
  </mat-form-field>
  <mat-form-field>
     <mat-label>Last Name</mat-label>
     <input matInput type="text" formControlName="lastname" required>
     <mat-error *ngIf="dataControls.lastname.hasError('required')">Lastname required</mat-error>
  </mat-form-field>

</form>

Getting error cannot read property 'hasError' of undefined. I tried like

<mat-error *ngIf="dataControls.user.firstname.hasError('required')">Firstname required</mat-error>

But not work

Body:
You have a FormGroup in a FormGroup so:

*ngIf="dataControls.user.controls.firstname.hasError('required')"

In typescript, you will need to cast (to avoid syntax error) :

(<FormGroup>this.dataControls.user).controls.firstname.hasError('required')

EDIT:

There is a better way, typescript side:

this.dataControls.user.get('firstname').hasError('required');


问:
Binding to ViewModel on ListView shows nothing but works fine on other controls
I'm trying to bind an ObservableCollection sitting in my ViewModel class to a ListView that uses a GridView for displaying rows but I am unable to show my data in the list.

For testing purposes I put a TextBlock and can successfully show the data with Binding (however only if I do DataContext = ViewModel in code behind first, doing ViewModel.MyData in XAML does not work)

I've noticed that whatever ItemsSource is bound to, there is always a random number of empty element showing in the list, I can tell that since when I hover my mouse on the ListView the rows highlight. This number does not match the capacity of my collection.

If in code behind I manually set the ItemsSource to the collection I want to display, the correct number of element then shows up but there are still no data displayed.

XAML

```<code><Page x:Class="GestionStockWPF.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:GestionStockWPF"
      mc:Ignorable="d"
      d:DesignHeight="450" d:DesignWidth="800"
      Title="MainPage"
      ShowsNavigationUI="False">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="13*"/>
            <RowDefinition Height="77*"/>
        </Grid.RowDefinitions>

        <!-- The Binding here seems to do nothing, there isn't the correct amount of rows in the app -->

        <ListView x:Name="listView"
                  HorizontalAlignment="Stretch"
                  Grid.Row="1" Margin="30, 0, 30, 30"
                  ItemsSource="{Binding Source=Tests}">
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Path=A}"
                        Header="Asset Number" Width="200"/>
                </GridView>
            </ListView.View>
        </ListView>

        <!-- This textblock is just here for testing purposes, it successfully shows "A" -->

        <TextBlock x:Name="textBlock" Text="{Binding Path=Tests[0].A}"
                   HorizontalAlignment="Left" Margin="252,28,0,0" TextWrapping="Wrap"
                   VerticalAlignment="Top"/>
    </Grid>
</Page>
</code>```

Code Behind File

```<code>using System.Windows;
using System.Windows.Controls;

namespace GestionStockWPF
{
    public partial class MainPage : Page
    {
        public MainPageViewModel ViewModel;
        public MainPage()
        {
            InitializeComponent();
            ViewModel = new MainPageViewModel();

            // If I do DataContext = this;
            // and then set the binding of the TextBlock to "ViewModel.Tests[0].A" nothing is shown
            DataContext = ViewModel;

            // If I don't do that the listview does not contain the correct number of rows
            listView.ItemsSource = ViewModel.tests;
        }
    }
}
</code>```

ViewModel & Test class

```<code>using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace GestionStockWPF
{
    // Not sure if I have to implement INotifyPropertyChanged but my real class does it
    public class Test : INotifyPropertyChanged
    {
        public string A { get { return "A"; } }
        public string B { get { return "B"; } }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
    public class MainPageViewModel
    {
        public ObservableCollection<Test> Tests { get; set; }
        public MainPageViewModel()
        {
            tests = new ObservableCollection<Test>();
            for (int i = 0; i < 50; ++i)
            {
                Tests.Add(new Test());
            }
        }
    }
}
</code>```

答:
Your binding is incorrect.

It should be:

```<code>ItemsSource="{Binding tests}"
</code>```

You need to specify the path in the binding, not the binding source.

The explicit Path part is optional in a binding, so you also can change your text block binding to:

```<code>Text="{Binding tests[0].A}"
</code>```

By the way, the properties should use PascalCase, so better call it Tests.

Body:
I'm trying to bind an ObservableCollection sitting in my ViewModel class to a ListView that uses a GridView for displaying rows but I am unable to show my data in the list.

For testing purposes I put a TextBlock and can successfully show the data with Binding (however only if I do DataContext = ViewModel in code behind first, doing ViewModel.MyData in XAML does not work)

I've noticed that whatever ItemsSource is bound to, there is always a random number of empty element showing in the list, I can tell that since when I hover my mouse on the ListView the rows highlight. This number does not match the capacity of my collection.

If in code behind I manually set the ItemsSource to the collection I want to display, the correct number of element then shows up but there are still no data displayed.

XAML

<Page x:Class="GestionStockWPF.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:GestionStockWPF"
      mc:Ignorable="d"
      d:DesignHeight="450" d:DesignWidth="800"
      Title="MainPage"
      ShowsNavigationUI="False">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="13*"/>
            <RowDefinition Height="77*"/>
        </Grid.RowDefinitions>

        <ListView x:Name="listView"
                  HorizontalAlignment="Stretch"
                  Grid.Row="1" Margin="30, 0, 30, 30"
                  ItemsSource="{Binding Source=Tests}">
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Path=A}"
                        Header="Asset Number" Width="200"/>
                </GridView>
            </ListView.View>
        </ListView>

        <TextBlock x:Name="textBlock" Text="{Binding Path=Tests[0].A}"
                   HorizontalAlignment="Left" Margin="252,28,0,0" TextWrapping="Wrap"
                   VerticalAlignment="Top"/>
    </Grid>
</Page>

Code Behind File

using System.Windows;
using System.Windows.Controls;

namespace GestionStockWPF
{
    public partial class MainPage : Page
    {
        public MainPageViewModel ViewModel;
        public MainPage()
        {
            InitializeComponent();
            ViewModel = new MainPageViewModel();

            // If I do DataContext = this;
            // and then set the binding of the TextBlock to "ViewModel.Tests[0].A" nothing is shown
            DataContext = ViewModel;

            // If I don't do that the listview does not contain the correct number of rows
            listView.ItemsSource = ViewModel.tests;
        }
    }
}

ViewModel & Test class

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace GestionStockWPF
{
    // Not sure if I have to implement INotifyPropertyChanged but my real class does it
    public class Test : INotifyPropertyChanged
    {
        public string A { get { return "A"; } }
        public string B { get { return "B"; } }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
    public class MainPageViewModel
    {
        public ObservableCollection<Test> Tests { get; set; }
        public MainPageViewModel()
        {
            tests = new ObservableCollection<Test>();
            for (int i = 0; i < 50; ++i)
            {
                Tests.Add(new Test());
            }
        }
    }
}

Body:
Your binding is incorrect.

It should be:

ItemsSource="{Binding tests}"

You need to specify the path in the binding, not the binding source.

The explicit Path part is optional in a binding, so you also can change your text block binding to:

Text="{Binding tests[0].A}"

By the way, the properties should use PascalCase, so better call it Tests.


问:
Partial output with reversed question marks when sending SMS with GSM900A module
I am using Arduino Uno along with GSM 900A Module to send SMS to my phone. This is the code

```<code>#include <SoftwareSerial.h>

SoftwareSerial mySerial(9, 10);

void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop()
{
  if (Serial.available()>0)
   switch(Serial.read())
  {
    case 's':
      mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
     delay(1000);  // Delay of 1 second
     mySerial.println("AT+CMGS=\"+91xxxxxxxxxx\"\r"); // Replace x with mobile number 91 is country code
     delay(1000);
     mySerial.println("Hi");// The SMS text you want to send
     delay(100);
     mySerial.println((char)26);// ASCII code of CTRL+Z for saying the end of sms to  the module
      delay(1000);
      break;

    case 'r':
      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
      break;
  }

 if (mySerial.available()>0)
   Serial.write(mySerial.read());
}
</code>```

This is the output I get
https://imgur.com/a/YYhfP8c

The GSM Module is showing Blue Light for Status and Yellow Light is stable for network meaning that the network is good for the module. Also, the TX light on Uno glows continuously but the RX light never glows

答: In my experience this is due to power supply issues (noise and lack of power). Try to power up the modem using at least 2A external power supply and use multiple 10nF or 100nF capacitors parallel to the VCC GND pins of the modem.</p>

Body:
I am using Arduino Uno along with GSM 900A Module to send SMS to my phone. This is the code

#include <SoftwareSerial.h>

SoftwareSerial mySerial(9, 10);

void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop()
{
  if (Serial.available()>0)
   switch(Serial.read())
  {
    case 's':
      mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
     delay(1000);  // Delay of 1 second
     mySerial.println("AT+CMGS=\"+91xxxxxxxxxx\"\r"); // Replace x with mobile number 91 is country code
     delay(1000);
     mySerial.println("Hi");// The SMS text you want to send
     delay(100);
     mySerial.println((char)26);// ASCII code of CTRL+Z for saying the end of sms to  the module
      delay(1000);
      break;

    case 'r':
      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
      break;
  }

 if (mySerial.available()>0)
   Serial.write(mySerial.read());
}

This is the output I get
https://imgur.com/a/YYhfP8c

The GSM Module is showing Blue Light for Status and Yellow Light is stable for network meaning that the network is good for the module. Also, the TX light on Uno glows continuously but the RX light never glows


问:
Why my code does not write the results to the file?
I am writing a code that reads the characters from a file, and then if one of these characters is 'A' it should be changed to 'Z', after these changes are made it should write it back to the file (not append, but write), but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me (since I tried correcting it by making some changes, here is the code I have so far:</p>

```<code>int main(){
    char variable1[2000000];
    FILE *filePointer1;
    FILE *filePointer2;
    int counter;
    int exact_char_numb;

    filePointer1 = fopen("File.txt", "r");
    filePointer2 = fopen("File.txt", "w");
    fread(variable1,2000000,sizeof(char), filePointer1);

    for(counter = 0; counter<= 2000000 ; counter ++){
        if(variable1[counter] == 'A'){
            variable1[counter] = 'Z';
        }
        if(variable1[counter] == '+'){
            exact_char_numb = counter; // I am using '+' to mark the end of
        }                              // the file (for now)
    }

    fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);

    printf("%s\n", variable1);
    printf("%d\n", exact_char_numb);

    return 0;
}
</code>```

答:
"but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me..."

You should check whether the opening of the streams to file.txt were successful by checking the returned pointers for a null pointer before doing any operations with the streams:

```<code>if (!(filePointer1 = fopen("File.txt", "r")))
{
    fputs("Error occurred at opening file to read!", stderr);
    exit(1);
}

if (!(filePointer2 = fopen("File.txt", "w")))
{
    fputs("Error occurred at opening file to write!\n", stderr);
    exit(1);
}
</code>```

Furthermore, you don´t need to do have two pointers to two different streams. Use r+ mode:

```<code>if (!(filePointer = fopen("File.txt", "r+")))
{
    fputs("Error occurred at opening file!", stderr);
    exit(1);
}
</code>```

Body:
I am writing a code that reads the characters from a file, and then if one of these characters is 'A' it should be changed to 'Z', after these changes are made it should write it back to the file (not append, but write), but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me (since I tried correcting it by making some changes, here is the code I have so far:

int main(){
    char variable1[2000000];
    FILE *filePointer1;
    FILE *filePointer2;
    int counter;
    int exact_char_numb;

    filePointer1 = fopen("File.txt", "r");
    filePointer2 = fopen("File.txt", "w");
    fread(variable1,2000000,sizeof(char), filePointer1);

    for(counter = 0; counter<= 2000000 ; counter ++){
        if(variable1[counter] == 'A'){
            variable1[counter] = 'Z';
        }
        if(variable1[counter] == '+'){
            exact_char_numb = counter; // I am using '+' to mark the end of
        }                              // the file (for now)
    }

    fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);

    printf("%s\n", variable1);
    printf("%d\n", exact_char_numb);

    return 0;
}

Body:
"but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me..."

You should check whether the opening of the streams to file.txt were successful by checking the returned pointers for a null pointer before doing any operations with the streams:

if (!(filePointer1 = fopen("File.txt", "r")))
{
    fputs("Error occurred at opening file to read!", stderr);
    exit(1);
}

if (!(filePointer2 = fopen("File.txt", "w")))
{
    fputs("Error occurred at opening file to write!\n", stderr);
    exit(1);
}

Furthermore, you don´t need to do have two pointers to two different streams. Use r+ mode:

if (!(filePointer = fopen("File.txt", "r+")))
{
    fputs("Error occurred at opening file!", stderr);
    exit(1);
}


问:
Pass generic parameter optionally?
I have the following NetworkUseCase interface which processes a network request. P is the type of requestData and R the type of responseData.

```<code>interface NetworkUseCase<in P, out R> {
    fun process(requestData: P) : R
}
</code>```

The way it is normally used is the following:

```<code>class ConcreteUseCase : NetworkUseCase<ConcreteRequestData, ConcreteResponseData> {
    override fun process(requestData: ConcreteRequestData): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(requestData)
</code>```

However, there are some use cases where there are no requestData needed. In that case, there should be no requestData argument passed. But I am not sure how to achieve that.

```<code>val responseData = ConcreteUseCase().process()
</code>```

What I have done so far is to set the type of requestData to Unit but then I still need to pass Unit as a parameter:

```<code>class ConcreteUseCase : NetworkUseCase<Unit, ConcreteResponseData> {
    override fun process(requestData: Unit): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(Unit)
</code>```

Is there a way to achieve not being forced to always pass an argument in process()?

答:
You could also define a type alias for a NetworkUseCase without request data:

```<code>typealias NoRequestDataNetworkUseCase<R> = NetworkUseCase<Unit, R>
</code>```

and add an extension function to the type alias like @Tenfour04 mentioned.

```<code>fun <T> NoRequestDataNetworkUseCase<T>.process() = process(Unit)
</code>```

so you will use it like this:

```<code>class ConcreteUseCase : NoRequestDataNetworkUseCase<ConcreteResponseData> {
    override fun process(requestData: Unit): ConcreteResponseData {
        // ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process()
</code>```

But I also think is better to define a different abstraction for network use cases that doesn't need request data.

```<code>interface NoRequestDataNetworkUseCase<out R> {
    fun process() : R
}
</code>```

Title: Pass generic parameter optionally?

Body:
I have the following NetworkUseCase interface which processes a network request. P is the type of requestData and R the type of responseData.

interface NetworkUseCase<in P, out R> {
    fun process(requestData: P) : R
}

The way it is normally used is the following:

class ConcreteUseCase : NetworkUseCase<ConcreteRequestData, ConcreteResponseData> {
    override fun process(requestData: ConcreteRequestData): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(requestData)

However, there are some use cases where there are no requestData needed. In that case, there should be no requestData argument passed. But I am not sure how to achieve that.

val responseData = ConcreteUseCase().process()

What I have done so far is to set the type of requestData to Unit but then I still need to pass Unit as a parameter:

class ConcreteUseCase : NetworkUseCase<Unit, ConcreteResponseData> {
    override fun process(requestData: Unit): ConcreteResponseData {
        ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process(Unit)

Is there a way to achieve not being forced to always pass an argument in process()?

Body:
You could also define a type alias for a NetworkUseCase without request data:

typealias NoRequestDataNetworkUseCase<R> = NetworkUseCase<Unit, R>

and add an extension function to the type alias like @Tenfour04 mentioned.

fun <T> NoRequestDataNetworkUseCase<T>.process() = process(Unit)

so you will use it like this:

class ConcreteUseCase : NoRequestDataNetworkUseCase<ConcreteResponseData> {
    override fun process(requestData: Unit): ConcreteResponseData {
        // ...
    }
}

// It is called like this
val responseData = ConcreteUseCase().process()

But I also think is better to define a different abstraction for network use cases that doesn't need request data.

interface NoRequestDataNetworkUseCase<out R> {
    fun process() : R
}


问:
Chrome and Firefox are not able to access iPhone Camera
The below code of HTML

```<code><video id="video" class="video" height="400" width="400" playsinline autoplay muted loop></video>
</code>```

and JavaScript

```<code>var video = document.getElementById("video");

navigator.mediaDevices.getUserMedia({video: true, audio: false})
    .then(function(s) {
    stream = s;
    video.srcObject = s;
    video.play();
  })
</code>```

The link works fine on all Browsers in Android device, also works fine on Safari browser of iPhone devices, but it does not even ask camera permission for other Browsers like Chrome and Firefox on iPhone Devices.

答:
Chrome on iOS (13.1.1) is able to access both front and rear cameras using html5 proper input tag for image capture, but yeah still a bummer they don't support the getUserMedia for video streaming.

Here's a fiddle

```<code>For Front:
<input type="file" accept="image/*" capture="user">

For Rear:
<input type="file" accept="image/*" capture="environment">
</code>```

Body:
The below code of HTML

<video id="video" class="video" height="400" width="400" playsinline autoplay muted loop></video>

and JavaScript

var video = document.getElementById("video");

navigator.mediaDevices.getUserMedia({video: true, audio: false})
    .then(function(s) {
    stream = s;
    video.srcObject = s;
    video.play();
  })

The link works fine on all Browsers in Android device, also works fine on Safari browser of iPhone devices, but it does not even ask camera permission for other Browsers like Chrome and Firefox on iPhone Devices.

Body:
Chrome on iOS (13.1.1) is able to access both front and rear cameras using html5 proper input tag for image capture, but yeah still a bummer they don't support the getUserMedia for video streaming.

Here's a fiddle

For Front:
<input type="file" accept="image/*" capture="user">

For Rear:
<input type="file" accept="image/*" capture="environment">


问:
Timed out waiting 45 seconds for Firefox to start
I am using ubuntu 16.04</p>

```<code>Timed out waiting 45 seconds for Firefox to start.
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:07:31.527Z'
System info: host: 'supranimbus-Inspiron-3250', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.10.0-40-generic', java.version: '1.8.0_151'
Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:131)
    at org.openqa.selenium.firefox.XpiDriverService.start(XpiDriverService.java:116)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:98)
    at facedoxmain.FaceDox.InvokeBrowser(FaceDox.java:17)
    at facedoxmain.FaceDox.main(FaceDox.java:57)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:20033/hub/status] to be available after 45005 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:129)
</code>```

答:
I haved this error for 2 days in WIndows, the solution for me was in Set.Plataform put Plataform.ANY or Plataform.Windows because Plataform.WIN10 not worked, marionette wasn't necessary and I added and neether works, only works this. I hope this helps someone else:</p>

```<code>public class Main {
    public static RemoteWebDriver driver;

    public static void main(String[] args) throws MalformedURLException {
        System.setProperty("webdriver.gecko.driver", "D:/Lib/geckodriver.exe");
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities().firefox();
        desiredCapabilities.setPlatform(Platform.ANY);
        desiredCapabilities.setBrowserName("firefox");

        driver = new RemoteWebDriver(new URL("http://172.20.19.182:5557/wd/hub"), desiredCapabilities);
        driver.navigate().to("http://www.google.com");
        driver.findElementByName("q").sendKeys("execute automation");
        driver.findElementByName("q").sendKeys(Keys.ENTER);
        driver.close();
        // write your code here
    }
}
</code>```

Body:
I am using ubuntu 16.04

Timed out waiting 45 seconds for Firefox to start.
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:07:31.527Z'
System info: host: 'supranimbus-Inspiron-3250', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.10.0-40-generic', java.version: '1.8.0_151'
Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:131)
    at org.openqa.selenium.firefox.XpiDriverService.start(XpiDriverService.java:116)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:98)
    at facedoxmain.FaceDox.InvokeBrowser(FaceDox.java:17)
    at facedoxmain.FaceDox.main(FaceDox.java:57)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:20033/hub/status] to be available after 45005 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:129)

Body:
I haved this error for 2 days in WIndows, the solution for me was in Set.Plataform put Plataform.ANY or Plataform.Windows because Plataform.WIN10 not worked, marionette wasn't necessary and I added and neether works, only works this. I hope this helps someone else:

public class Main {
    public static RemoteWebDriver driver;

    public static void main(String[] args) throws MalformedURLException {
        System.setProperty("webdriver.gecko.driver", "D:/Lib/geckodriver.exe");
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities().firefox();
        desiredCapabilities.setPlatform(Platform.ANY);
        desiredCapabilities.setBrowserName("firefox");

        driver = new RemoteWebDriver(new URL("http://172.20.19.182:5557/wd/hub"), desiredCapabilities);
        driver.navigate().to("http://www.google.com");
        driver.findElementByName("q").sendKeys("execute automation");
        driver.findElementByName("q").sendKeys(Keys.ENTER);
        driver.close();
        // write your code here
    }
}


问:
How can I view the Git history in Visual Studio Code?
I can execute various Git commands from Visual Studio Code, however I couldn't find a way to visualize the history.</p>

答:
If you need to know the Commit history only, So don't use much Meshed up and bulky plugins,

I will recommend you a Basic simple plugin like "Git Commits"

I use it too :

https://marketplace.visualstudio.com/items?itemName=exelord.git-commits

Enjoy


问:
How cache entry's valid period is calculated in MULE4?
If I cache a payload, how long it will be valid?

There are 2 settings in caching-strategy;

Entry TTL and

Expiration Interval.
If I want to invalidate my cached value after 8 hours, How I should set above parameters?

What is the usage for 'invalidate cache' processor?

答:
Entry TTL is how long an entry should live in the cache. Expiration interval is how frequently the object store will check the entries to see if one entry should be deleted. In your case entryTTL should 8 hours. Be mindful of the units used for each attribute. Expiration interval is a bit more tricky. You may want to check entries much more frequently to avoid them living more than 8 hours before expiring. It may be 10 minutes, 30 minutes, 1 hour or whatever works for you.

I explained it more in my blog: https://medium.com/@adobni/configuring-an-object-store-in-mule-4-5da609e3456a


问:
Performance of operator| vs operators+
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

```<code>uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}
</code>```

the code will be used many times, so i want to speed it up as much as possible.

答:
Use |.

+ can only add to the operation time par obvious reasons.

Title: Performance of operator| vs operators+

Body:
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}

the code will be used many times, so i want to speed it up as much as possible.


问:
How to use tensorflow_io's IODataset?
I'm trying to write a program that can uses malicious pcap files as datasets and predicts if other pcaps files have malicious packets in them.
After some digging through the Tensorflow doumentation,  I have found TensorIO, but I can't figure out how to use the dataset to create a model and predict with it.

Here's my code:

```<code>%tensorflow_version 2.x
import tensorflow as tf
import numpy as np
from tensorflow import keras

try:
  import tensorflow_io as tfio
  import tensorflow_datasets as tfds
except:
  !pip install tensorflow-io
  !pip install tensorflow-datasets

import tensorflow_io as tfio
import tensorflow_datasets as tfds

# print(tf.__version__)

dataset = tfio.IODataset.from_pcap("dataset.pcap")
print(dataset) # <PcapIODataset shapes: ((), ()), types: (tf.float64, tf.string)>
</code>```

(Using Google Collab)

Iv'e tried looking for answers online, but couldn't find any.

答:
I have downloaded two pcap files and concatenated them. Later I have extracted the packet_timestamp and packet_data. Request you to preprocess the packet_data as per your requirement. If you have any labels to be added, you can add to the training dataset (In the below model example, I have created a dummy labels of all zero and adding as a column). If it is in a file then you can zip them to pcap files. Passing a dataset of (feature, label) pairs is all that's needed for Model.fit and Model.evaluate:

Below is an example of packet_data preprocessing - May be you can modify like if packet_data is valid then labels = valid else malicious.

```<code>%tensorflow_version 2.x
import tensorflow as tf
import tensorflow_io as tfio
import numpy as np

# Create an IODataset from a pcap file
first_file = tfio.IODataset.from_pcap('/content/fuzz-2006-06-26-2594.pcap')
second_file = tfio.IODataset.from_pcap(['/content/fuzz-2006-08-27-19853.pcap'])

# Concatenate the Read Files
feature = first_file.concatenate(second_file)
# List for pcap
packet_timestamp_list = []
packet_data_list = []

# some dummy labels
labels = []

packets_total = 0
for v in feature:
    (packet_timestamp, packet_data) = v
    packet_timestamp_list.append(packet_timestamp.numpy())
    packet_data_list.append(packet_data.numpy())
    labels.append(0)
    if packets_total == 0:
        assert np.isclose(
            packet_timestamp.numpy()[0], 1084443427.311224, rtol=1e-15
        )  # we know this is the correct value in the test pcap file
        assert (
            len(packet_data.numpy()[0]) == 62
        )  # we know this is the correct packet data buffer length in the test pcap file
    packets_total += 1
assert (
    packets_total == 43
)  # we know this is the correct number of packets in the test pcap file
</code>```

Below is example of using in Model - The model won't work because I have not handled the packet_data which is of string type. Do the preprocessing as explained as per your requirement and use in the model.

```<code>%tensorflow_version 2.x
import tensorflow as tf
import tensorflow_io as tfio
import numpy as np

# Create an IODataset from a pcap file
first_file = tfio.IODataset.from_pcap('/content/fuzz-2006-06-26-2594.pcap')
second_file = tfio.IODataset.from_pcap(['/content/fuzz-2006-08-27-19853.pcap'])

# Concatenate the Read Files
feature = first_file.concatenate(second_file)

# List for pcap
packet_timestamp = []
packet_data = []

# some dummy labels
labels = []

# add 0 as label. You can use your actual labels here
for v in feature:
  (timestamp, data) = v
  packet_timestamp.append(timestamp.numpy())
  packet_data.append(data.numpy())
  labels.append(0)

## Do the preprocessing of packet_data here

# Add labels to the training data
# Preprocess the packet_data to convert string to meaningful value and use here
train_ds = tf.data.Dataset.from_tensor_slices(((packet_timestamp,packet_data), labels))
# Set the batch size
train_ds = train_ds.shuffle(5000).batch(32)

##### PROGRAM WILL RUN SUCCESSFULLY TILL HERE. TO USE IN THE MODEL DO THE PREPROCESSING OF PACKET DATA AS EXPLAINED ###

# Have defined some simple model
model = tf.keras.Sequential([
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(100),
  tf.keras.layers.Dense(10)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(train_ds, epochs=2)
</code>```

Hope this answers your question. Happy Learning.

Title: How to use tensorflow_io's IODataset?

Body:
I'm trying to write a program that can uses malicious pcap files as datasets and predicts if other pcaps files have malicious packets in them.
After some digging through the Tensorflow doumentation,  I have found TensorIO, but I can't figure out how to use the dataset to create a model and predict with it.

Here's my code:

%tensorflow_version 2.x
import tensorflow as tf
import numpy as np
from tensorflow import keras

try:
  import tensorflow_io as tfio
  import tensorflow_datasets as tfds
except:
  !pip install tensorflow-io
  !pip install tensorflow-datasets

import tensorflow_io as tfio
import tensorflow_datasets as tfds

# print(tf.__version__)

dataset = tfio.IODataset.from_pcap("dataset.pcap")
print(dataset) # <PcapIODataset shapes: ((), ()), types: (tf.float64, tf.string)>

(Using Google Collab)

Iv'e tried looking for answers online, but couldn't find any.

Body:
I have downloaded two pcap files and concatenated them. Later I have extracted the packet_timestamp and packet_data. Request you to preprocess the packet_data as per your requirement. If you have any labels to be added, you can add to the training dataset (In the below model example, I have created a dummy labels of all zero and adding as a column). If it is in a file then you can zip them to pcap files. Passing a dataset of (feature, label) pairs is all that's needed for Model.fit and Model.evaluate:

Below is an example of packet_data preprocessing - May be you can modify like if packet_data is valid then labels = valid else malicious.

%tensorflow_version 2.x
import tensorflow as tf
import tensorflow_io as tfio
import numpy as np

# Create an IODataset from a pcap file
first_file = tfio.IODataset.from_pcap('/content/fuzz-2006-06-26-2594.pcap')
second_file = tfio.IODataset.from_pcap(['/content/fuzz-2006-08-27-19853.pcap'])

# Concatenate the Read Files
feature = first_file.concatenate(second_file)
# List for pcap
packet_timestamp_list = []
packet_data_list = []

# some dummy labels
labels = []

packets_total = 0
for v in feature:
    (packet_timestamp, packet_data) = v
    packet_timestamp_list.append(packet_timestamp.numpy())
    packet_data_list.append(packet_data.numpy())
    labels.append(0)
    if packets_total == 0:
        assert np.isclose(
            packet_timestamp.numpy()[0], 1084443427.311224, rtol=1e-15
        )  # we know this is the correct value in the test pcap file
        assert (
            len(packet_data.numpy()[0]) == 62
        )  # we know this is the correct packet data buffer length in the test pcap file
    packets_total += 1
assert (
    packets_total == 43
)  # we know this is the correct number of packets in the test pcap file

Below is example of using in Model - The model won't work because I have not handled the packet_data which is of string type. Do the preprocessing as explained as per your requirement and use in the model.

%tensorflow_version 2.x
import tensorflow as tf
import tensorflow_io as tfio
import numpy as np

# Create an IODataset from a pcap file
first_file = tfio.IODataset.from_pcap('/content/fuzz-2006-06-26-2594.pcap')
second_file = tfio.IODataset.from_pcap(['/content/fuzz-2006-08-27-19853.pcap'])

# Concatenate the Read Files
feature = first_file.concatenate(second_file)

# List for pcap
packet_timestamp = []
packet_data = []

# some dummy labels
labels = []

# add 0 as label. You can use your actual labels here
for v in feature:
  (timestamp, data) = v
  packet_timestamp.append(timestamp.numpy())
  packet_data.append(data.numpy())
  labels.append(0)

## Do the preprocessing of packet_data here

# Add labels to the training data
# Preprocess the packet_data to convert string to meaningful value and use here
train_ds = tf.data.Dataset.from_tensor_slices(((packet_timestamp,packet_data), labels))
# Set the batch size
train_ds = train_ds.shuffle(5000).batch(32)

##### PROGRAM WILL RUN SUCCESSFULLY TILL HERE. TO USE IN THE MODEL DO THE PREPROCESSING OF PACKET DATA AS EXPLAINED ###

# Have defined some simple model
model = tf.keras.Sequential([
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(100),
  tf.keras.layers.Dense(10)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(train_ds, epochs=2)

Hope this answers your question. Happy Learning.


问:
Pyodbc is only accepting windows authentication
I'm having one python script which connects to the MS SQL server from windows via pyodbc. When trying with windows authentication, it is getting connected to the database, but when trying with SQL server authentication (with username and password), it is showing below error.

"('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL
  Server]Login failed for user 'xxxx'. (18456) (SQLDriverConnect);
  [28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed
  for user 'xxxx'. (18456)")".

But I'm able to connect to the SQL server using that username and password (SQL server credentials). I've enabled DB read, write permission for that user in user mapping tab, and SQL server authentication is also in an enabled state.
This becomes a bottleneck. Solutions are welcome. Thanks in advance!!!.

答:
Today I learned that in python Upper case and lower case matters the most.
My previous connection string is,

conn=pyodbc.connect(r'DRIVER=SQL Server;SERVER=10.60.144.13;UID=BOT_Autoheal;PWD=bot_Aut0h3a1;DATABASE=OO_GlobalAutoHealing;TRUSTED_CONNECTION=NO';)

But actual connection string worked for me is,

conn=pyodbc.connect(r'DRIVER=SQL Server;SERVER=10.60.144.13;UID=BOT_Autoheal;PWD=bot_Aut0h3a1;DATABASE=OO_GlobalAutoHealing;Trusted_Connection=no')

So, always use Trusted_Connection=no as it is, don't try to change it to Upper case.


问:
trying to get data from one table into another AttributeError: 'BaseQuery' object has no attribute
I'm trying to get the data from my show data into an artist.past_shows attribute.  I'm using flask_sqlalchemy. I'm getting the error:

```<code>AttributeError: 'BaseQuery' object has no attribute 'past_shows'
</code>```

I'm not quite sure how to do this.  I'm trying to make the query like this:

```<code>artist = Artist.query.join(Artist.past_shows).filter(Artist.id==artist_id, Show.artist_id==artist_id)
</code>```

These are my models:

```<code>class Venue(db.Model):
    __tablename__ = 'venue'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    address = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))
    seeking_talent = db.Column(db.Boolean, default=False)
    seeking_description = db.Column(db.String())
    genres = db.Column(db.ARRAY(db.String))
    website = db.Column(db.String())
    pastshows = db.relationship('Show', backref='pastshows', lazy=True)

class Artist(db.Model):
    __tablename__ = 'artist'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    genres = db.Column(db.ARRAY(db.String))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))
    seeking_venue = db.Column(db.Boolean, nullable=False, default=False)
    seeking_description = db.Column(db.String())
    website = db.Column(db.String())
    past_shows = db.relationship('Show', backref='past_shows', lazy=True)

class Show(db.Model):
    __tablename__ = 'show'
    id = db.Column(db.Integer, primary_key=True)
    venue_id = db.Column(db.Integer, db.ForeignKey('venue.id'), nullable=False)
    artist_id = db.Column(db.Integer, db.ForeignKey('artist.id'), nullable=False)
    artist_name = db.Column(db.String())
    venue_name = db.Column(db.String())
    venue_image = db.Column(db.String())
    start_time = db.Column(db.DateTime(), nullable=False)
</code>```

How can I get the shows data for the artist_id I'm requesting into artist.past_shows?

答: I figured it out by creating a data object and putting the data in it using for loops.</p>

Body:
I'm trying to get the data from my show data into an artist.past_shows attribute.  I'm using flask_sqlalchemy. I'm getting the error:

AttributeError: 'BaseQuery' object has no attribute 'past_shows'

I'm not quite sure how to do this.  I'm trying to make the query like this:

artist = Artist.query.join(Artist.past_shows).filter(Artist.id==artist_id, Show.artist_id==artist_id)

These are my models:

class Venue(db.Model):
    __tablename__ = 'venue'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    address = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))
    seeking_talent = db.Column(db.Boolean, default=False)
    seeking_description = db.Column(db.String())
    genres = db.Column(db.ARRAY(db.String))
    website = db.Column(db.String())
    pastshows = db.relationship('Show', backref='pastshows', lazy=True)

class Artist(db.Model):
    __tablename__ = 'artist'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    genres = db.Column(db.ARRAY(db.String))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))
    seeking_venue = db.Column(db.Boolean, nullable=False, default=False)
    seeking_description = db.Column(db.String())
    website = db.Column(db.String())
    past_shows = db.relationship('Show', backref='past_shows', lazy=True)

class Show(db.Model):
    __tablename__ = 'show'
    id = db.Column(db.Integer, primary_key=True)
    venue_id = db.Column(db.Integer, db.ForeignKey('venue.id'), nullable=False)
    artist_id = db.Column(db.Integer, db.ForeignKey('artist.id'), nullable=False)
    artist_name = db.Column(db.String())
    venue_name = db.Column(db.String())
    venue_image = db.Column(db.String())
    start_time = db.Column(db.DateTime(), nullable=False)

How can I get the shows data for the artist_id I'm requesting into artist.past_shows?