问:
Record filtering doesn't return all records
I have a JS code that filters the records of a table, the problem is that the table has a specific amount of records (5 records per page) and when I do a filtering test, only the records of the selected pagination are filtered. that records from other pagination pages don't show up unless I change the pagination page.

```<code>var filter = document.getElementById('name_client');
var table = document.getElementById('search_client');

filtro.onkeyup = function() {
    var filterName = filter.value.toLowerCase();
    for (var i = 1; i < table.rows.length; i++) {
        var content = table.rows[i].cells[1].innerText;
        var corresponds = content.toLowerCase().indexOf(Filtername) >= 0;
        table.rows[i].style.display = corresponds ? '' : 'none';
    }
}
</code>```

                  <form class="d-flex" role="search">
                     <input class="form-control me-2" type="search" placeholder="Search client" id="name_client" aria-label="Search">
                  </form>

                     ID
                     Nome
                     Actions

                  @foreach($clients as c)

                     {{ $c->id }}
                     {{ $c->name }}

                        <form action="{{ url("delete/".encrypt($c->id)) }}" method="POST">
                        id)) }}" class="btn btn-primary"> Update
                        {{ ' ' }} {{ method_field('DELETE') }} {{ csrf_field() }}
                        <button type="submit" class="btn btn-danger"> Deletr</button>
                        </form>

                  @endforeach

            {{ $clients->links() }}

```

How to solve it problem?

Body:
I have a JS code that filters the records of a table, the problem is that the table has a specific amount of records (5 records per page) and when I do a filtering test, only the records of the selected pagination are filtered. that records from other pagination pages don't show up unless I change the pagination page.

var filter = document.getElementById('name_client');
var table = document.getElementById('search_client');

filtro.onkeyup = function() {
    var filterName = filter.value.toLowerCase();
    for (var i = 1; i
= 0;
        table.rows[i].style.display = corresponds ? '' : 'none';
    }
}

                  <form class="d-flex" role="search">
                     <input class="form-control me-2" type="search" placeholder="Search client" id="name_client" aria-label="Search">
                  </form>

                     ID
                     Nome
                     Actions

                  @foreach($clients as c)

                     {{ $c->id }}
                     {{ $c->name }}

                        <form action="{{ url("delete/".encrypt($c->id)) }}" method="POST">
                        id)) }}" class="btn btn-primary"> Update
                        {{ ' ' }} {{ method_field('DELETE') }} {{ csrf_field() }}
                        <button type="submit" class="btn btn-danger"> Deletr</button>
                        </form>

                  @endforeach

            {{ $clients->links() }}

How to solve it problem?


来源: stackexchange

问:
How to create a checkbox with a link, without triggering checkbox checked event in Quasar q-checkbox?
I am trying to create terms and conditions checkbox using q-checkbox. The label of the checkbox should be something like this, 'I have read and understood the' part should not be clickable, and the User Clarification Text part should be clickable that opens a popup when clicked, i have tried this:

```<code> .row
   q-checkbox(color="primary" v-model="termsAccepted")
   div
     .text-regular.no-pointer-events.text-primary(style="text-decoration: none")
       | I have read and understood the
     .cursor-pointer.text-primary.text-regular.text-underline(@click="openConditionsDialog()" style="text-decoration: underline")
       | User Clarification Text.

</code>```

@click event is not triggered and both texts are apart from each other, and not even near to checkbox, i also tried using q-checkbox's default slot

```<code>q-checkbox(v-model="val" style="cursor:auto")
  I have read and understood the
  a(@click="openPopup") User Clarification Text.
</code>```

It works and triggers the event but when clicked, it also checks the checkbox, i don't want that, can you help me find a better solution?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create terms and conditions checkbox using q-checkbox. The label of the checkbox should be something like this, 'I have read and understood the' part should not be clickable, and the User Clarification Text part should be clickable that opens a popup when clicked, i have tried this:

 .row
   q-checkbox(color="primary" v-model="termsAccepted")
   div
     .text-regular.no-pointer-events.text-primary(style="text-decoration: none")
       | I have read and understood the
     .cursor-pointer.text-primary.text-regular.text-underline(@click="openConditionsDialog()" style="text-decoration: underline")
       | User Clarification Text.

@click event is not triggered and both texts are apart from each other, and not even near to checkbox, i also tried using q-checkbox's default slot

q-checkbox(v-model="val" style="cursor:auto")
  I have read and understood the
  a(@click="openPopup") User Clarification Text.

It works and triggers the event but when clicked, it also checks the checkbox, i don't want that, can you help me find a better solution?


问:
I want to iterate through a list that I created and then log random result based on conditional statement. However I am getting random first letters?
I think it has something to do with my loop? I am using the AP code.org curriculum, ie. "getColumn" is one of their functions I believe.

var birdColor = getColumn("100 Birds of the World", "Primary Color");
var conservationStatus = getColumn("100 Birds of the World", "Conservation Status");
var birdName = getColumn("100 Birds of the World", "Name");
var filteredRandomizedBirdList = [];

//Global variable, these will be choices from the dropdown var colorChoice = "Black"; var statusChoice = "Least Concern";

function filter() {
  var index = 0;
  var color = birdColor;
  var status = conservationStatus;
  for (i = 0; i < birdColor.length; i++) {
    if (color[i] === colorChoice && status[i] === statusChoice) {
      filteredRandomizedBirdList = birdName[i];
      index = randomNumber(0, filteredRandomizedBirdList.length - 1);
      console.log(filteredRandomizedBirdList[index]);
      setText("textArea", filteredRandomizedBirdList);
    }
  }
}

filter();
```


问:
Debugging Ios App Extension in Flutter app
I am writing a flutter application, but I needed to write a ios application extension in the native part. I think there might be a bug and I'm debugging this target. I selected the extension I needed as a target for launching, made a debug scheme for it, selected the application with which the extension would be launched, and launched it. Next I got an error about not being able to run flutter without a debugger:

To launch in debug mode in iOS 14+, run flutter run from Flutter tools, run from an IDE with a Flutter IDE plugin or run the iOS project from Xcode. Alternatively profile and release mode apps can be launched from the home screen.

Is there any way to debug ios extensions for flutter app?


问:
NativeWind styles not being applied
I am seeing not styling changes despite installing NativeWind CSS.

I have followed the trouble shooting guide but this has not helped (https://www.nativewind.dev/guides/troubleshooting)

package.json

```<code>{
  "name": "betting-app",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "expo": "~47.0.9",
    "expo-status-bar": "~1.4.2",
    "nativewind": "^2.0.11",
    "react": "18.1.0",
    "react-native": "0.70.5"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "tailwindcss": "^3.2.4"
  },
  "private": true
}

</code>```

Babel.config.js

```<code>module.exports = function (api) {
  api.cache(true);
  return {
    plugins: ["nativewind/babel"],
    presets: ["babel-preset-expo"],
  };
};

</code>```

tailwind.config.js

```<code>// tailwind.config.js
module.exports = {
  content: [
    "./screens/**/*.{js,ts,jsx,tsx}",
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  // ...
};

</code>```

Title: NativeWind styles not being applied

Body:
I am seeing not styling changes despite installing NativeWind CSS.

I have followed the trouble shooting guide but this has not helped (https://www.nativewind.dev/guides/troubleshooting)

package.json

{
  "name": "betting-app",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "expo": "~47.0.9",
    "expo-status-bar": "~1.4.2",
    "nativewind": "^2.0.11",
    "react": "18.1.0",
    "react-native": "0.70.5"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "tailwindcss": "^3.2.4"
  },
  "private": true
}

Babel.config.js

module.exports = function (api) {
  api.cache(true);
  return {
    plugins: ["nativewind/babel"],
    presets: ["babel-preset-expo"],
  };
};

tailwind.config.js

// tailwind.config.js
module.exports = {
  content: [
    "./screens/**/*.{js,ts,jsx,tsx}",
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  // ...
};


问:
i have 'A RenderFlex overflowed by 99865 pixels on the bottom.' in my drowpdownButton

how to get catagory name to show in dropdown

i have 'A RenderFlex overflowed by 99865 pixels on the bottom.' in my drowpdownButton how do i show the data

```<code>

class Filtering extends StatefulWidget {
  const Filtering({this.itemId});
  final dynamic itemId;
  @override
  State<Filtering> createState() => _FilteringState();
}

class _FilteringState extends State<Filtering> {
  dynamic dropDownItem;
  void initState() {
    onlineShopingProvider dropdownProvider =
        Provider.of(context, listen: false);
    dropDownItem = dropdownProvider.getShopingCatagory.where((element) {
      return element['catagory_id'] == widget.itemId;
    }).toList();
    setState(() {
      dropDownItem = dropDownItem[0];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 20),
      child: Row(
        // ignore: prefer_const_literals_to_create_immutables
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // heading
          const Text(
            'shoping',
            style: TextStyle(fontSize: 30),
          ),

          //dropdown button
          DropdownButton(
            items: <DropdownMenuItem<String>>[
              DropdownMenuItem(
                // ignore: prefer_if_null_operators
                child: dropDownItem[0],
                value: dropDownItem['catagory_name'],
              ),
            ],
            onChanged: ((value) {
              setState(() {
                dropDownItem[value] = dropDownItem['catagory_name'];
              });
            }),
            iconSize: 40,
            elevation: 16,
            dropdownColor: Colors.blue,
            style: const TextStyle(color: Colors.deepPurple),
            underline: Container(
              height: 2,
              color: Colors.deepPurpleAccent,
            ),
          )
        ],
      ),
    );
  }
}
</code>```

and this is my provider page. what should i change in my setState function?
and can someone tell me why in drop downMeanuItem it require index? I'm binger in the field , and I would love if someone could help me in finding any recourses to improve my programming skill

```<code>
class onlineShopingProvider with ChangeNotifier {
final dynamic shopingCatagory = [
 {
   "category_id": 22,
   "category_name": "Jeep",
   "category_image": "https://pngimg.com/uploads/jeep/jeep_PNG95.png"
 },
 {
   "category_id": 24,
   "category_name": "Toyota",
   "category_image":
       "https://www.freepnglogos.com/uploads/toyota-logo-png/toyota-logos-brands-logotypes-0.png"
 },
 {
   "category_id": 23,
   "category_name": "BMW",
   "category_image":
       "https://pngimg.com/uploads/bmw_logo/bmw_logo_PNG19714.png"
 }
];

get getOnlineItem => _onlineitem;
get getShopingCatagory => shopingCatagory;

Filtering(item, item_id) {
 return item.where((element) => element['category_id'] == item_id).toList();
 notifyListeners();
}
}
</code>```

Body:
how to get catagory name to show in dropdown

i have 'A RenderFlex overflowed by 99865 pixels on the bottom.' in my drowpdownButton how do i show the data

class Filtering extends StatefulWidget {
  const Filtering({this.itemId});
  final dynamic itemId;
  @override
  State<Filtering> createState() => _FilteringState();
}

class _FilteringState extends State<Filtering> {
  dynamic dropDownItem;
  void initState() {
    onlineShopingProvider dropdownProvider =
        Provider.of(context, listen: false);
    dropDownItem = dropdownProvider.getShopingCatagory.where((element) {
      return element['catagory_id'] == widget.itemId;
    }).toList();
    setState(() {
      dropDownItem = dropDownItem[0];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 20),
      child: Row(
        // ignore: prefer_const_literals_to_create_immutables
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // heading
          const Text(
            'shoping',
            style: TextStyle(fontSize: 30),
          ),

          //dropdown button
          DropdownButton(
            items: <DropdownMenuItem<String>>[
              DropdownMenuItem(
                // ignore: prefer_if_null_operators
                child: dropDownItem[0],
                value: dropDownItem['catagory_name'],
              ),
            ],
            onChanged: ((value) {
              setState(() {
                dropDownItem[value] = dropDownItem['catagory_name'];
              });
            }),
            iconSize: 40,
            elevation: 16,
            dropdownColor: Colors.blue,
            style: const TextStyle(color: Colors.deepPurple),
            underline: Container(
              height: 2,
              color: Colors.deepPurpleAccent,
            ),
          )
        ],
      ),
    );
  }
}

and this is my provider page. what should i change in my setState function?
and can someone tell me why in drop downMeanuItem it require index? I'm binger in the field , and I would love if someone could help me in finding any recourses to improve my programming skill

class onlineShopingProvider with ChangeNotifier {
final dynamic shopingCatagory = [
 {
   "category_id": 22,
   "category_name": "Jeep",
   "category_image": "https://pngimg.com/uploads/jeep/jeep_PNG95.png"
 },
 {
   "category_id": 24,
   "category_name": "Toyota",
   "category_image":
       "https://www.freepnglogos.com/uploads/toyota-logo-png/toyota-logos-brands-logotypes-0.png"
 },
 {
   "category_id": 23,
   "category_name": "BMW",
   "category_image":
       "https://pngimg.com/uploads/bmw_logo/bmw_logo_PNG19714.png"
 }
];

get getOnlineItem => _onlineitem;
get getShopingCatagory => shopingCatagory;

Filtering(item, item_id) {
 return item.where((element) => element['category_id'] == item_id).toList();
 notifyListeners();
}
}


问:
Enter someone else's branch in a collaborative project on gitHub
Im working with a team in a repository in GitHub (we are many collaborators), but Im always having merge conflicts in my command line in Visual Code every time I finish working and want to push my changes. And recently got into GitHub and saw another member's name in my branch but I don't remember what else the message said- The member said that they were only looking at my commits bit didn't change anything. However, I wonder if that member going into my branch may have causes some sort of problem that I couldn't commit any of my work. Any ideas? Thanks!</p>


问:
pageViewController.view.transform called simultaneously with .setViewControllers causes a visual glitch in the animation
I resumed an old project of mine in which I was trying to achieve a book flipping animation while the book translates on the x axis. This was achieved as explained below.

In viewDidLoad() I declared the pageViewController as follows, with .pageCurl as the transition style:

```<code>    pageController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
    pageController?.setViewControllers([UIViewController()], direction: .forward, animated: true, completion: nil)
</code>```

The spine is set to be .mid in the DataSource protocol, that's the reason of the generic UIViewController().

Then, in viewDidAppear(), I performed both the translation tapping into the .transform property and the flipping animation through .setViewControllers().

```<code>override internal func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
        UIView.animate(withDuration: 0.3, delay: 0, animations: {
            self.pageController?.view.transform = CGAffineTransform(translationX: self.view.bounds.width/4, y: 0)
        }, completion: nil)
        self.pageController?.setViewControllers(self.startingPages, direction: .forward, animated: true, completion: nil)
    }
}
</code>```

Although maybe not pretty, this did the job almost two years ago, so Xcode 12.5, Swift 5.4 and testing on iOS 14.5.
The final effect was this.

Testing again now on iOS 16.1.1, with Xcode 14.2, this is the result.
Apparently the same identical code causes now a visual glitch, as the cover page of the book simply freezes and don't flip/translate. This happens just like 80% of the times, not always, otherwise the animations are fine. Also, occasionally it gives me a crash in the app.

Do anyone knows what's the issue and how to solve this?

Body:
I resumed an old project of mine in which I was trying to achieve a book flipping animation while the book translates on the x axis. This was achieved as explained below.

In viewDidLoad() I declared the pageViewController as follows, with .pageCurl as the transition style:

    pageController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
    pageController?.setViewControllers([UIViewController()], direction: .forward, animated: true, completion: nil)

The spine is set to be .mid in the DataSource protocol, that's the reason of the generic UIViewController().

Then, in viewDidAppear(), I performed both the translation tapping into the .transform property and the flipping animation through .setViewControllers().

override internal func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
        UIView.animate(withDuration: 0.3, delay: 0, animations: {
            self.pageController?.view.transform = CGAffineTransform(translationX: self.view.bounds.width/4, y: 0)
        }, completion: nil)
        self.pageController?.setViewControllers(self.startingPages, direction: .forward, animated: true, completion: nil)
    }
}

Although maybe not pretty, this did the job almost two years ago, so Xcode 12.5, Swift 5.4 and testing on iOS 14.5.
The final effect was this.

Testing again now on iOS 16.1.1, with Xcode 14.2, this is the result.
Apparently the same identical code causes now a visual glitch, as the cover page of the book simply freezes and don't flip/translate. This happens just like 80% of the times, not always, otherwise the animations are fine. Also, occasionally it gives me a crash in the app.

Do anyone knows what's the issue and how to solve this?


问:
Mongoose deleting object ($pull) in Array does not work
I'm trying to delete an object inside an array in my DB using the $pull in Mongoose but does not work.

This is my attempt:

```<code>const listSchema = new Schema({
    name: String,
    items: []
});

const List = mongoose.model("list", listSchema);

const itemDeleted = req.body.checkbox;
//I get here the ID of the object inside the array
const itemListDeleted = req.body.listDeleted;
// Here the name of the object that contains the array
</code>```
```<code>List.findOneAndUpdate({name:itemListDeleted},{$pull:{items:{_id: itemDeleted}}},function (err,foundList) {
        if (foundList){
            res.redirect("/"+ itemListDeleted);
        } else {
            console.log(err);
        }
})
</code>```

I searched for solutions and everybody recommends using $Pull but in my case, it doesn't work. I log the const and all things appear to be right.

Do you have any suggestions?

Body:
I'm trying to delete an object inside an array in my DB using the $pull in Mongoose but does not work.

This is my attempt:

const listSchema = new Schema({
    name: String,
    items: []
});

const List = mongoose.model("list", listSchema);

const itemDeleted = req.body.checkbox;
//I get here the ID of the object inside the array
const itemListDeleted = req.body.listDeleted;
// Here the name of the object that contains the array

List.findOneAndUpdate({name:itemListDeleted},{$pull:{items:{_id: itemDeleted}}},function (err,foundList) {
        if (foundList){
            res.redirect("/"+ itemListDeleted);
        } else {
            console.log(err);
        }
})

I searched for solutions and everybody recommends using $Pull but in my case, it doesn't work. I log the const and all things appear to be right.

Do you have any suggestions?


问:
How to fix "extension has no installation script nor update path" error?
I'm maintaining an old PostgreSQL extension, and trying to release a new version. The test script fails when running CREATE EXTENSION IF NOT EXISTS table_version version '1.10.3';:

ERROR:  extension "table_version" has no installation script nor update path for version "1.10.3"

It is not this issue, because the package (installed successfully in an earlier step in the test script) does contain the relevant /usr/share/postgresql/10/extension/table_version--1.10.3.sql file. I'm stumped for what else could be the issue.

To reproduce:

Run nix-shell --pure --run 'docker build --tag=docker-builder .' on the "master" branch of of linz-software-repository to create the Debian package builder image (log)

Run docker run --env=DRY_RUN=1 --env=GITHUB_REPOSITORY=linz/postgresql-tableversion --env=RUNNER_WORKSPACE="$(dirname "$PWD")" --volume=/var/run/docker.sock:/var/run/docker.sock docker-builder focal jq "$PWD" on the postgresql-tableversion "release-1.10" branch to create the Debian package (log)

Run docker build --build-arg=RELEASE=focal --tag=tester . to create the test runner Docker image (log)

Run docker run --rm --volume="${PWD}/build-area:/packages" tester ./test/ci/package-upgrade.bash 10 to see the error (log).

Trying the last step manually, the Docker container ends up with these files:

```<code>root@939371dd2cf4:/src# ls -1 /usr/share/postgresql/10/extension/table_version*
/usr/share/postgresql/10/extension/table_version--1.10.2--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.2dev--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.3--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.3dev--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.4--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.4--1.10.4next.sql
/usr/share/postgresql/10/extension/table_version--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.4next--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--unpackaged--1.10.4.sql
/usr/share/postgresql/10/extension/table_version.control
</code>```

Possibly related findings:

The locally built package gets its version number from the latest tag, rather than EXTVERSION in the Makefile. But creating the new "1.10.4" tag and pushing it doesn't seem to help in any way.

apt-get --assume-yes install postgresql-10-tableversion does create /usr/share/postgresql/10/extension/table_version--1.10.3.sql, but this file is gone after installing the locally built .deb file.

Body:
I'm maintaining an old PostgreSQL extension, and trying to release a new version. The test script fails when running CREATE EXTENSION IF NOT EXISTS table_version version '1.10.3';:

ERROR:  extension "table_version" has no installation script nor update path for version "1.10.3"

It is not this issue, because the package (installed successfully in an earlier step in the test script) does contain the relevant /usr/share/postgresql/10/extension/table_version--1.10.3.sql file. I'm stumped for what else could be the issue.

To reproduce:

Run nix-shell --pure --run 'docker build --tag=docker-builder .' on the "master" branch of of linz-software-repository to create the Debian package builder image (log)

Run docker run --env=DRY_RUN=1 --env=GITHUB_REPOSITORY=linz/postgresql-tableversion --env=RUNNER_WORKSPACE="$(dirname "$PWD")" --volume=/var/run/docker.sock:/var/run/docker.sock docker-builder focal jq "$PWD" on the postgresql-tableversion "release-1.10" branch to create the Debian package (log)

Run docker build --build-arg=RELEASE=focal --tag=tester . to create the test runner Docker image (log)

Run docker run --rm --volume="${PWD}/build-area:/packages" tester ./test/ci/package-upgrade.bash 10 to see the error (log).

Trying the last step manually, the Docker container ends up with these files:

root@939371dd2cf4:/src# ls -1 /usr/share/postgresql/10/extension/table_version*
/usr/share/postgresql/10/extension/table_version--1.10.2--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.2dev--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.3--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.3dev--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.4--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.4--1.10.4next.sql
/usr/share/postgresql/10/extension/table_version--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--1.10.4next--1.10.4.sql
/usr/share/postgresql/10/extension/table_version--unpackaged--1.10.4.sql
/usr/share/postgresql/10/extension/table_version.control

Possibly related findings:

The locally built package gets its version number from the latest tag, rather than EXTVERSION in the Makefile. But creating the new "1.10.4" tag and pushing it doesn't seem to help in any way.

apt-get --assume-yes install postgresql-10-tableversion does create /usr/share/postgresql/10/extension/table_version--1.10.3.sql, but this file is gone after installing the locally built .deb file.


问:
Unwanted colored borders around Javax.swing Containers
 In the above screenshot we have a JFrame containing A JTabbedPane which (in Tab2) contains a JButton opening a JMenue.

So I want to change the color of these . JFrame worked all good as you see it is now black. And now with the JTabbed pane starts my first issue.

Problem 1: As you see (marked with a 1) the tab1 background color is set but there is this white frame around it is there a way to remove that?

Problem 2: As you see (marked with a 2) a selected tabs background hast this white blueish color ,is there a way to change that .setForeground(Color c) doesn't seem to work.

Next Problem (marked with 3) you see the main body of the JTabbedPane has also a border is there a way to remove that (maybe the same as Problem 1).

Problem 4 and 5 are the borders around the JButton (marked with 4) and the JMenue (marked with 5) is there a way to remove the borders?

I tried .setForeground on the JTabbedPane.


问:
How to run the levenshtein_distance function using the text_preprocessing variable?
I have a program like this:

```<code>$text1 = "Hello, World!";
$text2 = "Levenshtein distance (or edit distance) between two strings";
$preprocessing_text1 = text_preprocessing($text1);

echo "<br>";
$preprocessing_text2 = text_preprocessing($text2);
echo "<br>";
function text_preprocessing($text)
{
     // Remove spaces at the beginning and end of the string
     $text = trim($text);

     // Converts all letters to lowercase
     $text = strtolower($text);

     // Remove punctuation
     $text = preg_replace('/[^a-z\d ]/i', '', $text);
     echo $text; // output: "hello world" & "levenshtein distance or edit distance between two strings"
}

echo levenshtein("hello world", "levenshtein distance or edit distance between two strings");

</code>```

and I want to run the levenshtein function with preprocessing_text1 & preprocessing_text2 variables but how come the result is 0 and not 50.

```<code>echo levenshtein($preprocessing_text1, $preprocessing_text1);
</code>```

Any help would be highly appreciated.

Body:
I have a program like this:

$text1 = "Hello, World!";
$text2 = "Levenshtein distance (or edit distance) between two strings";
$preprocessing_text1 = text_preprocessing($text1);

echo "
";
$preprocessing_text2 = text_preprocessing($text2);
echo "
";
function text_preprocessing($text)
{
     // Remove spaces at the beginning and end of the string
     $text = trim($text);

     // Converts all letters to lowercase
     $text = strtolower($text);

     // Remove punctuation
     $text = preg_replace('/[^a-z\d ]/i', '', $text);
     echo $text; // output: "hello world" & "levenshtein distance or edit distance between two strings"
}

echo levenshtein("hello world", "levenshtein distance or edit distance between two strings");

and I want to run the levenshtein function with preprocessing_text1 & preprocessing_text2 variables but how come the result is 0 and not 50.

echo levenshtein($preprocessing_text1, $preprocessing_text1);

Any help would be highly appreciated.


问:
Check if either virtual or hardware keyboard is being used SwiftUI. Check presence or height
I'm trying to show an extra textfield above my virtual keyboard when it is being used. I want to either check if the keyboard height is above 0 to show this extra textfield or check if there is a hardware keyboard connected to avoid showing the extra textfield.

I tried checking the keyboard height with this:

```<code>class KeyboardHelper: ObservableObject {
    @Published var keyboardHeight: CGFloat = 0

    init() {
        self.listenForKeyboardNotifications()
    }

    public func listenForKeyboardNotifications() {
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification,
                                               object: nil,
                                               queue: .main) { (notification) in
            guard let userInfo = notification.userInfo,
                  let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }

            self.keyboardHeight = keyboardRect.height
        }

        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification,
                                               object: nil,
                                               queue: .main) { (notification) in
            self.keyboardHeight = 0
        }
    }
}
</code>```

But when I started typing the keyboard height gets reset to 0. Also I was unable to type in the extra textfield and this error appeared:

```<code>[SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.
</code>```

Here are some pictures of what I'm trying to accomplish:

This is how it should look without the virtual keyboard and with the hardware keyboard connected:

This is how it should look with the virtual keyboard and extra textfield in the screen

Body:
I'm trying to show an extra textfield above my virtual keyboard when it is being used. I want to either check if the keyboard height is above 0 to show this extra textfield or check if there is a hardware keyboard connected to avoid showing the extra textfield.

I tried checking the keyboard height with this:

class KeyboardHelper: ObservableObject {
    @Published var keyboardHeight: CGFloat = 0

    init() {
        self.listenForKeyboardNotifications()
    }

    public func listenForKeyboardNotifications() {
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification,
                                               object: nil,
                                               queue: .main) { (notification) in
            guard let userInfo = notification.userInfo,
                  let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }

            self.keyboardHeight = keyboardRect.height
        }

        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification,
                                               object: nil,
                                               queue: .main) { (notification) in
            self.keyboardHeight = 0
        }
    }
}

But when I started typing the keyboard height gets reset to 0. Also I was unable to type in the extra textfield and this error appeared:

[SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior.

Here are some pictures of what I'm trying to accomplish:

This is how it should look without the virtual keyboard and with the hardware keyboard connected:

This is how it should look with the virtual keyboard and extra textfield in the screen


问:
Which DNS zone anwsers query for the DNS domain itself?
I am a co-maintainer of a slash-number network, which has a DNS domain sub.dom.tld assigned. The used name server is ISC bind 9. Everything is working as expected:

queries from inside and from outside that network for host.sub.dom.tld return the expected IP address

queries from inside and from outside that network for IP addresses within the network range return the correct FQDN.

I'm asking: which DNS zone would return the IP address for the DNS domain sub.dom.tld itself?

Is it the DNS zone dom.tld, which I do not control. Or is it the DNS zone sub.dom.tld, which I control. In case it is the latter, how would the syntax look like?

It is not clear to me how to specify it. The entries for individual hosts in the forward zone look like host IN A IPv4.


问:
Masking sensitive data in Angular FE with content projection
I'm building a reusable component that will take sensitive data and include a toggle to show/hide that data. Hidden data is replaced with a PrimeNG skeleton. The problem I'm trying to solve is that if the <ng-content> is empty, I'd rather just show a - than the skeleton to prevent having to toggle it, just to find no data.

```<code><ng-container *ngIf="dataIsMasked; then maskData else showData"></ng-container>
   <ng-template #maskData>
       <span class="skeleton-container">
           <p-skeleton></p-skeleton>
       </span>

       <span class="no-data-placeholder"> - </span>
   </ng-template>

   <ng-template #showData>
        <span class="data-mask-container">
            <ng-content></ng-content>
        </span>
   </ng-template>

..code to toggle button & component variable...
</code>```

I'm attempting to use some CSS selectors to determine if the content is empty or not, but on instances where the .data-container is empty, the styles aren't applied to .skeleton-container:

```<code>.data-container:empty + .skeleton-container {
     display: none;
}
</code>```

Body:
I'm building a reusable component that will take sensitive data and include a toggle to show/hide that data. Hidden data is replaced with a PrimeNG skeleton. The problem I'm trying to solve is that if the <ng-content> is empty, I'd rather just show a - than the skeleton to prevent having to toggle it, just to find no data.

<ng-container *ngIf="dataIsMasked; then maskData else showData"></ng-container>
   <ng-template #maskData>

        -
   </ng-template>

   <ng-template #showData>

            <ng-content></ng-content>

   </ng-template>

..code to toggle button & component variable...

I'm attempting to use some CSS selectors to determine if the content is empty or not, but on instances where the .data-container is empty, the styles aren't applied to .skeleton-container:

.data-container:empty + .skeleton-container {
     display: none;
}


问:
Flutter Floor no such column ONLY on some devices
Strange issue I'm facing using the Floor database package with Flutter. On some Android devices (notably Pixel 1) I'm getting this error

```<code>DatabaseException(no such column: true (code 1 SQLITE_ERROR
</code>```

Using this query

```<code>  @Query('SELECT * FROM FlashCard WHERE timeStamp NOT IN (:lastCardTimeStampList) AND showInRecent = true ORDER BY timeStamp DESC LIMIT 20')
  Future<List<FlashCard>> getNextTwentyRecentCards(List<int> lastCardTimeStampList);
</code>```

As mentioned this is working fine generally across iOS devices and most Android, just some Android devices won't play ball. Any suggestions?

My entity

```<code>@entity
class FlashCard {
  @primaryKey
  String id;
  String name;
  Uint8List image;
  double textSize;
  int textColor;
  int cardBackgroundColor;
  String font;
  int timeStamp;
  bool showInRecent;

  FlashCard(
      {required this.id,
      required this.name,
      required this.image,
      required this.textSize,
      required this.textColor,
      required this.cardBackgroundColor,
      required this.font,
      required this.timeStamp,
      required this.showInRecent});
}
</code>```

Body:
Strange issue I'm facing using the Floor database package with Flutter. On some Android devices (notably Pixel 1) I'm getting this error

DatabaseException(no such column: true (code 1 SQLITE_ERROR

Using this query

  @Query('SELECT * FROM FlashCard WHERE timeStamp NOT IN (:lastCardTimeStampList) AND showInRecent = true ORDER BY timeStamp DESC LIMIT 20')
  Future<List<FlashCard>> getNextTwentyRecentCards(List<int> lastCardTimeStampList);

As mentioned this is working fine generally across iOS devices and most Android, just some Android devices won't play ball. Any suggestions?

My entity

@entity
class FlashCard {
  @primaryKey
  String id;
  String name;
  Uint8List image;
  double textSize;
  int textColor;
  int cardBackgroundColor;
  String font;
  int timeStamp;
  bool showInRecent;

  FlashCard(
      {required this.id,
      required this.name,
      required this.image,
      required this.textSize,
      required this.textColor,
      required this.cardBackgroundColor,
      required this.font,
      required this.timeStamp,
      required this.showInRecent});
}


问:
Passing lambda function as Parameter to threading.Thread
Im new to python so forgive me if Im not applying best practices and I welcome any feedback to help doing the code below the python way. I have the following code and the out put is making me very confused and not sure how to fix in order to get the expected output. Im getting the name Sal on both greetings:

```<code>    from time import sleep
    import threading

    def printGreating(get_greeting):
        sleep(5)
        greeting = get_greeting()
        print(greeting)

    def createGreeting(greeting,name):
        return greeting+' '+ name

    nameslist = ["Sam","Sal"]
    threads = []

    for n in nameslist:
        print(n)

        if n == "Sam":

            create_greeting_l = lambda : createGreeting("Hello",n)

        else:

            create_greeting_l = lambda : createGreeting("Greeting",n)

        t = threading.Thread(target=printGreating, args=(create_greeting_l,))

        t.start()

        threads.append(t)

    for t in threads:

        t.join()

print('-------------------Completed--------------')

Expected output:

Sam
Sal
Hello Sam
Greeting Sal
-------------------Completed--------------

What Im getting:
Sam
Sal
Greeting Sal
Hello Sal
</code>```

Expected output:

Sam
Sal
Hello Sam
Greeting Sal

What Im getting:
Sam
Sal
Greeting Sal
Hello Sal

UPDATED Dec 22,2022:

I finally figured out the fix. the name should be passed as parameter to the lambda funntion:

```<code>if n == "Sam":

        create_greeting_l = lambda a : createGreeting("Hello",a)

     else:

        create_greeting_l = lambda a : createGreeting("Greeting",a)

     t = GreeterClass(create_greeting_l,n)
</code>```

Body:
Im new to python so forgive me if Im not applying best practices and I welcome any feedback to help doing the code below the python way. I have the following code and the out put is making me very confused and not sure how to fix in order to get the expected output. Im getting the name Sal on both greetings:

    from time import sleep
    import threading

    def printGreating(get_greeting):
        sleep(5)
        greeting = get_greeting()
        print(greeting)

    def createGreeting(greeting,name):
        return greeting+' '+ name

    nameslist = ["Sam","Sal"]
    threads = []

    for n in nameslist:
        print(n)

        if n == "Sam":

            create_greeting_l = lambda : createGreeting("Hello",n)

        else:

            create_greeting_l = lambda : createGreeting("Greeting",n)

        t = threading.Thread(target=printGreating, args=(create_greeting_l,))

        t.start()

        threads.append(t)

    for t in threads:

        t.join()

print('-------------------Completed--------------')

Expected output:

Sam
Sal
Hello Sam
Greeting Sal
-------------------Completed--------------

What Im getting:
Sam
Sal
Greeting Sal
Hello Sal

Expected output:

Sam
Sal
Hello Sam
Greeting Sal

What Im getting:
Sam
Sal
Greeting Sal
Hello Sal

UPDATED Dec 22,2022:

I finally figured out the fix. the name should be passed as parameter to the lambda funntion:

if n == "Sam":

        create_greeting_l = lambda a : createGreeting("Hello",a)

     else:

        create_greeting_l = lambda a : createGreeting("Greeting",a)

     t = GreeterClass(create_greeting_l,n)


问:
Google Analytics 4 - Measurement Protocol hits not recording
I'm sending events hits to GA using the Measurement Protocol for GA4 but the hits are not getting recorded (they are showing on the GA dashboard even after waiting for more then 24 hours).

The URL I'm sending the POST request to:

https://www.google-analytics.com/mp/collect?measurement_id=G-XXXXXXXXXX&api_secret=XXXXXXXXXXXX

The JSON body:

```<code>{
    "client_id": "XXXXXXX.XXXXXXX",
    "events": [
        {
            "name": "add_to_cart",
            "params": {
                "value": 50,
                "currency": "USD",
                "items": [
                    {
                        "item_id": "ITEM-SKU-001",
                        "item_name": "Product Name",
                        "item_variant": "Product Name",
                        "currency": "USD",
                        "price": "50",
                        "quantity": 1
                    }
                ]
            }
        }
    ]
}
</code>```

The "client_id" is the value of the _ga cookie with "GA1.1." removed.

The above request returns an empty response body and a 204 http status code.

When I send the hit to the debug URL, I get the http status code 200 and the response body as:

```<code>{
    "validationMessages": []
}
</code>```

What am I doing wrong?

Body:
I'm sending events hits to GA using the Measurement Protocol for GA4 but the hits are not getting recorded (they are showing on the GA dashboard even after waiting for more then 24 hours).

The URL I'm sending the POST request to:

https://www.google-analytics.com/mp/collect?measurement_id=G-XXXXXXXXXX&api_secret=XXXXXXXXXXXX

The JSON body:

{
    "client_id": "XXXXXXX.XXXXXXX",
    "events": [
        {
            "name": "add_to_cart",
            "params": {
                "value": 50,
                "currency": "USD",
                "items": [
                    {
                        "item_id": "ITEM-SKU-001",
                        "item_name": "Product Name",
                        "item_variant": "Product Name",
                        "currency": "USD",
                        "price": "50",
                        "quantity": 1
                    }
                ]
            }
        }
    ]
}

The "client_id" is the value of the _ga cookie with "GA1.1." removed.

The above request returns an empty response body and a 204 http status code.

When I send the hit to the debug URL, I get the http status code 200 and the response body as:

{
    "validationMessages": []
}

What am I doing wrong?


问:
GCC ignoring the "access" function-attribute?
I am currently getting into using attributes using c. However when trying to use the "access" attribute for funtions. However when compiling I get a warning saying the attribute is ignored.

This is a minimal example that has this issue arise:

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

__attribute__ ((access (read_only,1))) void  printAll(double * arr,size_t size){
  for(int i=0;i<size;i++) printf("%lf\n", arr[i]);
}

int main(){
  double testArr[]={1,2,3,4,5,6};
  printAll(testArr,6);
}
</code>```

The compiler gives the following warning:

warning: 'access' attribute directive ignored [-Wattributes] __attribute__ ((access (read_only,1))) void  printAll(double * arr,size_t size){

I read about this issue arising with other attributes.
And one solution was that the gcc version may be relevant.
I still have gcc version 8.3.0 from an older installation.

Body:
I am currently getting into using attributes using c. However when trying to use the "access" attribute for funtions. However when compiling I get a warning saying the attribute is ignored.

This is a minimal example that has this issue arise:

#include <stdio.h>

__attribute__ ((access (read_only,1))) void  printAll(double * arr,size_t size){
  for(int i=0;i<size;i++) printf("%lf\n", arr[i]);
}

int main(){
  double testArr[]={1,2,3,4,5,6};
  printAll(testArr,6);
}

The compiler gives the following warning:

warning: 'access' attribute directive ignored [-Wattributes] __attribute__ ((access (read_only,1))) void  printAll(double * arr,size_t size){

I read about this issue arising with other attributes.
And one solution was that the gcc version may be relevant.
I still have gcc version 8.3.0 from an older installation.


问:
How do you handle collisions in PyTMX?
Using the module pytmx I have gotten as far in my map as blitting it to the screen, But now I have a different problem... Collisions. I tried to make a tile class and assign an image and a rect, and then append the rect to the list I was using to check for collisions. But that didn't work. I am able to walk on tiles just not the tiles that actually exist.

My program after running

if it affects anything in any way I am on a mac, and am using DaFluffyPotato's tutorial.

EDIT: It did work it's just I wasn't moving the tiles whith my camera:)

Title: How do you handle collisions in PyTMX?


问:
GDI+ CashedBitmap Transformation not working
I am trying to utilize the Cached Bitmap feature of GDI+ Graphics method.

I initialize the Graphics _drawingSurface[index] with an [index] array referencing various bitmap files without error.

I then assign a CachedBitmap _fastFace[index] with the bitmap in png format without error.

I then perform a ->ScaleTransform and ->RotateTransform with MatrixOrderAppend... also successfully.

I then draw the image original Bitmap without error.. but the Scale and Rotate does not actually effect the image... I feel like I missing something in the relationship of the CachedBitmap Method... and there is no example that I can find.

Can someone look at this and give me a lead where to find a working example?

```<code>//initialize variables: //
    WCHAR* fileTempWide = new WCHAR[260];
    size_t ret = mbstowcs(fileTempWide, path, 260);
    this->_face[index] = std::unique_ptr<Gdiplus::Bitmap>(Gdiplus::Bitmap::FromFile(fileTempWide));
    status = this->_face[index].get()->GetLastStatus();

</code>```

// status 0 = success

```<code>// Associate the image with a Graphics drawing surface and cache it
    this->_drawingSurface[index] = std::unique_ptr<Gdiplus::Graphics>(Gdiplus::Graphics::FromImage(this->_face[index].get()));
    this->_fastFace[index] = std::unique_ptr<Gdiplus::CachedBitmap>(
        new Gdiplus::CachedBitmap(this->_face[index].get(), this->_graphics)
    );

    // ensure cached image was intiialized properly
    status = this->_fastFace[index]->GetLastStatus();
</code>```

// status 0 = success

```<code>// NOT WORKING !!
    // Scale
    status = this->_drawingSurface[faceIndex]->ScaleTransform(horizontalScalingFactor, verticalScalingFactor, (Gdiplus::MatrixOrder) 0 );
    // Rotate
    float angle = this->GetRotation(); // command to calculate rotation in degress.
    status = this->_drawingSurface[faceIndex]->RotateTransform(angle, (Gdiplus::MatrixOrder) 0 );

    int realX = (int)((float)x * horizontalScalingFactor * char_scale_x);
    int realY = (int)((float)y * verticalScalingFactor * char_scale_y);

    status = this->_drawingSurface[faceIndex]->DrawImage(this->_face[faceIndex].get(), realX, realY);

// status 0 = success

    status = this->_graphics->DrawCachedBitmap(this->_fastFace[faceIndex].get(), realX, realY);

// status 0 = success
</code>```

Body:
I am trying to utilize the Cached Bitmap feature of GDI+ Graphics method.

I initialize the Graphics _drawingSurface[index] with an [index] array referencing various bitmap files without error.

I then assign a CachedBitmap _fastFace[index] with the bitmap in png format without error.

I then perform a ->ScaleTransform and ->RotateTransform with MatrixOrderAppend... also successfully.

I then draw the image original Bitmap without error.. but the Scale and Rotate does not actually effect the image... I feel like I missing something in the relationship of the CachedBitmap Method... and there is no example that I can find.

Can someone look at this and give me a lead where to find a working example?

//initialize variables: //
    WCHAR* fileTempWide = new WCHAR[260];
    size_t ret = mbstowcs(fileTempWide, path, 260);
    this->_face[index] = std::unique_ptr<Gdiplus::Bitmap>(Gdiplus::Bitmap::FromFile(fileTempWide));
    status = this->_face[index].get()->GetLastStatus();

// status 0 = success

// Associate the image with a Graphics drawing surface and cache it
    this->_drawingSurface[index] = std::unique_ptr<Gdiplus::Graphics>(Gdiplus::Graphics::FromImage(this->_face[index].get()));
    this->_fastFace[index] = std::unique_ptr<Gdiplus::CachedBitmap>(
        new Gdiplus::CachedBitmap(this->_face[index].get(), this->_graphics)
    );

    // ensure cached image was intiialized properly
    status = this->_fastFace[index]->GetLastStatus();

// status 0 = success

// NOT WORKING !!
    // Scale
    status = this->_drawingSurface[faceIndex]->ScaleTransform(horizontalScalingFactor, verticalScalingFactor, (Gdiplus::MatrixOrder) 0 );
    // Rotate
    float angle = this->GetRotation(); // command to calculate rotation in degress.
    status = this->_drawingSurface[faceIndex]->RotateTransform(angle, (Gdiplus::MatrixOrder) 0 );

    int realX = (int)((float)x * horizontalScalingFactor * char_scale_x);
    int realY = (int)((float)y * verticalScalingFactor * char_scale_y);

    status = this->_drawingSurface[faceIndex]->DrawImage(this->_face[faceIndex].get(), realX, realY);

// status 0 = success

    status = this->_graphics->DrawCachedBitmap(this->_fastFace[faceIndex].get(), realX, realY);

// status 0 = success


问:
What is the cause of the low CPU utilization in rllib PPO? What does 'cpu_util_percent' measure?
I implement multiagent ppo in rllib with a custom environment, it learns and works well except for the speed performance. I wonder if an underutilized CPU may cause the issue, so I want to know what ray/tune/perf/cpu_util_percent measures. Does it measure only the rollout workers, or is averaged over the learner? And what may be the cause? (All my runs give average of 13% CPU usage.)

```<code>run on gcp
ray 2.0
python3.9
torch1.12
head: n1-standard-8 with 1 v100 gpu
2 workers: c2-standard-60

num_workers: 120  # this worker != machine, num_workers = num_rollout_workers
num_envs_per_worker: 1
num_cpus_for_driver: 8
num_gpus: 1
num_cpus_per_worker: 1
num_gpus_per_worker: 0
train_batch_size: 12000
sgd_minibatch_size: 3000
</code>```

I tried smaller batch size=4096 and smaller number of workers=10, and larger batch_size=480000, all resulted 10~20% CPU usage.

I cannot share the code.

Body:
I implement multiagent ppo in rllib with a custom environment, it learns and works well except for the speed performance. I wonder if an underutilized CPU may cause the issue, so I want to know what ray/tune/perf/cpu_util_percent measures. Does it measure only the rollout workers, or is averaged over the learner? And what may be the cause? (All my runs give average of 13% CPU usage.)

run on gcp
ray 2.0
python3.9
torch1.12
head: n1-standard-8 with 1 v100 gpu
2 workers: c2-standard-60

num_workers: 120  # this worker != machine, num_workers = num_rollout_workers
num_envs_per_worker: 1
num_cpus_for_driver: 8
num_gpus: 1
num_cpus_per_worker: 1
num_gpus_per_worker: 0
train_batch_size: 12000
sgd_minibatch_size: 3000

I tried smaller batch size=4096 and smaller number of workers=10, and larger batch_size=480000, all resulted 10~20% CPU usage.

I cannot share the code.


问:
TSQL Lock behaviour on Index Creation/Partition Switch
I currently have the use case of inserting lots of Data (3.5Mio Rows, somewhere around 200GB) into multiple Staging Tables and then switching them into the destination-Tables. Now, becaufe of the amount of Data, we discovered that it would be faster to insert the data into an empty heap-table, then creating the columnstore index so the structure is identical to the destination table, and then switching - all within one transaction.
All the Tables are in the same Database, but they do not depend on each other, so the best-case would be to fill table A-Stage and B-Stage at the same time, create the corresponding indices on them at the same time, and then switching them at the same time.
Obviously, with Creating Indices and Switching Partitions, there are plenty of locks involved. Now i was curious whether those locks can cause a deadlock at any point, especially when it comes to sys-Tables.
All Tables involved will get a SCH-M lock, and certain sys Tables will also get locked, but from what i can see, they get locked on PAGE/KEY/EXTENT level.

Now i guess my Question is:
Are the sys-Tables and other structures i might miss stored in a way that i can alter indices/partitions without running into locks, as long as those are different tables/objects that do not depend on each other (no Foreign Keys or anything for example) or will i eventually run into a scenario where Table B has to wait for Table A to finish before even starting, or worse, a deadlock?

Thanks in advance!

Tried Creating a Clustered Columnstore Index/Switching Partitons and saw that certain sys-Objects couldn´t be accessed, wondered whether this will cause locks in the future or if the locks for different objects will always work out


问:
My loop structure isn't working (while wend in VBA for excel)
I am writing a code in VBA where I'm trying to fill some cells with a formula while the cell right next to it is different from "". However, my loop never ends and when I interrupt it, it shows me that it's running (or stucked) at the addition of the iterator (sorry for the bad english).

Here's what I wrote so far:

```<code>While Cells(i, 4) <> ""
    Cells(i, 5).FormulaR1C1 = "=IFERROR(IF(RC[-3]=R[-1]C[-3],"""",IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3],RC[-3]=R[3]C[-3],RC[-3]=R[4]C[-3],RC[-3]=R[5]C[-3],RC[-3]=R[6]C[-3]),SUMPRODUCT(RC[-2]:R[4]C[-2],RC[-1]:R[6]C[-1])/SUM(RC[-2]:R[6]C[-2]),IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3],RC[-3]=R[3]C[-3],RC[-3]=R[4]C[-3],RC[-3]=R[5]C[-3]),SUMPRODUCT(RC[-2]:R[4]C[-2],RC[-1]:R[5]C[-1])/SUM(RC[-2]:R[5]C" & _
    "[-2]),IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3],RC[-3]=R[3]C[-3],RC[-3]=R[4]C[-3]),SUMPRODUCT(RC[-2]:R[4]C[-2],RC[-1]:R[4]C[-1])/SUM(RC[-2]:R[4]C[-2]),IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3],RC[-3]=R[3]C[-3]),SUMPRODUCT(RC[-2]:R[3]C[-2],RC[-1]:R[3]C[-1])/SUM(RC[-2]:R[3]C[-2]),IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3]),SUMPRODUCT(RC[-2]:R[2]C[-2],RC[-1]:R[2]C[-1])/SUM" & _
    "(RC[-2]:R[2]C[-2]),IF(RC[-3]=R[1]C[-3],SUMPRODUCT(RC[-2]:R[1]C[-2],RC[-1]:R[1]C[-1])/SUM(RC[-2]:R[1]C[-2]),RC[-1]))))))),"""")" & _
    ""
    i = i + 1
Wend
</code>```

The formula is working and I am getting the result I expected. However, the application never ends running until e press esc twice. Then when I debug it, the application shows me the "i = i + 1" in yellow.

How can I fix it?

Body:
I am writing a code in VBA where I'm trying to fill some cells with a formula while the cell right next to it is different from "". However, my loop never ends and when I interrupt it, it shows me that it's running (or stucked) at the addition of the iterator (sorry for the bad english).

Here's what I wrote so far:

While Cells(i, 4) <> ""
    Cells(i, 5).FormulaR1C1 = "=IFERROR(IF(RC[-3]=R[-1]C[-3],"""",IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3],RC[-3]=R[3]C[-3],RC[-3]=R[4]C[-3],RC[-3]=R[5]C[-3],RC[-3]=R[6]C[-3]),SUMPRODUCT(RC[-2]:R[4]C[-2],RC[-1]:R[6]C[-1])/SUM(RC[-2]:R[6]C[-2]),IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3],RC[-3]=R[3]C[-3],RC[-3]=R[4]C[-3],RC[-3]=R[5]C[-3]),SUMPRODUCT(RC[-2]:R[4]C[-2],RC[-1]:R[5]C[-1])/SUM(RC[-2]:R[5]C" & _
    "[-2]),IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3],RC[-3]=R[3]C[-3],RC[-3]=R[4]C[-3]),SUMPRODUCT(RC[-2]:R[4]C[-2],RC[-1]:R[4]C[-1])/SUM(RC[-2]:R[4]C[-2]),IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3],RC[-3]=R[3]C[-3]),SUMPRODUCT(RC[-2]:R[3]C[-2],RC[-1]:R[3]C[-1])/SUM(RC[-2]:R[3]C[-2]),IF(AND(RC[-3]=R[1]C[-3],RC[-3]=R[2]C[-3]),SUMPRODUCT(RC[-2]:R[2]C[-2],RC[-1]:R[2]C[-1])/SUM" & _
    "(RC[-2]:R[2]C[-2]),IF(RC[-3]=R[1]C[-3],SUMPRODUCT(RC[-2]:R[1]C[-2],RC[-1]:R[1]C[-1])/SUM(RC[-2]:R[1]C[-2]),RC[-1]))))))),"""")" & _
    ""
    i = i + 1
Wend

The formula is working and I am getting the result I expected. However, the application never ends running until e press esc twice. Then when I debug it, the application shows me the "i = i + 1" in yellow.

How can I fix it?


问:
PySerial - readline stops or repeats
I wrote simple code to read data from sensor it works but it always stops or repeats the last value.

```<code>import serial
import codecs
import time

com = serial.Serial(port='COM5', baudrate =115200,bytesize=8,parity=serial.PARITY_NONE,
                    stopbits=serial.STOPBITS_ONE,rtscts =True, timeout=0.1)

while True:
    if com.in_waiting:
        data = com.readline()
        print(data.decode())
        time.sleep(2)
</code>```

Output:

```<code>+UUDF:6C1DEBA413DF,-30,-90,50,0,39,"6C1DEBA0999A","",4125
+UUDF:6C1DEBA413DF,-30,-90,50,0,39,"6C1DEBA0999A","",4128
</code>```

Works <80 times or repeats last row.

I would like to get an infinite loop reading.

Update:

From logs:

```<code>INFO:root:b'+UUDF:6C1DEBA413DF,-34,90,-90,0,39,"6C1DEBA0999A","",4374\r\n'
INFO:root:b'\r\n'
INFO:root:b'+UUDF:6C1DEBA413DF,-42,90,-90,0,37,"6C1DEBA0999A","",4402\r\n'
</code>```

So script stopped when missing that: b'\r\n' beetween received information.

Title: PySerial - readline stops or repeats

Body:
I wrote simple code to read data from sensor it works but it always stops or repeats the last value.

import serial
import codecs
import time

com = serial.Serial(port='COM5', baudrate =115200,bytesize=8,parity=serial.PARITY_NONE,
                    stopbits=serial.STOPBITS_ONE,rtscts =True, timeout=0.1)

while True:
    if com.in_waiting:
        data = com.readline()
        print(data.decode())
        time.sleep(2)

Output:

+UUDF:6C1DEBA413DF,-30,-90,50,0,39,"6C1DEBA0999A","",4125
+UUDF:6C1DEBA413DF,-30,-90,50,0,39,"6C1DEBA0999A","",4128

Works <80 times or repeats last row.

I would like to get an infinite loop reading.

Update:

From logs:

INFO:root:b'+UUDF:6C1DEBA413DF,-34,90,-90,0,39,"6C1DEBA0999A","",4374\r\n'
INFO:root:b'\r\n'
INFO:root:b'+UUDF:6C1DEBA413DF,-42,90,-90,0,37,"6C1DEBA0999A","",4402\r\n'

So script stopped when missing that: b'\r\n' beetween received information.


问:
Export Kubernetes pods statistics dynamically using Azuredevops pipelines
I have an azuredevops yaml bash task to query all the pods in my aks cluster and from there I used jq filter to query the pods resource statics etc.. as given below.

```<code>kubectl get pods -A -o json >all.json

jq -r '["Namespace,NodeName, PodName, ContainerName","MemoryRequest","MemoryLimit","CPURequest","CPULimit"], (.items[] | [.metadata.namespace , .spec.nodeName , .metadata.name ] + (.spec.containers[] | [.name, .resources.requests.memory, .resources.limits.memory, .resources.requests.cpu, .resources.limits.cpu]) ) | @csv' all.json
</code>```

In addition to the above, I would like to get below details as well

in addition to the Resource request &limit , how I can get and export all pods actual usage of memory and cpu (something like from kubectl top command)

Our release pipelines have version assigned to each releases as part of the pipeline and corresponding version will be appended to the image name of the each kubernetes deployments. So can we dynamically fetch this appended version from the kubernetes deployments( for example, each deployments image will be appended like myregistry/myrepo/myapp1:v1.0.318, from this image name if we are able to get the "v1.0.318" , its the app version). Is this possible to fetch the appversion from all kubernetes deployments and output as above step?

Is it possible to dynamically upload above exported values to Azure wiki in a readable table format and over mail using azuredevops tasks?

Body:
I have an azuredevops yaml bash task to query all the pods in my aks cluster and from there I used jq filter to query the pods resource statics etc.. as given below.

kubectl get pods -A -o json >all.json

jq -r '["Namespace,NodeName, PodName, ContainerName","MemoryRequest","MemoryLimit","CPURequest","CPULimit"], (.items[] | [.metadata.namespace , .spec.nodeName , .metadata.name ] + (.spec.containers[] | [.name, .resources.requests.memory, .resources.limits.memory, .resources.requests.cpu, .resources.limits.cpu]) ) | @csv' all.json

In addition to the above, I would like to get below details as well

in addition to the Resource request &limit , how I can get and export all pods actual usage of memory and cpu (something like from kubectl top command)

Our release pipelines have version assigned to each releases as part of the pipeline and corresponding version will be appended to the image name of the each kubernetes deployments. So can we dynamically fetch this appended version from the kubernetes deployments( for example, each deployments image will be appended like myregistry/myrepo/myapp1:v1.0.318, from this image name if we are able to get the "v1.0.318" , its the app version). Is this possible to fetch the appversion from all kubernetes deployments and output as above step?

Is it possible to dynamically upload above exported values to Azure wiki in a readable table format and over mail using azuredevops tasks?


问:
Excel VBA Open Macro
The Excel VBA code below executes when I open my Excel document on my computer. However, when someone else opens my document, the code does not execute (VBA macros are enabled). I am also having the same issue with the custom ribbon I designed for the Excel document. When I open my Excel document on my computer the custom ribbon appears. However, when someone else opens my document, the custom ribbon does not appear.

```<code>Private Sub Workbook_Open()
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .WindowState = xlNormal
        .CommandBars("Full Screen").Visible = False
        .CommandBars("Worksheet Menu Bar").Enabled = False
        .DisplayStatusBar = False
        .DisplayFormulaBar = False
        .Width = 845
        .Height = 408
    End With
    With ActiveWindow
        .DisplayRuler = False
        .DisplayHeadings = False
    End With
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
    End With
End Sub
</code>```

Could someone please explain to me how I could fix this ongoing issue. I don't understand why the Excel workbook formating is different between my computer and my colleagues computer.

Thank you!

Title: Excel VBA Open Macro

Body:
The Excel VBA code below executes when I open my Excel document on my computer. However, when someone else opens my document, the code does not execute (VBA macros are enabled). I am also having the same issue with the custom ribbon I designed for the Excel document. When I open my Excel document on my computer the custom ribbon appears. However, when someone else opens my document, the custom ribbon does not appear.

Private Sub Workbook_Open()
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .WindowState = xlNormal
        .CommandBars("Full Screen").Visible = False
        .CommandBars("Worksheet Menu Bar").Enabled = False
        .DisplayStatusBar = False
        .DisplayFormulaBar = False
        .Width = 845
        .Height = 408
    End With
    With ActiveWindow
        .DisplayRuler = False
        .DisplayHeadings = False
    End With
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
    End With
End Sub

Could someone please explain to me how I could fix this ongoing issue. I don't understand why the Excel workbook formating is different between my computer and my colleagues computer.

Thank you!


问:
How to change AndroidManifest during build in Xamarin?
Is there a way to change generated AndroidManifest during the build in Xamarin?

Generated manifest in directory in \obj\Release\120\android has /service android:name="crc6494e14b9856016c30.PNFirebaseMessagingService"/ and I nned to add android:exported="true" property to after the file is generated before it is included in build.

I cannot upgrade the dll with PNFirebaseMessagingService to never version, where the exported flag is set correctly :-(
Thanks for any ideas.

I tried to add /service android:name="crc6494e14b9856016c30.PNFirebaseMessagingService" android:exported="true"/ to the Properties/AndroidManifest but i got error APT2263: unexpected element service found in manifest.


问:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 7 supplied.?
my error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 7 supplied.?</p>
```<code>cursor.execute(f"SELECT player, invites FROM join WHERE server = {member.guild.id} AND spieler = {member.id}")
invites = cursor.fetchone()

cursor.execute(f"SELECT leaves FROM invite_ge WHERE spieler = {invites[0]} AND invite = ?", (invites [1]))
</code>```

Body:
my error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 7 supplied.?

cursor.execute(f"SELECT player, invites FROM join WHERE server = {member.guild.id} AND spieler = {member.id}")
invites = cursor.fetchone()

cursor.execute(f"SELECT leaves FROM invite_ge WHERE spieler = {invites[0]} AND invite = ?", (invites [1]))


问:
Ansible: How to move on from task if the task has no return value
I have an ansible job that looks something like this:

```<code>- name: Start Server
  shell: |
    cd /home/ubuntu/ &&
    chmod +x main
    ./main -- start
</code>```

The executable starts a golang server but doesn't return anything because it's just listening for requests (it does print out "Server is starting on port 3000..."). What is the best way to tell ansible that it's ok to pass this task so I can move on with other tasks in my pipeline?

Body:
I have an ansible job that looks something like this:

- name: Start Server
  shell: |
    cd /home/ubuntu/ &&
    chmod +x main
    ./main -- start

The executable starts a golang server but doesn't return anything because it's just listening for requests (it does print out "Server is starting on port 3000..."). What is the best way to tell ansible that it's ok to pass this task so I can move on with other tasks in my pipeline?


问:
Reading names from a file, put in list — how can I update the list without restarting script?
I need some help with Python (3).

users.txt is a list of usernames that are fetched from a website, each on a separate line. In my code, the first block reads users.txt, adding it to the users variable with the newlines removed, as a list.

The write_to_users_add() function appends what’s in users to users.txt.

The last part is used later in the code to append new users to usersand append them to the users.txt file.

My problem is that when a new user is added to users and users.txt, the first block doesn’t re-read users.txt and add any new usernames to the users variable. It also duplicates the entire text file because the variable already has the names in it.

I’ve tried using an async function, but I couldn’t figure out how to achieve it as I’m not that familiar with asynchronous functions in Python. I also tried a few different things, such as making the first block a function and calling it in the last code block; as well as just two variables—users and users_add, and that solves the duplication issue but not the other issue of the variable not recognizing new names.

TL;DR: Script reads users.txt, adds names to users var. I later append new names to users and then to the txt file. How can I keep the users var updated with new users without restarting the script and without the names in users.txt duplicating? If anybody here could offer me some help with this problem, I would be very grateful!

# 1. Read users.txt
if os.path.isfile('users.txt'):
    with open('users.txt', 'r') as \
            file:
        users = [line.rstrip('\n') for line in file]

# 2. Function for writing to users.txt
def write_to_users():
    try:
        with open('users.txt', 'a') \
                as file:
            for item in users:
                file.write('{}\n'.format(item))
    except FileNotFoundError:
        print('Current path:', os.getcwd())
        print('Isdir reports:', os.path.isdir(os.getcwd()))
        print('Isfile reports:', os.path.isfile(
            'users.txt'))
        raise
```
<p> </p>
<hr />
<p> </p>
<pre class="lang-py prettyprint-override"><code>users.append(author)
write_to_users()
time.sleep(1)
</code>```

Body:
I need some help with Python (3).

users.txt is a list of usernames that are fetched from a website, each on a separate line. In my code, the first block reads users.txt, adding it to the users variable with the newlines removed, as a list.

The write_to_users_add() function appends what’s in users to users.txt.

The last part is used later in the code to append new users to usersand append them to the users.txt file.

My problem is that when a new user is added to users and users.txt, the first block doesn’t re-read users.txt and add any new usernames to the users variable. It also duplicates the entire text file because the variable already has the names in it.

I’ve tried using an async function, but I couldn’t figure out how to achieve it as I’m not that familiar with asynchronous functions in Python. I also tried a few different things, such as making the first block a function and calling it in the last code block; as well as just two variables—users and users_add, and that solves the duplication issue but not the other issue of the variable not recognizing new names.

TL;DR: Script reads users.txt, adds names to users var. I later append new names to users and then to the txt file. How can I keep the users var updated with new users without restarting the script and without the names in users.txt duplicating? If anybody here could offer me some help with this problem, I would be very grateful!

# 1. Read users.txt
if os.path.isfile('users.txt'):
    with open('users.txt', 'r') as \
            file:
        users = [line.rstrip('\n') for line in file]

# 2. Function for writing to users.txt
def write_to_users():
    try:
        with open('users.txt', 'a') \
                as file:
            for item in users:
                file.write('{}\n'.format(item))
    except FileNotFoundError:
        print('Current path:', os.getcwd())
        print('Isdir reports:', os.path.isdir(os.getcwd()))
        print('Isfile reports:', os.path.isfile(
            'users.txt'))
        raise

users.append(author)
write_to_users()
time.sleep(1)


问:
Job DSL how to configure "Deploy to Container" plugin in Jobs groovy script?
So I want to use the "Deploy to Container" plugin in Jenkins and dynamically configure it using a Job DSL groovy script to deploy to our Tomcat application servers. So far, I can't seem to find out how to do it. I can see docs for "Deploy to WebLogic", which is similar, but not "Deploy to Container". Anyone else doing this? Am I the only one?

Here's the XMl from the config.xml that I need to model that I generated using the Jenkins web interface for "Deploy to Container". Not sure how to do it using configure either:

```<code><hudson.plugins.deploy.DeployPublisher plugin="deploy@1.16">
  <adapters>
    <hudson.plugins.deploy.tomcat.Tomcat6xAdapter>
      <credentialsId>jenkinsTomcat</credentialsId>
      <url>http://webserv02v.idc.vpn.freightgate.com:8080/</url>
      <path></path>
    </hudson.plugins.deploy.tomcat.Tomcat6xAdapter>
    <hudson.plugins.deploy.tomcat.Tomcat6xAdapter>
      <credentialsId>jenkinsTomcat</credentialsId>
      <url>http://webserv02v.idc.vpn.freightgate.com:8081</url>
      <path></path>
    </hudson.plugins.deploy.tomcat.Tomcat6xAdapter>
  </adapters>
  <contextPath>scheduler</contextPath>
  <war>scheduler_${BUILD_TAG_NUMBER}_live.war</war>
  <onFailure>false</onFailure>
</hudson.plugins.deploy.DeployPublisher>
</code>```

Body:
So I want to use the "Deploy to Container" plugin in Jenkins and dynamically configure it using a Job DSL groovy script to deploy to our Tomcat application servers. So far, I can't seem to find out how to do it. I can see docs for "Deploy to WebLogic", which is similar, but not "Deploy to Container". Anyone else doing this? Am I the only one?

Here's the XMl from the config.xml that I need to model that I generated using the Jenkins web interface for "Deploy to Container". Not sure how to do it using configure either:

<hudson.plugins.deploy.DeployPublisher plugin="deploy@1.16">
  <adapters>
    <hudson.plugins.deploy.tomcat.Tomcat6xAdapter>
      <credentialsId>jenkinsTomcat</credentialsId>
      <url>http://webserv02v.idc.vpn.freightgate.com:8080/</url>
      <path></path>
    </hudson.plugins.deploy.tomcat.Tomcat6xAdapter>
    <hudson.plugins.deploy.tomcat.Tomcat6xAdapter>
      <credentialsId>jenkinsTomcat</credentialsId>
      <url>http://webserv02v.idc.vpn.freightgate.com:8081</url>
      <path></path>
    </hudson.plugins.deploy.tomcat.Tomcat6xAdapter>
  </adapters>
  <contextPath>scheduler</contextPath>
  <war>scheduler_${BUILD_TAG_NUMBER}_live.war</war>
  <onFailure>false</onFailure>
</hudson.plugins.deploy.DeployPublisher>


问:
Can I use a wrangled dataframe from one output in an RShiny server to continue wrangling in another?
I have multiple tabs (one for uploading files, and many others that show table and plot outputs). Every tab uses the same base dataframe. That base dataframe is influenced by the user input in the UI on the upload tab. Then, each output (tables and plots) is individually manipulated by the user in different tabs to change data displayed, types of plots, etc.

This is my first time building an RShiny app. The fileInput reactives directly influence the base dataframe, and I get errors if I try and do the data-wrangling with these objects outside of an output in the server. Because of this the build process has become cumbersome since all changes I make to the base dataframe in my working output also need to be copied into all others in the server.

Is there a better way to do this?

I have tried to use renderTable to export the wrangled dataframe into the UI and then use it as an input for the table and plot outputs on the server side, but that just caused more problems than it solved.

I apologize I do not have any code to show. My code is long (as a result of this problem), untidy (as a result of me), and will just take up too much space and offer no helpful context.

Thank you in advance!


问:
How do I decline observed call with CallKit?
I'm completely new to Swift programming and I don't know how to make this work.
Basically I have and iOS app which observes incoming phone calls and declines it automatically if the caller number is equal to a user defined number to decline, without showing user any notification (this app is only for my private use).

Currently I have this code which observes incoming call. It works like a charm but I don't know how to make it decline the call (for now all phone numbers).

```<code>import CallKit

class CallTest: NSObject, CXCallObserverDelegate, ObservableObject {
    @Published var incomingCallNumber: String?

    let callObserver = CXCallObserver()

    override init() {
        super.init()

        callObserver.setDelegate(self, queue: nil)
    }

    func callObserver(_ callObserver: CXCallObserver, callChanged call: CXCall) {
        if (call.isOutgoing == false && call.hasConnected == false) {
            print("Incoming call")
        }
    }
}
</code>```

I've tried to decline incoming call like this.

```<code>import CallKit

class CallTest: NSObject, CXCallObserverDelegate, ObservableObject {
    @Published var incomingCallNumber: String?

    let callObserver = CXCallObserver()

    override init() {
        super.init()

        callObserver.setDelegate(self, queue: nil)
    }

    func callObserver(_ callObserver: CXCallObserver, callChanged call: CXCall) {
        if (call.isOutgoing == false && call.hasConnected == false) {
            print("Incoming call")
let callController = CXCallController()
            let endCallAction = CXEndCallAction(call: call.uuid)
            let transaction = CXTransaction(action: endCallAction)

            callController.request(transaction) { error in
                if let error = error {
                    print("Error declining call: \(error)")
                } else {
                    print("Call declined successfully")
                }
            }
        }
    }
}

</code>```

But I keep getting error:

Error Domain=com.apple.CallKit.error.requesttransaction Code=2 "(null)"

Which means 'unknownCallProvider', but I don't know how to set provider for this.

Body:
I'm completely new to Swift programming and I don't know how to make this work.
Basically I have and iOS app which observes incoming phone calls and declines it automatically if the caller number is equal to a user defined number to decline, without showing user any notification (this app is only for my private use).

Currently I have this code which observes incoming call. It works like a charm but I don't know how to make it decline the call (for now all phone numbers).

import CallKit

class CallTest: NSObject, CXCallObserverDelegate, ObservableObject {
    @Published var incomingCallNumber: String?

    let callObserver = CXCallObserver()

    override init() {
        super.init()

        callObserver.setDelegate(self, queue: nil)
    }

    func callObserver(_ callObserver: CXCallObserver, callChanged call: CXCall) {
        if (call.isOutgoing == false && call.hasConnected == false) {
            print("Incoming call")
        }
    }
}

I've tried to decline incoming call like this.

import CallKit

class CallTest: NSObject, CXCallObserverDelegate, ObservableObject {
    @Published var incomingCallNumber: String?

    let callObserver = CXCallObserver()

    override init() {
        super.init()

        callObserver.setDelegate(self, queue: nil)
    }

    func callObserver(_ callObserver: CXCallObserver, callChanged call: CXCall) {
        if (call.isOutgoing == false && call.hasConnected == false) {
            print("Incoming call")
let callController = CXCallController()
            let endCallAction = CXEndCallAction(call: call.uuid)
            let transaction = CXTransaction(action: endCallAction)

            callController.request(transaction) { error in
                if let error = error {
                    print("Error declining call: \(error)")
                } else {
                    print("Call declined successfully")
                }
            }
        }
    }
}

But I keep getting error:

Error Domain=com.apple.CallKit.error.requesttransaction Code=2 "(null)"

Which means 'unknownCallProvider', but I don't know how to set provider for this.


问:
How to refactor this ScopeType in TypeScript?
I asked How to resolve Type 'K' cannot be used to index type 'X' in TypeScript? and am wanting to isolate a smaller portion of that problem I'm facing to figure out how to better structure the ScopeType. I have this TypeScript playground demonstrating the full situation.

```<code>export enum Scope {
  Form = "form",
  Nest = "nest",
}

export type ScopeKeyListType<T extends ScopeType<Scope>> =
  T["parent"] extends ScopeType<Scope>
    ? (keyof T["data"] & string) | ScopeKeyListType<T["parent"]>
    : keyof T["data"] & string;

export type ScopeNestDataType = {
  index: number;
  nest: {
    foo: string;
    bar: boolean;
  };
};

export type ScopeFormDataType = {
  hello: string;
  world: number;
};

export type ScopeTableType = {
  form: ScopeFormDataType;
  nest: ScopeNestDataType;
};

export type ScopeType<
  A extends Scope,
  B extends ScopeType<Scope> | unknown = unknown
> = {
  data: ScopeTableType[A];
  like: A;
  parent?: B;
};

export type ScopeValueType<
  T extends ScopeType<Scope>,
  K extends string
> = T["data"] extends { [key in K]: unknown }
  ? T["data"][K]
  : T["parent"] extends ScopeType<Scope>
  ? ScopeValueType<T["parent"], K>
  : never;

export function setPropertyValueOnScope<
  S extends ScopeType<Scope>,
  K extends ScopeKeyListType<S>
>(scope: S, property: K, value: ScopeValueType<S, K>): void {
  if (property in scope.data) {
    scope.data[property] = value;
  } else if (scope.parent) {
    setPropertyValueOnScope(scope.parent, property, value);
  } else {
    throw new Error(`Property not defined on scope`);
  }
}
</code>```

How should I organize/structure the ScopeType so it can handle my situations? Should I get rid of the generics on it and have it be a simple type? If so, how should I specify the type of the scope.data attribute? I have potentially 30 different types for the data property, which means generically there are at least going to be 30 different "scope" types. Basically I am typing the "lexical scope" in every different context in which it exists. Should I just do something like this?

```<code>export type ScopeDataType =
  | ScopeDataDeckType
  | ScopeDataDeckTermType
  | ScopeDataDeckFaceType
  | ScopeDataLoadType
  | ScopeDataLoadTakeType
  | ScopeDataLoadTakeSaveType
  | ScopeDataBearType
  | ScopeDataTreeType
  | ScopeDataTakeType
  | ScopeDataLikeType
  | ScopeDataFormType
  | ScopeDataTaskType
  | ScopeDataBindType
  | ScopeDataTaskFlowType
  | ScopeDataReadType
  | ScopeDataCordType
  | ScopeDataMarkType
  | ScopeDataBondType
  | ScopeDataSuitType
  | ScopeDataSuitTaskType
  | ScopeDataHostType
  | ScopeDataFaceType
  | ScopeDataTestType
  | ScopeDataHookType
  | ScopeDataWearType
  | ScopeDataHoldType
  | ScopeDataSeekType
  | ScopeDataZoneType
  | ScopeDataZoneToolType
  | ScopeDataTermType
  | ScopeDataDeckCardType
  | ScopeDataCodeCardType
  | ScopeDataBookCardType

export type ScopeType =
  | ScopeDeckType
  | ScopeDeckTermType
  | ScopeDeckFaceType
  | ScopeLoadType
  | ScopeLoadTakeType
  | ScopeLoadTakeSaveType
  | ScopeBearType
  | ScopeTreeType
  | ScopeTakeType
  | ScopeLikeType
  | ScopeFormType
  | ScopeTaskType
  | ScopeBindType
  | ScopeTaskFlowType
  | ScopeReadType
  | ScopeCordType
  | ScopeMarkType
  | ScopeBondType
  | ScopeSuitType
  | ScopeSuitTaskType
  | ScopeHostType
  | ScopeFaceType
  | ScopeTestType
  | ScopeHookType
  | ScopeWearType
  | ScopeHoldType
  | ScopeSeekType
  | ScopeZoneType
  | ScopeZoneToolType
  | ScopeTermType
  | ScopeDeckCardType
  | ScopeCodeCardType
  | ScopeBookCardType;
</code>```

And have all the ScopeXType reference a ScopeXDataType?

```<code>type ScopeTermType = BaseScopeType & {
  data: ScopeTermDataType
}
</code>```

That would mean that the type is not generic, I have to modify the file for every new scope I end up needing, which isn't that big of a problem, but it seems less than ideal.

One of the problems is, the scope can be nested deeply within other scopes, and I'm not entirely sure what the final tree structure could be. For example, say we have two scope data types, ScopeModuleDataType and ScopeTermDataType. Well the term data type can be nested in module or term, I guess then we do know the possibilities, just use | types maybe? Just not sure what the best approach will be. Should it be generic, or should I have every combination of hardcoded types?

Body:
I asked How to resolve Type 'K' cannot be used to index type 'X' in TypeScript? and am wanting to isolate a smaller portion of that problem I'm facing to figure out how to better structure the ScopeType. I have this <a href="https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBMAdgVwLZwMoGMJmHAbwCg44AxadAXjgCIAzS2gGhLgDlgBneG2xbjBZEAvkSKhIsODACeeTDjwBpYLIAyASx4AVecAA8OhCBhIAJl0W5gevAew2AfE7hU2OgNq0wAQyhIQgC6JmaIltZ4doaOeE5spAD8cAAUANZqEPRwXrTmvjC+tCEAZHA8UJqIAOYAlHAAPpHAqhraMNFG3n4BiMHxpKQAXHAZslk53vmFxXBlFVXVANziktDwcgqxwJw8ACIFvtFuhGxV5qAjKKgARsBQK6QCPCPEg3CMECMLNY+DN-4RjcIBAADbAXyIP4iFYw1bgdYyfTNChQVAHQrHGhvOAAC2AoNBX3KMEqvzYAHdoKDzFc0HcHqIVhIEdJNvhtjpfDdwVjTqRGGiRttUejDtE-s8YMKlDtBBijvpYcy1mzkZz9AY2ABBUIWKzbVikABCevCBtlnW2riayEQaUQEApiBOdodTsQRFc2LY018MpsXJ5tn0nm1QT+oM0GRG2r+PUCiRGxuV8KkG3VsoAar5QcgQ-YPGaIhr7NajXBlMWrD9ql6Trk-bNQGEIgQ4J4xnAqpWgiM3Y7nXAxElJnlDsVPMogmwRrkE31m6Z9c0rbKBnBktsc3mC4Z5-5AsVmJWN1dgAA3e4q1nweh2rAwTQQF1cYAwAAKUBssFkO-zADyiDbFqpAYNWq6auWbBVi2K7bK0Wi6FB8ROCkXCysKJ5gN+eC-iMygnheub5gGeD-nuDgnsoTi1CMF4QJo5j8t22QpDhP5yN2r6ygAdH69Q4qQGE2PxhyeBxeFyCENDEbu0IIKCb6sakIl4LxC4wIJCTlO+X6cX+JHAEB2zoXxmnYbh9xyERRm1ApBLKUJMi4t+FJwAI7kAKJQN+UApAABvpUmyB5EDwBc9BVMAzEvuUsoBfZbBiGILLph8D5PnFUoAJJcDo9yoCkbBqcAZGUdsvG7DATisHRcDAmCEIujiOCIDwHmCCcpViYUvFSuIpCaGxUq8VGAhjUg1QwLicCuAAjNp7wBDAyBQC69C5m+yWDSpKSjeNwCTTUM1uFQNAAAxLYMK1rRtW3ADtbDgvAh0nAd0WeBdM5DWxACEh3XaQt3rR8D1Pb9qSHWN0b4H951wAA5GYaKI0DcAg-dSmPaQqWQyk0PjWkx3TbN8M0ItLHA++d1g9jENwC9jNVGkJyEyzX0-XtRNzGURMwxkZ00IjOBQOYaNUxjNOg6S+YM5jdPbSIQA" rel="nofollow noreferrer">TypeScript playground demonstrating the full situation.

export enum Scope {
  Form = "form",
  Nest = "nest",
}

export type ScopeKeyListType<T extends ScopeType<Scope>> =
  T["parent"] extends ScopeType<Scope>
    ? (keyof T["data"] & string) | ScopeKeyListType<T["parent"]>
    : keyof T["data"] & string;

export type ScopeNestDataType = {
  index: number;
  nest: {
    foo: string;
    bar: boolean;
  };
};

export type ScopeFormDataType = {
  hello: string;
  world: number;
};

export type ScopeTableType = {
  form: ScopeFormDataType;
  nest: ScopeNestDataType;
};

export type ScopeType<
  A extends Scope,
  B extends ScopeType<Scope> | unknown = unknown
> = {
  data: ScopeTableType[A];
  like: A;
  parent?: B;
};

export type ScopeValueType<
  T extends ScopeType<Scope>,
  K extends string
> = T["data"] extends { [key in K]: unknown }
  ? T["data"][K]
  : T["parent"] extends ScopeType<Scope>
  ? ScopeValueType<T["parent"], K>
  : never;

export function setPropertyValueOnScope<
  S extends ScopeType<Scope>,
  K extends ScopeKeyListType<S>
>(scope: S, property: K, value: ScopeValueType<S, K>): void {
  if (property in scope.data) {
    scope.data[property] = value;
  } else if (scope.parent) {
    setPropertyValueOnScope(scope.parent, property, value);
  } else {
    throw new Error(`Property not defined on scope`);
  }
}

How should I organize/structure the ScopeType so it can handle my situations? Should I get rid of the generics on it and have it be a simple type? If so, how should I specify the type of the scope.data attribute? I have potentially 30 different types for the data property, which means generically there are at least going to be 30 different "scope" types. Basically I am typing the "lexical scope" in every different context in which it exists. Should I just do something like this?

export type ScopeDataType =
  | ScopeDataDeckType
  | ScopeDataDeckTermType
  | ScopeDataDeckFaceType
  | ScopeDataLoadType
  | ScopeDataLoadTakeType
  | ScopeDataLoadTakeSaveType
  | ScopeDataBearType
  | ScopeDataTreeType
  | ScopeDataTakeType
  | ScopeDataLikeType
  | ScopeDataFormType
  | ScopeDataTaskType
  | ScopeDataBindType
  | ScopeDataTaskFlowType
  | ScopeDataReadType
  | ScopeDataCordType
  | ScopeDataMarkType
  | ScopeDataBondType
  | ScopeDataSuitType
  | ScopeDataSuitTaskType
  | ScopeDataHostType
  | ScopeDataFaceType
  | ScopeDataTestType
  | ScopeDataHookType
  | ScopeDataWearType
  | ScopeDataHoldType
  | ScopeDataSeekType
  | ScopeDataZoneType
  | ScopeDataZoneToolType
  | ScopeDataTermType
  | ScopeDataDeckCardType
  | ScopeDataCodeCardType
  | ScopeDataBookCardType

export type ScopeType =
  | ScopeDeckType
  | ScopeDeckTermType
  | ScopeDeckFaceType
  | ScopeLoadType
  | ScopeLoadTakeType
  | ScopeLoadTakeSaveType
  | ScopeBearType
  | ScopeTreeType
  | ScopeTakeType
  | ScopeLikeType
  | ScopeFormType
  | ScopeTaskType
  | ScopeBindType
  | ScopeTaskFlowType
  | ScopeReadType
  | ScopeCordType
  | ScopeMarkType
  | ScopeBondType
  | ScopeSuitType
  | ScopeSuitTaskType
  | ScopeHostType
  | ScopeFaceType
  | ScopeTestType
  | ScopeHookType
  | ScopeWearType
  | ScopeHoldType
  | ScopeSeekType
  | ScopeZoneType
  | ScopeZoneToolType
  | ScopeTermType
  | ScopeDeckCardType
  | ScopeCodeCardType
  | ScopeBookCardType;

And have all the ScopeXType reference a ScopeXDataType?

type ScopeTermType = BaseScopeType & {
  data: ScopeTermDataType
}

That would mean that the type is not generic, I have to modify the file for every new scope I end up needing, which isn't that big of a problem, but it seems less than ideal.

One of the problems is, the scope can be nested deeply within other scopes, and I'm not entirely sure what the final tree structure could be. For example, say we have two scope data types, ScopeModuleDataType and ScopeTermDataType. Well the term data type can be nested in module or term, I guess then we do know the possibilities, just use | types maybe? Just not sure what the best approach will be. Should it be generic, or should I have every combination of hardcoded types?


问:
How can I make Grafana:Loki parse through HAProxy Logs and appropriately assign labels to specific line items in the log?
I'm trying to get Grafana:Loki & PromTail working in my environment. Our goal is to pull information from /var/logs/haproxy.log to track the traffic hitting each of our servers. Specifically, client IP addresses so we can graph it out over time. HAProxy has an exporter service that historically seems to work with Prometheus, however, we're unable to setup the exporter service due to specific security requirements on our end. Additionally, that involves a reboot that we do not want to do at the moment. So we've discovered Loki by Grafana that can pull the raw log, but it's up to us to design a proper regular expression configuration that pulls the information we want.

Long story long, I've managed to get Loki setup without much of an issue. Same with Promtail. However, I ran into an issue trying to configure Promtail to appropriately grab the information we want from our log files. I was able to find a regular expression that somebody else has written along with some labels, however, the labeling does not work appropriately on Grafana. So I'm kind of stuck. Below is the config file from Promtail with two stages: 1 to parse the data of the log and 2 to label said data.

I'm not sure this is the best way to approach this, but I'm stuck and don't know what to do. Is there a better way to grab the specific information I want from the HAProxy logs? Or is anyone able to help me make a regular expression/label for the information I want?

```<code>server:

  http_listen_port: 9080

  grpc_listen_port: 0

positions:

  #  This file is promtail A file that records log offsets , Every time you collect this file, it will be updated

  #  Even if the service goes down , The next restart will also start from the log offset recorded in this file

  filename: /tmp/positions.yaml

clients:

  - url: http://10.10.140.53:3100/loki/api/v1/push

scrape_configs:

#  The following configuration section is similar to Prometheus Very similar.

  - job_name: system

    static_configs:

    - targets:

        - 10.10.140.53

      labels:

        #  Static tags , On behalf of the job All logs under include at least these two tags

        job: haproxy

        # level, because haproxy The log itself is not well wrapped log level, therefore loki It doesn't work out

        #  If the normal log contains the mark of standard log registration, this label does not need to be set

        level: info

        __path__: /var/log/*log.1

    pipeline_stages:

    - match:

        #  This part deals with logs ,selector Selectors are used to filter log streams that meet the criteria

        selector: '{job="haproxy"}'

        stages:

        - regex:

            # RE2 Regular expression of format ,?P<XXX> Represents setting the matching part as a variable

            expression: '^[^[]+\s+(\w+)\[(\d+)\]:([^:]+):(\d+)\s+\[([^\]]+)\]\s+[^\s]+\s+(\w+)\/(\w+)\s+(\d+)\/(\d+)\/(\d+)\/(\d+)\/(\d*)\s+(\d+)\s+(\d+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s(\d+)\/(\d+)\/(\d+)\/(\d+)\/(\d+)\s+(\d+)\/(\d+)\s+\{([^}]*)\}\s\{([^}]*)\}\s+\"([^"]+)\"$'

        #  Don't filter out my time and other records , With output Variable output

        - output:

            source: output

    - match:

        #  Although I still use the same conditional selector here , But the log stream at this time has been processed once

        #  So the unwanted information no longer exists

        selector: '{job="haproxy"}'

        stages:

        - regex:

            expression: 'frontend:(?P<frontend>\S+) haproxy:(?P<haproxy>\S+) client:(?P<client>\S+) method:(?P<method>\S+) code:(?P<code>\S+) url:(?P<url>\S+) destination:(?P<destination>\S+)}?$'

        - labels:

            #  Dynamic label generation

            frontend:

            method:

            code:

            destination:
</code>```

Here's a log file example:

```<code>Dec 13 11:35:50 haproxy haproxy[8733]: frontend:app_https_frontend/haproxy/10.10.150.53:443 client:111.222.333.444:38034 GMT:13/Dec/2022:11:35:50 +0000 body:- request:GET /bower_components/modernizr/modernizr.js?v=3.30.0 HTTP/1.1
</code>```

Body:
I'm trying to get Grafana:Loki & PromTail working in my environment. Our goal is to pull information from /var/logs/haproxy.log to track the traffic hitting each of our servers. Specifically, client IP addresses so we can graph it out over time. HAProxy has an exporter service that historically seems to work with Prometheus, however, we're unable to setup the exporter service due to specific security requirements on our end. Additionally, that involves a reboot that we do not want to do at the moment. So we've discovered Loki by Grafana that can pull the raw log, but it's up to us to design a proper regular expression configuration that pulls the information we want.

Long story long, I've managed to get Loki setup without much of an issue. Same with Promtail. However, I ran into an issue trying to configure Promtail to appropriately grab the information we want from our log files. I was able to find a regular expression that somebody else has written along with some labels, however, the labeling does not work appropriately on Grafana. So I'm kind of stuck. Below is the config file from Promtail with two stages: 1 to parse the data of the log and 2 to label said data.

I'm not sure this is the best way to approach this, but I'm stuck and don't know what to do. Is there a better way to grab the specific information I want from the HAProxy logs? Or is anyone able to help me make a regular expression/label for the information I want?

server:

  http_listen_port: 9080

  grpc_listen_port: 0

positions:

  #  This file is promtail A file that records log offsets , Every time you collect this file, it will be updated

  #  Even if the service goes down , The next restart will also start from the log offset recorded in this file

  filename: /tmp/positions.yaml

clients:

  - url: http://10.10.140.53:3100/loki/api/v1/push

scrape_configs:

#  The following configuration section is similar to Prometheus Very similar.

  - job_name: system

    static_configs:

    - targets:

        - 10.10.140.53

      labels:

        #  Static tags , On behalf of the job All logs under include at least these two tags

        job: haproxy

        # level, because haproxy The log itself is not well wrapped log level, therefore loki It doesn't work out

        #  If the normal log contains the mark of standard log registration, this label does not need to be set

        level: info

        __path__: /var/log/*log.1

    pipeline_stages:

    - match:

        #  This part deals with logs ,selector Selectors are used to filter log streams that meet the criteria

        selector: '{job="haproxy"}'

        stages:

        - regex:

            # RE2 Regular expression of format ,?P<XXX> Represents setting the matching part as a variable

            expression: '^[^[]+\s+(\w+)\[(\d+)\]:([^:]+):(\d+)\s+\[([^\]]+)\]\s+[^\s]+\s+(\w+)\/(\w+)\s+(\d+)\/(\d+)\/(\d+)\/(\d+)\/(\d*)\s+(\d+)\s+(\d+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s(\d+)\/(\d+)\/(\d+)\/(\d+)\/(\d+)\s+(\d+)\/(\d+)\s+\{([^}]*)\}\s\{([^}]*)\}\s+\"([^"]+)\"$'

        #  Don't filter out my time and other records , With output Variable output

        - output:

            source: output

    - match:

        #  Although I still use the same conditional selector here , But the log stream at this time has been processed once

        #  So the unwanted information no longer exists

        selector: '{job="haproxy"}'

        stages:

        - regex:

            expression: 'frontend:(?P<frontend>\S+) haproxy:(?P<haproxy>\S+) client:(?P<client>\S+) method:(?P<method>\S+) code:(?P\S+) url:(?P<url>\S+) destination:(?P<destination>\S+)}?$'

        - labels:

            #  Dynamic label generation

            frontend:

            method:

            code:

            destination:

Here's a log file example:

Dec 13 11:35:50 haproxy haproxy[8733]: frontend:app_https_frontend/haproxy/10.10.150.53:443 client:111.222.333.444:38034 GMT:13/Dec/2022:11:35:50 +0000 body:- request:GET /bower_components/modernizr/modernizr.js?v=3.30.0 HTTP/1.1