问:
Elastic Beanstalk Wrong Ruby version even though specified in Gemfile
I'm launching a ruby on rails application on AWS EB and am getting the following error

[ERROR] An error occurred during execution of command [app-deploy] -
[stage ruby application]. Stop running the command. Error: install
dependencies in Gemfile failed with error Command /bin/sh -c bundle
2.4.1 install failed with error exit status 18. Stderr:Don't run Bundler as root. Installing your bundle as root will break this
application for all non-root users on this machine. Your Ruby version
is 3.0.5, but your Gemfile specified 3.0.0

I've triple checked the Gemfile in the directory I'm running EB commands from and am positive it has ruby "3.0.5" specified:

```<code>source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.0.5"

# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
gem "rails", "~> 7.0.4"

# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
gem "sprockets-rails"

# Use sqlite3 as the database for Active Record
gem "sqlite3", "~> 1.4"

# Use the Puma web server [https://github.com/puma/puma]
gem "puma", "~> 5.0"

# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
gem "importmap-rails"

# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "turbo-rails"

# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "stimulus-rails"

# Use Tailwind CSS [https://github.com/rails/tailwindcss-rails]
gem "tailwindcss-rails"

# Build JSON APIs with ease [https://github.com/rails/jbuilder]
gem "jbuilder"

# Use Redis adapter to run Action Cable in production
# gem "redis", "~> 4.0"

# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis]
# gem "kredis"

# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword]
# gem "bcrypt", "~> 3.1.7"

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]

# Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false

# Use Sass to process CSS
# gem "sassc-rails"

# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"

group :development, :test do
  # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
  gem "debug", platforms: %i[ mri mingw x64_mingw ]
end

group :development do
  # Use console on exceptions pages [https://github.com/rails/web-console]
  gem "web-console"

  # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
  # gem "rack-mini-profiler"

  # Speed up commands on slow machines / big apps [https://github.com/rails/spring]
  # gem "spring"
end

group :test do
  # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
  gem "capybara"
  gem "selenium-webdriver"
  gem "webdrivers"
end

gem 'pg'

gem 'devise'

gem "rqrcode"
</code>```

using the commands

```<code>$ eb init

$ eb create
</code>```

What could be causing the error saying my Gemfile specified 3.0.0?

Body:
I'm launching a ruby on rails application on AWS EB and am getting the following error

[ERROR] An error occurred during execution of command [app-deploy] -
[stage ruby application]. Stop running the command. Error: install
dependencies in Gemfile failed with error Command /bin/sh -c bundle
2.4.1 install failed with error exit status 18. Stderr:Don't run Bundler as root. Installing your bundle as root will break this
application for all non-root users on this machine. Your Ruby version
is 3.0.5, but your Gemfile specified 3.0.0

I've triple checked the Gemfile in the directory I'm running EB commands from and am positive it has ruby "3.0.5" specified:

source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.0.5"

# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
gem "rails", "~> 7.0.4"

# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
gem "sprockets-rails"

# Use sqlite3 as the database for Active Record
gem "sqlite3", "~> 1.4"

# Use the Puma web server [https://github.com/puma/puma]
gem "puma", "~> 5.0"

# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
gem "importmap-rails"

# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "turbo-rails"

# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "stimulus-rails"

# Use Tailwind CSS [https://github.com/rails/tailwindcss-rails]
gem "tailwindcss-rails"

# Build JSON APIs with ease [https://github.com/rails/jbuilder]
gem "jbuilder"

# Use Redis adapter to run Action Cable in production
# gem "redis", "~> 4.0"

# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis]
# gem "kredis"

# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword]
# gem "bcrypt", "~> 3.1.7"

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]

# Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false

# Use Sass to process CSS
# gem "sassc-rails"

# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"

group :development, :test do
  # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
  gem "debug", platforms: %i[ mri mingw x64_mingw ]
end

group :development do
  # Use console on exceptions pages [https://github.com/rails/web-console]
  gem "web-console"

  # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
  # gem "rack-mini-profiler"

  # Speed up commands on slow machines / big apps [https://github.com/rails/spring]
  # gem "spring"
end

group :test do
  # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
  gem "capybara"
  gem "selenium-webdriver"
  gem "webdrivers"
end

gem 'pg'

gem 'devise'

gem "rqrcode"

using the commands

$ eb init

$ eb create

What could be causing the error saying my Gemfile specified 3.0.0?


来源: stackexchange

问:
Using Flyway with Redshift Serverless
I'm currently using a provisioned Redshift cluster, and managing database migrations with Flyway. I'm thinking on migrating to Redshift Serverless, but I'm not sure if can still use Flyway to manage the migrations.

Already added the rule in my security group to allow my IP (I'm trying to run Flyway migrations locally), and also have the Publicly accessible parameter set to On, following the steps in this document, and using the endpoint given by the workspace.

ContentLicense: CC BY-SA 4.0

Title: Using Flyway with Redshift Serverless


问:
why am i getting npm ERR! syscall spawn powershell and am using UBUNTU 20.04?

npx create-react-app project1 npm ERR! code ENOENT npm ERR! syscall
spawn powershell npm ERR! path /home/timothy npm ERR! errno -2 npm
ERR! enoent spawn powershell ENOENT npm ERR! enoent This is related to
npm not being able to find a file. npm ERR! enoent

npm ERR! A complete log of this run can be found in: npm ERR!

/home/timothy/.npm/_logs/2023-01-10T18_38_05_978Z-debug-0.log

I've tried everything I know. I just need help before I give up.


问:
Why does python list resize overallocation differ from other languages?
I've been reading a bit of python source code and found a peculiar comment about the resize overallocation strategy -

```<code>/* This over-allocates proportional to the list size, making room
 * for additional growth.  The over-allocation is mild, but is
 * enough to give linear-time amortized behavior over a long
 * sequence of appends() in the presence of a poorly-performing
 * system realloc().
 * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
 */
+
−new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
</code>```

I remembered the usual strategy is to double the capacity when the limit is reached.

I checked with a few other languages source code and found that indeed it is as I though, in go, rust and c#

Also I found out they changed it a bit in the next python prerelease version, but for unrelated reasons - keeping the same concept of the strategy.

So why does python have such a unique method of resizing, and what are the implications on performance?

Body:
I've been reading a bit of python source code and found a peculiar comment about the resize overallocation strategy -

/* This over-allocates proportional to the list size, making room
 * for additional growth.  The over-allocation is mild, but is
 * enough to give linear-time amortized behavior over a long
 * sequence of appends() in the presence of a poorly-performing
 * system realloc().
 * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
 */
+
−new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);

I remembered the usual strategy is to double the capacity when the limit is reached.

I checked with a few other languages source code and found that indeed it is as I though, in go, rust and c#

Also I found out they changed it a bit in the next python prerelease version, but for unrelated reasons - keeping the same concept of the strategy.

So why does python have such a unique method of resizing, and what are the implications on performance?


问:
Github actions PM2 start command not starting process
I'm facing issue with PM2 start. when i push code to master branch all below steps working correctly without any issue. but when i login to my EC2 using SSH and check for pm2 list there is no process showing.

I've google a lot but didn't get any working solution.

Below is my workflows yml file

```<code>name: Node.js CI

on:
 push:
  branches: [ "master" ]

jobs:
 build:

runs-on: self-hosted

strategy:
  matrix:
    node-version: [14.x]
    # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
  uses: actions/setup-node@v3
  with:
    node-version: ${{ matrix.node-version }}
    cache: 'npm'
- run: pwd
- run: npm ci
- run: npm run build --if-present
- run: pm2 kill
- run: echo 'pm2 process killed successfully'
- run: pm2 start dist/main.js
- run: pm2 list
</code>```

Body:
I'm facing issue with PM2 start. when i push code to master branch all below steps working correctly without any issue. but when i login to my EC2 using SSH and check for pm2 list there is no process showing.

I've google a lot but didn't get any working solution.

Below is my workflows yml file

name: Node.js CI

on:
 push:
  branches: [ "master" ]

jobs:
 build:

runs-on: self-hosted

strategy:
  matrix:
    node-version: [14.x]
    # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
  uses: actions/setup-node@v3
  with:
    node-version: ${{ matrix.node-version }}
    cache: 'npm'
- run: pwd
- run: npm ci
- run: npm run build --if-present
- run: pm2 kill
- run: echo 'pm2 process killed successfully'
- run: pm2 start dist/main.js
- run: pm2 list


问:
R's gc() on parallel runs seems to dramatically under-report peak memory
In R I have a task that I'm trying to parallelize. Part of this is comparing run-times and peak memory usage for different implementations of the task at hand. I'm using the peakRAM library to determine peak memory, which I think just uses gc() under the surface, since if I do it manually I get the same peak memory results.

The problem is that the results from peakRAM are different from the computer's task manager (or top on Linux). If I run a single-core, these numbers are in the same ballpark, but even using 2 cores, they are really different.

I'm parallelizing using pblapply in a manner similar to this.

```<code>times_parallel = peakRAM(
        pblapply(X = 1:10,
                 FUN = \(x) data[iteration==x] %>% parallel_task(),
                 cl = makeCluster(numcores, type = "FORK"))
    )
</code>```

With a single core, this process requires a peak of 30G of memory. But with 2 cores, peakRAM reports only about 3G of memory. Looking at top however, shows that each of the 2 threads is using around 20-30G of memory at a time.

The only thing I can think of is that peakRAM is only reporting the memory of the main thread but I see nothing in the gc() details that suggests this is happening.

The time reported from peakRAM seems appropriate. Sub-linear gains at different core levels.

Body:
In R I have a task that I'm trying to parallelize. Part of this is comparing run-times and peak memory usage for different implementations of the task at hand. I'm using the peakRAM library to determine peak memory, which I think just uses gc() under the surface, since if I do it manually I get the same peak memory results.

The problem is that the results from peakRAM are different from the computer's task manager (or top on Linux). If I run a single-core, these numbers are in the same ballpark, but even using 2 cores, they are really different.

I'm parallelizing using pblapply in a manner similar to this.

times_parallel = peakRAM(
        pblapply(X = 1:10,
                 FUN = \(x) data[iteration==x] %>% parallel_task(),
                 cl = makeCluster(numcores, type = "FORK"))
    )

With a single core, this process requires a peak of 30G of memory. But with 2 cores, peakRAM reports only about 3G of memory. Looking at top however, shows that each of the 2 threads is using around 20-30G of memory at a time.

The only thing I can think of is that peakRAM is only reporting the memory of the main thread but I see nothing in the gc() details that suggests this is happening.

The time reported from peakRAM seems appropriate. Sub-linear gains at different core levels.


问:
URL forwarding for Lambda functions within VPC
My AWS lambda function code is calling an external API says GET method example.com/getBooks
That lambda function is deployed using AWS SAM and running within VPC & Subnets.

What I am trying to achieve is to redirect the example.com/getBooks to my API Gateway URL(eg. xxxyy.us-east-2.com/getBooks) without modifying lambda code and without needing to create environment parameter for lambda function.

It wasn't as easy as I thought like what I usually done in Windows/Linux by just adding the mapping source and destination URL to the hosts file.

I am not getting relevant solution after reading and testing thru Route 53, Route Tables and AWS ELB
I have setup Route 53 resolver but it doesn't let me put my expected target FQDN, instead it is asking for IP address.

Anyone can suggest a solution for this.
Appreciate for help.


问:
How to send selected cells from google sheets via appscript?
hello is any one familiar with app scripts?

I'm sending data from unity app to google sheets form then to template, send to a new spreadsheet be converted into pdf with needed data and then send as email,

I'm having trouble with the sheets, I have the where what I want to send should not go pass row 86.

In the email I get all rows of the new spreadsheet which is sending 7 pages, I only need one page to send for this or one range A1:AX86, I've been trying multiple solutions, anyone have a take on this

Thanks,

```<code>typefunction sendPdfEmailWithLatestData() {
  // Constants
  const SPREADSHEET_ID = SpreadsheetApp.getActiveSpreadsheet().getId();
  const FORM_RESPONSE_SHEET_NAME = 'FormResponses';
  const PERIODONTAL_CHART_SHEET_NAME = 'Periodontal Chart';
  const EMAIL_SUBJECT = 'Periodontal Chart';
  const EMAIL_BODY = 'Attached is the Periodontal Chart for your review.';

  // Get the active spreadsheet and the sheets by their name
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const formResponseSheet = activeSpreadsheet.getSheetByName(FORM_RESPONSE_SHEET_NAME);
  const periodontalChartSheet = activeSpreadsheet.getSheetByName(PERIODONTAL_CHART_SHEET_NAME);

  // Get the range of all data in the FormResponses sheet, including the header row
  const formResponseDataRange = formResponseSheet.getDataRange();
  const numRows = formResponseDataRange.getNumRows();
  const numColumns = formResponseDataRange.getNumColumns();
  const values = formResponseDataRange.getValues();

  // Get the values from the latest row in the FormResponses sheet
  const headerRow = values[0]; // first row is the header row
  const latestRow = values[numRows - 1]; // last row is the latest row
  const patientLastName = latestRow[headerRow.indexOf('Last Name')];
  const patientFirstName = latestRow[headerRow.indexOf('First Name')];
  const patientDateOfBirth = latestRow[headerRow.indexOf('Date of Birth')];
  const appointmentDate = latestRow[headerRow.indexOf('Date')];
  const appointmentTime = latestRow[headerRow.indexOf('Time')];
  const appointmentVisit = latestRow[headerRow.indexOf('Visit')];
  const patientEmail = latestRow[headerRow.indexOf('Email')];

  // Update the values in the Periodontal Chart sheet
  const columnNames = ['E7:L7', 'Q7:X7', 'AC7:AJ7', 'AM7:AO7', 'AR7:AT7', 'AW7:AX7'];
  columnNames.forEach(function(columnName) {
  // Clear the contents of the cells in the specified column
  periodontalChartSheet.getRange(columnName).clearContent();
});
  const valuesToSet = [patientLastName, patientFirstName, patientDateOfBirth, appointmentDate, appointmentTime, appointmentVisit];
  columnNames.forEach((columnName, index) => {
    periodontalChartSheet.getRange(columnName).setValue(valuesToSet[index]);
  });

  // Convert the active spreadsheet to a PDF file and save it to Google Drive
  const pdf = DriveApp.createFile(activeSpreadsheet.getAs('application/pdf'));

  pdf.setName('Periodontal Chart.pdf');

  // Send the email with the PDF file attached
  //GmailApp.sendEmail(patientEmail, EMAIL_SUBJECT, EMAIL_BODY, {attachments: [pdf]});

  // Delete the PDF file from Google Drive
  pdf.setTrashed(true);

  console.log(`Latest row: ${latestRow}`);
copySheetAndSendEmail(SpreadsheetApp.getActiveSpreadsheet(), patientEmail, "Periodontal Chart", "Attached is the Periodontal Chart for your review.",PERIODONTAL_CHART_SHEET_NAME);

}

function copySheetAndSendEmail(sourceSpreadsheet, emailAddress, emailSubject, emailBody, PERIODONTAL_CHART_SHEET_NAME) {

  // Get the source sheet
  const periodontalChartSheet = sourceSpreadsheet.getSheetByName(PERIODONTAL_CHART_SHEET_NAME);
  // Create a new spreadsheet
  var newSpreadsheet = SpreadsheetApp.create("Periodontal Chart");

  // Copy the sheet to the new spreadsheet, including data and formatting
  periodontalChartSheet.copyTo(newSpreadsheet).setName("Periodontal Chart.pdf");

  // Get all sheets in the newSpreadsheet
  var sheets = newSpreadsheet.getSheets();

  // Loop through all sheets
  for (var i = 0; i < sheets.length; i++) {
    var sheet = sheets[i];

    // If the sheet is not the Periodontal Chart sheet, delete it
    if (sheet.getName() != "Periodontal Chart.pdf") {
      newSpreadsheet.deleteSheet(sheet);
    }
  }

var sheet = SpreadsheetApp.getActiveSheet();
for(var i=87;i<=sheet.getLastRow();i++){
  sheet.hideRow(i);
}

  // Convert the specified range of cells to a PDF file and save it to Google Drive
  const pdf2 = DriveApp.createFile(newSpreadsheet.getAs('application/pdf'));

  // Send the email with the PDF file attached
  GmailApp.sendEmail(emailAddress, emailSubject, emailBody, {attachments: [pdf2]});

  // Delete the new spreadsheet
  pdf2.setTrashed(true);
} here
</code>```

If I manually goto file download in sheets I will get the export options for the pdf, though I'm not sure how to fully implement via app scripts

Body:
hello is any one familiar with app scripts?

I'm sending data from unity app to google sheets form then to template, send to a new spreadsheet be converted into pdf with needed data and then send as email,

I'm having trouble with the sheets, I have the where what I want to send should not go pass row 86.

In the email I get all rows of the new spreadsheet which is sending 7 pages, I only need one page to send for this or one range A1:AX86, I've been trying multiple solutions, anyone have a take on this

Thanks,

typefunction sendPdfEmailWithLatestData() {
  // Constants
  const SPREADSHEET_ID = SpreadsheetApp.getActiveSpreadsheet().getId();
  const FORM_RESPONSE_SHEET_NAME = 'FormResponses';
  const PERIODONTAL_CHART_SHEET_NAME = 'Periodontal Chart';
  const EMAIL_SUBJECT = 'Periodontal Chart';
  const EMAIL_BODY = 'Attached is the Periodontal Chart for your review.';

  // Get the active spreadsheet and the sheets by their name
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const formResponseSheet = activeSpreadsheet.getSheetByName(FORM_RESPONSE_SHEET_NAME);
  const periodontalChartSheet = activeSpreadsheet.getSheetByName(PERIODONTAL_CHART_SHEET_NAME);

  // Get the range of all data in the FormResponses sheet, including the header row
  const formResponseDataRange = formResponseSheet.getDataRange();
  const numRows = formResponseDataRange.getNumRows();
  const numColumns = formResponseDataRange.getNumColumns();
  const values = formResponseDataRange.getValues();

  // Get the values from the latest row in the FormResponses sheet
  const headerRow = values[0]; // first row is the header row
  const latestRow = values[numRows - 1]; // last row is the latest row
  const patientLastName = latestRow[headerRow.indexOf('Last Name')];
  const patientFirstName = latestRow[headerRow.indexOf('First Name')];
  const patientDateOfBirth = latestRow[headerRow.indexOf('Date of Birth')];
  const appointmentDate = latestRow[headerRow.indexOf('Date')];
  const appointmentTime = latestRow[headerRow.indexOf('Time')];
  const appointmentVisit = latestRow[headerRow.indexOf('Visit')];
  const patientEmail = latestRow[headerRow.indexOf('Email')];

  // Update the values in the Periodontal Chart sheet
  const columnNames = ['E7:L7', 'Q7:X7', 'AC7:AJ7', 'AM7:AO7', 'AR7:AT7', 'AW7:AX7'];
  columnNames.forEach(function(columnName) {
  // Clear the contents of the cells in the specified column
  periodontalChartSheet.getRange(columnName).clearContent();
});
  const valuesToSet = [patientLastName, patientFirstName, patientDateOfBirth, appointmentDate, appointmentTime, appointmentVisit];
  columnNames.forEach((columnName, index) => {
    periodontalChartSheet.getRange(columnName).setValue(valuesToSet[index]);
  });

  // Convert the active spreadsheet to a PDF file and save it to Google Drive
  const pdf = DriveApp.createFile(activeSpreadsheet.getAs('application/pdf'));

  pdf.setName('Periodontal Chart.pdf');

  // Send the email with the PDF file attached
  //GmailApp.sendEmail(patientEmail, EMAIL_SUBJECT, EMAIL_BODY, {attachments: [pdf]});

  // Delete the PDF file from Google Drive
  pdf.setTrashed(true);

  console.log(`Latest row: ${latestRow}`);
copySheetAndSendEmail(SpreadsheetApp.getActiveSpreadsheet(), patientEmail, "Periodontal Chart", "Attached is the Periodontal Chart for your review.",PERIODONTAL_CHART_SHEET_NAME);

}

function copySheetAndSendEmail(sourceSpreadsheet, emailAddress, emailSubject, emailBody, PERIODONTAL_CHART_SHEET_NAME) {

  // Get the source sheet
  const periodontalChartSheet = sourceSpreadsheet.getSheetByName(PERIODONTAL_CHART_SHEET_NAME);
  // Create a new spreadsheet
  var newSpreadsheet = SpreadsheetApp.create("Periodontal Chart");

  // Copy the sheet to the new spreadsheet, including data and formatting
  periodontalChartSheet.copyTo(newSpreadsheet).setName("Periodontal Chart.pdf");

  // Get all sheets in the newSpreadsheet
  var sheets = newSpreadsheet.getSheets();

  // Loop through all sheets
  for (var i = 0; i < sheets.length; i++) {
    var sheet = sheets[i];

    // If the sheet is not the Periodontal Chart sheet, delete it
    if (sheet.getName() != "Periodontal Chart.pdf") {
      newSpreadsheet.deleteSheet(sheet);
    }
  }

var sheet = SpreadsheetApp.getActiveSheet();
for(var i=87;i<=sheet.getLastRow();i++){
  sheet.hideRow(i);
}

  // Convert the specified range of cells to a PDF file and save it to Google Drive
  const pdf2 = DriveApp.createFile(newSpreadsheet.getAs('application/pdf'));

  // Send the email with the PDF file attached
  GmailApp.sendEmail(emailAddress, emailSubject, emailBody, {attachments: [pdf2]});

  // Delete the new spreadsheet
  pdf2.setTrashed(true);
} here

If I manually goto file download in sheets I will get the export options for the pdf, though I'm not sure how to fully implement via app scripts


问:
How Do You Use SharePoint Online List Title and Description in form Header json?
I would like to use the SharePoint Online List Title and List Description in form Header json custom formatting. So far I have had no luck discovering how to do this, just how to use columns like "Title" but not the parameter to use for the List title itself. We also use Descriptions heavily and are hoping we can use this to make the transition to SP Online easier for our users.

Have attempted to discover the proper parameter names/formatting for SPO list title and description but no luck yet.


问:
how I can fix overlap issue in stackbarchart using vue-chartjs
I'm using latest vue-chartjs package with vue3 to create stackbarchart. I've shown the stackbarchart on my app but it's labels are overlapping. I need to know which property can add in options that can fix my issue.

```<code><template>
  <Bar
    v-if="chartData != null"
    :key="id"
    :data="chartData"
    :options="chartOptions"
  />
</template>

  <script>
import { Bar, getElementAtEvent } from "vue-chartjs";
import ChartJSPluginDatalabels from "chartjs-plugin-datalabels";
import uniqueId from "lodash.uniqueid";
import { drilldown } from "@/views/Reports/js/drilldown";
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  BarElement,
  CategoryScale,
  LinearScale,
  ArcElement
} from "chart.js";

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
  ArcElement,
  ChartJSPluginDatalabels
);

export default {
  name: "BarChartStacked",
  components: {
    Bar,
  },
  props: ["data", "options", "reportData", "eventInfo", "item", "duringDay"],
  data() {
    return {
      id: null,
    };
  },
  computed:{
    chartData() { return this.data; /* mutable chart data */ },
    chartOptions() { return this.options; /* mutable chart options */ }
  },
  mounted() {
    this.id = uniqueId();
    this.chartOptions.plugins.responsive = true;

    if (this.reportData && this.reportData.dataFilter) {

            if (this.item.conditions) {
                // change cursor to pointer if element is clickable
                this.chartOptions.hover = {
                    onHover: function(e) {
                        var point =getElementAtEvent(e);
                        if (point.length) e.target.style.cursor = 'pointer';
                        else e.target.style.cursor = 'default';
                    }
                }
                this.chartOptions.onClick = this.handle;
                }
        } else {
            this.chartOptions.hover = {}
        }

  },
</code>```

The stackbarchart should display value for the top most graph only like mention in the picture.

Body:
I'm using latest vue-chartjs package with vue3 to create stackbarchart. I've shown the stackbarchart on my app but it's labels are overlapping. I need to know which property can add in options that can fix my issue.

<template>
  <Bar
    v-if="chartData != null"
    :key="id"
    :data="chartData"
    :options="chartOptions"
  />
</template>


问:
IronPython.Runtime.Exceptions.ImportException: 'No module named 'errno'

Overview

Hi I'm trying to integrate some python code that uses various libraries in a C# application, but even referencing the Lib folder isn't helping me.

C# code

```<code>var loader = "C:\\PythonNet\\PythonNetProvider\\loader.py";
var lib = "C:\\Python34\\Lib";
ICollection\<string\> paths = engine.GetSearchPaths();
paths.Add(loader);
paths.Add(lib);
engine.SetSearchPaths(paths);
var source = engine.CreateScriptSourceFromFile("C:\\PythonNet\\PythonNetProvider\\main.py");
var scope = engine.CreateScope();
var compiledSource = source.Compile();

//The line underneath is where the exception is being thrown
compiledSource.Execute(scope);
</code>```

The exception is the following: IronPython.Runtime.Exceptions.ImportException: 'No module named 'errno''

loader.py

import pandas as pd

# other code

main.py

import loader

import copy

# other code

Conclusions

If I try to change the order of the two imports in the main.py the exception gives me the following message: IronPython.Runtime.Exceptions.ImportException: 'No module named '_weakref''

How can I solve these issues? Even using a different technology than IronPython

I've done pip install pandas and added the pandas folder path to the ICollection<string> paths but nothing changes

Body:
Overview

Hi I'm trying to integrate some python code that uses various libraries in a C# application, but even referencing the Lib folder isn't helping me.

C# code

var loader = "C:\\PythonNet\\PythonNetProvider\\loader.py";
var lib = "C:\\Python34\\Lib";
ICollection\<string\> paths = engine.GetSearchPaths();
paths.Add(loader);
paths.Add(lib);
engine.SetSearchPaths(paths);
var source = engine.CreateScriptSourceFromFile("C:\\PythonNet\\PythonNetProvider\\main.py");
var scope = engine.CreateScope();
var compiledSource = source.Compile();

//The line underneath is where the exception is being thrown
compiledSource.Execute(scope);

The exception is the following: IronPython.Runtime.Exceptions.ImportException: 'No module named 'errno''

loader.py

import pandas as pd

# other code

main.py

import loader

import copy

# other code

Conclusions

If I try to change the order of the two imports in the main.py the exception gives me the following message: IronPython.Runtime.Exceptions.ImportException: 'No module named '_weakref''

How can I solve these issues? Even using a different technology than IronPython

I've done pip install pandas and added the pandas folder path to the ICollection<string> paths but nothing changes


问:
Problems with API application
I built this Weather API JavaScript, but the API is not correspond correctly, when I'm trying to put my code to run it shows some errors on it, such as:

index.html:1 Access to fetch at 'file:///C:/Users/pauli/Documents/Projects/Weather/$%7Bproxy%7Dhttps://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&exclude=${part}&appid={c1660da1e108d8e09df7672f453f341f}' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

app.js:22          GET file:///C:/Users/pauli/Documents/Projects/Weather/$%7Bproxy%7Dhttps://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&exclude=${part}&appid={c1660da1e108d8e09df7672f453f341f} net::ERR_FAILED

app.js:22                  Uncaught (in promise) TypeError: Failed to fetch
at app.js:22:7

this is my JavaScript codes:

```<code>window.addEventListener('load', ()=>{
  let long;
  let lat;
  let temperatureDescription = document.querySelector('.temperature-description');
  let temperatureDegree = document.querySelector('.temperature-degree');
  let locationTimezone = document.querySelector('.location-timezone');
  let temperatureSection = document.querySelector(".temperature");
  const temperatureSpan = document.querySelector('.temperature span');

  if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(position => {
      long = position.coords.longitude;
      la = position.coords.latitude;

      const proxy = 'https://cors-anywhere.herokuapp.com/';

      //const api = `${proxy}https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/${lat},${long}?5bc2b4f40acfffa046713955a4370d52`;

      const api = '${proxy}https://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&exclude=${part}&appid={c1660da1e108d8e09df7672f453f341f}';

      fetch(api)
        .then(response => {
          return response.json();
        })

        .then(data => {
          const { temperature, summary, icon } = data.currently;

          //Set DOM Elements from the API
          temperatureDegree.textContent = temperature;
          temperatureDescription.textContent = summary;
          locationTimezone.textContent = data.timezone;

            })
        });
    });

</code>```

Can someone give me some help with it?

I tried to recode all the API application from different forms and it isn't working properly

Title: Problems with API application

Body:
I built this Weather API JavaScript, but the API is not correspond correctly, when I'm trying to put my code to run it shows some errors on it, such as:

index.html:1 Access to fetch at 'file:///C:/Users/pauli/Documents/Projects/Weather/$%7Bproxy%7Dhttps://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&exclude=${part}&appid={c1660da1e108d8e09df7672f453f341f}' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

app.js:22          GET file:///C:/Users/pauli/Documents/Projects/Weather/$%7Bproxy%7Dhttps://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&exclude=${part}&appid={c1660da1e108d8e09df7672f453f341f} net::ERR_FAILED

app.js:22                  Uncaught (in promise) TypeError: Failed to fetch
at app.js:22:7

this is my JavaScript codes:

window.addEventListener('load', ()=>{
  let long;
  let lat;
  let temperatureDescription = document.querySelector('.temperature-description');
  let temperatureDegree = document.querySelector('.temperature-degree');
  let locationTimezone = document.querySelector('.location-timezone');
  let temperatureSection = document.querySelector(".temperature");
  const temperatureSpan = document.querySelector('.temperature span');

  if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(position => {
      long = position.coords.longitude;
      la = position.coords.latitude;

      const proxy = 'https://cors-anywhere.herokuapp.com/';

      //const api = `${proxy}https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/${lat},${long}?5bc2b4f40acfffa046713955a4370d52`;

      const api = '${proxy}https://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&exclude=${part}&appid={c1660da1e108d8e09df7672f453f341f}';

      fetch(api)
        .then(response => {
          return response.json();
        })

        .then(data => {
          const { temperature, summary, icon } = data.currently;

          //Set DOM Elements from the API
          temperatureDegree.textContent = temperature;
          temperatureDescription.textContent = summary;
          locationTimezone.textContent = data.timezone;

            })
        });
    });

Can someone give me some help with it?

I tried to recode all the API application from different forms and it isn't working properly


问:
Eclipse: What's the difference between product definition via .product configuration file and via extension?
In the context of Eclipse Plugin Development, while associating an application with a product, what's the difference between product definition via .product configuration file and via extension? I know that the product configuration file allows one to specify lot of other launching and branding configuration options.

However, in the product configuration file, under Overview tab in Product Definition section there is Product and Application association. One can also associate the application for a product by adding the org.eclipse.core.runtime.products extension.

Editing application value in one DOES NOT update the other. The Run/Debug Configuration uses product/application information from the extension.

What's the purpose of defining specifying application inside the product configuration file if that's not sync'ed with the extension definition?


问:
With duckdb how can i just print the result without the preview in python?
I have a python program that im in the process of coverting to use dynamodb from sqllite

DuckDb allows me to keep all my sql statements intact but how can i get the result and not all the extra preview?

Here is my code:

```<code>import duckdb
from dynamo_pandas import get_df
import pandas as pd

player_df = get_df(table="player_table")
player_df = player_df.sort_values(by=['Name'],ascending=True)

results_df = get_df(table="results_table")
results_df = results_df.filter(['Date',
                        'Team A Result?',
                        'Team B Result?',
                        'Team A Total',
                        'Team B Total',
                        'Team A Player 1',
                        'Team A Player 2',
                        'Team A Player 3',
                        'Team A Player 4',
                        'Team A Player 5',
                        'Team B Player 1',
                        'Team B Player 2',
                        'Team B Player 3',
                        'Team B Player 4',
                        'Team B Player 5',
                        'Team A Colour',
                        'Team B Colour'])
results_df['Date'] = pd.to_datetime(results_df.Date,
                                format='%Y%m%d', errors='ignore')

player = "Player2"

sql = f'''SELECT
COUNT(CASE WHEN "Team A Player 1" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team A Player 2" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team A Player 3" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team A Player 4" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team A Player 5" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 1" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 2" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 3" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 4" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 5" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END)
    FROM results_df;'''
result = duckdb.query(sql)
print(f'Calulated {player}s wins as {result}')
</code>```

The result should literally be the number 2, but the result is:

```<code>Calulated Player2s wins as ---------------------
--- Relation Tree ---
---------------------
Subquery

---------------------
-- Result Columns  --
---------------------
- (((((((((count(CASE  WHEN ((("Team A Player 1" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END) + count(CASE  WHEN ((("Team A Player 2" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 3" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 4" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 5" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 1" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 2" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 3" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 4" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 5" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) (BIGINT)

---------------------
-- Result Preview  --
---------------------
(((((((((count(CASE  WHEN ((("Team A Player 1" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END) + count(CASE  WHEN ((("Team A Player 2" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 3" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 4" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 5" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 1" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 2" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 3" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 4" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 5" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END))
BIGINT
[ Rows: 1]
2
</code>```

Body:
I have a python program that im in the process of coverting to use dynamodb from sqllite

DuckDb allows me to keep all my sql statements intact but how can i get the result and not all the extra preview?

Here is my code:

import duckdb
from dynamo_pandas import get_df
import pandas as pd

player_df = get_df(table="player_table")
player_df = player_df.sort_values(by=['Name'],ascending=True)

results_df = get_df(table="results_table")
results_df = results_df.filter(['Date',
                        'Team A Result?',
                        'Team B Result?',
                        'Team A Total',
                        'Team B Total',
                        'Team A Player 1',
                        'Team A Player 2',
                        'Team A Player 3',
                        'Team A Player 4',
                        'Team A Player 5',
                        'Team B Player 1',
                        'Team B Player 2',
                        'Team B Player 3',
                        'Team B Player 4',
                        'Team B Player 5',
                        'Team A Colour',
                        'Team B Colour'])
results_df['Date'] = pd.to_datetime(results_df.Date,
                                format='%Y%m%d', errors='ignore')

player = "Player2"

sql = f'''SELECT
COUNT(CASE WHEN "Team A Player 1" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team A Player 2" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team A Player 3" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team A Player 4" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team A Player 5" = '{player}' AND "Team A Result?" > "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 1" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 2" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 3" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 4" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END) +
COUNT(CASE WHEN "Team B Player 5" = '{player}' AND "Team A Result?" < "Team B Result?" THEN 1 END)
    FROM results_df;'''
result = duckdb.query(sql)
print(f'Calulated {player}s wins as {result}')

The result should literally be the number 2, but the result is:

Calulated Player2s wins as ---------------------
--- Relation Tree ---
---------------------
Subquery

---------------------
-- Result Columns  --
---------------------
- (((((((((count(CASE  WHEN ((("Team A Player 1" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END) + count(CASE  WHEN ((("Team A Player 2" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 3" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 4" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 5" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 1" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 2" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 3" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 4" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 5" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) (BIGINT)

---------------------
-- Result Preview  --
---------------------
(((((((((count(CASE  WHEN ((("Team A Player 1" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END) + count(CASE  WHEN ((("Team A Player 2" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 3" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 4" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team A Player 5" = 'Player2') AND ("Team A Result?" > "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 1" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 2" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 3" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 4" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END)) + count(CASE  WHEN ((("Team B Player 5" = 'Player2') AND ("Team A Result?" < "Team B Result?"))) THEN (1) ELSE NULL END))
BIGINT
[ Rows: 1]
2


问:
How to solve certain attributes in a table to show result depends on another attributes on another table in SQLWorkbench SQL?
how to make attributes shows in table PAYMENT such as totalFoodQuantity and totalPayment

referred to above ERD img,what can I do with totalFoodQuantity and totalPayment on table PAYMENT to show its right result?

Unfortunately, I am not able to make it shows in SQL workbench when I'm trying to INSERT INTO data into those tables as I was left confused about totalFoodQuantity and totalPayment in table PAYMENT as I have stated above. The other table works fine but the problem is table PAYMENT. Hopefully someone can solve this for me and feel free to points out if there are something wrong with other tables.

Let's assume this ERD is about Burger Ordering System, and in table MENU, we have menu_ID that specifies types of burger. example: 'Meat Burger' and 'Cheese Burger'. Let's assume that both of these 2 attributes have foodQuantity of 3 and 5.Let's say both price are 3.00 and 4.00.

So in table PAYMENT, what can I do to make totalFoodQuantity, which is if one customer order those 2 types of burger, the totalFoodQuantity will show its total amount of 8.

This same goes with totalPayment where I want it to total up those foodPrice in table MENU depending on foodPrice and foodQuantity that the customer has ordered.What can I do to make totalPayment shows the result of 7.00?


问:
How does GridDB handle performance and scalability for large time-series data and compare it to traditional databases?
How does the use of GridDB improve performance and scalability when handling large amounts of time series data, such as sensor data from IoT devices, in comparison to traditional relational databases? And how does GridDB handle data consistency and availability in a distributed environment ?</p>


问:
How to group specific row data?
I want to turn this:

Query:

```<code>select A.DispatchNote, B.MStockCode, B.NComment
from MdnMaster A
  left join MdnDetail B on A.DispatchNote = B.DispatchNote
</code>```

A.DispatchNote
B.MStockCode
B.NComment

258579/0001
RFK2-8520-150-25

258579/0001

FREIGHT

258579/0001

1 Parcel UPS Ground 2/28/2020

258579/0001

Trk#: 1Z8R9V900342021397 -- 0.9 lb

258585/0001
CAW2-1832-25L

258585/0001

FREIGHT

258585/0001

6 Parcels UPS Ground 2/28/2020

258585/0001

Trk#: 1Z8R9V900342126962 -- 15 lb

258585/0001

Trk#: 1Z8R9V900342515176 -- 15 lb

258585/0001

Trk#: 1Z8R9V900340703781 -- 15 lb

258585/0001

Trk#: 1Z8R9V900340988792 -- 15 lb

258585/0001

Trk#: 1Z8R9V900340706204 -- 15 lb

258585/0001

Trk#: 1Z8R9V900342832014 -- 15 lb

into this:

Query:

```<code>select
   A.DispatchNote,
   MAX(B.MStockCode) as StockCode,
   MAX(B.NComment) as Comment
from MdnMaster A
left join MdnDetail B on A.DispatchNote = B.DispatchNote
      and (B.NComment LIKE 'Trk%' OR B.MStockCode is not null)
group by A.DispatchNote
</code>```

A.DispatchNote
B.MStockCode
B.NComment

258579/0001
RFK2-8520-150-25
Trk#: 1Z8R9V900342021397 -- 0.9 lb

258585/0001
CAW2-1832-25L
Trk#: 1Z8R9V900342126962 -- 15 lb

But I'm not sure how. When I run my query I still get rowsthat have random info in the NComment Column (like Blank NComments or things other than Trk#). I think I'm closer, but I'm still missing something.

Basically I want to clear the empty rows in MStockCode (or condense the rows I guess) and only pull the first visible tracking number that shows up for each dispatchnote when I run the query unsorted).

Title: How to group specific row data?

Body:
I want to turn this:

Query:

select A.DispatchNote, B.MStockCode, B.NComment
from MdnMaster A
  left join MdnDetail B on A.DispatchNote = B.DispatchNote

A.DispatchNote
B.MStockCode
B.NComment

258579/0001
RFK2-8520-150-25

258579/0001

FREIGHT

258579/0001

1 Parcel UPS Ground 2/28/2020

258579/0001

Trk#: 1Z8R9V900342021397 -- 0.9 lb

258585/0001
CAW2-1832-25L

258585/0001

FREIGHT

258585/0001

6 Parcels UPS Ground 2/28/2020

258585/0001

Trk#: 1Z8R9V900342126962 -- 15 lb

258585/0001

Trk#: 1Z8R9V900342515176 -- 15 lb

258585/0001

Trk#: 1Z8R9V900340703781 -- 15 lb

258585/0001

Trk#: 1Z8R9V900340988792 -- 15 lb

258585/0001

Trk#: 1Z8R9V900340706204 -- 15 lb

258585/0001

Trk#: 1Z8R9V900342832014 -- 15 lb

into this:

Query:

select
   A.DispatchNote,
   MAX(B.MStockCode) as StockCode,
   MAX(B.NComment) as Comment
from MdnMaster A
left join MdnDetail B on A.DispatchNote = B.DispatchNote
      and (B.NComment LIKE 'Trk%' OR B.MStockCode is not null)
group by A.DispatchNote

A.DispatchNote
B.MStockCode
B.NComment

258579/0001
RFK2-8520-150-25
Trk#: 1Z8R9V900342021397 -- 0.9 lb

258585/0001
CAW2-1832-25L
Trk#: 1Z8R9V900342126962 -- 15 lb

But I'm not sure how. When I run my query I still get rowsthat have random info in the NComment Column (like Blank NComments or things other than Trk#). I think I'm closer, but I'm still missing something.

Basically I want to clear the empty rows in MStockCode (or condense the rows I guess) and only pull the first visible tracking number that shows up for each dispatchnote when I run the query unsorted).


问:
How to run SQL query as a function
I created an onclick javascript function and the idea is to send values in the database table in every click of the button/a href but it seems that in every time I reload/open the page in the web it sends and runs every single function/query automatically.

This the function in my html file

```<code>//audit trail
function auditPrint(){
  <?php
  mysqli_query($conn,"insert into `audittrail` (user,activity) values ('employee','printed receipt')");
  ?>
}
function auditCancel(){
  <?php
  mysqli_query($conn,"insert into `audittrail` (user,activity) values ('employee','canceled transaction')");
  ?>
}
function auditLogout(){
  <?php
  mysqli_query($conn,"insert into `audittrail` (user,activity) values ('employee','logged out')");
  ?>
}
</code>```

It works fine but I would like it to send only if I click the button. Is there a way I can fix it?

Title: How to run SQL query as a function

Body:
I created an onclick javascript function and the idea is to send values in the database table in every click of the button/a href but it seems that in every time I reload/open the page in the web it sends and runs every single function/query automatically.

This the function in my html file

//audit trail
function auditPrint(){
  <?php
  mysqli_query($conn,"insert into `audittrail` (user,activity) values ('employee','printed receipt')");
  ?>
}
function auditCancel(){
  <?php
  mysqli_query($conn,"insert into `audittrail` (user,activity) values ('employee','canceled transaction')");
  ?>
}
function auditLogout(){
  <?php
  mysqli_query($conn,"insert into `audittrail` (user,activity) values ('employee','logged out')");
  ?>
}

It works fine but I would like it to send only if I click the button. Is there a way I can fix it?


问:
Can someone explain why I have build task error MSB3491?
When building using Visual Studio 2022, targeting net7.0, net6.0, and netstandard2.0, the build fails with the following warnings in the build output (I don't think multi-targeting has any impact):

>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3588,5): warning MSB3491: Could not write lines to file "obj\Debug\net6.0\.NETCoreApp,Version=v6.0.AssemblyAttributes.cs". Access to the path 'D:\src\XXX\obj\Debug\net6.0\.NETCoreApp,Version=v6.0.AssemblyAttributes.cs' is denied.
>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3588,5): warning MSB3491: Could not write lines to file "obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs". Access to the path 'D:\src\XXX\obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs' is denied.
>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3588,5): warning MSB3491: Could not write lines to file "obj\Debug\netstandard2.0\.NETStandard,Version=v2.0.AssemblyAttributes.cs". Access to the path 'D:\src\XXXn\obj\Debug\netstandard2.0\.NETStandard,Version=v2.0.AssemblyAttributes.cs' is denied.
```
<p>When logs are set to verbose, the following is emitted (only including for net7.0 TFM):</p>
<pre class="lang-bash prettyprint-override"><code>>    Target GenerateTargetFrameworkMonikerAttribute:
>      Building target "GenerateTargetFrameworkMonikerAttribute" completely.
>      Input file "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.targets" is newer than output file "obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs".
>      Task "WriteLinesToFile"
>        C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3588,5): warning MSB3491: Could not write lines to file "obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs". Access to the path 'D:\src\XXX\obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs' is denied.
>        The previous error was converted to a warning because the task was called with ContinueOnError=true.
>        Build continuing because "ContinueOnError" on the task "WriteLinesToFile" is set to "true".
>      Done executing task "WriteLinesToFile" -- FAILED.
>    Done building target "GenerateTargetFrameworkMonikerAttribute" in project "HatTrick.DbEx.CodeTemplating.csproj".
</code>```

The warnings reference temporary files created by the build process prior to compilation.

Things I've tried to figure this out:

If I run dotnet build from the command line, it results in the same.

If I change branches/pull or clean/build/rebuild, the build fails - there are no error messages in the output, only the warnings above.

If I restart Visual Studio and rebuild, the build succeeds, but still has the warnings.

I've tried on another machine and it works as expected (no errors or warnings) - I cannot reproduce this issue on another machine.

I don't think it's a file/directory permission exception because I can rebuild and the build process outputs the assemblies to the bin and obj folders just fine.

Body:
When building using Visual Studio 2022, targeting net7.0, net6.0, and netstandard2.0, the build fails with the following warnings in the build output (I don't think multi-targeting has any impact):

>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3588,5): warning MSB3491: Could not write lines to file "obj\Debug\net6.0\.NETCoreApp,Version=v6.0.AssemblyAttributes.cs". Access to the path 'D:\src\XXX\obj\Debug\net6.0\.NETCoreApp,Version=v6.0.AssemblyAttributes.cs' is denied.
>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3588,5): warning MSB3491: Could not write lines to file "obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs". Access to the path 'D:\src\XXX\obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs' is denied.
>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3588,5): warning MSB3491: Could not write lines to file "obj\Debug\netstandard2.0\.NETStandard,Version=v2.0.AssemblyAttributes.cs". Access to the path 'D:\src\XXXn\obj\Debug\netstandard2.0\.NETStandard,Version=v2.0.AssemblyAttributes.cs' is denied.

When logs are set to verbose, the following is emitted (only including for net7.0 TFM):

>    Target GenerateTargetFrameworkMonikerAttribute:
>      Building target "GenerateTargetFrameworkMonikerAttribute" completely.
>      Input file "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.targets" is newer than output file "obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs".
>      Task "WriteLinesToFile"
>        C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3588,5): warning MSB3491: Could not write lines to file "obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs". Access to the path 'D:\src\XXX\obj\Debug\net7.0\.NETCoreApp,Version=v7.0.AssemblyAttributes.cs' is denied.
>        The previous error was converted to a warning because the task was called with ContinueOnError=true.
>        Build continuing because "ContinueOnError" on the task "WriteLinesToFile" is set to "true".
>      Done executing task "WriteLinesToFile" -- FAILED.
>    Done building target "GenerateTargetFrameworkMonikerAttribute" in project "HatTrick.DbEx.CodeTemplating.csproj".

The warnings reference temporary files created by the build process prior to compilation.

Things I've tried to figure this out:

If I run dotnet build from the command line, it results in the same.

If I change branches/pull or clean/build/rebuild, the build fails - there are no error messages in the output, only the warnings above.

If I restart Visual Studio and rebuild, the build succeeds, but still has the warnings.

I've tried on another machine and it works as expected (no errors or warnings) - I cannot reproduce this issue on another machine.

I don't think it's a file/directory permission exception because I can rebuild and the build process outputs the assemblies to the bin and obj folders just fine.


问:
Control which multi fields are queried by default
I have a preexisting index that contains field mappings and is currently being queried by many applications. I would like to add additional ways for the data to be queried, specifically, support full text search via analysis. Multi-fields seemed like the obvious way to do this, but I found that adding new multi-fields actually changes the existing query behavior.

For example, I have an "id" field that is a keyword. Applications are already using this field to query on. After I add a new multi-field, like "txt" (using the standard analyzer), new documents can be found by querying with just a partial value match. Values for "id" look like this: "123-abc" so now a query with just "abc" will match when querying against the "id" field. This is not how it worked previously (the keyword only field would require the entire value "123-abc").

Ideally, the top-level "id" field would be keyword only, and if a "full text" search was required, the query would need to specify "id.txt". So my question is... is there a way to disable multi-fields and require that the query explicitly set a sub field when needed?

My only other thought on how to solve this, was to use copy_to so that these fields are completely distinct... but that is a bit more work and there are many many fields to deal with that would require this.


问:
MS Forms to Power Automate to Azure DevOps with attachment help - JSON
I have a MS Form getting information, creating a flow in Power Automate, then creating a work task in DevOps.  Everything works fine but I cannot get it to attach a file.  I've tried a lot of different options.  I'm creating a work task through JSON and not the "create a work item" action.  Below is an example:

Then after, I tried to add another request just to see but it doesn't do anything:


问:
How to upload either image or video with same input tag in angular 14
I need tips on how to upload both video and images in Angular / html.

```<code><div>
    <mat-icon *ngIf="file" (click)="removeImage(image)">cancel</mat-icon>
    <img [src]="file" alt="test" width="50" height="50" />
    <video [src]="file"  width="50" height="50" controls></video>
    <input type="file" accept=".png, .jpg, .mp4" (change)="onSelect($event)" #fileUpload>
</div>

<div>
   <button (click)="fileUpload.click()" mat-raised-button><mat-icon>camera_alt</mat-icon>
      <span>Upload</span>
   </button>
</div>
</code>```

What I am looking for is how to upload e.g 2 images and 1 video. Code above is not working because when I upload e.g an image, empty video alt follows it and vise versa. Also image is deleting video.

I found an the link here: url but the answer is not helping because it only upload either or video, it does not upload both.

How can I adjust the code to be able to upload more that one image and video e.g 2 images and 1 video?

Body:
I need tips on how to upload both video and images in Angular / html.

    <mat-icon *ngIf="file" (click)="removeImage(image)">cancel</mat-icon>

    <video [src]="file"  width="50" height="50" controls></video>
    <input type="file" accept=".png, .jpg, .mp4" (change)="onSelect($event)" #fileUpload>

   <button (click)="fileUpload.click()" mat-raised-button><mat-icon>camera_alt</mat-icon>
      Upload
   </button>

What I am looking for is how to upload e.g 2 images and 1 video. Code above is not working because when I upload e.g an image, empty video alt follows it and vise versa. Also image is deleting video.

I found an the link here: url but the answer is not helping because it only upload either or video, it does not upload both.

How can I adjust the code to be able to upload more that one image and video e.g 2 images and 1 video?


问:
change value inside keyframe animation using js
I want to change value given to translateX (-9vw) in animation using js, here is the code:

.transformX{animation: activeAni 2s;}

@keyframes activeAni {100% {transform: translateX(-9vw);}}


问:
Python mock patch tests work separately but not combined
I have written units test using unittest.mock and I am facing some issues with running tests together and singularly. I am mocking jira.JIRA from the JIRA SDK (on PyPI). My tests look something like:

```<code>import ...

class MyTests(BaseTest):
  setUp ...
  tearDown ...

  @mock.patch('os.system')
  @mock.patch('jira.JIRA')
  def test_my_lambda(self, mock_jira, mock_os) -> None:
    # run some code

    mock_jira().transition_issue.assert_called_once()
    mock_jira().transition_issue.assert_called_with(param1, param2)

    # other mock conditions
</code>```

Now of course from my understanding, the MagicMock returned and I can do sub calls on it etc and I can still call assertions on those sub functions etc. This test runs in isolation, however when running many tests together it says that the transition_issue call was not called, despite me going through the code and seeing it is called.

Am I missing something?

I tried to look into resetting the mock after each test, but I assumed the patch took care of that.

I also tried to to do imports relating to the jira.JIRA within the function (anything which imports my class which has the jira.JIRA() call in), but this did not work.

The fact it works as a single test is confusing me.

Body:
I have written units test using unittest.mock and I am facing some issues with running tests together and singularly. I am mocking jira.JIRA from the JIRA SDK (on PyPI). My tests look something like:

import ...

class MyTests(BaseTest):
  setUp ...
  tearDown ...

  @mock.patch('os.system')
  @mock.patch('jira.JIRA')
  def test_my_lambda(self, mock_jira, mock_os) -> None:
    # run some code

    mock_jira().transition_issue.assert_called_once()
    mock_jira().transition_issue.assert_called_with(param1, param2)

    # other mock conditions

Now of course from my understanding, the MagicMock returned and I can do sub calls on it etc and I can still call assertions on those sub functions etc. This test runs in isolation, however when running many tests together it says that the transition_issue call was not called, despite me going through the code and seeing it is called.

Am I missing something?

I tried to look into resetting the mock after each test, but I assumed the patch took care of that.

I also tried to to do imports relating to the jira.JIRA within the function (anything which imports my class which has the jira.JIRA() call in), but this did not work.

The fact it works as a single test is confusing me.


问:
getProperty from Properties.java file is returning ${browser} instead of null when no value is passed
So, we have this selenium.properties file from where we get the browser details from the below tag.

browser = ${browser}

When we run through maven command, this value get populated based on what we pass in -Dbrowser and its all good. However, when we don't pass in a browser value, instead of returning us null value getProperty is returning "${browser}" as value. How to avoid this?

Tried googling about this but no real info on how to fix this.


问:
Microsoft Teams App - pass team's culture to oauth backend provider in Tabs
I have build a Teams application on Asp.net core and connected the oauth backend provider. At startup.cs, I dont know the Team's culture yet. Then I ask user to login and get the culture in my cshtml page. But I am not able to find a way to pass Team's cultutre to my oauth backend.The settings goes like this in statup.cs:

```<code> services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieScheme;
                options.DefaultChallengeScheme = OAuthScheme;
                options.DefaultAuthenticateScheme = CookieScheme;
                options.DefaultSignInScheme = CookieScheme;
                options.DefaultSignOutScheme = CookieScheme;
            })
            .AddCookie(CookieScheme, options =>
            {
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.Cookie.SameSite = SameSiteMode.None;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
                options.SlidingExpiration = false;
                options.Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = RefreshTokenIfRequired
                };
            })
            .AddOAuth(OAuthScheme, options =>
            {
                var settings = JsonConvert.DeserializeObject<OnlineApiSettings>(Configuration["settings"]);
                options.ClientId = settings.ClientId;
                options.ClientSecret = settings.ClientSecret;
                options.AuthorizationEndpoint = settings.AuthEndpoint;
                options.TokenEndpoint = settings.TokenEndpoint;
                options.CallbackPath = new PathString("/oauth/callback");
                options.SaveTokens = true;
            });
</code>```

This is how login page constructed:

```<code><script type="text/javascript">

    function loginV1() {
        microsoftTeams.app.initialize().then(() => {
            microsoftTeams.app.getContext().then((context) => {
                login(window.location.origin + "/LoginPopup?culture=" + context.app.locale);
            });
        });
    }

    function login(url) {

        const urlParams = new URLSearchParams(window.location.search);
        const redirectUrl = urlParams.get('redirectPath');

        microsoftTeams.authentication.authenticate({
            url: url,
            width: 600,
            height: 535,
            successCallback: function (result) {
                console.log("Login succeeded: " + result);
                window.location.href = "/" + redirectUrl;
            },
            failureCallback: function (reason) {
                console.log("Login failed: " + reason);
                window.location.href = "/" + redirectUrl;
            }
        });
    }

</script>
</code>```

and LoginPopup page is like below:

```<code>
    [Authorize]
    public class LoginPopupModel : PageModel
    {

        private readonly IHttpContextAccessor _httpContext;

        public LoginPopupModel(IHttpContextAccessor httpContextAccessor)
        {
            _httpContext = httpContextAccessor;
        }

        public async Task<IActionResult> OnGetAsync()
        {
            if (_httpContext.HttpContext.User.Identity.IsAuthenticated)
            {
                return RedirectToPage("LoginSuccess");
            }
            return null;
        }
    }
</code>```

Body:
I have build a Teams application on Asp.net core and connected the oauth backend provider. At startup.cs, I dont know the Team's culture yet. Then I ask user to login and get the culture in my cshtml page. But I am not able to find a way to pass Team's cultutre to my oauth backend.The settings goes like this in statup.cs:

 services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieScheme;
                options.DefaultChallengeScheme = OAuthScheme;
                options.DefaultAuthenticateScheme = CookieScheme;
                options.DefaultSignInScheme = CookieScheme;
                options.DefaultSignOutScheme = CookieScheme;
            })
            .AddCookie(CookieScheme, options =>
            {
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.Cookie.SameSite = SameSiteMode.None;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
                options.SlidingExpiration = false;
                options.Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = RefreshTokenIfRequired
                };
            })
            .AddOAuth(OAuthScheme, options =>
            {
                var settings = JsonConvert.DeserializeObject<OnlineApiSettings>(Configuration["settings"]);
                options.ClientId = settings.ClientId;
                options.ClientSecret = settings.ClientSecret;
                options.AuthorizationEndpoint = settings.AuthEndpoint;
                options.TokenEndpoint = settings.TokenEndpoint;
                options.CallbackPath = new PathString("/oauth/callback");
                options.SaveTokens = true;
            });

This is how login page constructed:

and LoginPopup page is like below:

    [Authorize]
    public class LoginPopupModel : PageModel
    {

        private readonly IHttpContextAccessor _httpContext;

        public LoginPopupModel(IHttpContextAccessor httpContextAccessor)
        {
            _httpContext = httpContextAccessor;
        }

        public async Task<IActionResult> OnGetAsync()
        {
            if (_httpContext.HttpContext.User.Identity.IsAuthenticated)
            {
                return RedirectToPage("LoginSuccess");
            }
            return null;
        }
    }


问:
How to Properly Destroy an Intersection Observer?
I am currently wrapping the IntersectionObserver API into a Svelte action. Part of this requires cleanup in a destroy() function, below is what I have.

function observe(node: HTMLElement, key: string) {
    const observer = new IntersectionObserver(nodes => {
        locations[key] = nodes[0]!.isIntersecting;
        locations = locations;
    });

    observer.observe(node);

    return {
        // this is the focus of my question
        destroy() {
            observer.unobserve(node);
        }
    }
}
```

Is there anything else I need to do to destroy the IntersectionObserver?

Body:
I am currently wrapping the IntersectionObserver API into a Svelte action. Part of this requires cleanup in a destroy() function, below is what I have.

function observe(node: HTMLElement, key: string) {
    const observer = new IntersectionObserver(nodes => {
        locations[key] = nodes[0]!.isIntersecting;
        locations = locations;
    });

    observer.observe(node);

    return {
        // this is the focus of my question
        destroy() {
            observer.unobserve(node);
        }
    }
}

Is there anything else I need to do to destroy the IntersectionObserver?


问:
Property 'includes' does not exist on type 'number[]'. Unable to resolve error even after changing lib in tsconfig.json
I'm using a function to fetch data from an API. Afterwards I'm trying to push part of that data (some id's) into an array, if that id is not already included. I wanted to use the .includes() method to check for this but I keep getting  "error TS2550: Property 'includes' does not exist on type 'number[]'."

This is the code below:

```<code>// Get data from API
const getFixturesData = () => {
    // Here I am fetching the data
    let domain: string = "https://v3.football.api-sports.io/fixtures?";
    let league: string = (document.getElementById("league")! as HTMLInputElement).value;
    let date: string = (document.getElementById("date-picker")! as HTMLInputElement).value;
    (async (url: string) => {
        const response: Response = await fetch(url, {
            "method": "GET",
            "headers": {
                "x-rapidapi-host": "v3.football.api-sports.io",
                "x-rapidapi-key": "personal API key"
            }
        });
        return response.json();
    })(`${domain}date=${date}&status=FT`).then(value => {
    // Here I am parsing the data
        let fixtures: any[] = [];
        let competitions: number[] = [];

        if (league == "") {
            fixtures = value.response;
            for (let event in fixtures) {
                competitions.push(parseInt(fixtures[event].league.id));
            }
        } else {
            let allFixtures: any[] = value.response;
            for (let event in allFixtures) {
                if (allFixtures[event].league.id == league) {
                    fixtures.push(allFixtures[event]);
                    // Here is where I am trying to use .includes()
                    if (!(competitions.includes(parseInt(allFixtures[event].league.id)))) {
                        competitions.push(parseInt(allFixtures[event].league.id));
                    }
                }
            }
        }
        }

</code>```

Other solutions that I found online point to changing the lib in the tsconfig.json file. I tried multiple options but none of them worked. I get the same error. Here is the current configuration of the file. I only pasted the rows which are not commented out.

I'm using TypeScript 4.8.3 .
I'm a beginner in TypeScript so pardon any gross mistakes that you may observe.

```<code>{
   "compilerOptions":{
      "target":"ES2016",
      "lib":[
         "DOM",
         "ES2022"
      ],
      "module":"commonjs",
      "esModuleInterop":true,
      "forceConsistentCasingInFileNames":true,
      "strict":true
   }
}
</code>```

Thank you for your time!

Body:
I'm using a function to fetch data from an API. Afterwards I'm trying to push part of that data (some id's) into an array, if that id is not already included. I wanted to use the .includes() method to check for this but I keep getting  "error TS2550: Property 'includes' does not exist on type 'number[]'."

This is the code below:

// Get data from API
const getFixturesData = () => {
    // Here I am fetching the data
    let domain: string = "https://v3.football.api-sports.io/fixtures?";
    let league: string = (document.getElementById("league")! as HTMLInputElement).value;
    let date: string = (document.getElementById("date-picker")! as HTMLInputElement).value;
    (async (url: string) => {
        const response: Response = await fetch(url, {
            "method": "GET",
            "headers": {
                "x-rapidapi-host": "v3.football.api-sports.io",
                "x-rapidapi-key": "personal API key"
            }
        });
        return response.json();
    })(`${domain}date=${date}&status=FT`).then(value => {
    // Here I am parsing the data
        let fixtures: any[] = [];
        let competitions: number[] = [];

        if (league == "") {
            fixtures = value.response;
            for (let event in fixtures) {
                competitions.push(parseInt(fixtures[event].league.id));
            }
        } else {
            let allFixtures: any[] = value.response;
            for (let event in allFixtures) {
                if (allFixtures[event].league.id == league) {
                    fixtures.push(allFixtures[event]);
                    // Here is where I am trying to use .includes()
                    if (!(competitions.includes(parseInt(allFixtures[event].league.id)))) {
                        competitions.push(parseInt(allFixtures[event].league.id));
                    }
                }
            }
        }
        }

Other solutions that I found online point to changing the lib in the tsconfig.json file. I tried multiple options but none of them worked. I get the same error. Here is the current configuration of the file. I only pasted the rows which are not commented out.

I'm using TypeScript 4.8.3 .
I'm a beginner in TypeScript so pardon any gross mistakes that you may observe.

{
   "compilerOptions":{
      "target":"ES2016",
      "lib":[
         "DOM",
         "ES2022"
      ],
      "module":"commonjs",
      "esModuleInterop":true,
      "forceConsistentCasingInFileNames":true,
      "strict":true
   }
}

Thank you for your time!


问:
Svelte (npm run dev) marks all CSS in global scss as unused and purges on macOS
So, I've tested this on two machines. One is a Debian VPS and the other is a local Mac. They're both running the latest softwares. However, running npm dev run on exactly the same project results in very different outcomes – on the Linux VPS, scss from global stylesheets declared with  everything is included nicely and propagates across my app, like I want it to. Do I do exactly the same on the Mac machine however, every css selector is marked as "unused" and is thus purged, resulting in all global css not making it to the app. How is it possible that with all the same files these two very different outcomes come to be, and how could I fix the situation on the Mac machine?

The project was set up with Sveltekit.

edit: to drive this point home: it even marks "html" as an unused css selector.


问:
Agent is not leaving the Assembler block in AnyLogic
Agent is not leaving the assembler block while the model keeps runing with out showing any error. The image of Assembler properties is given below.

When I run the model, I act like this all the time.

Moreover, when I limited the number of arrivals to one for the sources, then it worked just fine.Kindly let me know what I am missing and how to solve this issue.


问:
Using a .env in a html and js file
How would I use an .env file in my html file and javascript file?

In my .env file I have:

```<code>GOOGLE_API_TOKEN=token
</code>```

In my html file I have:

```<code><iframe id="maps" src="https://www.google.com/maps/embed/v1/place?key=GOOGLE_API_TOKEN&q=United+States" width="600" height="450" style="border:0" allowfullscreen="" loading="lazy"></iframe>
</code>```

I'm not sure how to obtain the token from the .env file and put it into the iframe src.

Since I'm new to using .env files, I'm not sure how to access the token in my javascript file.

Directory Layout

I've tried using the backtick, but that doesn't work in html.
For javascript I've tried import and require, but can't do that.

Title: Using a .env in a html and js file

Body:
How would I use an .env file in my html file and javascript file?

In my .env file I have:

GOOGLE_API_TOKEN=token

In my html file I have:

I'm not sure how to obtain the token from the .env file and put it into the iframe src.

Since I'm new to using .env files, I'm not sure how to access the token in my javascript file.

Directory Layout

I've tried using the backtick, but that doesn't work in html.
For javascript I've tried import and require, but can't do that.


问:
SwiftUI View with inconsistent Navigation Bar appearance
This is the scenario:

I'm moving from a UIViewController to a SwiftUI View:

```<code>let viewController = UIHostingController(rootView: DashboardView())
pushViewController(viewController, animated: true)
</code>```

On the first time the View's navigation bar will be as expected, when we scroll the screen the bar will be opaque and we won't see the content bellow it:

Now I go back to the previous screen and move to the same Dashboard screen exactly how we are doing it on step #1, but now the content is visible under the navigation bar:

If I modify the appearance then other screens will have an appearance change as well. One simple example would be screens that didn't have text on their back button now have it.

I've tried this following piece of code a few more things:

```<code>let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
</code>```

Any suggestions?

This is the body structure for this SwiftUI View:

```<code>var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                // subviews inside
            }
        }
}
</code>```

EDIT:

Here's the hierarchy:

For the first time we move into the Dashboard:

For the second time we move into the Dashboard:

Body:
This is the scenario:

I'm moving from a UIViewController to a SwiftUI View:

let viewController = UIHostingController(rootView: DashboardView())
pushViewController(viewController, animated: true)

On the first time the View's navigation bar will be as expected, when we scroll the screen the bar will be opaque and we won't see the content bellow it:

Now I go back to the previous screen and move to the same Dashboard screen exactly how we are doing it on step #1, but now the content is visible under the navigation bar:

If I modify the appearance then other screens will have an appearance change as well. One simple example would be screens that didn't have text on their back button now have it.

I've tried this following piece of code a few more things:

let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance

Any suggestions?

This is the body structure for this SwiftUI View:

var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                // subviews inside
            }
        }
}

EDIT:

Here's the hierarchy:

For the first time we move into the Dashboard:

For the second time we move into the Dashboard:


问:
Struggling to rotate 2D array 90° CW in c++
I am attempting to write code to rotate an array 90 degrees clockwise in c++:

```<code>#include <iostream>

int main() {
    int ary[4][4] = { {1,2,3,4},
                      {6,7,8,9},
                      {11,12,13,14},
                      {16,17,18,19} };

    int temp[4][4];
    int l = sizeof(ary) / sizeof(ary[0]);
    int w = sizeof(ary[0]) / sizeof(ary[0][0]);
    //int size = sizeof(ary)/sizeof(int);
    std::cout << "Length: " << l << std::endl;
    std::cout << "Width: " << w << std::endl;
    std::cout << "Original Ary: " << std::endl;

    //prints each element of a 2D ary
    for (int i = 0; i < l; i++) {
        //cout<<"entered i2 loop"<<endl;
        for (int j = 0; j < w; j++) {
            //cout<<"entered j2 loop"<<endl;
            std::cout << ary[i][j] << " ";
            //endl after last elem in row
            if (j == w - 1) {
                std::cout << std::endl;
            }
        }
    }
    std::cout << std::endl;

    //rotates array 90 CW
    for (int i = 0; i < (l - 1); i++) {
        for (int j = i; j < (w-i-1); j++) {
            //swaps elements in ary
            temp[i][j] = ary[i][j];
            ary[i][j] = ary[w - 1 - j][i];
            ary[w - 1 - j][i] = ary[l - 1 - i][w - 1 - j];
            ary[j][l - 1 - i] = temp[i][j];
        }
    }
    std::cout << "Rotated Ary: " << std::endl;

    //prints each element of a 2D ary
    for (int i = 0; i < l; i++) {
        //cout<<"entered i2 loop"<<endl;
        for (int j = 0; j < w; j++) {
            //cout<<"entered j2 loop"<<endl;
            std::cout << ary[i][j] << " ";
            //endl after last elem in row
            if (j == w - 1) {
                std::cout << std::endl;
            }
        }
    }
    return 0;
}
</code>```

This is the current output:

Length: 4
Width: 4
Original Ary:
1 2 3 4
6 7 8 9
11 12 13 14
16 17 18 19

Rotated Ary:
16 11 6 1
17 12 7 2
18 13 13 3
19 17 18 19
```
<p>I was expecting the rotated array to look like this:</p>
<pre class="lang-none prettyprint-override"><code>16 11 6 1
17 12 7 2
18 13 8 3
19 14 9 4
</code>```

As you can see, the first 2 lines rotate correctly but the values 13, 17, 18, and 19 repeated in the last 2 lines when they should not be. What changes do I need to make to this code, and why does this program not work as intended?

Body:
I am attempting to write code to rotate an array 90 degrees clockwise in c++:

#include <iostream>

int main() {
    int ary[4][4] = { {1,2,3,4},
                      {6,7,8,9},
                      {11,12,13,14},
                      {16,17,18,19} };

    int temp[4][4];
    int l = sizeof(ary) / sizeof(ary[0]);
    int w = sizeof(ary[0]) / sizeof(ary[0][0]);
    //int size = sizeof(ary)/sizeof(int);
    std::cout << "Length: " << l << std::endl;
    std::cout << "Width: " << w << std::endl;
    std::cout << "Original Ary: " << std::endl;

    //prints each element of a 2D ary
    for (int i = 0; i < l; i++) {
        //cout<<"entered i2 loop"<<endl;
        for (int j = 0; j < w; j++) {
            //cout<<"entered j2 loop"<<endl;
            std::cout << ary[i][j] << " ";
            //endl after last elem in row
            if (j == w - 1) {
                std::cout << std::endl;
            }
        }
    }
    std::cout << std::endl;

    //rotates array 90 CW
    for (int i = 0; i < (l - 1); i++) {
        for (int j = i; j < (w-i-1); j++) {
            //swaps elements in ary
            temp[i][j] = ary[i][j];
            ary[i][j] = ary[w - 1 - j][i];
            ary[w - 1 - j][i] = ary[l - 1 - i][w - 1 - j];
            ary[j][l - 1 - i] = temp[i][j];
        }
    }
    std::cout << "Rotated Ary: " << std::endl;

    //prints each element of a 2D ary
    for (int i = 0; i < l; i++) {
        //cout<<"entered i2 loop"<<endl;
        for (int j = 0; j < w; j++) {
            //cout<<"entered j2 loop"<<endl;
            std::cout << ary[i][j] << " ";
            //endl after last elem in row
            if (j == w - 1) {
                std::cout << std::endl;
            }
        }
    }
    return 0;
}

This is the current output:

Length: 4
Width: 4
Original Ary:
1 2 3 4
6 7 8 9
11 12 13 14
16 17 18 19

Rotated Ary:
16 11 6 1
17 12 7 2
18 13 13 3
19 17 18 19

I was expecting the rotated array to look like this:

16 11 6 1
17 12 7 2
18 13 8 3
19 14 9 4

As you can see, the first 2 lines rotate correctly but the values 13, 17, 18, and 19 repeated in the last 2 lines when they should not be. What changes do I need to make to this code, and why does this program not work as intended?


问:
Variable storage issue
So I wrote a Python script on my phone to control Roku TVs and it works great, but...
When I use the standard method to find a Roku device on the Network it returns the First Device to respond, so...
I added Store and Recall buttons to Make it easier to cycle through devices on the Network... (Some logic was used to make it so the Store button only shows if the Device it finds isn't already stored, etc... And Recall is set to cycle to the Next Device Stored in the list after the one it's on...)
This works so far, however...
I'm storing/reading variables in a file because the Tkinter Background Canvas and Buttons are in a loop so Global variables are continually reset.
Normally, I would just pass variables to a second (memory) script and read them back on each event.  But the phone only runs one script at a time.
Is there a better way to keep the variables in memory (namely the current device)</p>
```<code>#!/usr/bin/env python
#Imports come first then
#defs read the file to a variable
#After defs I find the first Roku device to respond
#I'm writing that as a variable to a file

Store_Location = open('/storage/emulated/0/Movies/Roku/MMemory.ini', 'w')
Store_Location.write(location)
Store_Location.close()

#It works
#Then Tkinter and buttons are standard and work then after buttons I

root.mainloop()
</code>```

Title: Variable storage issue

Body:
So I wrote a Python script on my phone to control Roku TVs and it works great, but...
When I use the standard method to find a Roku device on the Network it returns the First Device to respond, so...
I added Store and Recall buttons to Make it easier to cycle through devices on the Network... (Some logic was used to make it so the Store button only shows if the Device it finds isn't already stored, etc... And Recall is set to cycle to the Next Device Stored in the list after the one it's on...)
This works so far, however...
I'm storing/reading variables in a file because the Tkinter Background Canvas and Buttons are in a loop so Global variables are continually reset.
Normally, I would just pass variables to a second (memory) script and read them back on each event.  But the phone only runs one script at a time.
Is there a better way to keep the variables in memory (namely the current device)

#!/usr/bin/env python
#Imports come first then
#defs read the file to a variable
#After defs I find the first Roku device to respond
#I'm writing that as a variable to a file

Store_Location = open('/storage/emulated/0/Movies/Roku/MMemory.ini', 'w')
Store_Location.write(location)
Store_Location.close()

#It works
#Then Tkinter and buttons are standard and work then after buttons I

root.mainloop()


问:
pytorch Dataloader __getitem idx control when using csv file
I am trying to load an image file using the following form of the csv file.
This is a simplified representation of my huge csv file in the same format.

I actually understand the basic method of sequentially loading images using rows of csv files by code "iloc[idx]".

However, like the attached image, it is difficult to sequentially load images containing as many images as "number of images" in the terminal folder written in the "file location."

According to the attached image, the idx of getitem_ points to 16 images in the "./data/asd" folder sequentially, and then to the "./data/vbn" folder so that the next 16 images can be imported sequentially.

It's a code that I've worked on so far, so I'd appreciate any advice you can give me here.

```<code>class CustomDataset(torch.utils.data.Dataset):

def __init__(self, root, csv_file):
    self.root = root
    self.df = pd.read_csv(csv_file)

def __len__(self):
    #The sum of "Number of Images" values will be the total length of the image dataset.
    return len(self.df.iloc[1:,1].sum())

def __getitem__(self, idx):
    #This is where I have trouble controlling idx.
    img_name = os.path.join(self.root, self.df.iloc[idx, 2] + '.dcm')
    image = io.imread(img_name)
    image = torch.tensor(image)

    return image
</code>```

Body:
I am trying to load an image file using the following form of the csv file.
This is a simplified representation of my huge csv file in the same format.

I actually understand the basic method of sequentially loading images using rows of csv files by code "iloc[idx]".

However, like the attached image, it is difficult to sequentially load images containing as many images as "number of images" in the terminal folder written in the "file location."

According to the attached image, the idx of getitem_ points to 16 images in the "./data/asd" folder sequentially, and then to the "./data/vbn" folder so that the next 16 images can be imported sequentially.

It's a code that I've worked on so far, so I'd appreciate any advice you can give me here.

class CustomDataset(torch.utils.data.Dataset):

def __init__(self, root, csv_file):
    self.root = root
    self.df = pd.read_csv(csv_file)

def __len__(self):
    #The sum of "Number of Images" values will be the total length of the image dataset.
    return len(self.df.iloc[1:,1].sum())

def __getitem__(self, idx):
    #This is where I have trouble controlling idx.
    img_name = os.path.join(self.root, self.df.iloc[idx, 2] + '.dcm')
    image = io.imread(img_name)
    image = torch.tensor(image)

    return image


问:
Thread safety of std::string::c_str()
It appears to me as if there is a requirement in modern C++ that after calling operator[](), c_str(), or data(), it is guaranteed that string's contents are terminated by a null.

However, is it possible that this initialization may be done "lazily"?  That is, the buffer allocated for the string's content may not be null terminated until after one of those functions is called, potentially making usage of this function not thread_safe?   I am ideally looking for a specific citation from the standard, one way or the other.

Title: Thread safety of std::string::c_str()


问:
Next.js Graphql Apollo Client query with "sort" parameter not work
Why can I specify parameters for pagination, but it does not work for sorting.

This works:

```<code>const GET_ALL_POSTS = gql`
  query GetAllPosts($start: Int, $limit: Int) {
    posts(pagination: { start: $start, limit: $limit }, sort: "Date:desc") {
      data {
</code>```

This does not work:

```<code>const GET_ALL_POSTS = gql`
  query GetAllPosts($start: Int, $limit: Int, $sort: String) {
    posts(pagination: { start: $start, limit: $limit }, sort: $sort) {
      data {
</code>```

My Query for sorting with param:

```<code>  const { data: GetAllPosts } = await client.query({
    query: GET_ALL_POSTS,
    variables: { start: 1, limit: -1, sort: 'Date:desc' },
  });
</code>```

Body:
Why can I specify parameters for pagination, but it does not work for sorting.

This works:

const GET_ALL_POSTS = gql`
  query GetAllPosts($start: Int, $limit: Int) {
    posts(pagination: { start: $start, limit: $limit }, sort: "Date:desc") {
      data {

This does not work:

const GET_ALL_POSTS = gql`
  query GetAllPosts($start: Int, $limit: Int, $sort: String) {
    posts(pagination: { start: $start, limit: $limit }, sort: $sort) {
      data {

My Query for sorting with param:

  const { data: GetAllPosts } = await client.query({
    query: GET_ALL_POSTS,
    variables: { start: 1, limit: -1, sort: 'Date:desc' },
  });