问:
How to use Custom Transition in GetPage flutter
I have CustomPageRoute that I use for navigating to new page with custom transition.

for navigating I use code below:

```<code>Navigator.push(
    context,
    CustomPageRoute(
        NewScreen(),
    ),
),
</code>```

This is works fine, but now I want to use GetPage in getx library to add dependencies.

```<code>GetPage(
    name: Routes.NEW_SCREEN,
    page: () => NewScreen(),
    binding: NewScreenBinding(),
),
</code>```

So I have to navigate with Get.toNamed(Routes.NEW_SCREEN) and my custom transition not work.

How can I integrate my custom transition with GetPage

This is my custom transition:

```<code>class CustomPageRoute<T> extends PageRoute<T> {
  final Widget child;

  CustomPageRoute(this.child);

  @override
  Color get barrierColor => Colors.black;

  @override
  String get barrierLabel => '';

  @override
  bool get maintainState => true;

  @override
  Duration get transitionDuration => Duration(milliseconds: 600);

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    return FadeTransition(
      opacity: animation,
      child: child,
    );
  }
}
</code>```

答:
You can change your default transition from main.dart inside the GetMaterialApp widget

GetMaterialApp(
     defaultTransition: Transition.fadeIn,
      //or customTransition
      initialBinding: InitialBindings(),
      initialRoute: '/',
      getPages: [
       ...
      ],
      ...
    );
    ```
</div>
</div>
</p>
<p>or you can add the transition inside the GetPage object like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>GetPage(
    name: Routes.NEW_SCREEN,
    page: () => NewScreen(),
    binding: NewScreenBinding(),
    transition: Transition.fadeIn,
    //or customTransition
),</code>```

you can also edit this transition's duration
by editing the default value of

transitionDuration```
</div>
</div>
</p>
<p>or you can use a CustomTransition object by editing the value of</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>customTransition</code>```

Body:
I have CustomPageRoute that I use for navigating to new page with custom transition.

for navigating I use code below:

Navigator.push(
    context,
    CustomPageRoute(
        NewScreen(),
    ),
),

This is works fine, but now I want to use GetPage in getx library to add dependencies.

GetPage(
    name: Routes.NEW_SCREEN,
    page: () => NewScreen(),
    binding: NewScreenBinding(),
),

So I have to navigate with Get.toNamed(Routes.NEW_SCREEN) and my custom transition not work.

How can I integrate my custom transition with GetPage

This is my custom transition:

class CustomPageRoute<T> extends PageRoute<T> {
  final Widget child;

  CustomPageRoute(this.child);

  @override
  Color get barrierColor => Colors.black;

  @override
  String get barrierLabel => '';

  @override
  bool get maintainState => true;

  @override
  Duration get transitionDuration => Duration(milliseconds: 600);

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    return FadeTransition(
      opacity: animation,
      child: child,
    );
  }
}

Body:
You can change your default transition from main.dart inside the GetMaterialApp widget

GetMaterialApp(
     defaultTransition: Transition.fadeIn,
      //or customTransition
      initialBinding: InitialBindings(),
      initialRoute: '/',
      getPages: [
       ...
      ],
      ...
    );

or you can add the transition inside the GetPage object like this:

GetPage(
    name: Routes.NEW_SCREEN,
    page: () => NewScreen(),
    binding: NewScreenBinding(),
    transition: Transition.fadeIn,
    //or customTransition
),

you can also edit this transition's duration
by editing the default value of

transitionDuration

or you can use a CustomTransition object by editing the value of

customTransition


来源: stackexchange

问:
Changes not reflecting in html when the Observable is subscribed
I'm trying to pass the object to object Model using a shared service to a already loaded component , even though i get data after subscription, it is not reflecting in html view.</p>
```<code><div *ngFor="let emp of emps" class="card">
      <div class="card-body">
            <img class="img-icon" [src]="emp?.logo" />
                </div>
      <div class="icon-text">
      <p class="maintext" >{{emp?.name}}</p>
      <p class="subtext">Emp Code: {{emp?.code}}</p>
       </div>

       <div class="icon-text">
             <a class="view-btn" >View Details</a>
       </div>
  </div>
</code>```
```<code>emps : EmployeeModel[];

ngOnInit(): void {

    this.service.getData().subscribe(data => {
      this.emps = data
      console.log(this.emps))
    })
   }

</code>```
```<code>export class EmployeeService {
  employeeData:any;
  private subject = new Subject<any>();
  constructor() { }

  setEmployeeData(data) {
    this.employeeData = data
    this.subject.next(data);
  }

 getData(): Observable<any> {
    return this.subject.asObservable();
 }
}

</code>```

答: The observable being returned from getData() isn't emitting anything. That is until you invoke setEmployeeData() with data.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to pass the object to object Model using a shared service to a already loaded component , even though i get data after subscription, it is not reflecting in html view.

{{emp?.name}}

Emp Code: {{emp?.code}}

             View Details

emps : EmployeeModel[];

ngOnInit(): void {

    this.service.getData().subscribe(data => {
      this.emps = data
      console.log(this.emps))
    })
   }

export class EmployeeService {
  employeeData:any;
  private subject = new Subject<any>();
  constructor() { }

  setEmployeeData(data) {
    this.employeeData = data
    this.subject.next(data);
  }

 getData(): Observable<any> {
    return this.subject.asObservable();
 }
}


问:
How can we insert multiple texts and paragraphs in google docs using google docs api with php?
I want to insert more the one texts in google docs with multiple paragraph contents and also want to style them. I also followed this link https://developers.google.com/docs/api/reference/rest/v1/documents/request but I am unable to achieve this.

```<code>$requests [] = new Google_Service_Docs_Request(
[
    'insertText' => [
        'text' => 'Sample1\n',
        'location' => [
            'index' => 1
        ]
    ]
],
  [
    'insertText' => [
      'text' => 'sample2\n',
      'location' => [
        'index' => 9
      ]
    ]
  ],
  [
    'updateParagraphStyle' => [
      'range' => [
        'startIndex' => 1,
        'endIndex' => 8
      ],
      'paragraphStyle' => [
        'namedStyleType' => 'HEADING_1'
      ],
      'fields' => 'namedStyleType'
    ]
  ],
  [
    'updateParagraphStyle' => [
      'range' => [
        'startIndex' => 9,
        'endIndex' => 17
      ],
      'paragraphStyle' => [
        'namedStyleType' => 'NORMAL_TEXT'
      ],
      'fields' => 'namedStyleType'
  ]
  ],
  [
    'updateTextStyle' => [
      'range' => [
        'startIndex' => 9,
        'endIndex' => 16
      ],
      'textStyle' => [
        'link' => [
          'url' => 'https://www.google.com'
        ]
      ],
      'fields' => 'link'
    ]
  ]
);
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

</code>```

I am doing in this way and getting this error

```<code>PHP Fatal error:  Uncaught Google\Service\Exception: {
  "error": {
    "code": 400,
    "message": "Invalid requests[0]: No request set.",
    "errors": [
      {
        "message": "Invalid requests[0]: No request set.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }
}

</code>```

Can anyone help me out with this. It would be a great help and i need it in PHP code.

答:
I think the error is caused by the construction of the batch request. The request array must contain a number of instances of Google_Service_Docs_Request.

Try change this:

$requests [] = new Google_Service_Docs_Request(
[
    'insertText' => [
        'text' => 'Sample1\n',
        'location' => [
            'index' => 1
        ]
    ]
],
  [
    'insertText' => [
      'text' => 'sample2\n',
      'location' => [
        'index' => 9
      ]
    ]
  ],
```
<p>To this:</p>
<pre class="lang-php prettyprint-override"><code>$requests = [
    new Google_Service_Docs_Request([
    'insertText' => [
        'text' => 'Sample1\n',
        'location' => [
            'index' => 1
        ]
    ]
    ]),
    new Google_Service_Docs_Request([
    'insertText' => [
      'text' => 'sample2\n',
      'location' => [
        'index' => 9
      ]
    ])
];

</code>```

And after proceed as follows:

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(['requests' => $requests]);
$result = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
```

Documentation:

PHP Google Docs API Client Library

Body:
I want to insert more the one texts in google docs with multiple paragraph contents and also want to style them. I also followed this link https://developers.google.com/docs/api/reference/rest/v1/documents/request but I am unable to achieve this.

$requests [] = new Google_Service_Docs_Request(
[
    'insertText' => [
        'text' => 'Sample1\n',
        'location' => [
            'index' => 1
        ]
    ]
],
  [
    'insertText' => [
      'text' => 'sample2\n',
      'location' => [
        'index' => 9
      ]
    ]
  ],
  [
    'updateParagraphStyle' => [
      'range' => [
        'startIndex' => 1,
        'endIndex' => 8
      ],
      'paragraphStyle' => [
        'namedStyleType' => 'HEADING_1'
      ],
      'fields' => 'namedStyleType'
    ]
  ],
  [
    'updateParagraphStyle' => [
      'range' => [
        'startIndex' => 9,
        'endIndex' => 17
      ],
      'paragraphStyle' => [
        'namedStyleType' => 'NORMAL_TEXT'
      ],
      'fields' => 'namedStyleType'
  ]
  ],
  [
    'updateTextStyle' => [
      'range' => [
        'startIndex' => 9,
        'endIndex' => 16
      ],
      'textStyle' => [
        'link' => [
          'url' => 'https://www.google.com'
        ]
      ],
      'fields' => 'link'
    ]
  ]
);
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

I am doing in this way and getting this error

PHP Fatal error:  Uncaught Google\Service\Exception: {
  "error": {
    "code": 400,
    "message": "Invalid requests[0]: No request set.",
    "errors": [
      {
        "message": "Invalid requests[0]: No request set.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }
}

Can anyone help me out with this. It would be a great help and i need it in PHP code.

Body:
I think the error is caused by the construction of the batch request. The request array must contain a number of instances of Google_Service_Docs_Request.

Try change this:

$requests [] = new Google_Service_Docs_Request(
[
    'insertText' => [
        'text' => 'Sample1\n',
        'location' => [
            'index' => 1
        ]
    ]
],
  [
    'insertText' => [
      'text' => 'sample2\n',
      'location' => [
        'index' => 9
      ]
    ]
  ],

To this:

$requests = [
    new Google_Service_Docs_Request([
    'insertText' => [
        'text' => 'Sample1\n',
        'location' => [
            'index' => 1
        ]
    ]
    ]),
    new Google_Service_Docs_Request([
    'insertText' => [
      'text' => 'sample2\n',
      'location' => [
        'index' => 9
      ]
    ])
];

And after proceed as follows:

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(['requests' => $requests]);
$result = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

Documentation:

PHP Google Docs API Client Library


问:
Using List as a key in map in Dart
Here is my Dart code

```<code>var mp = new Map();
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.remove([3,5]);
  print(mp);
</code>```

Output here is null

How can i access value at mp[[3,5]]?

答:
Two list instances containing the same elements is not equal to each other in Dart. This is the reason your example does not work.

If you want to create a Map which works like your example, you can use LinkedHashMap from dart:collection (basically the same when you are using Map()) to create an instance with its own definition of what it means for keys to be equal and how hashCode is calculated for a key.

So something like this if you want to have keys to be equal if the list contains the same elements in the same order. It should be noted it does not support nested lists:

```<code>import 'dart:collection';

void main() {
  final mp = LinkedHashMap<List<int>, String>(
    equals: (list1, list2) {
      if (list1.length != list2.length) {
        return false;
      }

      for (var i = 0; i < list1.length; i++) {
        if (list1[i] != list2[i]) {
          return false;
        }
      }

      return true;
    },
    hashCode: Object.hashAll,
  );

  mp[[1, 2]] = "Hi";
  mp[[3, 5]] = "sir";
  mp.remove([3, 5]);
  print(mp); // {[1, 2]: Hi}
}
</code>```

I should also add that this is really an inefficient way to do use maps and I am highly recommend to never use List as keys in maps.

Title: Using List as a key in map in Dart

Body:
Here is my Dart code

var mp = new Map();
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.remove([3,5]);
  print(mp);

Output here is null

How can i access value at mp[[3,5]]?

Body:
Two list instances containing the same elements is not equal to each other in Dart. This is the reason your example does not work.

If you want to create a Map which works like your example, you can use LinkedHashMap from dart:collection (basically the same when you are using Map()) to create an instance with its own definition of what it means for keys to be equal and how hashCode is calculated for a key.

So something like this if you want to have keys to be equal if the list contains the same elements in the same order. It should be noted it does not support nested lists:

import 'dart:collection';

void main() {
  final mp = LinkedHashMap<List<int>, String>(
    equals: (list1, list2) {
      if (list1.length != list2.length) {
        return false;
      }

      for (var i = 0; i < list1.length; i++) {
        if (list1[i] != list2[i]) {
          return false;
        }
      }

      return true;
    },
    hashCode: Object.hashAll,
  );

  mp[[1, 2]] = "Hi";
  mp[[3, 5]] = "sir";
  mp.remove([3, 5]);
  print(mp); // {[1, 2]: Hi}
}

I should also add that this is really an inefficient way to do use maps and I am highly recommend to never use List as keys in maps.


问:
area onmouseover cursor appearance
I've got a map with area tags set up, for which I'd like to have a onmouseover event, changing the cursor's appearance to tell the user its clickable. But, there is a problem using safari:

Using onmouseover="style.cursor = 'pointer';" doesen't seem to work in the area tag. Not generally, as it totally triggers other things when hovering. Also safari lets me change its appearance using other ways, but with this combination it just doesen't...

```<code><div class="desktop"> <img src="docs/docs_overview_desktop.jpg" usemap="#desktop"> <map name="desktop"> <area shape="rect" coords="2057.143,0,2742.857,960" onmouseover="style.cursor = 'pointer';" onclick="document.getElementById('lightboxSrc').src='docs/docs_000.jpg'; lightboxOpen();"> </map> </div>
</code>```

答:
Safari isn't always supporting the "general" functions that other browsers do these days. But still, I can hardly believe that they wouldn't support an onmouseover event, so it's probably the rest of the code that's causing the problem for it not to work.

If really want to use javascript to apply the styling for a pointer then try  to make it more specific like this:
onmouseover="this.style.cursor='pointer';"

But why use JavaScript when you want to add a styling? CSS alone would be enough just place this in your stylesheet and you can remove the whole inline onmouseover:

```<code>.desktop area:hover{
   cursor: pointer;
}
</code>```

Or use an empty href="#"so the browsers sees it's a link and it shows the pointer by default.

Here's an example. Make sure your coordinates are in the image aswell of course!

img {
  width: 100px;
  height: 100px;
  border: solid 1px black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="desktop">
  <img src="docs/docs_overview_desktop.jpg" usemap="#desktop">
  <map name="desktop">
    <!-- Coords are from left uper corner (10px on the x and y axis) to the right bottom corner (90px on the x and y axis) -->
    <area shape="rect" coords="10,10,90,90" onclick="document.getElementById('lightboxSrc').src='docs/docs_000.jpg'; lightboxOpen();" href="#">
  </map>
</div></code>```

Title: area onmouseover cursor appearance

Body:
I've got a map with area tags set up, for which I'd like to have a onmouseover event, changing the cursor's appearance to tell the user its clickable. But, there is a problem using safari:

Using onmouseover="style.cursor = 'pointer';" doesen't seem to work in the area tag. Not generally, as it totally triggers other things when hovering. Also safari lets me change its appearance using other ways, but with this combination it just doesen't...

  <map name="desktop"> <area shape="rect" coords="2057.143,0,2742.857,960" onmouseover="style.cursor = 'pointer';" onclick="document.getElementById('lightboxSrc').src='docs/docs_000.jpg'; lightboxOpen();"> </map>

Body:
Safari isn't always supporting the "general" functions that other browsers do these days. But still, I can hardly believe that they wouldn't support an onmouseover event, so it's probably the rest of the code that's causing the problem for it not to work.

If really want to use javascript to apply the styling for a pointer then try  to make it more specific like this:
onmouseover="this.style.cursor='pointer';"

But why use JavaScript when you want to add a styling? CSS alone would be enough just place this in your stylesheet and you can remove the whole inline onmouseover:

.desktop area:hover{
   cursor: pointer;
}

Or use an empty href="#"so the browsers sees it's a link and it shows the pointer by default.

Here's an example. Make sure your coordinates are in the image aswell of course!

img {
  width: 100px;
  height: 100px;
  border: solid 1px black;
}

<div class="desktop">
  <img src="docs/docs_overview_desktop.jpg" usemap="#desktop">
  <map name="desktop">
    <!-- Coords are from left uper corner (10px on the x and y axis) to the right bottom corner (90px on the x and y axis) -->
    <area shape="rect" coords="10,10,90,90" onclick="document.getElementById('lightboxSrc').src='docs/docs_000.jpg'; lightboxOpen();" href="#">
  </map>
</div>


问:
while insatalling expo cli
E:>npm i -g expo-cli
npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated uuid@3.0.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
npm WARN deprecated graphql-tools@3.0.0: This package has been deprecated and now it only exports makeExecutableSchema.\nAnd it will no longer receive updates.\nWe recommend you to migrate to scoped packages such as @graphql-tools/schema, @graphql-tools/utils and etc.\nCheck out https://www.graphql-tools.com to learn what package you should use instead
npm WARN deprecated graphql@0.13.2: Version no longer supported. Please upgrade

added 1621 packages, and audited 1622 packages in 5m

115 packages are looking for funding
run npm fund for details

66 vulnerabilities (55 moderate, 9 high, 2 critical)

To address issues that do not require attention, run:
npm audit fix

To address all issues (including breaking changes), run:
npm audit fix --force

Run npm audit for details.

please help me how to fix the vulnarebilities
and say can we install expo-cli in different directories are only in c drive

答:
run npm audit To check for vulnerabilities and fixing packages.

run npm audit fix
or
protections disabled npm audit fix --force (Recommended!) To update packages.

If you encounter an error during the update. Check your internet speed and use vpn in some countries

Title: while insatalling expo cli


问:
How to submit multiple forms in Stepper in Angular material
I have used angular mat-stepper to implement a form of multiple steps. The first step is one form and there are 3 such steps.
Something like this:

```<code>    firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  thirdFormGroup: FormGroup;
  fourthFormGroup: FormGroup;
  rows: FormArray;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.firstFormGroup = this.formBuilder.group({
      name : ['', Validators.required],
      gender : ['', Validators.required]
    });
    this.secondFormGroup = this.formBuilder.group({
      permanentHouseName: ['', Validators.required],
      permanentHouseNumber: ['', Validators.required],
      permanentPlace: ['', Validators.required]
    });
    this.thirdFormGroup = this.formBuilder.group({
      profession  : ['', Validators.required],
      designation  : ['', Validators.required],
    });
</code>```

I want to submit all 3 forms at once on click of submit at the last third step. I am able to access the data of the forms individually but is there any way we can submit it as one form data to my java spring controller in backend.

Access to data:

```<code> submit() {

    if (this.basicInfoForm.valid) {
      console.log(this.firstFormGroup.value);
    }
    console.log(this.secondFormGroup.value);
  }
</code>```

答:
If you can access the form individually, then you can combine the values into 1 object & then send it to your backend.

```<code>const combinedValue={
 ...this.firstFormGroup.value,
 ...this.secondFormGroup.value,
 ...this.thirdFormGroup.value
};
</code>```

Here, we used the spread operator to extract all values of the individual form & made a new object out of it. You can use this object to send to backend.

Body:
I have used angular mat-stepper to implement a form of multiple steps. The first step is one form and there are 3 such steps.
Something like this:

    firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  thirdFormGroup: FormGroup;
  fourthFormGroup: FormGroup;
  rows: FormArray;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.firstFormGroup = this.formBuilder.group({
      name : ['', Validators.required],
      gender : ['', Validators.required]
    });
    this.secondFormGroup = this.formBuilder.group({
      permanentHouseName: ['', Validators.required],
      permanentHouseNumber: ['', Validators.required],
      permanentPlace: ['', Validators.required]
    });
    this.thirdFormGroup = this.formBuilder.group({
      profession  : ['', Validators.required],
      designation  : ['', Validators.required],
    });

I want to submit all 3 forms at once on click of submit at the last third step. I am able to access the data of the forms individually but is there any way we can submit it as one form data to my java spring controller in backend.

Access to data:

 submit() {

    if (this.basicInfoForm.valid) {
      console.log(this.firstFormGroup.value);
    }
    console.log(this.secondFormGroup.value);
  }

Body:
If you can access the form individually, then you can combine the values into 1 object & then send it to your backend.

const combinedValue={
 ...this.firstFormGroup.value,
 ...this.secondFormGroup.value,
 ...this.thirdFormGroup.value
};

Here, we used the spread operator to extract all values of the individual form & made a new object out of it. You can use this object to send to backend.


问:
What is the difference between quote and double quote in mssql
Is there a difference in these two expressions for example?</p>
```<code>Select [column] as 'column1' from [table]
</code>```
```<code>Select [column] as "column1" from [table]
</code>```

答:
Single quotes are for literal strings. Double quotes are the ANSI SQL Delimit Identifier for object names (T-SQL's delimit identifier is brackets ([])).

Don't use single quotes (') for aliases though, as (as mentioned) single quotes are for literal strings, not delimit identifying object names. Single quotes only work as delimit identifiers on aliases when you define said alias, no where else. This means that you can easily confuse those new to the language (and even those who've been using it for years if your formatting is poor).

As an example, ORDER BY 'column1' would not order by your column aliased as 'column1', it would order by the varchar literal 'column1'; effectively your data would not be ordered at all and would be returned in an arbitrary order (as every row has the same value for it ordering). Like wise in the following the 1st statement would return no rows and the second would error:

SELECT 'Column1'
FROM (SELECT [Column] + '_suffix' AS Column1
      FROM dbo.MyTable) MT
WHERE 'Column1' LIKE 'ID%';
GO
SELECT 'Column1' + 2
FROM (SELECT [SomeIntColumn] AS 'Column1'
      FROM dbo.MyTable) MT;
```

The first would return no rows as the literal varchar value 'Column1' will never be LIKE 'ID%'. The second would error as although the column has been aliased as 'Column1', and it's name suggests it's an int column, the outer SELECT would try to convert the literal varchar value 'Column1' to an int, and (obviously) that won't work.

Also some syntaxes with literal string aliases are deprecated (specifically 'string_alias' = expression).

Stick to object and alias names that don't need delimit identifying, and if you must delimit identify them use the T-SQL identifier, brackets ([]), or ANSI-SQL's, double quotes ("). column1 does not need identifying, so you should just define is as column1.

Body:
Is there a difference in these two expressions for example?

Select [column] as 'column1' from [table]

Select [column] as "column1" from [table]

Body:
Single quotes are for literal strings. Double quotes are the ANSI SQL Delimit Identifier for object names (T-SQL's delimit identifier is brackets ([])).

Don't use single quotes (') for aliases though, as (as mentioned) single quotes are for literal strings, not delimit identifying object names. Single quotes only work as delimit identifiers on aliases when you define said alias, no where else. This means that you can easily confuse those new to the language (and even those who've been using it for years if your formatting is poor).

As an example, ORDER BY 'column1' would not order by your column aliased as 'column1', it would order by the varchar literal 'column1'; effectively your data would not be ordered at all and would be returned in an arbitrary order (as every row has the same value for it ordering). Like wise in the following the 1st statement would return no rows and the second would error:

SELECT 'Column1'
FROM (SELECT [Column] + '_suffix' AS Column1
      FROM dbo.MyTable) MT
WHERE 'Column1' LIKE 'ID%';
GO
SELECT 'Column1' + 2
FROM (SELECT [SomeIntColumn] AS 'Column1'
      FROM dbo.MyTable) MT;

The first would return no rows as the literal varchar value 'Column1' will never be LIKE 'ID%'. The second would error as although the column has been aliased as 'Column1', and it's name suggests it's an int column, the outer SELECT would try to convert the literal varchar value 'Column1' to an int, and (obviously) that won't work.

Also some syntaxes with literal string aliases are deprecated (specifically 'string_alias' = expression).

Stick to object and alias names that don't need delimit identifying, and if you must delimit identify them use the T-SQL identifier, brackets ([]), or ANSI-SQL's, double quotes ("). column1 does not need identifying, so you should just define is as column1.


问:
Multiple S3 credentials in a Spark Structured Streaming application
I want to migrate our Delta lake from S3 to Parquet files in our own on-prem Ceph storage, both accessible through the S3-compliant s3a API in Spark. Is there a possibility to provide different credentials for readStream and writeStream to achieve this?

答:
the s3a connector supports per-bucket configuration, so you can declare a different set of secrets, endpoint etc for your internal buckets from your external ones.

consult the hadoop s3a docs for the normative details and examples


问:
XAMPP Error: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
I am running XAMPP and have rebuilt my PHP server from the ground up, renamed the server from ServerV1 to ServerV2, and now attempting a basic POST request from Android volley, returns the error found within the Apache logs:

```<code>[Sat Dec 19 19:24:57.528601 2015] [core:notice] [pid 7956:tid 260] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache'
[Sat Dec 19 19:24:57.531601 2015] [mpm_winnt:notice] [pid 7956:tid 260] AH00418: Parent: Created child process 5784
[Sat Dec 19 19:24:58.047631 2015] [ssl:warn] [pid 5784:tid 272] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Sat Dec 19 19:24:58.290645 2015] [ssl:warn] [pid 5784:tid 272] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Sat Dec 19 19:24:58.325647 2015] [mpm_winnt:notice] [pid 5784:tid 272] AH00354: Child: Starting 150 worker threads.
</code>```

I am not listening on any used ports:

I have research others simply running as an administrator in sources like: https://teamtreehouse.com/community/solved-xampp-apache-error  and
XAMPP - Apache Error

Upon attempting that, it still does not work, where the only return from any POST is a 0.

NOTE: I have tested every action with google chromes POSTMAN and know my routes do work and return the proper JSON objects.
https://chrome.google.com/webstore/detail/postman-rest-client-short/mkhojklkhkdaghjjfdnphfphiaiohkef?hl=en

What steps can I take to alleviate this issue?

答:
Try this:

Open httpd-ssl.conf here:

```<code>C:\xampp\apache\conf\extra
</code>```

Comment out the line and change it to localhost

```<code>#ServerName www.example.com:443
ServerName localhost
</code>```

And of course restart your Apache

Body:
I am running XAMPP and have rebuilt my PHP server from the ground up, renamed the server from ServerV1 to ServerV2, and now attempting a basic POST request from Android volley, returns the error found within the Apache logs:

[Sat Dec 19 19:24:57.528601 2015] [core:notice] [pid 7956:tid 260] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache'
[Sat Dec 19 19:24:57.531601 2015] [mpm_winnt:notice] [pid 7956:tid 260] AH00418: Parent: Created child process 5784
[Sat Dec 19 19:24:58.047631 2015] [ssl:warn] [pid 5784:tid 272] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Sat Dec 19 19:24:58.290645 2015] [ssl:warn] [pid 5784:tid 272] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Sat Dec 19 19:24:58.325647 2015] [mpm_winnt:notice] [pid 5784:tid 272] AH00354: Child: Starting 150 worker threads.

I am not listening on any used ports:

I have research others simply running as an administrator in sources like: https://teamtreehouse.com/community/solved-xampp-apache-error  and
XAMPP - Apache Error

Upon attempting that, it still does not work, where the only return from any POST is a 0.

NOTE: I have tested every action with google chromes POSTMAN and know my routes do work and return the proper JSON objects.
https://chrome.google.com/webstore/detail/postman-rest-client-short/mkhojklkhkdaghjjfdnphfphiaiohkef?hl=en

What steps can I take to alleviate this issue?

Body:
Try this:

Open httpd-ssl.conf here:

C:\xampp\apache\conf\extra

Comment out the line and change it to localhost

#ServerName www.example.com:443
ServerName localhost

And of course restart your Apache


问:
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view in Django RestFramework
I'm trying to return a response after the execution of loop but I'm getting an error as

```<code>AssertionError at Data/CurrentRunningActivityForAudit/10
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
</code>```

when I added another return response outside the loop it shows the empty array i.e.,.[ ] it's returning empty response

`

views.py:

```<code>def CurrentRunningActivity(UserID):
        cursor = connection.cursor()
        cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
        result_set = cursor.fetchall()

        IsActive = 'true'

        for row in result_set:
         data = []
         data.append({
            'TaskId':row[0],
            'TaskName' : row[1],
            'Source' : row[2],
            'Requester' : row[3],
            'type' : row[4],
            'IsActive':IsActive,

         })

         return Response(data[0], status=status.HTTP_200_OK)
</code>```

when I move the return response outside the loop it shows as local variable 'data' referenced before assignment

答:
You've to change your code like this</p>
```<code>def CurrentRunningActivity(UserID):
    cursor = connection.cursor()
    cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
    result_set = cursor.fetchall()

    IsActive = 'true'
    data = [] # changed
    for row in result_set:
        data.append({
          'TaskId':row[0],
          'TaskName' : row[1],
          'Source' : row[2],
          'Requester' : row[3],
          'type' : row[4],
          'IsActive':IsActive,

        })

     return Response(data[0], status=status.HTTP_200_OK)
</code>```

Body:
I'm trying to return a response after the execution of loop but I'm getting an error as

AssertionError at Data/CurrentRunningActivityForAudit/10
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

when I added another return response outside the loop it shows the empty array i.e.,.[ ] it's returning empty response

`

views.py:

def CurrentRunningActivity(UserID):
        cursor = connection.cursor()
        cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
        result_set = cursor.fetchall()

        IsActive = 'true'

        for row in result_set:
         data = []
         data.append({
            'TaskId':row[0],
            'TaskName' : row[1],
            'Source' : row[2],
            'Requester' : row[3],
            'type' : row[4],
            'IsActive':IsActive,

         })

         return Response(data[0], status=status.HTTP_200_OK)

when I move the return response outside the loop it shows as local variable 'data' referenced before assignment

Body:
You've to change your code like this

def CurrentRunningActivity(UserID):
    cursor = connection.cursor()
    cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
    result_set = cursor.fetchall()

    IsActive = 'true'
    data = [] # changed
    for row in result_set:
        data.append({
          'TaskId':row[0],
          'TaskName' : row[1],
          'Source' : row[2],
          'Requester' : row[3],
          'type' : row[4],
          'IsActive':IsActive,

        })

     return Response(data[0], status=status.HTTP_200_OK)


问:
How do i re-run useEffect hook if the localstorage value has been changed?
I'm trying to re-run the useEffect hook based if any new item has been added to the localstorage.

My useEffect looks like this :

```<code>useEffect(() => {
      //getting all localstorage items and setting to a variable
      const localStorageItems = { ...localStorage }

      // filtering out the localstorage items for keys that only starts with "HTTP" & pushing it to the state called "testData" using setTestData useState hook.

      const filteredByKey = Object.fromEntries(
        Object.entries(localStorageItems).filter(([key, value]) => {
          if (key.startsWith("http")) {
            testArr2.push({ urls: [key, value] })
            // setTestData({ urls: [key, value] })
            setTestData((prev) => [...prev, { key, value }])
          }
        })
      )
    }, [])
</code>```

My problem is when I hit a button(adding a new data) this useEffect should ideally re-run, setting the latest data to the "testData" state.

The Problem :

I cannot pass window.localstorage to the useEffect's array dependency list, as it is external variable I believe and react doesn't allow it.

What I have tried:

I have looked at this answer on SO, but my situation is a bit complex as I'm loading the entire items to a variable first(I'm not aware of any better alternatives)

I have tried to put the state value in the dependency list, but it doesn't work and goes to infinite loop.

Please help.
Thanks for reading this far.

答:
Define a state that holds the local storage value and pass it as a useEffect parameter.</p>
```<code>const [localStorageData, setLocalStorageData] = useState([]);

useEffect(() => {

    // Your codes

}, [localStorageData])
</code>```

Body:
I'm trying to re-run the useEffect hook based if any new item has been added to the localstorage.

My useEffect looks like this :

useEffect(() => {
      //getting all localstorage items and setting to a variable
      const localStorageItems = { ...localStorage }

      // filtering out the localstorage items for keys that only starts with "HTTP" & pushing it to the state called "testData" using setTestData useState hook.

      const filteredByKey = Object.fromEntries(
        Object.entries(localStorageItems).filter(([key, value]) => {
          if (key.startsWith("http")) {
            testArr2.push({ urls: [key, value] })
            // setTestData({ urls: [key, value] })
            setTestData((prev) => [...prev, { key, value }])
          }
        })
      )
    }, [])

My problem is when I hit a button(adding a new data) this useEffect should ideally re-run, setting the latest data to the "testData" state.

The Problem :

I cannot pass window.localstorage to the useEffect's array dependency list, as it is external variable I believe and react doesn't allow it.

What I have tried:

I have looked at this answer on SO, but my situation is a bit complex as I'm loading the entire items to a variable first(I'm not aware of any better alternatives)

I have tried to put the state value in the dependency list, but it doesn't work and goes to infinite loop.

Please help.
Thanks for reading this far.

Body:
Define a state that holds the local storage value and pass it as a useEffect parameter.

const [localStorageData, setLocalStorageData] = useState([]);

useEffect(() => {

    // Your codes

}, [localStorageData])


问:
MediaWiki documentation with external user access control
We are using MediaWiki inhouse for our software and hardware documentation. It looks like granting / revoking "read access" to parts of the documentation for our external users - customers, project partners - is not easy to achieve. How could we control read access to some areas of the documentation based on user or role access rights?

Edit: I am asking this because I don't like to go back to the "old style" of documentation - storing Office documents in dozens of different locations, and nobody has a clue where they are. So if there is no way to give users limited access only to their product information, I am afraid that management will drop the whole MediaWiki solution and introduce something "new and better". (this could mean we have to transfer all content to a new system, formatting and hyperlinks would be lost etc. ...).

Many thanks for the comments and answers!

Some interesting informations are available at http://meta.wikimedia.org/wiki/Access_control

For example there is a HiddenWiki patch which seems to be in active development, located at http://sourceforge.net/projects/hiddenwiki/

答:
You could use the Page Access Restriction extension: http://www.mediawiki.org/wiki/Extension:Page_access_restriction and groups to do this.

That being said, MediaWiki doesn't recommend you do it...

(Stolen from my answer to Stack Overflow question MediaWiki payment gateway.)

OwnerDisplayName: mjustin

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: mjustin

OwnerDisplayName: Adrian Archer


问:
VBA Deleting records by iterating through ADODB Result Set
I am trying to loop through an ADODB resultset and delete the record if a condition is true. However, when I do this only the first field of the record is deleted the rest of the record remains.

Any Ideas?
I have the following code:

```<code>Set ytdRS = New ADODB.Recordset
ytdRS.Source = SQL_YTD
ytdRS.CursorType = adOpenStatic
ytdRS.LockType = adLockBatchOptimistic

rst.MoveFirst
Do Until rst.EOF
  if (value = 1) then
    rst.Delete
    rst.MoveNext
  end if
Loop
</code>```

答:
One thing I don't see is the ytdRS.Open command. Could this be (part of) the issue?

EDIT: A few other things:

You're not using the same recordset name throughout this block (ytdRS), so I'm not sure if your intention is to use two different recordsets (I'm assuming it's not)

I'm not sure if "Value" is intended to be the value of a field in the recordset (i.e. ytdRS!FieldName.Value) or a variable name. In this context it is a variable name.

Either way you're almost guaranteeing that you're going to hit an endless loop by having your MoveNext within the if statement, because your Recordset won't move to the next record unless the Value is equal to 1.

I had to change the CursorType and LockType to get your example to work on a test table. I do not think an adOpenStatic will allow you to delete records (I believe it gives you a static, or unchangeable, cursor). An adOpenKeyset usually seems to be the way to go when you run into problems updating data. The adLockBatchOptimistic that you used for locking assumes you are operating in batch mode; normally adLockOptimistic works fine.  See here for more info on the Delete method and batch operation, if you need it.

The code below worked for me; you will have to edit it for your specific application. In particular you will need to edit ytdRS.Source, the ActiveConnection:= in the Open() method, and the ytdRs![Order ID].Value = 36 line, to correspond to your "Value" statement in the block of code you posted.

Hope this helps!

Please let me know if you have any questions.

```<code>Sub testme()
    Dim ytdRs As ADODB.Recordset
    Set ytdRs = New ADODB.Recordset

    ytdRs.Source = "SELECT * FROM [Order Summary 2]"
    ytdRs.CursorType = adOpenKeyset
    ytdRs.LockType = adLockOptimistic
    ytdRs.Open ActiveConnection:=CurrentProject.Connection

    ytdRs.MoveFirst
    Do Until ytdRs.EOF
      If (ytdRs![Order ID].Value = 36) Then
        ytdRs.Delete
      End If
      ytdRs.MoveNext
    Loop
End Sub
</code>```

Body:
I am trying to loop through an ADODB resultset and delete the record if a condition is true. However, when I do this only the first field of the record is deleted the rest of the record remains.

Any Ideas?
I have the following code:

Set ytdRS = New ADODB.Recordset
ytdRS.Source = SQL_YTD
ytdRS.CursorType = adOpenStatic
ytdRS.LockType = adLockBatchOptimistic

rst.MoveFirst
Do Until rst.EOF
  if (value = 1) then
    rst.Delete
    rst.MoveNext
  end if
Loop

Body:
One thing I don't see is the ytdRS.Open command. Could this be (part of) the issue?

EDIT: A few other things:

You're not using the same recordset name throughout this block (ytdRS), so I'm not sure if your intention is to use two different recordsets (I'm assuming it's not)

I'm not sure if "Value" is intended to be the value of a field in the recordset (i.e. ytdRS!FieldName.Value) or a variable name. In this context it is a variable name.

Either way you're almost guaranteeing that you're going to hit an endless loop by having your MoveNext within the if statement, because your Recordset won't move to the next record unless the Value is equal to 1.

I had to change the CursorType and LockType to get your example to work on a test table. I do not think an adOpenStatic will allow you to delete records (I believe it gives you a static, or unchangeable, cursor). An adOpenKeyset usually seems to be the way to go when you run into problems updating data. The adLockBatchOptimistic that you used for locking assumes you are operating in batch mode; normally adLockOptimistic works fine.  See here for more info on the Delete method and batch operation, if you need it.

The code below worked for me; you will have to edit it for your specific application. In particular you will need to edit ytdRS.Source, the ActiveConnection:= in the Open() method, and the ytdRs![Order ID].Value = 36 line, to correspond to your "Value" statement in the block of code you posted.

Hope this helps!

Please let me know if you have any questions.

Sub testme()
    Dim ytdRs As ADODB.Recordset
    Set ytdRs = New ADODB.Recordset

    ytdRs.Source = "SELECT * FROM [Order Summary 2]"
    ytdRs.CursorType = adOpenKeyset
    ytdRs.LockType = adLockOptimistic
    ytdRs.Open ActiveConnection:=CurrentProject.Connection

    ytdRs.MoveFirst
    Do Until ytdRs.EOF
      If (ytdRs![Order ID].Value = 36) Then
        ytdRs.Delete
      End If
      ytdRs.MoveNext
    Loop
End Sub


问:
Ensure That Node Cron Job is Only Configured Once
I'm writing a Discord bot and having it schedule a cron job when it starts up using node-cron. I've defined it as follows (very basic so far):

```<code>    cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
        GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
    });
</code>```

The problem is, Discord bots will often reconnect which will rerun the portion of the code where this has to be. I'm considering having a check of an external value, perhaps in my database, that manages whether or not it's run recently or is already running or something like that, but I was wondering if there was a proper way to make a cron job unique using node-cron?

答:
First, you need somewhere to save the name of the scheduled task, which defaults to a UUID V4 but can be provided as an option using the 3rd argument of the schedule method you are calling above.

With a reference to this name, either from a database or a constant that is hard-coded in the script you have wrote, you can use cron.getTasks to list all of the scheduled tasks to ensure that the current task doesn't already exist before scheduling it.

If you are referencing a hard-coded name, then calling the schedule method will replace the existing scheduled task, rather than creating a new task.

UPDATE

To set the name of the scheduled task, simply pass in an options object as a third argument to the schedule method you are calling, with a name for your task.

Example:

```<code>cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
    GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
}, { name: "example-task-1234" });
</code>```

Body:
I'm writing a Discord bot and having it schedule a cron job when it starts up using node-cron. I've defined it as follows (very basic so far):

    cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
        GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
    });

The problem is, Discord bots will often reconnect which will rerun the portion of the code where this has to be. I'm considering having a check of an external value, perhaps in my database, that manages whether or not it's run recently or is already running or something like that, but I was wondering if there was a proper way to make a cron job unique using node-cron?

Body:
First, you need somewhere to save the name of the scheduled task, which defaults to a UUID V4 but can be provided as an option using the 3rd argument of the schedule method you are calling above.

With a reference to this name, either from a database or a constant that is hard-coded in the script you have wrote, you can use cron.getTasks to list all of the scheduled tasks to ensure that the current task doesn't already exist before scheduling it.

If you are referencing a hard-coded name, then calling the schedule method will replace the existing scheduled task, rather than creating a new task.

UPDATE

To set the name of the scheduled task, simply pass in an options object as a third argument to the schedule method you are calling, with a name for your task.

Example:

cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
    GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
}, { name: "example-task-1234" });


问:
How I can display the number of items on the page I am looking at? (using liquid / ruby on rails / shopify)
Does anyone know how I can display the number of items on the page I am looking at?
I only know how to display the total number of items, using {{ paginate.items }}

My goal is to display the following message...
"Showing 1 to 8 products from 100" and have this update each time you go to the next page...
"Showing 9 to 16 products from 100"...

```<code>      <div>
        <p class="text-sm text-gray-700">
          Showing
          <span class="font-medium">{{ what goes here? }}</span>
          to
          <span class="font-medium">{{ what goes here? }}</span>
          products from
          <span class="font-medium">{{ paginate.items }}</span>
        </p>
      </div>

</code>```

答:
Here's should be the correct version</p>
```<code><p class="text-sm text-gray-700">
  {% assign from = paginate.current_offset | plus: 1 %}
  {% assign to = paginate.items %}
  {% if paginate.next.is_link %}
        {% assign to = paginate.current_offset | plus: paginate.page_size %}
  {% endif %}
  <span class="font-medium">{{ from }}</span>    to
  <span class="font-medium">{{ to }}</span>
  products from <span class="font-medium">{{ paginate.items }}</span>
</p>
</code>```

Body:
Does anyone know how I can display the number of items on the page I am looking at?
I only know how to display the total number of items, using {{ paginate.items }}

My goal is to display the following message...
"Showing 1 to 8 products from 100" and have this update each time you go to the next page...
"Showing 9 to 16 products from 100"...

          Showing
          {{ what goes here? }}
          to
          {{ what goes here? }}
          products from
          {{ paginate.items }}

Body:
Here's should be the correct version

<p class="text-sm text-gray-700">
  {% assign from = paginate.current_offset | plus: 1 %}
  {% assign to = paginate.items %}
  {% if paginate.next.is_link %}
        {% assign to = paginate.current_offset | plus: paginate.page_size %}
  {% endif %}
  <span class="font-medium">{{ from }}</span>    to
  <span class="font-medium">{{ to }}</span>
  products from <span class="font-medium">{{ paginate.items }}</span>
</p>


问:
Iterating over data to display inputs renders data multiple times
I am trying to create a custom component that iterates over an array of data and display for each item an input field type radio with its according label, it works but for some reason the data is displayed three times, instead of just once for each field and I cant figure out why, I just want to render just three inputs, why does this behavior occur, am I missing something? Here is my code:

```<code>import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Tooltip } from '@progress/kendo-react-tooltip';
import { Form, Field, FormElement } from '@progress/kendo-react-form';
import { RadioGroup, RadioButton } from '@progress/kendo-react-inputs';
import { Error } from '@progress/kendo-react-labels';
import { Input } from '@progress/kendo-react-inputs';
const emailRegex = new RegExp(/\S+@\S+\.\S+/);

const data = [
  {
    label: 'Female',
    value: 'female',
  },
  {
    label: 'Male',
    value: 'male',
  },
  {
    label: 'Other',
    value: 'other',
  },
];

const emailValidator = (value) =>
  emailRegex.test(value) ? '' : 'Please enter a valid email.';

const EmailInput = (fieldRenderProps) => {
  const { validationMessage, visited, ...others } = fieldRenderProps;
  return (
    <div>
      <Input {...others} />
      {visited && validationMessage && <Error>{validationMessage}</Error>}
    </div>
  );
};

const Component = () => {
  return (
    <>
      {data.map((item, index) => {
        return (
          <p>
            <input
              name="group1"
              type="radio"
              value={item.value}
              label={item.label}
              key={index}
            />
            <label>{item.label}</label>
          </p>
        );
      })}
    </>
  );
};

const App = () => {
  const handleSubmit = (dataItem) => alert(JSON.stringify(dataItem, null, 2));
  const tooltip = React.useRef(null);

  return (
    <Form
      onSubmit={handleSubmit}
      render={(formRenderProps) => (
        <FormElement
          style={{
            maxWidth: 650,
          }}
        >
          <fieldset className={'k-form-fieldset'}>
            <legend className={'k-form-legend'}>
              Please fill in the fields:
            </legend>
            <div className="mb-3">
              <Field
                name={'firstName'}
                component={Input}
                label={'First name'}
              />
            </div>

            <div className="mb-3">
              <Field name={'lastName'} component={Input} label={'Last name'} />
            </div>

            <div className="mb-3">
              <Field
                name={'email'}
                type={'email'}
                component={EmailInput}
                label={'Email'}
                validator={emailValidator}
              />
            </div>
          </fieldset>

          <div
            onMouseOver={(event) =>
              tooltip.current && tooltip.current.handleMouseOver(event)
            }
            onMouseOut={(event) =>
              tooltip.current && tooltip.current.handleMouseOut(event)
            }
          >
            <RadioGroup data={data} item={Component} />
            <Tooltip
              ref={tooltip}
              anchorElement="target"
              position="right"
              openDelay={300}
              parentTitle={true}
            />
          </div>

          <div className="k-form-buttons">
            <button
              type={'submit'}
              className="k-button k-button-md k-rounded-md k-button-solid k-button-solid-base"
              disabled={!formRenderProps.allowSubmit}
            >
              Submit
            </button>
          </div>
        </FormElement>
      )}
    />
  );
};

ReactDOM.render(<App />, document.querySelector('my-app'));
</code>```

and here is an example:

https://stackblitz.com/edit/react-rfb1ux-jpqvwy?file=app/main.jsx

答:
seems like this works,</p>
```<code>const Component = ({ children: { props } }) => {
  const { value, label } = { ...props };
  return (
    <p>
      <input name="group1" type="radio" value={value} label={label} />
      <label>{label}</label>
    </p>
  );
};
</code>```

Body:
I am trying to create a custom component that iterates over an array of data and display for each item an input field type radio with its according label, it works but for some reason the data is displayed three times, instead of just once for each field and I cant figure out why, I just want to render just three inputs, why does this behavior occur, am I missing something? Here is my code:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Tooltip } from '@progress/kendo-react-tooltip';
import { Form, Field, FormElement } from '@progress/kendo-react-form';
import { RadioGroup, RadioButton } from '@progress/kendo-react-inputs';
import { Error } from '@progress/kendo-react-labels';
import { Input } from '@progress/kendo-react-inputs';
const emailRegex = new RegExp(/\S+@\S+\.\S+/);

const data = [
  {
    label: 'Female',
    value: 'female',
  },
  {
    label: 'Male',
    value: 'male',
  },
  {
    label: 'Other',
    value: 'other',
  },
];

const emailValidator = (value) =>
  emailRegex.test(value) ? '' : 'Please enter a valid email.';

const EmailInput = (fieldRenderProps) => {
  const { validationMessage, visited, ...others } = fieldRenderProps;
  return (

      <Input {...others} />
      {visited && validationMessage && <Error>{validationMessage}</Error>}

  );
};

const Component = () => {
  return (
    <>
      {data.map((item, index) => {
        return (

            <input
              name="group1"
              type="radio"
              value={item.value}
              label={item.label}
              key={index}
            />
            {item.label}

        );
      })}
    </>
  );
};

const App = () => {
  const handleSubmit = (dataItem) => alert(JSON.stringify(dataItem, null, 2));
  const tooltip = React.useRef(null);

  return (
    <Form
      onSubmit={handleSubmit}
      render={(formRenderProps) => (
        <FormElement
          style={{
            maxWidth: 650,
          }}
        >
          <fieldset className={'k-form-fieldset'}>
            <legend className={'k-form-legend'}>
              Please fill in the fields:
            </legend>

              <Field
                name={'firstName'}
                component={Input}
                label={'First name'}
              />

              <Field name={'lastName'} component={Input} label={'Last name'} />

              <Field
                name={'email'}
                type={'email'}
                component={EmailInput}
                label={'Email'}
                validator={emailValidator}
              />

          </fieldset>

              tooltip.current && tooltip.current.handleMouseOver(event)
            }
            onMouseOut={(event) =>
              tooltip.current && tooltip.current.handleMouseOut(event)
            }
          >
            <RadioGroup data={data} item={Component} />
            <Tooltip
              ref={tooltip}
              anchorElement="target"
              position="right"
              openDelay={300}
              parentTitle={true}
            />

            <button
              type={'submit'}
              className="k-button k-button-md k-rounded-md k-button-solid k-button-solid-base"
              disabled={!formRenderProps.allowSubmit}
            >
              Submit
            </button>

        </FormElement>
      )}
    />
  );
};

ReactDOM.render(<App />, document.querySelector('my-app'));

and here is an example:

https://stackblitz.com/edit/react-rfb1ux-jpqvwy?file=app/main.jsx

Body:
seems like this works,

const Component = ({ children: { props } }) => {
  const { value, label } = { ...props };
  return (
    <p>
      <input name="group1" type="radio" value={value} label={label} />
      <label>{label}</label>
    </p>
  );
};


问:
Swiper horizontal slide scroll navigation
I'm building a top sticky navigation with swiper.
It should provide a mobile friendly navigation for long pages.
If you click on one item it scrolls to the referenced content on the page.

Right now swiper highlights clicked items with the class "slideActiveClass". This should stay as it is. It also applies this class when sliding through the menu.

I need to change two things.

I want to get rid of it applying the active class while sliding through the menu.

I want the active slide get set to the specific element related to where the user viewport is located. e.G. If you scroll to "div id=three", the active slide should be changed to the Slide "Three" etc.

Any Idea how to implement this properly?

I think I'd need to use "

swiper.slideTo(index, speed, runCallbacks)

Run transition to the slide with index number equal to 'index' parameter for the duration equal to 'speed' parameter.

index - number - Index number of slide.

speed - number - Transition duration (in ms).

runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events."

taken from: https://swiperjs.com/swiper-api#method-swiper-slideTo

Any help is appreciated.

I'm planning to release the finished code to codepen, since I had trouble finding an example for the requested functionality and think it might be useful for a lot of projects.

var swiper = new Swiper(".swiper-container", {
  slidesPerView: "auto",
  freeMode: true,
  slideToClickedSlide: true,
  spaceBetween: 10,
  mousewheel: true
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  scroll-behavior: smooth;
}
.swiper-container {
  width: 100%;
}
.swiper-slide {
   background-color: rgba(0,255,0,0.1);
   padding: 10px;
   width: 20%!important;
}
.swiper-slide-active {
  background-color: red;
}

.swiper-container ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.swiper-container a {
  color: black;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  width: 100%;
  height: 100%;
}
.sticky {
  position: sticky;
  top: 0px;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.1/css/swiper.min.css" rel="stylesheet"/>

One

Two

Three

Four

Five

Six

item 7

item 8

item 9

One

Two

Three

Four

Five

Six

```

答:
Found a solution myself.

Got rid of using the ".swiper-slide-active" class to display active navigation and used ".swiper-slide-active2" instead.

I added an "alt" tag to every  element in the swiper container.
Every "alt" value corresponds to the swiper index number (starting at 0).

I change the class of the nav elements with an observer and tell swiper to slide to the index number.
works okay.
Improvements are welcome.

Link to codepen: https://codepen.io/peplebe/pen/MWOJgXe

var swiper = new Swiper(".swiper-container", {
  slidesPerView: "auto",
  freeMode: {
    enabled: true,
    sticky: true,
  },

  spaceBetween: 10,
  mousewheel: true
});
//
function selectElementByClass(className) {
  return document.querySelector(`.${className}`);
}

const sections = [
  selectElementByClass("firstClass"),
  selectElementByClass("secondClass"),
  selectElementByClass("thirdClass"),
  selectElementByClass("fourthClass"),
  selectElementByClass("fifthClass"),
  selectElementByClass("sixtClass")
];

const navItems = {
  firstID: selectElementByClass("FirstNavItem"),
  secondID: selectElementByClass("SecondNavItem"),
  thirdID: selectElementByClass("ThirdNavItem"),
  fourthID: selectElementByClass("FourthNavItem"),
  fifthID: selectElementByClass("FifthNavItem"),
  sixtID: selectElementByClass("SixtNavItem")
};

// intersection observer setup
const observerOptions = {
  root: null,
  rootMargin: "0px",
  threshold: 0.1
};

function observerCallback(entries, observer) {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // get the nav item corresponding to the id of the section
      // that is currently in view
      const navItem = navItems[entry.target.id];
      //get the "alt" tag of section in view
      // alt tag equals slide index of swiper
      const navItemAlt = navItem.getAttribute("alt");
      // tell swiper to slide to the slide with index of "alt"
      swiper.slideTo(navItemAlt, 300, true)
      // add 'active' class on the navItem
      navItem.classList.add("swiper-slide-active2");
      // remove 'active' class from any navItem that is not
      // same as 'navItem' defined above
      Object.values(navItems).forEach((item) => {
        if (item != navItem) {
          item.classList.remove("swiper-slide-active2");
        }
      });
    }
  });
}

const observer = new IntersectionObserver(observerCallback, observerOptions);

sections.forEach((sec) => observer.observe(sec));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  scroll-behavior: smooth;
}
.swiper-container {
  width: 100%;
}
.swiper-slide {
   padding: 10px;
   width: 33vw!important;
}
.swiper-slide-active2 {
  background-color: #95D5B2;
  border-radius: 25px;
}

.swiper-container ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.swiper-container a {
  color: black;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  width: 100%;
  height: 100%;
}
.sticky {
  position: sticky;
  top: 0px;
}
section {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5rem;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.1/css/swiper.min.css" rel="stylesheet"/>

    First
    Second
   Third
   Fourth
   Fifth
    Sixt

      First

      Second

      Third

      Fourth

      Fifth

      Sixt

```

Body:
I'm building a top sticky navigation with swiper.
It should provide a mobile friendly navigation for long pages.
If you click on one item it scrolls to the referenced content on the page.

Right now swiper highlights clicked items with the class "slideActiveClass". This should stay as it is. It also applies this class when sliding through the menu.

I need to change two things.

I want to get rid of it applying the active class while sliding through the menu.

I want the active slide get set to the specific element related to where the user viewport is located. e.G. If you scroll to "div id=three", the active slide should be changed to the Slide "Three" etc.

Any Idea how to implement this properly?

I think I'd need to use "

swiper.slideTo(index, speed, runCallbacks)

Run transition to the slide with index number equal to 'index' parameter for the duration equal to 'speed' parameter.

index - number - Index number of slide.

speed - number - Transition duration (in ms).

runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events."

taken from: https://swiperjs.com/swiper-api#method-swiper-slideTo

Any help is appreciated.

I'm planning to release the finished code to codepen, since I had trouble finding an example for the requested functionality and think it might be useful for a lot of projects.

var swiper = new Swiper(".swiper-container", {
  slidesPerView: "auto",
  freeMode: true,
  slideToClickedSlide: true,
  spaceBetween: 10,
  mousewheel: true
});

html {
  scroll-behavior: smooth;
}
.swiper-container {
  width: 100%;
}
.swiper-slide {
   background-color: rgba(0,255,0,0.1);
   padding: 10px;
   width: 20%!important;
}
.swiper-slide-active {
  background-color: red;
}

.swiper-container ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.swiper-container a {
  color: black;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  width: 100%;
  height: 100%;
}
.sticky {
  position: sticky;
  top: 0px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.1/css/swiper.min.css" rel="stylesheet"/>

One

Two

Three

Four

Five

Six

item 7

item 8

item 9

One

Two

Three

Four

Five

Six

Body:
Found a solution myself.

Got rid of using the ".swiper-slide-active" class to display active navigation and used ".swiper-slide-active2" instead.

I added an "alt" tag to every  element in the swiper container.
Every "alt" value corresponds to the swiper index number (starting at 0).

I change the class of the nav elements with an observer and tell swiper to slide to the index number.
works okay.
Improvements are welcome.

Link to codepen: https://codepen.io/peplebe/pen/MWOJgXe

var swiper = new Swiper(".swiper-container", {
  slidesPerView: "auto",
  freeMode: {
    enabled: true,
    sticky: true,
  },

  spaceBetween: 10,
  mousewheel: true
});
//
function selectElementByClass(className) {
  return document.querySelector(`.${className}`);
}

const sections = [
  selectElementByClass("firstClass"),
  selectElementByClass("secondClass"),
  selectElementByClass("thirdClass"),
  selectElementByClass("fourthClass"),
  selectElementByClass("fifthClass"),
  selectElementByClass("sixtClass")
];

const navItems = {
  firstID: selectElementByClass("FirstNavItem"),
  secondID: selectElementByClass("SecondNavItem"),
  thirdID: selectElementByClass("ThirdNavItem"),
  fourthID: selectElementByClass("FourthNavItem"),
  fifthID: selectElementByClass("FifthNavItem"),
  sixtID: selectElementByClass("SixtNavItem")
};

// intersection observer setup
const observerOptions = {
  root: null,
  rootMargin: "0px",
  threshold: 0.1
};

function observerCallback(entries, observer) {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // get the nav item corresponding to the id of the section
      // that is currently in view
      const navItem = navItems[entry.target.id];
      //get the "alt" tag of section in view
      // alt tag equals slide index of swiper
      const navItemAlt = navItem.getAttribute("alt");
      // tell swiper to slide to the slide with index of "alt"
      swiper.slideTo(navItemAlt, 300, true)
      // add 'active' class on the navItem
      navItem.classList.add("swiper-slide-active2");
      // remove 'active' class from any navItem that is not
      // same as 'navItem' defined above
      Object.values(navItems).forEach((item) => {
        if (item != navItem) {
          item.classList.remove("swiper-slide-active2");
        }
      });
    }
  });
}

const observer = new IntersectionObserver(observerCallback, observerOptions);

sections.forEach((sec) => observer.observe(sec));

html {
  scroll-behavior: smooth;
}
.swiper-container {
  width: 100%;
}
.swiper-slide {
   padding: 10px;
   width: 33vw!important;
}
.swiper-slide-active2 {
  background-color: #95D5B2;
  border-radius: 25px;
}

.swiper-container ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.swiper-container a {
  color: black;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  width: 100%;
  height: 100%;
}
.sticky {
  position: sticky;
  top: 0px;
}
section {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5rem;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.1/css/swiper.min.css" rel="stylesheet"/>
<!--Sticky wrapper-->
<div class="sticky">
<!--swiper container-->
<div class="swiper-container" id="scroll-tags">
  <ul class="swiper-wrapper">
    <a alt="0" class="swiper-slide FirstNavItem" href="#firstID">First</a>
    <a alt="1" class="swiper-slide SecondNavItem" href="#secondID">Second</a>
   <a alt="2" class="swiper-slide ThirdNavItem" href="#thirdID">Third</a>
   <a alt="3" class="swiper-slide FourthNavItem"href="#fourthID">Fourth</a>
   <a alt="4" class="swiper-slide FifthNavItem"href="#fifthID">Fifth</a>
    <a alt="5" class="swiper-slide SixtNavItem"href="#sixtID">Sixt</a>
    </ul>
</div>
</div>
<!--wrapping div to extend page below last section-->
<div style="height: 500vh">
<!--Page sections-->
   <section class="firstClass" id="firstID">
    <h1>
      First
    </h1>
  </section>
  <section class="secondClass" id="secondID">
    <h1>
      Second
    </h1>
  </section>
  <section class="thirdClass" id="thirdID">
    <h1>
      Third
    </h1>
  </section>
  <section class="fourthClass" id="fourthID">
    <h1>
      Fourth
    </h1>
  </section>
  <section class="fifthClass" id="fifthID">
    <h1>
      Fifth
    </h1>
  </section>
   <section class="sixtClass" id="sixtID">
    <h1>
      Sixt
    </h1>
  </section>
  <section></section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.1/js/swiper.min.js"></script>


Title: groupby roling get index of max value

Body:
       week_date    hy_code high
1630    2021-06-06  880324  871.76
1631    2021-06-06  880535  742.43
1632    2021-06-13  880324  860.31
1633    2021-06-13  880535  738.39
1634    2021-06-20  880324  842.46
1635    2021-06-20  880535  725.64
1636    2021-06-27  880324  836.14
1637    2021-06-27  880535  736.13
1638    2021-07-04  880324  836.05
1639    2021-07-04  880535  739.09

Goal

I want to get index of max value(base on last 3 rows) for each group and each row.

Try

df.groupby(['hy_code']).rolling(3)['high'].agg(lambda x:x.idxmax()).reset_index()

But the result does not match my expectation.

   hy_code  level_1 high
0   880324  1630    NaN
1   880324  1632    NaN
2   880324  1634    1630.0
3   880324  1636    1631.0
4   880324  1638    1632.0
5   880535  1631    NaN
6   880535  1633    NaN
7   880535  1635    1635.0
8   880535  1637    1636.0
9   880535  1639    1639.0

For 880535 group and index=1637,the index of max values based on last 3 rows should be 1633.

Body:
I got different ouput, for easy check are data sorted by both columns and added to new column:

df['week_date'] = pd.to_datetime(df['week_date'])

df = df.sort_values(['hy_code','week_date'])

df['new'] = (df.groupby(['hy_code'])['high'].rolling(3)
               .apply(lambda x:x.idxmax())
               .droplevel(0))

print (df)
      week_date  hy_code    high     new
1630 2021-06-06   880324  871.76     NaN
1632 2021-06-13   880324  860.31     NaN
1634 2021-06-20   880324  842.46  1630.0
1636 2021-06-27   880324  836.14  1632.0
1638 2021-07-04   880324  836.05  1634.0
1631 2021-06-06   880535  742.43     NaN
1633 2021-06-13   880535  738.39     NaN
1635 2021-06-20   880535  725.64  1631.0
1637 2021-06-27   880535  736.13  1633.0
1639 2021-07-04   880535  739.09  1639.0


问:
Save stop-Process error in a variable and write it in eventlog
This seemed like easy one, but it wasn't.
I have the following function that stops processes and write in eventlog:

```<code>$PiEventlog = "Company Name"
$PiEventlogSource = "Source Name"
#   For Testing purpose, i use this PIDs.
$gpid = 45852,5264

function Terminate-Processs {
#   if $pid is empty, give this msg.
    if(!$gpid){
        Write-Host "Nth here"
    }
    else{
        for ($i = 0; $i -lt ($gpid).Count; $i++) {
            $PIDForEventLog = $gpid
            try{
                Stop-Process -Id $gpid[$i] -force -ErrorAction SilentlyContinue -ErrorVariable $ResultStopProcess
                Write-EventLog -logname $PiEventlog -source $PiEventlogSource -eventID 1021 -entrytype Information -message "$env:USERNAME killed the following PID $PIDForEventLog from the instance  $Global:SelectedInstance"
            }
            catch{
                Write-EventLog -logname $PiEventlog -source $PiEventlogSource -eventID 1021 -entrytype Error -message "$env:USERNAME could not kill the following PID $PIDForEventLog from the instance  $Global:SelectedInstance `n$ResultStopProcess `nPlease check manually whether the process is still available."
            }
        }
    }
}
</code>```

in the Catch loop, i am trying to give the errorvariable $resultstopprcess to the eventlog entry. That means, if an error occur while stoping an process, the error should be saved into that variable and it should be given to eventlog. the variable should contain sth like this, if error occurs:

Stop-Process : Es kann kein Prozess mit der Prozess-ID 34234 gefunden
werden. In Zeile:1 Zeichen:1

Stop-Process -id 34234

```<code>  + CategoryInfo          : ObjectNotFound: (34234:Int32) [Stop-Process], ProcessCommandException
  + FullyQualifiedErrorId : NoProcessFoundForGivenId,Microsoft.PowerShell.Commands.StopProcessCommand
</code>```

But the variable is somehow always empty.
How can i do this? How can i save the error to a variable. so that i can use it later?

答:
Error Analysis

```<code> -ErrorVariable $ResultStopProcess
</code>```

The parameter ErrorVariabe expects the name of the variable without $ prefix.

```<code>  try {} catch {}
</code>```

With -ErrorAction SilentlyContinue, the catch block will never be entered.

Possible solutions:

Pass -ErrorAction Stop to throw an exception in case of any error

Keep -ErrorAction SilentlyContinue and check the automatic execution status variable $? for success.

```<code>  Write-EventLog -message ".... $ResultStopProcess ..."
</code>```

This only outputs the exception message ("Es kann kein Prozess mit der Prozess-ID 34234 gefunden werden.").

To include everything you normally see on the console, pass $ResultStopProcess to the Out-String command.

Fixed code

```<code>Stop-Process -Id $gpid[$i] -force -ErrorAction SilentlyContinue -ErrorVariable ResultStopProcess
if( $? ) {
    Write-EventLog -logname $PiEventlog -source $PiEventlogSource -eventID 1021 -entrytype Information -message "$env:USERNAME killed the following PID $PIDForEventLog from the instance  $Global:SelectedInstance"
}
else {
    $ErrorView = 'NormalView'   # PS 7.2+ defaults to 'ConciseView'
    $fullErrorMessage = $ResultStopProcess | Out-String

    Write-EventLog -logname $PiEventlog -source $PiEventlogSource -eventID 1021 -entrytype Error -message "$env:USERNAME could not kill the following PID $PIDForEventLog from the instance  $Global:SelectedInstance `n$fullErrorMessage `nPlease check manually whether the process is still available."
}
</code>```

Remarks

Make sure to check $? immediately after the command that could possibly fail, else it could be overwritten by another command.

As of PowerShell 7.2, you don't get the full error message, even when using Out-String, as the default formatting mode is now ConciseView. Therefore I've set the preference variable $ErrorView = 'NormalView' to get the same output as in previous PS versions.

Body:
This seemed like easy one, but it wasn't.
I have the following function that stops processes and write in eventlog:

$PiEventlog = "Company Name"
$PiEventlogSource = "Source Name"
#   For Testing purpose, i use this PIDs.
$gpid = 45852,5264

function Terminate-Processs {
#   if $pid is empty, give this msg.
    if(!$gpid){
        Write-Host "Nth here"
    }
    else{
        for ($i = 0; $i -lt ($gpid).Count; $i++) {
            $PIDForEventLog = $gpid
            try{
                Stop-Process -Id $gpid[$i] -force -ErrorAction SilentlyContinue -ErrorVariable $ResultStopProcess
                Write-EventLog -logname $PiEventlog -source $PiEventlogSource -eventID 1021 -entrytype Information -message "$env:USERNAME killed the following PID $PIDForEventLog from the instance  $Global:SelectedInstance"
            }
            catch{
                Write-EventLog -logname $PiEventlog -source $PiEventlogSource -eventID 1021 -entrytype Error -message "$env:USERNAME could not kill the following PID $PIDForEventLog from the instance  $Global:SelectedInstance `n$ResultStopProcess `nPlease check manually whether the process is still available."
            }
        }
    }
}

in the Catch loop, i am trying to give the errorvariable $resultstopprcess to the eventlog entry. That means, if an error occur while stoping an process, the error should be saved into that variable and it should be given to eventlog. the variable should contain sth like this, if error occurs:

Stop-Process : Es kann kein Prozess mit der Prozess-ID 34234 gefunden
werden. In Zeile:1 Zeichen:1

Stop-Process -id 34234

  + CategoryInfo          : ObjectNotFound: (34234:Int32) [Stop-Process], ProcessCommandException
  + FullyQualifiedErrorId : NoProcessFoundForGivenId,Microsoft.PowerShell.Commands.StopProcessCommand

But the variable is somehow always empty.
How can i do this? How can i save the error to a variable. so that i can use it later?

Body:
Error Analysis

 -ErrorVariable $ResultStopProcess

The parameter ErrorVariabe expects the name of the variable without $ prefix.

  try {} catch {}

With -ErrorAction SilentlyContinue, the catch block will never be entered.

Possible solutions:

Pass -ErrorAction Stop to throw an exception in case of any error

Keep -ErrorAction SilentlyContinue and check the automatic execution status variable $? for success.

  Write-EventLog -message ".... $ResultStopProcess ..."

This only outputs the exception message ("Es kann kein Prozess mit der Prozess-ID 34234 gefunden werden.").

To include everything you normally see on the console, pass $ResultStopProcess to the Out-String command.

Fixed code

Stop-Process -Id $gpid[$i] -force -ErrorAction SilentlyContinue -ErrorVariable ResultStopProcess
if( $? ) {
    Write-EventLog -logname $PiEventlog -source $PiEventlogSource -eventID 1021 -entrytype Information -message "$env:USERNAME killed the following PID $PIDForEventLog from the instance  $Global:SelectedInstance"
}
else {
    $ErrorView = 'NormalView'   # PS 7.2+ defaults to 'ConciseView'
    $fullErrorMessage = $ResultStopProcess | Out-String

    Write-EventLog -logname $PiEventlog -source $PiEventlogSource -eventID 1021 -entrytype Error -message "$env:USERNAME could not kill the following PID $PIDForEventLog from the instance  $Global:SelectedInstance `n$fullErrorMessage `nPlease check manually whether the process is still available."
}

Remarks

Make sure to check $? immediately after the command that could possibly fail, else it could be overwritten by another command.

As of PowerShell 7.2, you don't get the full error message, even when using Out-String, as the default formatting mode is now ConciseView. Therefore I've set the preference variable $ErrorView = 'NormalView' to get the same output as in previous PS versions.


问:
Visual Studio Code "Error while fetching extensions. XHR failed"
This problem started a few weeks ago, when I started using NordVPN on my laptop.
When I try to search for an extension and even when trying to download through the marketplace I get this error:

EDIT: Just noticed another thing that might indicate to what's causing the issue. When I open VSCode and go to developer tools I get this error messege (before even doing anything):

"(node:19368) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.(Use Code --trace-deprecation ... to show where the warning was created)"

The only partial solution I found so far was to manually download and install extensions.

I've checked similar question here and in other places online, but I didn't find a way to fix this. So far I've tried:

Flushing my DNS cache and setting it to google's DNS server.

Disabling the VPN on my laptop and restarting VS Code.

Clearing the Extension search results.

Disabling all the extensions currently running.

I'm using a laptop running Windows 10. Any other possible solutions I haven't tried?

答:
In my case, the solution was to remove HTTPS_PROXY (Could be HTTP_PROXY) environment variable set during terminal initialisations.

Environment variables can be confirmed by env command for most operating systems.

I removed the line which sets the environment variable for proxy from the bash profile, then restarted the OS.

Apart from ~/.bashrc for bash or any other sh-compatible shell, the environment variable could be in:

/etc/environment: specifically meant for environment variables

/etc/env.d/*: environment variables, split in multiple files

/etc/profile: all types of initialization scripts

/etc/profile.d/*: initialization scripts

/etc/bashrc, /etc/bash.bashrc: meant for functions and aliases

~/.bash_profile: initialization for login (bash-)shells

~/.bashrc: initialization for all interactive (bash-)shells

~/.profile: used for all shells

~/.cshrc, ~/.zshrc, ~/.tcshrc: similar for non-bash shells

Credit to this post.
https://unix.stackexchange.com/a/249922

The environment variable HTTP(S)_PROXY may be used by other applications. Therefore, be aware of the side effects of removing it.


问:
JSON Schema Validation Failing - Error is not of type 'object'
I am attempting to use the jsonschema and python_jsonschema_objects libraries to create a python object from a schema file, populate some data in that object, and then validate it against the original schema.  Somehow I think i'm doing something wrong but not sure what exactly.

I've attempted several different schemas and data values as well as removing arrays, using flat/single object.  Still the validation fails.

```<code>from jsonschema import validate
import python_jsonschema_objects as pjs
import jsonschema
import json
import os

with open('geocoordinate/geocoordinatearray3.schema.json') as opfile:
   schema = json.load(opfile)

builder = pjs.ObjectBuilder(schema)
ns = builder.build_classes()

Coordinate = ns.Rootschema
ca = Coordinate(latitude=22.22,longitude=33.33)
print(ca.serialize())

try:
    print("about to validate first example")
    validate(instance=ca, schema=schema)
except jsonschema.exceptions. ValidationError as e:
    print("this is validation error:", e)
except json.decorder.JSONDecodeError as e:
    print("not JSON", e)
</code>```

this is the schema file:

```<code>    {
      "definitions": {},
      "$schema": "http://json-schema.org/draft-07/schema#",
      "$id": "http://example.com/root.json",
      "type": "object",
      "title": "rootSchema",
      "required": [
        "latitude",
        "longitude"
      ],
      "properties": {
        "location": {
          "$id": "#/properties/location",
          "type": "string",
          "title": "The Location Schema",
          "default": "",
          "examples": [
            "Denver, CO"
          ],
          "pattern": "^(.*)$"
        },
        "latitude": {
          "$id": "#/properties/latitude",
          "type": "number",
          "title": "The Latitude Schema",
          "default": 0.0,
          "examples": [
            39.7392
          ]
        },
        "longitude": {
          "$id": "#/properties/longitude",
          "type": "number",
          "title": "The Longitude Schema",
          "default": 0.0,
          "examples": [
            -104.9903
          ]
        },
        "alt": {
          "$id": "#/properties/alt",
          "type": "integer",
          "title": "The Alt Schema",
          "default": 0,
          "examples": [
            5280
          ]
        }
      }
    }
</code>```

I'm expecting this to validate, it's pretty straightforward what i'm attempting to do.  Getting this error:

about to validate first example
this is validation error:  0> latitude= 22.22> location= > longitude= 33.33>> is not of type 'object'

Failed validating 'type' in schema:

schema

On instance:

```<code><rootschema alt=<Literal<int> 0> latitude=<Literal<float> 22.22>
location=<Literal<str> > longitude=<Literal<float> 33.33>>
</code>```

答:
I encountered the same issue and used json.loads on the json String before validation :

import json

json.loads('{"property1":"value1"}')

Body:
I am attempting to use the jsonschema and python_jsonschema_objects libraries to create a python object from a schema file, populate some data in that object, and then validate it against the original schema.  Somehow I think i'm doing something wrong but not sure what exactly.

I've attempted several different schemas and data values as well as removing arrays, using flat/single object.  Still the validation fails.

from jsonschema import validate
import python_jsonschema_objects as pjs
import jsonschema
import json
import os

with open('geocoordinate/geocoordinatearray3.schema.json') as opfile:
   schema = json.load(opfile)

builder = pjs.ObjectBuilder(schema)
ns = builder.build_classes()

Coordinate = ns.Rootschema
ca = Coordinate(latitude=22.22,longitude=33.33)
print(ca.serialize())

try:
    print("about to validate first example")
    validate(instance=ca, schema=schema)
except jsonschema.exceptions. ValidationError as e:
    print("this is validation error:", e)
except json.decorder.JSONDecodeError as e:
    print("not JSON", e)

this is the schema file:

    {
      "definitions": {},
      "$schema": "http://json-schema.org/draft-07/schema#",
      "$id": "http://example.com/root.json",
      "type": "object",
      "title": "rootSchema",
      "required": [
        "latitude",
        "longitude"
      ],
      "properties": {
        "location": {
          "$id": "#/properties/location",
          "type": "string",
          "title": "The Location Schema",
          "default": "",
          "examples": [
            "Denver, CO"
          ],
          "pattern": "^(.*)$"
        },
        "latitude": {
          "$id": "#/properties/latitude",
          "type": "number",
          "title": "The Latitude Schema",
          "default": 0.0,
          "examples": [
            39.7392
          ]
        },
        "longitude": {
          "$id": "#/properties/longitude",
          "type": "number",
          "title": "The Longitude Schema",
          "default": 0.0,
          "examples": [
            -104.9903
          ]
        },
        "alt": {
          "$id": "#/properties/alt",
          "type": "integer",
          "title": "The Alt Schema",
          "default": 0,
          "examples": [
            5280
          ]
        }
      }
    }

I'm expecting this to validate, it's pretty straightforward what i'm attempting to do.  Getting this error:

about to validate first example
this is validation error:  0> latitude= 22.22> location= > longitude= 33.33>> is not of type 'object'

Failed validating 'type' in schema:

schema

On instance:

<rootschema alt=<Literal<int> 0> latitude=<Literal<float> 22.22>
location=<Literal<str> > longitude=<Literal<float> 33.33>>


问:
benefits for setting dependency interface in cmake target_link_libraries
I use CMake in my C++ project for a while, and my project is an application (not a library) consisting of multiple sub modules, where each module depends on other internal modules in the same project, and depends on multiple third party libraries as well, and each of them is built using CMake.

Currently, we use PUBLIC in target_link_libraries when specifying these dependencies. I read some articles/documentations [1][2][3] about this topic, and know the general difference between PUBLIC/INTERFACE/PRIVATE, and know that it is recommended to specify different visibility as detailed as possible. But since I am building an application but not a library, I am not worried that internal APIs are "leaked" accidentally, is there any other benefit that we should choose to use non PUBLIC visibility like PRIVATE? For example, besides affecting linking's speed, does it affect compilation speed? If linking doesn't take too much time, does it still make sense to optimize compilation speed by exploring this option? Does it affect the size of the binary in the end? Or is there any other benefit for controlling this behavior? Thanks.

[1] https://cmake.org/cmake/help/latest/command/target_link_libraries.html
[2] https://leimao.github.io/blog/CMake-Public-Private-Interface/
[3] https://cmake.org/pipermail/cmake/2016-May/063400.html

答:
You should absolutely always use a visibility specifier with target_link_libraries.

Whether or not target_link_libraries(target lib) is considered to be PRIVATE or PUBLIC by default depends on whether or not you use visibility specifiers elsewhere in the CMakeLists.txt. This risk of changing the visibility of a library simply by adding a different library should really be all the justification anyone needs to just use the maintainer-recommended best practices.

Having too many public dependencies will eventually lead to pointlessly long link lines, which can indeed bloat link times as the linker will need to determine that a symbol is not relevant. Worse, it's possible that one library that didn't need to be public will win a symbol conflict incorrectly and cause trouble. There's simply no reason to intentionally set up an inaccurate dependency model.

Finally, for executables, which visibility specifier to use is usually simple to choose: 99% of the time, it will be PRIVATE. However, this is not always the case. If you are building a plugin system, say, you might have ENABLE_EXPORTS set on your executable. In this case, libraries may in fact link to the executable target and visibility becomes relevant again.


问:
Can someone explain how WebDriver casting to TakesScreenShot in Selenium working
This is a JAVA conceptual question, not related to Selenium.

For a sample code like :

```<code>// Taking a screenshot in Selenium
WebDriver driver= new ChromeDriver();
File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
</code>```

When I observe, WebDriver and TakesScreenshot do not share a common super interface. In that case how can casting be valid and why not a ClassCastException?

It would be really great if this can be explained with an example.

答:
Let's take Selenium out of the picture and use built-in types for simplicity. Your code is similar (in terms of casting) to this:

Comparable<String> text = "hello";
int length = ((CharSequence) text).length();
```

This compiles and executes without an exception because:

"hello" is a String

String implements both Comparable<String> and CharSequence

The cast to CharSequence is concerned by the execution-time type of the object that the value of text refers to, not the compile-time type text

At execution time, the value of text refers to a String object ("hello"). The fact that the compile-time type is Comparable<String> is irrelevant when it comes to the cast - so long as it's possible. (If you try to cast an expression with a compile-time type which can't possibly be valid, e.g. casting from String to InputStream, then you'll get a compile-time error. But when the compiler is happy that the cast could potentially succeed, the compile-time type of the variable is irrelevant when it comes to the execution-time handling of the cast.)

Body:
This is a JAVA conceptual question, not related to Selenium.

For a sample code like :

// Taking a screenshot in Selenium
WebDriver driver= new ChromeDriver();
File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

When I observe, WebDriver and TakesScreenshot do not share a common super interface. In that case how can casting be valid and why not a ClassCastException?

It would be really great if this can be explained with an example.

Body:
Let's take Selenium out of the picture and use built-in types for simplicity. Your code is similar (in terms of casting) to this:

Comparable<String> text = "hello";
int length = ((CharSequence) text).length();

This compiles and executes without an exception because:

"hello" is a String

String implements both Comparable<String> and CharSequence

The cast to CharSequence is concerned by the execution-time type of the object that the value of text refers to, not the compile-time type text

At execution time, the value of text refers to a String object ("hello"). The fact that the compile-time type is Comparable<String> is irrelevant when it comes to the cast - so long as it's possible. (If you try to cast an expression with a compile-time type which can't possibly be valid, e.g. casting from String to InputStream, then you'll get a compile-time error. But when the compiler is happy that the cast could potentially succeed, the compile-time type of the variable is irrelevant when it comes to the execution-time handling of the cast.)


问:
Railstutorial : which parts of the app to upgrade first?
After finishing with Rails Tutorial by Michael Hartl, which parts of the sample app proposed in tutorial should I upgrade first? Authentication method comes to mind first..

Given the huge popularity of that tutorial, I suppose there is something like a list of steps to be taken for that app to become more up-to-date in this ever changing world of web dev etc. etc. etc.

Overall is it a good idea to use that app as a foundation for building something more advanced?

Thanks in advance!

答:
I learned Rails with that book :)
However, even the authentication algorithm used there is great to learn, in practice you can use other alternatives. For example I use the wonderful Devise gem (Railscasts 209 and 210).

There are some ideas at the end of the book that explain how you can extend the application. However, I think that building your own app from scratch is better now that you know how to do it.

After reading that book, I created some basic projects, and in parallel started reading The Ruby Programming Language and The Rails 3 Way.

Hope it helps! Welcome to the Rails world :)