问:
Does caching the return value of typeof(MyControl) provide any optimization?
I see code similar to the following sprinkled about some native WPF controls:

```<code>static MyControl {
    Type typeFromHandle = typeof(MyControl);

    // Which is used in various places
    SomeProperty.OverrideMetadata(typeFromHandle, ...);
    CommandManager.RegisterClassInputBinding(typeFromHandle, ...);
    EventManager.RegisterClassHandler(typeFromHandle, ...);
}
</code>```

Seems like the following code would have the same performance:

```<code>static MyControl {
    SomeProperty.OverrideMetadata(typeof(MyControl), ...);
    CommandManager.RegisterClassInputBinding(typeof(MyControl), ...);
    EventManager.RegisterClassHandler(typeof(MyControl), ...);
}
</code>```

Does this approach offer any benefit performance wise when JIT-ing the code or during runtime?

答: It's unlikely you'll write code where the performance of typeof is significant so you should choose the style of code that is most clear and maintainable.</p>

Body:
I see code similar to the following sprinkled about some native WPF controls:

static MyControl {
    Type typeFromHandle = typeof(MyControl);

    // Which is used in various places
    SomeProperty.OverrideMetadata(typeFromHandle, ...);
    CommandManager.RegisterClassInputBinding(typeFromHandle, ...);
    EventManager.RegisterClassHandler(typeFromHandle, ...);
}

Seems like the following code would have the same performance:

static MyControl {
    SomeProperty.OverrideMetadata(typeof(MyControl), ...);
    CommandManager.RegisterClassInputBinding(typeof(MyControl), ...);
    EventManager.RegisterClassHandler(typeof(MyControl), ...);
}

Does this approach offer any benefit performance wise when JIT-ing the code or during runtime?


来源: stackexchange

问:
How to correctly migrate old data saved with NSKeyedArchiver into new format while migrating from Objective-C to Swift
An older version of the app has a NSCoding-compliant class (lets call it OldItem), written in Objective C. This class has about 20 properties with different types:

```<code>@property (nonatomic) NSInteger x;

// ...

- (id)initWithCoder:(NSCoder *)coder {

    if (self = [super init])  {
        _x = [coder decodeIntegerForKey:@"x"];
        // all 20 fields are decoded in the similar way
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [self.x encodeWithCoder:coder];
    // all 20 fields encoded in the similar way
}
</code>```

It's used in another class (lets call it Controller) as array:

```<code>@property (nonatomic, strong, nonnull) NSMutableArray<OldItem *> *items;
</code>```

Controller also caches items to disk like this:

```<code>NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.items];
[data writeToFile:@"myfile.txt" options:NSDataWritingFileProtectionComplete error:nil];
</code>```

Now I need to migrate OldItem to Swift, while Controller only changes the type of item it handles:

```<code>@property (nonatomic, strong, nonnull) NSMutableArray<NewItem *> *items;
</code>```

Question is: how do I migrate an old data, saved in myfile.txt in previous version of the application into new version?

Ideally new class has a different name, e.g NewItem, but I'm open to keeping the old name, if it significantly simplifies the migration.

Don't care if new version will be saving data into the same file, or reading an old file once, and moving data over to a new file.

For this question, ignore any differences between OldItem and NewItem. Treat them as direct port.

Clearly NewItem should still be NSCoding-compliant, and reading/writing NewItem into the file is not an issue.

答:
After looking around for a bit, the actual solution is:

Make sure public required init?(coder: NSCoder) in NewItem class properly unarchives all fields you want to preserve from OldItem. For instance enums, or number type conversions may require special handling, even if you didn't change fields per se.

Right before unarchiving, tell NSKeyedUnarchiver that NewItem should be used in place of OldItem, using NSKeyedUnarchiver.setClass method.

Example:

```<code>let archivedData = try Data(contentsOf: filePath)
NSKeyedUnarchiver.setClass(NewItem.self, forClassName: "OldItem")
let items = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(archivedData)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
An older version of the app has a NSCoding-compliant class (lets call it OldItem), written in Objective C. This class has about 20 properties with different types:

@property (nonatomic) NSInteger x;

// ...

- (id)initWithCoder:(NSCoder *)coder {

    if (self = [super init])  {
        _x = [coder decodeIntegerForKey:@"x"];
        // all 20 fields are decoded in the similar way
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [self.x encodeWithCoder:coder];
    // all 20 fields encoded in the similar way
}

It's used in another class (lets call it Controller) as array:

@property (nonatomic, strong, nonnull) NSMutableArray<OldItem *> *items;

Controller also caches items to disk like this:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.items];
[data writeToFile:@"myfile.txt" options:NSDataWritingFileProtectionComplete error:nil];

Now I need to migrate OldItem to Swift, while Controller only changes the type of item it handles:

@property (nonatomic, strong, nonnull) NSMutableArray<NewItem *> *items;

Question is: how do I migrate an old data, saved in myfile.txt in previous version of the application into new version?

Ideally new class has a different name, e.g NewItem, but I'm open to keeping the old name, if it significantly simplifies the migration.

Don't care if new version will be saving data into the same file, or reading an old file once, and moving data over to a new file.

For this question, ignore any differences between OldItem and NewItem. Treat them as direct port.

Clearly NewItem should still be NSCoding-compliant, and reading/writing NewItem into the file is not an issue.

Body:
After looking around for a bit, the actual solution is:

Make sure public required init?(coder: NSCoder) in NewItem class properly unarchives all fields you want to preserve from OldItem. For instance enums, or number type conversions may require special handling, even if you didn't change fields per se.

Right before unarchiving, tell NSKeyedUnarchiver that NewItem should be used in place of OldItem, using NSKeyedUnarchiver.setClass method.

Example:

let archivedData = try Data(contentsOf: filePath)
NSKeyedUnarchiver.setClass(NewItem.self, forClassName: "OldItem")
let items = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(archivedData)


问:
How to know which form is submitted to the flask web server
This code is very big, in this code I am taking data from forms and I don't know from which form the user has triggered the button. So, in code I am identifying where it has values and where not which has make my code big that's a very awkward and maybe this is not a professional way to do this. If there is another way to minimize/upgrade this code, please let me know.

```<code>@app.route('/search', methods=['POST','GET'])
def search():
    if request.method=='POST':
        """Fetching all the Inputs"""
        isbn = request.form.get('isbn')
        title = request.form.get('title')
        author = request.form.get('author')

        if isbn is None:
            if title is None:
                if author is not None:
                    """Here ONly we have author input"""
                    info = db.execute("SELECT * FROM books WHERE author = :author",{'author':author}).fetchall()
                else:
                    """Here no one"""
            else:
                """Here title has value"""
                if author is not None:
                    """here title and author has only value"""
                    info = db.execute("SELECT * FROM books WHERE author = :author OR title = :title",{'author':author, 'title':title}).fetchall()
                else:
                    info = db.execute("SELECT * FROM books WHERE title = :title",{'title':title}).fetchall()

        else:
            if title is None:
                if author is not None:
                    """Here ONly we have author and isbn input"""
                    info = db.execute("SELECT * FROM books WHERE author = :author OR isbn = :isbn",{'author':author, 'isbn':isbn}).fetchall()
                else:
                    info = db.execute("SELECT * FROM books WHERE isbn = :isbn",{'isbn':isbn}).fetchall()
            else:
                """Here title and isbn has value"""
                if author is not None:
                    """here title, isbn, author has only value"""
                    info = db.execute("SELECT * FROM books WHERE author = :author OR ibsn = :isbn OR title = :title",{'author':author, 'ibsn':ibsn, 'title':title}).fetchall()
                else:
                    """here title, isbn has only value"""
                    info = db.execute("SELECT * FROM books WHERE title = :title OR isbn = :isbn",{'title':title, 'isbn':isbn}).fetchall()
</code>```

Html code look like this;

```<code><div class="row" style="margin-top: 15px; padding: 2px;">
        <nav class="navbar navbar-light bg-light">
            <form class="form-inline" action="{{ url_for('search') }}" method="post">
                <input class="form-control mr-sm-2" name="isbn" type="search" placeholder="Enter Isbn" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </nav>
        <nav class="navbar navbar-light bg-light">
            <form class="form-inline" action="{{ url_for('search') }}" method="post">
                <input class="form-control mr-sm-2" name="title" type="search" placeholder="Enter Title" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </nav>
        <nav class="navbar navbar-light bg-light">
            <form class="form-inline" action="{{ url_for('search') }}" method="post">
                <input class="form-control mr-sm-2" name="author" type="search" placeholder="Enter Author" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </nav>
    </div>
    <div>
        <form id="center" action="{{ url_for('search') }}" method="post">
                <button type="button" class="btn btn-primary">Search</button>
        </form>
    </div>
</code>```

答:
Well in order to do it in an easy and more professional way
you can add a query string to the requested URL for submitting
each form like this simple example:

forms.html

<form action="/reg?f=f1" method="post">
  <input type="text" name="username" placeholder="username">
  <input type="submit" value="submit">
</form>

<form action="/reg?f=f2" method="post">
  <input type="email" name="email" placeholder="email">
  <input type="submit" value="submit">
</form>
```

<p>so the first form and the second one can be ientified because
of the query string, so if the <code>f</code> equals <code>"f1"</code> then it's the first form
otherwise it's the second one</p>

<p><strong>server_app.py</strong></p>

<pre class="lang-py prettyprint-override"><code>from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/reg', methods=['GET', 'POST'])
def sign_up():
  # if the method is POST then the user is submitting a form otherwise he's just requesting page content
  if request.method == "POST":
    # the first form being submitted
    if request.args.get("f") == "f1":
      print(request.form["username"])
    # the second form being submitted
    else:
      print(request.form["email"])
  # always the same page only for testing
  return render_template("forms.html")

app.run(host='127.0.0.1',port=8080,debug=True)
</code>```

Body:
This code is very big, in this code I am taking data from forms and I don't know from which form the user has triggered the button. So, in code I am identifying where it has values and where not which has make my code big that's a very awkward and maybe this is not a professional way to do this. If there is another way to minimize/upgrade this code, please let me know.

@app.route('/search', methods=['POST','GET'])
def search():
    if request.method=='POST':
        """Fetching all the Inputs"""
        isbn = request.form.get('isbn')
        title = request.form.get('title')
        author = request.form.get('author')

        if isbn is None:
            if title is None:
                if author is not None:
                    """Here ONly we have author input"""
                    info = db.execute("SELECT * FROM books WHERE author = :author",{'author':author}).fetchall()
                else:
                    """Here no one"""
            else:
                """Here title has value"""
                if author is not None:
                    """here title and author has only value"""
                    info = db.execute("SELECT * FROM books WHERE author = :author OR title = :title",{'author':author, 'title':title}).fetchall()
                else:
                    info = db.execute("SELECT * FROM books WHERE title = :title",{'title':title}).fetchall()

        else:
            if title is None:
                if author is not None:
                    """Here ONly we have author and isbn input"""
                    info = db.execute("SELECT * FROM books WHERE author = :author OR isbn = :isbn",{'author':author, 'isbn':isbn}).fetchall()
                else:
                    info = db.execute("SELECT * FROM books WHERE isbn = :isbn",{'isbn':isbn}).fetchall()
            else:
                """Here title and isbn has value"""
                if author is not None:
                    """here title, isbn, author has only value"""
                    info = db.execute("SELECT * FROM books WHERE author = :author OR ibsn = :isbn OR title = :title",{'author':author, 'ibsn':ibsn, 'title':title}).fetchall()
                else:
                    """here title, isbn has only value"""
                    info = db.execute("SELECT * FROM books WHERE title = :title OR isbn = :isbn",{'title':title, 'isbn':isbn}).fetchall()

Html code look like this;

            <form class="form-inline" action="{{ url_for('search') }}" method="post">
                <input class="form-control mr-sm-2" name="isbn" type="search" placeholder="Enter Isbn" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>

            <form class="form-inline" action="{{ url_for('search') }}" method="post">
                <input class="form-control mr-sm-2" name="title" type="search" placeholder="Enter Title" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>

            <form class="form-inline" action="{{ url_for('search') }}" method="post">
                <input class="form-control mr-sm-2" name="author" type="search" placeholder="Enter Author" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>

        <form id="center" action="{{ url_for('search') }}" method="post">
                <button type="button" class="btn btn-primary">Search</button>
        </form>

Body:
Well in order to do it in an easy and more professional way
you can add a query string to the requested URL for submitting
each form like this simple example:

forms.html

<form action="/reg?f=f1" method="post">
  <input type="text" name="username" placeholder="username">
  <input type="submit" value="submit">
</form>

<form action="/reg?f=f2" method="post">
  <input type="email" name="email" placeholder="email">
  <input type="submit" value="submit">
</form>

so the first form and the second one can be ientified because
of the query string, so if the f equals "f1" then it's the first form
otherwise it's the second one

server_app.py

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/reg', methods=['GET', 'POST'])
def sign_up():
  # if the method is POST then the user is submitting a form otherwise he's just requesting page content
  if request.method == "POST":
    # the first form being submitted
    if request.args.get("f") == "f1":
      print(request.form["username"])
    # the second form being submitted
    else:
      print(request.form["email"])
  # always the same page only for testing
  return render_template("forms.html")

app.run(host='127.0.0.1',port=8080,debug=True)


问:
How to make users STOP the execution of an HTML5 audio autoplay file clicking anything on the page?
I'm working on a page that, on my client's request, loads playing a background soundtrack.
Of course it's just for those users who are not navigating with audio autoplay disabled.
So the simple piece of code used to start playing the music is something like the following:

```<code><audio autoplay id="background-soundtrack">
  <source src="mytrack.mp3" type="audio/mpeg">
</audio>
</code>```

I'd like to make music stop (even better: make it fade out in a matter of a few seconds) as soon as the user clicks anywhere on the page -- it should work tapping on mobile devices too.

Can you please suggesitng me a smart way to achieve my goal?
It doesn't matter if it's pure JavaScript or jQuery.

Thanks!

答:
try this jquery:</p>

```<code>$('document').on('click','body',function(){
  if ($('#background-soundtrack').paused == false){
    $('#background-soundtrack').animate({volume: 0}, 1500,
       //1500 duration time
       function(){
         $('#background-soundtrack').pause()
       });
  }
});
</code>```

Body:
I'm working on a page that, on my client's request, loads playing a background soundtrack.
Of course it's just for those users who are not navigating with audio autoplay disabled.
So the simple piece of code used to start playing the music is something like the following:

<audio autoplay id="background-soundtrack">
  <source src="mytrack.mp3" type="audio/mpeg">
</audio>

I'd like to make music stop (even better: make it fade out in a matter of a few seconds) as soon as the user clicks anywhere on the page -- it should work tapping on mobile devices too.

Can you please suggesitng me a smart way to achieve my goal?
It doesn't matter if it's pure JavaScript or jQuery.

Thanks!

Body:
try this jquery:

$('document').on('click','body',function(){
  if ($('#background-soundtrack').paused == false){
    $('#background-soundtrack').animate({volume: 0}, 1500,
       //1500 duration time
       function(){
         $('#background-soundtrack').pause()
       });
  }
});


问:
Store Data in memory to access later on
New to C++.  I have a code that spins thru directories to look for a specific file (123.txt) and lists the result in a textbox.  What i need to do is store these result in memory so i can access it later. An array maybe? I'm not exactly sure how that's done.

Here's the code to execute it:

```<code>outfile1.open("pxutil1.log");

    DWORD dwSize = MAX_PATH;
    char szLogicalDrives[MAX_PATH];
    DWORD dwResult = GetLogicalDriveStrings(dwSize, szLogicalDrives);
    if (dwResult == 0)
    {
        // error handling...
    }
    else if (dwResult > MAX_PATH)
    {
        // not enough buffer space...
    }
    else
    {
        for (char* szSingleDrive = szLogicalDrives; *szSingleDrive != 0; szSingleDrive += (lstrlenA(szSingleDrive) + 1))
        {
            if (GetDriveTypeA(szSingleDrive) == DRIVE_FIXED)
                FindFile(szSingleDrive);
        }
    }
</code>```

Here's the code to search for 123.txt and list the restult in a logfile.

```<code>std::string dir = directory;
    if ((!dir.empty()) && (dir.back() != '\\') && (dir.back() != '/'))
        dir += '\\';

    WIN32_FIND_DATAA file;
    HANDLE search_handle = FindFirstFileA((dir + "*").c_str(), &file);
    if (search_handle == INVALID_HANDLE_VALUE)
    {
        if (GetLastError() != ERROR_FILE_NOT_FOUND)
        {
            // error handling...
            //::MessageBox(NULL, "File not found", "", MB_OK);
        }
    }
    else
    {
        do
        {
            if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if ((lstrcmpA(file.cFileName, ".") != 0) && (lstrcmpA(file.cFileName, "..") != 0))
                {
                    //FindFile(dir + file.cFileName);
                    if (!ExcludeDir(dir + file.cFileName))
                    {
                        FindFile(dir + file.cFileName);
                    }
                }
            }
            else
            {
                if (lstrcmpA(file.cFileName, "123.txt") == 0)
                {
                    outfile1 << dir.c_str() << endl; //write to log file
                }
            }
        } while (FindNextFileA(search_handle, &file));

        if (GetLastError() != ERROR_NO_MORE_FILES)
        {
            ::MessageBox(NULL, "No more files", "", MB_OK);
        }

        FindClose(search_handle);
    }
</code>```

I thought maybe i could add this to the code, but it doesn't work

```<code>string listOfDir[20]

std::string(dir) >> listOfDir;
</code>```

答:
The standard C++ language does not have overloads of operator>> to input arrays.

The following does not work:

```<code>std::cin >> listOfDir;
</code>```

The C++ language does not have any functions to split a string.

The following does not work:

```<code>std::string(dir) >> listOfDir;
</code>```

The compiler can't find any overload of operator>> that takes a std::string parameter and an array parameter.  The statement would be equivalent of:

```<code>operator>>(std::string, std::string[]);
</code>```

In summary, you'll need to write the code yourself to parse or split a string; or you can search the internet for a string library.

If you use std::vector, this code may be more useful:

```<code>std::vector<std::string> listOfDir;
//...
listOfDir.push_back(dir);
</code>```

The above code fragment appends a copy of dir to the vector listOfDir.

Title: Store Data in memory to access later on

Body:
New to C++.  I have a code that spins thru directories to look for a specific file (123.txt) and lists the result in a textbox.  What i need to do is store these result in memory so i can access it later. An array maybe? I'm not exactly sure how that's done.

Here's the code to execute it:

outfile1.open("pxutil1.log");

    DWORD dwSize = MAX_PATH;
    char szLogicalDrives[MAX_PATH];
    DWORD dwResult = GetLogicalDriveStrings(dwSize, szLogicalDrives);
    if (dwResult == 0)
    {
        // error handling...
    }
    else if (dwResult > MAX_PATH)
    {
        // not enough buffer space...
    }
    else
    {
        for (char* szSingleDrive = szLogicalDrives; *szSingleDrive != 0; szSingleDrive += (lstrlenA(szSingleDrive) + 1))
        {
            if (GetDriveTypeA(szSingleDrive) == DRIVE_FIXED)
                FindFile(szSingleDrive);
        }
    }

Here's the code to search for 123.txt and list the restult in a logfile.

std::string dir = directory;
    if ((!dir.empty()) && (dir.back() != '\\') && (dir.back() != '/'))
        dir += '\\';

    WIN32_FIND_DATAA file;
    HANDLE search_handle = FindFirstFileA((dir + "*").c_str(), &file);
    if (search_handle == INVALID_HANDLE_VALUE)
    {
        if (GetLastError() != ERROR_FILE_NOT_FOUND)
        {
            // error handling...
            //::MessageBox(NULL, "File not found", "", MB_OK);
        }
    }
    else
    {
        do
        {
            if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if ((lstrcmpA(file.cFileName, ".") != 0) && (lstrcmpA(file.cFileName, "..") != 0))
                {
                    //FindFile(dir + file.cFileName);
                    if (!ExcludeDir(dir + file.cFileName))
                    {
                        FindFile(dir + file.cFileName);
                    }
                }
            }
            else
            {
                if (lstrcmpA(file.cFileName, "123.txt") == 0)
                {
                    outfile1 << dir.c_str() << endl; //write to log file
                }
            }
        } while (FindNextFileA(search_handle, &file));

        if (GetLastError() != ERROR_NO_MORE_FILES)
        {
            ::MessageBox(NULL, "No more files", "", MB_OK);
        }

        FindClose(search_handle);
    }

I thought maybe i could add this to the code, but it doesn't work

string listOfDir[20]

std::string(dir) >> listOfDir;

Body:
The standard C++ language does not have overloads of operator>> to input arrays.

The following does not work:

std::cin >> listOfDir;

The C++ language does not have any functions to split a string.

The following does not work:

std::string(dir) >> listOfDir;

The compiler can't find any overload of operator>> that takes a std::string parameter and an array parameter.  The statement would be equivalent of:

operator>>(std::string, std::string[]);

In summary, you'll need to write the code yourself to parse or split a string; or you can search the internet for a string library.

If you use std::vector, this code may be more useful:

std::vector<std::string> listOfDir;
//...
listOfDir.push_back(dir);

The above code fragment appends a copy of dir to the vector listOfDir.


问:
Filtering and Searching Data with JavaScript
Where would I start to learn how to filter data like you would see in a product listing page on a shopping site like Nordstrom, Bestbuy, Whirlpool? I want to know how someone would do it with javascript and category and product json data.

https://bestbuyapis.github.io/api-documentation/?shell#categorizations

https://marketplace.intel.com/s/search?search=%7B%22cat%22%3Anull%2C%22q%22%3A%22%22%2C%22type%22%3A%22all%22%7D&language=en_US - This one is kind of confusing to me how they use checkboxes with children. Is this an example of recursion?

Best answer would provide helpful links and an example with explanation. But honestly anything helps!

TIA - just trying to become a better developer!

答:
Here is how you could fetch and filter the data from the Best Buy API from the front-end (i.e. on a web page).

From the BestBuy API website, here is an example request:
https://api.bestbuy.com/beta/products/openBox(categoryId=abcat0400000)?apiKey=YourAPIKey

And here is the example JSON request:

```<code>{
  "results": [
    {
      "customerReviews": {
        "averageScore": "4.7",
        "count": 145
      },
      "descriptions": {
        "short": "Compatible with most Canon DSLR cameras; stepping motor; 52mm filter size; 11.8\" minimum focus distance"
      },
      "images": {
        "standard": "http://img.bbystatic.com/BestBuy_US/images/products/5729/5729048_sc.jpg"
      },
      "links": {
        "product": "https://api.bestbuy.com/v1/products/5729048.json?apiKey=YourAPIKey",
        "web": "http://www.bestbuy.com/site/canon-ef-40mm-f-2-8-stm-standard-lens-black/5729048.p?id=1218688218296&skuId=5729048&cmp=RMX&ky=2l9pmD3wUBb9cc0tkHo49KBFCMPCiIPY4#tab=buyingOptions",
        "addToCart": "https://api.bestbuy.com/click/-/5729048/cart"
      },
      "names": {
        "title": "Canon - EF 40mm f/2.8 STM Standard Lens - Black"
      },
      "offers": [
        {
          "condition": "excellent",
          "prices": {
            "current": 167.99,
            "regular": 199.99
          }
        }
      ],
      "prices": {
        "current": 199.99,
        "regular": 199.99
      },
      "sku": "5729048"
    }
  ]
}
</code>```

Fetch the data, then process the results. You can adjust your filter based on the BestBuy categories and based on what other criteria their API returns (i.e. price, condition, etc.). Below is some sample code that uses the API to get results from the camera category, then only filter out all items above a certain price.

```<code>//search based on your desired BestBuy category ID - need to look up the IDs from their documentation
//change the searchCategoryID when you want to search for a different category
const getAPIData = (searchCategoryID) =>{
    //used built-in Fetch Web API to perform a get request. Need to get an API Key from Best Buy
    fetch(`https://api.bestbuy.com/beta/products/openBox(categoryId=${searchCategoryID})?apiKey=YourAPIKey`)
    .then(response => response.json())
    .then(data => {
        //process the data, that is formated like above, with the filter array method
        const dataArr=data.results;
        results.filter(item =>{
            //this is an example where we only keep items less than some target price. You would need to set your filter criteria to what you want
            //you can only use the data best buy returns in their api
            if(item.prices.current<targetPrice){return true;}
            else{return false;}
        })
    });
}
</code>```

Body:
Here is how you could fetch and filter the data from the Best Buy API from the front-end (i.e. on a web page).

From the BestBuy API website, here is an example request:
https://api.bestbuy.com/beta/products/openBox(categoryId=abcat0400000)?apiKey=YourAPIKey

And here is the example JSON request:

{
  "results": [
    {
      "customerReviews": {
        "averageScore": "4.7",
        "count": 145
      },
      "descriptions": {
        "short": "Compatible with most Canon DSLR cameras; stepping motor; 52mm filter size; 11.8\" minimum focus distance"
      },
      "images": {
        "standard": "http://img.bbystatic.com/BestBuy_US/images/products/5729/5729048_sc.jpg"
      },
      "links": {
        "product": "https://api.bestbuy.com/v1/products/5729048.json?apiKey=YourAPIKey",
        "web": "http://www.bestbuy.com/site/canon-ef-40mm-f-2-8-stm-standard-lens-black/5729048.p?id=1218688218296&skuId=5729048&cmp=RMX&ky=2l9pmD3wUBb9cc0tkHo49KBFCMPCiIPY4#tab=buyingOptions",
        "addToCart": "https://api.bestbuy.com/click/-/5729048/cart"
      },
      "names": {
        "title": "Canon - EF 40mm f/2.8 STM Standard Lens - Black"
      },
      "offers": [
        {
          "condition": "excellent",
          "prices": {
            "current": 167.99,
            "regular": 199.99
          }
        }
      ],
      "prices": {
        "current": 199.99,
        "regular": 199.99
      },
      "sku": "5729048"
    }
  ]
}

Fetch the data, then process the results. You can adjust your filter based on the BestBuy categories and based on what other criteria their API returns (i.e. price, condition, etc.). Below is some sample code that uses the API to get results from the camera category, then only filter out all items above a certain price.

//search based on your desired BestBuy category ID - need to look up the IDs from their documentation
//change the searchCategoryID when you want to search for a different category
const getAPIData = (searchCategoryID) =>{
    //used built-in Fetch Web API to perform a get request. Need to get an API Key from Best Buy
    fetch(`https://api.bestbuy.com/beta/products/openBox(categoryId=${searchCategoryID})?apiKey=YourAPIKey`)
    .then(response => response.json())
    .then(data => {
        //process the data, that is formated like above, with the filter array method
        const dataArr=data.results;
        results.filter(item =>{
            //this is an example where we only keep items less than some target price. You would need to set your filter criteria to what you want
            //you can only use the data best buy returns in their api
            if(item.prices.current<targetPrice){return true;}
            else{return false;}
        })
    });
}


问:
Run application without GUI on iOS?
I have a C++ library that I want to include into my iOS application. It has unit tests. If I put it simply, it's something like:

```<code>#include <cstdio>
int main()
{
   printf("Test result\n");
}
</code>```

Is it possible to run such an application that uses only stdin/stdout on an arm64 based iOS device to make sure that all compiles and works correctly?

I can do it on a real android device with adb push/adb shell, so I wonder, is it possible to do the same on iOS based devices?

答:
It's not completely clear what are you trying to archive. But let me guess:

There is a third-party library you don't have control over.

There're tests in this library. The tests are a separate console app.

And you're looking for a way to run this app in some kind of shell on iOS that can run an arbitrary executables. And you can't because of all the security.

But if you have the source code of unit tests, then with some small changes you can compile them as a library, not as an executable. And call them from a "shell" you can write yourself - a small host app the sole purpose of which is to call these tests (and probably send their results via any kind of connection that suits you).

More on this you can read here

Yes, this host app will have a GUI, but I don't really understand why do you against it... if you really are.

Also these may be helpfull:

debug bridge for iPhone / shell command prompt

ADB equivalent for iOS device

Title: Run application without GUI on iOS?

Body:
I have a C++ library that I want to include into my iOS application. It has unit tests. If I put it simply, it's something like:

#include <cstdio>
int main()
{
   printf("Test result\n");
}

Is it possible to run such an application that uses only stdin/stdout on an arm64 based iOS device to make sure that all compiles and works correctly?

I can do it on a real android device with adb push/adb shell, so I wonder, is it possible to do the same on iOS based devices?


问:
How to convert float to varchar in SQL Server
I have a float column with numbers of different length and I'm trying to convert them to varchar.

Some values exceed bigint max size, so I can't do something like this

```<code>cast(cast(float_field as bigint) as varchar(100))
</code>```

I've tried using decimal, but numbers aren't of the same size, so this doesn't help too

```<code>CONVERT(varchar(100), Cast(float_field as decimal(38, 0)))
</code>```

Any help is appreciated.

UPDATE:

Sample value is 2.2000012095022E+26.

答:
```<code>SELECT LTRIM(STR(float_field, 25, 0))
</code>```

is the best way so you do not add .0000 and any digit at the end of the value.

ContentLicense: CC BY-SA 2.5

Body:
I have a float column with numbers of different length and I'm trying to convert them to varchar.

Some values exceed bigint max size, so I can't do something like this

cast(cast(float_field as bigint) as varchar(100))

I've tried using decimal, but numbers aren't of the same size, so this doesn't help too

CONVERT(varchar(100), Cast(float_field as decimal(38, 0)))

Any help is appreciated.

UPDATE:

Sample value is 2.2000012095022E+26.

Body:
SELECT LTRIM(STR(float_field, 25, 0))

is the best way so you do not add .0000 and any digit at the end of the value.


问:
Iterating over double 'for-each' function in javascript returning undefined when getting property from 'this' keyword
This must be a stupid question, but I am not able to figure anything to do about it.

I have a simple HTML table with every  element having a property 'data-value'. I need to do some operations based on that, but one column at a time. Hence, I wrote a function which only runs on the first td element of each row. I am getting the rows by running another for each function.

When I use console.log($(this)), I am getting the expected td element from the all the first columns. Now, I want to store the 'data-value' property in another variable and do stuff on it.

```<code>  $(this).find('td:first-of-type').each(function() {
    console.log($(this));
    //returns td object
  })
});
</code>```

As seen here, all the td elements are correctly being logged on console.

But when I use jquery to get the property 'data-value' from it, I get undefined.

What could be the error ? Is this the best way to iterate every column's tds property  ?

$('#table_canvas tbody tr').each(function() {
  $(this).find('td:first-of-type').each(function() {
    console.log($(this));
    //returns td object
  })
});

$('#table_canvas tbody tr').each(function() {
  $(this).find('td:first-of-type').each(function() {
    console.log($(this).attr('data-value'));
    //returns tr object which does not have the 'data-value'property
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}</code>```

HTML Table

      first_name
      is_staff
      last_name

      id

      1
      1
      True
      1

      3
      1
      True
      1

      4
      1
      True
      1

      5
      1
      True
      1

      6
      1
      True
      1

      7
      1
      True
      1

```

答:
its been awhile i dont use javascript but i think this is work for you vanilla js

just select every second child of every tr tag

```<code>document.querySelectorAll('#table_canvas tr td:nth-child(2)').forEach( x => {
    console.log(x.dataset.property);
})
</code>```

Body:
This must be a stupid question, but I am not able to figure anything to do about it.

I have a simple HTML table with every  element having a property 'data-value'. I need to do some operations based on that, but one column at a time. Hence, I wrote a function which only runs on the first td element of each row. I am getting the rows by running another for each function.

When I use console.log($(this)), I am getting the expected td element from the all the first columns. Now, I want to store the 'data-value' property in another variable and do stuff on it.

  $(this).find('td:first-of-type').each(function() {
    console.log($(this));
    //returns td object
  })
});

As seen here, all the td elements are correctly being logged on console.

But when I use jquery to get the property 'data-value' from it, I get undefined.

What could be the error ? Is this the best way to iterate every column's tds property  ?

$('#table_canvas tbody tr').each(function() {
  $(this).find('td:first-of-type').each(function() {
    console.log($(this));
    //returns td object
  })
});

$('#table_canvas tbody tr').each(function() {
  $(this).find('td:first-of-type').each(function() {
    console.log($(this).attr('data-value'));
    //returns tr object which does not have the 'data-value'property
  })
});

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

HTML Table

      first_name
      is_staff
      last_name

      id

      1
      1
      True
      1

      3
      1
      True
      1

      4
      1
      True
      1

      5
      1
      True
      1

      6
      1
      True
      1

      7
      1
      True
      1

Body:
its been awhile i dont use javascript but i think this is work for you vanilla js

just select every second child of every tr tag

document.querySelectorAll('#table_canvas tr td:nth-child(2)').forEach( x => {
    console.log(x.dataset.property);
})


问:
select date and time from 2 columns mysql with date_format
I have a table formatted as follows:

```<code>|   ID   |   Name  |     date       |   time     |
|   1    |    A    |   2020-05-04   |  19:00:00  |
|   2    |    B    |   2020-05-04   |  19:10:00  |
|   3    |    C    |   2020-05-04   |  19:20:00  |
</code>```

I want to select the result between 2020-05-04 - 19:00:00 and 2020-05-04 - 19:20:00, so I'm expecting the result to be B

And if I use date_format:

```<code>SELECT *
  from table
 where (date > DATE_FORMAT('2020-05-04 19:00:00','%Y-%m-%d %T'))
   AND (date < DATE_FORMAT('2020-05-04 19:20:00','%Y-%m-%d %T'))
</code>```

it ends up being wrong because it only uses the date.

How can I search in 2 columns at the same time?

答:
```<code>SELECT *
FROM table
WHERE ADDTIME(`date`, `time`) BEETWEEN '2020-05-04 19:00:00' AND '2020-05-04 19:20:00';
</code>```

If you need strict non-equiation with one or both datetame range borders then replace BETWEEN..END with 2 according unequations.

Body:
I have a table formatted as follows:

|   ID   |   Name  |     date       |   time     |
|   1    |    A    |   2020-05-04   |  19:00:00  |
|   2    |    B    |   2020-05-04   |  19:10:00  |
|   3    |    C    |   2020-05-04   |  19:20:00  |

I want to select the result between 2020-05-04 - 19:00:00 and 2020-05-04 - 19:20:00, so I'm expecting the result to be B

And if I use date_format:

SELECT *
  from table
 where (date > DATE_FORMAT('2020-05-04 19:00:00','%Y-%m-%d %T'))
   AND (date < DATE_FORMAT('2020-05-04 19:20:00','%Y-%m-%d %T'))

it ends up being wrong because it only uses the date.

How can I search in 2 columns at the same time?

Body:
SELECT *
FROM table
WHERE ADDTIME(`date`, `time`) BEETWEEN '2020-05-04 19:00:00' AND '2020-05-04 19:20:00';

If you need strict non-equiation with one or both datetame range borders then replace BETWEEN..END with 2 according unequations.


问:
Send selected order notification emails from admin list in Woocommerce
Would it be possible to add a custom bulk action to orders list in Woocommerce, which would allow for sending of order emails, based on the orders selected in the list? I have found very useful posts here (such as this), describing the procedure to make custom bulk actions, but I am missing the final piece of the puzzle - how to make that custom bulk action send out order notification emails.

I have looked through numerous plugins, but I haven't found anything related to my problem. Any help is appreciated.

答:
Based on the link you supplied you will need to use wp_mail() function in the foreach loop.

This will send an email to each order in the loop.

Source: https://developer.wordpress.org/reference/functions/wp_mail/


问:
How to efficiently calculate pairwise intersection of nonzero indices in a scipy.csr sparse matrix?
I have a scipy.sparse.csr matrix X which is n x p. For each row in X I would like to compute the intersection of the non zero element indices with each row in X and store them in a new tensor or maybe even a dictionary. For example, X is:

```<code>X = [
[0., 1.5, 4.7],
[4., 0., 0.],
[0., 0., 2.6]
]
</code>```

I would like the output to be

```<code>intersect =
[
[[1,2], [], [2]],
[[], [0], []],
[[2], [], [2]]
]
</code>```

intersect[i,j] is an ndarray representing the intersection of the indices of nonzero elements of ith and jth rows of X i.e X[i], X[j].

Currently the way I am doing this is by looping and I would like to vectorize this as it would be much faster and the computations are done in parallel.

```<code># current code
n = X.shape[0]
intersection_dict = {}
for i in range(n):
    for j in range(n):
        indices = np.intersect1d(X[i].indices, X[j].indices)
        intersection_dict[(i,j)] = indices
</code>```

My n is pretty large so looping over n^2 is very poor. I am just having trouble figuring out a way to vectorize this operation. Does anybody have any ideas on how to tackle this?

EDIT:
It was made apparent that I should explain the problem I am trying to solve, so here it is.

I am solving an optimization problem and have an equation
W = X diag(theta) X'. I want to find W in a quick manner as I update the entries of theta till convergence. Further I am updating parameters using pytorch where sparse operations are not as extensive as in scipy.

where:

```<code>X : n x p sparse data matrix (n documents, p features)
theta : p x 1 parameter vector I want to learn and will be updating
X' : p x n transpose of sparse data matrix

note p >> n
</code>```

I had in mind two methods of solving this quickly

Cache sparse outer product of (see More efficient matrix multiplication with diagonal matrix)

W_ij = X_i * theta * X_j (element wise product of row i of X, theta, and row j of X. And since X_i, X_j are sparse I was thinking if I take the intersection of the nonzero indices then I can do a simple dense elementwise product (sparse element wise product not supported in pytorch) of X_i[intersection indices] * theta[intersection indices] X_j[intersection indices]

I want to vectorize as much of this computation as possible rather than loop as my n is typically in the thousands and p is 11 million.

I am attempting method 2 over method 1 do to the lack of sparse support in Pytorch. Mainly when updating the entries of theta I would not like to do sparse-dense or sparse-sparse operations. I want to do dense-dense operations.

答:
One first easy solution is to notice that the output matrix is symmetrical:

```<code>n = X.shape[0]
intersection_dict = {}
for i in range(n):
    for j in range(i,n): #note the edit here
        indices = np.intersect1d(X[i].indices, X[j].indices)
        intersection_dict[(i,j)] = indices
</code>```

This will reduce by a bit less than 2X your computation

Body:
I have a scipy.sparse.csr matrix X which is n x p. For each row in X I would like to compute the intersection of the non zero element indices with each row in X and store them in a new tensor or maybe even a dictionary. For example, X is:

X = [
[0., 1.5, 4.7],
[4., 0., 0.],
[0., 0., 2.6]
]

I would like the output to be

intersect =
[
[[1,2], [], [2]],
[[], [0], []],
[[2], [], [2]]
]

intersect[i,j] is an ndarray representing the intersection of the indices of nonzero elements of ith and jth rows of X i.e X[i], X[j].

Currently the way I am doing this is by looping and I would like to vectorize this as it would be much faster and the computations are done in parallel.

# current code
n = X.shape[0]
intersection_dict = {}
for i in range(n):
    for j in range(n):
        indices = np.intersect1d(X[i].indices, X[j].indices)
        intersection_dict[(i,j)] = indices

My n is pretty large so looping over n^2 is very poor. I am just having trouble figuring out a way to vectorize this operation. Does anybody have any ideas on how to tackle this?

EDIT:
It was made apparent that I should explain the problem I am trying to solve, so here it is.

I am solving an optimization problem and have an equation
W = X diag(theta) X'. I want to find W in a quick manner as I update the entries of theta till convergence. Further I am updating parameters using pytorch where sparse operations are not as extensive as in scipy.

where:

X : n x p sparse data matrix (n documents, p features)
theta : p x 1 parameter vector I want to learn and will be updating
X' : p x n transpose of sparse data matrix

note p >> n

I had in mind two methods of solving this quickly

Cache sparse outer product of (see More efficient matrix multiplication with diagonal matrix)

W_ij = X_i * theta * X_j (element wise product of row i of X, theta, and row j of X. And since X_i, X_j are sparse I was thinking if I take the intersection of the nonzero indices then I can do a simple dense elementwise product (sparse element wise product not supported in pytorch) of X_i[intersection indices] * theta[intersection indices] X_j[intersection indices]

I want to vectorize as much of this computation as possible rather than loop as my n is typically in the thousands and p is 11 million.

I am attempting method 2 over method 1 do to the lack of sparse support in Pytorch. Mainly when updating the entries of theta I would not like to do sparse-dense or sparse-sparse operations. I want to do dense-dense operations.

Body:
One first easy solution is to notice that the output matrix is symmetrical:

n = X.shape[0]
intersection_dict = {}
for i in range(n):
    for j in range(i,n): #note the edit here
        indices = np.intersect1d(X[i].indices, X[j].indices)
        intersection_dict[(i,j)] = indices

This will reduce by a bit less than 2X your computation


问:
how to convert byte* into jpeg file in VC++
how to convert byte*  into jpeg file in VC++

i am capturing Video samples and writing it as bmp files, but i want to write that video samples into jpeg file using MFC support in ATL COM.

答: Use libjpg. Download from: http://www.ijg.org/</p>

OwnerDisplayName: BALA

LastEditorDisplayName: BALA

OwnerDisplayName: Jimmy J


问:
Shared variables in TypeScripts just like in JS
In JS I am able to connect scripts inside HTML. Assume I have two scripts first.js and second.js, so I can make this:

```<code><script src=".../first.js"></script>
<script src=".../second.js"></script>
</code>```

and then I am able to use any variable of first.js in second.js
How to reach such a result via TypeScript keeping those scripts as separated files?

答:
In order to avoid globals, you can extract the shared parts into a separate module:

shared.ts

```<code>const MY_VAR = 1337;

export { MY_VAR }
</code>```

and use it in one of the other scripts:

first.ts:

```<code>import { MY_VAR } from './shared';

console.log(MY_VAR);
</code>```

Body:
In JS I am able to connect scripts inside HTML. Assume I have two scripts first.js and second.js, so I can make this:

and then I am able to use any variable of first.js in second.js
How to reach such a result via TypeScript keeping those scripts as separated files?

Body:
In order to avoid globals, you can extract the shared parts into a separate module:

shared.ts

const MY_VAR = 1337;

export { MY_VAR }

and use it in one of the other scripts:

first.ts:

import { MY_VAR } from './shared';

console.log(MY_VAR);


问:
With an Azure Function, can a single CosmosDB change feed be processed concurrently?
With a CosmosDb-trigger function-binding to process a change feed, do I need to handle the possibility that multiple functions can be running concurrently, processing different parts of the change feed?

If not, am I right to consider that this means there is a potential performance bottleneck? (in that it may be possible for data to be ingested by multiple instances, faster than a single instance can process the feed).

答:
Yes I need to handle the possibility. And there shouldn't be a performance bottleneck.

See Matias' answer at cosmosdb-change-feed-scaling, which goes into more detail.


问:
Creating an JS array from PHP
I'm developing a Google Geochart and I'd like it to be dynamic. This is the static code to make the array to store the two values are as follows. The Country is the unique identifier for the map and the colour value is what the colour of the map will be. (Irrelevant but context)

```<code>  arrayData = [['Country','Color Value'],
  ['China',3],
  ['Russia',2.6],
  ['France',2.5],
  ['Spain',2.4],
  ['Portugal',1.1]
</code>```

I'd like to be able to make this array from a for loop taken from php echo values. Something like this pseudo code;

```<code>for (i in range table.length)

 arrayData = [['Country','Color Value'],

 [<?php echo $statements["Country"]; ?>], [<?php echo $statements["Color_Value"]; ?>],
</code>```

So similar to a php table as it gets all the values, I would like to do the same but for a JavaScript array. Any advice would be kind!

EDIT: The static code is an example, I want to take values from the database, the first value being country and the second value being colour value. BOTH from the database. I suppose in turn making the geochart dynamic

答:
```<code>//First you need to check the structure of the result from your database query
//Then Loop through the result Object/Array to get the desired structure
//Most Common way of doing this is foreach loop

//define an blank array
$chart = [];

//put your axis tags/ texts in on first index
$chart[] = ['Country', 'Colour Count'];

//let's say $reult stores the data fetched from database

foreach ($result as $key => $value){
    //let's assume $value has field with country name as value
    //and field colour_count have color count values, so
    // $value->country = Country Name
    //$value->colour_count = Color Count Value
    $chart[] = [$value->country, $value->colour_count];
}
// Once the Loop is finished, you will get an array with your desired format

//$chart = [['Country', 'Colour Count'],['France', 12],['USA',34],.....so on];
</code>```

Title: Creating an JS array from PHP

Body:
I'm developing a Google Geochart and I'd like it to be dynamic. This is the static code to make the array to store the two values are as follows. The Country is the unique identifier for the map and the colour value is what the colour of the map will be. (Irrelevant but context)

  arrayData = [['Country','Color Value'],
  ['China',3],
  ['Russia',2.6],
  ['France',2.5],
  ['Spain',2.4],
  ['Portugal',1.1]

I'd like to be able to make this array from a for loop taken from php echo values. Something like this pseudo code;

for (i in range table.length)

 arrayData = [['Country','Color Value'],

 [<?php echo $statements["Country"]; ?>], [<?php echo $statements["Color_Value"]; ?>],

So similar to a php table as it gets all the values, I would like to do the same but for a JavaScript array. Any advice would be kind!

EDIT: The static code is an example, I want to take values from the database, the first value being country and the second value being colour value. BOTH from the database. I suppose in turn making the geochart dynamic


问:
Clion and cmd ssh WSL are refused on windows 10
I've configured WSL for my computer, and it work in WSL terminal successfully.

```<code>zoom@Zoom:/etc/ssh$ ssh zoom@localhost -p 2222
zoom@localhost's password:
Welcome to Ubuntu 20.04 LTS (GNU/Linux 4.19.104-microsoft-standard x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue Jun  2 19:42:24 CST 2020

  System load:  0.0                Processes:             16
  Usage of /:   0.9% of 250.98GB   Users logged in:       0
  Memory usage: 1%                 IPv4 address for eth0: myIpAddress
  Swap usage:   0%

0 updates can be installed immediately.
0 of these updates are security updates.

Last login: Tue Jun  2 19:33:21 2020 from 127.0.0.1
</code>```

However, I can't ssh WSL with cmd or Clion.

```<code>CMD:
C:\Users\Zoom>ssh zoom@localhost -p 2222
ssh: connect to host localhost port 2222: Connection refused

Clion ssh
I get this error
Can't connect to remote host: Connection refused: connect
</code>```

I have tried my best to search for a solution. But no solution works

this is some information on my sshd_config file:

```<code>ListenAddress 0.0.0.0
Port 2222
UsePrivilegeSeparation no
PasswordAuthentication yes
AllowUsers zoom
</code>```

I realy want to know how to fix it.

My Windos version is 2004 (os build 19635.1).

WSL version is 2.

WSL system is ubuntu-20.04

Thanks very much!

答:
Ok, I see the problem.
The WSL2 is said to use a virtual machine. So the IP in WSL is different from that in Windows. You won't have this problem in WSL version 1.
Unfortunately, this will change the IP address of the WSL every time you reboot. There are also some solutions but I can't understand, so I will put the link reference from someone blog in chinese: https://www.oyohyee.com/post/note_wsl2_net
(I don't know if this blog can solve the problem, but it seems like it could)
I found the official solution: https://devblogs.microsoft.com/commandline/whats-new-for-wsl-in-insiders-preview-build-18945/</p>

Body:
I've configured WSL for my computer, and it work in WSL terminal successfully.

zoom@Zoom:/etc/ssh$ ssh zoom@localhost -p 2222
zoom@localhost's password:
Welcome to Ubuntu 20.04 LTS (GNU/Linux 4.19.104-microsoft-standard x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue Jun  2 19:42:24 CST 2020

  System load:  0.0                Processes:             16
  Usage of /:   0.9% of 250.98GB   Users logged in:       0
  Memory usage: 1%                 IPv4 address for eth0: myIpAddress
  Swap usage:   0%

0 updates can be installed immediately.
0 of these updates are security updates.

Last login: Tue Jun  2 19:33:21 2020 from 127.0.0.1

However, I can't ssh WSL with cmd or Clion.

CMD:
C:\Users\Zoom>ssh zoom@localhost -p 2222
ssh: connect to host localhost port 2222: Connection refused

Clion ssh
I get this error
Can't connect to remote host: Connection refused: connect

I have tried my best to search for a solution. But no solution works

this is some information on my sshd_config file:

ListenAddress 0.0.0.0
Port 2222
UsePrivilegeSeparation no
PasswordAuthentication yes
AllowUsers zoom

I realy want to know how to fix it.

My Windos version is 2004 (os build 19635.1).

WSL version is 2.

WSL system is ubuntu-20.04

Thanks very much!


问:
AmazonS3: Getting warning: S3AbortableInputStream:Not all bytes were read from the S3ObjectInputStream, aborting HTTP connection
Here's the warning that I am getting:

S3AbortableInputStream:Not all bytes were read from the S3ObjectInputStream, aborting HTTP connection. This is likely an error and may result in sub-optimal behavior. Request only the bytes you need via a ranged GET or drain the input stream after use.

I tried using try with resources but S3ObjectInputStream doesn't seem to close via this method.

```<code> try (S3Object s3object = s3Client.getObject(new GetObjectRequest(bucket, key));
      S3ObjectInputStream s3ObjectInputStream = s3object.getObjectContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(s3ObjectInputStream, StandardCharsets.UTF_8));
    ){
  //some code here blah blah blah
 }
</code>```

I also tried below code and explicitly closing but that doesn't work either:

```<code>S3Object s3object = s3Client.getObject(new GetObjectRequest(bucket, key));
S3ObjectInputStream s3ObjectInputStream = s3object.getObjectContent();

try (BufferedReader reader = new BufferedReader(new InputStreamReader(s3ObjectInputStream, StandardCharsets.UTF_8));
){
     //some code here blah blah
     s3ObjectInputStream.close();
     s3object.close();
}
</code>```

Any help would be appreciated.

PS: I am only reading two lines of the file from S3 and the file has more data.

答:
I ran into the same error.

As others have pointed out, the /tmp space in lambda is limited to 512 MB.
And if the lambda context is re-used for a new invocation, then the /tmp space is already half-full.

So, when reading the S3 objects and writing all the files to the /tmp directory (as I was doing),
I ran out of disk space somewhere in between.
Lambda exited with error, but NOT all bytes from the S3ObjectInputStream were read.

So, two things one need to keep in mind:

1) If the first execution causes the problem, be stingy with your /tmp space.
   We have only 512 MB

2) If the second execution causes the problem, then this could be resolved by attacking the root problem.
   Its not possible to delete the /tmp folder.
   So, delete all the files in the /tmp folder after the execution is finished.

In java, here is what I did, which successfully resolved the problem.

public String handleRequest(Map < String, String > keyValuePairs, Context lambdaContext) {
  try {
    // All work here
  } catch (Exception e) {
    logger.error("Error {}", e.toString());
    return "Error";
  } finally {
    deleteAllFilesInTmpDir();
  }
}
private void deleteAllFilesInTmpDir() {
  Path path = java.nio.file.Paths.get(File.separator, "tmp", File.separator);
  try {
    if (Files.exists(path)) {
      deleteDir(path.toFile());
      logger.info("Successfully cleaned up the tmp directory");
    }
  } catch (Exception ex) {
    logger.error("Unable to clean up the tmp directory");
  }
}
public void deleteDir(File dir) {
  File[] files = dir.listFiles();
  if (files != null) {
    for (final File file: files) {
      deleteDir(file);
    }
  }
  dir.delete();
}```

ContentLicense: CC BY-SA 3.0

Body:
Here's the warning that I am getting:

S3AbortableInputStream:Not all bytes were read from the S3ObjectInputStream, aborting HTTP connection. This is likely an error and may result in sub-optimal behavior. Request only the bytes you need via a ranged GET or drain the input stream after use.

I tried using try with resources but S3ObjectInputStream doesn't seem to close via this method.

 try (S3Object s3object = s3Client.getObject(new GetObjectRequest(bucket, key));
      S3ObjectInputStream s3ObjectInputStream = s3object.getObjectContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(s3ObjectInputStream, StandardCharsets.UTF_8));
    ){
  //some code here blah blah blah
 }

I also tried below code and explicitly closing but that doesn't work either:

S3Object s3object = s3Client.getObject(new GetObjectRequest(bucket, key));
S3ObjectInputStream s3ObjectInputStream = s3object.getObjectContent();

try (BufferedReader reader = new BufferedReader(new InputStreamReader(s3ObjectInputStream, StandardCharsets.UTF_8));
){
     //some code here blah blah
     s3ObjectInputStream.close();
     s3object.close();
}

Any help would be appreciated.

PS: I am only reading two lines of the file from S3 and the file has more data.


问:
Image get disappeared while zooming out image using DeltaManipulation event (pinching)
My requirement is to do pinch zooming in WPF platform. For that, i have created simple POC sample according to my requirement and it can be reproduced. Please find the snippets below

XAML:

```<code><Grid>
    <Image x:Name="JPGImage"
           Source="TestImage.jpg"
           IsManipulationEnabled="True"
           ManipulationDelta="Image_ManipulationDelta"
           ManipulationStarted="JPGImage_ManipulationStarted"
           ManipulationCompleted="JPGImage_ManipulationCompleted"/>
</Grid>
</code>```

C#:

```<code>private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.DeltaManipulation.Translation.X + " " + e.DeltaManipulation.Translation.Y);
    if (e.Manipulators.Count() > 1)
    {
        if (scale.ScaleX > 1.6 || scale.ScaleX < 0.5)
        {
            scale.ScaleX = 1;
            scale.ScaleY = 1;
            translation.X = 0;
            translation.Y = 0;
            this.JPGImage.RenderTransform = transformGroup;
        }
        else
        {
            if (isScale)
            {
                scale.ScaleX = previousCumlativeScale * e.DeltaManipulation.Scale.X;
                scale.ScaleY = previousCumlativeScale * e.DeltaManipulation.Scale.Y;
                var x = (e.ManipulationOrigin.X - previousXPosition) * (scale.ScaleX - 1);
                var y = (e.ManipulationOrigin.Y - previousYPosition) * (scale.ScaleY - 1);
                translation.X += x;
                translation.Y += y;
            }
            else
            {
                scale.ScaleX *= e.DeltaManipulation.Scale.X;
                scale.ScaleY *= e.DeltaManipulation.Scale.Y;
                translation.X += e.DeltaManipulation.Translation.X;
                translation.Y += e.DeltaManipulation.Translation.Y;
            }

            scale.CenterX = e.ManipulationOrigin.X;
            scale.CenterY = e.ManipulationOrigin.Y;
            this.JPGImage.RenderTransform = transformGroup;
        }

        previousCumlativeScale = scale.ScaleX;
        previousTranslateX = translation.X;
        previousTranslateY = translation.Y;
        previousXPosition = scale.CenterX;
        previousYPosition = scale.CenterY;
    }
    else
    {
        translation.X += e.DeltaManipulation.Translation.X;
        translation.Y += e.DeltaManipulation.Translation.Y;
    }
}
</code>```

My problems are

If i try to Zoomout the image using pinch, then it get disappeared when its scale value becomes less than 1

Zooming is also not smooth

Also i have reset the zoom after certain level of scale (mentioned below) then the image is not get reset properly.

C#

```<code>         if (scale.ScaleX > 1.6 || scale.ScaleX < 0.5)
         {
            scale.ScaleX = 1;
            scale.ScaleY = 1;
            translation.X = 0;
            translation.Y = 0;
            this.JPGImage.RenderTransform = transformGroup;
         }
</code>```

Please get the sample from the below link
WPFZooming

I have found the below issue only related to manipulation events in github
https://github.com/Microsoft/dotnet/issues/575

Could you please help me to resolve the problems?.

Thanks in advance

Vignesh.

答:
Not sure why exactly your code seems so complicated. The following also works, where the important point is to handle the ManipulationDelta on the parent element of the Image element:

```<code><Canvas IsManipulationEnabled="True"
        ManipulationDelta="OnManipulationDelta">
    <Image Source="...">
        <Image.RenderTransform>
            <MatrixTransform x:Name="imageTransform"/>
        </Image.RenderTransform>
    </Image>
</Canvas>
</code>```

with this event handler:

```<code>private void OnManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
    var origin = e.ManipulationOrigin;
    var delta = e.DeltaManipulation;
    var scale = (delta.Scale.X + delta.Scale.Y) / 2; // mean value

    var matrix = imageTransform.Matrix; // current transform matrix

    matrix.ScaleAt(scale, scale, origin.X, origin.Y);
    matrix.Translate(delta.Translation.X, delta.Translation.Y);

    imageTransform.Matrix = matrix; // new transform matrix
}
</code>```

Body:
My requirement is to do pinch zooming in WPF platform. For that, i have created simple POC sample according to my requirement and it can be reproduced. Please find the snippets below

XAML:

<Grid>
    <Image x:Name="JPGImage"
           Source="TestImage.jpg"
           IsManipulationEnabled="True"
           ManipulationDelta="Image_ManipulationDelta"
           ManipulationStarted="JPGImage_ManipulationStarted"
           ManipulationCompleted="JPGImage_ManipulationCompleted"/>
</Grid>

C#:

private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.DeltaManipulation.Translation.X + " " + e.DeltaManipulation.Translation.Y);
    if (e.Manipulators.Count() > 1)
    {
        if (scale.ScaleX > 1.6 || scale.ScaleX < 0.5)
        {
            scale.ScaleX = 1;
            scale.ScaleY = 1;
            translation.X = 0;
            translation.Y = 0;
            this.JPGImage.RenderTransform = transformGroup;
        }
        else
        {
            if (isScale)
            {
                scale.ScaleX = previousCumlativeScale * e.DeltaManipulation.Scale.X;
                scale.ScaleY = previousCumlativeScale * e.DeltaManipulation.Scale.Y;
                var x = (e.ManipulationOrigin.X - previousXPosition) * (scale.ScaleX - 1);
                var y = (e.ManipulationOrigin.Y - previousYPosition) * (scale.ScaleY - 1);
                translation.X += x;
                translation.Y += y;
            }
            else
            {
                scale.ScaleX *= e.DeltaManipulation.Scale.X;
                scale.ScaleY *= e.DeltaManipulation.Scale.Y;
                translation.X += e.DeltaManipulation.Translation.X;
                translation.Y += e.DeltaManipulation.Translation.Y;
            }

            scale.CenterX = e.ManipulationOrigin.X;
            scale.CenterY = e.ManipulationOrigin.Y;
            this.JPGImage.RenderTransform = transformGroup;
        }

        previousCumlativeScale = scale.ScaleX;
        previousTranslateX = translation.X;
        previousTranslateY = translation.Y;
        previousXPosition = scale.CenterX;
        previousYPosition = scale.CenterY;
    }
    else
    {
        translation.X += e.DeltaManipulation.Translation.X;
        translation.Y += e.DeltaManipulation.Translation.Y;
    }
}

My problems are

If i try to Zoomout the image using pinch, then it get disappeared when its scale value becomes less than 1

Zooming is also not smooth

Also i have reset the zoom after certain level of scale (mentioned below) then the image is not get reset properly.

C#

         if (scale.ScaleX > 1.6 || scale.ScaleX < 0.5)
         {
            scale.ScaleX = 1;
            scale.ScaleY = 1;
            translation.X = 0;
            translation.Y = 0;
            this.JPGImage.RenderTransform = transformGroup;
         }

Please get the sample from the below link
WPFZooming

I have found the below issue only related to manipulation events in github
https://github.com/Microsoft/dotnet/issues/575

Could you please help me to resolve the problems?.

Thanks in advance

Vignesh.

Body:
Not sure why exactly your code seems so complicated. The following also works, where the important point is to handle the ManipulationDelta on the parent element of the Image element:

<Canvas IsManipulationEnabled="True"
        ManipulationDelta="OnManipulationDelta">
    <Image Source="...">
        <Image.RenderTransform>
            <MatrixTransform x:Name="imageTransform"/>
        </Image.RenderTransform>
    </Image>
</Canvas>

with this event handler:

private void OnManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
    var origin = e.ManipulationOrigin;
    var delta = e.DeltaManipulation;
    var scale = (delta.Scale.X + delta.Scale.Y) / 2; // mean value

    var matrix = imageTransform.Matrix; // current transform matrix

    matrix.ScaleAt(scale, scale, origin.X, origin.Y);
    matrix.Translate(delta.Translation.X, delta.Translation.Y);

    imageTransform.Matrix = matrix; // new transform matrix
}


问:
Which table is used when using class inheritance for models?
I am working on a .NET Core 3.1 Web API. Suppose I have the following model classes:

This is a model that points to an underlying database table called TableA:

```<code>[Table("TableA")]
public class TableA
{
    public string ColumnA { get; set; }
}
</code>```

This is a model that inherits from TableA but gets extra columns from a view in the database:

```<code>[Table("ViewTableA")]
public class ViewTableA : TableA
{
    public string ColumnA { get; set; }
    other properties from view ...
}
</code>```

When reading from the database I will query using the ViewTableA model.  Since the ViewTableA has the attribute [Table("ViewTableA")] entity framework with generate the query to pull data from the ViewTableA view.

My question is if I had the following:

```<code>ViewTableA objA = new ViewTableA(){ populate properties here};
TableA objB = (TableA)objA;
</code>```

If I were to add objB to the DBContext and save the changes which table/view would it hit?  The TableA table since objB is of type TableA which has an attribute of [Table("TableA")] or would it still hit the view called ViewTableA?

答: objB won't be change tracked until you call db.Set<T>().Add(objB); If you call db.Set<ViewTableA>().Add(objB), all is well. If you call db.Set<TableA>().Add(objB) EF might insert into TableA or ViewTableA, or fail. I'm not sure which, and you shouldn't rely on the behavior.

Body:
I am working on a .NET Core 3.1 Web API. Suppose I have the following model classes:

This is a model that points to an underlying database table called TableA:

[Table("TableA")]
public class TableA
{
    public string ColumnA { get; set; }
}

This is a model that inherits from TableA but gets extra columns from a view in the database:

[Table("ViewTableA")]
public class ViewTableA : TableA
{
    public string ColumnA { get; set; }
    other properties from view ...
}

When reading from the database I will query using the ViewTableA model.  Since the ViewTableA has the attribute [Table("ViewTableA")] entity framework with generate the query to pull data from the ViewTableA view.

My question is if I had the following:

ViewTableA objA = new ViewTableA(){ populate properties here};
TableA objB = (TableA)objA;

If I were to add objB to the DBContext and save the changes which table/view would it hit?  The TableA table since objB is of type TableA which has an attribute of [Table("TableA")] or would it still hit the view called ViewTableA?


问:
Regex: Exclude 5 digit numbers
The regex should match every value (+ whitepsaces) that does not include a 5 digit number:

12345 - no match

abc12345 - no match

abc123456 - match

12345abc - no match

123456abc - match

abc12345abc - no match

abc123456abc - match

abc123 - match

The current regex does not work properly as it does not exclude numbers with more than 5 digits

```<code>^(?!(?:\.|^)(\d{5})(?:\.|$)).*$
</code>```

https://regex101.com/r/CRcZzM/1

答:
You  may use

```<code>^(?!.*(?<!\d)\d{5}(?!\d)).*
^(?!.*(?:\D|^)\d{5}(?!\d)).*
</code>```

See the regex demo.

Details

^ - start of string

(?!.*(?<!\d)\d{5}(?!\d)) - a negative lookahead that fails the match if, immediately to the right of the current location, there is

.* - any 0 or more chars other than line break chars, as many as possible.

(?<!\d)\d{5}(?!\d) - a five digit string (\d{5}) neither preceded ((?<!\d)) nor followed with a digit ((?!\d))

.* - any 0 or more chars other than line break chars, as many as possible.

You do not need the last .* if you do not need a full string match.

Title: Regex: Exclude 5 digit numbers

Body:
The regex should match every value (+ whitepsaces) that does not include a 5 digit number:

12345 - no match

abc12345 - no match

abc123456 - match

12345abc - no match

123456abc - match

abc12345abc - no match

abc123456abc - match

abc123 - match

The current regex does not work properly as it does not exclude numbers with more than 5 digits

^(?!(?:\.|^)(\d{5})(?:\.|$)).*$

https://regex101.com/r/CRcZzM/1

Body:
You  may use

^(?!.*(?<!\d)\d{5}(?!\d)).*
^(?!.*(?:\D|^)\d{5}(?!\d)).*

See the regex demo.

Details

^ - start of string

(?!.*(?<!\d)\d{5}(?!\d)) - a negative lookahead that fails the match if, immediately to the right of the current location, there is

.* - any 0 or more chars other than line break chars, as many as possible.

(?<!\d)\d{5}(?!\d) - a five digit string (\d{5}) neither preceded ((?<!\d)) nor followed with a digit ((?!\d))

.* - any 0 or more chars other than line break chars, as many as possible.

You do not need the last .* if you do not need a full string match.


问:
no such file to load -- rspec/matchers - rspec-rails, shoulda, cucumber, factory girl, Rails2.3.10
I've inherited an old Rails2.3 app. It's very complex and has (shock, horror) no tests whatsoever. I'm used to rspec and cucumber so I thought I'd start working on getting specs and features defined for the eventual (long-away) upgrade to Rails 3. It's easier to upgrade if I know exactly what will fail.

Anyway, I found it very difficult to find resources on the internet that show how to set up rspec, cucumber, factory girl, and shoulda in a rails 2.3 environment. My bundle is as follows:

```<code>source "http://rubygems.org"

# Production gems
gem "rails",    "2.3.10"
gem "nokogiri", "1.4.4"
gem "mysql",    "~> 2.8.1"

group :development do
  # bundler requires these gems in development
  gem 'rspec',          '1.3.2'
  gem 'rspec-core',     '2.5.2'
  gem 'rspec-rails',    '1.3.4'
end

group :test do
  # bundler requires these gems while running tests
  gem 'cucumber-rails', '0.4.1'
  gem 'factory_girl'
  gem 'shoulda',        '2.11.3'
  gem 'shoulda-matchers'
end
</code>```

When I go to run

```<code>bundle exec rspec spec,
</code>```

I get the following stacktrace from shoulda:

```<code>/Users/sys/src/proj/rails/ruby/1.8/gems/shoulda-2.11.3/lib/shoulda/integrations/rspec2.rb:8: no such file to load -- rspec/matchers (MissingSourceFile)
    from /Users/sys/src/proj/vendor/rails/activesupport/lib/active_support/dependencies.rb:184:in `require'
    from /Users/sys/src/proj/vendor/rails/activesupport/lib/active_support/dependencies.rb:184:in `require'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/shoulda-2.11.3/lib/shoulda.rb:4
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:68:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:68:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:66:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:66:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:55:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:55:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler.rb:120:in `require'
    from /Users/sys/src/proj/config/boot.rb:119:in `load_gems'
    from /Users/sys/src/proj/config/../vendor/rails/railties/lib/initializer.rb:164:in `process'
    from /Users/sys/src/proj/config/../vendor/rails/railties/lib/initializer.rb:113:in `send'
    from /Users/sys/src/proj/config/../vendor/rails/railties/lib/initializer.rb:113:in `run'
    from /Users/sys/src/proj/config/environment.rb:12
    from /Users/sys/src/proj/spec/spec_helper.rb:4:in `require'
    from /Users/sys/src/proj/spec/spec_helper.rb:4
    from /Users/sys/src/proj/spec/models/announcement_spec.rb:1:in `require'
    from /Users/sys/src/proj/spec/models/announcement_spec.rb:1
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/configuration.rb:386:in `load'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/configuration.rb:386:in `load_spec_files'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/configuration.rb:386:in `map'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/configuration.rb:386:in `load_spec_files'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/runner.rb:46:in `run'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/runner.rb:10:in `autorun'
    from /Users/sys/src/proj/rails/ruby/1.8/bin/rspec:19
</code>```

Googling for that error provides frighteningly few hits... I'm not sure what I've done wrong?

Removing rspec-core gives:

bundle exec rspec spec/models/announcement_spec.rb
/Users/sys/.rvm/gems/ree-1.8.7-2011.03@proj/gems/bundler-1.0.14/lib/bundler/rubygems_integration.rb:143:in `gem': rspec-core is not part of the bundle. Add it to Gemfile. (Gem::LoadError)

contents of opt/local/bin/rspec

```<code>cat /opt/local/bin/rspec
#!/usr/bin/env ruby
#
# This file was generated by RubyGems.
#
# The application 'rspec-core' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'

version = ">= 0"

if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
  version = $1
  ARGV.shift
end

gem 'rspec-core', version
load Gem.bin_path('rspec-core', 'rspec', version)
</code>```

I wonder if this is conflicting with other rspec's I have installed (I've a Rails3 app installed, also with bundler/rvm)... Not sure why rspec is being run out of opt/local/bin and not the bundle, though..

答:
It looks like rspec-core, which is from a version of rspec that only supports Rails 3, may be the problem. Try uninstalling that and removing it from your Gemfile.

For comparison, here's a section from our Gemfile that works fine for Rails 2.3:

```<code>group :development, :local, :test do
  gem "rspec",              "= 1.3.1"
  gem "rspec-rails",        "= 1.3.3"
  gem "factory_girl",       "= 1.3.3"
  gem "webrat",             "= 0.7.3"
  gem "shoulda",            "= 2.11.3"
end
</code>```

Body:
I've inherited an old Rails2.3 app. It's very complex and has (shock, horror) no tests whatsoever. I'm used to rspec and cucumber so I thought I'd start working on getting specs and features defined for the eventual (long-away) upgrade to Rails 3. It's easier to upgrade if I know exactly what will fail.

Anyway, I found it very difficult to find resources on the internet that show how to set up rspec, cucumber, factory girl, and shoulda in a rails 2.3 environment. My bundle is as follows:

source "http://rubygems.org"

# Production gems
gem "rails",    "2.3.10"
gem "nokogiri", "1.4.4"
gem "mysql",    "~> 2.8.1"

group :development do
  # bundler requires these gems in development
  gem 'rspec',          '1.3.2'
  gem 'rspec-core',     '2.5.2'
  gem 'rspec-rails',    '1.3.4'
end

group :test do
  # bundler requires these gems while running tests
  gem 'cucumber-rails', '0.4.1'
  gem 'factory_girl'
  gem 'shoulda',        '2.11.3'
  gem 'shoulda-matchers'
end

When I go to run

bundle exec rspec spec,

I get the following stacktrace from shoulda:

/Users/sys/src/proj/rails/ruby/1.8/gems/shoulda-2.11.3/lib/shoulda/integrations/rspec2.rb:8: no such file to load -- rspec/matchers (MissingSourceFile)
    from /Users/sys/src/proj/vendor/rails/activesupport/lib/active_support/dependencies.rb:184:in `require'
    from /Users/sys/src/proj/vendor/rails/activesupport/lib/active_support/dependencies.rb:184:in `require'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/shoulda-2.11.3/lib/shoulda.rb:4
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:68:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:68:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:66:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:66:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:55:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler/runtime.rb:55:in `require'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.14/lib/bundler.rb:120:in `require'
    from /Users/sys/src/proj/config/boot.rb:119:in `load_gems'
    from /Users/sys/src/proj/config/../vendor/rails/railties/lib/initializer.rb:164:in `process'
    from /Users/sys/src/proj/config/../vendor/rails/railties/lib/initializer.rb:113:in `send'
    from /Users/sys/src/proj/config/../vendor/rails/railties/lib/initializer.rb:113:in `run'
    from /Users/sys/src/proj/config/environment.rb:12
    from /Users/sys/src/proj/spec/spec_helper.rb:4:in `require'
    from /Users/sys/src/proj/spec/spec_helper.rb:4
    from /Users/sys/src/proj/spec/models/announcement_spec.rb:1:in `require'
    from /Users/sys/src/proj/spec/models/announcement_spec.rb:1
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/configuration.rb:386:in `load'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/configuration.rb:386:in `load_spec_files'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/configuration.rb:386:in `map'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/configuration.rb:386:in `load_spec_files'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/runner.rb:46:in `run'
    from /Users/sys/src/proj/rails/ruby/1.8/gems/rspec-core-2.5.2/lib/rspec/core/runner.rb:10:in `autorun'
    from /Users/sys/src/proj/rails/ruby/1.8/bin/rspec:19

Googling for that error provides frighteningly few hits... I'm not sure what I've done wrong?

Removing rspec-core gives:

bundle exec rspec spec/models/announcement_spec.rb
/Users/sys/.rvm/gems/ree-1.8.7-2011.03@proj/gems/bundler-1.0.14/lib/bundler/rubygems_integration.rb:143:in `gem': rspec-core is not part of the bundle. Add it to Gemfile. (Gem::LoadError)

contents of opt/local/bin/rspec

cat /opt/local/bin/rspec
#!/usr/bin/env ruby
#
# This file was generated by RubyGems.
#
# The application 'rspec-core' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'

version = ">= 0"

if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
  version = $1
  ARGV.shift
end

gem 'rspec-core', version
load Gem.bin_path('rspec-core', 'rspec', version)

I wonder if this is conflicting with other rspec's I have installed (I've a Rails3 app installed, also with bundler/rvm)... Not sure why rspec is being run out of opt/local/bin and not the bundle, though..

Body:
It looks like rspec-core, which is from a version of rspec that only supports Rails 3, may be the problem. Try uninstalling that and removing it from your Gemfile.

For comparison, here's a section from our Gemfile that works fine for Rails 2.3:

group :development, :local, :test do
  gem "rspec",              "= 1.3.1"
  gem "rspec-rails",        "= 1.3.3"
  gem "factory_girl",       "= 1.3.3"
  gem "webrat",             "= 0.7.3"
  gem "shoulda",            "= 2.11.3"
end


问:
Discord Node.js bot Log recieved messages to console
I'm not really experienced with discord.js and node.js but I want to know how I log DMs being sent to the bot to the console. This is the code I'm using to send messages to different people.

case 'senddm':
  mention = msg.mentions.users.first();
  msg.delete();
  if (mention == null) { return; }
  mentionMessage = msg.content.slice(9);
  mention.sendMessage(mentionMessage);
  console.log(`Send message: ${mentionMessage}`)
break;
```

答:
You can check if your the id of the mentioned user is the same as your bot.

case 'senddm':
  mention = msg.mentions.users.first();
  msg.delete();
  if (mention == null) { return; }
  mentionMessage = msg.content.slice(9);
  mention.sendMessage(mentionMessage);

  if(mention.id === "your bot id here"){
      console.log(`Send message: ${mentionMessage}`)
  }
break;
```


答:
You can combine the two columns using the timestamp function:</p>

```<code>SELECT * FROM `table`
 WHERE timestamp(`date`, `time`) > '2020-05-04 19:00:00'
 AND   timestamp(`date`, `time`) < '2020-05-04 19:20:00'
</code>```

Title: select date and time from 2 columns mysql with date_format

Body:
You can combine the two columns using the timestamp function:

SELECT * FROM `table`
 WHERE timestamp(`date`, `time`) > '2020-05-04 19:00:00'
 AND   timestamp(`date`, `time`) < '2020-05-04 19:20:00'


问:
How to have a teardown function in module scope based on running test result
I want to clean up some files after all tests pass. If they fail, keep them for debug. I read https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures so I have the following in my conftest.py:

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()

    # set a report attribute for each phase of a call, which can
    # be "setup", "call", "teardown"

    setattr(item, "rep_" + rep.when, rep)

@pytest.fixture(scope="module", autouse=True)
def teardown(request):
    yield
    # request.node is an "item" because we use the default
    # "function" scope
    if request.node.rep_setup.failed:
        print("setting up a test failed!", request.node.nodeid)
    elif request.node.rep_setup.passed:
        #clean up my files
```

<p>however, I got the error:</p>

```AttributeError: 'Module' object has no attribute 'rep_setup'
```

The only difference from doc example is that my teardown has 'scope=module'. But I have to do this because I want to clean up files after all tests pass, some files are used by all tests. If I use the default scope which is 'function' level, it will clean up after each test case rather than after the whole module. How can I fix this?

Update: Before I had 'hook', I still had the teardown which is "module" level, and it worked fine, meaning it cleaned up all files for me after all tests running, the only problem is that it will clean up for me no matter tests pass or fail.

答:
If you are in module scope, request.node represents the module, not a single test. If you want just check for failed tests, you can check the session:

@pytest.fixture(scope="module", autouse=True)
def teardown(request):
    yield
    if request.session.testsfailed > 0:
        print(f"{} test(s) failed!", request.session.testsfailed)
    else:
        #  clean up my files
```

<p>I'm not sure if there is any information about setup failures in the request at this point, if you are only interested in these.<br>
In this case you could implement a file scoped fixture which sets a flag in case of a setup failure, and use that, something like:</p>

<pre class="lang-py prettyprint-override"><code>SETUP_FAILED = False

@pytest.fixture(autouse=True)
def teardown_test(request):
    yield
    if request.node.rep_setup.failed:
        global SETUP_FAILED
        SETUP_FAILED = True

@pytest.fixture(scope="module", autouse=True)
def teardown_module():
    global SETUP_FAILED
    SETUP_FAILED = False
    yield
    if SETUP_FAILED:
        print("At least one test setup failed!")
    else:
        #  clean up my files
</code>```

This is not nice, and maybe someone knows a better solution, but it will work.
You could also collect information about the tests where the setup failed if needed.

Body:
I want to clean up some files after all tests pass. If they fail, keep them for debug. I read https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures so I have the following in my conftest.py:

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()

    # set a report attribute for each phase of a call, which can
    # be "setup", "call", "teardown"

    setattr(item, "rep_" + rep.when, rep)

@pytest.fixture(scope="module", autouse=True)
def teardown(request):
    yield
    # request.node is an "item" because we use the default
    # "function" scope
    if request.node.rep_setup.failed:
        print("setting up a test failed!", request.node.nodeid)
    elif request.node.rep_setup.passed:
        #clean up my files

however, I got the error:

AttributeError: 'Module' object has no attribute 'rep_setup'

The only difference from doc example is that my teardown has 'scope=module'. But I have to do this because I want to clean up files after all tests pass, some files are used by all tests. If I use the default scope which is 'function' level, it will clean up after each test case rather than after the whole module. How can I fix this?

Update: Before I had 'hook', I still had the teardown which is "module" level, and it worked fine, meaning it cleaned up all files for me after all tests running, the only problem is that it will clean up for me no matter tests pass or fail.

Body:
If you are in module scope, request.node represents the module, not a single test. If you want just check for failed tests, you can check the session:

@pytest.fixture(scope="module", autouse=True)
def teardown(request):
    yield
    if request.session.testsfailed > 0:
        print(f"{} test(s) failed!", request.session.testsfailed)
    else:
        #  clean up my files

I'm not sure if there is any information about setup failures in the request at this point, if you are only interested in these.

In this case you could implement a file scoped fixture which sets a flag in case of a setup failure, and use that, something like:

SETUP_FAILED = False

@pytest.fixture(autouse=True)
def teardown_test(request):
    yield
    if request.node.rep_setup.failed:
        global SETUP_FAILED
        SETUP_FAILED = True

@pytest.fixture(scope="module", autouse=True)
def teardown_module():
    global SETUP_FAILED
    SETUP_FAILED = False
    yield
    if SETUP_FAILED:
        print("At least one test setup failed!")
    else:
        #  clean up my files

This is not nice, and maybe someone knows a better solution, but it will work.
You could also collect information about the tests where the setup failed if needed.


问:
Every possible combination in a specific order
all out of ideas so looking for help. So I have two tables with a single column with ID's 1-29, each ID represents a coworker. I have a 3rd table where I have already created every combination of records from the first 2 tables.

The part that I am struggling with is that I need to order my 3rd tables as follows, say person 1 calls person 2, the ID in table 3 will look like this: '1-2', now I need to make the next record start with 2 and have person 2 call someone who is not person 1 (who has already been called) and have person 1 not be called again until the remaining 28 people are already called as to ensure that everyone gets called at least once before looking through to other combos.

It's a bit hard to explain so I am willing to elaborate if needed.

For those wondering, the purpose of this exercise to to create a bit of "call train" to have everyone check up on everyone else. Thanks in advance!

答:
You could set up the call chain as follows:

So in Stage 2 1 would call 3 and 2 would call 4 at the same time,etc.  At each stage the number of callers would be double the number of callers from the previous stage.

(it is possible to map this into a tree structure)

EDIT#1:

I generated the pattern with this small VBA macro:

```<code>Sub Peak()
    Dim stage As Long, i As Long, j As Long, K As Long

    K = 1
    j = 1

    For stage = 1 To 5
        For i = 1 To j
            Cells(K, 1) = i
            Cells(K, 2) = K + 1
            K = K + 1
        Next i
        j = j * 2
    Next stage
End Sub
</code>```

But a formula-based solution should also be possible.

EDIT#2:

In A1 enter 1
in B1 enter 2

In A2 enter:

```<code>=IF(ROWS($1:2)=2*A1,1,1+A1)  and copy downwards.
</code>```

In B2 enter:

```<code>=B1+1 and copy downwards
</code>```

Body:
You could set up the call chain as follows:

So in Stage 2 1 would call 3 and 2 would call 4 at the same time,etc.  At each stage the number of callers would be double the number of callers from the previous stage.

(it is possible to map this into a tree structure)

EDIT#1:

I generated the pattern with this small VBA macro:

Sub Peak()
    Dim stage As Long, i As Long, j As Long, K As Long

    K = 1
    j = 1

    For stage = 1 To 5
        For i = 1 To j
            Cells(K, 1) = i
            Cells(K, 2) = K + 1
            K = K + 1
        Next i
        j = j * 2
    Next stage
End Sub

But a formula-based solution should also be possible.

EDIT#2:

In A1 enter 1
in B1 enter 2

In A2 enter:

=IF(ROWS($1:2)=2*A1,1,1+A1)  and copy downwards.

In B2 enter:

=B1+1 and copy downwards


问:
How to receive Postman binary data in ExpressJS?

I want to receive uploaded image in Node ExpressJS server?

I'm unable find the content in req.body

Any help will much be appreciated.

My server.js looks like this

app.use(
  bodyParser.json({
    limit: '50mb',
  }),
);
app.use(
  bodyParser.urlencoded({
    limit: '50mb',
    extended: true,
    parameterLimit: 50000,
  }),
);

app.use(cors());

```

答:
If the request body is a binary JPEG, then it isn't JSON and it isn't URL Encoded, so the body parsers you are using aren't helpful.

Use a raw body parser instead.

```<code>app.use(
    bodyParser.raw({ limit: '50mb', type: ['image/*'] })
);
</code>```

Body:
If the request body is a binary JPEG, then it isn't JSON and it isn't URL Encoded, so the body parsers you are using aren't helpful.

Use a raw body parser instead.

app.use(
    bodyParser.raw({ limit: '50mb', type: ['image/*'] })
);


问:
How to make users STOP the execution of an HTML5 audio autoplay file clicking anything on the page?
I'm working on a page that, on my client's request, loads playing a background soundtrack.
Of course it's just for those users who are not navigating with audio autoplay disabled.
So the simple piece of code used to start playing the music is something like the following:

```<code><audio autoplay id="background-soundtrack">
  <source src="mytrack.mp3" type="audio/mpeg">
</audio>
</code>```

I'd like to make music stop (even better: make it fade out in a matter of a few seconds) as soon as the user clicks anywhere on the page -- it should work tapping on mobile devices too.

Can you please suggesitng me a smart way to achieve my goal?
It doesn't matter if it's pure JavaScript or jQuery.

Thanks!

答:
The HTML5 audio elements has the pause method, that you can use at "onClick" (work in touch too) event on body, document, window...
Like this (I delete the "-" in id):

document.onclick = function(e){
  backgroundsoundtrack.pause();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><audio autoplay id="backgroundsoundtrack">
  <source src="mytrack.mp3" type="audio/mpeg">
</audio></code>```

Body:
I'm working on a page that, on my client's request, loads playing a background soundtrack.
Of course it's just for those users who are not navigating with audio autoplay disabled.
So the simple piece of code used to start playing the music is something like the following:

<audio autoplay id="background-soundtrack">
  <source src="mytrack.mp3" type="audio/mpeg">
</audio>

I'd like to make music stop (even better: make it fade out in a matter of a few seconds) as soon as the user clicks anywhere on the page -- it should work tapping on mobile devices too.

Can you please suggesitng me a smart way to achieve my goal?
It doesn't matter if it's pure JavaScript or jQuery.

Thanks!

Body:
The HTML5 audio elements has the pause method, that you can use at "onClick" (work in touch too) event on body, document, window...
Like this (I delete the "-" in id):

document.onclick = function(e){
  backgroundsoundtrack.pause();
}

<audio autoplay id="backgroundsoundtrack">
  <source src="mytrack.mp3" type="audio/mpeg">
</audio>


问:
Typescript SyntaxError: Unexpected token ':' i am stuck with these error while declaring a variable?
I am new to typescript and visual studio code. I cannot able figure out whats going wrong, isn't it the problem arise because of installation of typescript in visual studio code.

for e.g. - students: number = 123

Please check the screenshot of the error.

Please check the screenshot of the error

答:
Try prepending your code snippet with const, var or let:

const students: number = 123;


问:
Is a good practice to used shifted unsigned numbers as an index number of array
Defining the enum as flags in the following way

```<code>    typedef enum
    {
        NOT_PID = 0,
        PID1 = (1U << 0),
        PID2 = (1U << 1),
        NUM_PID = 3

    } pid_t;

    float m_derivative[pid_t::NUM_PID];
</code>```

and using it as follows:

```<code>    m_derivative[pid_t::PID1] = 4.0
    m_derivative[pid_t::PID2] = 3.0
</code>```

Is good practice to used shifted unsigned numbers as a index number of array in this way?

答:
Using enum values as array indices is good practice. In fact, Scott Meyers suggests this in item 10 of "Effective Modern C++".

However, defining the enum values with bit shifting looks shifty.
You won't get a contiguous array. it this is important to you - avoid this.

Body:
Defining the enum as flags in the following way

    typedef enum
    {
        NOT_PID = 0,
        PID1 = (1U << 0),
        PID2 = (1U << 1),
        NUM_PID = 3

    } pid_t;

    float m_derivative[pid_t::NUM_PID];

and using it as follows:

    m_derivative[pid_t::PID1] = 4.0
    m_derivative[pid_t::PID2] = 3.0

Is good practice to used shifted unsigned numbers as a index number of array in this way?