问:
How to identify the sender of an event
I have a to-do software application in which I dynamically create each to-do task. I have a checkmark image on each task that when clicked, calls a MouseLeftButtonDown event. It works perfectly fine, but I need to identify which task I clicked on. Here's how I'm doing it so far:

```<code>private void CreateTask() {
    Image checkmarkImage = new Image();
    checkmarkImage.MouseLeftButtonDown += checkmarkPressed;
}
private void CheckmarkPressed(object sender, MouseButtonEventArgs e) {
    Console.WriteLine("Pressed");
}
</code>```

Whenever the image is clicked on, the console writes "Pressed". Is there any way for me to identify which specific object called the function? It would be great if I could pass arguments to the CheckmarkPressed function like an integer; tasksAdded that could identify the specific task from any array. Anyone know how I can do this?

I tried things like sender.ToString() or e.Source but those just tell me that the sender was an image.

答:
Assuming your are using the event handler CheckmarkPressed to be called only by the same type of objects, and that you are setting a unique identifier to recognize your objects, like @Ostas mentioned in his comment, you may use the property Tag for this purpose image.Tag = "checkbox" + tasksAdded (Quoted from your comment):

```<code>private void CheckmarkPressed(object sender, MouseButtonEventArgs e) {
    var caller = (Image) sender;
    Console.WriteLine("Pressed by{0}",caller.Tag);
}
</code>```

Title: How to identify the sender of an event

Body:
I have a to-do software application in which I dynamically create each to-do task. I have a checkmark image on each task that when clicked, calls a MouseLeftButtonDown event. It works perfectly fine, but I need to identify which task I clicked on. Here's how I'm doing it so far:

private void CreateTask() {
    Image checkmarkImage = new Image();
    checkmarkImage.MouseLeftButtonDown += checkmarkPressed;
}
private void CheckmarkPressed(object sender, MouseButtonEventArgs e) {
    Console.WriteLine("Pressed");
}

Whenever the image is clicked on, the console writes "Pressed". Is there any way for me to identify which specific object called the function? It would be great if I could pass arguments to the CheckmarkPressed function like an integer; tasksAdded that could identify the specific task from any array. Anyone know how I can do this?

I tried things like sender.ToString() or e.Source but those just tell me that the sender was an image.

Body:
Assuming your are using the event handler CheckmarkPressed to be called only by the same type of objects, and that you are setting a unique identifier to recognize your objects, like @Ostas mentioned in his comment, you may use the property Tag for this purpose image.Tag = "checkbox" + tasksAdded (Quoted from your comment):

private void CheckmarkPressed(object sender, MouseButtonEventArgs e) {
    var caller = (Image) sender;
    Console.WriteLine("Pressed by{0}",caller.Tag);
}


来源: stackexchange

问:
iOS flip tableview and UIView
So what I want to do is, I want to flip a tableview and reveal a normal UIView under it, and vise versa. How can I achieve this? Thanks!</p>

答:
If you want to control the UITableView and the UIView on the back with the same UIViewController (sounds like this might be your case given that your tableview doesn't fill the entire screen), you can simply do a view transition between the two views using transitionFromView:toView:duration:options:completion: in UIView.

The fromView is your tableview, which should already be part of the view hierarchy. The toView is your UIView to be displayed on the back of the tableview. It should be detached from the view hierarchy (no superview) before calling transitionFromView.

ContentLicense: CC BY-SA 3.0

Title: iOS flip tableview and UIView


问:
C# Null propagating operator / Conditional access expression & if blocks
The Null propagating operator / Conditional access expression coming in c#-6.0 looks like quite a handy feature.  But I'm curious if it will help solve the problem of checking if a child member is not null and then calling a Boolean method on said child member inside an if block:

```<code>  public class Container<int>{
       IEnumerable<int> Objects {get;set;}
  }

  public Container BuildContainer()
  {
      var c = new Container();

      if (/* Some Random Condition */)
         c.Objects = new List<int>{1,2,4};
  }

  public void Test()
  {
      var c = BuildContainer();

      //Old way
      if ( null != c && null != c.Objects && c.Objects.Any())
         Console.Write("Container has items!");

      //C# 6 way?
      if (c?.Object?.Any())
          Console.Write("Container has items!");
  }
</code>```

Will c?.Object?.Any() compile?  If the propagating operator short circuits (I assume that's the right term) to null then you have if (null), which isn't valid.

Will the C# team address this concern or am I missing the intended use case for the null propagating operator?

答:
var x = c?.Objects?.Any() is going to give you a nullable boolean, and as others have said, this means you can use an equality operator like this

```<code>x == true
</code>```

or you can use null coalescing like this to have your result not be nullable

```<code>var x = c?.Objects?.Any() ?? false
</code>```

But, personally, I think that 3-state (nullable) booleans are code smell. Even if this one is practically invisible, its existence should encourage you to think about what you are actually trying to do and determine if a nullable boolean is actually the way to go. In this case, I think that what you really want to do is something like this -

```<code>var objects = c?.Objects ?? Enumerable.Empty<Object>();
if (objects.Any())
{
 ...
}
</code>```

Put that in an extension method and it will be even more succinct -

```<code>public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
{
   return !(collection ?? Enumerable.Empty<T>()).Any()
}
</code>```

Body:
The Null propagating operator / Conditional access expression coming in c#-6.0 looks like quite a handy feature.  But I'm curious if it will help solve the problem of checking if a child member is not null and then calling a Boolean method on said child member inside an if block:

  public class Container<int>{
       IEnumerable<int> Objects {get;set;}
  }

  public Container BuildContainer()
  {
      var c = new Container();

      if (/* Some Random Condition */)
         c.Objects = new List<int>{1,2,4};
  }

  public void Test()
  {
      var c = BuildContainer();

      //Old way
      if ( null != c && null != c.Objects && c.Objects.Any())
         Console.Write("Container has items!");

      //C# 6 way?
      if (c?.Object?.Any())
          Console.Write("Container has items!");
  }

Will c?.Object?.Any() compile?  If the propagating operator short circuits (I assume that's the right term) to null then you have if (null), which isn't valid.

Will the C# team address this concern or am I missing the intended use case for the null propagating operator?

Body:
var x = c?.Objects?.Any() is going to give you a nullable boolean, and as others have said, this means you can use an equality operator like this

x == true

or you can use null coalescing like this to have your result not be nullable

var x = c?.Objects?.Any() ?? false

But, personally, I think that 3-state (nullable) booleans are code smell. Even if this one is practically invisible, its existence should encourage you to think about what you are actually trying to do and determine if a nullable boolean is actually the way to go. In this case, I think that what you really want to do is something like this -

var objects = c?.Objects ?? Enumerable.Empty<Object>();
if (objects.Any())
{
 ...
}

Put that in an extension method and it will be even more succinct -

public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
{
   return !(collection ?? Enumerable.Empty<T>()).Any()
}

ContentLicense: CC BY-SA 4.0


问:
How is 'Inbound NAT rules' different from 'Load Balancing Rules' different from each other in Azure Load Balancer v2
Can someone explain to me what actually happens in the back-end to the load balancer (v2) for the two scenarios:

Applying Inbound NAT rules.

Applying Load Balancing Rules.

答:
this documentation link will help: https://learn.microsoft.com/en-us/azure/load-balancer/components#inbound-nat-rules

We added examples to help clarify. You can think of inbound NAT rules as a special type of Load Balancing rules to reference specific VMs.

-- Anavi N
Senior PM load, Azure Load Balancer


问:
How to correctly implement Web Crypto API generateKey and exportKey?
Hello everyone!

I have this code:

```<code>async function generateKey() {
  const algoritm = { name: "AES-CBC", length: 256 };
  const exportable = true;
  const usage = ['encrypt'];
  return await window.crypto.subtle.generateKey(algoritm, exportable, usage).then(key => { return key;
  });
}
</code>```

when I call console.log(generateKey ()); I get: >Promise at first load and >Promise {<pending>} when update browser window.

```<code>async function exportKey(key) {
  const format = "jwk";
  return await window.crypto.subtle.exportKey(format, key).then(key => { return key; });
}
</code>```

when I call let key =generateKey(); console.log(exportKey (key)); I get:  'SubtleCrypto': parameter 2 is not of type 'CryptoKey'.

I have two questions about

What is the correct way to generate a key with the given parameters?

What is the correct way to export a generated key in JSON format?

I come read from: SubtleCrypto MDN Web Docs

答:
Your API usage looks correct. You are getting the error 'SubtleCrypto': parameter 2 is not of type 'CryptoKey' because parameter 2 is of type Promise. To fix this issue, resolve the promise from generateKey before passing it to exportKey

const main = async () => {
  const key = await generateKey()
  const exported = await exportKey(key)
  console.log(exported)
}
```

<p>Of course, this can get even simpler if you use my library, rubico</p>

<pre class="lang-js prettyprint-override"><code>const { pipe } = require('rubico')

const main = pipe([generateKey, exportKey, console.log])
</code>```

The two examples are equivalent.

Body:
Hello everyone!

I have this code:

async function generateKey() {
  const algoritm = { name: "AES-CBC", length: 256 };
  const exportable = true;
  const usage = ['encrypt'];
  return await window.crypto.subtle.generateKey(algoritm, exportable, usage).then(key => { return key;
  });
}

when I call console.log(generateKey ()); I get: >Promise at first load and >Promise {<pending>} when update browser window.

async function exportKey(key) {
  const format = "jwk";
  return await window.crypto.subtle.exportKey(format, key).then(key => { return key; });
}

when I call let key =generateKey(); console.log(exportKey (key)); I get:  'SubtleCrypto': parameter 2 is not of type 'CryptoKey'.

I have two questions about

What is the correct way to generate a key with the given parameters?

What is the correct way to export a generated key in JSON format?

I come read from: SubtleCrypto MDN Web Docs

Body:
Your API usage looks correct. You are getting the error 'SubtleCrypto': parameter 2 is not of type 'CryptoKey' because parameter 2 is of type Promise. To fix this issue, resolve the promise from generateKey before passing it to exportKey

const main = async () => {
  const key = await generateKey()
  const exported = await exportKey(key)
  console.log(exported)
}

Of course, this can get even simpler if you use my library, rubico

const { pipe } = require('rubico')

const main = pipe([generateKey, exportKey, console.log])

The two examples are equivalent.


问:
Filter Array of cookies for a specific cookie and get value of a specific cookie in Java
I am fixing some issue in a legacy module and came across this code which get the array of cookies from request object which can return null. The code looks for a specific cookie, if present then returns cookie value otherwise it returns null. Below is the existing code

final Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (int i = 0; i < cookies.length; i++) {
        final Cookie cookie = cookies[i];
        if ("random cookie".equals(cookie.getName())) {
            return cookie.getValue();
        }
    }
    return null;
}
```

<p>I refactored it to something like this</p>

<pre class="lang-java prettyprint-override"><code>final Cookie[] cookies = request.getCookies();
if (cookies != null) {
    Optional<Cookie> cookie = Arrays.stream(cookies).
            filter(e -> "random cookie".equals(e.getName())).
            findAny();
    return cookie.isPresent() ? cookie.get().getValue() : null;
}
return null;
</code>```

Can the above be refactored in a better way?

答:
I would refactor this into a method which returns Optional<String>:

```<code>public Optional<String> getCookieValue(String name) {
   final Cookie[] cookies = request.getCookies();
   if(cookies == null) return Optional.empty();
   return Arrays.stream(cookies)
                .filter(e -> name.equals(e.getName()))
                .findAny().map(Cookie::getValue);
}
</code>```

then the caller of this method would do any of these depending on how they intend to use the result:

```<code>getCookieValue("random cookie").ifPresent(e -> { ... });
getCookieValue("random cookie").orElse(null);
....
....
</code>```

return Optional<String> to avoid dealing with nullity and let the user of this method decide what to do in the "no value case". This also reads better to the user of this API etc....

However, if you wish to persist with your current method signature then you can at least improve it to:

```<code>final Cookie[] cookies = request.getCookies();
if(cookies == null) return null; // avoids if blocks
return Arrays.stream(cookies)
             .filter(e -> "random cookie".equals(e.getName()))
             .findAny()
             .map(Cookie::getValue)
             .orElse(null);
</code>```

Body:
I am fixing some issue in a legacy module and came across this code which get the array of cookies from request object which can return null. The code looks for a specific cookie, if present then returns cookie value otherwise it returns null. Below is the existing code

final Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (int i = 0; i < cookies.length; i++) {
        final Cookie cookie = cookies[i];
        if ("random cookie".equals(cookie.getName())) {
            return cookie.getValue();
        }
    }
    return null;
}

I refactored it to something like this

final Cookie[] cookies = request.getCookies();
if (cookies != null) {
    Optional<Cookie> cookie = Arrays.stream(cookies).
            filter(e -> "random cookie".equals(e.getName())).
            findAny();
    return cookie.isPresent() ? cookie.get().getValue() : null;
}
return null;

Can the above be refactored in a better way?

Body:
I would refactor this into a method which returns Optional<String>:

public Optional<String> getCookieValue(String name) {
   final Cookie[] cookies = request.getCookies();
   if(cookies == null) return Optional.empty();
   return Arrays.stream(cookies)
                .filter(e -> name.equals(e.getName()))
                .findAny().map(Cookie::getValue);
}

then the caller of this method would do any of these depending on how they intend to use the result:

getCookieValue("random cookie").ifPresent(e -> { ... });
getCookieValue("random cookie").orElse(null);
....
....

return Optional<String> to avoid dealing with nullity and let the user of this method decide what to do in the "no value case". This also reads better to the user of this API etc....

However, if you wish to persist with your current method signature then you can at least improve it to:

final Cookie[] cookies = request.getCookies();
if(cookies == null) return null; // avoids if blocks
return Arrays.stream(cookies)
             .filter(e -> "random cookie".equals(e.getName()))
             .findAny()
             .map(Cookie::getValue)
             .orElse(null);


问:
PostgreSQL 9.4 suddenly invalid memory alloc request size
I'm building a website which will be used to handle excel files from stores and manipulate them (merging, view, etc.). I'm using PostgreSQL 9.4 for the database, running on Centos 6.6 VM with 4GB RAM. It has 3 databases as follow:

postgres database

db_raw, which is used as a placeholder for the data. The excel which are uploaded from the website will be parsed, and the data will be stored here. The database consists of few tables used to keep the data required to process the excel, and a huge table for storing the excel data with currently >140 column and almost 1 million row

db_processed, which is the main database for the website. It has few small tables for the operational of the website (user table, access list, logging, etc), and 8 tables to store the processed excel data from db_raw. Each of the 8 tables have around 40 column and about a million row.

The databases were running fine until this morning. I tried connecting to the db_processed through pgAdmin and PuTTY, and PostgreSQL gave me this message

```<code>FATAL:  invalid memory alloc request size 144115188075856068
</code>```

db_raw works fine, and nothing has been changed since 3 days ago as far as I know. What should I do so I can connect to the database again?

update : I did what @CraigRinger said and restarted the service. I manage to connect to the database, but all the tables are gone :| now this keeps appearing in the log

```<code>< 2015-09-21 12:27:22.155 WIB >DEBUG:  performing replication slot checkpoint
< 2015-09-21 12:27:22.158 WIB >LOG:  request to flush past end of generated WAL; request 46/9E0981D8, currpos 46/771C69B0
< 2015-09-21 12:27:22.158 WIB >CONTEXT:  writing block 2 of relation base/18774/12766
< 2015-09-21 12:27:22.158 WIB >ERROR:  xlog flush request 46/9E0981D8 is not satisfied --- flushed only to 46/771C69B0
< 2015-09-21 12:27:22.158 WIB >CONTEXT:  writing block 2 of relation base/18774/12766
< 2015-09-21 12:27:22.158 WIB >WARNING:  could not write block 2 of base/18774/12766
< 2015-09-21 12:27:22.158 WIB >DETAIL:  Multiple failures --- write error might be permanent.
</code>```

答:
It is caused by corrupted rows.

Create a function do "detect" the rows that are corrupted:

```<code>CREATE OR REPLACE FUNCTION is_bad_row(tableName TEXT, tabName TEXT, tidInitial tid)
RETURNS integer
as $find_bad_row$
BEGIN
    EXECUTE 'SELECT (each(hstore(' || tabName || '))).* FROM ' || tableName || ' WHERE ctid = $1' USING tidInitial;
    RETURN 0;
    EXCEPTION
        WHEN OTHERS THEN
        RAISE NOTICE '% = %: %', tidInitial, SQLSTATE, SQLERRM;
        RETURN 1;
END
$find_bad_row$
LANGUAGE plpgsql;
</code>```

... and then create a "temp table" to store the ctid of the bad rows:

```<code>create table bad_rows as
SELECT ctid as row_tid
FROM your_schema.your_table
where is_bad_row('your_schema.your_table', 'your_table', ctid) = 1
</code>```

... and after that you just need to delete those rows:

```<code>delete from your_schema.your_table where ctid in (select row_tid from bad_rows)
</code>```

... and remove the "temp table":

```<code>drop table bad_rows
</code>```

Body:
I'm building a website which will be used to handle excel files from stores and manipulate them (merging, view, etc.). I'm using PostgreSQL 9.4 for the database, running on Centos 6.6 VM with 4GB RAM. It has 3 databases as follow:

postgres database

db_raw, which is used as a placeholder for the data. The excel which are uploaded from the website will be parsed, and the data will be stored here. The database consists of few tables used to keep the data required to process the excel, and a huge table for storing the excel data with currently >140 column and almost 1 million row

db_processed, which is the main database for the website. It has few small tables for the operational of the website (user table, access list, logging, etc), and 8 tables to store the processed excel data from db_raw. Each of the 8 tables have around 40 column and about a million row.

The databases were running fine until this morning. I tried connecting to the db_processed through pgAdmin and PuTTY, and PostgreSQL gave me this message

FATAL:  invalid memory alloc request size 144115188075856068

db_raw works fine, and nothing has been changed since 3 days ago as far as I know. What should I do so I can connect to the database again?

update : I did what @CraigRinger said and restarted the service. I manage to connect to the database, but all the tables are gone :| now this keeps appearing in the log

< 2015-09-21 12:27:22.155 WIB >DEBUG:  performing replication slot checkpoint
< 2015-09-21 12:27:22.158 WIB >LOG:  request to flush past end of generated WAL; request 46/9E0981D8, currpos 46/771C69B0
< 2015-09-21 12:27:22.158 WIB >CONTEXT:  writing block 2 of relation base/18774/12766
< 2015-09-21 12:27:22.158 WIB >ERROR:  xlog flush request 46/9E0981D8 is not satisfied --- flushed only to 46/771C69B0
< 2015-09-21 12:27:22.158 WIB >CONTEXT:  writing block 2 of relation base/18774/12766
< 2015-09-21 12:27:22.158 WIB >WARNING:  could not write block 2 of base/18774/12766
< 2015-09-21 12:27:22.158 WIB >DETAIL:  Multiple failures --- write error might be permanent.

Body:
It is caused by corrupted rows.

Create a function do "detect" the rows that are corrupted:

CREATE OR REPLACE FUNCTION is_bad_row(tableName TEXT, tabName TEXT, tidInitial tid)
RETURNS integer
as $find_bad_row$
BEGIN
    EXECUTE 'SELECT (each(hstore(' || tabName || '))).* FROM ' || tableName || ' WHERE ctid = $1' USING tidInitial;
    RETURN 0;
    EXCEPTION
        WHEN OTHERS THEN
        RAISE NOTICE '% = %: %', tidInitial, SQLSTATE, SQLERRM;
        RETURN 1;
END
$find_bad_row$
LANGUAGE plpgsql;

... and then create a "temp table" to store the ctid of the bad rows:

create table bad_rows as
SELECT ctid as row_tid
FROM your_schema.your_table
where is_bad_row('your_schema.your_table', 'your_table', ctid) = 1

... and after that you just need to delete those rows:

delete from your_schema.your_table where ctid in (select row_tid from bad_rows)

... and remove the "temp table":

drop table bad_rows


问:
Display information according to the <selected> location
I'm trying to make like a simple printer manager so i will be able to see all of my printers statuses so far i have managed to display all the data now i want to organize it by location and the error i'm getting is: Cannot read property 'Location' of undefined maybe the reason is that  [(ngModel)] that it is not working properly i think
thank you.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';
import { Values } from '../Models/Values';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  selectedPrinter: Values;
  values: any;

  constructor(private http: HttpClient, public sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.getValues();

  }

  getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = response;
    }, error => {
      console.log(error);
    })
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><H2>Print Manager</H2>

<div id="selectCompanyDiv">

  <div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
    <label for="">Select location</label>
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " [ngValue]="each">{{each.location}}</option>
    </select>

  </div>

  <br>
  <br>

  <div>
    <div *ngFor="let value of values" id="mainDiv">
      <!-- <p>{{value.id}},{{value.hostName}},{{value.location}},{{value.manufacturer}},{{value.ip}}</p> -->

      <span>Hostname: {{value.hostName}}</span>
      <br>
      <span>Location: {{value.location}}</span>
      <br>
      <span>Manufacturer: {{value.manufacturer}}</span>
      <br>
      <span>IP: {{value.ip}}</span>
      <br>
      <h2>{{value.location}}</h2>

      <div>

        <div *ngIf="value.hostName==='BROTHERJ480'" class="outerFrame">
          <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframej480" scrolling="no"></iframe>
        </div>

        <div *ngIf="value.hostName==='Brother6530DW'" class="outerFrame">
          <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrother6530DW" scrolling="no"></iframe>
        </div>

      </div>

    </div></code>```

答: You can obtain the selected value, at the time of selection using ngModelChange event and can perform the desired functionality (based on the selected Printer value). If this is not the issue, please elaborate the issue.

Body:
I'm trying to make like a simple printer manager so i will be able to see all of my printers statuses so far i have managed to display all the data now i want to organize it by location and the error i'm getting is: Cannot read property 'Location' of undefined maybe the reason is that  [(ngModel)] that it is not working properly i think
thank you.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';
import { Values } from '../Models/Values';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  selectedPrinter: Values;
  values: any;

  constructor(private http: HttpClient, public sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.getValues();

  }

  getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = response;
    }, error => {
      console.log(error);
    })
  }

}

Print Manager

    Select location
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " [ngValue]="each">{{each.location}}</option>
    </select>

      Hostname: {{value.hostName}}

      Location: {{value.location}}

      Manufacturer: {{value.manufacturer}}

      IP: {{value.ip}}

{{value.location}}


问:
How can I get an updated $Revision$ in my code
I have a project into which I'd like to embed the revision number automagically.

In this case, it's a multi-file perl script. In the main file, I have a line that looks like this:

my $revision = '$Revision: 24 $';

When I make a release, I checkout the project to my release dir.

The revision number does change whenever I check-in a change to THAT FILE. The $Revision$ attribute is updated on check-in, but not check-out.

The thing is, the main file doesn't change that often, so even though the other files in the project are now at 27, the main still has 24.

Is there a way that I can get the main file to reflect the latest rev number? The one that svn prints out at the end of the checkout, ie "Checked out revision 27."

答:
```<code>if (! -e '.version')
{
    open VERSION, '>.version';
    print VERSION `svnversion -n | cut -f1 -d:`;
    close VERSION;
}

my $revision = '$Revision: ' . `cat .version` . ' $';
</code>```

(Note: a puppy will die if you use this code as-is)

OwnerDisplayName: mmccoo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mmccoo

Body:
if (! -e '.version')
{
    open VERSION, '>.version';
    print VERSION `svnversion -n | cut -f1 -d:`;
    close VERSION;
}

my $revision = '$Revision: ' . `cat .version` . ' $';

(Note: a puppy will die if you use this code as-is)

OwnerDisplayName: Sean Bright


问:
Special characters is encoded when run script inside a file Powershell
Hi I have a script to automate some tasks, running in powershell core v.7.+.

In one of these scripts when I run the command inside the ps1 file and the special characters returned is encoded and I can't decode to right format, below the command used to do this and the return:

```<code>// the variable $script is my command its a ask-cli command to work in alexa
$model = pwsh -Command $script
/*
* when I running the script from here the special characters returned is these:
* "n├ñchste",
* "n├ñchstgelegene"
*/
</code>```

But when I run the same command directly in the terminal the strings returned are:

```<code>/*
* "nächste",
* "nächstgelegene"
*/
</code>```

I would like to know how can I run the command inside the file without encode the return.
I already tried some things as:

```<code>   $encoding = [System.Text.Encoding]::Unicode

    $model = pwsh -Command $script

    Write-Output $model

    $model = $encoding.GetBytes($model)

    $model = $encoding.GetString($model)
</code>```

But don't work as expected, I don't know more how I can to this, if someone could help me with this I appreciate too much.

答:
After many researches, I could find something more easiest to solve my problem.
Powershell has by default a different output encoder used in these cases, and the only thing I need to do it's change it.

I used the command:

```<code>$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
</code>```

I find this question explaining how this work and this help a lot, for more question please check this answer.

Body:
Hi I have a script to automate some tasks, running in powershell core v.7.+.

In one of these scripts when I run the command inside the ps1 file and the special characters returned is encoded and I can't decode to right format, below the command used to do this and the return:

// the variable $script is my command its a ask-cli command to work in alexa
$model = pwsh -Command $script
/*
* when I running the script from here the special characters returned is these:
* "n├ñchste",
* "n├ñchstgelegene"
*/

But when I run the same command directly in the terminal the strings returned are:

/*
* "nächste",
* "nächstgelegene"
*/

I would like to know how can I run the command inside the file without encode the return.
I already tried some things as:

   $encoding = [System.Text.Encoding]::Unicode

    $model = pwsh -Command $script

    Write-Output $model

    $model = $encoding.GetBytes($model)

    $model = $encoding.GetString($model)

But don't work as expected, I don't know more how I can to this, if someone could help me with this I appreciate too much.

Body:
After many researches, I could find something more easiest to solve my problem.
Powershell has by default a different output encoder used in these cases, and the only thing I need to do it's change it.

I used the command:

$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding

I find this question explaining how this work and this help a lot, for more question please check this answer.


问:
Can we install Business Central Workbench 7.36 on TomcatServer?
Can we install the business central workbench  7.36 on the tomcat server. In the documentation , only the wars related to the wildfly server are present.

https://www.drools.org/download/download.html

Business Central Workbench

Business Central Workbench is the web application and repository to govern Drools and jBPM assets. See documentation for details about installation.

WildFly 14 WAR

Can you point me to the tomcat installation version of it

答:
It only refers to the wildfly or jboss eap servers. It doesnt show the war file for installing it on tomcat server.

Business Central (General)
11.1. Installation
11.1.1. War installation
Use the war from the Business Central distribution zip that corresponds to your application server. The differences between these war files are mainly superficial. For example, some JARs might be excluded if the application server already supplies them.

eap7: tailored for Red Hat JBoss Enterprise Application Platform 7

wildfly14: tailored for Wildfly 14


问:
Need to update products quantity to zero after stripe checkout and webhook hits in rails 6
I am putting together a site for an artist to sell their art pieces.  It uses stripe checkout for payments.  I've got the checkout and webhook set up and I need to update the product's quantity to 0 once the webhook hits and the checkout session is completed.

Here is the checkout controller(think of piece as product)

```<code>class CheckoutController < ApplicationController

  def create
    piece = Piece.find(params[:id])

    if piece.nil?
      redirect_to root_path
      return
    end

    @session = Stripe::Checkout::Session.create(
      payment_method_types: [:card],
      line_items: [{
        name: piece.name,
        description: piece.description,
        amount: (piece.price*100).to_i,
        currency: 'usd',
        quantity: 1
      }],
      shipping_address_collection: {
        allowed_countries: ['US', 'CA'],
      },
      success_url: checkout_success_url,
      cancel_url: checkout_cancel_url
      )

    respond_to do |format|
      format.js
    end

  end

  def success

  end

  def cancel

  end

end
</code>```

Here is the webhook events controller

```<code>class WebhookEventsController < ApplicationController
  # ignore CSRF
  skip_before_action :verify_authenticity_token

  def create

    if !valid_signatures?
      render json: { message: "Invalid sigs"}, status: 400
      return
    end

    # idempotent
    if !WebhookEvent.find_by(source: params[:source], external_id: external_id).nil?
      render json: { message: "Already Processed #{ external_id }"}
      return
    end

    event = WebhookEvent.create(webhook_params)
    ProcessEventsJob.perform_later(event.id)
    render json: params

  end

  def valid_signatures?
    if params[:source] == 'stripe'
      begin
        wh_secret = Rails.application.credentials.dig(:stripe, :wh)
        Stripe::Webhook.construct_event(
          request.body.read,
          request.env["HTTP_STRIPE_SIGNATURE" ],
          wh_secret
        )
      rescue Stripe::SignatureVerificationError => e
        return false
      end
    end
    true
  end

  def external_id
    return params[:id] if params[:source] == 'stripe'

    SecureRandom.hex
  end

  def webhook_params
    {
      source: params[:source],
      data: params.except(:source, :action, :controller).permit!,
      external_id: external_id
    }
  end
end
</code>```

Here is the stripe handler where I believe the code to update the piece quantity should go

```<code>module Events
  class StripeHandler
    def self.process(event)
      stripe_event = Stripe::Event.construct_from(event.data)

      case stripe_event.type
      when 'checkout.session.completed'
        checkout_session = stripe_event.data.object
        # now can do #{ checkout_session.customer }.. or some attribute of checkout_session object
        puts "*** Do things here i.e. logic for emails/inventory management"

      end
    end
  end
end
</code>```

All this so I can basically disable the purchase button on the art piece.

答:
A couple notes here:

You might want to set client_reference_id to the Piece's ID, which makes reconciling this easier: https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-client_reference_id

You need to either inspect the line_items on the completed session or use client_reference_id to find the item your customer purchased after the session is completed.

Your controller logic looks correct so far. You'll need a quantity field on Piece. I'm assuming you pass {client_reference_id: piece.id} in your CheckoutSession creation. With that assumption, your webhook handling logic looks like this:

module Events
  class StripeHandler
    def self.process(event)
      stripe_event = Stripe::Event.construct_from(event.data)

      case stripe_event.type

      when 'checkout.session.completed'
        Piece.transaction do
          piece = Piece.find(id: checkout.client_reference_id)
          raise Exception.new("item already purchased!") if piece.quantity == 0
          piece.quantity = 0
          piece.save!
        end
      end
    end
  end
end
```

This implements a simple "first person to pay wins" scenario, so the first person who goes through Checkout for a given Piece, pays, and whose checkout.session.completed webhook gets sent to your application & processed first will get the Piece. If two people pay at the same time, only one can get the Piece, so you may want to do something like refund the customer automatically & send them an email.

I used a database transaction to update the Piece so that if two customers somehow pay at the exact same time, we will not accidentally give both customers the Piece.

Body:
I am putting together a site for an artist to sell their art pieces.  It uses stripe checkout for payments.  I've got the checkout and webhook set up and I need to update the product's quantity to 0 once the webhook hits and the checkout session is completed.

Here is the checkout controller(think of piece as product)

class CheckoutController < ApplicationController

  def create
    piece = Piece.find(params[:id])

    if piece.nil?
      redirect_to root_path
      return
    end

    @session = Stripe::Checkout::Session.create(
      payment_method_types: [:card],
      line_items: [{
        name: piece.name,
        description: piece.description,
        amount: (piece.price*100).to_i,
        currency: 'usd',
        quantity: 1
      }],
      shipping_address_collection: {
        allowed_countries: ['US', 'CA'],
      },
      success_url: checkout_success_url,
      cancel_url: checkout_cancel_url
      )

    respond_to do |format|
      format.js
    end

  end

  def success

  end

  def cancel

  end

end

Here is the webhook events controller

class WebhookEventsController < ApplicationController
  # ignore CSRF
  skip_before_action :verify_authenticity_token

  def create

    if !valid_signatures?
      render json: { message: "Invalid sigs"}, status: 400
      return
    end

    # idempotent
    if !WebhookEvent.find_by(source: params[:source], external_id: external_id).nil?
      render json: { message: "Already Processed #{ external_id }"}
      return
    end

    event = WebhookEvent.create(webhook_params)
    ProcessEventsJob.perform_later(event.id)
    render json: params

  end

  def valid_signatures?
    if params[:source] == 'stripe'
      begin
        wh_secret = Rails.application.credentials.dig(:stripe, :wh)
        Stripe::Webhook.construct_event(
          request.body.read,
          request.env["HTTP_STRIPE_SIGNATURE" ],
          wh_secret
        )
      rescue Stripe::SignatureVerificationError => e
        return false
      end
    end
    true
  end

  def external_id
    return params[:id] if params[:source] == 'stripe'

    SecureRandom.hex
  end

  def webhook_params
    {
      source: params[:source],
      data: params.except(:source, :action, :controller).permit!,
      external_id: external_id
    }
  end
end

Here is the stripe handler where I believe the code to update the piece quantity should go

module Events
  class StripeHandler
    def self.process(event)
      stripe_event = Stripe::Event.construct_from(event.data)

      case stripe_event.type
      when 'checkout.session.completed'
        checkout_session = stripe_event.data.object
        # now can do #{ checkout_session.customer }.. or some attribute of checkout_session object
        puts "*** Do things here i.e. logic for emails/inventory management"

      end
    end
  end
end

All this so I can basically disable the purchase button on the art piece.

Body:
A couple notes here:

You might want to set client_reference_id to the Piece's ID, which makes reconciling this easier: https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-client_reference_id

You need to either inspect the line_items on the completed session or use client_reference_id to find the item your customer purchased after the session is completed.

Your controller logic looks correct so far. You'll need a quantity field on Piece. I'm assuming you pass {client_reference_id: piece.id} in your CheckoutSession creation. With that assumption, your webhook handling logic looks like this:

module Events
  class StripeHandler
    def self.process(event)
      stripe_event = Stripe::Event.construct_from(event.data)

      case stripe_event.type

      when 'checkout.session.completed'
        Piece.transaction do
          piece = Piece.find(id: checkout.client_reference_id)
          raise Exception.new("item already purchased!") if piece.quantity == 0
          piece.quantity = 0
          piece.save!
        end
      end
    end
  end
end

This implements a simple "first person to pay wins" scenario, so the first person who goes through Checkout for a given Piece, pays, and whose checkout.session.completed webhook gets sent to your application & processed first will get the Piece. If two people pay at the same time, only one can get the Piece, so you may want to do something like refund the customer automatically & send them an email.

I used a database transaction to update the Piece so that if two customers somehow pay at the exact same time, we will not accidentally give both customers the Piece.


答:
It would be best to make the method return Optional<String> - but if you can't then how about this:

final Cookie[] maybeCookies = request.getCookies();
return Optional.ofNullable(maybeCookies)
    .flatMap(cookies -> Arrays.stream(cookies)
         //Find the cookie if we can.
         .filter(e->"random cookie".equals(cookie.getName()))
         .findAny()
    )
    //If we have a matching cookie, return its value.
    .map(e->e.getValue())
    //otherwise return null to retain original behaviour
    .orElse(null);
```

Title: Filter Array of cookies for a specific cookie and get value of a specific cookie in Java


问:
How to add mappings by namespace in Fluent NHibernate
In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way.

The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings:

```<code>    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>())
    .Mappings(m => m.FluentMappings.Add<UserClassMap>()
</code>```

If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace(). Is there a way to do this?

答:
I wound up writing an extension method that does this for me. Basically it uses reflection to iterate over all the types I'm interested in, and add them one-by-one. It is based on the implementation of AddFromAssemblyOf. Usage:

```<code>.Mappings(m => m.FluentMappings.AddFromNamespaceOf<UserClassMap>())
</code>```

Implementation:

```<code>public static class FluentNHibernateExtensions
{
    public static FluentMappingsContainer AddFromNamespaceOf<T>(
        this FluentMappingsContainer fmc)
    {
        string ns = typeof(T).Namespace;
        IEnumerable<Type> types = typeof(T).Assembly.GetExportedTypes()
            .Where(t => t.Namespace == ns)
            .Where(x => IsMappingOf<IMappingProvider>(x) ||
                        IsMappingOf<IIndeterminateSubclassMappingProvider>(x) ||
                        IsMappingOf<IExternalComponentMappingProvider>(x) ||
                        IsMappingOf<IFilterDefinition>(x));

        foreach(Type t in types) {
            fmc.Add(t);
        }

        return fmc;
    }

    /// <summary>
    /// Private helper method cribbed from FNH source (PersistenModel.cs:151)
    /// </summary>
    private static bool IsMappingOf<T>(Type type)
    {
        return !type.IsGenericType && typeof(T).IsAssignableFrom(type);
    }
}
</code>```

Caveats:

The name is a little misleading, since it only searches one assembly. It should perhaps be called AddFromAssemblyAndNamespaceOf, but that's a little verbose.

It is not entirely future-proof. If future versions of FNH add or remove some of the mappable interfaces, it wouldn't include them.

But it works for my purposes.

Body:
In my application, I need to talk to multiple databases. I am handling this in NHibernate by creating one SessionFactory per database (I assume this is the correct thing to do). So I have two sets of models (one per database), and two sets of Fluent NHibernate ClassMap<> mappings. Both are in the same project (separated by namespace) and I'd like to keep it that way.

The problem comes when creating the SessionFactory. As far as I can see, Fluent NHibernate has basically two methods for adding mappings:

    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserClassMap>())
    .Mappings(m => m.FluentMappings.Add<UserClassMap>()

If I use the first overload, then my session factories get all the mappings for both databases. If I use the second, I have to specify each individual ClassMap. I'd like something like FluentMappings.AddFromNamespace(). Is there a way to do this?

Body:
I wound up writing an extension method that does this for me. Basically it uses reflection to iterate over all the types I'm interested in, and add them one-by-one. It is based on the implementation of AddFromAssemblyOf. Usage:

.Mappings(m => m.FluentMappings.AddFromNamespaceOf<UserClassMap>())

Implementation:

public static class FluentNHibernateExtensions
{
    public static FluentMappingsContainer AddFromNamespaceOf<T>(
        this FluentMappingsContainer fmc)
    {
        string ns = typeof(T).Namespace;
        IEnumerable<Type> types = typeof(T).Assembly.GetExportedTypes()
            .Where(t => t.Namespace == ns)
            .Where(x => IsMappingOf<IMappingProvider>(x) ||
                        IsMappingOf<IIndeterminateSubclassMappingProvider>(x) ||
                        IsMappingOf<IExternalComponentMappingProvider>(x) ||
                        IsMappingOf<IFilterDefinition>(x));

        foreach(Type t in types) {
            fmc.Add(t);
        }

        return fmc;
    }

    /// <summary>
    /// Private helper method cribbed from FNH source (PersistenModel.cs:151)
    /// </summary>
    private static bool IsMappingOf<T>(Type type)
    {
        return !type.IsGenericType && typeof(T).IsAssignableFrom(type);
    }
}

Caveats:

The name is a little misleading, since it only searches one assembly. It should perhaps be called AddFromAssemblyAndNamespaceOf, but that's a little verbose.

It is not entirely future-proof. If future versions of FNH add or remove some of the mappable interfaces, it wouldn't include them.

But it works for my purposes.


问:
Dynamic textinput inside Flatlist State update
From the sample code below i am trying to render textbox along with content inside Flatlist renderItem method and simultaneously trying to update textbox value.

Bad luck is on device after typing a single character, keyboard goes down.

Please find relevant Snack expo at : https://snack.expo.io/BJGMscqsS
Here is code :

```<code>import * as React from "react";
import {
  View,
  Text,
  FlatList,

  TextInput
} from "react-native";

export default class App extends React.Component {
  state = {
data: []
  };
  updateItem = async (index, innerindex, itemAttributeVal) => {
    console.log(index, innerindex, itemAttributeVal);
    console.log(this.state.data);
    let { data } = this.state;
    data[index][innerindex].Value = itemAttributeVal;
    this.setState({
      data
    });
    console.log("newtry", this.state.data);
  };
  componentDidMount = async () => {
const listdata =
  {
    totalRow: "2",
    coddindata: [
      {
        "SNo": "1",
        "Item": "10",
        "Material Code": "SERVICE LABOUR1",
        "Invoice Description": "Labour for Services1",
        "Invoice Item Amt": "765000.00",
        "Approved Quantity": "85",
      },
      {
        "SNo": "2",
        "Item": "20",
        "Material Code": "SERVICE LABOUR1",
        "Invoice Description": "Labour for Services2",
        "Invoice Item Amt": "810000.00",
        "Approved Quantity": "90",
      }
    ]
  }
;
const codingData = listdata.coddindata;
var finalarr = [];
var finalarr1 = [];
codingData.map(datavalue => {
  finalarr1 = [];
  Object.keys(datavalue).map((key, val) => {
    finalarr1.push({ Key: key, Value: datavalue[key] });
  });
  finalarr.push(finalarr1);
});
this.setState({
  data: [...this.state.data, ...finalarr],
  totalCount: listdata.totalRow
});
console.log(this.state.data);
  };

  render() {
return (
  <View style={{ flex: 1,padding: 20}}>
    <FlatList
      style={{ padding: 20 }}
      data={this.state.data}
      renderItem={({ item, index }) =>
        item.map((element, innerindex) => {
          // console.log(" innerindex  ",innerindex);
          const inputstateval = this.state.data[index][innerindex].Value;
          return (
            <View
              key={Math.random().toString()}
              style={{
                alignItems: "center",
                height: 30,
                justifyContent: "center",
                flexDirection: "row",
                lineHeight: 4
              }}
            >
              <View style={{ flex: 1, alignSelf: "stretch" }}>
                <Text>{element.Key}</Text>
              </View>
              {/* { element.Key != "total_amount" ? */}
              {element.Key !== "Approved Quantity" ? (
                <View
                  style={{ flex: 2, alignSelf: "stretch", marginTop: 3 }}
                >
                  <Text>{element.Value}</Text>
                </View>
              ) : (
                <View
                  style={{ flex: 2, alignSelf: "stretch", marginTop: 3 }}
                >
                  <TextInput
                    // defaultValue={element.Value}
                    placeholder={element.Key}
                    onChangeText={text => {
                      console.log("in onChangeText--- ");
                      this.updateItem(index, innerindex, text);
                    }}
                    value={this.state.data[index][innerindex].Value}
                    style={{
                      paddingTop: 1,
                      fontSize: 16,
                      borderWidth: 1,
                      height: 30,
                      marginTop: -6
                    }}
                  />
                </View>
              )}
            </View>
          );
        })
      }
      keyExtractor={item => Math.random().toString()}
    />
  </View>
);
  }
}
</code>```

答:
In your code, you just need to fix the lines 87, and 132 to something like this:

```<code>87: key={'key'}
132: keyExtractor={(item) => ''+item}
</code>```

So react knows that even after render, those text inputs are the same as the ones before the setState update.

Still, I cant manage to fix this same bug in my project.

Body:
From the sample code below i am trying to render textbox along with content inside Flatlist renderItem method and simultaneously trying to update textbox value.

Bad luck is on device after typing a single character, keyboard goes down.

Please find relevant Snack expo at : https://snack.expo.io/BJGMscqsS
Here is code :

import * as React from "react";
import {
  View,
  Text,
  FlatList,

  TextInput
} from "react-native";

export default class App extends React.Component {
  state = {
data: []
  };
  updateItem = async (index, innerindex, itemAttributeVal) => {
    console.log(index, innerindex, itemAttributeVal);
    console.log(this.state.data);
    let { data } = this.state;
    data[index][innerindex].Value = itemAttributeVal;
    this.setState({
      data
    });
    console.log("newtry", this.state.data);
  };
  componentDidMount = async () => {
const listdata =
  {
    totalRow: "2",
    coddindata: [
      {
        "SNo": "1",
        "Item": "10",
        "Material Code": "SERVICE LABOUR1",
        "Invoice Description": "Labour for Services1",
        "Invoice Item Amt": "765000.00",
        "Approved Quantity": "85",
      },
      {
        "SNo": "2",
        "Item": "20",
        "Material Code": "SERVICE LABOUR1",
        "Invoice Description": "Labour for Services2",
        "Invoice Item Amt": "810000.00",
        "Approved Quantity": "90",
      }
    ]
  }
;
const codingData = listdata.coddindata;
var finalarr = [];
var finalarr1 = [];
codingData.map(datavalue => {
  finalarr1 = [];
  Object.keys(datavalue).map((key, val) => {
    finalarr1.push({ Key: key, Value: datavalue[key] });
  });
  finalarr.push(finalarr1);
});
this.setState({
  data: [...this.state.data, ...finalarr],
  totalCount: listdata.totalRow
});
console.log(this.state.data);
  };

  render() {
return (
  <View style={{ flex: 1,padding: 20}}>
    <FlatList
      style={{ padding: 20 }}
      data={this.state.data}
      renderItem={({ item, index }) =>
        item.map((element, innerindex) => {
          // console.log(" innerindex  ",innerindex);
          const inputstateval = this.state.data[index][innerindex].Value;
          return (
            <View
              key={Math.random().toString()}
              style={{
                alignItems: "center",
                height: 30,
                justifyContent: "center",
                flexDirection: "row",
                lineHeight: 4
              }}
            >
              <View style={{ flex: 1, alignSelf: "stretch" }}>
                <Text>{element.Key}</Text>
              </View>
              {/* { element.Key != "total_amount" ? */}
              {element.Key !== "Approved Quantity" ? (
                <View
                  style={{ flex: 2, alignSelf: "stretch", marginTop: 3 }}
                >
                  <Text>{element.Value}</Text>
                </View>
              ) : (
                <View
                  style={{ flex: 2, alignSelf: "stretch", marginTop: 3 }}
                >
                  <TextInput
                    // defaultValue={element.Value}
                    placeholder={element.Key}
                    onChangeText={text => {
                      console.log("in onChangeText--- ");
                      this.updateItem(index, innerindex, text);
                    }}
                    value={this.state.data[index][innerindex].Value}
                    style={{
                      paddingTop: 1,
                      fontSize: 16,
                      borderWidth: 1,
                      height: 30,
                      marginTop: -6
                    }}
                  />
                </View>
              )}
            </View>
          );
        })
      }
      keyExtractor={item => Math.random().toString()}
    />
  </View>
);
  }
}

Body:
In your code, you just need to fix the lines 87, and 132 to something like this:

87: key={'key'}
132: keyExtractor={(item) => ''+item}

So react knows that even after render, those text inputs are the same as the ones before the setState update.

Still, I cant manage to fix this same bug in my project.


问:
Is there a way to only get files in a date range over FTP?
We have a sync process that is daily making sure we have all files from a remote SFTP but as time goes on, we're having to download all files just to check that we already file copies in the database by content hash.

Is there a way, let's say using SSH.NET or WinSCP, to only do this process with files in the last two weeks?

答:
I'd use FluentFTP

```<code>using FluentFTP;
using System.Linq;

.
.
.

DateTime min = ...;
DateTime max = ...;

using (var conn = new FtpClient("address", "user", "password"))
{
    conn.Connect();

    var files = conn
        .GetListing("/path", FtpListOption.Recursive)
        .Where(item => item.Type == FtpFileSystemObjectType.File
                    && item.Modified >= min
                    && item.Modified <= max);

    foreach(var file in files)
    {
        ...
    }
}
</code>```

You can use Created instead of Modified

Body:
I'd use FluentFTP

using FluentFTP;
using System.Linq;

.
.
.

DateTime min = ...;
DateTime max = ...;

using (var conn = new FtpClient("address", "user", "password"))
{
    conn.Connect();

    var files = conn
        .GetListing("/path", FtpListOption.Recursive)
        .Where(item => item.Type == FtpFileSystemObjectType.File
                    && item.Modified >= min
                    && item.Modified <= max);

    foreach(var file in files)
    {
        ...
    }
}

You can use Created instead of Modified


问:
how to connect domain name to AWS Application Load Balancer?
I have a simple AWS setup of 2 VMs hosting a WebApp. An Application Load Balancer is in-front of these machines. I can access the DNS name of the Load Balancer and can reach to the WebApp.
Now, I want to connect to my app with a domain name hosted on Godaddy. I tried to simply create CNAME (as no Elastic IP on Application LB) with the LB's DNS name, but it didn't work.

What am I missing ? I tried with godaddy support but already wasted 7 days with not solution.
I want to put SSL certificate also on ALB. Should I be aware of anything specific in this setup?

答: The problem was, I was trying to CNAME for root level domain. Now, I created an alias in Route 53 and used AWS's nameservers on Godaddy to forward request there. </p>


问:
VBA Runtime Error 1004 - Problems with variables?
since my last problem got solved, i came up with another one! Woooo

Method "Range" for Object '_Global' failed.

Here, I am importing data which haven been searched up my a variable (PZ_RNG/strSearch)

```<code>Private Sub Search_Click()

Dim PZ_RNG As Range
Dim strSearch As String

strSearch = Packzettelinfo.PZ_ID

Set PZ_RNG = ThisWorkbook.Sheets("Data").Range("B:B").Find(strSearch, , xlValues, xlWhole)
If Not PZ_RNG Is Nothing Then

Packzettelinfo.KD_ID = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 1)
Packzettelinfo.Customer_Combination = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 2)
Packzettelinfo.Ship_ID = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 3)
Packzettelinfo.Author_ID = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 4)
Packzettelinfo.Art_Lager = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 5)
Packzettelinfo.Art_Bestell = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 6)
Packzettelinfo.DTPicker1 = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 7)
Packzettelinfo.Calc_Time = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 8)
Packzettelinfo.Time1 = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 10)
Packzettelinfo.Time2 = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 11)
Packzettelinfo.Time3 = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 12)
Packzettelinfo.Time_Special = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 13)
Packzettelinfo.Time_Total = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 14)
Packzettelinfo.Notes_Buero = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 15)
Packzettelinfo.Notes_Lager = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 16)

ThisWorkbook.Sheets("Data").Range("E1") = PZ_RNG.Address 'save data

Else
    MsgBox "Packzettel Nr. " & strSearch & " konnte nicht gefunden werden (Fehler #001)", vbOKOnly
    Packzettelinfo.PZ_ID.SetFocus
    Exit Sub
End If
</code>```

Now: I wanna save the contents when a button is clicked:

```<code>With ThisWorkbook.Sheets("Data")
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 1) = Packzettelinfo.KD_ID
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 2) = Packzettelinfo.Customer_Combination
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 3) = Packzettelinfo.Ship_ID
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 4) = Packzettelinfo.Author_ID
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 5) = Packzettelinfo.Art_Lager
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 6) = Packzettelinfo.Art_Bestell
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 7) = Packzettelinfo.DTPicker1
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 8) = Packzettelinfo.Calc_Time
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 10) = Packzettelinfo.Time1
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 11) = Packzettelinfo.Time2
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 12) = Packzettelinfo.Time3
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 13) = Packzettelinfo.Time_Special
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 14) = Packzettelinfo.Time_Total
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 15) = Packzettelinfo.Notes_Buero
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 16) = Packzettelinfo.Notes_Lager
End With
MsgBox "Packzettel " & Packzettelinfo.PZ_ID & " wurde gespeichert!", vbOKOnly
Unload Me
End Sub
</code>```

It errors at the first line ".Cells" already. Dunno whats wrong.

答:
If I understand you correctly, you write the address of a search into cell "E1" and later you want to write something to this cell. All this happens while a user form is active.

I don't like the attempt, as long as the form is active, it is sufficient to define the range variable PZ_RNG as a global variable within the form. In that case you could use something like

```<code>With ThisWorkbook.Sheets("Data")
    PZ_RNG.Offset(0, 1) = Packzettelinfo.KD_ID
    PZ_RNG.Offset(0, 2) = Packzettelinfo.Customer_Combination
    (...)
End With
</code>```

btw: Reading the data from the sheet into the form could also be done much easier:

```<code>With ThisWorkbook.Sheets("Data")
    Packzettelinfo.KD_ID = PZ_RNG.Offset(0, 1)
    (...)
End With
</code>```

explanation is easy, PZ_RNG is already a Range and Offset returns a Range that's a specific number of rows and columns apart (in this case 0 rows below and 1 resp. 2 columns to the right).

That said, coming back to your question and let's pretend you want to stick to your current solution. First thing is to split those monster-statements into smaller pieces, that helps you to debug. First step is to read the cell that holds your address and create a Range of it:

```<code>With ThisWorkbook.Sheets("Data")
    Dim adr as String, PZ_RNG as Range
    adr = .range(E1)
    set PZ_RNG = .range(adr)
</code>```

If this gives a runtime error, you likely have not the correct address - which could by easily checked by checking the content of the variable adr. If no error occurs, you could continue with the syntax suggested above, but even if for any reason you want to stick with the attempt of using the .Cells-syntax and therefore need the row and column, declare 2 variables and use those:

```<code>    dim destRow as Long, destCol as Long
    destRow = PZ_RNG.row
    destCol = PZ_RNG.column
    .Cells(destRow, destCol+1) = Packzettelinfo.KD_ID
    (...)
</code>```

Now if something fails, it is much easier to find the problem (learn to use the debugger!!!). And no, declaring and using some extra variables doesn't slow down execution.

And now, at the end of this rather long answer, the thing that (likely) caused your runtime error. SO is full of cases like this because it is not so obvious: You are using a With-statement (good), but even if you do, so called unqualified terms like Range refer to the active sheet, not the sheet of the With-clause. And also not of the sheet that you are addressing with the Cells-statement. If you want to read the range from the Worksheet that you specify in the With-clause, you have to put a . in front of Range. Every. Single. Time.:

```<code> With ThisWorkbook.Sheets("Data")
    .Cells(.Range(.Range("E1")).Row, .Range(.Range("E1")).Column + 1)
</code>```

So, likely the Sheet "Data" was not the active sheet, so Range("E1") was not reading the address you stored but something random (which was not an adress), therefore Range(.Range("E1")) had to fail.

Body:
since my last problem got solved, i came up with another one! Woooo

Method "Range" for Object '_Global' failed.

Here, I am importing data which haven been searched up my a variable (PZ_RNG/strSearch)

Private Sub Search_Click()

Dim PZ_RNG As Range
Dim strSearch As String

strSearch = Packzettelinfo.PZ_ID

Set PZ_RNG = ThisWorkbook.Sheets("Data").Range("B:B").Find(strSearch, , xlValues, xlWhole)
If Not PZ_RNG Is Nothing Then

Packzettelinfo.KD_ID = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 1)
Packzettelinfo.Customer_Combination = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 2)
Packzettelinfo.Ship_ID = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 3)
Packzettelinfo.Author_ID = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 4)
Packzettelinfo.Art_Lager = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 5)
Packzettelinfo.Art_Bestell = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 6)
Packzettelinfo.DTPicker1 = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 7)
Packzettelinfo.Calc_Time = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 8)
Packzettelinfo.Time1 = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 10)
Packzettelinfo.Time2 = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 11)
Packzettelinfo.Time3 = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 12)
Packzettelinfo.Time_Special = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 13)
Packzettelinfo.Time_Total = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 14)
Packzettelinfo.Notes_Buero = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 15)
Packzettelinfo.Notes_Lager = ThisWorkbook.Sheets("Data").Cells(PZ_RNG.Row, PZ_RNG.Column + 16)

ThisWorkbook.Sheets("Data").Range("E1") = PZ_RNG.Address 'save data

Else
    MsgBox "Packzettel Nr. " & strSearch & " konnte nicht gefunden werden (Fehler #001)", vbOKOnly
    Packzettelinfo.PZ_ID.SetFocus
    Exit Sub
End If

Now: I wanna save the contents when a button is clicked:

With ThisWorkbook.Sheets("Data")
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 1) = Packzettelinfo.KD_ID
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 2) = Packzettelinfo.Customer_Combination
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 3) = Packzettelinfo.Ship_ID
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 4) = Packzettelinfo.Author_ID
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 5) = Packzettelinfo.Art_Lager
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 6) = Packzettelinfo.Art_Bestell
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 7) = Packzettelinfo.DTPicker1
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 8) = Packzettelinfo.Calc_Time
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 10) = Packzettelinfo.Time1
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 11) = Packzettelinfo.Time2
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 12) = Packzettelinfo.Time3
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 13) = Packzettelinfo.Time_Special
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 14) = Packzettelinfo.Time_Total
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 15) = Packzettelinfo.Notes_Buero
.Cells(Range(Range("E1")).Row, Range(Range("E1")).Column + 16) = Packzettelinfo.Notes_Lager
End With
MsgBox "Packzettel " & Packzettelinfo.PZ_ID & " wurde gespeichert!", vbOKOnly
Unload Me
End Sub

It errors at the first line ".Cells" already. Dunno whats wrong.

Body:
If I understand you correctly, you write the address of a search into cell "E1" and later you want to write something to this cell. All this happens while a user form is active.

I don't like the attempt, as long as the form is active, it is sufficient to define the range variable PZ_RNG as a global variable within the form. In that case you could use something like

With ThisWorkbook.Sheets("Data")
    PZ_RNG.Offset(0, 1) = Packzettelinfo.KD_ID
    PZ_RNG.Offset(0, 2) = Packzettelinfo.Customer_Combination
    (...)
End With

btw: Reading the data from the sheet into the form could also be done much easier:

With ThisWorkbook.Sheets("Data")
    Packzettelinfo.KD_ID = PZ_RNG.Offset(0, 1)
    (...)
End With

explanation is easy, PZ_RNG is already a Range and Offset returns a Range that's a specific number of rows and columns apart (in this case 0 rows below and 1 resp. 2 columns to the right).

That said, coming back to your question and let's pretend you want to stick to your current solution. First thing is to split those monster-statements into smaller pieces, that helps you to debug. First step is to read the cell that holds your address and create a Range of it:

With ThisWorkbook.Sheets("Data")
    Dim adr as String, PZ_RNG as Range
    adr = .range(E1)
    set PZ_RNG = .range(adr)

If this gives a runtime error, you likely have not the correct address - which could by easily checked by checking the content of the variable adr. If no error occurs, you could continue with the syntax suggested above, but even if for any reason you want to stick with the attempt of using the .Cells-syntax and therefore need the row and column, declare 2 variables and use those:

    dim destRow as Long, destCol as Long
    destRow = PZ_RNG.row
    destCol = PZ_RNG.column
    .Cells(destRow, destCol+1) = Packzettelinfo.KD_ID
    (...)

Now if something fails, it is much easier to find the problem (learn to use the debugger!!!). And no, declaring and using some extra variables doesn't slow down execution.

And now, at the end of this rather long answer, the thing that (likely) caused your runtime error. SO is full of cases like this because it is not so obvious: You are using a With-statement (good), but even if you do, so called unqualified terms like Range refer to the active sheet, not the sheet of the With-clause. And also not of the sheet that you are addressing with the Cells-statement. If you want to read the range from the Worksheet that you specify in the With-clause, you have to put a . in front of Range. Every. Single. Time.:

 With ThisWorkbook.Sheets("Data")
    .Cells(.Range(.Range("E1")).Row, .Range(.Range("E1")).Column + 1)

So, likely the Sheet "Data" was not the active sheet, so Range("E1") was not reading the address you stored but something random (which was not an adress), therefore Range(.Range("E1")) had to fail.


问:
Fork other's package, modify it, then submit to npmjs.com. How to write package.json is appropriate?
I forked https://github.com/markedjs/marked on github, make some changes, now I want to publish it to npmjs.com. The package name changes to @myname/marked, how do I fill in the author information part, so that I can retain the original author info, and add my info like Name, website, email, github repo, etc?

I making some special modify for marked, only for special purpose usage. I chang the heading syntax, using #1, #2, #3 ... #108 instead of the original #, ##, ### ... ###### , so I must making a new package.

the original package.json:

```<code>{
  "name": "marked",
  "description": "A markdown parser built for speed",
  "author": "Christopher Jeffrey",
  "version": "0.8.2",
  "main": "./src/marked.js",
  "bin": "./bin/marked",
  "man": "./man/marked.1",
  "files": [
    "bin/",
    "lib/",
    "src/",
    "man/",
    "marked.min.js"
  ],
  "repository": "git://github.com/markedjs/marked.git",
  "homepage": "https://marked.js.org",
  "bugs": {
    "url": "http://github.com/markedjs/marked/issues"
  },
  "license": "MIT",
  ......
}
</code>```

答:
Your process of making changes to your favourite npm package and publishing it is incorrect.

What you would need to do is,

Fork the GitHub repository

Create a branch

Make your changes on the branch

Submit a PR from your forked repository's branch to the original repository

The owner/maintainer will review your PR and merge it

Then it's up to them to plan and release a new version which includes your changes

Body:
I forked https://github.com/markedjs/marked on github, make some changes, now I want to publish it to npmjs.com. The package name changes to @myname/marked, how do I fill in the author information part, so that I can retain the original author info, and add my info like Name, website, email, github repo, etc?

I making some special modify for marked, only for special purpose usage. I chang the heading syntax, using #1, #2, #3 ... #108 instead of the original #, ##, ### ... ###### , so I must making a new package.

the original package.json:

{
  "name": "marked",
  "description": "A markdown parser built for speed",
  "author": "Christopher Jeffrey",
  "version": "0.8.2",
  "main": "./src/marked.js",
  "bin": "./bin/marked",
  "man": "./man/marked.1",
  "files": [
    "bin/",
    "lib/",
    "src/",
    "man/",
    "marked.min.js"
  ],
  "repository": "git://github.com/markedjs/marked.git",
  "homepage": "https://marked.js.org",
  "bugs": {
    "url": "http://github.com/markedjs/marked/issues"
  },
  "license": "MIT",
  ......
}


问:
Need to pick contact from a dialog preference
I would like to add a preference setting that uses an ACTION_PICK intent. My goal is to acquire the phone number of a contact in my phone by using a preference. Is this possible?

I can run this code from my activity but I discovered I cannot run it from a class that extends DialogPreference.

```<code>Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intentContact, PICK_CONTACT);
</code>```

Or is there a way to start a new Activity from a Preference? Then that Activity could execute the above two lines of code?

答:
```<code>    // Get Custom contact Pref
    Preference customContact = (Preference)findPreference("custom_contact");
    customContact.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(i, PICK_CONTACT);
            return true;
        }
    });
</code>```

Body:
I would like to add a preference setting that uses an ACTION_PICK intent. My goal is to acquire the phone number of a contact in my phone by using a preference. Is this possible?

I can run this code from my activity but I discovered I cannot run it from a class that extends DialogPreference.

Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intentContact, PICK_CONTACT);

Or is there a way to start a new Activity from a Preference? Then that Activity could execute the above two lines of code?


问:
How do I run specific functions based on tags in C++?
I am writing a test framework that will run hundreds of tests.  Each of these tests has been written as an independent function.  Currently, I have my main function run each of these tests one-by-one.  What I would like to make is a system that uses tags.  For example, I want to be able to run all the tests with the 'WiFi' tag or run all the tests that have a 'notifications' tag.

I have tried looking up how to do this, but all I can find are articles that talk about tag dispatching which doesn't help me.  Maybe a tag isn't what I need here?

Not sure if this matters but I'm writing in c++11 on a Mac, and I'm using VS Code.

btw I'm new to stack overflow, so sorry if I messed anything up.  Thanks in advance!

Edit:
I would use multiple tags per function. For example, there is a function that would need 'WiFi' and 'Network' tags, and another that would need 'Haptic', 'Notification', and 'Network' tags.

答:
You could go with multimap, but you can also keep it simple with just one container with all the tests:</p>

```<code>#include <vector>
#include <type_traits>

template <class E> auto as_underlying(E e) -> std::underlying_type_t<E>
{ return static_cast<std::underlying_type_t<E>>(e); }

enum class Tag : unsigned {
    WiFi = 0x01u,
    Network = 0x02u,
    Haptic = 0x04u,
    Notification = 0x08u,
};

auto operator|(Tag lhs, Tag rhs) -> Tag
{
    return Tag{as_underlying(lhs) | as_underlying(rhs)};
}

struct Test
{
    using F = bool();

    Tag tag;
    F* test; // or std::function

    bool has_tag(Tag tag_to_check) const
    {
        return as_underlying(tag) & as_underlying(tag_to_check);
    }

    bool operator()() const { return test(); }
};

template <class Cont>
auto run_by_tag(const Cont& tests, Tag tag)
{
    for (const auto& test : tests)
    {
        if (test.has_tag(tag))
        {
            test();
        }
    }
}

auto test()
{
    std::vector<Test> tests{
        Test{Tag::WiFi | Tag::Network, [] { return true;}},
        Test{Tag::Haptic | Tag::Notification | Tag::Network, [] { return false; }},
        Test{Tag::Notification, [] { return true;}}
    };

    run_by_tag(tests, Tag::WiFi);
    run_by_tag(tests, Tag::Notification);
}
</code>```

Body:
You could go with multimap, but you can also keep it simple with just one container with all the tests:

#include <vector>
#include <type_traits>

template <class E> auto as_underlying(E e) -> std::underlying_type_t<E>
{ return static_cast<std::underlying_type_t<E>>(e); }

enum class Tag : unsigned {
    WiFi = 0x01u,
    Network = 0x02u,
    Haptic = 0x04u,
    Notification = 0x08u,
};

auto operator|(Tag lhs, Tag rhs) -> Tag
{
    return Tag{as_underlying(lhs) | as_underlying(rhs)};
}

struct Test
{
    using F = bool();

    Tag tag;
    F* test; // or std::function

    bool has_tag(Tag tag_to_check) const
    {
        return as_underlying(tag) & as_underlying(tag_to_check);
    }

    bool operator()() const { return test(); }
};

template <class Cont>
auto run_by_tag(const Cont& tests, Tag tag)
{
    for (const auto& test : tests)
    {
        if (test.has_tag(tag))
        {
            test();
        }
    }
}

auto test()
{
    std::vector<Test> tests{
        Test{Tag::WiFi | Tag::Network, [] { return true;}},
        Test{Tag::Haptic | Tag::Notification | Tag::Network, [] { return false; }},
        Test{Tag::Notification, [] { return true;}}
    };

    run_by_tag(tests, Tag::WiFi);
    run_by_tag(tests, Tag::Notification);
}


问:
Javascript. How can I access a variable outside of a function?
I'm trying to create a simple application that generates a random question with an onclick, and will generate a solution to said question with a different onclick.  I've been able to create the random question function simple enough, but what I'm having trouble with is the solution part.  Essentially I cant access the variables produced from the "generate question" function.

The following function generates a random question: "Convert 10mg/mL to mcg/mL"

```<code>const arr = ['mg/mL', 'mcg/mL', 'mg/L'];

function genConversion () {
  function clearBox(elementID){ //this resets the question
      document.getElementById(elementID).innerHTML = "";
  }

  clearBox('output');

  function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

   function randomNum() {
    var number = Math.floor((Math.random() * 100) +1);
    return number
  }

  var num = randomNum()

  shuffle(arr);

  output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]

}
</code>```

Now, when I try to create a function that will solve the generated problem (the actual logic will come once I can figure out how to access the question variables), I cant seem to access variable 'num'.  Interestingly, I am able to access the random array element arr[0].

```<code>function solveProb() {
  console.log(arr[0]);
  console.log(num);
}
</code>```

Im sure this has something to do with scope that Im having trouble with, but any advice would be appreciated.

答:
Just declare the num variable outside, then assign to it inside genConversion, just like how the arr variable is declared outside:

const arr = ['mg/mL', 'mcg/mL', 'mg/L'];
let num;

function genConversion () {
  function clearBox(elementID){ //this resets the question
      document.getElementById(elementID).innerHTML = "";
  }

  clearBox('output');

  function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

   function randomNum() {
    var number = Math.floor((Math.random() * 100) +1);
    return number
  }

  num = randomNum()
  shuffle(arr);

  output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]
}

genConversion();
document.querySelector('button').addEventListener('click', () => {
  console.log('Random generation was: ', "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output"></div>
<button>click</button></code>```

Body:
I'm trying to create a simple application that generates a random question with an onclick, and will generate a solution to said question with a different onclick.  I've been able to create the random question function simple enough, but what I'm having trouble with is the solution part.  Essentially I cant access the variables produced from the "generate question" function.

The following function generates a random question: "Convert 10mg/mL to mcg/mL"

const arr = ['mg/mL', 'mcg/mL', 'mg/L'];

function genConversion () {
  function clearBox(elementID){ //this resets the question
      document.getElementById(elementID).innerHTML = "";
  }

  clearBox('output');

  function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

   function randomNum() {
    var number = Math.floor((Math.random() * 100) +1);
    return number
  }

  var num = randomNum()

  shuffle(arr);

  output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]

}

Now, when I try to create a function that will solve the generated problem (the actual logic will come once I can figure out how to access the question variables), I cant seem to access variable 'num'.  Interestingly, I am able to access the random array element arr[0].

function solveProb() {
  console.log(arr[0]);
  console.log(num);
}

Im sure this has something to do with scope that Im having trouble with, but any advice would be appreciated.

Body:
Just declare the num variable outside, then assign to it inside genConversion, just like how the arr variable is declared outside:

const arr = ['mg/mL', 'mcg/mL', 'mg/L'];
let num;

function genConversion () {
  function clearBox(elementID){ //this resets the question
      document.getElementById(elementID).innerHTML = "";
  }

  clearBox('output');

  function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

   function randomNum() {
    var number = Math.floor((Math.random() * 100) +1);
    return number
  }

  num = randomNum()
  shuffle(arr);

  output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]
}

genConversion();
document.querySelector('button').addEventListener('click', () => {
  console.log('Random generation was: ', "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]);
});

<div id="output"></div>
<button>click</button>


问:
How to debug pressing 'o' freezes Vim
My Vim normally works fine, however, at times, it gets into a weird state.

When it does, pressing o in normal mode causes Vim to hang. I can then get it out of that state by pressing Ctrl + c. I'd expect the cursor to move down one line and enter insert mode.

What's interesting is that I can replicate it every time once it gets into this state. Pressing o again will hang again, until I press Ctrl+c.

It is hard to debug whether it is a specific plugin since it doesn't happen every time. If I disabled one plugin, I wouldn't know for sure it was the plugin that was causing this problem since Vim usually works, so it occurs maybe once every few days.

Also, I don't have any mapping to o. map o returns No mapping found.

I am not sure how to debug this; does anyone have any ideas?

答:
Since I could replicate this issue when I got into this weird state, I could profile the problem.

```<code>profile start freezing_debug.txt
profile func *
profile file *
</code>```

I managed to find that GetLastRealCodeLNum in Vim package was the root cause. Searching Google helped me find that a ticket had been created and all I probably have to do is update my Vim version to pull this change in.

Title: How to debug pressing 'o' freezes Vim

Body:
Since I could replicate this issue when I got into this weird state, I could profile the problem.

profile start freezing_debug.txt
profile func *
profile file *

I managed to find that GetLastRealCodeLNum in Vim package was the root cause. Searching Google helped me find that a ticket had been created and all I probably have to do is update my Vim version to pull this change in.


问:
Spring Security Facebook Oauth2 redirects to home page
I can't redirect the user to the previous page after his basic Facebook authentication. Instead I'm getting redirected to the home page. I'm following the example mentioned in https://spring.io/guides/tutorials/spring-boot-oauth2/

This is my structure:

SocialController:

```<code>@RestController
public class SocialController {

    @GetMapping("/user")
    public Principal user(Principal principal) {
        return principal;
    }

}
</code>```

test.html:

```<code><div class="container unauthenticated">
    With Facebook: <a href="login">click here</a>
</div>
<div class="container authenticated" style="display:none">
    Logged in as: <span id="user"></span>
</div>

<script>
 $.get("/user", function(data) {
        console.log("Inside users: " + data);
        $("#user").html(data.userAuthentication.details.name);
        $(".unauthenticated").hide()
        $(".authenticated").show()
    });
</script>
</code>```

Main method:

```<code>@SpringBootApplication
@EnableOAuth2Sso
public class IvanstanevPortfolioApplication extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/img/**", "/audio/**" , "/" ,"/index","/contacts","/about_me","/test")
                .permitAll()
                .anyRequest()
                .authenticated();
    }

    public static void main(String[] args) {
        SpringApplication.run(IvanstanevPortfolioApplication.class, args);
    }

}
</code>```

Basically i want to retrieve users name from Facebook and stay at the page where he was (test.html). Instead im getting redirected to home page. Spent all day on this, cant find a solution. :\

答:
I had a similar problem, except that the user needs to return to the same page every time rather than returning to the last page.

You can say that the redirect page is hard-coded...but this may help

Create a class that implements SignInAdapter from package org.springframework.social.connect.web

This class should @Override the signIn method, and this method has to return String. This String represents the redirect resource you want to go to.

If you want to redirect to the homepage, you can simply return null for this method.

```<code>@Service
public class FacebookSignInAdapter implements SignInAdapter {
  @Override
  public String signIn(
        String localUserId,
        Connection<?> connection,
        NativeWebRequest request) {

    SecurityContextHolder.getContext().setAuthentication(
            new UsernamePasswordAuthenticationToken(
                    connection.getDisplayName(), null,
                    Arrays.asList(new SimpleGrantedAuthority("FACEBOOK_USER"))));

    return "/form";
  }
}
</code>```

Here is a useful guide for more details:
https://www.baeldung.com/facebook-authentication-with-spring-security-and-social

Body:
I can't redirect the user to the previous page after his basic Facebook authentication. Instead I'm getting redirected to the home page. I'm following the example mentioned in https://spring.io/guides/tutorials/spring-boot-oauth2/

This is my structure:

SocialController:

@RestController
public class SocialController {

    @GetMapping("/user")
    public Principal user(Principal principal) {
        return principal;
    }

}

test.html:

    With Facebook: click here

    Logged in as:

Main method:

@SpringBootApplication
@EnableOAuth2Sso
public class IvanstanevPortfolioApplication extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/img/**", "/audio/**" , "/" ,"/index","/contacts","/about_me","/test")
                .permitAll()
                .anyRequest()
                .authenticated();
    }

    public static void main(String[] args) {
        SpringApplication.run(IvanstanevPortfolioApplication.class, args);
    }

}

Basically i want to retrieve users name from Facebook and stay at the page where he was (test.html). Instead im getting redirected to home page. Spent all day on this, cant find a solution. :\

Body:
I had a similar problem, except that the user needs to return to the same page every time rather than returning to the last page.

You can say that the redirect page is hard-coded...but this may help

Create a class that implements SignInAdapter from package org.springframework.social.connect.web

This class should @Override the signIn method, and this method has to return String. This String represents the redirect resource you want to go to.

If you want to redirect to the homepage, you can simply return null for this method.

@Service
public class FacebookSignInAdapter implements SignInAdapter {
  @Override
  public String signIn(
        String localUserId,
        Connection<?> connection,
        NativeWebRequest request) {

    SecurityContextHolder.getContext().setAuthentication(
            new UsernamePasswordAuthenticationToken(
                    connection.getDisplayName(), null,
                    Arrays.asList(new SimpleGrantedAuthority("FACEBOOK_USER"))));

    return "/form";
  }
}

Here is a useful guide for more details:
https://www.baeldung.com/facebook-authentication-with-spring-security-and-social


答: As you can see, arr is a global variable (not declared inside any function) but num is declared inside genConversion hence it exists only there.

Title: Javascript. How can I access a variable outside of a function?


问:
How to Automatically Detects User's Location and Display in Wordpress Page
I have developed a Custom wordpress Theme and i want to detect the user's location and get inside dropdown?</p>

答:
To locate a users position you can use the HTML Geolocation API. Check out the documentation:
https://www.w3schools.com/html/html5_geolocation.asp

Like in the example of w3schools you only need something to trigger the javascript function. This can be your dropdown element, just give the attribute onclick="getLocation()" to it. Give the element where you want to output the location an ID, so you can put the result of the function in it.

Then you can put the following javascript in the footer.php file of your wordpress theme, or anywhere you think it fits your setting best.

Taken from: https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_geolocation

```<code><script>
var x = document.getElementById("your_dropwdown_id");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>
</code>```

So on click of the element with the onclick="getLocation()" attribute, the getLocation() function is fired. The function gets the browser location data and outputs the result inside of the element with the id your_dropdown_id.

Hope this helps!

Body:
To locate a users position you can use the HTML Geolocation API. Check out the documentation:
https://www.w3schools.com/html/html5_geolocation.asp

Like in the example of w3schools you only need something to trigger the javascript function. This can be your dropdown element, just give the attribute onclick="getLocation()" to it. Give the element where you want to output the location an ID, so you can put the result of the function in it.

Then you can put the following javascript in the footer.php file of your wordpress theme, or anywhere you think it fits your setting best.

Taken from: https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_geolocation

<script>
var x = document.getElementById("your_dropwdown_id");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>

So on click of the element with the onclick="getLocation()" attribute, the getLocation() function is fired. The function gets the browser location data and outputs the result inside of the element with the id your_dropdown_id.

Hope this helps!


问:
Assigned value to variable in function, variable undefined after function call
What i want to do is have a function which checks some conditions and assigns a value according to which condition is true. But the variable assignment in the function does not affect the value outside. (Scopes)

While the following code won't work, is there any way to not have to write the if-elif block again and again?

```<code>def calc():
    if o==1:
        z=x+y
    elif o==2:
        z=x-y

calc()
print(z)
</code>```

答:
this is referred to as scope in the computer science world ... and your assignment is out of scope of the main program space

instead you should just return the value

```<code>def calc():
    if o==1:
        z=x+y
    elif o==2:
        z=x-y
    return z

y = calc()
print(y)
</code>```

Body:
What i want to do is have a function which checks some conditions and assigns a value according to which condition is true. But the variable assignment in the function does not affect the value outside. (Scopes)

While the following code won't work, is there any way to not have to write the if-elif block again and again?

def calc():
    if o==1:
        z=x+y
    elif o==2:
        z=x-y

calc()
print(z)

Body:
this is referred to as scope in the computer science world ... and your assignment is out of scope of the main program space

instead you should just return the value

def calc():
    if o==1:
        z=x+y
    elif o==2:
        z=x-y
    return z

y = calc()
print(y)