问:
LINQ: Select where object does not contain items from list
I'm struggling with LINQ syntax here...thought I'd toss it out here. I cant find exactly what I'm looking for anywhere else.

OK, say I've got this:

```<code>public class Bar
{
   public int BarId { get; set; }
}

public class Foo
{
   public List<Bar> BarList { get; set; }
}

List<Foo> fooBunch = GetABunchOfFoos(); //let's just assume I'm getting more than one
List<Foo> fooSelect = new List<Foo>;
List<Bar> filterBars = GetAFewBars(); //assume I'm getting like 2 or 3

fooSelect = (from f in fooBunch
             where !(from b in f.BarList select b.BarId).Contains(ITEM FROM filterBars.BarId)
             select f).ToList();
</code>```

So, long story short I want to use LINQ to filter out my list of objects based on objects from another list. I hope this makes sense. I think I'm just lost on the Contains portion...I don't know how to write that.

答:
In general, you're looking for the "Except" extension.

```<code>var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);
</code>```

In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int> of IDs)

Body:
I'm struggling with LINQ syntax here...thought I'd toss it out here. I cant find exactly what I'm looking for anywhere else.

OK, say I've got this:

public class Bar
{
   public int BarId { get; set; }
}

public class Foo
{
   public List<Bar> BarList { get; set; }
}

List<Foo> fooBunch = GetABunchOfFoos(); //let's just assume I'm getting more than one
List<Foo> fooSelect = new List<Foo>;
List<Bar> filterBars = GetAFewBars(); //assume I'm getting like 2 or 3

fooSelect = (from f in fooBunch
             where !(from b in f.BarList select b.BarId).Contains(ITEM FROM filterBars.BarId)
             select f).ToList();

So, long story short I want to use LINQ to filter out my list of objects based on objects from another list. I hope this makes sense. I think I'm just lost on the Contains portion...I don't know how to write that.

Body:
In general, you're looking for the "Except" extension.

var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);

In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int> of IDs)


来源: stackexchange

问:
Native library not found on android build?
I am getting this error: unable to lookup library path for, native render plugin support disabled when I run my app on android. I think I am building the shared libraries incorrectly.

I am looking to build the source files from this repo. I'll say my build process and perhaps someone can spot a step I'm missing or doing incorrect.

Following this guide, I came up with this:

Android.mk

```<code>LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE    := libhydrogen
LOCAL_SRC_FILES := ..\hydrogen.c

include $(BUILD_SHARED_LIBRARY)
</code>```

Application.mk

```<code>APP_PLATFORM := android-16
APP_OPTIM := release
APP_MODULES := libhydrogen
</code>```

Next I:

Placed these files in the jni folder.

Called ndk-build.

Copied the .so files from the \libs folder and placed them in their respective folders in Unity (i.e. Hydrogen\Plugins\Android\arm64-v8a).

Made sure their platforms and CPU architectures were correct.

Built my app.

Here is the c# wrapper I am using.
Calling Hydrogen.Library.Initialize(); is then giving me this error.
Here is the full logcat related to this error.

And in the case my build process manages to be correct, and the .so files are fine; what else might cause this to happen?

Edit: I am trying to build for armeabi-v7a and `x86. Here are the .so file details, maybe there is something there that is not right? I am unfamiliar with c and since I haven't heard of anyone building this library for android, I wonder: could there be anything within the c source file that is incompatible with the NDK build process?

答: It was a bug with Unity! For some reason when switching the project's target platform some of my files would get corrupted. Strangely, it only seems to happen in this one project, but in any case the (temporary) solution is to re-import the plugin folder whenever I switch platforms.</p>

OwnerDisplayName: Bureto

ContentLicense: CC BY-SA 4.0

Body:
I am getting this error: unable to lookup library path for, native render plugin support disabled when I run my app on android. I think I am building the shared libraries incorrectly.

I am looking to build the source files from this repo. I'll say my build process and perhaps someone can spot a step I'm missing or doing incorrect.

Following this guide, I came up with this:

Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE    := libhydrogen
LOCAL_SRC_FILES := ..\hydrogen.c

include $(BUILD_SHARED_LIBRARY)

Application.mk

APP_PLATFORM := android-16
APP_OPTIM := release
APP_MODULES := libhydrogen

Next I:

Placed these files in the jni folder.

Called ndk-build.

Copied the .so files from the \libs folder and placed them in their respective folders in Unity (i.e. Hydrogen\Plugins\Android\arm64-v8a).

Made sure their platforms and CPU architectures were correct.

Built my app.

Here is the c# wrapper I am using.
Calling Hydrogen.Library.Initialize(); is then giving me this error.
Here is the full logcat related to this error.

And in the case my build process manages to be correct, and the .so files are fine; what else might cause this to happen?

Edit: I am trying to build for armeabi-v7a and `x86. Here are the .so file details, maybe there is something there that is not right? I am unfamiliar with c and since I haven't heard of anyone building this library for android, I wonder: could there be anything within the c source file that is incompatible with the NDK build process?


问:
How do I determine the OS version at runtime in OS X or iOS (without using Gestalt)?
The Gestalt() function located in CarbonCore/OSUtils.h has been deprecated as of OS X 10.8 Mountain Lion.

I often use this function to test the version of the OS X operating system at runtime (see the toy example below).

What other API could be used to check the OS X operating system version at runtime in a Cocoa application?

```<code>int main() {
    SInt32 versMaj, versMin, versBugFix;
    Gestalt(gestaltSystemVersionMajor, &versMaj);
    Gestalt(gestaltSystemVersionMinor, &versMin);
    Gestalt(gestaltSystemVersionBugFix, &versBugFix);

    printf("OS X Version: %d.%d.%d\n", versMaj, versMin, versBugFix);
}
</code>```

答:
Gestalt() is a pure C API. The accepted answer suggests using NSProcessInfo but that requires Objective-C code and cannot be used if pure C is a requirement for some reason. Same holds true for NSAppKitVersionNumber, which also isn't updated anymore by Apple since 10.13.4. Using the constant kCFCoreFoundationVersionNumber was possible in C code but this constant hasn't been updated anymore since 10.11.4. Reading kern.osrelease using sysctl is possible in C but requires a mapping table or relying on the current kernel versioning scheme and thus is not reliable for future version as the kernel version scheme might change and a mapping table cannot know future versions.

The official and recommend way from Apple is to read /System/Library/CoreServices/SystemVersion.plist as this is also where Gestalt() gets the version number from, this is also where NSProcessInfo() gets the version number from, this is also where the command line tool sw_vers gets the version number from and this is even where the new @available(macOS 10.x, ...) compiler feature gets the version number from (I diged deep into the system to find out about this). I wouldn't be surprised if even Swift's #available(macOS 10.x, *) would get the version number from there.

There is just no simple C call for reading the version number from there, so I wrote the following pure C code which only requires CoreFoundation framework that itself is pure C framework:

```<code>static bool versionOK;
static unsigned versions[3];
static dispatch_once_t onceToken;

static
void initMacOSVersion ( void * unused ) {
    // `Gestalt()` actually gets the system version from this file.
    // Even `if (@available(macOS 10.x, *))` gets the version from there.
    CFURLRef url = CFURLCreateWithFileSystemPath(
        NULL, CFSTR("/System/Library/CoreServices/SystemVersion.plist"),
        kCFURLPOSIXPathStyle, false);
    if (!url) return;

    CFReadStreamRef readStr = CFReadStreamCreateWithFile(NULL, url);
    CFRelease(url);
    if (!readStr) return;

    if (!CFReadStreamOpen(readStr)) {
        CFRelease(readStr);
        return;
    }

    CFErrorRef outError = NULL;
    CFPropertyListRef propList = CFPropertyListCreateWithStream(
        NULL, readStr, 0, kCFPropertyListImmutable, NULL, &outError);
    CFRelease(readStr);
    if (!propList) {
        CFShow(outError);
        CFRelease(outError);
        return;
    }

    if (CFGetTypeID(propList) != CFDictionaryGetTypeID()) {
        CFRelease(propList);
        return;
    }

    CFDictionaryRef dict = propList;
    CFTypeRef ver = CFDictionaryGetValue(dict, CFSTR("ProductVersion"));
    if (ver) CFRetain(ver);
    CFRelease(dict);
    if (!ver) return;

    if (CFGetTypeID(ver) != CFStringGetTypeID()) {
        CFRelease(ver);
        return;
    }

    CFStringRef verStr = ver;
    // `1 +` for the terminating NUL (\0) character
    CFIndex size = 1 + CFStringGetMaximumSizeForEncoding(
        CFStringGetLength(verStr), kCFStringEncodingASCII);
    // `calloc` initializes the memory with all zero (all \0)
    char * cstr = calloc(1, size);
    if (!cstr) {
        CFRelease(verStr);
        return;
    }

    CFStringGetBytes(ver, CFRangeMake(0, CFStringGetLength(verStr)),
        kCFStringEncodingASCII, '?', false, (UInt8 *)cstr, size, NULL);
    CFRelease(verStr);

    printf("%s\n", cstr);

    int scans = sscanf(cstr, "%u.%u.%u",
        &versions[0], &versions[1], &versions[2]);
    free(cstr);
    // There may only be two values, but only one is definitely wrong.
    // As `version` is `static`, its zero initialized.
    versionOK = (scans >= 2);
}

static
bool macOSVersion (
    unsigned *_Nullable outMajor,
    unsigned *_Nullable outMinor,
    unsigned *_Nullable outBugfix
) {
    dispatch_once_f(&onceToken, NULL, &initMacOSVersion);
    if (versionOK) {
        if (outMajor) *outMajor = versions[0];
        if (outMinor) *outMinor = versions[1];
        if (outBugfix) *outBugfix = versions[2];
    }
    return versionOK;
}
</code>```

The reason for using a dispatch_once_f instead of dispatch_once is that blocks aren't pure C either. The reason for using dispatch_once at all is that the version number cannot change while the system is running, so there is no reason for reading the version number more than once during a single app run. Also reading it is not guaranteed to be fail-safe and too expensive to re-read it every time your app may require it.

Talking about not being fail-safe, even though it is unlikely, reading it may, of course, fail, in which case the function returns false and always will return false. I leave it up to you to handle that case in a meaningful way in your app code because I cannot know how critical knowing the version number is to your app. If the version number is not critical, maybe you can work around it, otherwise you should make your app fail in a user friendly way.

Note

If you only require the version number to execute alternative code depending on the system version, there might be a better alternative to querying the version number on your own. See this question for details.

ContentLicense: CC BY-SA 3.0

Body:
The Gestalt() function located in CarbonCore/OSUtils.h has been deprecated as of OS X 10.8 Mountain Lion.

I often use this function to test the version of the OS X operating system at runtime (see the toy example below).

What other API could be used to check the OS X operating system version at runtime in a Cocoa application?

int main() {
    SInt32 versMaj, versMin, versBugFix;
    Gestalt(gestaltSystemVersionMajor, &versMaj);
    Gestalt(gestaltSystemVersionMinor, &versMin);
    Gestalt(gestaltSystemVersionBugFix, &versBugFix);

    printf("OS X Version: %d.%d.%d\n", versMaj, versMin, versBugFix);
}

Body:
Gestalt() is a pure C API. The accepted answer suggests using NSProcessInfo but that requires Objective-C code and cannot be used if pure C is a requirement for some reason. Same holds true for NSAppKitVersionNumber, which also isn't updated anymore by Apple since 10.13.4. Using the constant kCFCoreFoundationVersionNumber was possible in C code but this constant hasn't been updated anymore since 10.11.4. Reading kern.osrelease using sysctl is possible in C but requires a mapping table or relying on the current kernel versioning scheme and thus is not reliable for future version as the kernel version scheme might change and a mapping table cannot know future versions.

The official and recommend way from Apple is to read /System/Library/CoreServices/SystemVersion.plist as this is also where Gestalt() gets the version number from, this is also where NSProcessInfo() gets the version number from, this is also where the command line tool sw_vers gets the version number from and this is even where the new @available(macOS 10.x, ...) compiler feature gets the version number from (I diged deep into the system to find out about this). I wouldn't be surprised if even Swift's #available(macOS 10.x, *) would get the version number from there.

There is just no simple C call for reading the version number from there, so I wrote the following pure C code which only requires CoreFoundation framework that itself is pure C framework:

static bool versionOK;
static unsigned versions[3];
static dispatch_once_t onceToken;

static
void initMacOSVersion ( void * unused ) {
    // `Gestalt()` actually gets the system version from this file.
    // Even `if (@available(macOS 10.x, *))` gets the version from there.
    CFURLRef url = CFURLCreateWithFileSystemPath(
        NULL, CFSTR("/System/Library/CoreServices/SystemVersion.plist"),
        kCFURLPOSIXPathStyle, false);
    if (!url) return;

    CFReadStreamRef readStr = CFReadStreamCreateWithFile(NULL, url);
    CFRelease(url);
    if (!readStr) return;

    if (!CFReadStreamOpen(readStr)) {
        CFRelease(readStr);
        return;
    }

    CFErrorRef outError = NULL;
    CFPropertyListRef propList = CFPropertyListCreateWithStream(
        NULL, readStr, 0, kCFPropertyListImmutable, NULL, &outError);
    CFRelease(readStr);
    if (!propList) {
        CFShow(outError);
        CFRelease(outError);
        return;
    }

    if (CFGetTypeID(propList) != CFDictionaryGetTypeID()) {
        CFRelease(propList);
        return;
    }

    CFDictionaryRef dict = propList;
    CFTypeRef ver = CFDictionaryGetValue(dict, CFSTR("ProductVersion"));
    if (ver) CFRetain(ver);
    CFRelease(dict);
    if (!ver) return;

    if (CFGetTypeID(ver) != CFStringGetTypeID()) {
        CFRelease(ver);
        return;
    }

    CFStringRef verStr = ver;
    // `1 +` for the terminating NUL (\0) character
    CFIndex size = 1 + CFStringGetMaximumSizeForEncoding(
        CFStringGetLength(verStr), kCFStringEncodingASCII);
    // `calloc` initializes the memory with all zero (all \0)
    char * cstr = calloc(1, size);
    if (!cstr) {
        CFRelease(verStr);
        return;
    }

    CFStringGetBytes(ver, CFRangeMake(0, CFStringGetLength(verStr)),
        kCFStringEncodingASCII, '?', false, (UInt8 *)cstr, size, NULL);
    CFRelease(verStr);

    printf("%s\n", cstr);

    int scans = sscanf(cstr, "%u.%u.%u",
        &versions[0], &versions[1], &versions[2]);
    free(cstr);
    // There may only be two values, but only one is definitely wrong.
    // As `version` is `static`, its zero initialized.
    versionOK = (scans >= 2);
}

static
bool macOSVersion (
    unsigned *_Nullable outMajor,
    unsigned *_Nullable outMinor,
    unsigned *_Nullable outBugfix
) {
    dispatch_once_f(&onceToken, NULL, &initMacOSVersion);
    if (versionOK) {
        if (outMajor) *outMajor = versions[0];
        if (outMinor) *outMinor = versions[1];
        if (outBugfix) *outBugfix = versions[2];
    }
    return versionOK;
}

The reason for using a dispatch_once_f instead of dispatch_once is that blocks aren't pure C either. The reason for using dispatch_once at all is that the version number cannot change while the system is running, so there is no reason for reading the version number more than once during a single app run. Also reading it is not guaranteed to be fail-safe and too expensive to re-read it every time your app may require it.

Talking about not being fail-safe, even though it is unlikely, reading it may, of course, fail, in which case the function returns false and always will return false. I leave it up to you to handle that case in a meaningful way in your app code because I cannot know how critical knowing the version number is to your app. If the version number is not critical, maybe you can work around it, otherwise you should make your app fail in a user friendly way.

Note

If you only require the version number to execute alternative code depending on the system version, there might be a better alternative to querying the version number on your own. See this question for details.


问:
How to chain promises in series in a while loop
I have to make a query to multiple databases in series. Basically a set of promises that have to be completed in series. I am implementing it in a while loop. The databases are named based on dates. I also have to set a request delay of 400ms times the amount of loops passed (400*count) between each promise. If it helps I am using cloudant as my database, similar to mongodb/couchdb but an online instance.

So I have implemented a query function that will take a start and end date and will retrieve all the values in the range. If the dates are the same then it will query one database, otherwise it will query multiple databases for each day between the range of dates. I am mainly having trouble with the else block in the if statement as you can see below.

```<code>db.predQuery = (start, end, locationCode) => {
        return new Promise((resolve, reject) => {
            let data = [];
            const startDate = moment(start, "MM/DD/YYYY");
            const endDate = moment(end, "MM/DD/YYYY");
            if (startDate.diff(endDate) === 0) {
                // THIS IF BLOCK WORKS GOOD
                let dbName = `prediction_${String(locationCode)}_`;
                dbName += startDate.format("YYYY-MM-DD");
                const db = this.cloudant.use(dbName);
                return db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                    data = body.docs;
                    return resolve(data);
                });
            } else {
                // THIS BLOCK IS WHERE THE PROBLEM IS

                // This is to start off the promise chain in the while loop
                let chainProm = Promise.resolve(1);
                let iterator = moment(startDate);
                let count = 0;

                // While loop for the series of promises
                while (iterator.isBefore(endDate) || iterator.isSame(endDate)) {
                    //dbName Format: prediction_0_2019-05-28
                    let dbName = `prediction_${String(locationCode)}_`;
                    dbName += iterator.format("YYYY-MM-DD");
                    const db = this.cloudant.use(dbName);
                    count += 1;

                    // Set off chain of promises
                    chainProm = chainProm.then(() => {
                        setTimeout(()=>{
                            db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                                // Keep adding on to the old array
                                data = data.concat(body.docs);
                            });
                        },count*400);
                    });

                    // Move to the next day
                    iterator.add(1,'days');
                }
                // Once all done resolve with the array of all the documents
                return resolve (data);
            }
        })
    };
</code>```

Basically the output is suppose to be an array of all the documents between the range of dates. Now the single date works, but when I do a range of dates it either the request doesn't not go through, or I hit the limit or it says the promise is never resolved. I don't think this may not be the best way to approach this, and am open to any solution. Any help is greatly appreciated.

答:
I haven't fully understood your code. However, if the queries are independent of one another it seems like Promise.all() would solve your problem:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

If you in fact need the promises to run in synchronous order, try simply awaiting for the promise resolve in the loop.

Body:
I have to make a query to multiple databases in series. Basically a set of promises that have to be completed in series. I am implementing it in a while loop. The databases are named based on dates. I also have to set a request delay of 400ms times the amount of loops passed (400*count) between each promise. If it helps I am using cloudant as my database, similar to mongodb/couchdb but an online instance.

So I have implemented a query function that will take a start and end date and will retrieve all the values in the range. If the dates are the same then it will query one database, otherwise it will query multiple databases for each day between the range of dates. I am mainly having trouble with the else block in the if statement as you can see below.

db.predQuery = (start, end, locationCode) => {
        return new Promise((resolve, reject) => {
            let data = [];
            const startDate = moment(start, "MM/DD/YYYY");
            const endDate = moment(end, "MM/DD/YYYY");
            if (startDate.diff(endDate) === 0) {
                // THIS IF BLOCK WORKS GOOD
                let dbName = `prediction_${String(locationCode)}_`;
                dbName += startDate.format("YYYY-MM-DD");
                const db = this.cloudant.use(dbName);
                return db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                    data = body.docs;
                    return resolve(data);
                });
            } else {
                // THIS BLOCK IS WHERE THE PROBLEM IS

                // This is to start off the promise chain in the while loop
                let chainProm = Promise.resolve(1);
                let iterator = moment(startDate);
                let count = 0;

                // While loop for the series of promises
                while (iterator.isBefore(endDate) || iterator.isSame(endDate)) {
                    //dbName Format: prediction_0_2019-05-28
                    let dbName = `prediction_${String(locationCode)}_`;
                    dbName += iterator.format("YYYY-MM-DD");
                    const db = this.cloudant.use(dbName);
                    count += 1;

                    // Set off chain of promises
                    chainProm = chainProm.then(() => {
                        setTimeout(()=>{
                            db.find({selector: {_id: {'$gt': 0}}}).then((body) => {
                                // Keep adding on to the old array
                                data = data.concat(body.docs);
                            });
                        },count*400);
                    });

                    // Move to the next day
                    iterator.add(1,'days');
                }
                // Once all done resolve with the array of all the documents
                return resolve (data);
            }
        })
    };

Basically the output is suppose to be an array of all the documents between the range of dates. Now the single date works, but when I do a range of dates it either the request doesn't not go through, or I hit the limit or it says the promise is never resolved. I don't think this may not be the best way to approach this, and am open to any solution. Any help is greatly appreciated.


问:
Heat map generation using coordinate points
I am new in Python. The answer to my question might be available in the StackOverflow, but honestly speaking, I tried almost all the codes and suggestions available in the StackOverflow.

My problem: Almost the same as it is described here. I have coordinate points (x and y) and the corresponding value (p) as a .csv file. I am reading that file using pandas.

```<code>df = pd.read_csv("example.csv")
</code>```

The example.csv file can be download from here. Let an image of size 2000 x 2000.

Task:

Based on the x and y coordinate points in the excel sheet, I have to locate the point in that image.

Lets, A is an image and A(x,y) is any point within A. Now I have to generate a heat map in such a way so that 50 pixels from x and 50 pixels fromy i.e., A(x,y), A(x+50, y), A(x, y+50) and A(x+50, y+50) contains p corresponding to that coordinate points.

I found this link which is very helpful and serves my issue, but the problem is some more modifications are necessary for my datasets.

The code which is available in the above link:

```<code>#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from skimage import io
from skimage.color import rgb2gray
import matplotlib as mpl
# Read original image
img = io.imread('img.jpg')

# Get the dimensions of the original image
x_dim, y_dim, z_dim = np.shape(img)

# Create heatmap
heatmap = np.zeros((x_dim, y_dim), dtype=float)

# Read CSV with a Pandas DataFrame
df = pd.read_csv("data.csv")

# Set probabilities values to specific indexes in the heatmap
for index, row in df.iterrows():
    x = np.int(row["x"])
    y = np.int(row["y"])
    x1 = np.int(row["x1"])
    y1 = np.int(row["y1"])
    p = row["Probability value"]
    heatmap[x:x1,y:y1] = p

# Plot images
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()

ax[0].imshow(img)
ax[0].set_title("Original")
fig.colorbar(ax[0].imshow(img), ax=ax[0])

ax[1].imshow(img, vmin=0, vmax=1)
ax[1].imshow(heatmap, alpha=.5, cmap='jet')
ax[1].set_title("Original + heatmap")

# Specific colorbar
norm = mpl.colors.Normalize(vmin=0,vmax=2)
N = 11
cmap = plt.get_cmap('jet',N)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
plt.colorbar(sm, ticks=np.linspace(0,1,N),
             boundaries=np.arange(0,1.1,0.1))

fig.tight_layout()
plt.show()
</code>```

Issues which I am facing when using this code:

This code is generating a heat map of square edges, but I am expecting a smooth edge. I know Gaussian distribution might solve this problem. But I am new in python and I don't know how to implement the Gaussian Distribution in my dataset.

The regions which don't belong to the coordinate points also generating a layer of color. As a result in an overlayed image those layer covering the background of original images. In one sentence I want the background of the heat map will be transparent so that overlays will not create any problem in showing the regions which are not covered by the coordinate points.

Any leads will be highly appreciated.

答:
Your code is perfect. Just change only one line, then your both issues will be solved.

Before changes:

```<code>ax[1].imshow(heatmap, alpha=.5, cmap='jet')
</code>```

After changes:

```<code>ax[1].imshow(heatmap, alpha=.5, cmap='coolwarm', interpolation='gaussian')
</code>```

Though above changes will solve your issue, but if you want then for additional transparency, you can use below function

```<code>def transparent_cmap(cmap, N=255):
    "Copy colormap and set alpha values"

    mycmap = cmap
    mycmap._init()
    mycmap._lut[:,-1] = np.linspace(0, 0.8, N+4)
    return mycmap
mycmap = transparent_cmap(plt.cm.coolwarm)
</code>```

In that case, your previous code line will change like below:

```<code>ax[1].imshow(heatmap, alpha=.5, cmap=mycmap, vmin=0, vmax=1)
</code>```

Body:
I am new in Python. The answer to my question might be available in the StackOverflow, but honestly speaking, I tried almost all the codes and suggestions available in the StackOverflow.

My problem: Almost the same as it is described here. I have coordinate points (x and y) and the corresponding value (p) as a .csv file. I am reading that file using pandas.

df = pd.read_csv("example.csv")

The example.csv file can be download from here. Let an image of size 2000 x 2000.

Task:

Based on the x and y coordinate points in the excel sheet, I have to locate the point in that image.

Lets, A is an image and A(x,y) is any point within A. Now I have to generate a heat map in such a way so that 50 pixels from x and 50 pixels fromy i.e., A(x,y), A(x+50, y), A(x, y+50) and A(x+50, y+50) contains p corresponding to that coordinate points.

I found this link which is very helpful and serves my issue, but the problem is some more modifications are necessary for my datasets.

The code which is available in the above link:

#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from skimage import io
from skimage.color import rgb2gray
import matplotlib as mpl
# Read original image
img = io.imread('img.jpg')

# Get the dimensions of the original image
x_dim, y_dim, z_dim = np.shape(img)

# Create heatmap
heatmap = np.zeros((x_dim, y_dim), dtype=float)

# Read CSV with a Pandas DataFrame
df = pd.read_csv("data.csv")

# Set probabilities values to specific indexes in the heatmap
for index, row in df.iterrows():
    x = np.int(row["x"])
    y = np.int(row["y"])
    x1 = np.int(row["x1"])
    y1 = np.int(row["y1"])
    p = row["Probability value"]
    heatmap[x:x1,y:y1] = p

# Plot images
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()

ax[0].imshow(img)
ax[0].set_title("Original")
fig.colorbar(ax[0].imshow(img), ax=ax[0])

ax[1].imshow(img, vmin=0, vmax=1)
ax[1].imshow(heatmap, alpha=.5, cmap='jet')
ax[1].set_title("Original + heatmap")

# Specific colorbar
norm = mpl.colors.Normalize(vmin=0,vmax=2)
N = 11
cmap = plt.get_cmap('jet',N)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
plt.colorbar(sm, ticks=np.linspace(0,1,N),
             boundaries=np.arange(0,1.1,0.1))

fig.tight_layout()
plt.show()

Issues which I am facing when using this code:

This code is generating a heat map of square edges, but I am expecting a smooth edge. I know Gaussian distribution might solve this problem. But I am new in python and I don't know how to implement the Gaussian Distribution in my dataset.

The regions which don't belong to the coordinate points also generating a layer of color. As a result in an overlayed image those layer covering the background of original images. In one sentence I want the background of the heat map will be transparent so that overlays will not create any problem in showing the regions which are not covered by the coordinate points.

Any leads will be highly appreciated.

Body:
Your code is perfect. Just change only one line, then your both issues will be solved.

Before changes:

ax[1].imshow(heatmap, alpha=.5, cmap='jet')

After changes:

ax[1].imshow(heatmap, alpha=.5, cmap='coolwarm', interpolation='gaussian')

Though above changes will solve your issue, but if you want then for additional transparency, you can use below function

def transparent_cmap(cmap, N=255):
    "Copy colormap and set alpha values"

    mycmap = cmap
    mycmap._init()
    mycmap._lut[:,-1] = np.linspace(0, 0.8, N+4)
    return mycmap
mycmap = transparent_cmap(plt.cm.coolwarm)

In that case, your previous code line will change like below:

ax[1].imshow(heatmap, alpha=.5, cmap=mycmap, vmin=0, vmax=1)


答:
The first thing you have to do, is to create two dataframes from your data (dfold and dfnew in the following example)

import datetime
import pyspark.sql.functions as F
l = [
 ('John',      'Doe'    ,  '2017-04-05',  '2017-05-04' ,        '2099-12-31'),
 ('Jane' ,      'Smith'  ,  '2018-04-05',  '2017-05-04' ,        '2099-12-31')
    ]

columns = [     'FirstName' , 'LastName', 'JoinDate'  , 'SnapshotBeginDate' , 'SnapshotEndDate']

dfold=spark.createDataFrame(l, columns)
dfold = dfold.withColumn('SnapshotBeginDate',   F.to_date(dfold.SnapshotBeginDate,  'yyyy-MM-dd'))
dfold = dfold.withColumn('SnapshotEndDate',   F.to_date(dfold.SnapshotEndDate,  'yyyy-MM-dd'))
dfnew = dfold
```

<p>You can update the SnapshotEndDate column of <code>dfold</code> and the SnapshotBeginDate of the <code>dfnew</code> with the withColumn function. This function allows you to apply an operation to a column. You also need the current date to update the values. The python module datetime provides such a functionality (in case you don't need the current date, just specify any other date as string), but doesn't return a column. To turn the return object into a column, we can use the pyspark lit function.  </p>

<pre class="lang-py prettyprint-override"><code>dfold= dfold.withColumn('SnapshotEndDate', F.lit(datetime.date.today()))
dfnew= dfnew.withColumn('SnapshotBeginDate', F.lit(datetime.date.today()))
dfold.union(dfnew).show()
</code>```

Output:

+---------+--------+----------+-----------------+---------------+
|FirstName|LastName|  JoinDate|SnapshotBeginDate|SnapshotEndDate|
+---------+--------+----------+-----------------+---------------+
|     John|     Doe|2017-04-05|       2017-05-04|     2019-06-01|
|     Jane|   Smith|2018-04-05|       2017-05-04|     2019-06-01|
|     John|     Doe|2017-04-05|       2019-06-01|     2099-12-31|
|     Jane|   Smith|2018-04-05|       2019-06-01|     2099-12-31|
+---------+--------+----------+-----------------+---------------+
```

Title: Update old records with new information in pyspark without overwriting

Body:
I want to update the old records based on the information I may or may not get from the new instance of the same record in pyspark.
This is what the old table/dataframe looks like

| FirstName | LastName | JoinDate  | SnapshotBeginDate | SnapshotEndDate |
-------------------------------------------------------------------------
| John      | Doe      |2017-04-05 | 2017-05-04        | 2099-12-31      |
-------------------------------------------------------------------------
| Jane      | Smith    |2018-04-05 | 2017-05-04        | 2099-12-31 |
-------------------------------------------------------------------------

I do not want to merely append the new data to the existing dataframe. Nor do I want to overwrite the existing record. I would instead want to update the snapshotEndDate of the old record.

For eg:

| FirstName | LastName | JoinDate  | SnapshotBeginDate | SnapshotEndDate |
-------------------------------------------------------------------------
| John      | Doe      |2017-04-05 | 2017-05-04        | 2019-04-03      |
-------------------------------------------------------------------------
| Jane      | Smith    |2018-04-05 | 2017-05-04        | 2019-04-03|
-------------------------------------------------------------------------
| John      | Doe      |2017-04-05 | 2019-04-03        | 2099-12-31|
-------------------------------------------------------------------------
| Jane      | Smith    |2018-04-05 | 2019-04-03        | 2099-12-31|
-------------------------------------------------------------------------

Body:
The first thing you have to do, is to create two dataframes from your data (dfold and dfnew in the following example)

import datetime
import pyspark.sql.functions as F
l = [
 ('John',      'Doe'    ,  '2017-04-05',  '2017-05-04' ,        '2099-12-31'),
 ('Jane' ,      'Smith'  ,  '2018-04-05',  '2017-05-04' ,        '2099-12-31')
    ]

columns = [     'FirstName' , 'LastName', 'JoinDate'  , 'SnapshotBeginDate' , 'SnapshotEndDate']

dfold=spark.createDataFrame(l, columns)
dfold = dfold.withColumn('SnapshotBeginDate',   F.to_date(dfold.SnapshotBeginDate,  'yyyy-MM-dd'))
dfold = dfold.withColumn('SnapshotEndDate',   F.to_date(dfold.SnapshotEndDate,  'yyyy-MM-dd'))
dfnew = dfold

You can update the SnapshotEndDate column of dfold and the SnapshotBeginDate of the dfnew with the withColumn function. This function allows you to apply an operation to a column. You also need the current date to update the values. The python module datetime provides such a functionality (in case you don't need the current date, just specify any other date as string), but doesn't return a column. To turn the return object into a column, we can use the pyspark lit function.

dfold= dfold.withColumn('SnapshotEndDate', F.lit(datetime.date.today()))
dfnew= dfnew.withColumn('SnapshotBeginDate', F.lit(datetime.date.today()))
dfold.union(dfnew).show()

Output:

+---------+--------+----------+-----------------+---------------+
|FirstName|LastName|  JoinDate|SnapshotBeginDate|SnapshotEndDate|
+---------+--------+----------+-----------------+---------------+
|     John|     Doe|2017-04-05|       2017-05-04|     2019-06-01|
|     Jane|   Smith|2018-04-05|       2017-05-04|     2019-06-01|
|     John|     Doe|2017-04-05|       2019-06-01|     2099-12-31|
|     Jane|   Smith|2018-04-05|       2019-06-01|     2099-12-31|
+---------+--------+----------+-----------------+---------------+


问:
Apache camel how to send file name from one router file component to another router file component
I hava file1.jpg,file2.jpg,file3.jpg in DirA.
I have file1.json,file2.json,file3.json in DirB

How can I create a apache camel file route such that first route picks file1.jpg from a DirA , processes and pass file1 name to second route so that it can read file1.json and processes.

```<code>CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
            public void configure() {
from("file:///DirA/?noop=true"). bean(MyBean.class,"doSomeThingWithJPG(${file:absolute.path})").

from("file:///DirB/?noop=true&fileName=${file:name}.json").
bean(AnotherBean.class,"doSomeThingWithJSON(${file:absolute.path})") ;
    }
 })
</code>```

The second from (file:///) component is also pointing to file in DirA instead of files in DirB

答:
You could:

Stage the JSON file

Write a processor or bean that copies a named file from one directory to another

Call that processor after processing JPG, to copy the JSON to another directory

Have the second file-listener polling that other directory

Body:
I hava file1.jpg,file2.jpg,file3.jpg in DirA.
I have file1.json,file2.json,file3.json in DirB

How can I create a apache camel file route such that first route picks file1.jpg from a DirA , processes and pass file1 name to second route so that it can read file1.json and processes.

CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
            public void configure() {
from("file:///DirA/?noop=true"). bean(MyBean.class,"doSomeThingWithJPG(${file:absolute.path})").

from("file:///DirB/?noop=true&fileName=${file:name}.json").
bean(AnotherBean.class,"doSomeThingWithJSON(${file:absolute.path})") ;
    }
 })

The second from (file:///) component is also pointing to file in DirA instead of files in DirB


答:
dump this into a more specific collection of just the ids you don't want

```<code>var notTheseBarIds = filterBars.Select(fb => fb.BarId);
</code>```

then try this:

```<code>fooSelect = (from f in fooBunch
             where !notTheseBarIds.Contains(f.BarId)
             select f).ToList();
</code>```

or this:

```<code>fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();
</code>```

Title: LINQ: Select where object does not contain items from list

Body:
dump this into a more specific collection of just the ids you don't want

var notTheseBarIds = filterBars.Select(fb => fb.BarId);

then try this:

fooSelect = (from f in fooBunch
             where !notTheseBarIds.Contains(f.BarId)
             select f).ToList();

or this:

fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();


问:
How Sort an array of objects regardless of object variable type
I have an array of Record objects and each record object has 5 fields (first name, last name, GPA, ID number,and email). I want to sort the array based on any of the variables attributed to the object. My professor says there is a way to use one function that will sort it regardless of the variable type that is passed through. But I can't figure out a way to have one function that can sort any of those 5 variables and 3 different variable types. Meaning I can't just copy paste my sort function 5 times once for each variable. So far I can sort the array by a single value, like record[].GPA but I need a way to have like record[].x where x is whatever variable the user decides the array should we sorted by.

I tried to create a sorting function and it sorts fine but it can only handle a single variable comparison at once. For example, I have to write record[i].GPA so it compares the GPAs of the two records. However, my teacher wants it so that the function can sort based on any of the fields.

```<code>template <class  T>
void sortArray(T record[]) {

    bool swap = true;
    while (swap) {
        swap = false;
        for (size_t i = 0; i < arraySize - 1; i++) {
            if (record[i].GPA< record[i + 1].GPA) {
                T temp = record[i];
                record[i] = record[i + 1];
                record[i + 1] = temp;
                swap = true;
            }
        }
    }
}
</code>```

This is my sorting code as you can see I had to indicate which record variable to sort by, GPA in this case, but I need it to sort by any of the record variables depending on user selection. I'm not suppose to have multiple sort functions for each variable. I can post the rest of my code if required.

答:
You might do something like:</p>

```<code>auto makeComp = [](auto member){
    return [=](const auto& lhs, const auto& rhs){
        return std::invoke(member, lhs) < std::invoke(member, lhs);
    }
};

switch (eMember)
{
    case EMember::FirstName: std::sort(record, record + arraySize, makeComp(T::FirstName)); break;
    case EMember::LastName:  std::sort(record, record + arraySize, makeComp(T::LastName)); break;
    case EMember::GPA:       std::sort(record, record + arraySize, makeComp(T::GPA)); break;
    case EMember::Id:        std::sort(record, record + arraySize, makeComp(T::Id)); break;
    case EMember::EMail:     std::sort(record, record + arraySize, makeComp(T::Email)); break;
}
</code>```

Body:
I have an array of Record objects and each record object has 5 fields (first name, last name, GPA, ID number,and email). I want to sort the array based on any of the variables attributed to the object. My professor says there is a way to use one function that will sort it regardless of the variable type that is passed through. But I can't figure out a way to have one function that can sort any of those 5 variables and 3 different variable types. Meaning I can't just copy paste my sort function 5 times once for each variable. So far I can sort the array by a single value, like record[].GPA but I need a way to have like record[].x where x is whatever variable the user decides the array should we sorted by.

I tried to create a sorting function and it sorts fine but it can only handle a single variable comparison at once. For example, I have to write record[i].GPA so it compares the GPAs of the two records. However, my teacher wants it so that the function can sort based on any of the fields.

template <class  T>
void sortArray(T record[]) {

    bool swap = true;
    while (swap) {
        swap = false;
        for (size_t i = 0; i < arraySize - 1; i++) {
            if (record[i].GPA< record[i + 1].GPA) {
                T temp = record[i];
                record[i] = record[i + 1];
                record[i + 1] = temp;
                swap = true;
            }
        }
    }
}

This is my sorting code as you can see I had to indicate which record variable to sort by, GPA in this case, but I need it to sort by any of the record variables depending on user selection. I'm not suppose to have multiple sort functions for each variable. I can post the rest of my code if required.

Body:
You might do something like:

auto makeComp = [](auto member){
    return [=](const auto& lhs, const auto& rhs){
        return std::invoke(member, lhs) < std::invoke(member, lhs);
    }
};

switch (eMember)
{
    case EMember::FirstName: std::sort(record, record + arraySize, makeComp(T::FirstName)); break;
    case EMember::LastName:  std::sort(record, record + arraySize, makeComp(T::LastName)); break;
    case EMember::GPA:       std::sort(record, record + arraySize, makeComp(T::GPA)); break;
    case EMember::Id:        std::sort(record, record + arraySize, makeComp(T::Id)); break;
    case EMember::EMail:     std::sort(record, record + arraySize, makeComp(T::Email)); break;
}


问:
HDF + pandas: how can I use a where mask with multindex?
I would like to select from a HUGE hdf5 a subset of the data, day by day. It would be perfect to use a where mask, but I can't make it work with a multiindex (since I have to have a where with two conditions). can't use a where mask with a multiindex:

```<code>import itertools
import pandas as pd
import numpy as np
a = ('A', 'B')
i = (0, 1, 2)
idx = pd.MultiIndex.from_tuples(list(itertools.product(a, i)),
                            names=('Alpha', 'Int'))
df = pd.DataFrame(np.random.randn(len(idx), 7), index=idx,
              columns=('I', 'II', 'III', 'IV', 'V', 'VI', 'VII'))
</code>```

Ok, now I put it in a hdf store

```<code>from pandas.io.pytables import HDFStore
store =HDFStore('cancella.h5', 'w')
store.append('df_mask',df)
</code>```

But if I read it again I have

```<code>c = store.select_column('df_mask','index')
print c
</code>```

this index which is WRONG.

```<code>0    0
1    1
2    2
3    3
4    4
5    5
dtype: int64
</code>```

So I can't use the where mask. Can you help me?

答:
In current pandas version 0.24.2, you may use direct querying without intermediate MultiIndex retrieval:

idx = pd.MultiIndex.from_product([('A', 'B'), range(3)], names=('Alpha', 'Int'))
df = pd.DataFrame(np.random.randn(len(idx), 3), index=idx,
                  columns=('I', 'II', 'III'))
df

>>>                    I           II         III
>>> Alpha   Int
>>>     A   0    0.547846   -1.630704    0.456686
>>>         1   -0.057442   -0.232721    0.349548
>>>         2    1.495230    0.661166    1.309862
>>>     B   0    2.116818    0.477923   -0.252352
>>>         1    1.001081    2.578723   -0.040782
>>>         2   -1.286964    0.357969    0.002976
```

<p>Just use built-in <code>where</code> mask:</p>

<pre class="lang-py prettyprint-override"><code>with pd.HDFStore('test.h5') as store:
    store.put('df_mask', df, format='t')
    store.select('df_mask', where = 'Alpha = A & Int in [0,2]')

>>>                         I          II        III
>>> Alpha   Int
>>>     A     0      0.621453   -1.757883   0.494433
>>>           2     -0.689012   -1.254884   0.655424
</code>```

For different functions allowed in where mask visit docs.

But if your desired filters are very complicated and you want to retrieve MultiIndex and build mask 'by hands', you may select it like so:

with pd.HDFStore('test.h5') as store:
    store.select('df_mask', columns=['index'])

>>> Alpha   Int
>>>     A     0
>>>           1
>>>           2
>>>     B     0
>>>           1
>>>           2
```

Body:
I would like to select from a HUGE hdf5 a subset of the data, day by day. It would be perfect to use a where mask, but I can't make it work with a multiindex (since I have to have a where with two conditions). can't use a where mask with a multiindex:

import itertools
import pandas as pd
import numpy as np
a = ('A', 'B')
i = (0, 1, 2)
idx = pd.MultiIndex.from_tuples(list(itertools.product(a, i)),
                            names=('Alpha', 'Int'))
df = pd.DataFrame(np.random.randn(len(idx), 7), index=idx,
              columns=('I', 'II', 'III', 'IV', 'V', 'VI', 'VII'))

Ok, now I put it in a hdf store

from pandas.io.pytables import HDFStore
store =HDFStore('cancella.h5', 'w')
store.append('df_mask',df)

But if I read it again I have

c = store.select_column('df_mask','index')
print c

this index which is WRONG.

0    0
1    1
2    2
3    3
4    4
5    5
dtype: int64

So I can't use the where mask. Can you help me?

Body:
In current pandas version 0.24.2, you may use direct querying without intermediate MultiIndex retrieval:

idx = pd.MultiIndex.from_product([('A', 'B'), range(3)], names=('Alpha', 'Int'))
df = pd.DataFrame(np.random.randn(len(idx), 3), index=idx,
                  columns=('I', 'II', 'III'))
df

>>>                    I           II         III
>>> Alpha   Int
>>>     A   0    0.547846   -1.630704    0.456686
>>>         1   -0.057442   -0.232721    0.349548
>>>         2    1.495230    0.661166    1.309862
>>>     B   0    2.116818    0.477923   -0.252352
>>>         1    1.001081    2.578723   -0.040782
>>>         2   -1.286964    0.357969    0.002976

Just use built-in where mask:

with pd.HDFStore('test.h5') as store:
    store.put('df_mask', df, format='t')
    store.select('df_mask', where = 'Alpha = A & Int in [0,2]')

>>>                         I          II        III
>>> Alpha   Int
>>>     A     0      0.621453   -1.757883   0.494433
>>>           2     -0.689012   -1.254884   0.655424

For different functions allowed in where mask visit docs.

But if your desired filters are very complicated and you want to retrieve MultiIndex and build mask 'by hands', you may select it like so:

with pd.HDFStore('test.h5') as store:
    store.select('df_mask', columns=['index'])

>>> Alpha   Int
>>>     A     0
>>>           1
>>>           2
>>>     B     0
>>>           1
>>>           2


问:
How to open an exe file in java
I am trying to use java to open an exe file. I'm not sure which program I want to open so I am using Skype as an example. When I try to do it, it gives me errors.

```<code> try {
            Process p = Runtime.getRuntime().exec("C:\\Program Files (x86)\\Skype\\Phone\\Skype");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

error:
Cannot run program "C:\Program": CreateProcess error=2, The system cannot find the file specified

答:
I tried this and it works fine, it's taken from your example. Pay attention to the double \\

```<code>public static void main(String[] args) {
    try {
        Process p;
        p = Runtime.getRuntime().exec("C:\\Program Files\\Java\\jdk1.8.0_05\\bin\\Jconsole.exe");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

Title: How to open an exe file in java

Body:
I am trying to use java to open an exe file. I'm not sure which program I want to open so I am using Skype as an example. When I try to do it, it gives me errors.

 try {
            Process p = Runtime.getRuntime().exec("C:\\Program Files (x86)\\Skype\\Phone\\Skype");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

error:
Cannot run program "C:\Program": CreateProcess error=2, The system cannot find the file specified

Body:
I tried this and it works fine, it's taken from your example. Pay attention to the double \\

public static void main(String[] args) {
    try {
        Process p;
        p = Runtime.getRuntime().exec("C:\\Program Files\\Java\\jdk1.8.0_05\\bin\\Jconsole.exe");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


问:
PowerApp Custom Cards Issues
Recently i customized my SharePoint form using PowerApps. After unlocking and customizing some of my columns, the columns converted into custom cards and have no entry into my original SharePoint List columns. So When i fill out the form and submit, those custom column don't update on SharePoint column tables. How do i get around this and ensure my custom cards field reflect on my original SharePoint Column tables when submitted?

POWER APP COLUMS CONVERTED TO CUSTOM CARDS COLUMS NOT BEEN UPDATED IN THE LIST

答:
Can you check the following properties to see if you somehow ended up modifying them when you unlocked the data card?

In PowerApps Studio, select your Data Card and in the property pane, go to Advanced.

Under DataField you should see the name of the field the card is mapped to.

Note that this is the internal name used by SharePoint list. If you want to validate that the field name is correct you can go to your SharePoint site > List settings > Edit the column that the data card is connected to. In the query string you should see "&Field" parameter with the field name as the value.

In PowerApps Studio also validate that Default is also set to ThisItem.[DataField from step above] and Update is set to Value(DataCardValue[N].Text).

Title: PowerApp Custom Cards Issues


问:
What's wrong with my function that gives current date in string type
When i do compare 2 string current date and past date it shows me that current date is not bigger than past date.

I tried to compare str and str2 and the comparison is true.

```<code>string str="21/05/2019";
    string str2="7/06/2019";
    string c=GetCurrentDate();
    if(c>str)
    {
        cout<<"true";
    }
</code>```

and function

```<code>inline string GetCurrentDate()
{
    auto t = time(nullptr);
    auto tm = *localtime(&t);
    ostringstream oss;
    oss << put_time(&tm, "%d/%m/%Y");
    auto strCurrentDate= oss.str();
    return strCurrentDate;
}
</code>```

答:
You're better of using built in types to represent time.

But to answer your question, since you're comparing strings, it's probably using lexicographical comparison, which is not what you want.

```<code>"7/06/2019" < "8/09/2019" // even though the month is higher

</code>```

because 7 just has a lower ascii value than 8, it returns true.

What you could do, although I am not recommending it, is format your date in "yyyy/mm/dd". This would work, but you'll have to make sure that you always add zeros when needed ("2019/06/31" and not "2019/6/31").

"yyyy/mm/dd" would work, because even though it will still be using lexicographical ordering, because the weight of the lexicographical value(ascii value) of any digit is tied to the actual value('actual date value')

```<code>"2019/mm/dd" > "2018/mm/dd";
"2019/06/dd" > "2019/05/dd" ;
"2019/06/25" > "2019/06/19";
</code>```

But yeah, definitely use a built in type that's made for time/date if you can instead of strings.

Body:
When i do compare 2 string current date and past date it shows me that current date is not bigger than past date.

I tried to compare str and str2 and the comparison is true.

string str="21/05/2019";
    string str2="7/06/2019";
    string c=GetCurrentDate();
    if(c>str)
    {
        cout<<"true";
    }

and function

inline string GetCurrentDate()
{
    auto t = time(nullptr);
    auto tm = *localtime(&t);
    ostringstream oss;
    oss << put_time(&tm, "%d/%m/%Y");
    auto strCurrentDate= oss.str();
    return strCurrentDate;
}

Body:
You're better of using built in types to represent time.

But to answer your question, since you're comparing strings, it's probably using lexicographical comparison, which is not what you want.

"7/06/2019" < "8/09/2019" // even though the month is higher

because 7 just has a lower ascii value than 8, it returns true.

What you could do, although I am not recommending it, is format your date in "yyyy/mm/dd". This would work, but you'll have to make sure that you always add zeros when needed ("2019/06/31" and not "2019/6/31").

"yyyy/mm/dd" would work, because even though it will still be using lexicographical ordering, because the weight of the lexicographical value(ascii value) of any digit is tied to the actual value('actual date value')

"2019/mm/dd" > "2018/mm/dd";
"2019/06/dd" > "2019/05/dd" ;
"2019/06/25" > "2019/06/19";

But yeah, definitely use a built in type that's made for time/date if you can instead of strings.


问:
How to successfully execute test via phpunit within relationship between two models?
I'm new in Laravel. I have 2 tables Productions and Products. Also, I have 2 factories ProductionFactory and ProductFactory. I want to test them via phpunit. Their connection is via production_id.

Error is ErrorException: Undefined variable: production.

I don't get it.

Thanks in advance.

This is a code.

ProductionFactory.php

```<code>        $factory->define(App\Production::class, function (Faker $faker) {
        return [
                'name' =>$faker->name,
            ];
          });
</code>```

ProductFactory.php

```<code>       $factory->define(App\Product::class, function (Faker $faker) {
        $production_id = App\Production::pluck('id');

       if(!$production_id->isEmpty()){
          $production = $production_id->random();
       }

    return [
             'id' =>$faker->uuid,
             'name' =>$faker->name,
             'price' => $faker->numberBetween($min = 100, $max = 900),
             'description' =>Str::random(10),
             'production_id'=> $production,
          ];
</code>```

ProductionTest.php

```<code>           class ProductionTest extends TestCase
            {
              use RefreshDatabase;

             /**
             * A basic unit test example.
             * @test
             * @return void
               */
            public function production()
               {
                   factory(Production::class)->make();
                   $this->assertTrue(true);
               }
           }
</code>```

ProductTest.php

```<code>           class ProductTest extends TestCase
            {
              use RefreshDatabase;

             /**
             * A basic unit test example.
             * @test
             * @return void
               */
            public function product()
               {
                   factory(Product::class)->make();
                   $this->assertTrue(true);
               }
           }
</code>```

答:
It depends on what functionality should be tested.

A basic test to check the model relationship is set correctly?

I pushed a working demo to GitHub (https://github.com/.../laravel-basic-relationship-tests).

App/Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function production()
    {
        return $this->belongsTo(Production::class);
    }
}
```

<p><strong>App/Production.php</strong></p>

<pre class="lang-php prettyprint-override"><code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Production extends Model
{
    public function products()
    {
        return $this->belongsTo(Product::class);
    }
}

</code>```

Product Factory

<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Product as Model;
use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    $production = factory(\App\Production::class)->make();
    $production->save();

    return [
        'name' => $faker->name,
        'price' => $faker->numberBetween($min = 100, $max = 900),
        'description' => $faker->text,
        'production_id' => $production->id
    ];
});

```

<p><strong>Production Factory</strong></p>

<pre class="lang-php prettyprint-override"><code><?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Production as Model;
use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    return [
        'name' => $faker->name
    ];
});

$factory->afterCreatingState(Model::class, 'seed', function ($production, $faker) {
    $product = factory(\App\Product::class)->make();
    $production->products()->associate($product);
});
</code>```

Product Test

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ProductTest extends TestCase
{
    /**
     * @return void
     */
    public function testProductHasWorkingProductionRelationship()
    {
        $product = factory(\App\Product::class)->create();
        $this->assertNotEmpty($product->production);
    }
}
```

<p><strong>Production Test</strong></p>

<pre class="lang-php prettyprint-override"><code><?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ProductionTest extends TestCase
{
    /**
     * @return void
     */
    public function testProductionHasWorkingProductRelationship()
    {
        $production = factory(\App\Production::class)->state('seed')->create();
        $this->assertNotEmpty($production->products);
    }
}
</code>```

Hope this is a great starting point for any further tests.

Body:
I'm new in Laravel. I have 2 tables Productions and Products. Also, I have 2 factories ProductionFactory and ProductFactory. I want to test them via phpunit. Their connection is via production_id.

Error is ErrorException: Undefined variable: production.

I don't get it.

Thanks in advance.

This is a code.

ProductionFactory.php

        $factory->define(App\Production::class, function (Faker $faker) {
        return [
                'name' =>$faker->name,
            ];
          });

ProductFactory.php

       $factory->define(App\Product::class, function (Faker $faker) {
        $production_id = App\Production::pluck('id');

       if(!$production_id->isEmpty()){
          $production = $production_id->random();
       }

    return [
             'id' =>$faker->uuid,
             'name' =>$faker->name,
             'price' => $faker->numberBetween($min = 100, $max = 900),
             'description' =>Str::random(10),
             'production_id'=> $production,
          ];

ProductionTest.php

           class ProductionTest extends TestCase
            {
              use RefreshDatabase;

             /**
             * A basic unit test example.
             * @test
             * @return void
               */
            public function production()
               {
                   factory(Production::class)->make();
                   $this->assertTrue(true);
               }
           }

ProductTest.php

           class ProductTest extends TestCase
            {
              use RefreshDatabase;

             /**
             * A basic unit test example.
             * @test
             * @return void
               */
            public function product()
               {
                   factory(Product::class)->make();
                   $this->assertTrue(true);
               }
           }

Body:
It depends on what functionality should be tested.

A basic test to check the model relationship is set correctly?

I pushed a working demo to GitHub (https://github.com/.../laravel-basic-relationship-tests).

App/Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function production()
    {
        return $this->belongsTo(Production::class);
    }
}

App/Production.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Production extends Model
{
    public function products()
    {
        return $this->belongsTo(Product::class);
    }
}

Product Factory

<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Product as Model;
use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    $production = factory(\App\Production::class)->make();
    $production->save();

    return [
        'name' => $faker->name,
        'price' => $faker->numberBetween($min = 100, $max = 900),
        'description' => $faker->text,
        'production_id' => $production->id
    ];
});

Production Factory

<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Production as Model;
use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    return [
        'name' => $faker->name
    ];
});

$factory->afterCreatingState(Model::class, 'seed', function ($production, $faker) {
    $product = factory(\App\Product::class)->make();
    $production->products()->associate($product);
});

Product Test

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ProductTest extends TestCase
{
    /**
     * @return void
     */
    public function testProductHasWorkingProductionRelationship()
    {
        $product = factory(\App\Product::class)->create();
        $this->assertNotEmpty($product->production);
    }
}

Production Test

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ProductionTest extends TestCase
{
    /**
     * @return void
     */
    public function testProductionHasWorkingProductRelationship()
    {
        $production = factory(\App\Production::class)->state('seed')->create();
        $this->assertNotEmpty($production->products);
    }
}

Hope this is a great starting point for any further tests.


问:
Regex to match Telephone Pattern logic
I am trying to create a regex string to match telephone numbers using the following logic:

1) For NPA (area code), 3 digits,  the first digit is [2-9], 2nd and 3rd digit [0-9]

2) For NXX (exchange – next 3 digits after NPA) same rules as NPA.  In addition, the 3rd digit cannot be ‘1’ if the 2nd digit is ‘1’ (reserved for public service)

3) For XXXX (number – next 4 digits after NXX), [0-9] for each of the 4 digits.

I've completed steps 1 and 3 and part of 2 with the following string:

```<code>^\(?([2-9]{1})\)?([0-9]{2})?[-.*]?([2-9]{1})\)?([0-9]{2})?[-.*]?([0-9]{4})$
</code>```

But I am stuck on trying to incorporate the logic stated here:

For NXX (exchange – next 3 digits after NPA) same rules as NPA.  In addition, the 3rd digit cannot be ‘1’ if the 2nd digit is ‘1’ (reserved for public service)

If anyone can help shine some light on this, it would be greatly appreciated.

False is what I want my regex not to match, while true is what I would want it continuing to match. It currently matches both sets .

False: 4807119320 4805119439 4809114739

True: 4805218482 4805123848 4809128327 4809418482

Title: Regex to match Telephone Pattern logic

Body:
I am trying to create a regex string to match telephone numbers using the following logic:

1) For NPA (area code), 3 digits,  the first digit is [2-9], 2nd and 3rd digit [0-9]

2) For NXX (exchange – next 3 digits after NPA) same rules as NPA.  In addition, the 3rd digit cannot be ‘1’ if the 2nd digit is ‘1’ (reserved for public service)

3) For XXXX (number – next 4 digits after NXX), [0-9] for each of the 4 digits.

I've completed steps 1 and 3 and part of 2 with the following string:

^\(?([2-9]{1})\)?([0-9]{2})?[-.*]?([2-9]{1})\)?([0-9]{2})?[-.*]?([0-9]{4})$

But I am stuck on trying to incorporate the logic stated here:

For NXX (exchange – next 3 digits after NPA) same rules as NPA.  In addition, the 3rd digit cannot be ‘1’ if the 2nd digit is ‘1’ (reserved for public service)

If anyone can help shine some light on this, it would be greatly appreciated.

False is what I want my regex not to match, while true is what I would want it continuing to match. It currently matches both sets .

False: 4807119320 4805119439 4809114739

True: 4805218482 4805123848 4809128327 4809418482

Body:
Using

^(?([2-9]))?([0-9]{2})?[-.]?([2-9]))?((?!11)[0-9]{2})?[-.]?([0-9]{4})$

Resolved my issue


问:
How do I Set Variable Dependent on Another Variable to Update when the Original Variable Updates?
In python, let's run the following lines of code:

x = 0
y = x
x += 1
print(y)
print(x)
```

The first line of output is clearly different from the second, even though we set x=y in line 2. Anyone experienced with programming as a whole would know that.

However, is there a way to make x update as y does?

答:
I am using the observer design pattern:</p>

```<code>#!/usr/bin/env python
# -*-coding: utf-8 -*-

class X:
    def __init__(self, subject):
        self.subject = subject
        self.subject.register(self)
        self.update()

    def update(self):
        self.data = self.subject.data

class Y:
    def __init__(self, data=10):
        self.data = data
        self._observers = list()

    def set(self, value):
        self.data = value
        self.notify()

    def register(self, observer):
        self._observers.append(observer)

    def notify(self):
        for ob in self._observers:
            ob.update()

y = Y(1)
x = X(y)
assert x.data == 1 and y.data == 1

y.set(20)
assert x.data == 20 and y.data == 20

y.set(-1)
assert x.data == -1 and y.data == -1
</code>```

Body:
In python, let's run the following lines of code:

x = 0
y = x
x += 1
print(y)
print(x)

The first line of output is clearly different from the second, even though we set x=y in line 2. Anyone experienced with programming as a whole would know that.

However, is there a way to make x update as y does?

Body:
I am using the observer design pattern:

#!/usr/bin/env python
# -*-coding: utf-8 -*-

class X:
    def __init__(self, subject):
        self.subject = subject
        self.subject.register(self)
        self.update()

    def update(self):
        self.data = self.subject.data

class Y:
    def __init__(self, data=10):
        self.data = data
        self._observers = list()

    def set(self, value):
        self.data = value
        self.notify()

    def register(self, observer):
        self._observers.append(observer)

    def notify(self):
        for ob in self._observers:
            ob.update()

y = Y(1)
x = X(y)
assert x.data == 1 and y.data == 1

y.set(20)
assert x.data == 20 and y.data == 20

y.set(-1)
assert x.data == -1 and y.data == -1


问:
How to import .AVI files?
I am trying to import an .avi file for frame processing.

```<code>Import["c:\\windows\\clock.avi","Elements"]
Import["c:\\windows\\clock.avi","VideoEncoding"]
Import["c:\\windows\\clock.avi"]
Import["c:\\windows\\clock.avi",{"Frames",{5,6}}]

Out[115]= {Animation,BitDepth,ColorSpace,Data,Duration,FrameCount,FrameRate,
           Frames,GraphicsList,ImageList,ImageSize,VideoEncoding}
Out[116]= rle8
Out[117]= {1,2,3,4,5,6,7,8,9,10,11,12}
During evaluation of In[115]:= Import::fmterr: Cannot import data as video format.
During evaluation of In[115]:= Import::fmterr: Cannot import data as video format.
Out[118]= {$Failed,$Failed}
</code>```

It reports the same error with all avi files I tested.

Any hints?

答:
AVI is a container format. You can encode movies with totally bizar and rare formats and still call it .avi.

You could use a video format converter like freemake to convert your movie into a format Mathematica can use. Check with Internal`$VideoEncodings what kind of internal formats are recognized.

Quite often, Quicktime (.mov) works easiest. AVIs sometimes load just fine, but don't display at all even if I have the correct codec on board and all my players can play it.

If all else fails, you can try VirtualDub. It can read AVIs and split them into separate images, which can easily be imported into mma.

EDIT

I recall from my most recent video project a total failure to read the AVIs I got from having the FireFox plugin DownloadHelper download a certain YouTube movie (though it played in all the players I have, VLC, Media Player Classic, Windows Media player etc.). A conversion by DH to .mov worked but DH inserts its logo into it. So finally I resorted to a download with FreeMake and conversion to individual frames by means of VirtualDub.

Title: How to import .AVI files?

Body:
I am trying to import an .avi file for frame processing.

Import["c:\\windows\\clock.avi","Elements"]
Import["c:\\windows\\clock.avi","VideoEncoding"]
Import["c:\\windows\\clock.avi"]
Import["c:\\windows\\clock.avi",{"Frames",{5,6}}]

Out[115]= {Animation,BitDepth,ColorSpace,Data,Duration,FrameCount,FrameRate,
           Frames,GraphicsList,ImageList,ImageSize,VideoEncoding}
Out[116]= rle8
Out[117]= {1,2,3,4,5,6,7,8,9,10,11,12}
During evaluation of In[115]:= Import::fmterr: Cannot import data as video format.
During evaluation of In[115]:= Import::fmterr: Cannot import data as video format.
Out[118]= {$Failed,$Failed}

It reports the same error with all avi files I tested.

Any hints?


答:
One option uses a correlated subquery to find the 7 day rolling sums:</p>

```<code>SELECT
    CUSTOMER_ID,
    ORDER_DATE,
    QUANTITY,
    (SELECT SUM(t2.QUANTITY) FROM yourTable t2
     WHERE t1.CUSTOMER_ID = t2.CUSTOMER_ID AND
           t2.ORDER_DATE >= DATE_SUB(t1.ORDER_DATE, INTERVAL 7 DAY) AND
           t2.ORDER_DATE < t1.ORDER_DATE) AS ORDER_HISTORY
FROM yourTable t1
ORDER BY ORDER_DATE;
</code>```

Title: Retrieve Past 7 days Order History from Order Table

Body:
Given Order Table with Columns Customer_Id, Order_Date, Quantity. How to generate another column that has Sum of Quantity for past seven days excluding the current order date.

Input:

CUSTOMER_ID ORDER_DATE  QUANTITY
          1 2019-05-01  1
          1 2019-05-02  1
          2 2019-05-02  1
          2 2019-05-03  1
          2 2019-05-04  1
          1 2019-05-05  1
          2 2019-05-05  1
          1 2019-05-06  1
          2 2019-05-06  1
          1 2019-05-07  1
          2 2019-05-07  1
          1 2019-05-08  1
          2 2019-05-08  1
          1 2019-05-09  1
          1 2019-05-10  1
          1 2019-05-11  1
          2 2019-05-11  1
          2 2019-05-12  1
          2 2019-05-13  1
          2 2019-05-14  1
          2 2019-05-15  1
          1 2019-05-16  1

Output:

CUSTOMER_ID ORDER_DATE  QUANTITY    ORDER_HISTORY
         1  2019-05-01  1           0
         1  2019-05-02  1           1
         2  2019-05-02  1           0
         2  2019-05-03  1           1
         2  2019-05-04  1           2
         1  2019-05-05  1           2
         2  2019-05-05  1           3
         1  2019-05-06  1           3
         2  2019-05-06  1           4
         1  2019-05-07  1           4
         2  2019-05-07  1           5
         1  2019-05-08  1           4
         2  2019-05-08  1           6
         1  2019-05-09  1           4
         1  2019-05-10  1           5
         1  2019-05-11  1           6
         2  2019-05-11  1           4
         2  2019-05-12  1           4
         2  2019-05-13  1           4
         2  2019-05-14  1           4
         2  2019-05-15  1           4
         1  2019-05-16  1           2

So far, I tried using DATE_SUB(ORDER_DATE, INTERVAL 6 DAY) without any luck.

Body:
One option uses a correlated subquery to find the 7 day rolling sums:

SELECT
    CUSTOMER_ID,
    ORDER_DATE,
    QUANTITY,
    (SELECT SUM(t2.QUANTITY) FROM yourTable t2
     WHERE t1.CUSTOMER_ID = t2.CUSTOMER_ID AND
           t2.ORDER_DATE >= DATE_SUB(t1.ORDER_DATE, INTERVAL 7 DAY) AND
           t2.ORDER_DATE < t1.ORDER_DATE) AS ORDER_HISTORY
FROM yourTable t1
ORDER BY ORDER_DATE;


问:
Updating a row in Microsoft SQL Server
I need to update a couple of rows in my database. But after updating the values and having confirmation that the values were updated, it reverts back to its original values.

Here is the script that I wrote

```<code>BEGIN TRAN;

UPDATE cars
SET sold = sold + 5
WHERE id IN (18, 25);

COMMIT TRAN;
</code>```

I ran the above script successfully, no errors were displayed and it showed that 2 rows were updated. I ran SELECT on the cars table and it showed that sold was indeed updated.

After that, I went and opened the system (a custom system for my project) that is using this database to view it on my admin panel. However, the sold column was not updated and showed the old values. When I ran SELECT again on the cars table, it returns my old values instead of the updated one.

Am I doing anything wrong? Since I have ran SELECT after updating and it showed that the values were indeed updated.

答: Another operation is updating the table again. Use the SQL SERVER PROFILER and check if other transactions are executed after your UPDATE. Additionally, in your project verify by sending the correct parameters so that you return the result you expect.</p>

Title: Updating a row in Microsoft SQL Server

Body:
I need to update a couple of rows in my database. But after updating the values and having confirmation that the values were updated, it reverts back to its original values.

Here is the script that I wrote

BEGIN TRAN;

UPDATE cars
SET sold = sold + 5
WHERE id IN (18, 25);

COMMIT TRAN;

I ran the above script successfully, no errors were displayed and it showed that 2 rows were updated. I ran SELECT on the cars table and it showed that sold was indeed updated.

After that, I went and opened the system (a custom system for my project) that is using this database to view it on my admin panel. However, the sold column was not updated and showed the old values. When I ran SELECT again on the cars table, it returns my old values instead of the updated one.

Am I doing anything wrong? Since I have ran SELECT after updating and it showed that the values were indeed updated.


问:
How to write SQL Select Query with a variable in Swift?
EDIT: now, I'm getting that my query statement has no results, when I know it does...

How to write a Select Statement in Swift that uses a local variable.

I have over 50 columns, how do I concatenate all the column names in an array?

```<code>let queryStatementStringSearch = "SELECT * FROM TABLE where Col1 = (?);"

var queryStatement: OpaquePointer? = nil
// 1
if sqlite3_prepare_v2(db, queryStatementStringSearch=, -1, &queryStatement, nil) == SQLITE_OK {
    sqlite3_bind_text(queryStatement, 1, userInput, -1, nil)
    // 2
    if sqlite3_step(queryStatement) == SQLITE_ROW {
        // 3
        let id = sqlite3_column_int(queryStatement, 0)

        // 4
        let queryResultCol1 = sqlite3_column_text(queryStatement, 1)
        let name = String(cString: queryResultCol1!)

        // 5
        print("Query Result:")
        print("\(id) | \(name)")

    } else {
        print("Query returned no results")
    }
} else {
    print("SELECT statement could not be prepared")
}
</code>```

答:
Your "SELECT" statement should be:

```<code>SELECT * FROM TABLE where Col1 = ?
</code>```

Calls to sqlite3_bind_xxx expect a 1-based column number. You are passing an index of 2 but it needs to be 1.

```<code>sqlite3_bind_text(queryStatement, 1, userInput, -1, nil)
</code>```

Make sure you call sqlite3_finalize on the prepared statement.

It's also a bad idea to use SELECT *. Explicitly list the column names. This ensures that when you make calls to sqlite3_column_xxx, the index you pass (which is 0-based, not 1-based) is to a known column in a fixed position.

Body:
EDIT: now, I'm getting that my query statement has no results, when I know it does...

How to write a Select Statement in Swift that uses a local variable.

I have over 50 columns, how do I concatenate all the column names in an array?

let queryStatementStringSearch = "SELECT * FROM TABLE where Col1 = (?);"

var queryStatement: OpaquePointer? = nil
// 1
if sqlite3_prepare_v2(db, queryStatementStringSearch=, -1, &queryStatement, nil) == SQLITE_OK {
    sqlite3_bind_text(queryStatement, 1, userInput, -1, nil)
    // 2
    if sqlite3_step(queryStatement) == SQLITE_ROW {
        // 3
        let id = sqlite3_column_int(queryStatement, 0)

        // 4
        let queryResultCol1 = sqlite3_column_text(queryStatement, 1)
        let name = String(cString: queryResultCol1!)

        // 5
        print("Query Result:")
        print("\(id) | \(name)")

    } else {
        print("Query returned no results")
    }
} else {
    print("SELECT statement could not be prepared")
}

Body:
Your "SELECT" statement should be:

SELECT * FROM TABLE where Col1 = ?

Calls to sqlite3_bind_xxx expect a 1-based column number. You are passing an index of 2 but it needs to be 1.

sqlite3_bind_text(queryStatement, 1, userInput, -1, nil)

Make sure you call sqlite3_finalize on the prepared statement.

It's also a bad idea to use SELECT *. Explicitly list the column names. This ensures that when you make calls to sqlite3_column_xxx, the index you pass (which is 0-based, not 1-based) is to a known column in a fixed position.


问:
Submit a Spark job from C# and get results
As per title, I would like to request a calculation to a Spark cluster (local/HDInsight in Azure) and get the results back from a C# application.

I acknowledged the existence of Livy which I understand is a REST API application sitting on top of Spark to query it, and I have not found a standard C# API package. Is this the right tool for the job? Is it just missing a well known C# API?

The Spark cluster needs to access Azure Cosmos DB, therefore I need to be able to submit a job including the connector jar library (or its path on the cluster driver) in order for Spark to read data from Cosmos.

答: Microsoft just released a dataframe based .NET support for Apache Spark via the .NET Foundation OSS. See http://dot.net/spark and http://github.com/dotnet/spark for more details. It is now available in HDInsight per default if you select the correct HDP/Spark version (currently 3.6 and 2.3, soon others as well).</p>


问:
Windows Azure xml comments file not found
I've recently published my web application to a windows API app service plan on Azure, and since have been having multiple issues with the XML docs I am using for swagger.

I'm getting an error 500:

```<code>DirectoryNotFoundException: Could not find a part of the path 'D:\home\site\wwwroot\bin\Release\netcoreapp1.1\Zwekness.Api.xml'
</code>```

At first the file wasn't being added when publishing, having done that manually I can now 100% confirm the file is on the server
as seen here, yet I am getting the exact same error.
I'm out of ideas what could be causing this behaviour ...

答:
Be sure that XML documentation file in Project Properties | Build | Output is set for debug and release configuration.

Be sure that you copied the xml file in the correct path. If you just specify a file name in step one then you need to have the xml file in your wwwroot folder.

Body:
I've recently published my web application to a windows API app service plan on Azure, and since have been having multiple issues with the XML docs I am using for swagger.

I'm getting an error 500:

DirectoryNotFoundException: Could not find a part of the path 'D:\home\site\wwwroot\bin\Release\netcoreapp1.1\Zwekness.Api.xml'

At first the file wasn't being added when publishing, having done that manually I can now 100% confirm the file is on the server
as seen here, yet I am getting the exact same error.
I'm out of ideas what could be causing this behaviour ...


问:
"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason
Our database is currently at 64 Gb and one of our apps started to fail with the following error:

System.Data.SqlClient.SqlException: Could not allocate space for object 'cnv.LoggedUnpreparedSpos'.'PK_LoggedUnpreparedSpos' in database 'travelgateway' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.

I double-checked everything: all files in a single filegroup are allowed to autogrow with a reasonable increments (100 Mb for a data file, 10% for a log file), more than 100 Gb of free space is available for the database, tempdb is set to autogrow as well with plenty of free HDD space on its drive.

To resolve a problem, I added second file to the filegroup and the error has gone. But I feel uneasy about this whole situation.

Where' the problem here, guys?

答:
In my experience, this message occurs when the primary file (.mdf) has no space to save the metadata of the database. This file include the system tables and they only save their data into it.

Make some space in the file and the commands works again.
That's all, Enjoy

ContentLicense: CC BY-SA 2.5


问:
Python - List comprehension within File I/O code
I want to replicate the functionality of the following code using a list comprehension:

```<code>with open('file.txt', 'w') as textfile:
    for i in range(1, 6):
        textfile.write(str(i) + '\n')
</code>```

I tried the following:

```<code>with open('file.txt', 'w') as textfile:
    textfile.write(str([i for i in range(1, 6)]) + '\n')
</code>```

but it (understandably) prints [1, 2, 3, 4, 5], instead of one number on a single line.

I don't have an answer to 'Why would you want to do that?'; I just want to see if it's possible. Thanks!

EDIT: Thank you all for the replies; for some reason I was under the impression that list comprehensions are always encapsulated in [].

答:
Please try the following:</p>

```<code>open('/tmp/foo.txt','w').writelines(f'{i}\n' for i in range(10))
</code>```

Body:
I want to replicate the functionality of the following code using a list comprehension:

with open('file.txt', 'w') as textfile:
    for i in range(1, 6):
        textfile.write(str(i) + '\n')

I tried the following:

with open('file.txt', 'w') as textfile:
    textfile.write(str([i for i in range(1, 6)]) + '\n')

but it (understandably) prints [1, 2, 3, 4, 5], instead of one number on a single line.

I don't have an answer to 'Why would you want to do that?'; I just want to see if it's possible. Thanks!

EDIT: Thank you all for the replies; for some reason I was under the impression that list comprehensions are always encapsulated in [].

Body:
Please try the following:

open('/tmp/foo.txt','w').writelines(f'{i}\n' for i in range(10))


问:
How to map a trait without any doctrine mapping in it?
I am wondering if there is no possibility to map an existing trait without any doctrine mapping into an entity?

```<code>trait TimestampableTrait
{
    protected $createdAt;
    protected $updatedAt;
}

/**
 * @ORM\Entity()
 * @ORM\Table(name="product")
 */
class Product
{
    use TimestampableTrait;

    /**
     *
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
}
</code>```

I have tried the AttributeOverride, but it seems only to work with mapped super classes.

Is there any easy way to achieve this with annotations or do I need a yml / xml mapping?

答:
Your entity needs at least one column which acts as primary key. So either you add an ID column to your Product entity, or you add some annotations to TimestampableTrait. For example, this works:

```<code>trait TimestampableTrait
{
    /**
     * @ORM\Id
     * @ORM\Column
     */
    protected $createdAt;
}

/**
 * @ORM\Entity()
 * @ORM\Table(name="product")
 */
final class Product
{
    use TimestampableTrait;
}
</code>```

That produces

```<code>CREATE TABLE product (
    created_at VARCHAR(255) NOT NULL,
    PRIMARY KEY(created_at)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB;
</code>```

If you want to change the column definition in your product class, you can use AttributeOverride like this:

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 * @ORM\AttributeOverrides({
 *      @ORM\AttributeOverride(
 *          name="createdAt", column=@ORM\Column(name="id")
 *     )
 * })
 */
final class Product
{
    use TimestampableTrait;
}
</code>```

Which will produce:

```<code>CREATE TABLE product (
    id VARCHAR(255) NOT NULL,
    PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB;
</code>```

Note that you cannot change the column type like this.

Body:
I am wondering if there is no possibility to map an existing trait without any doctrine mapping into an entity?

trait TimestampableTrait
{
    protected $createdAt;
    protected $updatedAt;
}

/**
 * @ORM\Entity()
 * @ORM\Table(name="product")
 */
class Product
{
    use TimestampableTrait;

    /**
     *
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
}

I have tried the AttributeOverride, but it seems only to work with mapped super classes.

Is there any easy way to achieve this with annotations or do I need a yml / xml mapping?

Body:
Your entity needs at least one column which acts as primary key. So either you add an ID column to your Product entity, or you add some annotations to TimestampableTrait. For example, this works:

trait TimestampableTrait
{
    /**
     * @ORM\Id
     * @ORM\Column
     */
    protected $createdAt;
}

/**
 * @ORM\Entity()
 * @ORM\Table(name="product")
 */
final class Product
{
    use TimestampableTrait;
}

That produces

CREATE TABLE product (
    created_at VARCHAR(255) NOT NULL,
    PRIMARY KEY(created_at)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB;

If you want to change the column definition in your product class, you can use AttributeOverride like this:

/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 * @ORM\AttributeOverrides({
 *      @ORM\AttributeOverride(
 *          name="createdAt", column=@ORM\Column(name="id")
 *     )
 * })
 */
final class Product
{
    use TimestampableTrait;
}

Which will produce:

CREATE TABLE product (
    id VARCHAR(255) NOT NULL,
    PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB;

Note that you cannot change the column type like this.


答:
To expand on @juanpa's comment, you can get this behavior if you wrap the value in a list:</p>

```<code>x = [0]
y = x
x[0] += 1
print(y[0])
print(x[0])
</code>```

Title: How do I Set Variable Dependent on Another Variable to Update when the Original Variable Updates?

Body:
To expand on @juanpa's comment, you can get this behavior if you wrap the value in a list:

x = [0]
y = x
x[0] += 1
print(y[0])
print(x[0])


问:
How do I fix a button command from being executed as soon as the code is run?
I'm trying to get a button to execute a function from another file called validate.py when it's pressed, but the function seems to be executing as soon as I run the code but not when I actually press it?

Button's code:

```<code>id_validate = ttk.Button(id_frame, text='Validate',
command=validate.validate(pack_id.get()))
</code>```

And this is the function's code:

```<code>def validate(pack_id):
    print('vAliDAte')
    return True
</code>```

I want that function to execute every time I click the button and print 'validate' in the console, but it only executes once as soon as I run the code and doesn't respond when the button is pressed.

How do I stop it from executing when the code is run and only execute when the button is pressed?

答:
The function executes because you call it; ends the function name with parenthesis.

The command attribute only wants the name of the function.

However, you can fix this with lambda:

```<code>command=lambda: validate(pack_id.get())
</code>```

A warning about using the name pack_id in the function: you already have used that name in the global scope in calling the function with the argument pack_id.get(). This might cause problems down the line.

Body:
I'm trying to get a button to execute a function from another file called validate.py when it's pressed, but the function seems to be executing as soon as I run the code but not when I actually press it?

Button's code:

id_validate = ttk.Button(id_frame, text='Validate',
command=validate.validate(pack_id.get()))

And this is the function's code:

def validate(pack_id):
    print('vAliDAte')
    return True

I want that function to execute every time I click the button and print 'validate' in the console, but it only executes once as soon as I run the code and doesn't respond when the button is pressed.

How do I stop it from executing when the code is run and only execute when the button is pressed?

Body:
The function executes because you call it; ends the function name with parenthesis.

The command attribute only wants the name of the function.

However, you can fix this with lambda:

command=lambda: validate(pack_id.get())

A warning about using the name pack_id in the function: you already have used that name in the global scope in calling the function with the argument pack_id.get(). This might cause problems down the line.


问:
How to update PostgreSQL timezone database
I use PostgreSQL version 9.5 on server. Timezone database apparently becomes outdated as time passes.

For example, according to icann mailing list, Volgograd, Russia moved from +3 to +4. However, in my database it looks like it is still in the same time zone as Moscow, Russia:

```<code>SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'Europe/Moscow';
        timezone
------------------------
 2001-02-16 20:38:40+03

SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'Europe/Volgograd';
        timezone
------------------------
 2001-02-16 20:38:40+03
</code>```

Is there a way to update just timezone database without updating or reinstalling the entire PostgreSQL?

答:
you can set a timezone to your database for example:

```<code>alter DATABASE your_dabase  set timezone  = '+N' --number of timezone
</code>```

or can use alter system to change to all databases in server:

```<code>alter system set timezone to '+N'; --number of timezone, reload configuration
</code>```

Regards

Body:
I use PostgreSQL version 9.5 on server. Timezone database apparently becomes outdated as time passes.

For example, according to icann mailing list, Volgograd, Russia moved from +3 to +4. However, in my database it looks like it is still in the same time zone as Moscow, Russia:

SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'Europe/Moscow';
        timezone
------------------------
 2001-02-16 20:38:40+03

SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'Europe/Volgograd';
        timezone
------------------------
 2001-02-16 20:38:40+03

Is there a way to update just timezone database without updating or reinstalling the entire PostgreSQL?

Body:
you can set a timezone to your database for example:

alter DATABASE your_dabase  set timezone  = '+N' --number of timezone

or can use alter system to change to all databases in server:

alter system set timezone to '+N'; --number of timezone, reload configuration

Regards


问:
How to create a switching function in Python?
I'm having difficulty creating a program that switches between string "X" and "O" every time the function is ran.

So for example, the first time switcher() is ran, it prints "x," and the next time it runs, it prints "o," and third it prints "x," and so forth

I've been able to achieve this without a function and just using an if else loop, but I can't do it using a function

```<code>def switch(value):
    if value == 0:
        x = value
        x + 1
        print("value: " + str(x) + " | turn: x")
        return x
    else:
        print("o")
        return 0

x = 0
for i in range(4):
    switch(x)
</code>```

it outputs:

```<code>value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
</code>```

In order to achieve this, I make it so that when x = 0, it prints "X" and when it's 1 it prints "O," and then resets back to 0. It stays as 0 and only gives me x.

答:
You could do something like this...works pretty well:

```<code>def switch(count):
    x = 0
    z = 1
    y = 0
    value = 1
    while x < count:
        if value == z:
            print(y)
            value = 0
        elif value == y:
            print(z)
            value = 1
        x+=1
</code>```

Then: (Based on the count it prints however many alterations)

```<code>switch(10)
0
1
0
1
0
1
0
1
0
1
</code>```

Body:
I'm having difficulty creating a program that switches between string "X" and "O" every time the function is ran.

So for example, the first time switcher() is ran, it prints "x," and the next time it runs, it prints "o," and third it prints "x," and so forth

I've been able to achieve this without a function and just using an if else loop, but I can't do it using a function

def switch(value):
    if value == 0:
        x = value
        x + 1
        print("value: " + str(x) + " | turn: x")
        return x
    else:
        print("o")
        return 0

x = 0
for i in range(4):
    switch(x)

it outputs:

value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x

In order to achieve this, I make it so that when x = 0, it prints "X" and when it's 1 it prints "O," and then resets back to 0. It stays as 0 and only gives me x.

Body:
You could do something like this...works pretty well:

def switch(count):
    x = 0
    z = 1
    y = 0
    value = 1
    while x < count:
        if value == z:
            print(y)
            value = 0
        elif value == y:
            print(z)
            value = 1
        x+=1

Then: (Based on the count it prints however many alterations)

switch(10)
0
1
0
1
0
1
0
1
0
1