问:
Why is this Binary search algorithm returning None twice?
Im starting to learn about Algorithms (using the grokkings algorithms book) and this is the binary search code that was in the book

```<code>def binary_search(list, item):

  low = 0
  high = len(list) - 1

  while low <= high:
    mid = round((low + high) )
    guess = list[mid]

    if guess == mid:
      return mid

    if guess > mid:
      high = mid - 1

    else:
      low = mid + 1

  return None

my_list = [1, 3, 5, 7, 9]

print(binary_search(my_list, 3))
print(binary_search(my_list, -1))

</code>```

The first one is supposed to return 1 but it returns None twice, anyone know why?

答: In the code is suppose to be mid = (low + high) // 2, where // is whole division.

Body:
Im starting to learn about Algorithms (using the grokkings algorithms book) and this is the binary search code that was in the book

def binary_search(list, item):

  low = 0
  high = len(list) - 1

  while low <= high:
    mid = round((low + high) )
    guess = list[mid]

    if guess == mid:
      return mid

    if guess > mid:
      high = mid - 1

    else:
      low = mid + 1

  return None

my_list = [1, 3, 5, 7, 9]

print(binary_search(my_list, 3))
print(binary_search(my_list, -1))

The first one is supposed to return 1 but it returns None twice, anyone know why?


来源: stackexchange

问:
Jetpack Compose: UnsupportedOperationException when adding Entries to MPAndroidCharts dynamically
I try to display live data in an MPAndroidChart hosted in an AndroidView.

I get the graph but an UnsupportedOperationException happens when I call addEntry() to update the graph dynamically. Am I doing something wrong?

You find a demo repo in the comments.

@Composable
fun MyLineChart() {
    val mainViewModel = viewModel()
    val sensorData = mainViewModel.sensorFlow.collectAsState(SensorModel(0F,0F)).value

    AndroidView(modifier = Modifier.fillMaxSize(),
        factory = { context ->
            val lineChart = LineChart(context)
            var entries = listOf(Entry(1f,1f))

            val dataSet = LineDataSet(entries, "Label").apply { color = Color.Red.toArgb() }

            val lineData = LineData(dataSet)
            lineChart.data = lineData
            lineChart.invalidate()

            lineChart
        }){

        try {
            Log.d("TAG", "MyLineChart: Update --- Current thread id: ${Thread.currentThread()}")

            it.data.dataSets[0].addEntry(Entry(sensorData.x, sensorData.y))
            it.lineData.notifyDataChanged()
            it.notifyDataSetChanged()
            it.invalidate()
        } catch(ex: Exception) {
            Log.d("TAG", "MyLineChart: $ex")
        }
    }
}
```
<p>The data is sent to the view via the following <code>ViewModel</code>:</p>
<pre class="lang-kotlin prettyprint-override"><code>@HiltViewModel
class MainViewModel @Inject constructor(@ApplicationContext var appContext: Context) : ViewModel()  {
    private var rand: Random = Random(1)

    val sensorFlow: Flow<SensorModel> = flow<SensorModel> {

        while (true) {
            delay(1000L)
            Log.d("TAG", "sensorFlow: Current thread id: ${Thread.currentThread()}")
            emit(SensorModel(rand.nextFloat(), rand.nextFloat()))
        }
    }
}
</code>```

答:
You pass entries to LineDataSet, which is an immutable list.

This library seems to have a pretty bad API, because it doesn't ask for a modifiable list as a parameter, but at the same time it doesn't make it modifiable on its side. This causes you to try to modify the immutable list, which leads to an exception.

Replace

```<code>var entries = listOf(Entry(1f,1f))
</code>```

with

```<code>val entries = mutableListOf(Entry(1f,1f))
</code>```

p.s. I can't advise you another graph library as I haven't worked with any, but I would advise you to look for a library with a better API.

ContentLicense: CC BY-SA 4.0

Body:
I try to display live data in an MPAndroidChart hosted in an AndroidView.

I get the graph but an UnsupportedOperationException happens when I call addEntry() to update the graph dynamically. Am I doing something wrong?

You find a demo repo in the comments.

@Composable
fun MyLineChart() {
    val mainViewModel = viewModel()
    val sensorData = mainViewModel.sensorFlow.collectAsState(SensorModel(0F,0F)).value

    AndroidView(modifier = Modifier.fillMaxSize(),
        factory = { context ->
            val lineChart = LineChart(context)
            var entries = listOf(Entry(1f,1f))

            val dataSet = LineDataSet(entries, "Label").apply { color = Color.Red.toArgb() }

            val lineData = LineData(dataSet)
            lineChart.data = lineData
            lineChart.invalidate()

            lineChart
        }){

        try {
            Log.d("TAG", "MyLineChart: Update --- Current thread id: ${Thread.currentThread()}")

            it.data.dataSets[0].addEntry(Entry(sensorData.x, sensorData.y))
            it.lineData.notifyDataChanged()
            it.notifyDataSetChanged()
            it.invalidate()
        } catch(ex: Exception) {
            Log.d("TAG", "MyLineChart: $ex")
        }
    }
}

The data is sent to the view via the following ViewModel:

@HiltViewModel
class MainViewModel @Inject constructor(@ApplicationContext var appContext: Context) : ViewModel()  {
    private var rand: Random = Random(1)

    val sensorFlow: Flow<SensorModel> = flow<SensorModel> {

        while (true) {
            delay(1000L)
            Log.d("TAG", "sensorFlow: Current thread id: ${Thread.currentThread()}")
            emit(SensorModel(rand.nextFloat(), rand.nextFloat()))
        }
    }
}

Body:
You pass entries to LineDataSet, which is an immutable list.

This library seems to have a pretty bad API, because it doesn't ask for a modifiable list as a parameter, but at the same time it doesn't make it modifiable on its side. This causes you to try to modify the immutable list, which leads to an exception.

Replace

var entries = listOf(Entry(1f,1f))

with

val entries = mutableListOf(Entry(1f,1f))

p.s. I can't advise you another graph library as I haven't worked with any, but I would advise you to look for a library with a better API.


问:
BigQuery - Grouping by date with a WHERE clause
My goal is to search for certain products, count the total per certain product, and group each by day.

Schema is like so:

line_items.sku
created_at

product1
2020-04-02T13:22:44

product2
2020-04-02T05:01:22

product2
2020-04-03T14:21:10

My query is below:

SELECT
  EXTRACT(DAY
  FROM
    CAST(`order`.created_at AS DATETIME)) AS day_extracted,
  EXTRACT(MONTH
  FROM
    CAST(`order`.created_at AS DATETIME)) AS month_extracted,
  `order`.line_items.sku AS sku
FROM
  `mydatabase`
WHERE
  `order`.line_items.sku = "product 1"
  OR `order`.line_items.sku = "product 2"
```
<p>The data is below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>row</th>
<th>day_extracted</th>
<th>month_extracted</th>
<th>sku</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>5</td>
<td>2</td>
<td>product1</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>1</td>
<td>product2</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>1</td>
<td>product1</td>
</tr>
</tbody>
</table>
</div>
<p>This is great and works, but I'm running into issues with needing to grouping the products and count <strong>per product</strong> total per day.</p>
<p>What am I doing wrong? If I add</p>
<pre class="lang-sql prettyprint-override"><code>  GROUP BY month_extracted, day_extracted
</code>```

to the query, another error comes up

```<code>SELECT list expression references `order`.line_items which is neither grouped nor aggregated at [8:3]
</code>```

Line 8 is:

 `order`.line_items.sku AS sku

答:
Mr.Batra led me down the rabbit hole of subqueries and that led me to my solution. Knowing which order queries are executed in made more sense now too.

SELECT day_extracted,month_extracted,Sku,count(*) FROM
    (
SELECT
    EXTRACT(DAY
    FROM
      CAST(`order`.created_at AS DATETIME)) AS day_extracted,
    EXTRACT(MONTH
    FROM
      CAST(`order`.created_at AS DATETIME)) AS month_extracted,
    `order`.line_items.sku AS Sku
  FROM
    `mydatabase`
  WHERE
    `order`.line_items.sku = "product1"
    OR `order`.line_items.sku = "product2"
    ) AS temp
    GROUP BY temp.Sku,day_extracted,month_extracted
    ORDER BY day_extracted
```

This gives me the data in this format:

day_extracted
month_extracted
Sku
col1

1
2
product1
41

1
2
product2
55

2
2
product1
91

Body:
My goal is to search for certain products, count the total per certain product, and group each by day.

Schema is like so:

line_items.sku
created_at

product1
2020-04-02T13:22:44

product2
2020-04-02T05:01:22

product2
2020-04-03T14:21:10

My query is below:

SELECT
  EXTRACT(DAY
  FROM
    CAST(`order`.created_at AS DATETIME)) AS day_extracted,
  EXTRACT(MONTH
  FROM
    CAST(`order`.created_at AS DATETIME)) AS month_extracted,
  `order`.line_items.sku AS sku
FROM
  `mydatabase`
WHERE
  `order`.line_items.sku = "product 1"
  OR `order`.line_items.sku = "product 2"

The data is below:

row
day_extracted
month_extracted
sku

1
5
2
product1

2
4
1
product2

2
4
1
product1

This is great and works, but I'm running into issues with needing to grouping the products and count per product total per day.

What am I doing wrong? If I add

  GROUP BY month_extracted, day_extracted

to the query, another error comes up

SELECT list expression references `order`.line_items which is neither grouped nor aggregated at [8:3]

Line 8 is:

 `order`.line_items.sku AS sku

Body:
Mr.Batra led me down the rabbit hole of subqueries and that led me to my solution. Knowing which order queries are executed in made more sense now too.

SELECT day_extracted,month_extracted,Sku,count(*) FROM
    (
SELECT
    EXTRACT(DAY
    FROM
      CAST(`order`.created_at AS DATETIME)) AS day_extracted,
    EXTRACT(MONTH
    FROM
      CAST(`order`.created_at AS DATETIME)) AS month_extracted,
    `order`.line_items.sku AS Sku
  FROM
    `mydatabase`
  WHERE
    `order`.line_items.sku = "product1"
    OR `order`.line_items.sku = "product2"
    ) AS temp
    GROUP BY temp.Sku,day_extracted,month_extracted
    ORDER BY day_extracted

This gives me the data in this format:

day_extracted
month_extracted
Sku
col1

1
2
product1
41

1
2
product2
55

2
2
product1
91


问:
How to looping trough an array of object when array name is not consistent?
Consider below example:

```<code>const obj ={
price:[{multiple items},{multiple items}],
name:"",
id:"",
}
</code>```

i want to apply foreach on price property but the issue is the property name is changing wrt cases like saleprice , taxprice etc.

if i am using obj.keys() method it doesn't work because it returns key as a string.

答:
You can use "Object.values()" or "Object.fromEntries()" to get the values or both keys & values.

```<code>const obj ={
price:[{multiple items},{multiple items}],
name:"",
id:"",
}

const priceArray = Object.values(obj).find( value => Array.isArray(value))

</code>```

FYI

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

Body:
Consider below example:

const obj ={
price:[{multiple items},{multiple items}],
name:"",
id:"",
}

i want to apply foreach on price property but the issue is the property name is changing wrt cases like saleprice , taxprice etc.

if i am using obj.keys() method it doesn't work because it returns key as a string.

Body:
You can use "Object.values()" or "Object.fromEntries()" to get the values or both keys & values.

const obj ={
price:[{multiple items},{multiple items}],
name:"",
id:"",
}

const priceArray = Object.values(obj).find( value => Array.isArray(value))

FYI

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values


问:
Using HTML in Rails flash messages
I use flash[:error] to display a simple message to users that they cannot do a delete operation under certain conditions. I also have a link that will help them to get information about the entity that they wanted to delete and why they cannot do so.

Is it advisable to include this hyperlink in the flash message? Which would mean that I would have a HTML fragment in my controller. If not, how would I go about doing this?

答:
If you want to include a link in your flash message from the controller there are 2 issues. Generating the link and then getting it displayed as HTML.

To use the link_to helper in the controller, fully qualify it.

To have the string display as html (instead of being escaped), call the html_safe method on the string. So the line in your controller might look like:

```<code>flash[:error] = "You can't do that. #{ActionController::Base.helpers.link_to "Here's why.", '/more_info.html'}".html_safe
</code>```

ContentLicense: CC BY-SA 2.5

Title: Using HTML in Rails flash messages

Body:
If you want to include a link in your flash message from the controller there are 2 issues. Generating the link and then getting it displayed as HTML.

To use the link_to helper in the controller, fully qualify it.

To have the string display as html (instead of being escaped), call the html_safe method on the string. So the line in your controller might look like:

flash[:error] = "You can't do that. #{ActionController::Base.helpers.link_to "Here's why.", '/more_info.html'}".html_safe

ContentLicense: CC BY-SA 3.0


问:
How to convert a 24 hour time to 12 hour in VB.net as hh:mm AM/PM
So let's say I have 1400, I want to convert it into 2:00PM

I tried the following:

```<code>Dim convertedTime As String = DateTime.ParseExact(theTime,"HHmm", Nothing)
</code>```

And it would give me this:

6/12/2012 02:00:00 PM

I do not want the date part, neither do I need the seconds. All I need is 2:00PM

How could I achieve this? Thanks!

答:
You Can Use String.Format() Function Without ParseExtract() Function

VB.NET:-

```<code>Dim time As String = String.Format("{0:hh}:{0:mm} {0:tt}", Date.Now) '12:00 PM'
Dim time_1 As String = String.Format("{0:hh}:{0:mm}:{0:ss} {0:tt}", Date.Now) '12:00:25 PM'
Dim time_2 As String = String.Format("{0:mm}:{0:ss}.{0:fff}", Date.Now) '00:25.986 - Mostly Used In Stopwatches'
</code>```

CSharp (C#):-

```<code>String time = String.Format("{0:hh}:{0:mm} {0:tt}", DateTime.Now); // 12:00 PM
String time_1 = String.Format("{0:hh}:{0:mm}:{0:ss} {0:tt}", DateTime.Now); // 12:00:25 PM
String time_2 = String.Format("{0:mm}:{0:ss}.{0:fff}", DateTime.Now); // 00:25.986 - Mostly Used In Stopwatches
</code>```

Above Codes Are Examples, You Can Use Above Codes To Experiment/Observe/Make Applications With It

Body:
So let's say I have 1400, I want to convert it into 2:00PM

I tried the following:

Dim convertedTime As String = DateTime.ParseExact(theTime,"HHmm", Nothing)

And it would give me this:

6/12/2012 02:00:00 PM

I do not want the date part, neither do I need the seconds. All I need is 2:00PM

How could I achieve this? Thanks!

Body:
You Can Use String.Format() Function Without ParseExtract() Function

VB.NET:-

Dim time As String = String.Format("{0:hh}:{0:mm} {0:tt}", Date.Now) '12:00 PM'
Dim time_1 As String = String.Format("{0:hh}:{0:mm}:{0:ss} {0:tt}", Date.Now) '12:00:25 PM'
Dim time_2 As String = String.Format("{0:mm}:{0:ss}.{0:fff}", Date.Now) '00:25.986 - Mostly Used In Stopwatches'

CSharp (C#):-

String time = String.Format("{0:hh}:{0:mm} {0:tt}", DateTime.Now); // 12:00 PM
String time_1 = String.Format("{0:hh}:{0:mm}:{0:ss} {0:tt}", DateTime.Now); // 12:00:25 PM
String time_2 = String.Format("{0:mm}:{0:ss}.{0:fff}", DateTime.Now); // 00:25.986 - Mostly Used In Stopwatches

Above Codes Are Examples, You Can Use Above Codes To Experiment/Observe/Make Applications With It


问:
How do I reference a cell in range of worksheets and look for a specific value in Excel?
Is this possible?

```<code>=IF(COUNTIF('**ALLSHEETS**'!D4, "ICT"),**SHEETNAME**, FALSE)
</code>```

Excel will look up a a specific value ("ICT") in the same cell in every sheet then if that cell contains the value it will return the name of the sheet(s)

答:
You can do it with a little trick

Put this Formula in Cell A1 of Everysheet you want to get searched

```<code>=IF(D4="ICT",MID(@CELL("filename",A1),FIND("]",@CELL("filename",A1))+1,255),"")
</code>```

Then, in the required sheet!cell add all sheets like

```<code>=Sheet1!A1&Sheet2!A1&Sheet3!A1
</code>```

Note: If it would be only one sheet having ICT and you are trying to find the sheet name, then this would be the easiest solution
But in case of multiple sheets having ICT in D4, the result would be a like

```<code>sheet1sheet2sheet3 in the same cell.
</code>```

Body:
Is this possible?

=IF(COUNTIF('**ALLSHEETS**'!D4, "ICT"),**SHEETNAME**, FALSE)

Excel will look up a a specific value ("ICT") in the same cell in every sheet then if that cell contains the value it will return the name of the sheet(s)

Body:
You can do it with a little trick

Put this Formula in Cell A1 of Everysheet you want to get searched

=IF(D4="ICT",MID(@CELL("filename",A1),FIND("]",@CELL("filename",A1))+1,255),"")

Then, in the required sheet!cell add all sheets like

=Sheet1!A1&Sheet2!A1&Sheet3!A1

Note: If it would be only one sheet having ICT and you are trying to find the sheet name, then this would be the easiest solution
But in case of multiple sheets having ICT in D4, the result would be a like

sheet1sheet2sheet3 in the same cell.


问:
Updating file in S3 bucket. Still getting '304 - Not modified'
I have a setup consisting of a S3 bucket containing a single ZIP file which is updated regularly. I have set up a cloudfront to make it available via https.

It works just fine, as in I get the file if I request the url. However, the response returns with a "304 - Not modified". I have tried to rename the file and to upload a new file to replace the old one. It still says "304 - Not modified".

I have tried to fiddle around with the Edge cache settings on the CloudFront behavior page. No luck, always just returns "304..."

What am I missing here?

答:
I was facing the same concern, did the hard refresh which resolved the issue and loaded the new s3 scripts.

To do hard refresh in windows chrome , use below command:

```<code>ctrl+shift+r
</code>```

Body:
I was facing the same concern, did the hard refresh which resolved the issue and loaded the new s3 scripts.

To do hard refresh in windows chrome , use below command:

ctrl+shift+r


问:
Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
I am using the following code to make a knex connection, but frequently the error occurred

Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?

Can anyone please suggest the solution for this issue?

```<code>var knexConn = reqKnex({
        client: pClient,
        native: false,
        connection: pConn,
        searchPath: pSearchPath,
        pool: {
            max: 7,
            min: 3,
            acquireTimeout: 60 * 1000
        }
    });

function getTransactionScope(pKnex, callback) {
    try {
        pKnex.transaction(function(trx) {
            return callback(trx);
        });
    } catch (error) {
        console.log(error);
    }
}

function ExecuteSQLQuery(pTranDB, pTrx, pQuery, pCallback) {
    try {
        var query = pTranDB.raw(pQuery);

        if (pTrx) {
            query = query.transacting(pTrx);
        }
        query.then(function(res, error) {
            try {
                if (error) {
                    console.log(error);
                } else {
                    return pCallback(res, error);
                }
            } catch (error) {
                console.log(error);
            }
        }).catch(function(error) {
            return pCallback(null, error);
        });
    } catch (error) {
        console.log(error);
    }
}

function Commit(pTrx, pIsCommit) {
    try {
        if (pIsCommit) {
            pTrx.commit();
        } else {
            pTrx.rollback();
        }
    } catch (error) {
        console.log(error);
    }
}
</code>```

答: Also check that your IP is among trusted sources on your DB. That was the issue for me:

Body:
I am using the following code to make a knex connection, but frequently the error occurred

Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?

Can anyone please suggest the solution for this issue?

var knexConn = reqKnex({
        client: pClient,
        native: false,
        connection: pConn,
        searchPath: pSearchPath,
        pool: {
            max: 7,
            min: 3,
            acquireTimeout: 60 * 1000
        }
    });

function getTransactionScope(pKnex, callback) {
    try {
        pKnex.transaction(function(trx) {
            return callback(trx);
        });
    } catch (error) {
        console.log(error);
    }
}

function ExecuteSQLQuery(pTranDB, pTrx, pQuery, pCallback) {
    try {
        var query = pTranDB.raw(pQuery);

        if (pTrx) {
            query = query.transacting(pTrx);
        }
        query.then(function(res, error) {
            try {
                if (error) {
                    console.log(error);
                } else {
                    return pCallback(res, error);
                }
            } catch (error) {
                console.log(error);
            }
        }).catch(function(error) {
            return pCallback(null, error);
        });
    } catch (error) {
        console.log(error);
    }
}

function Commit(pTrx, pIsCommit) {
    try {
        if (pIsCommit) {
            pTrx.commit();
        } else {
            pTrx.rollback();
        }
    } catch (error) {
        console.log(error);
    }
}


问:
Getting an AddressFilter Mismatch When Forwarding WCF Traffic Through an HAPRoxy Server on a Different Port
My client application makes WCF calls through an HAProxy server on port 8080 which then forwards the traffic to the application server on port 770 which is the port that the application server is expecting. However, WCF is detecting the mismatch of ports 8080 vs 770 and reports the following error:

The message with To 'net.tcp://172.31.31.219:8080/MyEndpoint' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher.  Check that the sender and receiver's EndpointAddresses agree.

How can I support this scenario? Everything works fine if I update the client to send traffic on port 770, but this is a special scenario where I want to support different ports.

答:
I want to support different ports.

Maybe you can configure multiple endpoints on the service and implement communication with each endpoint from the client, you can check out the tutorial.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/multiple-endpoints

The message with To 'net.tcp://172.31.31.219:8080/MyEndpoint' cannot
be processed at the receiver, due to an AddressFilter mismatch at the
EndpointDispatcher. Check that the sender and receiver's
EndpointAddresses agree.

You can check this post for the solution to this error.

If the service has only one endpoint, a quick workaround is to use

```<code>[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]
</code>```

This will turn off the address filter.

Or include the following in the SOAP header to access the web service:

```<code><soap:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:To>http://example.com/service</wsa:To>
</soap:title>
</code>```

Body:
I want to support different ports.

Maybe you can configure multiple endpoints on the service and implement communication with each endpoint from the client, you can check out the tutorial.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/multiple-endpoints

The message with To 'net.tcp://172.31.31.219:8080/MyEndpoint' cannot
be processed at the receiver, due to an AddressFilter mismatch at the
EndpointDispatcher. Check that the sender and receiver's
EndpointAddresses agree.

You can check this post for the solution to this error.

If the service has only one endpoint, a quick workaround is to use

[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]

This will turn off the address filter.

Or include the following in the SOAP header to access the web service:

<soap:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:To>http://example.com/service</wsa:To>
</soap:title>


问:
How to keep viewModel state when fragment is destroyed?
I have an issue with keeping the state of data in a viewModel. The viewModel that I have is initialised inside of the onViewCreated method like this:

```<code>val viewModel: PlayerViewModelImpl by viewModels {
            ViewModelFactory(
              PlayerRepositoryImpl(MockContentProviderImpl()),
              ClipsAudioPlayerImpl.getInstance(requireActivity()),
              storage
            )
          }
</code>```

and whenever i go back, and then open the fragment again I lose all the data that was processed inside of the viewModel. Does anyone have an idea on how can I retain the data and state of the viewModel for this scenario?
Also here is my ViewModelFactory class:

```<code>/**
 * Factory for view models.
 */
class ViewModelFactory(
  private val repository: PlayerRepository,
  private val player: ClipsAudioPlayer<ClipsModel>,
  private val storage: PreferencesStorage): ViewModelProvider.NewInstanceFactory() {

  override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T = PlayerViewModelImpl(repository,storage,player) as T
}
</code>```

Any help will be very much appreciated! Thanks

答:
You need to declare the scope of the ViewModel to a context greater than the Fragments.

```<code>val factory = ViewModelFactory(
    PlayerRepositoryImpl(MockContentProviderImpl()),
    ClipsAudioPlayerImpl.getInstance(requireActivity()),
    storage
)
viewModel = ViewModelProvider(requireActivity(),factory).get(PlayerViewModelImpl::class.java)
</code>```

As long as the current activity isn't destroyed the ViewModel should be preserved.

Body:
I have an issue with keeping the state of data in a viewModel. The viewModel that I have is initialised inside of the onViewCreated method like this:

val viewModel: PlayerViewModelImpl by viewModels {
            ViewModelFactory(
              PlayerRepositoryImpl(MockContentProviderImpl()),
              ClipsAudioPlayerImpl.getInstance(requireActivity()),
              storage
            )
          }

and whenever i go back, and then open the fragment again I lose all the data that was processed inside of the viewModel. Does anyone have an idea on how can I retain the data and state of the viewModel for this scenario?
Also here is my ViewModelFactory class:

/**
 * Factory for view models.
 */
class ViewModelFactory(
  private val repository: PlayerRepository,
  private val player: ClipsAudioPlayer<ClipsModel>,
  private val storage: PreferencesStorage): ViewModelProvider.NewInstanceFactory() {

  override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T = PlayerViewModelImpl(repository,storage,player) as T
}

Any help will be very much appreciated! Thanks

Body:
You need to declare the scope of the ViewModel to a context greater than the Fragments.

val factory = ViewModelFactory(
    PlayerRepositoryImpl(MockContentProviderImpl()),
    ClipsAudioPlayerImpl.getInstance(requireActivity()),
    storage
)
viewModel = ViewModelProvider(requireActivity(),factory).get(PlayerViewModelImpl::class.java)

As long as the current activity isn't destroyed the ViewModel should be preserved.


答:
Try comparing guess with item:

```<code>def binary_search(lst, item):
    low = 0
    high = len(lst) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = lst[mid]
        if guess < item:
            low = mid + 1
        elif guess > item:
            high = mid - 1
        else:
            return mid
    return None

my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 3))
print(binary_search(my_list, -1))
</code>```

Output:

```<code>1
None
</code>```

Title: Why is this Binary search algorithm returning None twice?

Body:
Im starting to learn about Algorithms (using the grokkings algorithms book) and this is the binary search code that was in the book

def binary_search(list, item):

  low = 0
  high = len(list) - 1

  while low <= high:
    mid = round((low + high) )
    guess = list[mid]

    if guess == mid:
      return mid

    if guess > mid:
      high = mid - 1

    else:
      low = mid + 1

  return None

my_list = [1, 3, 5, 7, 9]

print(binary_search(my_list, 3))
print(binary_search(my_list, -1))

The first one is supposed to return 1 but it returns None twice, anyone know why?

Body:
Try comparing guess with item:

def binary_search(lst, item):
    low = 0
    high = len(lst) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = lst[mid]
        if guess < item:
            low = mid + 1
        elif guess > item:
            high = mid - 1
        else:
            return mid
    return None

my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 3))
print(binary_search(my_list, -1))

Output:

1
None


问:
Codeigniter htaccess adds an extra forward slash
This is my current .htaccess:

```<code>Options +FollowSymLinks +SymLinksIfOwnerMatch
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L]
</code>```

My config file:

```<code>$config['base_url'] = 'http://localhost/argh/';
$config['index_page'] = '';
</code>```

And when I click, for example, on the about us link it looks like this:

```<code>http://localhost/argh//about
</code>```

(2 forward slashes between argh and about)

Any suggestion? : )

EDIT:

Not sure, but this looks like a Codeigniter issue, because the function:

```<code>function site_url($uri = '')
{
    if ($uri == '')
    {
        return $this->slash_item('base_url').$this->item('index_page');
    }

    if ($this->item('enable_query_strings') == FALSE)
    {
        $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix');
        return $this->slash_item('base_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix;
    }
    else
    {
        return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri);
    }
}
</code>```

More precisely here:

```<code>return $this->slash_item('base_url').$this->item('index_page');
</code>```

returns the base_url when:

```<code>$config['index_page'] = '';
</code>```

That's why the previous example ends like this:

```<code>http://localhost/argh//about
</code>```

答:
this work

"  change to    '">

Body:
This is my current .htaccess:

Options +FollowSymLinks +SymLinksIfOwnerMatch
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L]

My config file:

$config['base_url'] = 'http://localhost/argh/';
$config['index_page'] = '';

And when I click, for example, on the about us link it looks like this:

http://localhost/argh//about

(2 forward slashes between argh and about)

Any suggestion? : )

EDIT:

Not sure, but this looks like a Codeigniter issue, because the function:

function site_url($uri = '')
{
    if ($uri == '')
    {
        return $this->slash_item('base_url').$this->item('index_page');
    }

    if ($this->item('enable_query_strings') == FALSE)
    {
        $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix');
        return $this->slash_item('base_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix;
    }
    else
    {
        return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri);
    }
}

More precisely here:

return $this->slash_item('base_url').$this->item('index_page');

returns the base_url when:

$config['index_page'] = '';

That's why the previous example ends like this:

http://localhost/argh//about

Body:
this work

<a href="<?php echo site_url('Controller_Name') ?>" </a> change to    <a href="#" onclick="window.location='<?php echo site_url('Controller_Name'); ?>'"></a>


问:
Is git notes the intended way to add category-style information to a commit?
The answer to Can I add metadata to git commits? Or can I hide some tags in gitk mentions git notes as a way to add metadata to a git commit.

Is git notes, possibly taking advantage of its namespace functionality in case I want to add other types of notes, the best way to categorize commits? For example, I'd like to categorize commits into "refactoring", "change-functionality", "bug-fix", "bug-introduce", and be able to ask git to only list commits that are in certain categories.

答:
What you are proposing is quite similar to what the ruby-based gem "step-up" is doing, based on git notes.

The great goal of this Gem is giving to developers an easy way to manage these notes.

With a culture of notating all the relevant developments, its possible to retrieve a summary of a range of versions besides that specifying what kind of information will be retrieved.

  For example, imagine that you want to see all the features implemented in your application since the version v1.10.1 up to v2.0.0

```<code>stepup notes --since v1.10.1 upto v2.0.0 --sections pre_deploy pos_deploy
</code>```

The result would be something like the following:

```<code>Showing notes since v1.10.1 up to v2.0.0 (including notes of tags: v1.10.1, v1.10.2, v1.51.0, v2.0.0)
---
Pre-Deploy:

  - dependency of version v10 of project XYZ
  - it needed to rename the following file
    - config/environment_variables.yml.sample -> config/environment_variables.yml
  - rake articles:index

Pos-Deploy:

  - Reindex articles
    - rake articles:index
  - rake db:seed
  - rake categories:reload
</code>```

ranged_notes.rb will define functions to get all the relevant commits, based on their notes.

git.rb contains the actual git notes commands.

Body:
What you are proposing is quite similar to what the ruby-based gem "step-up" is doing, based on git notes.

The great goal of this Gem is giving to developers an easy way to manage these notes.

With a culture of notating all the relevant developments, its possible to retrieve a summary of a range of versions besides that specifying what kind of information will be retrieved.

  For example, imagine that you want to see all the features implemented in your application since the version v1.10.1 up to v2.0.0

stepup notes --since v1.10.1 upto v2.0.0 --sections pre_deploy pos_deploy

The result would be something like the following:

Showing notes since v1.10.1 up to v2.0.0 (including notes of tags: v1.10.1, v1.10.2, v1.51.0, v2.0.0)
---
Pre-Deploy:

  - dependency of version v10 of project XYZ
  - it needed to rename the following file
    - config/environment_variables.yml.sample -> config/environment_variables.yml
  - rake articles:index

Pos-Deploy:

  - Reindex articles
    - rake articles:index
  - rake db:seed
  - rake categories:reload

ranged_notes.rb will define functions to get all the relevant commits, based on their notes.

git.rb contains the actual git notes commands.


问:
How to align a span element vertically center inside a div?
I am trying to align a span vertically centered. But its not working.

Here is my code:

    Purchase Order

```

Actually, i am converting above code to pdf instead html rendering using wkhtmltopdf.

答:
Use display:flex;, align-items:center; on parent div and display:inline-block; on span element to make it an actual block element.

    Purchase Order

```

Body:
I am trying to align a span vertically centered. But its not working.

Here is my code:

    Purchase Order

Actually, i am converting above code to pdf instead html rendering using wkhtmltopdf.

Body:
Use display:flex;, align-items:center; on parent div and display:inline-block; on span element to make it an actual block element.

<div style="height:150px; width:100%;">
  <div style="height:150px;width:150px;;background-color:blue;display: inline-block;">
    <img style="width:100%;float:left;height:100%;" t-att-src="'data:image/png;base64,%s' % to_text(o.company_id.header_image)" />
  </div>
  <div style="height:150px;width:400px;float:right;background-color:red;display: flex;align-items:center;">
    <span style="display:inline-block;font-size:40px;vertical-align:middle;padding-left:16%;"><b>Purchase Order</b></span>
  </div>
</div>


问:
MySQL Query Comparing DateTime not give the right row
dosen_schedule_datetimestart , dosen_schedule_datetimeend , academic_schedule_datetimestart , academic_schedule_datetimeendis formatted in DATETIME Format YYYY-MM-DD HH:MM:SS

This was my MySQL Query, so what i want to do is SELECT Row that Today is still in between  datetimestart and datetimeend And TIME of datetimestart is less than 15 minutes compared to current time

But it doesnt work, and i also comparing academic_schedule_dow with Today's DOW

Any Idea?

```<code>$checkdosenschedule = mysqli_query($conn, "SELECT dosen_schedule_table.*, dosen_table.*, TIME(dosen_schedule_table.dosen_schedule_datetimestart) AS dosen_schedule_checkstart FROM dosen_schedule_table
                                        INNER JOIN dosen_table
                                        ON dosen_table.dosen_id = dosen_schedule_table.dosen_id
                                        WHERE (dosen_schedule_status = 'Active' AND dosen_subs_id != '' ) AND ((DATE(dosen_schedule_datetimestart) >= CURDATE() AND DATE(dosen_schedule_datetimeend) >= CURDATE()) AND (TIME(dosen_schedule_datetimestart) > (NOW() - INTERVAL 15 MINUTE)))");

$checkacademicschedule = mysqli_query($conn, "SELECT academic_schedule_table.*, dosen_table.* FROM academic_schedule_table
                                    INNER JOIN dosen_table
                                    ON dosen_table.dosen_id = academic_schedule_table.dosen_id
                                    WHERE ((academic_schedule_status = 'Active' AND dosen_subs_id != '' ) AND academic_schedule_dow = DAYOFWEEK(NOW())) AND ((DATE(academic_schedule_datetimestart) >= CURDATE() AND DATE(academic_schedule_datetimeend) >= CURDATE()) AND (TIME(academic_schedule_datetimestart) > (NOW() - INTERVAL 15 MINUTE)))");
</code>```

答:
Try using DATE(NOW()) instead of CURDATE()
Also you are checking the range with same sign of greater then equal to.
If you want to check in between, use >= for start and <= for end.</p>

Body:
dosen_schedule_datetimestart , dosen_schedule_datetimeend , academic_schedule_datetimestart , academic_schedule_datetimeendis formatted in DATETIME Format YYYY-MM-DD HH:MM:SS

This was my MySQL Query, so what i want to do is SELECT Row that Today is still in between  datetimestart and datetimeend And TIME of datetimestart is less than 15 minutes compared to current time

But it doesnt work, and i also comparing academic_schedule_dow with Today's DOW

Any Idea?

$checkdosenschedule = mysqli_query($conn, "SELECT dosen_schedule_table.*, dosen_table.*, TIME(dosen_schedule_table.dosen_schedule_datetimestart) AS dosen_schedule_checkstart FROM dosen_schedule_table
                                        INNER JOIN dosen_table
                                        ON dosen_table.dosen_id = dosen_schedule_table.dosen_id
                                        WHERE (dosen_schedule_status = 'Active' AND dosen_subs_id != '' ) AND ((DATE(dosen_schedule_datetimestart) >= CURDATE() AND DATE(dosen_schedule_datetimeend) >= CURDATE()) AND (TIME(dosen_schedule_datetimestart) > (NOW() - INTERVAL 15 MINUTE)))");

$checkacademicschedule = mysqli_query($conn, "SELECT academic_schedule_table.*, dosen_table.* FROM academic_schedule_table
                                    INNER JOIN dosen_table
                                    ON dosen_table.dosen_id = academic_schedule_table.dosen_id
                                    WHERE ((academic_schedule_status = 'Active' AND dosen_subs_id != '' ) AND academic_schedule_dow = DAYOFWEEK(NOW())) AND ((DATE(academic_schedule_datetimestart) >= CURDATE() AND DATE(academic_schedule_datetimeend) >= CURDATE()) AND (TIME(academic_schedule_datetimestart) > (NOW() - INTERVAL 15 MINUTE)))");


问:
How does one enable Intel Processor Tracing (IPT) in a virtualized environment?
I am attempting to run Alex Ionescu's WinIPT interface in a virtual machine, and having no success.  (This is a Windows 10 Pro host running a Windows 10 VM and both are the 18363 update)

I have successfully built and run Intel's driver as well as Alex's toolchain on the host, and processed the trace with ptxed.  I have also run Intel's cpuid utility, and verified that the INTEL_PROCESSOR_TRACE feature is active on the host.  However, when I run the utility in a VM, it does not display the INTEL_PROCESSOR_TRACE flag, and indeed, the driver returns an error that the feature is not enabled.

I've attempted to run the same setup in several different virtual environments, including the latest versions of VirtualBox, VMWare Workstation, and Hyper-V.

When I enable the Hyper-V Platform, it silently disables the INTEL_PROCESSOR_TRACE feature on the host.

VMWare Workstation doesn't disable it directly, but when I tried to run my trace tool again on the host after starting the VM, it threw a BSoD, so I don't have high hopes there.

VirtualBox at least didn't take away any functionality, but even when I enabled the VT-x passthrough option, it still didn't have the flag set to enable IPT.

According to Microsoft, a process theoretically exists to enable this in Hyper-V, though I run into the aforementioned problem where it ends up disabled on my host:

Enabling performance monitoring components in a virtual machine

Has anyone gotten this to work?  I'd prefer a solution in my current environment (Windows VM on Windows host), but I'd appreciate any insights using perf on Linux or any other approaches.  I've also found some posts and questions from 2017 indicating IPT wasn't supported 'yet', but nothing within the past year or so.  The technology and architecture seem to still be evolving, so really I'd like to know if anyone has had success in any form, as well as any insights on what to do or avoid.

Other resources:

Background on Intel Processor Tracing:  Processor Tracing

Edited to add (2/10/2020)

Looking at the Microsoft instructions more carefully, they mention that you need "An Intel processor that supports IPT and the PT2GPA feature" to enable IPT in a virtual machine.  According to Intel, the only architecture they have listed as supporting PT2GPA is Ice Lake.

The computer I'm currently working with is running an earlier microarchitectutre (Coffee Lake), which may explain the behavior I'm seeing where IPT is fine on the host.  Can anyone confirm that they have it working on a more recent processor?

答:
In my case, WinIPT and my implementation using libipt worked fine in Hyper-V (both the host and the guest runs Windows 10 21H1).

However, the PT buffer size is reduced to 2MB for the Hyper-V guest, while the buffer size is 10MB in my Xeon Gold 6136 CPU.


问:
how do i create a variable from the output of another in bash
Here's an example script that doesn't work the way I expect:

```<code>#!/bin/bash
for dynamic in a b c; do
  myvar=$dynamic

  export $myvar="hi"

  echo $(eval "$myvar")
  echo $dynamic
done
</code>```

I want the output would be:

```<code>hi

a

hi

b

hi

c
</code>```

Any ideas?  I'm willing to stray away from this method, but I definitely want to be able to create a variable named from the output of an algorithm.  In this case it's just a for loop.

答:
It's not entirely clear that this is what you're looking for, but I think you want something like:</p>

```
#!/bin/sh

a=A
b=B
c=C
for i in a b c; do
        eval $i=value_$i
        eval echo \$$i
done
echo $a  # Prints "value_a"
```

Body:
Here's an example script that doesn't work the way I expect:

#!/bin/bash
for dynamic in a b c; do
  myvar=$dynamic

  export $myvar="hi"

  echo $(eval "$myvar")
  echo $dynamic
done

I want the output would be:

hi

a

hi

b

hi

c

Any ideas?  I'm willing to stray away from this method, but I definitely want to be able to create a variable named from the output of an algorithm.  In this case it's just a for loop.

Body:
It's not entirely clear that this is what you're looking for, but I think you want something like:

#!/bin/sh

a=A
b=B
c=C
for i in a b c; do
        eval $i=value_$i
        eval echo \$$i
done
echo $a  # Prints "value_a"


问:
How to configure AWS CDK Account and Region to look up a VPC
I am learning the AWS CDK, and this is a problem I can't seem to figure out. JS/Node are not languages I use often, so if there is some obvious native thing that I am missing, please don't be too harsh. I'm trying to deploy a container to an existing VPC / new ECS Cluster. The following code isn't my whole script but is an important part. Hopefully, it gives the idea of what I'm trying to do.

//import everything first

stack_name = "frontend";

class Frontend extends core.Stack {
constructor(scope, id, props = {}) {
    super(scope, id);

    console.log("env variable " + JSON.stringify(props));

    const base_platform = new BasePlatform(this, id, props);

    //this bit doesn't matter, I'm just showing the functions I'm calling to set everything up

    const fargate_load_balanced_service = ecs_patterns.ApplicationLoadBalancedFargateService();
    this.fargate_load_balanced_service.taskDefinition.addToTaskRolePolicy();
    this.fargate_load_balanced_service.service.connections.allowTo();
    const autoscale = this.fargate_load_balanced_service.service.autoScaleTaskCount({});
    this.autoscale.scale_on_cpu_utilization();
    }
}

class BasePlatform extends core.Construct {
constructor(scope, id, props = {}) {
    super(scope, id);
    this.environment_name="frontend";

    console.log("environment variables " + JSON.stringify(process.env));

    //This bit is my problem child

    const vpc = ec2.Vpc.fromLookup(
        this, "VPC",{
        vpcId: 'vpc-##########'
    });

    //this bit doesn't matter, I'm just showing the functions I'm calling to set everything up

    const sd_namespace = service_discovery.PrivateDnsNamespace.from_private_dns_namespace_attributes();
    const ecs_cluster = ecs.Cluster.from_cluster_attributes();
    const services_sec_grp = ec2.SecurityGroup.from_security_group_id();
    }
}

const app = new core.App();

_env = {account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION };

new Frontend(app, stack_name, {env: _env});

app.synth();
```

When I run CDK synth, it spits out:

Error: Cannot retrieve the value from context provider vpc-provider since the account/region is not specified at the stack level. Either configure "env" with explicit account and region when you define your stack or use the environment variables "CDK_DEFAULT_ACCOUNT" and "CDK_DEFAULT_REGION" to inherit environment information from the CLI (not recommended for production stacks)

But I don't know why. My usage here fits several other Stackoverflow answers to similar questions, it loos like the examples in the AWS docs, and when I console.log(process.env), it spits out the correct/expected values of CDK_DEFAULT_REGION and CDK_DEFAULT_ACCOUNT. When I log "env" it spits out the expected values as well.

So my question is, how do I configure my environment so ec2.Vpc.fromLookup knows my account info, or how do I pass the values properly to "env"?

答:
Replace super(scope, id)  with super(scope, id, props);

The props need to be passed to super for the vpc-provider to use it.

Body:
I am learning the AWS CDK, and this is a problem I can't seem to figure out. JS/Node are not languages I use often, so if there is some obvious native thing that I am missing, please don't be too harsh. I'm trying to deploy a container to an existing VPC / new ECS Cluster. The following code isn't my whole script but is an important part. Hopefully, it gives the idea of what I'm trying to do.

//import everything first

stack_name = "frontend";

class Frontend extends core.Stack {
constructor(scope, id, props = {}) {
    super(scope, id);

    console.log("env variable " + JSON.stringify(props));

    const base_platform = new BasePlatform(this, id, props);

    //this bit doesn't matter, I'm just showing the functions I'm calling to set everything up

    const fargate_load_balanced_service = ecs_patterns.ApplicationLoadBalancedFargateService();
    this.fargate_load_balanced_service.taskDefinition.addToTaskRolePolicy();
    this.fargate_load_balanced_service.service.connections.allowTo();
    const autoscale = this.fargate_load_balanced_service.service.autoScaleTaskCount({});
    this.autoscale.scale_on_cpu_utilization();
    }
}

class BasePlatform extends core.Construct {
constructor(scope, id, props = {}) {
    super(scope, id);
    this.environment_name="frontend";

    console.log("environment variables " + JSON.stringify(process.env));

    //This bit is my problem child

    const vpc = ec2.Vpc.fromLookup(
        this, "VPC",{
        vpcId: 'vpc-##########'
    });

    //this bit doesn't matter, I'm just showing the functions I'm calling to set everything up

    const sd_namespace = service_discovery.PrivateDnsNamespace.from_private_dns_namespace_attributes();
    const ecs_cluster = ecs.Cluster.from_cluster_attributes();
    const services_sec_grp = ec2.SecurityGroup.from_security_group_id();
    }
}

const app = new core.App();

_env = {account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION };

new Frontend(app, stack_name, {env: _env});

app.synth();

When I run CDK synth, it spits out:

Error: Cannot retrieve the value from context provider vpc-provider since the account/region is not specified at the stack level. Either configure "env" with explicit account and region when you define your stack or use the environment variables "CDK_DEFAULT_ACCOUNT" and "CDK_DEFAULT_REGION" to inherit environment information from the CLI (not recommended for production stacks)

But I don't know why. My usage here fits several other Stackoverflow answers to similar questions, it loos like the examples in the AWS docs, and when I console.log(process.env), it spits out the correct/expected values of CDK_DEFAULT_REGION and CDK_DEFAULT_ACCOUNT. When I log "env" it spits out the expected values as well.

So my question is, how do I configure my environment so ec2.Vpc.fromLookup knows my account info, or how do I pass the values properly to "env"?


问:
Android studio can't see the design?
I have been doing it in Android studio for a few days but I have never had such a problem :(

Background  blank only text showing androidx.constraintlayout....ConstraintLayout

XML file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Gradle file

```<code>dependencies {

implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
</code>```

enter image description here

```<code>dependencies {
    classpath "com.android.tools.build:gradle:7.0.4"

    // NOTE: Do not place your application dependencies here; they
    belong
    // in the individual module build.gradle files
}
</code>```

答:
I think it's related to the Gradle script file version issue just see your dependencies and change if it is outdated.. maybe this can help?

```<code>dependencies {
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

</code>```

and sync it !!

Title: Android studio can't see the design?

Body:
I have been doing it in Android studio for a few days but I have never had such a problem :(

Background  blank only text showing androidx.constraintlayout....ConstraintLayout

XML file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>

Gradle file

dependencies {

implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

enter image description here

dependencies {
    classpath "com.android.tools.build:gradle:7.0.4"

    // NOTE: Do not place your application dependencies here; they
    belong
    // in the individual module build.gradle files
}

Body:
I think it's related to the Gradle script file version issue just see your dependencies and change if it is outdated.. maybe this can help?

dependencies {
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

and sync it !!


问:
Uncaught Error in jQuery UI ToolTip with Select2
I am using jQuery UI ToolTip with Select2. My code is like below.

```<code>let selectEle = cellEle.children("select").select2({
    //more code here
});

selectEle.on("select2:opening", function (e) {
            $(document).on('hover', '.select2-results__option', function () {
              $(this).tooltip({
                position: {
                  my: "center bottom-20",
                  at: "center top",
                  using: function( position, feedback ) {
                    $(this).css(position);
                    var txt = $(this).text();
                    $(this).html(txt);
                    $( "<div>" )
                      .addClass( "arrow" )
                      .addClass( feedback.vertical )
                      .addClass( feedback.horizontal )
                      .appendTo( this );
                  }
                }
              });
            });
          });

selectEle.on("select2:closing", function (e) {
  $('.select2-results__option').tooltip('close');
});
</code>```

But I am getting Uncaught Error: cannot call methods on tooltip prior to initialization; attempted to call method 'close'.

答:
You could use this:

```<code>$('.select2-results__option').hide();
</code>```

instead of :

```<code>$('.select2-results__option').tooltip('close');
</code>```

and keep it in mind that all of your jquery code should be in $(document).ready(function () { // here  }) function like this:

```<code>$(document).ready(function () {
let selectEle = cellEle.children("select").select2({
    //more code here
});

selectEle.on("select2:opening", function (e) {
            $(document).on('hover', '.select2-results__option', function () {
              $(this).tooltip({
                position: {
                  my: "center bottom-20",
                  at: "center top",
                  using: function( position, feedback ) {
                    $(this).css(position);
                    var txt = $(this).text();
                    $(this).html(txt);
                    $( "<div>" )
                      .addClass( "arrow" )
                      .addClass( feedback.vertical )
                      .addClass( feedback.horizontal )
                      .appendTo( this );
                  }
                }
              });
            });
          });

   selectEle.on("select2:closing", function (e) {
      $('.select2-results__option').hide();
   });
})
</code>```

Body:
I am using jQuery UI ToolTip with Select2. My code is like below.

let selectEle = cellEle.children("select").select2({
    //more code here
});

selectEle.on("select2:opening", function (e) {
            $(document).on('hover', '.select2-results__option', function () {
              $(this).tooltip({
                position: {
                  my: "center bottom-20",
                  at: "center top",
                  using: function( position, feedback ) {
                    $(this).css(position);
                    var txt = $(this).text();
                    $(this).html(txt);
                    $( "
" )
                      .addClass( "arrow" )
                      .addClass( feedback.vertical )
                      .addClass( feedback.horizontal )
                      .appendTo( this );
                  }
                }
              });
            });
          });

selectEle.on("select2:closing", function (e) {
  $('.select2-results__option').tooltip('close');
});

But I am getting Uncaught Error: cannot call methods on tooltip prior to initialization; attempted to call method 'close'.

Body:
You could use this:

$('.select2-results__option').hide();

instead of :

$('.select2-results__option').tooltip('close');

and keep it in mind that all of your jquery code should be in $(document).ready(function () { // here  }) function like this:

$(document).ready(function () {
let selectEle = cellEle.children("select").select2({
    //more code here
});

selectEle.on("select2:opening", function (e) {
            $(document).on('hover', '.select2-results__option', function () {
              $(this).tooltip({
                position: {
                  my: "center bottom-20",
                  at: "center top",
                  using: function( position, feedback ) {
                    $(this).css(position);
                    var txt = $(this).text();
                    $(this).html(txt);
                    $( "<div>" )
                      .addClass( "arrow" )
                      .addClass( feedback.vertical )
                      .addClass( feedback.horizontal )
                      .appendTo( this );
                  }
                }
              });
            });
          });

   selectEle.on("select2:closing", function (e) {
      $('.select2-results__option').hide();
   });
})


问:
Simplifying a SQL query
I've been using below query to get the desired value and it gives me the correct output, but is there any way to simplify this query?

```<code>SELECT (
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%accountc/upgrade%'
AND page_urlpath like '%success%'
AND app_id = 'rapper') +
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%/upgrade/personal/success/%'
AND app_id = 'rapper') +
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%/upgrade/team/success/%'
AND app_id = 'rapper') +
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%/upgrade/desktop/personal/success/%'
AND app_id = 'rapper') +
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%/upgrade/desktop/team/success/%'
AND app_id = 'rapper')
) as total
</code>```

All the columns are in a single table.

答:
You might like to use regular expression to combine all page_urlpath ref: similar to clause</p>
```<code>SELECT Count(DISTINCT user_id)
FROM   table1
WHERE  date BETWEEN '2022-01-01' AND    '2022-01-20'
AND    (
              page_urlpath similar TO '%(\/upgrade\/personal\/success\/|\/upgrade\/team\/success\/|\/upgrade\/desktop\/personal\/success/|\/upgrade\/desktop\/team\/success\/)%'
       OR     (
                     page_urlpath LIKE '%accountc\/upgrade%'
              AND    page_urlpath LIKE '%success%'))
AND    app_id='rapper';
</code>```

Title: Simplifying a SQL query

Body:
I've been using below query to get the desired value and it gives me the correct output, but is there any way to simplify this query?

SELECT (
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%accountc/upgrade%'
AND page_urlpath like '%success%'
AND app_id = 'rapper') +
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%/upgrade/personal/success/%'
AND app_id = 'rapper') +
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%/upgrade/team/success/%'
AND app_id = 'rapper') +
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%/upgrade/desktop/personal/success/%'
AND app_id = 'rapper') +
(SELECT count(DISTINCT user_id)
FROM table1
WHERE date between '2022-01-01' and '2022-01-20'
AND page_urlpath like '%/upgrade/desktop/team/success/%'
AND app_id = 'rapper')
) as total

All the columns are in a single table.

Body:
You might like to use regular expression to combine all page_urlpath ref: similar to clause

SELECT Count(DISTINCT user_id)
FROM   table1
WHERE  date BETWEEN '2022-01-01' AND    '2022-01-20'
AND    (
              page_urlpath similar TO '%(\/upgrade\/personal\/success\/|\/upgrade\/team\/success\/|\/upgrade\/desktop\/personal\/success/|\/upgrade\/desktop\/team\/success\/)%'
       OR     (
                     page_urlpath LIKE '%accountc\/upgrade%'
              AND    page_urlpath LIKE '%success%'))
AND    app_id='rapper';


问:
How to make a stored procedure in which the parameters are a list of strings [ SQL Server, ASP.NET Core 3.1 ]
I am creating a website where users can filter the data by brand, storage, price, etc. I want to use a stored procedure to get the data. The problem is that I don't know how to make a stored procedure that accepts a list of strings as parameters.

For example, this is my ASP.NET Core controller:

```<code>    private readonly contextItem _context;

    public ItemsController(contextItem context)
    {
        _context = context;
    }

    // GET: api/Items
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Item>>> GetItem(
        string samsung, string iphone, string lg, string _32gb, string _64gb,string _128gb,
        string max, string min)
    {
        List<string> brands = new List<string>(), storage = new List<string>();
        string price_min = null, price_max = null;

        // brands
        if (samsung != null) { brands.Add("samsung"); }
        if (iphone != null) { brands.Add("iphone"); }
        if (lg != null) { brands.Add("lg"); }

        // storage
        if (_32gb != null) { storage.Add("32gb"); }
        if (_64gb != null) { storage.Add("64gb"); }
        if (_128gb != null) { storage.Add("128gb"); }

        // price
        price_max = max != null ? max : "";
        price_min = min != null ? min : "";

        string query = $"EXEC SP_Filter @brand ='{string.Join(",", brands)}',@storage='{string.Join(",", storage)}'," +
            $"@min='{price_min}',@max='{price_max}'";

        return await _context.Item.FromSqlRaw(query).ToListAsync();
    }
</code>```

So the parameters can be more than one, but if they weren't, it would be easy to make a stored procedure like this

```<code>create procedure SP_Filter
    @brands varchar(250),
    @storage varchar(250),
    @min decimal,
    @max decimal
as
    Select *
    From Item
    Where NAME like '%'+@brands+'%'
      and NAME like '%'+@storage+'%'
      and PRICE between @min and @max
</code>```

答:
Here's an example using table value parameters;

CREATE TYPE [TableString] AS TABLE (
   Id nvarchar(4000) NULL
)
go
create procedure [name]
  @brands [TableString],
  ...
as
...
```
<pre class="lang-cs prettyprint-override"><code>    public SqlParameter ToSqlParameter(IEnumerable<string> values)
    {
        var meta = new SqlMetaData("Id", SqlDbType.NVarChar, 4000);
        var records = values.Select(v => {
            var record = new SqlDataRecord(
                meta
            );
            if (v == null)
                record.SetDBNull(0);
            else
                record.SetString(0, v);
            return record;
        });
        return new SqlParameter()
        {
            TypeName = "TableString",
            SqlDbType = SqlDbType.Structured,
            Value = records
        };
    }
</code>```

Now you can define that your procedure takes a TableString argument.

You can extend this example slightly, so that you can pass in a TableString into a query;

public class TableValue<T>
{
    public T Id { get; set; }
}

public class MyContext : DbContext {
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
    ...
        modelBuilder.Entity<TableValue<string>>(e =>
        {
            e.HasNoKey();
            e.ToView("TableString");
            e.Property(p => p.Id).HasMaxLength(4000);
        });
    }
}

var queryable = context.Set<TableValue<string>>()
    .FromSqlInterpolated($"select * from {ToSqlParameter( ... )}");
```

Body:
I am creating a website where users can filter the data by brand, storage, price, etc. I want to use a stored procedure to get the data. The problem is that I don't know how to make a stored procedure that accepts a list of strings as parameters.

For example, this is my ASP.NET Core controller:

    private readonly contextItem _context;

    public ItemsController(contextItem context)
    {
        _context = context;
    }

    // GET: api/Items
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Item>>> GetItem(
        string samsung, string iphone, string lg, string _32gb, string _64gb,string _128gb,
        string max, string min)
    {
        List<string> brands = new List<string>(), storage = new List<string>();
        string price_min = null, price_max = null;

        // brands
        if (samsung != null) { brands.Add("samsung"); }
        if (iphone != null) { brands.Add("iphone"); }
        if (lg != null) { brands.Add("lg"); }

        // storage
        if (_32gb != null) { storage.Add("32gb"); }
        if (_64gb != null) { storage.Add("64gb"); }
        if (_128gb != null) { storage.Add("128gb"); }

        // price
        price_max = max != null ? max : "";
        price_min = min != null ? min : "";

        string query = $"EXEC SP_Filter @brand ='{string.Join(",", brands)}',@storage='{string.Join(",", storage)}'," +
            $"@min='{price_min}',@max='{price_max}'";

        return await _context.Item.FromSqlRaw(query).ToListAsync();
    }

So the parameters can be more than one, but if they weren't, it would be easy to make a stored procedure like this

create procedure SP_Filter
    @brands varchar(250),
    @storage varchar(250),
    @min decimal,
    @max decimal
as
    Select *
    From Item
    Where NAME like '%'+@brands+'%'
      and NAME like '%'+@storage+'%'
      and PRICE between @min and @max

Body:
Here's an example using table value parameters;

CREATE TYPE [TableString] AS TABLE (
   Id nvarchar(4000) NULL
)
go
create procedure [name]
  @brands [TableString],
  ...
as
...

    public SqlParameter ToSqlParameter(IEnumerable<string> values)
    {
        var meta = new SqlMetaData("Id", SqlDbType.NVarChar, 4000);
        var records = values.Select(v => {
            var record = new SqlDataRecord(
                meta
            );
            if (v == null)
                record.SetDBNull(0);
            else
                record.SetString(0, v);
            return record;
        });
        return new SqlParameter()
        {
            TypeName = "TableString",
            SqlDbType = SqlDbType.Structured,
            Value = records
        };
    }

Now you can define that your procedure takes a TableString argument.

You can extend this example slightly, so that you can pass in a TableString into a query;

public class TableValue<T>
{
    public T Id { get; set; }
}

public class MyContext : DbContext {
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
    ...
        modelBuilder.Entity<TableValue<string>>(e =>
        {
            e.HasNoKey();
            e.ToView("TableString");
            e.Property(p => p.Id).HasMaxLength(4000);
        });
    }
}

var queryable = context.Set<TableValue<string>>()
    .FromSqlInterpolated($"select * from {ToSqlParameter( ... )}");


问:
AWS Route 53 - Not Receiving NS Records
My domain was in different provider.

So I create record on AWS Route 53,
And find the NS records. So that, o copy and paste them to my provider's NS Records.

But after redirection, my A and CNAME records are not working.
I made NS lookup and It returned that; records are belong to AWS Route 53 but not working yet.

After that I've seen that,
My SOA Records are not belong to AWS. It still belongs to another provider:

So that,
I can not manage my DNS records by Route 53.
But NS records are shown as AWS.

Whats wrong with that?

答:
There's a TTL attached with each record and is managed by the service provider. So it is important to understand how you're testing the NS and other records value. I will recommend to use https://mxtoolbox.com/ which will ignore the multi levels of cache in the DNS lifecycle.

Once your NS servers are updated. You can setup any txt record to test that AWS Route53 is working for you. The best part is Route53 is super FAST and updates in seconds instead of days for some other providers. Then just go ahead and setup your A records & CNAME.

Title: AWS Route 53 - Not Receiving NS Records


问:
Python requests WWW-Authenticate missing in headers
I'm trying to access the WWW-Authenticate header after a GET request using Python's requests library. When I do this in Postman it returns it but in Python it doesn't.

Python:

import requests
from requests.auth import HTTPBasicAuth

headers = {
    # "Python-Token": "<calculated when request is sent>",
    # "Host": "<calculated when request is sent>",
    "Accept": "application/json, */*",
    "User-Agent": "PythonRuntime/3.9.7",
    # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Access-Control-Expose-Headers": "x-WWW-Authenticate",
    'x-requested-with': 'XMLHttpRequest',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    "Authorization": "Bearer"
}
site = "https://YourSPOSiteURL/_vti_bin/client.svc/"
auth = HTTPBasicAuth('something@email.com', 'somepasswordhere')
headers = dict( requests.get(f"{site}/_vti_bin/client.svc/", auth=auth).headers )
```
<p><code>headers</code>:</p>
```{'Cache-Control': 'private, max-age=0',
 'Content-Length': '0',
 'Content-Security-Policy': "frame-ancestors 'self' teams.microsoft.com "
                            '*.teams.microsoft.com *.skype.com '
                            '*.teams.microsoft.us local.teams.office.com '
                            '*.powerapps.com *.yammer.com '
                            '*.officeapps.live.com *.office.com '
                            '*.stream.azure-test.net *.microsoftstream.com '
                            '*.dynamics.com;',
 'Date': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'Expires': 'Thu, 20 Jan 2022 14:53:16 GMT',
 'Last-Modified': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'MS-CV': 'xxxxxxxxxxxxx.0',
 'MicrosoftSharePointTeamServices': 'xx.x.x.xxxxx',
 'P3P': 'CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR '
        'SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"',
 'SPRequestGuid': '697da8340-a0d3-30123-9fc9-98c88419387426',
 'Server': 'Microsoft-IIS/10.0',
 'Strict-Transport-Security': 'max-age=31536000',
 'Vary': 'Origin',
 'X-AspNet-Version': '4.0.xxxxx',
 'X-Content-Type-Options': 'nosniff',
 'X-FRAME-OPTIONS': 'SAMEORIGIN',
 'X-MS-InvokeApp': '1; RequireReadOnly',
 'X-Powered-By': 'ASP.NET',
 'X-SharePointHealthScore': '2',
 'request-id': '697da8340-a0d3-30123-9fc9-98c88419387426'}
```

Postman:

I've tried every headers param I can find but can't seem to return the WWW-Authenticate response header which I need...any help would be much appreciated.

Edit:

Within Postman, it looks to be the Host key in the headers get request that's generating the WWW-Authenticate in the response headers. When I remove it (in Postman) I get only a handful of headers in the response headers. But how would I replicate this in Python's requests library?

This is what it says when hovering over the Host header in GET:

答:
You are not using that headers dict when sending the request.

You can easily debug what was actually sent accessing the request property from the response you got without additional software

```<code>response = requests.get(
    f"{site}/_vti_bin/client.svc/",
    auth=('something@email.com', 'somepasswordhere'),
    headers=headers,
)
print(response.request.headers)
print(response.headers)
</code>```

so you can inspect all those additional headers (but not the Host header https://stackoverflow.com/a/57771006/11715259)

See https://docs.python-requests.org/en/latest/user/advanced/#prepared-requests

Yet, I truly recommend you get used to throw in a reverse proxy for debugging.

https://mitmproxy.org/ is quite great for this, much more playful than tcpdump/wireshark if you only work with the http protocol.

Body:
I'm trying to access the WWW-Authenticate header after a GET request using Python's requests library. When I do this in Postman it returns it but in Python it doesn't.

Python:

import requests
from requests.auth import HTTPBasicAuth

headers = {
    # "Python-Token": "<calculated when request is sent>",
    # "Host": "<calculated when request is sent>",
    "Accept": "application/json, */*",
    "User-Agent": "PythonRuntime/3.9.7",
    # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Access-Control-Expose-Headers": "x-WWW-Authenticate",
    'x-requested-with': 'XMLHttpRequest',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    "Authorization": "Bearer"
}
site = "https://YourSPOSiteURL/_vti_bin/client.svc/"
auth = HTTPBasicAuth('something@email.com', 'somepasswordhere')
headers = dict( requests.get(f"{site}/_vti_bin/client.svc/", auth=auth).headers )

headers:

{'Cache-Control': 'private, max-age=0',
 'Content-Length': '0',
 'Content-Security-Policy': "frame-ancestors 'self' teams.microsoft.com "
                            '*.teams.microsoft.com *.skype.com '
                            '*.teams.microsoft.us local.teams.office.com '
                            '*.powerapps.com *.yammer.com '
                            '*.officeapps.live.com *.office.com '
                            '*.stream.azure-test.net *.microsoftstream.com '
                            '*.dynamics.com;',
 'Date': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'Expires': 'Thu, 20 Jan 2022 14:53:16 GMT',
 'Last-Modified': 'Fri, 04 Feb 2022 14:53:16 GMT',
 'MS-CV': 'xxxxxxxxxxxxx.0',
 'MicrosoftSharePointTeamServices': 'xx.x.x.xxxxx',
 'P3P': 'CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR '
        'SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"',
 'SPRequestGuid': '697da8340-a0d3-30123-9fc9-98c88419387426',
 'Server': 'Microsoft-IIS/10.0',
 'Strict-Transport-Security': 'max-age=31536000',
 'Vary': 'Origin',
 'X-AspNet-Version': '4.0.xxxxx',
 'X-Content-Type-Options': 'nosniff',
 'X-FRAME-OPTIONS': 'SAMEORIGIN',
 'X-MS-InvokeApp': '1; RequireReadOnly',
 'X-Powered-By': 'ASP.NET',
 'X-SharePointHealthScore': '2',
 'request-id': '697da8340-a0d3-30123-9fc9-98c88419387426'}

Postman:

I've tried every headers param I can find but can't seem to return the WWW-Authenticate response header which I need...any help would be much appreciated.

Edit:

Within Postman, it looks to be the Host key in the headers get request that's generating the WWW-Authenticate in the response headers. When I remove it (in Postman) I get only a handful of headers in the response headers. But how would I replicate this in Python's requests library?

This is what it says when hovering over the Host header in GET:

Body:
You are not using that headers dict when sending the request.

You can easily debug what was actually sent accessing the request property from the response you got without additional software

response = requests.get(
    f"{site}/_vti_bin/client.svc/",
    auth=('something@email.com', 'somepasswordhere'),
    headers=headers,
)
print(response.request.headers)
print(response.headers)

so you can inspect all those additional headers (but not the Host header https://stackoverflow.com/a/57771006/11715259)

See https://docs.python-requests.org/en/latest/user/advanced/#prepared-requests

Yet, I truly recommend you get used to throw in a reverse proxy for debugging.

https://mitmproxy.org/ is quite great for this, much more playful than tcpdump/wireshark if you only work with the http protocol.


问:
Remove shadow and gradient from this p5.js sketch
I'm trying to adapt this sketch for my own work but I can't seem to figure out how to make it such that the tiles are solid colours and each row does not have that shadow.

The gradients and shadows are controlled by row 116 to 123.

答:
To make each tile a solid color simply replace the call to gradient() with a call to fill() given the color you want and rect(x, y, w, h).

// P_1_2_3_03
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var colorCount = 30;
var hueValues = [];
var saturationValues = [];
var brightnessValues = [];
var actRandomSeed = 0;
var alphaValue = 255;

function setup() {
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB, 360, 100, 100, 100);
  noStroke();
}

function draw() {
  noLoop();
  background(0);
  randomSeed(actRandomSeed);

  // ------ colors ------
  // create palette
  for (var i = 0; i < colorCount; i++) {
    if (i % 2 == 0) {
      hueValues[i] = 0;
      saturationValues[i] = 0;
      brightnessValues[i] = random(100);
    } else {
      hueValues[i] = 0;
      saturationValues[i] = 0;
      brightnessValues[i] = 100;
    }
  }

  // ------ area tiling ------
  // count tiles
  var counter = 0;
  // row count and row height
  var rowCount = 6;
  var rowHeight = height / rowCount;

  // seperate each line in parts
  for (var i = rowCount; i >= 0; i--) {
    // how many fragments
    var partCount = i + 1;
    var parts = [];

    for (var ii = 0; ii < partCount; ii++) {
      // sub fragments or not?
      if (random() < 0.075) {
        // take care of big values
        var fragments = int(random(2, 20));
        partCount = partCount + fragments;
        for (var iii = 0; iii < fragments; iii++) {
          parts.push(random(2));
        }
      } else {
        parts.push(random(2, 20));
      }
    }

    // add all subparts
    var sumPartsTotal = 0;
    for (var ii = 0; ii < partCount; ii++) {
      sumPartsTotal += parts[ii];
    }

    // draw rects
    var sumPartsNow = 0;
    for (var ii = 0; ii < parts.length; ii++) {
      sumPartsNow += parts[ii];

      var x = map(sumPartsNow, 0, sumPartsTotal, 0, width);
      var y = rowHeight * i;
      var w = -map(parts[ii], 0, sumPartsTotal, 0, width);
      var h = rowHeight * 1.5;

      var index = counter % colorCount;
      var col1 = color(0);
      var col2 = color(hueValues[index], saturationValues[index], brightnessValues[index], alphaValue);
      // gradient(x, y, w, h, col1, col2);
      fill(col2);
      rect(x, y, w, h);

      counter++;
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script></code>```

Body:
To make each tile a solid color simply replace the call to gradient() with a call to fill() given the color you want and rect(x, y, w, h).

// P_1_2_3_03
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var colorCount = 30;
var hueValues = [];
var saturationValues = [];
var brightnessValues = [];
var actRandomSeed = 0;
var alphaValue = 255;

function setup() {
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB, 360, 100, 100, 100);
  noStroke();
}

function draw() {
  noLoop();
  background(0);
  randomSeed(actRandomSeed);

  // ------ colors ------
  // create palette
  for (var i = 0; i < colorCount; i++) {
    if (i % 2 == 0) {
      hueValues[i] = 0;
      saturationValues[i] = 0;
      brightnessValues[i] = random(100);
    } else {
      hueValues[i] = 0;
      saturationValues[i] = 0;
      brightnessValues[i] = 100;
    }
  }

  // ------ area tiling ------
  // count tiles
  var counter = 0;
  // row count and row height
  var rowCount = 6;
  var rowHeight = height / rowCount;

  // seperate each line in parts
  for (var i = rowCount; i >= 0; i--) {
    // how many fragments
    var partCount = i + 1;
    var parts = [];

    for (var ii = 0; ii < partCount; ii++) {
      // sub fragments or not?
      if (random() < 0.075) {
        // take care of big values
        var fragments = int(random(2, 20));
        partCount = partCount + fragments;
        for (var iii = 0; iii < fragments; iii++) {
          parts.push(random(2));
        }
      } else {
        parts.push(random(2, 20));
      }
    }

    // add all subparts
    var sumPartsTotal = 0;
    for (var ii = 0; ii < partCount; ii++) {
      sumPartsTotal += parts[ii];
    }

    // draw rects
    var sumPartsNow = 0;
    for (var ii = 0; ii < parts.length; ii++) {
      sumPartsNow += parts[ii];

      var x = map(sumPartsNow, 0, sumPartsTotal, 0, width);
      var y = rowHeight * i;
      var w = -map(parts[ii], 0, sumPartsTotal, 0, width);
      var h = rowHeight * 1.5;

      var index = counter % colorCount;
      var col1 = color(0);
      var col2 = color(hueValues[index], saturationValues[index], brightnessValues[index], alphaValue);
      // gradient(x, y, w, h, col1, col2);
      fill(col2);
      rect(x, y, w, h);

      counter++;
    }
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>


问:
How to save "text" from Twitter JSON data to a ACF field?
I need help with my code. What it's suppose to do is a user enter the full URL from twitter into a text field ('https://twitter.com/openbayou/status/1487977976033685506') and when the post is saved, it breaks down the url by using explode and then gets data from a tweet via Twitter API v2.

My code:

```<code>$tweet_url_raw = get_field('twitter_url');
$parts = explode('/', $tweet_url_raw);
$url = 'https://api.twitter.com/2/tweets/' . $parts[5] . '?expansions=author_id&tweet.fields=created_at&user.fields=username,verified';
$authorization = 'Authorization: Bearer ' . get_field_object('twitter_bearer_token', 'option')['value'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
$tweet_data = json_encode($result);
$tweet_data2 = json_decode($tweet_data);
</code>```

The code above does get the data:

```<code>{"data":{"text":"SEC Super Bowl!!","created_at":"2022-01-31T02:36:09.000Z","author_id":"1471331","id":"1487977976033685506"},"includes":{"users":[{"name":"OpenBayou","verified":false,"id":"1471331","username":"openbayou"}]}}
</code>```

The problem I'm having is when I'm trying to get individual data from the output. I'm trying to update a text field called tweet with the text from text. I've tried to use update_field('tweet', $tweet_data2->data, $post_id); and it was blank. When I use                update_field('tweet2', $tweet_data2["data"], $post_id); all it saves is {

Any idea what I'm doing wrong?

答:
You are almost there.

Since you omitted the associative parameter for json_decode, it defaults to false so you get an object, not an array. You then need to reference it as such:

```<code>$tweet_data2 = json_decode($tweet_data);
echo 'Tweet text: ' . $tweet_data2->data->text;
</code>```

If you prefer to work with arrays, simply pass true to json_decode:

```<code>$tweet_data2 = json_decode($tweet_data, true);
echo 'Tweet text: ' . $tweet_data2['data']['text'];
</code>```

More info on json_decode can be found at the PHP Manual site:
https://www.php.net/manual/en/function.json-decode.php

Body:
I need help with my code. What it's suppose to do is a user enter the full URL from twitter into a text field ('https://twitter.com/openbayou/status/1487977976033685506') and when the post is saved, it breaks down the url by using explode and then gets data from a tweet via Twitter API v2.

My code:

$tweet_url_raw = get_field('twitter_url');
$parts = explode('/', $tweet_url_raw);
$url = 'https://api.twitter.com/2/tweets/' . $parts[5] . '?expansions=author_id&tweet.fields=created_at&user.fields=username,verified';
$authorization = 'Authorization: Bearer ' . get_field_object('twitter_bearer_token', 'option')['value'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
$tweet_data = json_encode($result);
$tweet_data2 = json_decode($tweet_data);

The code above does get the data:

{"data":{"text":"SEC Super Bowl!!","created_at":"2022-01-31T02:36:09.000Z","author_id":"1471331","id":"1487977976033685506"},"includes":{"users":[{"name":"OpenBayou","verified":false,"id":"1471331","username":"openbayou"}]}}

The problem I'm having is when I'm trying to get individual data from the output. I'm trying to update a text field called tweet with the text from text. I've tried to use update_field('tweet', $tweet_data2->data, $post_id); and it was blank. When I use                update_field('tweet2', $tweet_data2["data"], $post_id); all it saves is {

Any idea what I'm doing wrong?

Body:
You are almost there.

Since you omitted the associative parameter for json_decode, it defaults to false so you get an object, not an array. You then need to reference it as such:

$tweet_data2 = json_decode($tweet_data);
echo 'Tweet text: ' . $tweet_data2->data->text;

If you prefer to work with arrays, simply pass true to json_decode:

$tweet_data2 = json_decode($tweet_data, true);
echo 'Tweet text: ' . $tweet_data2['data']['text'];

More info on json_decode can be found at the PHP Manual site:
https://www.php.net/manual/en/function.json-decode.php


问:
Nested Owned Type Contains Navigation Property - Not Work
I try to define my data model much closer to domain models, but I think that Ef does not support this simple need. I worked with ownsMany, ownsOne, hasMany, hasOne, withOwner, Navigation builder, IEntityTypeConfiguration, and ... in different ways.

```<code>public class Custom
{
    [Required]
    public int id { get; set; }
    public string name { get; set; }

    public Demo demo{ get; set; }
}

[Owned()]
public class Demo
{
    public virtual ICollection<PDemo> pDemoes{ get; set; }
}

public class PDemo
{
    [Required]
    public int id { get; set; }
    public string name { get; set; }

    [ForeignKey("Custom")]
    public int CustomId{ get; set; }
    public virtual Custom Custom{ get; set; }
}

public class RepositoryContext : DbContext
    {
        public RepositoryContext(DbContextOptions<RepositoryContext> options) : base(options)
        {

        }

        public DbSet<Custom> custom { get; set; }
        public DbSet<PDemo> pDemoes{ get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
}
</code>```

EF Core Add-Migration Says :

```<code>Unable to determine the relationship represented by navigation 'Demo.pDemoes' of type 'ICollection<PDemo>'.
Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or
by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
</code>```

答:
I try to find the best answer, so raise an issue on the official GitHub repository for Entity framework Core  :
https://github.com/dotnet/efcore
and find out that the error message is not appropriate, and the development team adds this feature in the next sprints backlog.

issue link :
https://github.com/dotnet/efcore/issues/27175

Body:
I try to define my data model much closer to domain models, but I think that Ef does not support this simple need. I worked with ownsMany, ownsOne, hasMany, hasOne, withOwner, Navigation builder, IEntityTypeConfiguration, and ... in different ways.

public class Custom
{
    [Required]
    public int id { get; set; }
    public string name { get; set; }

    public Demo demo{ get; set; }
}

[Owned()]
public class Demo
{
    public virtual ICollection<PDemo> pDemoes{ get; set; }
}

public class PDemo
{
    [Required]
    public int id { get; set; }
    public string name { get; set; }

    [ForeignKey("Custom")]
    public int CustomId{ get; set; }
    public virtual Custom Custom{ get; set; }
}

public class RepositoryContext : DbContext
    {
        public RepositoryContext(DbContextOptions<RepositoryContext> options) : base(options)
        {

        }

        public DbSet<Custom> custom { get; set; }
        public DbSet<PDemo> pDemoes{ get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
}

EF Core Add-Migration Says :

Unable to determine the relationship represented by navigation 'Demo.pDemoes' of type 'ICollection<PDemo>'.
Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or
by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.