问:
Get every email of random pages
I want to get every email address of 1000 webpages using Python's Selenium.

My idea:

go to page x

```<code>a = driver.page_source
</code>```

get the text of a that contains @

But however I cant get that part from a.

答:
You can get a list of the links this way:

```<code>links = [elem.get_attribute('href') for elem in elems]
</code>```

where elems is a driver.find_elements_by_...() returned value, for example:

```<code>elem = driver.find_elements_by_css_selector('a') # You need <a> tags if you want to be sure to find href attribute
</code>```

You can check if it's an email this way:

```<code>def isMail(link: str):
    if ('mailto:' in link):
        return True
    return False
</code>```

So

```<code>mails = [link.removeprefix('mailto:') for link in links if isMail(link)]
</code>```

I would suggest to read also this and this.

Title: Get every email of random pages

Body:
I want to get every email address of 1000 webpages using Python's Selenium.

My idea:

go to page x

a = driver.page_source

get the text of a that contains @

But however I cant get that part from a.

Body:
You can get a list of the links this way:

links = [elem.get_attribute('href') for elem in elems]

where elems is a driver.find_elements_by_...() returned value, for example:

elem = driver.find_elements_by_css_selector('a') # You need <a> tags if you want to be sure to find href attribute

You can check if it's an email this way:

def isMail(link: str):
    if ('mailto:' in link):
        return True
    return False

So

mails = [link.removeprefix('mailto:') for link in links if isMail(link)]

I would suggest to read also this and this.


来源: stackexchange

问:
Slick Slider: Go to slide with link and mark active links
I want to use a link to go to a certain slide inside a slick slider.

At the moment I'm using the following code for that (You can see it here: https://codepen.io/cray_code/pen/xxPRLKK):

```<code><div class="slider slider-for">
    <div><h3>1</h3></div>
    <div><h3>2</h3></div>
    <div><h3>3</h3></div>
    <div><h3>4</h3></div>
    <div><h3>5</h3></div>
  </div>
  <div class="action">
    <a href="#" data-slide="3">go to slide 3</a>
    <a href="#" data-slide="4">go to slide 4</a>
    <a href="#" data-slide="5">go to slide 5</a>
  </div>
</code>```

And this JS code:

```<code> $('.slider').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   arrows: false,
   fade: true,
 });

 $('a[data-slide]').click(function(e) {
   e.preventDefault();
   var slideno = $(this).data('slide');
   $('.slider').slick('slickGoTo', slideno - 1);
 });
</code>```

It works fine to jump do a certain slide.
But I need to mark the current slide inside the navigation as active and add a class .active to the link.

Is that possible?

I know that there is a thing like slider syncing with asNavFor. But I can't use that in my case.

答:
You can add an active class when clicking on those nav items.
You can see it here https://codepen.io/sifat009/pen/VwrmzPm

Here is the code i've changed.

```<code> $('.slider').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   arrows: false,
   fade: true,
 });

 $('a[data-slide]').click(function(e) {
   e.preventDefault();
   var slideno = $(this).data('slide');
   $('.slider').slick('slickGoTo', slideno - 1);
   $('a[data-slide]').removeClass('active');
   this.classList.add('active');
 });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to use a link to go to a certain slide inside a slick slider.

At the moment I'm using the following code for that (You can see it here: https://codepen.io/cray_code/pen/xxPRLKK):

1

2

3

4

5

    go to slide 3
    go to slide 4
    go to slide 5

And this JS code:

 $('.slider').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   arrows: false,
   fade: true,
 });

 $('a[data-slide]').click(function(e) {
   e.preventDefault();
   var slideno = $(this).data('slide');
   $('.slider').slick('slickGoTo', slideno - 1);
 });

It works fine to jump do a certain slide.
But I need to mark the current slide inside the navigation as active and add a class .active to the link.

Is that possible?

I know that there is a thing like slider syncing with asNavFor. But I can't use that in my case.

Body:
You can add an active class when clicking on those nav items.
You can see it here https://codepen.io/sifat009/pen/VwrmzPm

Here is the code i've changed.

 $('.slider').slick({
   slidesToShow: 1,
   slidesToScroll: 1,
   arrows: false,
   fade: true,
 });

 $('a[data-slide]').click(function(e) {
   e.preventDefault();
   var slideno = $(this).data('slide');
   $('.slider').slick('slickGoTo', slideno - 1);
   $('a[data-slide]').removeClass('active');
   this.classList.add('active');
 });


问:
Renaming of Computer Name
I want to get details of when and by whom the computer name was renamed.

I found that if a  renaming  is done for a computer an event id 6011 will be generated in event logs.

I am trying to pull the details of who did the rename using below command

```<code>Get-EventLog -LogName System | where {$_.EventID -eq 6011}
</code>```

But its not giving the required result.

答: This is working for me, but you can check the EventLog if you have logs with ID (6012).</p>

ContentLicense: CC BY-SA 3.0

Title: Renaming of Computer Name

Body:
I want to get details of when and by whom the computer name was renamed.

I found that if a  renaming  is done for a computer an event id 6011 will be generated in event logs.

I am trying to pull the details of who did the rename using below command

Get-EventLog -LogName System | where {$_.EventID -eq 6011}

But its not giving the required result.


问:
Insert a node at a specific position in a linked list JAVA
```<code>public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position) {
    if(llist == null) {
        llist =  new SinglyLinkedListNode(data);
        return llist;
    } else {
        for (int i = 0; i < position-1; i++) {
            llist = llist.next;
        }
        SinglyLinkedListNode temp = llist;
        llist.next = new SinglyLinkedListNode(data);
        llist = llist.next;
        llist.next = temp.next;
        return llist;
    }
}
</code>```

This is my code to place a custom index node in LinkedList. But hackerrank is not accepting my code. What's wrong with my algorithm?

答:
Easiest solution No need of explaination :
Solution :</p>
```<code>static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode head, int data, int position) {
        if (head == null) return null;
        SinglyLinkedListNode temp = new SinglyLinkedListNode(data);
        if (position == 0) {
            temp.next = head;
            return temp;
        }
        SinglyLinkedListNode p = head;
        for (int i = 0; i< position-1; i++) {
            p = p.next;
        }
        SinglyLinkedListNode next = p.next;
        p.next = temp;
        temp.next = next;
        return head;
    }
</code>```

Body:
public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position) {
    if(llist == null) {
        llist =  new SinglyLinkedListNode(data);
        return llist;
    } else {
        for (int i = 0; i < position-1; i++) {
            llist = llist.next;
        }
        SinglyLinkedListNode temp = llist;
        llist.next = new SinglyLinkedListNode(data);
        llist = llist.next;
        llist.next = temp.next;
        return llist;
    }
}

This is my code to place a custom index node in LinkedList. But hackerrank is not accepting my code. What's wrong with my algorithm?

Body:
Easiest solution No need of explaination :
Solution :

static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode head, int data, int position) {
        if (head == null) return null;
        SinglyLinkedListNode temp = new SinglyLinkedListNode(data);
        if (position == 0) {
            temp.next = head;
            return temp;
        }
        SinglyLinkedListNode p = head;
        for (int i = 0; i< position-1; i++) {
            p = p.next;
        }
        SinglyLinkedListNode next = p.next;
        p.next = temp;
        temp.next = next;
        return head;
    }


问:
Xslt Insert Image From Path
I have a xslt file and i want add an image from path. I tried with this codes but i didn't see image in my xslt file.

My codes:

```<code> <td width="40%" align="right" valign="middle">
       <br/>
       <img style="width:400px;" align="right" alt="Barcode"
       src="file:///C:/DCS/DCSEInvoiceBarcode.png"/>
 </td>
</code>```

And my result is here:

What is the problem in my code and what must do i?

Thank you.

答:
Solved our problem.
When we searched, we found that: Our codes is correct. The problem's source is invoice provider company's service. If you need insert picture from path to xslt, you can use this codes:</p>
```<code> <td width="40%" align="right" valign="middle">
       <br/>
       <img style="width:400px;" align="right" alt="Barcode"
       src="file:///C:/DCS/DCSEInvoiceBarcode.png"/>
 </td>
</code>```

Title: Xslt Insert Image From Path

Body:
I have a xslt file and i want add an image from path. I tried with this codes but i didn't see image in my xslt file.

My codes:

And my result is here:

What is the problem in my code and what must do i?

Thank you.

Body:
Solved our problem.
When we searched, we found that: Our codes is correct. The problem's source is invoice provider company's service. If you need insert picture from path to xslt, you can use this codes:

 <td width="40%" align="right" valign="middle">
       <br/>
       <img style="width:400px;" align="right" alt="Barcode"
       src="file:///C:/DCS/DCSEInvoiceBarcode.png"/>
 </td>


问:
Draw borders within bars in barplot?
I'm drawing a simple barplot with thick bar borders:

```<code>par(lwd=3)
barplot(c(6,7))
arrows(0,0,10,0,lwd=1)
</code>```

The borders stick out slightly over the x-axis, which looks bad.

Is there any way to draw the border within each bar, rather than around it?

答:
The best I can think of is to hack something together by hand by setting border = NA in barplot and then adding the borders using lines:

```<code>par(lwd = 3, lend = 2)
barplot(c(6,7),border = NA)
lines(c(0.2,0.2,1.2,1.2),c(0.02,6,6,0.02))
lines(c(1.4,1.4,2.4,2.4),c(0.02,7,7,0.02))
</code>```

This is far from ideal. The coordinates used in lines assume the default 0.2 space between bars and pulling the bottom up to 0.02 was just based on me eyeballing it. You might have to tinker with it on a case by case basis.

Title: Draw borders within bars in barplot?

Body:
I'm drawing a simple barplot with thick bar borders:

par(lwd=3)
barplot(c(6,7))
arrows(0,0,10,0,lwd=1)

The borders stick out slightly over the x-axis, which looks bad.

Is there any way to draw the border within each bar, rather than around it?

Body:
The best I can think of is to hack something together by hand by setting border = NA in barplot and then adding the borders using lines:

par(lwd = 3, lend = 2)
barplot(c(6,7),border = NA)
lines(c(0.2,0.2,1.2,1.2),c(0.02,6,6,0.02))
lines(c(1.4,1.4,2.4,2.4),c(0.02,7,7,0.02))

This is far from ideal. The coordinates used in lines assume the default 0.2 space between bars and pulling the bottom up to 0.02 was just based on me eyeballing it. You might have to tinker with it on a case by case basis.


问:
What does "size" parameter in Kucoin futures API refer to?
Kucoin Futures API documentation for placing a limit order ( https://docs.kucoin.com/futures/#place-an-order ) has a param called "size" with type Integer. The description is given as "Order size. Must be a positive number".

A limit order to buy "CELRUSDTM" with param size = 1 results in an order placed to buy 10 CELR.
A limit order to buy "ETHUSDTM" with param size = 1 results in an order placed to buy .01 ETH.

What does "size" actually refer to?

For reference, I'm using a python library called kucoin-futures-python-sdk (https://github.com/Kucoin/kucoin-futures-python-sdk/blob/main/kucoin_futures/trade/trade.py) and the class method is called create_limit_order

Here's the python to call this method to place the orders:

```<code>def limit_order(symbol, side, lever, size, price):
    # place a limit buy order
    order_id = client.create_limit_order(symbol, side, lever, size, price)

limit_order('ETHUSDTM', 'buy', '1', '1', '1000')
limit_order('CELRUSDTM', 'buy', '1', '2', '.01')
</code>```

(Although Kucoin documentation requests "size" param as an integer, the python library takes size as a string, which is why I'm submitting it as a string in the examples above. I've thought about whether size is proportional to the price, but that also doesn't add up. 0.01 ETH at $1000 = $10, whereas 10 CELR at .01 = $1)

答:
The same documentation explains:

SIZE

The size must be no less than the lotSize for the contract and no larger than the maxOrderQty. It should be a multiple number of lotSize, or the system will report an error when you place the order. Size indicates the amount of contract to buy or sell. Size is the number or lot size of the contract. Eg. the lot size of XBTUSDTM is 0.001 Bitcoin, the lot size of XBTUSDM is 1 USD.

The applicable lotSize is returned when requesting the order info of the contract:

HTTP Request

```<code>GET /api/v1/contracts/{symbol}
</code>```

Example

```<code>GET /api/v1/contracts/XBTUSDM
</code>```

PARAMETERS

Param
Type
Description

symbol
String
Path Parameter. Symbol of the contract

The response looks like this:

  {
    "code": "200000",
    "data": {
      "symbol": "XBTUSDM", //Ticker symbol of the contract
      "lotSize": 1,   //Minimum lot size
      // [...]
    }
  }
```

Body:
Kucoin Futures API documentation for placing a limit order ( https://docs.kucoin.com/futures/#place-an-order ) has a param called "size" with type Integer. The description is given as "Order size. Must be a positive number".

A limit order to buy "CELRUSDTM" with param size = 1 results in an order placed to buy 10 CELR.
A limit order to buy "ETHUSDTM" with param size = 1 results in an order placed to buy .01 ETH.

What does "size" actually refer to?

For reference, I'm using a python library called kucoin-futures-python-sdk (https://github.com/Kucoin/kucoin-futures-python-sdk/blob/main/kucoin_futures/trade/trade.py) and the class method is called create_limit_order

Here's the python to call this method to place the orders:

def limit_order(symbol, side, lever, size, price):
    # place a limit buy order
    order_id = client.create_limit_order(symbol, side, lever, size, price)

limit_order('ETHUSDTM', 'buy', '1', '1', '1000')
limit_order('CELRUSDTM', 'buy', '1', '2', '.01')

(Although Kucoin documentation requests "size" param as an integer, the python library takes size as a string, which is why I'm submitting it as a string in the examples above. I've thought about whether size is proportional to the price, but that also doesn't add up. 0.01 ETH at $1000 = $10, whereas 10 CELR at .01 = $1)

Body:
The same documentation explains:

SIZE

The size must be no less than the lotSize for the contract and no larger than the maxOrderQty. It should be a multiple number of lotSize, or the system will report an error when you place the order. Size indicates the amount of contract to buy or sell. Size is the number or lot size of the contract. Eg. the lot size of XBTUSDTM is 0.001 Bitcoin, the lot size of XBTUSDM is 1 USD.

The applicable lotSize is returned when requesting the order info of the contract:

HTTP Request

GET /api/v1/contracts/{symbol}

Example

GET /api/v1/contracts/XBTUSDM

PARAMETERS

Param
Type
Description

symbol
String
Path Parameter. Symbol of the contract

The response looks like this:

  {
    "code": "200000",
    "data": {
      "symbol": "XBTUSDM", //Ticker symbol of the contract
      "lotSize": 1,   //Minimum lot size
      // [...]
    }
  }


问:
How to return from a child function?
I have this function, it's responsible for getting a specific text of an element within an xml. But console.log gives me undefined every time i call the function. I get that the mistake is that i return to fs.readFile not to getTodayHoroscopes, but how can I fix it?</p>
```<code>const getTodayHoroscope = (signNumber) => {
    fs.readFile('./horoscopy.xml', 'utf8', (err, data) => {
        if (err) {
            console.log('File read failed:', err);
        return;
        }
        try {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(data, "xml/html");
            horoscopeString = (xmlDoc.getElementsByTagName("today")[signNumber].textContent);
            result = horoscopeString
            return result;
        } catch (err) {
            console.log('Error parsing JSON:', err);
        }
    console.log(result);
    });
}
</code>```

答:
readFileSync

const getTodayHoroscope = (signNumber) => {
  try {
    const data = fs.readFileSync('./horoscopy.xml', 'utf8' )
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(data, "xml/html");
    const horoscopeString = (xmlDoc.getElementsByTagName("today")[signNumber].textContent);
    return horoscopeString;
  } catch (error) {
    console.log(error);
  }
}
```
<ol start="2">
<li><code>promise</code></li>
</ol>
<pre class="lang-js prettyprint-override"><code>const getTodayHoroscope =  (signNumber) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./horoscopy.xml', 'utf8', (err, data) => {
      if (err) {
          console.log('File read failed:', err);
          reject(err)
          return
      }
      try {
          parser = new DOMParser();
          xmlDoc = parser.parseFromString(data, "xml/html");
          horoscopeString = (xmlDoc.getElementsByTagName("today")[signNumber].textContent);
          result = horoscopeString
          resolve(result) ;
      } catch (err) {
          console.log('Error parsing JSON:', err);
          reject(err)
      }
  });
  })
}

(async () => {
  try {
    console.log(await getTodayHoroscope('xxx'))
  } catch (error) {
    console.log(error)
  }
})();
</code>```

Title: How to return from a child function?

Body:
I have this function, it's responsible for getting a specific text of an element within an xml. But console.log gives me undefined every time i call the function. I get that the mistake is that i return to fs.readFile not to getTodayHoroscopes, but how can I fix it?

const getTodayHoroscope = (signNumber) => {
    fs.readFile('./horoscopy.xml', 'utf8', (err, data) => {
        if (err) {
            console.log('File read failed:', err);
        return;
        }
        try {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(data, "xml/html");
            horoscopeString = (xmlDoc.getElementsByTagName("today")[signNumber].textContent);
            result = horoscopeString
            return result;
        } catch (err) {
            console.log('Error parsing JSON:', err);
        }
    console.log(result);
    });
}

Body:
readFileSync

const getTodayHoroscope = (signNumber) => {
  try {
    const data = fs.readFileSync('./horoscopy.xml', 'utf8' )
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(data, "xml/html");
    const horoscopeString = (xmlDoc.getElementsByTagName("today")[signNumber].textContent);
    return horoscopeString;
  } catch (error) {
    console.log(error);
  }
}

promise

const getTodayHoroscope =  (signNumber) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./horoscopy.xml', 'utf8', (err, data) => {
      if (err) {
          console.log('File read failed:', err);
          reject(err)
          return
      }
      try {
          parser = new DOMParser();
          xmlDoc = parser.parseFromString(data, "xml/html");
          horoscopeString = (xmlDoc.getElementsByTagName("today")[signNumber].textContent);
          result = horoscopeString
          resolve(result) ;
      } catch (err) {
          console.log('Error parsing JSON:', err);
          reject(err)
      }
  });
  })
}

(async () => {
  try {
    console.log(await getTodayHoroscope('xxx'))
  } catch (error) {
    console.log(error)
  }
})();


问:
How to correctly use axios params with arrays
How to add indexes to array in query string?

I tried send data like this:

```<code>axios.get('/myController/myAction', { params: { storeIds: [1,2,3] })
</code>```

And I got this url:

```<code>http://localhost/api/myController/myAction?storeIds[]=1&storeIds[]=2&storeIds[]=3
</code>```

So, I should to get this url:

```<code>http://localhost/api/myController/myAction?storeIds[0]=1&storeIds[1]=2&storeIds[2]=3
</code>```

What I should add in my params options to get this url?

答:
I know that this approach is not very good and I don't know the downsides it may have, but i tried this and it worked:

before making the request, prepare the params:

```<code>  let params = '?';

  for (let i = 0; i < YOUR_ARRAY.length; i++) {  // In this case YOUR_ARRAY == [1, 2, 3]
    params += `storeIds=${YOUR_ARRAY[i]}`;  // storeIds is your PARAM_NAME
    if (i !== YOUR_ARRAY.length - 1) params += '&';
  }
</code>```

And then make the request like so:

```<code>axios.get('/myController/myAction' + params)
</code>```

Body:
How to add indexes to array in query string?

I tried send data like this:

axios.get('/myController/myAction', { params: { storeIds: [1,2,3] })

And I got this url:

http://localhost/api/myController/myAction?storeIds[]=1&storeIds[]=2&storeIds[]=3

So, I should to get this url:

http://localhost/api/myController/myAction?storeIds[0]=1&storeIds[1]=2&storeIds[2]=3

What I should add in my params options to get this url?

Body:
I know that this approach is not very good and I don't know the downsides it may have, but i tried this and it worked:

before making the request, prepare the params:

  let params = '?';

  for (let i = 0; i < YOUR_ARRAY.length; i++) {  // In this case YOUR_ARRAY == [1, 2, 3]
    params += `storeIds=${YOUR_ARRAY[i]}`;  // storeIds is your PARAM_NAME
    if (i !== YOUR_ARRAY.length - 1) params += '&';
  }

And then make the request like so:

axios.get('/myController/myAction' + params)


问:
Google Analytics Core Reporting API - Cannot get information with batchGet without entering a metric
I'm trying to receive data from google analytics to make specific report.
This report does not include any metric but only dimensions.
The problem is that batchGet requests a metric in order to send a request properly.
This is the how the data is requested via Data Studio

As you can see the metric section is empty.

And this is how I run the batchGet request (using python)

```<code>analytics.reports().batchGet(
  body={
    'reportRequests': [
    {
      'viewId': VIEW_ID,
      'dateRanges': [{'startDate': '2022-01-01', 'endDate': '2022-01-01'}],
      'metrics': [],
      'dimensions': [{'name': 'ga:date'},
                    {'name': 'ga:transactionId'},
                    {'name': 'ga:adContent'},
                    {'name': 'ga:source'},
                    {'name': 'ga:medium'},
                    {'name': 'ga:campaign'},
                    {'name': 'ga:keyword'}]
    }]
  }).execute()
</code>```

When I run this code I get an error:

"Selected dimensions and metrics cannot be queried together."

And that's because I ask both dimensions {'name': 'ga:transactionId'},{'name': 'ga:adContent'} in the same request.

How can I request this data and receiving this without any errors, because I know I can see it in Data Studio but I cannot request it via Google Analytics Core Reporting API.

Thanks in advance,

Tom

答:
Actually I finally found an solution.

I use 2 different requests with a unique field that will map between the transactionId field and the adContent field.

```<code>def get_campaign_report(VIEW_ID, analytics, specific_day):
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': specific_day, 'endDate': specific_day}],
          'metrics': [{'expression': 'ga:transactions'}],
          'dimensions': [{'name': 'ga:clientID'},
                        {'name': 'ga:visitLength'},
                        {'name': 'ga:date'},
                        {'name': 'ga:source'},
                        {'name': 'ga:medium'},
                        {'name': 'ga:campaign'},
                        {'name': 'ga:adContent'},
                        {'name': 'ga:keyword'}]
        }]
      }
  ).execute()

def get_transaction_id(VIEW_ID, analytics, specific_day):
  return analytics.reports().batchGet(
        body={
          'reportRequests': [
          {
            'viewId': VIEW_ID,
            'dateRanges': [{'startDate': specific_day, 'endDate': specific_day}],
            'metrics': [{'expression': 'ga:transactions'}],
            'dimensions': [{'name': 'ga:clientID'},
                          {'name': 'ga:visitLength'},
                          {'name': 'ga:transactionId'}]
          }]
        }
    ).execute()
</code>```

Then I created dictionary for each request:
which the key is [{ga:clientID}{ga:visitLength}] which is pretty unique id and then I could mapping between {ga:transactionId} to {ga:adContent}

Body:
I'm trying to receive data from google analytics to make specific report.
This report does not include any metric but only dimensions.
The problem is that batchGet requests a metric in order to send a request properly.
This is the how the data is requested via Data Studio

As you can see the metric section is empty.

And this is how I run the batchGet request (using python)

analytics.reports().batchGet(
  body={
    'reportRequests': [
    {
      'viewId': VIEW_ID,
      'dateRanges': [{'startDate': '2022-01-01', 'endDate': '2022-01-01'}],
      'metrics': [],
      'dimensions': [{'name': 'ga:date'},
                    {'name': 'ga:transactionId'},
                    {'name': 'ga:adContent'},
                    {'name': 'ga:source'},
                    {'name': 'ga:medium'},
                    {'name': 'ga:campaign'},
                    {'name': 'ga:keyword'}]
    }]
  }).execute()

When I run this code I get an error:

"Selected dimensions and metrics cannot be queried together."

And that's because I ask both dimensions {'name': 'ga:transactionId'},{'name': 'ga:adContent'} in the same request.

How can I request this data and receiving this without any errors, because I know I can see it in Data Studio but I cannot request it via Google Analytics Core Reporting API.

Thanks in advance,

Tom

Body:
Actually I finally found an solution.

I use 2 different requests with a unique field that will map between the transactionId field and the adContent field.

def get_campaign_report(VIEW_ID, analytics, specific_day):
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': specific_day, 'endDate': specific_day}],
          'metrics': [{'expression': 'ga:transactions'}],
          'dimensions': [{'name': 'ga:clientID'},
                        {'name': 'ga:visitLength'},
                        {'name': 'ga:date'},
                        {'name': 'ga:source'},
                        {'name': 'ga:medium'},
                        {'name': 'ga:campaign'},
                        {'name': 'ga:adContent'},
                        {'name': 'ga:keyword'}]
        }]
      }
  ).execute()

def get_transaction_id(VIEW_ID, analytics, specific_day):
  return analytics.reports().batchGet(
        body={
          'reportRequests': [
          {
            'viewId': VIEW_ID,
            'dateRanges': [{'startDate': specific_day, 'endDate': specific_day}],
            'metrics': [{'expression': 'ga:transactions'}],
            'dimensions': [{'name': 'ga:clientID'},
                          {'name': 'ga:visitLength'},
                          {'name': 'ga:transactionId'}]
          }]
        }
    ).execute()

Then I created dictionary for each request:
which the key is [{ga:clientID}{ga:visitLength}] which is pretty unique id and then I could mapping between {ga:transactionId} to {ga:adContent}


问:
how to access the properties of the host activity from a fragment dialog (kotlin)?
i have this fragment dialog and i want to edit some host activity properties when he click on btnOk in line 26 can any one help me or give me another way to communicate between a dialog fragment and its host activity
`

```<code>package com.exemple.tic_tac_toe

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.DialogFragment
import android.app.Activity

class restartDialog : DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val layout : View = inflater.inflate(R.layout.exit_layout , container , false)
        this.isCancelable = false
        val btnOk : Button = layout.findViewById(R.id.btnYes)
        val btnNo : Button = layout.findViewById(R.id.btnNO)
        btnOk.setOnClickListener(){
            dismiss()
            /////here acces the host activity properties and change them
        }
        btnNo.setOnClickListener(){
            dismiss()
        }
        return  layout
    }
}
</code>```

`

答:
I think the better approach would be to use an interface or a callback, rather than having the DialogFragment access the Activity properties.

You can create an interface:

```<code>interface DialogClickListener {
    fun dialogOkClicked()
    fun dialogCancelClicked()
}
</code>```

Make the hosting Activity implement it:

```<code>class YourActivity: AppCompatActivity(), DialogClickListener {

    override fun dialogOkClicked() {

    }

    override fun dialogCancelClicked() {

    }
}
</code>```

And in your DialogFragment, call those methods in case the Activity implements them:

```<code>btnOk.setOnClickListener(){
    (activity as? DialogClickListener)?.dialogOkClicked()
    dismiss()

}
btnNo.setOnClickListener(){
    (activity as? DialogClickListener)?.dialogCancelClicked()
    dismiss()
}
</code>```

This would allow you to use this DialogFragment in other places and not inside a specific hosting Activity.

Body:
i have this fragment dialog and i want to edit some host activity properties when he click on btnOk in line 26 can any one help me or give me another way to communicate between a dialog fragment and its host activity
`

package com.exemple.tic_tac_toe

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.DialogFragment
import android.app.Activity

class restartDialog : DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val layout : View = inflater.inflate(R.layout.exit_layout , container , false)
        this.isCancelable = false
        val btnOk : Button = layout.findViewById(R.id.btnYes)
        val btnNo : Button = layout.findViewById(R.id.btnNO)
        btnOk.setOnClickListener(){
            dismiss()
            /////here acces the host activity properties and change them
        }
        btnNo.setOnClickListener(){
            dismiss()
        }
        return  layout
    }
}

`

Body:
I think the better approach would be to use an interface or a callback, rather than having the DialogFragment access the Activity properties.

You can create an interface:

interface DialogClickListener {
    fun dialogOkClicked()
    fun dialogCancelClicked()
}

Make the hosting Activity implement it:

class YourActivity: AppCompatActivity(), DialogClickListener {

    override fun dialogOkClicked() {

    }

    override fun dialogCancelClicked() {

    }
}

And in your DialogFragment, call those methods in case the Activity implements them:

btnOk.setOnClickListener(){
    (activity as? DialogClickListener)?.dialogOkClicked()
    dismiss()

}
btnNo.setOnClickListener(){
    (activity as? DialogClickListener)?.dialogCancelClicked()
    dismiss()
}

This would allow you to use this DialogFragment in other places and not inside a specific hosting Activity.


问:
Monitoring and alerting on activemq
Hi with activemq problems that i usually face are as under:-
1. Pushed message do not get consumed
2. As a result of point 1, queue size becomes huge
3. Messages in queue keep on retrying

So is there any open source that anyone of you have used in project to send mails when queue size goes beyond a certain threshold. Can we also send message details or store it somewhere to diagnose later why these messages were not getting consumed.

答:
Zabbix can be a choice: https://www.zabbix.com/integrations/activemq
If the queue size becomes huge, it will create an alert. Also, it has more variety of other alerts that can be useful.</p>

Title: Monitoring and alerting on activemq


问:
No suitable Java Virtual Machine could be found on your system
I am running Ubuntu 16 on my computer and
I am attempting to run a Java application on my computer and I get the following error:

```<code>No suitable Java Virtual Machine could be found on your system.
The version of the JVM must be at least 11.
Please define INSTALL4J_JAVA_HOME to point to a suitable JVM.
</code>```

However I have already Java installed and a virtual machine.
When I press

```<code>$java -version
</code>```

I get the following output:

```<code>openjdk version "1.8.0_192"
OpenJDK Runtime Environment (Zulu 8.33.0.1-linux64) (build 1.8.0_192-b01)
OpenJDK 64-Bit Server VM (Zulu 8.33.0.1-linux64) (build 25.192-b01, mixed mode)
</code>```

Does anyone know how I can fix this problem? Many thanks.

答:
From the output above, it is evident that an updated version of Java is missing. You need at least a version of JVM equal to 11 or upper.

Let’s now proceed and install both JRE and JDK which both constitute JAVA

JRE

Ubuntu

```<code>sudo apt install default-jre
</code>```

Arch

```<code>sudo pacman -S jre-openjdk
</code>```

JDK

Ubuntu

```<code>sudo apt install default-jdk
</code>```

Arch

```<code>sudo pacman -sS java | grep jdk
sudo pacman -S jdk-openjdk
</code>```

you can check the version with java -version

```<code>java -version
</code>```

Body:
I am running Ubuntu 16 on my computer and
I am attempting to run a Java application on my computer and I get the following error:

No suitable Java Virtual Machine could be found on your system.
The version of the JVM must be at least 11.
Please define INSTALL4J_JAVA_HOME to point to a suitable JVM.

However I have already Java installed and a virtual machine.
When I press

$java -version

I get the following output:

openjdk version "1.8.0_192"
OpenJDK Runtime Environment (Zulu 8.33.0.1-linux64) (build 1.8.0_192-b01)
OpenJDK 64-Bit Server VM (Zulu 8.33.0.1-linux64) (build 25.192-b01, mixed mode)

Does anyone know how I can fix this problem? Many thanks.

Body:
From the output above, it is evident that an updated version of Java is missing. You need at least a version of JVM equal to 11 or upper.

Let’s now proceed and install both JRE and JDK which both constitute JAVA

JRE

Ubuntu

sudo apt install default-jre

Arch

sudo pacman -S jre-openjdk

JDK

Ubuntu

sudo apt install default-jdk

Arch

sudo pacman -sS java | grep jdk
sudo pacman -S jdk-openjdk

you can check the version with java -version

java -version


问:
Can I uninstall visual studio 2017 and still use the 2017 platform toolset in visual studio 2019?
IIRC, you used to have to have a prior version installed in order to build using that tool set, but from what I gather now the platform tools are optionally installed with the newer version.  At the time I installed 2019, I was using the 2017 version, I still have lots of projects using the 2017 platform tool set even though I only use vs2019.

So my question is if I can now uninstall VS2017 and continue to build using that platform toolkit in VS2019?

TIA!!

答:
Yes, you can, but not the way you think. The vc141 toolkit (VS2017) also comes with 2019 and you have to install it separately.

uninstall VS2017 completely

open the Visual Studio Installer

click "modify" on the 2019 instance

go to "invidual components"

enter "v141" in the search field

install all components you need

IOW: The platform and toolkit for VS2017 are also contained in VS2019.

Now you can choose "v141" in the "Toolkit" property and you can even mix and match.


问:
In x86-64, why the address of a structure sometimes be a pointer type and sometimes be a long type?
I read the chapter 3 of the textbook "Computer Systems: A Programmer Perspective". Chapter 3 is about introducing instruction set architecture(ISA) of x86-64. In this chapter, there are several examples of assembly code that were compiled from C programs. In these examples, I encountered two questions which are about the address of structure.

First, suppose the starting address of integer array E and integer index i are stored in register %rdx and %rcx, respectively. The following shows an assembly-code implementation of each expression:

Expression
Type
Value
Assembly code

E
int *
XE
movl %rdx, %rax

E[0]
int
M[XE]
movl (%rdx), %eax

&E[2]
int *
XE+8
leaq 8(%rdx), %rax

&E[i]-E
long
i
movq %rcx, %rax

Why the expression &E[i]-E be the long type instead of the int * type? Why the value of &E[i]-E be i instead of 4i?

Second, suppose a structure:

```<code>typedef union {
    struct{
        long u;
        short v;
        char w;
    }t1;
    struct{
        int a[2];
        char *p;
    }t2;
} u_type;
</code>```

You write a series of functions of the form

```<code>void get(u_type *up, type *dest){
    *dest = expr;
}
</code>```

with different access expression expr and with destination data type type set according to type associated with expr. Suppose in these functions that up and dest are loaded into register %rdi and %rsi, respectively.The following table is about the assembly code of the expression:

Expression
Type
Assembly code

up->t1.u
long
movq (%rdi), %rax \n      movq %rax, (%rsi)

&up->t1.w
char *
addq $10, %rdi \n  movq %rdi, (%rsi)

Considering expression &up->t1.w, I know that we want to assign the the address of the char w to dest and the offset of the char w is 10 bytes of the beginning of the structure. But why the answer is to store 10 to dest instead of storing 10(%rdi) to dest? If the answer is correct, why the type is char * instead of long?

To make it clear, why the assembly code of the expression &up->t1.w not like this:

```<code>leaq 10(%rdi), %rax
movq %rax, (%rsi)
</code>```

答:
It makes little or no sense at all to analyze not optimized code. If you enable the optimizations all your problems disappear magically.

```<code>struct s1{
    int a[2];
    char *p;
};

typedef union {
    struct{
        long u;
        short v;
        char w;
    };
    struct s1 s;
} u_type;

void get(u_type *up, char *dest)
{
    *dest = up -> w;
}

        movzbl  10(%rdi), %eax
        movb    %al, (%rsi)
        ret

void get(u_type *up, long *dest)
{
    *dest = up -> u;
}

        movq    (%rdi), %rax
        movq    %rax, (%rsi)
        ret

void get(u_type *up, struct s1 *dest)
{
    *dest = up -> s;
}

        movdqu  (%rdi), %xmm0
        movups  %xmm0, (%rsi)
        ret

void get(u_type *up, int *dest)
{
    *dest = up -> s.a[1];
}

        movl    4(%rdi), %eax
        movl    %eax, (%rsi)
        ret
</code>```

https://godbolt.org/z/xPPvTbPTq

Body:
I read the chapter 3 of the textbook "Computer Systems: A Programmer Perspective". Chapter 3 is about introducing instruction set architecture(ISA) of x86-64. In this chapter, there are several examples of assembly code that were compiled from C programs. In these examples, I encountered two questions which are about the address of structure.

First, suppose the starting address of integer array E and integer index i are stored in register %rdx and %rcx, respectively. The following shows an assembly-code implementation of each expression:

Expression
Type
Value
Assembly code

E
int *
XE
movl %rdx, %rax

E[0]
int
M[XE]
movl (%rdx), %eax

&E[2]
int *
XE+8
leaq 8(%rdx), %rax

&E[i]-E
long
i
movq %rcx, %rax

Why the expression &E[i]-E be the long type instead of the int * type? Why the value of &E[i]-E be i instead of 4i?

Second, suppose a structure:

typedef union {
    struct{
        long u;
        short v;
        char w;
    }t1;
    struct{
        int a[2];
        char *p;
    }t2;
} u_type;

You write a series of functions of the form

void get(u_type *up, type *dest){
    *dest = expr;
}

with different access expression expr and with destination data type type set according to type associated with expr. Suppose in these functions that up and dest are loaded into register %rdi and %rsi, respectively.The following table is about the assembly code of the expression:

Expression
Type
Assembly code

up->t1.u
long
movq (%rdi), %rax \n      movq %rax, (%rsi)

&up->t1.w
char *
addq $10, %rdi \n  movq %rdi, (%rsi)

Considering expression &up->t1.w, I know that we want to assign the the address of the char w to dest and the offset of the char w is 10 bytes of the beginning of the structure. But why the answer is to store 10 to dest instead of storing 10(%rdi) to dest? If the answer is correct, why the type is char * instead of long?

To make it clear, why the assembly code of the expression &up->t1.w not like this:

leaq 10(%rdi), %rax
movq %rax, (%rsi)

Body:
It makes little or no sense at all to analyze not optimized code. If you enable the optimizations all your problems disappear magically.

struct s1{
    int a[2];
    char *p;
};

typedef union {
    struct{
        long u;
        short v;
        char w;
    };
    struct s1 s;
} u_type;

void get(u_type *up, char *dest)
{
    *dest = up -> w;
}

        movzbl  10(%rdi), %eax
        movb    %al, (%rsi)
        ret

void get(u_type *up, long *dest)
{
    *dest = up -> u;
}

        movq    (%rdi), %rax
        movq    %rax, (%rsi)
        ret

void get(u_type *up, struct s1 *dest)
{
    *dest = up -> s;
}

        movdqu  (%rdi), %xmm0
        movups  %xmm0, (%rsi)
        ret

void get(u_type *up, int *dest)
{
    *dest = up -> s.a[1];
}

        movl    4(%rdi), %eax
        movl    %eax, (%rsi)
        ret

https://godbolt.org/z/xPPvTbPTq


答:
You can use shared view model to achieve this.
Make a viewModel and create instance of that viewModel in your Activity.

```<code>class HomeViewModel : ViewModel() {
   private val _sharedData = MutableLiveData<Event<Int,Any>>() // Int is type and Any is Data
   val sharedData : LiveData<Event<Int,Any>> get() = _sharedData

  fun setData(type : Int, data : Any) {
     sharedData.value = Event(type, data)
  }
}
</code>```

you can get the event class from here
https://gist.github.com/JoseAlcerreca/5b661f1800e1e654f07cc54fe87441af

you can register your viewModel in Activity

```<code>private val mViewModel by viewModels<HomeViewModel>()
</code>```

and get the instance of your viewModel in fragment/dialog fragment

```<code>private val mHomeViewModel by activityViewModels<HomeViewModel>()
</code>```

when you want to send data

```<code>mHomeViewModel.setData(your_type,your_data)
</code>```

and in your activity observe viewModel

```<code>mViewModel.observe(this,EventObserver{
 // you will get the data here with corresponding type
})
</code>```

for more info you can check the official documentation
https://developer.android.com/guide/fragments/communicate

Title: how to access the properties of the host activity from a fragment dialog (kotlin)?

Body:
You can use shared view model to achieve this.
Make a viewModel and create instance of that viewModel in your Activity.

class HomeViewModel : ViewModel() {
   private val _sharedData = MutableLiveData<Event<Int,Any>>() // Int is type and Any is Data
   val sharedData : LiveData<Event<Int,Any>> get() = _sharedData

  fun setData(type : Int, data : Any) {
     sharedData.value = Event(type, data)
  }
}

you can get the event class from here
https://gist.github.com/JoseAlcerreca/5b661f1800e1e654f07cc54fe87441af

you can register your viewModel in Activity

private val mViewModel by viewModels<HomeViewModel>()

and get the instance of your viewModel in fragment/dialog fragment

private val mHomeViewModel by activityViewModels<HomeViewModel>()

when you want to send data

mHomeViewModel.setData(your_type,your_data)

and in your activity observe viewModel

mViewModel.observe(this,EventObserver{
 // you will get the data here with corresponding type
})

for more info you can check the official documentation
https://developer.android.com/guide/fragments/communicate


问:
Append response data in LocalStorage objects
I have a frontend that sends an id automatically when someone visits a URL, like /products/1, /products/2, it send the id like 1 or 2 to the server, then the server send a response for that id back to the browser, now I want to save this response in localStorage, but when someone visits, /1 its saves response in local storage, but now when someone visits, /2 it replaces the previous local storage value instead of adding new, How can I keep on adding new data to localStorage instead of updating the previous value?</p>
```<code>
fetch("/apps/proxy/sendid", {
        method: "POST",
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(jspid)
      }).then(function (response) {
        // The API call was successful!
        console.log(response);
        return response.json();
      }).then(function (data) {
        // This is the JSON from our response
         // This is the JSON from our response
        console.log(data);

        const productsDetails = [];

        productsDetails.push(data);

        localStorage.setItem('future', JSON.stringify(productsDetails));

      }).catch(function (err) {
        // There was an error
        console.warn('Something went wrong.', err);
      });
  }
</code>```

答:
First, get the current items from localStorage and assigned them to productsDetails. Then append the next items to the array.

```<code>let productsDetails = localStorage.getItem('future');

if(null === productsDetails) {
    productsDetails = [];
}

productsDetails.push(data);

localStorage.setItem('future', JSON.stringify(productsDetails));
</code>```

Body:
I have a frontend that sends an id automatically when someone visits a URL, like /products/1, /products/2, it send the id like 1 or 2 to the server, then the server send a response for that id back to the browser, now I want to save this response in localStorage, but when someone visits, /1 its saves response in local storage, but now when someone visits, /2 it replaces the previous local storage value instead of adding new, How can I keep on adding new data to localStorage instead of updating the previous value?

fetch("/apps/proxy/sendid", {
        method: "POST",
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(jspid)
      }).then(function (response) {
        // The API call was successful!
        console.log(response);
        return response.json();
      }).then(function (data) {
        // This is the JSON from our response
         // This is the JSON from our response
        console.log(data);

        const productsDetails = [];

        productsDetails.push(data);

        localStorage.setItem('future', JSON.stringify(productsDetails));

      }).catch(function (err) {
        // There was an error
        console.warn('Something went wrong.', err);
      });
  }

Body:
First, get the current items from localStorage and assigned them to productsDetails. Then append the next items to the array.

let productsDetails = localStorage.getItem('future');

if(null === productsDetails) {
    productsDetails = [];
}

productsDetails.push(data);

localStorage.setItem('future', JSON.stringify(productsDetails));


问:
How to make this bubble type widget in flutter which depicts a certain message on tap?
I need help with this widget .

答:
Use this link to view the flutter animated popUp
https://www.youtube.com/watch?v=vsyjMrZa5OU</p>

Body: I need help with this widget .


问:
How do I throttle a CPU intensive loop in Adobe Flex?
I have a method, which connects to a HTTP server and requests via XMLRPC, a list of data structures and then for each data structure gets a list of attributes and the values of those attributes. It's implemented using nested for each loops.

The problem is that it's loading a lot of data all at once, and consuming a massive amount of CPU (over 100%) reading responses from the server and parsing the XML.

If I were writing the program in C, I'd insert a usleep() at the end of the loop, to wait before trying to load more data and reduce CPU usage. What would the equivalent be in Flex?

答: In some scenarios, it's better to stick with what you have access to if you're not in control of your server-side data source. Another alternative would be to write getter/setter wrapper to your XML object. XML is first class citizen in AS3. Easy for programs to read (e4x) but annoying for us devs to write and modify. If you can, get a page of data that once received will kick off another request while the user can work with the data from pages that have already been loaded. Create the illusion of parallelism using serial techniques.</p>


问:
How to use TextInput isFocused() Method
According to this link in the React Native API Documents:
https://facebook.github.io/react-native/docs/0.59/textinput#isfocused

The TextInput component has a method called isFocused(). How would I go about accessing this method? Do I have to use a ref?

Also, I already know that I can achieve the same effect by using the onFocus prop and setting up a state manager and a function to change the state of the input based on the onFocus. However, I am just curious how I would go about using these component methods since there are others in other components as well.

I have tried using this

```<code><TextInput onChangeText={this.handleText} style={(this.isFocused()) ? styles.input : styles.lame} placeholder="Names"/>
</code>```

but it is looking like I might have to use a ref since it seems that it isn't defined even though the method should be a part of this component.

答:
This another easy way to use the onFocus prop in TextInput

import React, { useState } from 'react'
import { View, StyleSheet, TextInput } from 'react-native'

const TextInput = () => {
  const [isHighlighted, setIsHighlighted] = useState(false)

  return (
    <View>
      <TextInput
        style={[styles.textInput, isHighlighted && styles.isHighlighted]}
        onFocus={() => { setIsHighlighted(true)}
        onBlur={() => {setIsHighlighted(false)} />
      </View>
  )
}

const styles = StyleSheet.create({
  textInput: {
    borderColor: 'grey',
    borderWidth: StyleSheet.hairlineWidth,
    borderRadius: 8,
    height: 43,
  },
  isHighlighted: {
    borderColor: 'green',
  }
})
```

Title: How to use TextInput isFocused() Method

Body:
According to this link in the React Native API Documents:
https://facebook.github.io/react-native/docs/0.59/textinput#isfocused

The TextInput component has a method called isFocused(). How would I go about accessing this method? Do I have to use a ref?

Also, I already know that I can achieve the same effect by using the onFocus prop and setting up a state manager and a function to change the state of the input based on the onFocus. However, I am just curious how I would go about using these component methods since there are others in other components as well.

I have tried using this

<TextInput onChangeText={this.handleText} style={(this.isFocused()) ? styles.input : styles.lame} placeholder="Names"/>

but it is looking like I might have to use a ref since it seems that it isn't defined even though the method should be a part of this component.


问:
How to assign value to variable from future before screen built?
In my application user can have multiple home and multiple rooms for each home. On top of my application I have dropdown box which im trying to set default value to selectedHome by user. Below that dropdown box I am showing the rooms in the home selected by user. In firebase I have rooms collection under each home. I'm getting the selected home data from firebase too. Also to show the rooms in selected home i need to query by home name. I have two FutureBuilder as you can see code below. One of them to get the selectedHome data from firebase and other for the getting the rooms in that home from firebase. As I said before to get the rooms in selected home I need to query by name of the home so I have a parameter which is the value of dropdownbox. In my code the problem is getting the rooms part is working before I get the selectedHome data from firebase and assign it to dropdown value. In this case I'm getting  "Null check operator used on a null value".

Basicly the question is how can i assign value from future to variable before screen gets build.

Here you can see the code for getting selected home data from firebase;

```<code>Future<String> selectedHome() async {
return await database.selectedHome();
</code>```

}

```<code>Future<String> selectedHome() async {
DocumentSnapshot docS =
    await firestore.collection("users").doc(auth.currentUser()).get();
String selectedHome = (docS.data() as Map)["selectedHome"];
return selectedHome;
</code>```

}

Here you can see the code for getting room data based on selectedHome from firebase;

```<code>Future<List<Map>> deviceAndRoomInfo() async {
    return database.numberOfRooms(_dropdownValue!);
  }

Future<List<Map>> numberOfRooms(String selectedHome) async {
    List<Map> prodsList = [];
    final snapshot = await firestore
        .collection("users")
        .doc(auth.currentUser())
        .collection("homes")
        .doc(selectedHome)
        .collection("rooms")
        .get();

    List listOfRooms = snapshot.docs;

    for (int a = 1; a <= listOfRooms.length; a++) {
      var productsInRoom = await firestore
          .collection("users")
          .doc(auth.currentUser())
          .collection("homes")
          .doc(selectedHome)
          .collection("rooms")
          .doc(listOfRooms[a - 1]["roomName"])
          .collection("products")
          .get();

      List prodList = productsInRoom.docs
          .map((e) => DeviceModel.fromMap(e.data()))
          .toList();

      Map qq = {
        "roomName": listOfRooms[a - 1]["roomName"],
        "deviceInfo": prodList
      };
      prodsList.add(qq);
    }
    return prodsList;
  }
</code>```

Here you can see the code for screen contains 2 future builder that i told;

```<code>     import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    import 'package:shelly_ess_production/constants.dart';
    import 'package:shelly_ess_production/helper_widgets/loading_widget.dart';
    import 'package:shelly_ess_production/screens/home_screen/components/circle_room_data.dart';
    import 'package:shelly_ess_production/screens/home_screen/components/device_in_room_card.dart';
    import 'package:shelly_ess_production/screens/home_screen/provider/home_screen_provider.dart';
    import 'package:shelly_ess_production/screens/models/device_model.dart';
    import 'package:shelly_ess_production/size_config.dart';

class Body extends StatefulWidget {
  const Body({Key? key}) : super(key: key);

  @override
  State<Body> createState() => _BodyState();
}

class _BodyState extends State<Body> {

  @override
  Widget build(BuildContext context) {
    var providerHelper =
        Provider.of<HomeScreenProvider>(context, listen: false);

    return SafeArea(
      child: Padding(
        padding:
            EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(0.07)),
        child: SingleChildScrollView(
            child: Column(
          children: [
            SizedBox(
              height: getProportionateScreenHeight(0.02),
            ),
            Consumer<HomeScreenProvider>(builder: (context, data, child) {
              return FutureBuilder<List<String>>(
                  future: data.getHomesAndSelected(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      data.setDropDownValue = snapshot.data![0];
                      return DropdownButtonHideUnderline(
                        child: DropdownButton(
                          iconEnabledColor: kPrimaryColor,
                          iconDisabledColor: kPrimaryColor,
                          style: TextStyle(
                              color: kPrimaryColor,
                              fontSize: getProportionateScreenHeight(0.05)),
                          menuMaxHeight: getProportionateScreenHeight(0.4),
                          borderRadius: BorderRadius.circular(15),
                          key: UniqueKey(),
                          value: data.dropdownValue,
                          isExpanded: true,
                          icon: const Icon(Icons.arrow_downward),
                          onChanged: (String? newValue) async {
                            data.setDropDownValue = newValue;
                            await data.changeSelectedHome();
                          },
                          items: snapshot.data!
                              .map<DropdownMenuItem<String>>((String value) {
                            return DropdownMenuItem<String>(
                              alignment: Alignment.center,
                              value: value,
                              child: Text(value),
                            );
                          }).toList(),
                        ),
                      );
                    } else {
                      return Transform.scale(
                        scale: 0.5,
                        child: const Center(
                          child: CircularProgressIndicator(),
                        ),
                      );
                    }
                  });
            }),
            SizedBox(
              height: getProportionateScreenHeight(0.02),
            ),
            SizedBox(
              height: getProportionateScreenHeight(0.14),
              child: ListView.builder(
                  shrinkWrap: true,
                  scrollDirection: Axis.horizontal,
                  itemCount: 5,
                  itemBuilder: (context, index) {
                    return CircleRoomData(
                      title: "Oda Sayısı",
                      icon: Icons.meeting_room,
                      content: "8",
                    );
                  }),
            ),
            Consumer<HomeScreenProvider>(builder: (context, data, snapshot) {
              return FutureBuilder<List<Map>>(
                  future: data.deviceAndRoomInfo(data.dropdownValue!),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      return ListView.builder(
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: snapshot.data!.length,
                          shrinkWrap: true,
                          itemBuilder: (context, index) {
                            return Column(
                              children: [
                                Divider(
                                  thickness:
                                      getProportionateScreenHeight(0.002),
                                ),
                                Text(
                                  snapshot.data![index]["roomName"],
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      color: kSecondaryColor,
                                      fontSize:
                                          getProportionateScreenHeight(0.03)),
                                ),
                                SizedBox(
                                  height: getProportionateScreenHeight(0.01),
                                ),
                                Text(
                                  "${(snapshot.data![index]["deviceInfo"] as List).length.toString()} Cihaz",
                                  style:
                                      const TextStyle(color: kSecondaryColor),
                                ),
                                SizedBox(
                                  height: getProportionateScreenHeight(0.02),
                                ),
                                GridView.builder(
                                    shrinkWrap: true,
                                    physics:
                                        const NeverScrollableScrollPhysics(),
                                    itemCount: (snapshot.data![index]
                                            ["deviceInfo"] as List)
                                        .length,
                                    gridDelegate:
                                        const SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 3,
                                    ),
                                    itemBuilder: (context, indexx) {
                                      print(index);
                                      return DeviceInRoom(
                                        icon: Icons.light,
                                        productName: ((snapshot.data![index]
                                                    ["deviceInfo"]
                                                as List)[indexx] as DeviceModel)
                                            .deviceName,
                                      );
                                    })
                              ],
                            );
                          });
                    } else {
                      return const Center(
                        child: CircularProgressIndicator(),
                      );
                    }
                  });
            }
            )
          ],
        )),
      ),
    );
  }
}
</code>```

答:
Am not certain where your error is coming from, but from what I see it maybe as a result of one of your functions returning null and a rendering of your content happens before the data is received.

You could try one of these:

You could declare the return type of your feature as being nullable for example you are expecting a value of type int:

```<code>Future<int?> xyz(){
  ......
  return .....;
}
</code>```

Now because your return type is nullable you wont have an issues as long as the receiving variable is also nullable.

Alternatively:

```<code>Future<int?> xyz(){
  ......
  return ..... ?? 10 /*some default value*/;
}
</code>```

because you know you result could be null you could also provide an optional default value incase your Future call returns a null value.

Body:
In my application user can have multiple home and multiple rooms for each home. On top of my application I have dropdown box which im trying to set default value to selectedHome by user. Below that dropdown box I am showing the rooms in the home selected by user. In firebase I have rooms collection under each home. I'm getting the selected home data from firebase too. Also to show the rooms in selected home i need to query by home name. I have two FutureBuilder as you can see code below. One of them to get the selectedHome data from firebase and other for the getting the rooms in that home from firebase. As I said before to get the rooms in selected home I need to query by name of the home so I have a parameter which is the value of dropdownbox. In my code the problem is getting the rooms part is working before I get the selectedHome data from firebase and assign it to dropdown value. In this case I'm getting  "Null check operator used on a null value".

Basicly the question is how can i assign value from future to variable before screen gets build.

Here you can see the code for getting selected home data from firebase;

Future<String> selectedHome() async {
return await database.selectedHome();

}

Future<String> selectedHome() async {
DocumentSnapshot docS =
    await firestore.collection("users").doc(auth.currentUser()).get();
String selectedHome = (docS.data() as Map)["selectedHome"];
return selectedHome;

}

Here you can see the code for getting room data based on selectedHome from firebase;

Future<List<Map>> deviceAndRoomInfo() async {
    return database.numberOfRooms(_dropdownValue!);
  }

Future<List<Map>> numberOfRooms(String selectedHome) async {
    List<Map> prodsList = [];
    final snapshot = await firestore
        .collection("users")
        .doc(auth.currentUser())
        .collection("homes")
        .doc(selectedHome)
        .collection("rooms")
        .get();

    List listOfRooms = snapshot.docs;

    for (int a = 1; a <= listOfRooms.length; a++) {
      var productsInRoom = await firestore
          .collection("users")
          .doc(auth.currentUser())
          .collection("homes")
          .doc(selectedHome)
          .collection("rooms")
          .doc(listOfRooms[a - 1]["roomName"])
          .collection("products")
          .get();

      List prodList = productsInRoom.docs
          .map((e) => DeviceModel.fromMap(e.data()))
          .toList();

      Map qq = {
        "roomName": listOfRooms[a - 1]["roomName"],
        "deviceInfo": prodList
      };
      prodsList.add(qq);
    }
    return prodsList;
  }

Here you can see the code for screen contains 2 future builder that i told;

     import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    import 'package:shelly_ess_production/constants.dart';
    import 'package:shelly_ess_production/helper_widgets/loading_widget.dart';
    import 'package:shelly_ess_production/screens/home_screen/components/circle_room_data.dart';
    import 'package:shelly_ess_production/screens/home_screen/components/device_in_room_card.dart';
    import 'package:shelly_ess_production/screens/home_screen/provider/home_screen_provider.dart';
    import 'package:shelly_ess_production/screens/models/device_model.dart';
    import 'package:shelly_ess_production/size_config.dart';

class Body extends StatefulWidget {
  const Body({Key? key}) : super(key: key);

  @override
  State createState() => _BodyState();
}

class _BodyState extends State {

  @override
  Widget build(BuildContext context) {
    var providerHelper =
        Provider.of<HomeScreenProvider>(context, listen: false);

    return SafeArea(
      child: Padding(
        padding:
            EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(0.07)),
        child: SingleChildScrollView(
            child: Column(
          children: [
            SizedBox(
              height: getProportionateScreenHeight(0.02),
            ),
            Consumer<HomeScreenProvider>(builder: (context, data, child) {
              return FutureBuilder<List<String>>(
                  future: data.getHomesAndSelected(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      data.setDropDownValue = snapshot.data![0];
                      return DropdownButtonHideUnderline(
                        child: DropdownButton(
                          iconEnabledColor: kPrimaryColor,
                          iconDisabledColor: kPrimaryColor,
                          style: TextStyle(
                              color: kPrimaryColor,
                              fontSize: getProportionateScreenHeight(0.05)),
                          menuMaxHeight: getProportionateScreenHeight(0.4),
                          borderRadius: BorderRadius.circular(15),
                          key: UniqueKey(),
                          value: data.dropdownValue,
                          isExpanded: true,
                          icon: const Icon(Icons.arrow_downward),
                          onChanged: (String? newValue) async {
                            data.setDropDownValue = newValue;
                            await data.changeSelectedHome();
                          },
                          items: snapshot.data!
                              .map<DropdownMenuItem<String>>((String value) {
                            return DropdownMenuItem<String>(
                              alignment: Alignment.center,
                              value: value,
                              child: Text(value),
                            );
                          }).toList(),
                        ),
                      );
                    } else {
                      return Transform.scale(
                        scale: 0.5,
                        child: const Center(
                          child: CircularProgressIndicator(),
                        ),
                      );
                    }
                  });
            }),
            SizedBox(
              height: getProportionateScreenHeight(0.02),
            ),
            SizedBox(
              height: getProportionateScreenHeight(0.14),
              child: ListView.builder(
                  shrinkWrap: true,
                  scrollDirection: Axis.horizontal,
                  itemCount: 5,
                  itemBuilder: (context, index) {
                    return CircleRoomData(
                      title: "Oda Sayısı",
                      icon: Icons.meeting_room,
                      content: "8",
                    );
                  }),
            ),
            Consumer<HomeScreenProvider>(builder: (context, data, snapshot) {
              return FutureBuilder<List<Map>>(
                  future: data.deviceAndRoomInfo(data.dropdownValue!),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      return ListView.builder(
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: snapshot.data!.length,
                          shrinkWrap: true,
                          itemBuilder: (context, index) {
                            return Column(
                              children: [
                                Divider(
                                  thickness:
                                      getProportionateScreenHeight(0.002),
                                ),
                                Text(
                                  snapshot.data![index]["roomName"],
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      color: kSecondaryColor,
                                      fontSize:
                                          getProportionateScreenHeight(0.03)),
                                ),
                                SizedBox(
                                  height: getProportionateScreenHeight(0.01),
                                ),
                                Text(
                                  "${(snapshot.data![index]["deviceInfo"] as List).length.toString()} Cihaz",
                                  style:
                                      const TextStyle(color: kSecondaryColor),
                                ),
                                SizedBox(
                                  height: getProportionateScreenHeight(0.02),
                                ),
                                GridView.builder(
                                    shrinkWrap: true,
                                    physics:
                                        const NeverScrollableScrollPhysics(),
                                    itemCount: (snapshot.data![index]
                                            ["deviceInfo"] as List)
                                        .length,
                                    gridDelegate:
                                        const SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 3,
                                    ),
                                    itemBuilder: (context, indexx) {
                                      print(index);
                                      return DeviceInRoom(
                                        icon: Icons.light,
                                        productName: ((snapshot.data![index]
                                                    ["deviceInfo"]
                                                as List)[indexx] as DeviceModel)
                                            .deviceName,
                                      );
                                    })
                              ],
                            );
                          });
                    } else {
                      return const Center(
                        child: CircularProgressIndicator(),
                      );
                    }
                  });
            }
            )
          ],
        )),
      ),
    );
  }
}

Body:
Am not certain where your error is coming from, but from what I see it maybe as a result of one of your functions returning null and a rendering of your content happens before the data is received.

You could try one of these:

You could declare the return type of your feature as being nullable for example you are expecting a value of type int:

Future<int?> xyz(){
  ......
  return .....;
}

Now because your return type is nullable you wont have an issues as long as the receiving variable is also nullable.

Alternatively:

Future<int?> xyz(){
  ......
  return ..... ?? 10 /*some default value*/;
}

because you know you result could be null you could also provide an optional default value incase your Future call returns a null value.


问:
How to update git submodule to a specific commit?
```<code>git submodule update --remote
</code>```

Above command updates the submodule to latest commit however I want to update to a specific commit (e.g. to some commit hash). How to achieve that ?

答:
git submodules are repositories inside a repository, hence it has the same behavior as any other git repository. Hence enter the dependency root by using cd submodule and use any git command.

```<code>cd submodule
git checkout -b NEW_BRANCH_NAME COMMIT_ID
</code>```

Body:
git submodule update --remote

Above command updates the submodule to latest commit however I want to update to a specific commit (e.g. to some commit hash). How to achieve that ?

Body:
git submodules are repositories inside a repository, hence it has the same behavior as any other git repository. Hence enter the dependency root by using cd submodule and use any git command.

cd submodule
git checkout -b NEW_BRANCH_NAME COMMIT_ID


问:
How to control gdb within C or Python code without the GDB Python API?
I am trying to write a program in python or c that can debug c code by using gdb.

I've read the solution of Tom and Invoke and control GDB from Python. But they are more or less a solution for scripting gdb in python. Since I am going to use an arm-gdb to debug embedded program, I cannot enable python scripting in my gdb.

My goal is to create a high-level abstraction of gdb. For example, launch gdb, set some breakpoints and continue within my code. I also read some material gdb/mi interface. But could anyone tell me how to use gdb/mi interface to create a gdb process and communicate with gdb from c/python code? (Luckily my arm-gdb supports gdb/mi interface).

答:
As promised in the comments above, I have published my (early, incomplete, almost certainly buggy) ruby work to http://github.com/mcarpenter/rubug.

Here's an example (you can find this in
examples/breakpoint). Function check_for_crash is a callback that may be invoked
after the program called factorial is set running. The breakpoint takes a function name
(fac; the leading colon just indicates that this is a
ruby symbol which to all intents and purposes here is a lightweight
string).

```<code>EXE = 'factorial'

def check_for_crash(gdb, event)
  case event.type
  when :command_response
    raise RuntimeError, 'oops' unless
  [ :done, :running ].include? event.response.result
  when :breakpoint
    puts 'Breakpoint reached'
    pp event
    gdb.continue
  when :exit
    puts 'Exit'
    gdb.stop_event_loop
    exit
  end
end

gdb = Rubug::Gdb.new
resp = gdb.file EXE
gdb.register_callback(method :check_for_crash)
gdb.break(:fac)
gdb.run '5 > /dev/null'
gdb.start_event_loop
</code>```

It is only fair to warn you that the code may be... crufty. Currently (this is where I stopped) nothing much works (subsequent to a gdb update midway through my work, see
Grammar below).

There are a bunch of examples in the directory of the same
name that might prove helpful however. To (attempt to!) run them, you will need to do something like this:

```<code>rake clean
rake grammar
rake make
cd examples/simple_fuzzer
ruby -I ../../lib -r rubygems simple_fuzzer.rb
</code>```

Given the time that this was written you should probably go with a ruby1.8
if you have the choice (I wasn't into 1.9 at the time and there are probably
string encoding issues under 1.9).

Parsing of responses is performed by treetop
http://treetop.rubyforge.org, a PEG parser. Looking at the grammar with
fresh eyes I'm sure that it could be simplified. You will need to install this
(and any other required gems) using gem install ....

Some more tips if you do Pythonize:

Documentation

There is little outside "Debugging with GDB"
(ch. 22). I've thrown this PDF and just ch. 22 as a separate file into
the docs section of the repository.

Async

The protocol is asynrchronous (at first I assumed this was
command/response type protocol, this was a mistake). If I were to
re-implement this I'd probably use something like event machine or
libevent rather than rolling my own select() loop.

Grammar

The grammar is a little... confusing. Although the documentation
(27.2.2) states that a response "consists of zero or more out of band
records followed, optionally, by a single result record":

```<code>`output -> ( out-of-band-record )* [ result-record ] "(gdb)" nl`
</code>```

you should be aware that since anything can arrive at any time a read()
on the socket can apparently return async/result/more
async/terminator(!). For example, I see this with my current gdb:

```<code>=thread-group-started,id="i1",pid="1086"
=thread-created,id="1",group-id="i1"
^running
*running,thread-id="all"
(gdb)
</code>```

The line starting ^ is a result record, all others are async (then
the terminator). This seems like a fairly significant flaw in the
specification.

Speed

My main focus is security and I was interested in MI for
automated fuzzing, binary inspection, etc. For this purpose GDB/MI is too
slow (cost of starting the program in the debugger). YMMV.

MI / CLI mapping

There were some things in the standard gdb CLI command set that I
could not see how to implement using MI commands. I have skeleton
code for something like this:

```<code>gdb = Gdb::MI.new
gdb.cli(:file, '/bin/ls')
gdb.cli(:set, :args, '> /dev/null')
gdb.cli(:run)
gdb.cli(:quit)
</code>```

(which is nice and clear, I think, for us non-MI-expert-but-gdb-knowledgeable users).
I can't now remember what those problematic things were (it's over a year
since I looked at this) but if those neurons do fire I'll come back and
update this.

Alternatives

When I first started out
on this road I found a blog posting from Jamis Buck:
http://weblog.jamisbuck.org/2006/9/25/gdb-wrapper-for-ruby This wraps a
gdb command line session in popen() which made me wince a little. In
particular one might expect it to be brittle since gdb makes no
guarantees about the stability of the CLI output. You may (or may not)
prefer this approach.

If you're on windows then PyDbg / PeiMei may be of interest: http://code.google.com/p/paimei/

You might also like the book Grey Hat Python: Python Programming for Hackers (Seitz). Again, mostly windows based but might prove inspirational.

Body:
As promised in the comments above, I have published my (early, incomplete, almost certainly buggy) ruby work to http://github.com/mcarpenter/rubug.

Here's an example (you can find this in
examples/breakpoint). Function check_for_crash is a callback that may be invoked
after the program called factorial is set running. The breakpoint takes a function name
(fac; the leading colon just indicates that this is a
ruby symbol which to all intents and purposes here is a lightweight
string).

EXE = 'factorial'

def check_for_crash(gdb, event)
  case event.type
  when :command_response
    raise RuntimeError, 'oops' unless
  [ :done, :running ].include? event.response.result
  when :breakpoint
    puts 'Breakpoint reached'
    pp event
    gdb.continue
  when :exit
    puts 'Exit'
    gdb.stop_event_loop
    exit
  end
end

gdb = Rubug::Gdb.new
resp = gdb.file EXE
gdb.register_callback(method :check_for_crash)
gdb.break(:fac)
gdb.run '5 > /dev/null'
gdb.start_event_loop

It is only fair to warn you that the code may be... crufty. Currently (this is where I stopped) nothing much works (subsequent to a gdb update midway through my work, see
Grammar below).

There are a bunch of examples in the directory of the same
name that might prove helpful however. To (attempt to!) run them, you will need to do something like this:

rake clean
rake grammar
rake make
cd examples/simple_fuzzer
ruby -I ../../lib -r rubygems simple_fuzzer.rb

Given the time that this was written you should probably go with a ruby1.8
if you have the choice (I wasn't into 1.9 at the time and there are probably
string encoding issues under 1.9).

Parsing of responses is performed by treetop
http://treetop.rubyforge.org, a PEG parser. Looking at the grammar with
fresh eyes I'm sure that it could be simplified. You will need to install this
(and any other required gems) using gem install ....

Some more tips if you do Pythonize:

Documentation

There is little outside "Debugging with GDB"
(ch. 22). I've thrown this PDF and just ch. 22 as a separate file into
the docs section of the repository.

Async

The protocol is asynrchronous (at first I assumed this was
command/response type protocol, this was a mistake). If I were to
re-implement this I'd probably use something like event machine or
libevent rather than rolling my own select() loop.

Grammar

The grammar is a little... confusing. Although the documentation
(27.2.2) states that a response "consists of zero or more out of band
records followed, optionally, by a single result record":

`output -> ( out-of-band-record )* [ result-record ] "(gdb)" nl`

you should be aware that since anything can arrive at any time a read()
on the socket can apparently return async/result/more
async/terminator(!). For example, I see this with my current gdb:

=thread-group-started,id="i1",pid="1086"
=thread-created,id="1",group-id="i1"
^running
*running,thread-id="all"
(gdb)

The line starting ^ is a result record, all others are async (then
the terminator). This seems like a fairly significant flaw in the
specification.

Speed

My main focus is security and I was interested in MI for
automated fuzzing, binary inspection, etc. For this purpose GDB/MI is too
slow (cost of starting the program in the debugger). YMMV.

MI / CLI mapping

There were some things in the standard gdb CLI command set that I
could not see how to implement using MI commands. I have skeleton
code for something like this:

gdb = Gdb::MI.new
gdb.cli(:file, '/bin/ls')
gdb.cli(:set, :args, '> /dev/null')
gdb.cli(:run)
gdb.cli(:quit)

(which is nice and clear, I think, for us non-MI-expert-but-gdb-knowledgeable users).
I can't now remember what those problematic things were (it's over a year
since I looked at this) but if those neurons do fire I'll come back and
update this.

Alternatives

When I first started out
on this road I found a blog posting from Jamis Buck:
http://weblog.jamisbuck.org/2006/9/25/gdb-wrapper-for-ruby This wraps a
gdb command line session in popen() which made me wince a little. In
particular one might expect it to be brittle since gdb makes no
guarantees about the stability of the CLI output. You may (or may not)
prefer this approach.

If you're on windows then PyDbg / PeiMei may be of interest: http://code.google.com/p/paimei/

You might also like the book Grey Hat Python: Python Programming for Hackers (Seitz). Again, mostly windows based but might prove inspirational.


问:
How does pixels relate to screen size in CSS
If set the width of a div to 450px. What will happen to the div on a smaller screen say a phone or tablet??</p>

答:
In short: If you are using <meta name="viewport" content="width=device-width, initial-scale=1"> it depends on the DPI (dots per inch) of the screen.

From the CSS Spec:

1px = 1/96th of 1 inch

and from Mozilla Docs on the CSS 2.1 spec:

If the pixel density of the output device is very different from that of a typical computer display, the user agent should rescale pixel values. It is recommended that the pixel unit refer to the whole number of device pixels that best approximates the reference pixel. It is recommended that the reference pixel be the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length.

A CSS pixel is actually its own unit and doesn't refer to pixels that you see. If your site with the 450px div is just a standard HTML page and you view it on a phone (in portrait) and a desktop monitor (say 1920x1080), you will notice on the phone the div appears to take up more screen space and on the desktop it will take up less screen space.

I think this video does a pretty decent job at explaining it.

If you are not using <meta name="viewport" content="width=device-width, initial-scale=1"> 1px closely represents 1px.

You can test this out for yourself by opening these two pages on a phone:

Viewport device width meta tag set

Viewport device width meta tag NOT set


问:
Delete signal/slot connection from Qt Designer
How do I delete a signal/slot connection that I've created from Qt Designer? I created such a connection, but now it's no longer needed and I want to delete it.

I tried right-clicking on it, but the Delete action is disabled:

I can't use Select All because I have other signals/slots which I don't want to delete. Basically I can't select the connection to delete it.

答:
1-> is where you can edit signals and slots (drag and drop) but if you wanna clear any connection , do step 2 and 3.

2-> right click here and check "signals and slots editor".(or go to menu and "view->views->signals and slots editr")

3-> in this place you can see connections that you added in step 1 , you can remove them! by the "-" button ( that is red there).


问:
Include a third party script in a functional component of react with server side rendering
I'm having trouble inserting a third-party script inside a functional component with server-side rendering.

This is the script I should include in a normal HTML document.

```<code><script class="feedaty_sdk" src="https://widget.feedaty.com/public/js/feedaty.js?merchant=******&style_ver=2021" async ></script><div class="feedaty_widget" data-ver="2021" data-id="61fee7f06c9b2" data-type="merchant" data-variant="150x100-1" data-lang="all" data-gui="all"></div>
</code>```

Inside react I created a functional component and within useEffect, I created the script.

```<code>import { useEffect, useState } from 'react';

const FeedatyButton = () => {
 const [scriptLoaded, setScriptLoaded] = useState(false);

 useEffect(() => {
    const feedatyDiv = document.getElementById('feedatyScript');
    if (typeof window !== undefined && !scriptLoaded && !feedatyDiv) {
        const script = document.createElement('script');
        script.setAttribute('async', '');
        script.setAttribute('id', 'feedatyScript');
        script.src =
                'https://widget.feedaty.com/public/js/feedaty.js?merchant=******&style_ver=2021';
        script.addEventListener('load', () => setScriptLoaded(true));
        document.appendChild(script);
    }
  }, []);

  return (
        <div className='flex justify-end items-center' id='feedatyContainer'>
            <div
                className='feedaty_widget'
                data-ver='2021'
                data-id='61fee7f06c9b2'
                data-type='merchant'
                data-variant='150x100-1'
                data-lang='all'
                data-gui='all'></div>
        </div>
    );
};

export default FeedatyButton;
</code>```

The script loads without problem, but nothing appears inside the feedaty_widget div.

If I create the div with createElement and append it to the document or the body, then it works, but it shows at the end of my react app and obviously, it's not what I want.
I want to place it inside my functional component in a specific position.

What could be the problem?

答:
I was wrong in approach, because I was not updating the component with the code generated by the "feedaty" script.
This is the updated code using ref to update the content</p>
```<code>import { useEffect, useState, useRef } from 'react';

const FeedatyButton = () => {
    const feedatyContainerRef = useRef();
    const [scriptLoaded, setScriptLoaded] = useState(false);

    useEffect(() => {
        scriptLoader();
        return () => {
            scriptUnloader();
        };
    }, []);

    useEffect(() => {
        if (!scriptLoaded) return;
    }, [scriptLoaded]);

    const scriptLoader = () => {
        window.addEventListener('load', scriptMover);
        const feedatyDiv = document.getElementById('feedatyScript');
        if (typeof window !== undefined && !feedatyDiv) {
            const script = document.createElement('script');
            script.src =
                'https://widget.feedaty.com/public/js/feedaty.js?merchant=1******&style_ver=2021';
            script.id = 'feedatyScript';
            script.async = true;
            document.body.appendChild(script);
        }
    };

    const scriptUnloader = () => {
        window.removeEventListener('load', scriptMover);
        const feedatyDiv = document.getElementById('feedatyScript');
        document.body.removeChild(document.querySelector('#feedatyScript'));
    };

    // this function get called when script is loaded and i get the content of the widget, so i can update my component using ref
    const scriptMover = () => {
        const feedatyWidgetUpdated = document.getElementById('feedatyWidget');
        feedatyContainerRef.current.appendChild(feedatyWidgetUpdated);
        setScriptLoaded();
    };

    return (
        <div
            className='flex justify-end items-start'
            id='feedatyContainer'
            ref={feedatyContainerRef}>
            <div
                id='feedatyWidget'
                className='feedaty_widget'
                data-id='61fee7f06c9b7'
                data-type='merchant'
                data-variant='150x100-1'
                data-lang='it-IT'
                data-gui='it-IT'></div>
        </div>
    );
};

export default FeedatyButton;
</code>```

Body:
I'm having trouble inserting a third-party script inside a functional component with server-side rendering.

This is the script I should include in a normal HTML document.

Inside react I created a functional component and within useEffect, I created the script.

import { useEffect, useState } from 'react';

const FeedatyButton = () => {
 const [scriptLoaded, setScriptLoaded] = useState(false);

 useEffect(() => {
    const feedatyDiv = document.getElementById('feedatyScript');
    if (typeof window !== undefined && !scriptLoaded && !feedatyDiv) {
        const script = document.createElement('script');
        script.setAttribute('async', '');
        script.setAttribute('id', 'feedatyScript');
        script.src =
                'https://widget.feedaty.com/public/js/feedaty.js?merchant=******&style_ver=2021';
        script.addEventListener('load', () => setScriptLoaded(true));
        document.appendChild(script);
    }
  }, []);

  return (

    );
};

export default FeedatyButton;

The script loads without problem, but nothing appears inside the feedaty_widget div.

If I create the div with createElement and append it to the document or the body, then it works, but it shows at the end of my react app and obviously, it's not what I want.
I want to place it inside my functional component in a specific position.

What could be the problem?

Body:
I was wrong in approach, because I was not updating the component with the code generated by the "feedaty" script.
This is the updated code using ref to update the content

import { useEffect, useState, useRef } from 'react';

const FeedatyButton = () => {
    const feedatyContainerRef = useRef();
    const [scriptLoaded, setScriptLoaded] = useState(false);

    useEffect(() => {
        scriptLoader();
        return () => {
            scriptUnloader();
        };
    }, []);

    useEffect(() => {
        if (!scriptLoaded) return;
    }, [scriptLoaded]);

    const scriptLoader = () => {
        window.addEventListener('load', scriptMover);
        const feedatyDiv = document.getElementById('feedatyScript');
        if (typeof window !== undefined && !feedatyDiv) {
            const script = document.createElement('script');
            script.src =
                'https://widget.feedaty.com/public/js/feedaty.js?merchant=1******&style_ver=2021';
            script.id = 'feedatyScript';
            script.async = true;
            document.body.appendChild(script);
        }
    };

    const scriptUnloader = () => {
        window.removeEventListener('load', scriptMover);
        const feedatyDiv = document.getElementById('feedatyScript');
        document.body.removeChild(document.querySelector('#feedatyScript'));
    };

    // this function get called when script is loaded and i get the content of the widget, so i can update my component using ref
    const scriptMover = () => {
        const feedatyWidgetUpdated = document.getElementById('feedatyWidget');
        feedatyContainerRef.current.appendChild(feedatyWidgetUpdated);
        setScriptLoaded();
    };

    return (
        <div
            className='flex justify-end items-start'
            id='feedatyContainer'
            ref={feedatyContainerRef}>
            <div
                id='feedatyWidget'
                className='feedaty_widget'
                data-id='61fee7f06c9b7'
                data-type='merchant'
                data-variant='150x100-1'
                data-lang='it-IT'
                data-gui='it-IT'></div>
        </div>
    );
};

export default FeedatyButton;


问:
$(d).attr("id") is undefined javascript
I have a variable d that I use like this:

```<code>$(function() {
    for(i = 1; i <= 31; i++) {
        var d = '#days' + i;
        if ($(d).attr("id").substr(4,2) == 11) {
            $(d).addClass("date_has_event");
            //console.log("diez");
        } else {
            console.log("otro");
        }
    }
}
</code>```

However I get the following error in firebug:

```

$(d).attr("id") is undefined
index.html    (L23)   (?)()()
jquery.min.js (L27)   onreadystatechange()()
jquery.min.js (L27)   onreadystatechange()()
jquery.min.js (L21)   nodeName()([function(), function()], function(), undefined)
onreadystatechange()()

```

I really don't understand why. Does anyone know?

Edit

I'm sorry for the poor explanation I had to run, here's what's going on a little bit more detailed. I am generating a calendar using javascript. each td has a different id (hence the #days + i) and I am running it from 1 to 31 so I can cover the longer months. However I am getting the error I mentioned above. I am also using the jQuery library to enable me to select more easily (i.e. instead of getElementById just #days)

答:
Since you are selecting by id, this is redundant:

```<code>if ($(d).attr("id").substr(4,2) == 11)
</code>```

because the ID attribute of d is d.

Is most simple to do:

```<code>if (i == 11)
</code>```

OwnerDisplayName: Proxify

ContentLicense: CC BY-SA 2.5

Title: $(d).attr("id") is undefined javascript

Body:
I have a variable d that I use like this:

$(function() {
    for(i = 1; i <= 31; i++) {
        var d = '#days' + i;
        if ($(d).attr("id").substr(4,2) == 11) {
            $(d).addClass("date_has_event");
            //console.log("diez");
        } else {
            console.log("otro");
        }
    }
}

However I get the following error in firebug:

$(d).attr("id") is undefined
index.html    (L23)   (?)()()
jquery.min.js (L27)   onreadystatechange()()
jquery.min.js (L27)   onreadystatechange()()
jquery.min.js (L21)   nodeName()([function(), function()], function(), undefined)
onreadystatechange()()

I really don't understand why. Does anyone know?

Edit

I'm sorry for the poor explanation I had to run, here's what's going on a little bit more detailed. I am generating a calendar using javascript. each td has a different id (hence the #days + i) and I am running it from 1 to 31 so I can cover the longer months. However I am getting the error I mentioned above. I am also using the jQuery library to enable me to select more easily (i.e. instead of getElementById just #days)

LastEditorDisplayName: Proxify

Body:
Since you are selecting by id, this is redundant:

if ($(d).attr("id").substr(4,2) == 11)

because the ID attribute of d is d.

Is most simple to do:

if (i == 11)

OwnerDisplayName: Ekeko