问:
Get values of 2 columns as single value separated with '|'
```<code>DECLARE @mockup TABLE(Column1 VARCHAR(1),Column2 VARCHAR(1));
INSERT INTO @mockup VALUES('1','2'),('-','2'),('1','2'),('-','-'),('2','-'),('1','2');

SELECT ISNULL(NULLIF(Column1 + '|','-|'),'')
      +ISNULL(NULLIF(Column2,'-'),'')
FROM @mockup
</code>```

Above query result is as below,

```<code>1|2
2
1|2
2|
1|2
</code>```

I want the result as above only except row4, where 2| should be only as 2 .
'|' should not be there at before or end of the values.

答:
I would do this as:

```<code>select stuff( ((case when column1 not like '-' then '|' + column1 else '' end) +
               (case when column2 not like '-' then '|' + column2 else '' end)
              ), 1, 1, '');
</code>```

This is the simplest way that I've found to implement concat_ws() in SQL Server.  concat_ws() is a function available in other databases, where you would just do:

```<code>select concat_ws('|',
                 (case when column1 not like '-' then column1 end),
                 (case when column2 not like '-' then column2 end)
                )
</code>```

Body:
DECLARE @mockup TABLE(Column1 VARCHAR(1),Column2 VARCHAR(1));
INSERT INTO @mockup VALUES('1','2'),('-','2'),('1','2'),('-','-'),('2','-'),('1','2');

SELECT ISNULL(NULLIF(Column1 + '|','-|'),'')
      +ISNULL(NULLIF(Column2,'-'),'')
FROM @mockup

Above query result is as below,

1|2
2
1|2
2|
1|2

I want the result as above only except row4, where 2| should be only as 2 .
'|' should not be there at before or end of the values.

Body:
I would do this as:

select stuff( ((case when column1 not like '-' then '|' + column1 else '' end) +
               (case when column2 not like '-' then '|' + column2 else '' end)
              ), 1, 1, '');

This is the simplest way that I've found to implement concat_ws() in SQL Server.  concat_ws() is a function available in other databases, where you would just do:

select concat_ws('|',
                 (case when column1 not like '-' then column1 end),
                 (case when column2 not like '-' then column2 end)
                )


来源: stackexchange

问:
Bluetooth app not working on devices running on Lollipop
I made a Bluetooth app. It works fine in Nougat, Marshmallow, Jelly Bean, KitKat but for reason, it crashes in Android Lollipop when Discover button (which discovers all the discoverable devices) is clicked.

Here is the method which gets triggered on clicking Discover button -

```<code>private void discoverDevices() {
        Log.d(TAG, "btnDiscover: Looking for unpaired devices.");

        if(mBluetoothAdapter.isDiscovering()){
            mBluetoothAdapter.cancelDiscovery();
            Log.d(TAG, "btnDiscover: Canceling discovery.");

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }
        if(!mBluetoothAdapter.isDiscovering()){

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }

    }
</code>```

CheckBTPermissions()-

```<code>private void checkBTPermissions() {

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
            permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
            if (permissionCheck != 0) {

                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
            }
        }else{
            Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version
=< LOLLIPOP.");
        }
    }
</code>```

Permissions in Manifest file-

```<code><uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
</code>```

build.gradle-

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.hpi5.bluetooth"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

I have not tested this app on Lollipop myself as I don't have any device running on Android L. I got to know about the crash from a friend of mine.

EDIT: I managed to arrange the logs.

```<code>07-07 19:29:00.219 30852-30852/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.hpi5.bluetooth, PID: 30852
                                                   java.lang.NoSuchMethodError: No virtual method checkSelfPermission(Ljava/lang/String;)I in class Lcom/example/hpi5/bluetooth/MainActivity; or its super classes (declaration of 'com.example.hpi5.bluetooth.MainActivity' appears in /data/app/com.example.hpi5.bluetooth-1/base.apk)
                                                       at com.example.hpi5.bluetooth.MainActivity.checkBTPermissions(MainActivity.java:243)
                                                       at com.example.hpi5.bluetooth.MainActivity.discoverDevices(MainActivity.java:230)
                                                       at com.example.hpi5.bluetooth.MainActivity.access$100(MainActivity.java:24)
                                                       at com.example.hpi5.bluetooth.MainActivity$7.onClick(MainActivity.java:189)
                                                       at android.view.View.performClick(View.java:4923)
                                                       at android.view.View$PerformClick.run(View.java:20341)
                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
</code>```

答:
So I arranged the logs somehow and found even for devices running on Lollipop the following condition was evaluating to true

```<code>if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
    //code here
}
</code>```

and because of this, the app was crashing on clicking the Discover button.

So, I just changed the above condition to -

```<code>if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

}
</code>```

The app is working fine on Lollipop devices now.

Why was it crashing on Lollipop devices earlier?

So, my friend's device was running on Android version 5.1.1 and that is why the condition was evaluating to true. And since checkSelfPermission was introduced in API level 23 (Android M), the app could not find it and thus crashed.

ContentLicense: CC BY-SA 3.0

Body:
I made a Bluetooth app. It works fine in Nougat, Marshmallow, Jelly Bean, KitKat but for reason, it crashes in Android Lollipop when Discover button (which discovers all the discoverable devices) is clicked.

Here is the method which gets triggered on clicking Discover button -

private void discoverDevices() {
        Log.d(TAG, "btnDiscover: Looking for unpaired devices.");

        if(mBluetoothAdapter.isDiscovering()){
            mBluetoothAdapter.cancelDiscovery();
            Log.d(TAG, "btnDiscover: Canceling discovery.");

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }
        if(!mBluetoothAdapter.isDiscovering()){

            //check BT permissions in manifest
            checkBTPermissions();

            mBluetoothAdapter.startDiscovery();
            IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
        }

    }

CheckBTPermissions()-

private void checkBTPermissions() {

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
            permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
            if (permissionCheck != 0) {

                this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
            }
        }else{
            Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version
=< LOLLIPOP.");
        }
    }

Permissions in Manifest file-

<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />

build.gradle-

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.hpi5.bluetooth"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

I have not tested this app on Lollipop myself as I don't have any device running on Android L. I got to know about the crash from a friend of mine.

EDIT: I managed to arrange the logs.

07-07 19:29:00.219 30852-30852/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.hpi5.bluetooth, PID: 30852
                                                   java.lang.NoSuchMethodError: No virtual method checkSelfPermission(Ljava/lang/String;)I in class Lcom/example/hpi5/bluetooth/MainActivity; or its super classes (declaration of 'com.example.hpi5.bluetooth.MainActivity' appears in /data/app/com.example.hpi5.bluetooth-1/base.apk)
                                                       at com.example.hpi5.bluetooth.MainActivity.checkBTPermissions(MainActivity.java:243)
                                                       at com.example.hpi5.bluetooth.MainActivity.discoverDevices(MainActivity.java:230)
                                                       at com.example.hpi5.bluetooth.MainActivity.access$100(MainActivity.java:24)
                                                       at com.example.hpi5.bluetooth.MainActivity$7.onClick(MainActivity.java:189)
                                                       at android.view.View.performClick(View.java:4923)
                                                       at android.view.View$PerformClick.run(View.java:20341)
                                                       at android.os.Handler.handleCallback(Handler.java:815)
                                                       at android.os.Handler.dispatchMessage(Handler.java:104)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

Body:
So I arranged the logs somehow and found even for devices running on Lollipop the following condition was evaluating to true

if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
    //code here
}

and because of this, the app was crashing on clicking the Discover button.

So, I just changed the above condition to -

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

}

The app is working fine on Lollipop devices now.

Why was it crashing on Lollipop devices earlier?

So, my friend's device was running on Android version 5.1.1 and that is why the condition was evaluating to true. And since checkSelfPermission was introduced in API level 23 (Android M), the app could not find it and thus crashed.


问:
Issue while Fetching tweets using Flume
I'm able to fetch tweets using flume, however, the language in which it is streamed is not what I want. Below is the flume.conf file

And the tweets that I'm getting is shown below:

Can anyone suggest changes that I need to make.?

答:
The TwitterSource in Apache Flume currently does not implement support for language filtering.  This prior question describes a procedure (admittedly complex) by which you could deploy your own patched version of the code with language support:

Flume - TwitterSource language filter

I think it would be a valuable enhancement for Apache Flume to support language filtering.  I encourage you to file a request in Apache JIRA in the FLUME project.

If you're interested, please also consider contributing a patch.  I think it would just be a matter of pulling the "language" setting out of configuration in the configure method, saving it in a member variable, and then passing it along in the Twitter4J APIs.

Title: Issue while Fetching tweets using Flume


问:
Vulkan Device Lost after submitting single-time CommandBuffer
I have written a basic Vulkan renderer a while and it worked fine. It then broke(something with the power supply) and I reinstalled the Vulkan drivers to version 1.0.42.0 and since then it gives me the error VK_ERROR_DEVICE_LOST when submitting a CommandBuffer for singe-time use(loading textures etc). I have tried the code on a different device with a different GPU, and there it works just fine. The exact breaking code:

```<code>vkEndCommandBuffer(commandBuffer);

VkSubmitInfo submitInfo =
    init::SubmitInfo();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;

vkQueueSubmit(context->transferQueue, 1, &submitInfo, VK_NULL_HANDLE);
//works fine until now
vkQueueWaitIdle(context->transferQueue);
//This gives me VK_ERROR_DEVICE_LOST
vkFreeCommandBuffers(context->device, context->cmdTempPool, 1, &commandBuffer);
//Also doesn't work since commandbuffer is still in queue
</code>```

It also only seems to happen during initialization, since it isn't giving me any errors during runtime(actual rendering code), but they occur again during cleanup(deleting textures and buffers)
Have there been any reports or workarounds for this problem?

The exact validation layer output is:

```<code>ParameterValidation: vkQueueWaitIdle: returned VK_ERROR_DEVICE_LOST,
indicating that the logical device has been lost
DS: Attempt to free command buffer (0x000002D18AAF1A90) which is in use. For
more information refer to Vulkan Spec Section '5.3. Command Buffer
Allocation and Management' which states 'All elements of pCommandBuffers
must not be in the pending state'
(https://www.khronos.org/registry/vulkan/specs/1.0-
extensions/html/vkspec.html#vkFreeCommandBuffers)
ParameterValidation: vkQueueSubmit: returned VK_ERROR_DEVICE_LOST,
indicating that the logical device has been lost
</code>```

EDIT:
since it seems to only happen when transitioning image layouts, here is the code for that:

```<code>void util::transitionImageLayout(VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout)
{
VkCommandBuffer commandBuffer = beginSingleTimeCommands();

VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
    barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
}
else {
    barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
}
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
if (oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
    barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
    barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
    barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
    barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
    barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
    barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
    barrier.srcAccessMask = 0;
    barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
}
else {
    throw std::invalid_argument("unsupported layout transition!");
}

vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);

endSingleTimeCommands(commandBuffer);
}
</code>```

答:
As noted in the comments you need to keep track of image ownership, esp. if you work with different queue families.

So make sure you specify all queue familiy indices that access an image at creation time (VkImageCreateInfo.pQueueFamilyIndices and VkImageCreateInfo.queueFamilyIndexCount) if you're using VK_SHARING_MODE_CONCURRENT. If you don't need concurrent queue access to the images you can also go with VK_SHARING_MODE_EXCLUSIVE without the need to specify queue family indices.

When dealing with different queue family indices (graphics and compute e.g.) it's also important to do proper queue family ownership transfer in your barriers via their srcQueueFamilyIndex and dstQueueFamilyIndex members in both directions.

Body:
I have written a basic Vulkan renderer a while and it worked fine. It then broke(something with the power supply) and I reinstalled the Vulkan drivers to version 1.0.42.0 and since then it gives me the error VK_ERROR_DEVICE_LOST when submitting a CommandBuffer for singe-time use(loading textures etc). I have tried the code on a different device with a different GPU, and there it works just fine. The exact breaking code:

vkEndCommandBuffer(commandBuffer);

VkSubmitInfo submitInfo =
    init::SubmitInfo();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;

vkQueueSubmit(context->transferQueue, 1, &submitInfo, VK_NULL_HANDLE);
//works fine until now
vkQueueWaitIdle(context->transferQueue);
//This gives me VK_ERROR_DEVICE_LOST
vkFreeCommandBuffers(context->device, context->cmdTempPool, 1, &commandBuffer);
//Also doesn't work since commandbuffer is still in queue

It also only seems to happen during initialization, since it isn't giving me any errors during runtime(actual rendering code), but they occur again during cleanup(deleting textures and buffers)
Have there been any reports or workarounds for this problem?

The exact validation layer output is:

ParameterValidation: vkQueueWaitIdle: returned VK_ERROR_DEVICE_LOST,
indicating that the logical device has been lost
DS: Attempt to free command buffer (0x000002D18AAF1A90) which is in use. For
more information refer to Vulkan Spec Section '5.3. Command Buffer
Allocation and Management' which states 'All elements of pCommandBuffers
must not be in the pending state'
(https://www.khronos.org/registry/vulkan/specs/1.0-
extensions/html/vkspec.html#vkFreeCommandBuffers)
ParameterValidation: vkQueueSubmit: returned VK_ERROR_DEVICE_LOST,
indicating that the logical device has been lost

EDIT:
since it seems to only happen when transitioning image layouts, here is the code for that:

void util::transitionImageLayout(VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout)
{
VkCommandBuffer commandBuffer = beginSingleTimeCommands();

VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
    barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
}
else {
    barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
}
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
if (oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
    barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
    barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
    barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
    barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
    barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
    barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
    barrier.srcAccessMask = 0;
    barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
}
else {
    throw std::invalid_argument("unsupported layout transition!");
}

vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);

endSingleTimeCommands(commandBuffer);
}


问:
Max, Min, Avg function for an array in C++
I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg.  My function must:  process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.</p>

```<code>#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    max = 0;
    min = 0;
    //int amount = size;
    int count = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i=0; i < size; i++)
    {
        count++;
        sum += i;

        if ( i > max)
        {
            i=max;
        }

        else if (i < min)
        {
            i=min;
        }
    }
    avg = sum/count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};

    cout << normalizeMinMaxAvg (data, 4, min, max, avg);
    return 0;
}
</code>```

答:
Couple things I noticed:

The values are stored in data[] so you must use data[i] in your loop to check for min, max, and to compute the average.

Also, you want to initialize min to the maximum double value so that it will be replaced by the actual minimum from the data.

Body:
I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg.  My function must:  process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.

#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    max = 0;
    min = 0;
    //int amount = size;
    int count = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i=0; i < size; i++)
    {
        count++;
        sum += i;

        if ( i > max)
        {
            i=max;
        }

        else if (i < min)
        {
            i=min;
        }
    }
    avg = sum/count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};

    cout << normalizeMinMaxAvg (data, 4, min, max, avg);
    return 0;
}


问:
Jackson JSON Deserialization of MongoDB ObjectId
Ok, so first off here's the JSON that's returning from my web service. I'm trying to deserialize it into pojos after an asynchronous query in a ResponseHandler in my Android ContentProvider.

```<code>{"exampleList" : [{
"locationId" : "00001" ,
"owners" : [
  {
    "paidID" : { "$oid" : "50a9c951300493f64fbffdb6"} ,
    "userID" : { "$oid" : "50a9c951300493f64fbffdb6"}
  } ,
  {
    "paidID" : { "$oid" : "50a9c951300493f64fbffdb7"} ,
    "userID" : { "$oid" : "50a9c951300493f64fbffdb7"}
  }
]
}]}
</code>```

At first, I was confused about the problem I was seeing, since I use the same Jackson-annotated beans for my web service as I do in my Android app--but then I realized that the owners object was never getting sent in the sample JSON to my web service (it skips the POJOs on my web service and gets added into the documents in mongoDB through atomic updates from the DAO).

So OK. Up to now, Jackson wasn't having to handle the owners object, and now that it is it is choking on it, namely:

JsonMappingException: Can not deserialize instance of java.lang.String out of
  START_OBJECT token at [char position where you can find "userID" and "paidID"]
  through reference chain [path to my Jackson bean which contains the owners class]

My Jackson bean has a wrapper, which is what that "exampleList" is all about:

```<code>public class Examples extends HashMap<String, ArrayList<Example>> {

}
</code>```

And then the actual Example class:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class Example implements Comparable<Example> {

@ObjectId @Id
private String id;

@JsonProperty(Constants.Example.location)
private String location;

@JsonProperty(Constants.Example.OWNERS)
private List<Owners> owners;

public int compareTo(Example _o) {
    return getId().compareTo(_o.getId());
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}
public List<Example.Owners> getOwners() {
    return owners;
}

public void setOwners(List<Example.Owners> owners) {
    this.owners = owners;
}

public Example() {
}

@JsonCreator
public Example(@Id @ObjectId String id) {
    this.id = id;
}

@JsonIgnoreProperties(ignoreUnknown = true)
public static class Owners implements Comparable<Owners> {

    @JsonProperty(Constants.Example.USERID)
    private String userID;

    @JsonProperty(Constants.Example.PAIDID)
    private String paidID;

    public Owners() {
    }

    public int compareTo(Owners _o) {
        return getUserID().compareTo(_o.getUserID());
    }

    @ObjectId
    public String getUserID() {
        return userID;
    }

    @ObjectId
    public void setUserID(String userID) {
        this.userID = userID;
    }

    @ObjectId
    public String getPaidID() {
        return paidID;
    }

    @ObjectId
    public void setPaidID(String paidID) {
        this.paidID = paidID;
    }

}

}
</code>```

And finally, the code in the ResponseHandler where this is all failing (the 2nd line produces the JsonMappingException):

```<code>objectMapper = MongoJacksonMapperModule.configure(objectMapper);
mExamples = objectMapper.readValue(jsonParser, Examples.class);
</code>```

I have a feeling the issue is that Jackson still doesn't know how to map those $oid, which are the mongoDB ObjectIds. The MongoJacksonMapper library is supposed to help that by providing the @ObjectId annotation and a way to configure the ObjectMapper to use that library, but it still isn't working. For some reason, it's still looking for the userID or paidID as a String, not an ObjectId. Any ideas?

答:
Jackson does not know how to serialize an ObjectId. I tweaked Arny's code to serialize any ObjectId and provide this working example:</p>

```<code>public class SerialiserTest {

 private ObjectMapper mapper = new ObjectMapper();

 public static class T {
    private ObjectId objectId;

    public ObjectId getObjectId() {
        return objectId;
    }

    public void setObjectId(ObjectId objectId) {
        this.objectId = objectId;
    }
 }

 @Test
 public final void serDeser() throws IOException {
    T t = new T();
    t.setObjectId(new ObjectId());
    List<T> ls = Collections.singletonList(t);
    String json = mapper.writeValueAsString(ls);
    System.out.println(json);
    SimpleModule mod = new SimpleModule("ObjectId", new Version(1, 0, 0, null, null, null));
    mod.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
    mapper.registerModule(mod);
    JavaType type = mapper.getTypeFactory().
            constructCollectionType(List.class, T.class);
    List<?> l  = mapper.readValue(json, type);
    System.out.println(l);
 }
}

public class ObjectIdDeserializer extends JsonDeserializer<ObjectId> {

 @Override
 public ObjectId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonNode n = (JsonNode)p.readValueAsTree();
    return new ObjectId(n.get("timestamp").asInt(), n.get("machineIdentifier").asInt(), (short) n.get("processIdentifier").asInt(), n.get("counter").asInt());
 }

}
</code>```

Body:
Ok, so first off here's the JSON that's returning from my web service. I'm trying to deserialize it into pojos after an asynchronous query in a ResponseHandler in my Android ContentProvider.

{"exampleList" : [{
"locationId" : "00001" ,
"owners" : [
  {
    "paidID" : { "$oid" : "50a9c951300493f64fbffdb6"} ,
    "userID" : { "$oid" : "50a9c951300493f64fbffdb6"}
  } ,
  {
    "paidID" : { "$oid" : "50a9c951300493f64fbffdb7"} ,
    "userID" : { "$oid" : "50a9c951300493f64fbffdb7"}
  }
]
}]}

At first, I was confused about the problem I was seeing, since I use the same Jackson-annotated beans for my web service as I do in my Android app--but then I realized that the owners object was never getting sent in the sample JSON to my web service (it skips the POJOs on my web service and gets added into the documents in mongoDB through atomic updates from the DAO).

So OK. Up to now, Jackson wasn't having to handle the owners object, and now that it is it is choking on it, namely:

JsonMappingException: Can not deserialize instance of java.lang.String out of
  START_OBJECT token at [char position where you can find "userID" and "paidID"]
  through reference chain [path to my Jackson bean which contains the owners class]

My Jackson bean has a wrapper, which is what that "exampleList" is all about:

public class Examples extends HashMap<String, ArrayList<Example>> {

}

And then the actual Example class:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Example implements Comparable<Example> {

@ObjectId @Id
private String id;

@JsonProperty(Constants.Example.location)
private String location;

@JsonProperty(Constants.Example.OWNERS)
private List<Owners> owners;

public int compareTo(Example _o) {
    return getId().compareTo(_o.getId());
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}
public List<Example.Owners> getOwners() {
    return owners;
}

public void setOwners(List<Example.Owners> owners) {
    this.owners = owners;
}

public Example() {
}

@JsonCreator
public Example(@Id @ObjectId String id) {
    this.id = id;
}

@JsonIgnoreProperties(ignoreUnknown = true)
public static class Owners implements Comparable<Owners> {

    @JsonProperty(Constants.Example.USERID)
    private String userID;

    @JsonProperty(Constants.Example.PAIDID)
    private String paidID;

    public Owners() {
    }

    public int compareTo(Owners _o) {
        return getUserID().compareTo(_o.getUserID());
    }

    @ObjectId
    public String getUserID() {
        return userID;
    }

    @ObjectId
    public void setUserID(String userID) {
        this.userID = userID;
    }

    @ObjectId
    public String getPaidID() {
        return paidID;
    }

    @ObjectId
    public void setPaidID(String paidID) {
        this.paidID = paidID;
    }

}

}

And finally, the code in the ResponseHandler where this is all failing (the 2nd line produces the JsonMappingException):

objectMapper = MongoJacksonMapperModule.configure(objectMapper);
mExamples = objectMapper.readValue(jsonParser, Examples.class);

I have a feeling the issue is that Jackson still doesn't know how to map those $oid, which are the mongoDB ObjectIds. The MongoJacksonMapper library is supposed to help that by providing the @ObjectId annotation and a way to configure the ObjectMapper to use that library, but it still isn't working. For some reason, it's still looking for the userID or paidID as a String, not an ObjectId. Any ideas?

Body:
Jackson does not know how to serialize an ObjectId. I tweaked Arny's code to serialize any ObjectId and provide this working example:

public class SerialiserTest {

 private ObjectMapper mapper = new ObjectMapper();

 public static class T {
    private ObjectId objectId;

    public ObjectId getObjectId() {
        return objectId;
    }

    public void setObjectId(ObjectId objectId) {
        this.objectId = objectId;
    }
 }

 @Test
 public final void serDeser() throws IOException {
    T t = new T();
    t.setObjectId(new ObjectId());
    List<T> ls = Collections.singletonList(t);
    String json = mapper.writeValueAsString(ls);
    System.out.println(json);
    SimpleModule mod = new SimpleModule("ObjectId", new Version(1, 0, 0, null, null, null));
    mod.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
    mapper.registerModule(mod);
    JavaType type = mapper.getTypeFactory().
            constructCollectionType(List.class, T.class);
    List<?> l  = mapper.readValue(json, type);
    System.out.println(l);
 }
}

public class ObjectIdDeserializer extends JsonDeserializer<ObjectId> {

 @Override
 public ObjectId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonNode n = (JsonNode)p.readValueAsTree();
    return new ObjectId(n.get("timestamp").asInt(), n.get("machineIdentifier").asInt(), (short) n.get("processIdentifier").asInt(), n.get("counter").asInt());
 }

}


问:
PHP connection to remote mysql with ssl works via command but not in browser
I want to connect to a remote (AWS) mysql server using ssl in PHP.

My script works when I execute it via command line, but doesn't when I call it from the browser.

```<code>$con=mysqli_init();
mysqli_ssl_set($con,NULL,NULL,"path/to/cacert.pem",NULL,NULL);
$link = mysqli_real_connect($con, "host", "username", "password");
</code>```

I am using php7/Apache/CentOs. I tried changing the ownership and permissions of the CA file, and noticed that it requires read permission the be executed on console. But in browser even if I give full permission to everybody (chmod 777) it still doesn't work.

The error i get is:
Warning: failed loading cafile stream.
When I check existence of file it returns true, but when I check is_readible, then also error.

Can somebody help?Thanks!

答:
So as I figured there was (is) something wrong with readability and maybe permissions. I could narrow down the problem to the certificate file being existent but not readable. I moved it to my server with filezilla via ftp.

I could solve my problem by creating a new .pem file and simply copying the content of my original file into it. This one is readable now and works in browser, but I can't figure out why as they both have the same chmod xxx permissions and chown ownership.

Detailed description(for users with similar problem using AWS MYSQL):

open rds-combined-ca-bundle.pem file(download link: https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem) in text editor.

Copy content.

On your server, where php script should run create new file and paste text into it.(it might require some additional editing, begin/end tags in separate line and new lines end at the same place as in original text)

Body:
I want to connect to a remote (AWS) mysql server using ssl in PHP.

My script works when I execute it via command line, but doesn't when I call it from the browser.

$con=mysqli_init();
mysqli_ssl_set($con,NULL,NULL,"path/to/cacert.pem",NULL,NULL);
$link = mysqli_real_connect($con, "host", "username", "password");

I am using php7/Apache/CentOs. I tried changing the ownership and permissions of the CA file, and noticed that it requires read permission the be executed on console. But in browser even if I give full permission to everybody (chmod 777) it still doesn't work.

The error i get is:
Warning: failed loading cafile stream.
When I check existence of file it returns true, but when I check is_readible, then also error.

Can somebody help?Thanks!


答: You need to be referencing the items in the array. So it should not just simply be i, that is just a number. It should be data[i]. This will refer to the ith element of the array data.</p>

Title: Max, Min, Avg function for an array in C++


问:
I need to get an old version of ember running with ember cli
Hi all I have an application I build for a client a while back.
please see the the application ember version data below.

```<code>Ember Inspector
1.10.0
Ember
1.13.7
Ember Data
1.13.8
jQuery
2.1.4
Ember Simple Auth
0.8.0
</code>```

I now need to make a change, but I am having issues running ember cli. Any idea what version of npm, node and ember cli i should use.

答:
You can uninstall the existing ember-cli and install specific version you required. in your case you can try 1.13.7</p>

```<code>npm uninstall -g ember-cli -- Remove old global ember-cli
npm cache clean -- Clear NPM cache
npm install -g ember-cli@1.13.7 -- Install new global ember-cli
</code>```

Body:
Hi all I have an application I build for a client a while back.
please see the the application ember version data below.

Ember Inspector
1.10.0
Ember
1.13.7
Ember Data
1.13.8
jQuery
2.1.4
Ember Simple Auth
0.8.0

I now need to make a change, but I am having issues running ember cli. Any idea what version of npm, node and ember cli i should use.

Body:
You can uninstall the existing ember-cli and install specific version you required. in your case you can try 1.13.7

npm uninstall -g ember-cli -- Remove old global ember-cli
npm cache clean -- Clear NPM cache
npm install -g ember-cli@1.13.7 -- Install new global ember-cli


问:
OneToMany Relations with Lift
I have a question once again and I have the feeling the solution is simple. Should be simple, in any case. I have been trying to model my mappings for my database, with the nice OneToMany trait, like so

```<code>class User extends MegaProtoUser[User] with OneToMany[Long, User] {
  def getSingleton = User

  object posts extends MappedOneToMany(Post, Post.author, OrderBy(Post.edited, Descending))
}

class Post extends LongKeyedMapper[Post] with IdPK with OneToMany[Long, Post] {
  def getSingleton = Post

  object author extends LongMappedMapper(this, User)

  object title extends MappedString(this, 100) {
    override def dbIndexed_? = true

    override def defaultValue = "New Post"
  }

  object contents extends MappedText(this)

  object edited extends MappedDate(this)
}
</code>```

All nice an done, I have my One-to-many relationship all right. But, what troubles me a real lot, how do I actually get the data in that relationship? Just supposing I've got a Post object and want to get the author's name to it?

```<code>bind("post", in, "title" -> post.title, "author" -> /* insert overly complicated method here */)
</code>```

I've learned I can get it over a Box, by post.author.obj or something. It does not quite work out, I have to do a match over it and such?

I feel the answer is simple, but yet I fail to see it.

ContentLicense: CC BY-SA 2.5

Title: OneToMany Relations with Lift

Body:
I have a question once again and I have the feeling the solution is simple. Should be simple, in any case. I have been trying to model my mappings for my database, with the nice OneToMany trait, like so

class User extends MegaProtoUser[User] with OneToMany[Long, User] {
  def getSingleton = User

  object posts extends MappedOneToMany(Post, Post.author, OrderBy(Post.edited, Descending))
}

class Post extends LongKeyedMapper[Post] with IdPK with OneToMany[Long, Post] {
  def getSingleton = Post

  object author extends LongMappedMapper(this, User)

  object title extends MappedString(this, 100) {
    override def dbIndexed_? = true

    override def defaultValue = "New Post"
  }

  object contents extends MappedText(this)

  object edited extends MappedDate(this)
}

All nice an done, I have my One-to-many relationship all right. But, what troubles me a real lot, how do I actually get the data in that relationship? Just supposing I've got a Post object and want to get the author's name to it?

bind("post", in, "title" -> post.title, "author" -> /* insert overly complicated method here */)

I've learned I can get it over a Box, by post.author.obj or something. It does not quite work out, I have to do a match over it and such?

I feel the answer is simple, but yet I fail to see it.

Body: post.author.obj.map(_.userNameOrSomething).openOr("Unknown writer")


答:
Just provide variables that can be passed to that function, and output these like follows:

```<code>int main ()
{
    double data[]={10.0,0.0,20.0,30.0};
    double min, max, avg;

    normalizeMinMaxAvg (data, 4, min, max, avg);
    cout << "min = " << min << "\n";
    cout << "max = " << max << "\n";
    cout << "avg = " << avg << "\n";
    return 0;
}
</code>```

Also inside your function use the data from the array to calculate min and max:

```<code>    if ( data[i] > max)
    {
        max = data[i];
    }

    else if (data[i] < min)
    {
        min = data[i];
    }
</code>```

Body:
Just provide variables that can be passed to that function, and output these like follows:

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};
    double min, max, avg;

    normalizeMinMaxAvg (data, 4, min, max, avg);
    cout << "min = " << min << "\n";
    cout << "max = " << max << "\n";
    cout << "avg = " << avg << "\n";
    return 0;
}

Also inside your function use the data from the array to calculate min and max:

    if ( data[i] > max)
    {
        max = data[i];
    }

    else if (data[i] < min)
    {
        min = data[i];
    }


问:
Dropdown navigation submenu renders behind other elements
The submenus in my navigation bar are rendering behind the main content. More specifically, I have a navigation component which is right above another component containing an h1 element. The submenus in the navigation bar are visibly behind the h1 element in the main body component (because there is no background). It is also being hidden by the footer.

In the main app component, the template looks like this:

```<code><nova-header></nova-header>
<nova-navigation [categories]="categories"></nova-navigation>
<router-outlet></router-outlet>
<nova-footer [categories]="categories"></nova-footer>
</code>```

What's strange is that I copy-pasted my code into JSFiddle, which you can see where I've separated the nova-navigation template HTML and the main body component HTML in the fiddle, however the problem is gone and the submenus render correctly. I'm new to Angular, so I assume I'm missing something with how Angular works.

Here's a link to said JSFiddle: https://jsfiddle.net/jonnylin13/nwxyd8j8/

I've tried z-index and overflow already

EDIT ** the problem must be with my local environment as I created a plnkr and the problem is not there. http://plnkr.co/edit/Pzzt6C4C9OrAvil50yqT?p=preview

答:
I haven't used Angular much, but I had similar issues with React: the framework adds elements into the DOM for handling the content (like wrapping animations and such). These elements interfere with the CSS positioning.

When you inspect the code in your browser, do you notice any extra  or
 wrapping your elements?

If so, you may need to define extra CSS rules with a selector like .content > span to set their position, because z-index only works on positioned elements.

Body:
The submenus in my navigation bar are rendering behind the main content. More specifically, I have a navigation component which is right above another component containing an h1 element. The submenus in the navigation bar are visibly behind the h1 element in the main body component (because there is no background). It is also being hidden by the footer.

In the main app component, the template looks like this:

<nova-header></nova-header>
<nova-navigation [categories]="categories"></nova-navigation>
<router-outlet></router-outlet>
<nova-footer [categories]="categories"></nova-footer>

What's strange is that I copy-pasted my code into JSFiddle, which you can see where I've separated the nova-navigation template HTML and the main body component HTML in the fiddle, however the problem is gone and the submenus render correctly. I'm new to Angular, so I assume I'm missing something with how Angular works.

Here's a link to said JSFiddle: https://jsfiddle.net/jonnylin13/nwxyd8j8/

I've tried z-index and overflow already

EDIT ** the problem must be with my local environment as I created a plnkr and the problem is not there. http://plnkr.co/edit/Pzzt6C4C9OrAvil50yqT?p=preview

Body:
I haven't used Angular much, but I had similar issues with React: the framework adds elements into the DOM for handling the content (like wrapping animations and such). These elements interfere with the CSS positioning.

When you inspect the code in your browser, do you notice any extra <span> or <div> wrapping your elements?

If so, you may need to define extra CSS rules with a selector like .content > span to set their position, because z-index only works on positioned elements.


问:
How to visualize an sklearn GradientBoostingClassifier?
I've trained a gradient boost classifier, and I would like to visualize it using the graphviz_exporter tool shown here.

When I try it I get:

```<code>AttributeError: 'GradientBoostingClassifier' object has no attribute 'tree_'
</code>```

this is because the graphviz_exporter is meant for decision trees, but I guess there's still a way to visualize it, since the gradient boost classifier must have an underlying decision tree.

How to do that?

答:
The attribute estimators contains the underlying decision trees. The following code displays one of the trees of a trained GradientBoostingClassifier. Notice that although the ensemble is a classifier as a whole, each individual tree computes floating point values.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.tree import export_graphviz
import numpy as np

# Ficticuous data
np.random.seed(0)
X = np.random.normal(0,1,(1000, 3))
y = X[:,0]+X[:,1]*X[:,2] > 0

# Classifier
clf = GradientBoostingClassifier(max_depth=3, random_state=0)
clf.fit(X[:600], y[:600])

# Get the tree number 42
sub_tree_42 = clf.estimators_[42, 0]

# Visualization
# Install graphviz: https://www.graphviz.org/download/
from pydotplus import graph_from_dot_data
from IPython.display import Image
dot_data = export_graphviz(
    sub_tree_42,
    out_file=None, filled=True, rounded=True,
    special_characters=True,
    proportion=False, impurity=False, # enable them if you want
)
graph = graph_from_dot_data(dot_data)
png = graph.create_png()
# Save (optional)
from pathlib import Path
Path('./out.png').write_bytes(png)
# Display
Image(png)
```

Tree number 42:

ContentLicense: CC BY-SA 4.0

Body:
I've trained a gradient boost classifier, and I would like to visualize it using the graphviz_exporter tool shown here.

When I try it I get:

AttributeError: 'GradientBoostingClassifier' object has no attribute 'tree_'

this is because the graphviz_exporter is meant for decision trees, but I guess there's still a way to visualize it, since the gradient boost classifier must have an underlying decision tree.

How to do that?

Body:
The attribute estimators contains the underlying decision trees. The following code displays one of the trees of a trained GradientBoostingClassifier. Notice that although the ensemble is a classifier as a whole, each individual tree computes floating point values.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.tree import export_graphviz
import numpy as np

# Ficticuous data
np.random.seed(0)
X = np.random.normal(0,1,(1000, 3))
y = X[:,0]+X[:,1]*X[:,2] > 0

# Classifier
clf = GradientBoostingClassifier(max_depth=3, random_state=0)
clf.fit(X[:600], y[:600])

# Get the tree number 42
sub_tree_42 = clf.estimators_[42, 0]

# Visualization
# Install graphviz: https://www.graphviz.org/download/
from pydotplus import graph_from_dot_data
from IPython.display import Image
dot_data = export_graphviz(
    sub_tree_42,
    out_file=None, filled=True, rounded=True,
    special_characters=True,
    proportion=False, impurity=False, # enable them if you want
)
graph = graph_from_dot_data(dot_data)
png = graph.create_png()
# Save (optional)
from pathlib import Path
Path('./out.png').write_bytes(png)
# Display
Image(png)

Tree number 42:


答:
Your problem is that you're not accessing your array's data. Instead you're using your iteration variable i. Basically, on your normalizeMinMaxAvg function, you should do this on your for loop:

```<code>for (i=0; i < size; i++){
    //count++;  - no need for it, you already have size!
    sum += data[i];
    if ( max > data[i]){
        max = data[i];
    }
    if (min < data[i]){
        min = data[i];
    }
}
avg = sum/size;
</code>```

Also you need to declare your variables min, max and avg on your main() function in order to use them when you call your normalizeMinMaxAvg function.

Body:
Your problem is that you're not accessing your array's data. Instead you're using your iteration variable i. Basically, on your normalizeMinMaxAvg function, you should do this on your for loop:

for (i=0; i < size; i++){
    //count++;  - no need for it, you already have size!
    sum += data[i];
    if ( max > data[i]){
        max = data[i];
    }
    if (min < data[i]){
        min = data[i];
    }
}
avg = sum/size;

Also you need to declare your variables min, max and avg on your main() function in order to use them when you call your normalizeMinMaxAvg function.


问:
Curve fitting without toolbox
Without the curve fit toolbox how do you fit a function to data in MATLAB?

In particular, how do you fit a function that isn't a polynomial, e.g., if I want to fit a function like y = x^(1/3) + 5 where it is not an integer?

答:
There are two ways to implementing Curve Fitting Without ToolBox, They are

In the Case of  uniformly spaced samples and then want to impmlement the curve fit using some linear combination of shifted kernels (e.g. B-splines), then the following tool will help you:

http://www.mathworks.com/matlabcentral/fileexchange/26292-regular-control-point-interpolation-matrix-with-boundary-conditions

2.USe polyfit,for creating your own fitting toolbox from scratch... with the help of this, you can fit a function to data in MATLAB,

doc polyfit.

eg,

```<code> help polyfit;
 help slash;
</code>```

% ...

For More Information on polyfit Refer this http://www.mathworks.com/help/techdoc/ref/polyfit.html

Title: Curve fitting without toolbox

Body:
There are two ways to implementing Curve Fitting Without ToolBox, They are

In the Case of  uniformly spaced samples and then want to impmlement the curve fit using some linear combination of shifted kernels (e.g. B-splines), then the following tool will help you:

http://www.mathworks.com/matlabcentral/fileexchange/26292-regular-control-point-interpolation-matrix-with-boundary-conditions

2.USe polyfit,for creating your own fitting toolbox from scratch... with the help of this, you can fit a function to data in MATLAB,

doc polyfit.

eg,

 help polyfit;
 help slash;

% ...

For More Information on polyfit Refer this http://www.mathworks.com/help/techdoc/ref/polyfit.html


问:
Print Button In Excel 2016 Using Macros?
I'm currently trying to create a Print Button on one of my worksheets.  I need it to print that worksheet as well as another one.  Both of the names are "Budget Sheet" and "Listed Commitments Sheet" without the quotation marks.

I created the button without hassle, but I know very little about Macros so I still need the code.  I've tried multiple solutions, but nothing seems to work.  I've recently tried to use this Code, but it hasn't worked.  What am I doing wrong?  What code could I possibly use instead?

```<code>Private Sub CommandButton1_Click()

Function PrintMultipleSheets()
    Sheets(Array("Budget Sheet", "Listed Commitments Sheet")).PrintOut
End Function

End Sub
</code>```

答:
It comes up with an error that says "Compile Error: Expected End Sub".

The code doesn't compile, because you can't have a Function inside a Sub.

Get ride of the line Function PrintMultipleSheets() and get rid of End Function. It should work I think. You'll end up with:

```<code>Private Sub CommandButton1_Click()

Sheets(Array("Budget Sheet", "Listed Commitments Sheet")).PrintOut

End Sub
</code>```

Body:
I'm currently trying to create a Print Button on one of my worksheets.  I need it to print that worksheet as well as another one.  Both of the names are "Budget Sheet" and "Listed Commitments Sheet" without the quotation marks.

I created the button without hassle, but I know very little about Macros so I still need the code.  I've tried multiple solutions, but nothing seems to work.  I've recently tried to use this Code, but it hasn't worked.  What am I doing wrong?  What code could I possibly use instead?

Private Sub CommandButton1_Click()

Function PrintMultipleSheets()
    Sheets(Array("Budget Sheet", "Listed Commitments Sheet")).PrintOut
End Function

End Sub

Body:
It comes up with an error that says "Compile Error: Expected End Sub".

The code doesn't compile, because you can't have a Function inside a Sub.

Get ride of the line Function PrintMultipleSheets() and get rid of End Function. It should work I think. You'll end up with:

Private Sub CommandButton1_Click()

Sheets(Array("Budget Sheet", "Listed Commitments Sheet")).PrintOut

End Sub


问:
How to create an instance of class and implement it in a subclass?
How would I create an instance of a class to use as an attribute in another class? I believe this is what I need to do:

```<code>ClassA a1 = new ClassA(); // ClassA is the super class
</code>```

This is where I get stuck, if my above code is even correct. How do I actually use this in a subclass of ClassA, say ClassB? So if ClassA has 'name' and 'age' and ClassB has 'tenant' what do I need to do in order to give tenant a name and age?

答: well Class B inherits from Class A. so in your constructor for Class B you have call the constructor of the super class using Super() then when you want to uuse attributes from the super class in the sub class you would just use super, so super.getAttribute() for example</p>

Body:
How would I create an instance of a class to use as an attribute in another class? I believe this is what I need to do:

ClassA a1 = new ClassA(); // ClassA is the super class

This is where I get stuck, if my above code is even correct. How do I actually use this in a subclass of ClassA, say ClassB? So if ClassA has 'name' and 'age' and ClassB has 'tenant' what do I need to do in order to give tenant a name and age?


问:
STM32F407 and ARDUINO UART Communication
I have been trying to communicate the STM32F407 Discovery and Arduino Mega with UART.I have a MAX232 module.STM32F4's PD8 and PD9 pins are connected to the MAX232 Module.Output of the modul is connected to the Arduino's Rx-Tx pins.All connections are double-checked.
And I transmitted a character "A" from STM to Arduino.In ASCII table,decimal value of the A is 65 in ASCII table.However,the Arduino's Serial Port read 95 in decimal.

I need a solution or idea about that Wrong Received/Transmitted values ?

Thanks,

```<code>/*  STM32F4 CODE */
#include "stm32f4xx_hal.h"
#include <stdio.h>

ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;
ADC_HandleTypeDef hadc3;

UART_HandleTypeDef huart3;

void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_ADC1_Init(void);
static void MX_ADC2_Init(void);
static void MX_ADC3_Init(void);

int main(void)
{
  HAL_Init();

  SystemClock_Config();

  MX_GPIO_Init();
  MX_USART3_UART_Init();
  MX_ADC1_Init();
  MX_ADC2_Init();
  MX_ADC3_Init();

  __HAL_UART_ENABLE_IT(&huart3,UART_IT_TC);

  char *buffer[10] = "00000000";

  while (1)
  {
        HAL_UART_Transmit_IT(&huart3,(uint8_t *)buffer,8);
        HAL_Delay(1000);
  }
}
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                          |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
  Error_Handler();
  }
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* ADC1 init function */
static void MX_ADC1_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc1.Instance = ADC1;
  hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc1.Init.Resolution = ADC_RESOLUTION_10B;
  hadc1.Init.ScanConvMode = DISABLE;
  hadc1.Init.ContinuousConvMode = ENABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  hadc1.Init.DMAContinuousRequests = DISABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
   }
  sConfig.Channel = ADC_CHANNEL_1;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_144CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* ADC2 init function */
static void MX_ADC2_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc2.Instance = ADC2;
  hadc2.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc2.Init.Resolution = ADC_RESOLUTION_8B;
  hadc2.Init.ScanConvMode = DISABLE;
  hadc2.Init.ContinuousConvMode = DISABLE;
  hadc2.Init.DiscontinuousConvMode = DISABLE;
  hadc2.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc2.Init.NbrOfConversion = 1;
  hadc2.Init.DMAContinuousRequests = DISABLE;
  hadc2.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc2) != HAL_OK)
   {
  Error_Handler();
  }
  sConfig.Channel = ADC_CHANNEL_11;
  sConfig.Rank = 1;
 sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* ADC3 init function */
static void MX_ADC3_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc3.Instance = ADC3;
  hadc3.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc3.Init.Resolution = ADC_RESOLUTION_12B;
  hadc3.Init.ScanConvMode = DISABLE;
  hadc3.Init.ContinuousConvMode = DISABLE;
  hadc3.Init.DiscontinuousConvMode = DISABLE;
  hadc3.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc3.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc3.Init.NbrOfConversion = 1;
  hadc3.Init.DMAContinuousRequests = DISABLE;
  hadc3.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc3) != HAL_OK)
  {
    Error_Handler();
  }
  sConfig.Channel = ADC_CHANNEL_12;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* USART3 init function */
static void MX_USART3_UART_Init(void)
{
  huart3.Instance = USART3;
  huart3.Init.BaudRate = 9600;
  huart3.Init.WordLength = UART_WORDLENGTH_8B;
  huart3.Init.StopBits = UART_STOPBITS_1;
  huart3.Init.Parity = UART_PARITY_NONE;
  huart3.Init.Mode = UART_MODE_TX_RX;
  huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart3.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart3) != HAL_OK)
  {
    Error_Handler();
  }
}
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct;
  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOE_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOE, Q1_Pin|Q2_Pin|Q3_Pin|Q4_Pin
                          |A_Pin|B_Pin|C_Pin|D_Pin
                          |E_Pin|F_Pin|G_Pin|DP_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(POWER_LED_GPIO_Port, POWER_LED_Pin, GPIO_PIN_SET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOD, IN1_Pin|IN2_Pin|IN3_Pin|IN4_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, Relay_Pin|BUZZER_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pins : Q1_Pin Q2_Pin Q3_Pin Q4_Pin
                           A_Pin B_Pin C_Pin D_Pin
                           E_Pin F_Pin G_Pin DP_Pin */
  GPIO_InitStruct.Pin = Q1_Pin|Q2_Pin|Q3_Pin|Q4_Pin
                          |A_Pin|B_Pin|C_Pin|D_Pin
                          |E_Pin|F_Pin|G_Pin|DP_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
  /*Configure GPIO pin : POWER_LED_Pin */
  GPIO_InitStruct.Pin = POWER_LED_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(POWER_LED_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : B3_Pin B4_Pin */
  GPIO_InitStruct.Pin = B3_Pin|B4_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
  /*Configure GPIO pin : B0_Pin */
  GPIO_InitStruct.Pin = B0_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(B0_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : IN1_Pin IN2_Pin IN3_Pin IN4_Pin */
  GPIO_InitStruct.Pin = IN1_Pin|IN2_Pin|IN3_Pin|IN4_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
  /*Configure GPIO pins : B1_Pin B2_Pin */
  GPIO_InitStruct.Pin = B1_Pin|B2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
  /*Configure GPIO pin : Digital_Temp_Pin */
  GPIO_InitStruct.Pin = Digital_Temp_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(Digital_Temp_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : Relay_Pin BUZZER_Pin */
  GPIO_InitStruct.Pin = Relay_Pin|BUZZER_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
void Error_Handler(void)
{
  while(1)
  {
  }
}
#ifdef USE_FULL_ASSERT
void assert_failed(uint8_t* file, uint32_t line)
{
}
#endif
</code>```

$

答: The easiest way to catch communication bugs is to use a logic analyser, then you will be sure on which side the problem is.</p>

Body:
I have been trying to communicate the STM32F407 Discovery and Arduino Mega with UART.I have a MAX232 module.STM32F4's PD8 and PD9 pins are connected to the MAX232 Module.Output of the modul is connected to the Arduino's Rx-Tx pins.All connections are double-checked.
And I transmitted a character "A" from STM to Arduino.In ASCII table,decimal value of the A is 65 in ASCII table.However,the Arduino's Serial Port read 95 in decimal.

I need a solution or idea about that Wrong Received/Transmitted values ?

Thanks,

/*  STM32F4 CODE */
#include "stm32f4xx_hal.h"
#include <stdio.h>

ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;
ADC_HandleTypeDef hadc3;

UART_HandleTypeDef huart3;

void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_USART3_UART_Init(void);
static void MX_ADC1_Init(void);
static void MX_ADC2_Init(void);
static void MX_ADC3_Init(void);

int main(void)
{
  HAL_Init();

  SystemClock_Config();

  MX_GPIO_Init();
  MX_USART3_UART_Init();
  MX_ADC1_Init();
  MX_ADC2_Init();
  MX_ADC3_Init();

  __HAL_UART_ENABLE_IT(&huart3,UART_IT_TC);

  char *buffer[10] = "00000000";

  while (1)
  {
        HAL_UART_Transmit_IT(&huart3,(uint8_t *)buffer,8);
        HAL_Delay(1000);
  }
}
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                          |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
  Error_Handler();
  }
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* ADC1 init function */
static void MX_ADC1_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc1.Instance = ADC1;
  hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc1.Init.Resolution = ADC_RESOLUTION_10B;
  hadc1.Init.ScanConvMode = DISABLE;
  hadc1.Init.ContinuousConvMode = ENABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  hadc1.Init.DMAContinuousRequests = DISABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
   }
  sConfig.Channel = ADC_CHANNEL_1;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_144CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* ADC2 init function */
static void MX_ADC2_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc2.Instance = ADC2;
  hadc2.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc2.Init.Resolution = ADC_RESOLUTION_8B;
  hadc2.Init.ScanConvMode = DISABLE;
  hadc2.Init.ContinuousConvMode = DISABLE;
  hadc2.Init.DiscontinuousConvMode = DISABLE;
  hadc2.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc2.Init.NbrOfConversion = 1;
  hadc2.Init.DMAContinuousRequests = DISABLE;
  hadc2.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc2) != HAL_OK)
   {
  Error_Handler();
  }
  sConfig.Channel = ADC_CHANNEL_11;
  sConfig.Rank = 1;
 sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* ADC3 init function */
static void MX_ADC3_Init(void)
{
  ADC_ChannelConfTypeDef sConfig;
  hadc3.Instance = ADC3;
  hadc3.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc3.Init.Resolution = ADC_RESOLUTION_12B;
  hadc3.Init.ScanConvMode = DISABLE;
  hadc3.Init.ContinuousConvMode = DISABLE;
  hadc3.Init.DiscontinuousConvMode = DISABLE;
  hadc3.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc3.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc3.Init.NbrOfConversion = 1;
  hadc3.Init.DMAContinuousRequests = DISABLE;
  hadc3.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc3) != HAL_OK)
  {
    Error_Handler();
  }
  sConfig.Channel = ADC_CHANNEL_12;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/* USART3 init function */
static void MX_USART3_UART_Init(void)
{
  huart3.Instance = USART3;
  huart3.Init.BaudRate = 9600;
  huart3.Init.WordLength = UART_WORDLENGTH_8B;
  huart3.Init.StopBits = UART_STOPBITS_1;
  huart3.Init.Parity = UART_PARITY_NONE;
  huart3.Init.Mode = UART_MODE_TX_RX;
  huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart3.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart3) != HAL_OK)
  {
    Error_Handler();
  }
}
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct;
  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOE_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOE, Q1_Pin|Q2_Pin|Q3_Pin|Q4_Pin
                          |A_Pin|B_Pin|C_Pin|D_Pin
                          |E_Pin|F_Pin|G_Pin|DP_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(POWER_LED_GPIO_Port, POWER_LED_Pin, GPIO_PIN_SET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOD, IN1_Pin|IN2_Pin|IN3_Pin|IN4_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, Relay_Pin|BUZZER_Pin, GPIO_PIN_RESET);
  /*Configure GPIO pins : Q1_Pin Q2_Pin Q3_Pin Q4_Pin
                           A_Pin B_Pin C_Pin D_Pin
                           E_Pin F_Pin G_Pin DP_Pin */
  GPIO_InitStruct.Pin = Q1_Pin|Q2_Pin|Q3_Pin|Q4_Pin
                          |A_Pin|B_Pin|C_Pin|D_Pin
                          |E_Pin|F_Pin|G_Pin|DP_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
  /*Configure GPIO pin : POWER_LED_Pin */
  GPIO_InitStruct.Pin = POWER_LED_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(POWER_LED_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : B3_Pin B4_Pin */
  GPIO_InitStruct.Pin = B3_Pin|B4_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
  /*Configure GPIO pin : B0_Pin */
  GPIO_InitStruct.Pin = B0_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(B0_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : IN1_Pin IN2_Pin IN3_Pin IN4_Pin */
  GPIO_InitStruct.Pin = IN1_Pin|IN2_Pin|IN3_Pin|IN4_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
  /*Configure GPIO pins : B1_Pin B2_Pin */
  GPIO_InitStruct.Pin = B1_Pin|B2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
  /*Configure GPIO pin : Digital_Temp_Pin */
  GPIO_InitStruct.Pin = Digital_Temp_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(Digital_Temp_GPIO_Port, &GPIO_InitStruct);
  /*Configure GPIO pins : Relay_Pin BUZZER_Pin */
  GPIO_InitStruct.Pin = Relay_Pin|BUZZER_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
void Error_Handler(void)
{
  while(1)
  {
  }
}
#ifdef USE_FULL_ASSERT
void assert_failed(uint8_t* file, uint32_t line)
{
}
#endif

$


问:
What improvements can I make to my ordering a set of n numbers program?
I am just learning how to program in javascript and I made my first program that "does something". I didn't look for help for any part of the algorithm, just in some parts to find the name of a function I wanted to use. This algorithm seems to work, but it doesnt seem to finish when you have a big list of number, like 10 or more. What yo do you think of it? Is wholly ineficient?</p>

```<code>var totNum = Number(prompt("How many numbers you want to compare"));
var unordNum = new Array(totNum);
var ordNum = new Array();
for( var i=1 ; i<= totNum; i++){
    unordNum[i] = Number(prompt("Write a new number","0"));
 }
while(ordNum.length < totNum){ // I will repeat this process until I order all numbers
    for(var i=1; i <=totNum; i++){ //choose a number, lets call it X
        if(!(ordNum.indexOf(unordNum[i]) >=0)){ //if it is already ordered, skip it
            var z = 0;
            for(var j=1; j<=totNum; j++){ //I will compare X against all the others numbers, except
                if(!(ordNum.indexOf(unordNum[j]) >= 0)){ //the ones that are already ordered
                    if( unordNum[i] >= unordNum[j]){ //if X is bigger than a number,
                        z++; // add 1 to z
                        }
                    if(z==totNum-ordNum.length){ // this means X is bigger or equal than all the other numbers
                        ordNum.push(unordNum[i]); //so write X in the first empty space of the ordered list
                        }
                    }
                }
            }
        }
    }
document.write(ordNum + "<br>");
</code>```

答:
You make use of ordNum.indexOf(unordNum[j]) to find if a number is already sorted. This would lead to an infinite loop in case of duplicates. Secondly, you are not really sorting, you would push a number for the first comparison success.
Below is a somewhat similar logic for your sorting.

```<code>var totNum = Number(prompt("How many numbers you want to compare"));
var unordNum = new Array(totNum);
var ordNum = new Array();
for( var i=0 ; i< totNum; i++){
    unordNum[i] = Number(prompt("Write a new number","0"));
 }

    for(var i=0; i <totNum; i++){
        if(unordNum[i] == undefined) continue; //jump to the next unsorted number
        var smallest = unordNum[i];  //initialize smallest to be the first unsorted number
        var index = i;               //initialize marker index to be set as undefined at last for the number being moved to the sorted array
        for(var j=0; j<totNum; j++){ //Comparison loop to find the smallest
            if(unordNum[j] != undefined){
                smallest  = unordNum[j]<smallest ? unordNum[j] : smallest; //Swap if j th number is smaller
                index = smallest == unordNum[j] ? j : index; // update index if swapping done
            }
        }
        unordNum[index] = undefined;//mark the number moved
        ordNum.push(smallest);      // add smallest number to sorted array
        i=0;                        //set outer loop to start from 0 again
    }

document.write(ordNum + "<br>");
</code>```

This would sort by copying the smallest number in the remaining array into a new array. Instead of using ordNum.indexOf(unordNum[j]) as you did, I am marking the sorted element as undefined. Duplicates cannot be sorted in your case. This would leave the new sorted array smaller than the input array and hence an infinite loop. Another thing, why do you use 1 as the starting index? The default index starts from 0 in Javascript as well.

There are far better sorting algorithms but perhaps that is not what you are looking for.

Body:
I am just learning how to program in javascript and I made my first program that "does something". I didn't look for help for any part of the algorithm, just in some parts to find the name of a function I wanted to use. This algorithm seems to work, but it doesnt seem to finish when you have a big list of number, like 10 or more. What yo do you think of it? Is wholly ineficient?

var totNum = Number(prompt("How many numbers you want to compare"));
var unordNum = new Array(totNum);
var ordNum = new Array();
for( var i=1 ; i<= totNum; i++){
    unordNum[i] = Number(prompt("Write a new number","0"));
 }
while(ordNum.length < totNum){ // I will repeat this process until I order all numbers
    for(var i=1; i <=totNum; i++){ //choose a number, lets call it X
        if(!(ordNum.indexOf(unordNum[i]) >=0)){ //if it is already ordered, skip it
            var z = 0;
            for(var j=1; j<=totNum; j++){ //I will compare X against all the others numbers, except
                if(!(ordNum.indexOf(unordNum[j]) >= 0)){ //the ones that are already ordered
                    if( unordNum[i] >= unordNum[j]){ //if X is bigger than a number,
                        z++; // add 1 to z
                        }
                    if(z==totNum-ordNum.length){ // this means X is bigger or equal than all the other numbers
                        ordNum.push(unordNum[i]); //so write X in the first empty space of the ordered list
                        }
                    }
                }
            }
        }
    }
document.write(ordNum + "
");

Body:
You make use of ordNum.indexOf(unordNum[j]) to find if a number is already sorted. This would lead to an infinite loop in case of duplicates. Secondly, you are not really sorting, you would push a number for the first comparison success.
Below is a somewhat similar logic for your sorting.

var totNum = Number(prompt("How many numbers you want to compare"));
var unordNum = new Array(totNum);
var ordNum = new Array();
for( var i=0 ; i< totNum; i++){
    unordNum[i] = Number(prompt("Write a new number","0"));
 }

    for(var i=0; i <totNum; i++){
        if(unordNum[i] == undefined) continue; //jump to the next unsorted number
        var smallest = unordNum[i];  //initialize smallest to be the first unsorted number
        var index = i;               //initialize marker index to be set as undefined at last for the number being moved to the sorted array
        for(var j=0; j<totNum; j++){ //Comparison loop to find the smallest
            if(unordNum[j] != undefined){
                smallest  = unordNum[j]<smallest ? unordNum[j] : smallest; //Swap if j th number is smaller
                index = smallest == unordNum[j] ? j : index; // update index if swapping done
            }
        }
        unordNum[index] = undefined;//mark the number moved
        ordNum.push(smallest);      // add smallest number to sorted array
        i=0;                        //set outer loop to start from 0 again
    }

document.write(ordNum + "<br>");

This would sort by copying the smallest number in the remaining array into a new array. Instead of using ordNum.indexOf(unordNum[j]) as you did, I am marking the sorted element as undefined. Duplicates cannot be sorted in your case. This would leave the new sorted array smaller than the input array and hence an infinite loop. Another thing, why do you use 1 as the starting index? The default index starts from 0 in Javascript as well.

There are far better sorting algorithms but perhaps that is not what you are looking for.


问:
Ways to cast objects to a generic type
In relation to Casting generic type "as T" whilst enforcing the type of T

And with the following example

```<code>private static T deserialize<T>(string streng) where T : class
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return ser.Deserialize(reader) as T;
}
</code>```

and

```<code>private static T deserialize<T>(string streng)
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return (T)ser.Deserialize(reader);
}
</code>```

I'm used to doing the object as Type casting, so I was a little confused when I found that I couldn't just do that with T. Then I found the question above and in that a solution to the as T compiler error.

But why is where T : class necessary when using object as T and not when using (T)object?
What is the actual difference between the two ways of casting the object?

答:
Casting with "as" is specified to 1) perform the cast if it can, and 2) return null if it can't.  This is problematic with an unconstrained generic parameter (your second example), because T could possibly be a value type (like int), variables of which cannot hold null.

When your generic parameter is constrained to be a reference type (with the class constraint), the compiler can reason about your type a little more and understand that null will always be a valid value for type T.  Therefore, the "as"-style cast can be safely used.

Title: Ways to cast objects to a generic type

Body:
In relation to Casting generic type "as T" whilst enforcing the type of T

And with the following example

private static T deserialize<T>(string streng) where T : class
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return ser.Deserialize(reader) as T;
}

and

private static T deserialize<T>(string streng)
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return (T)ser.Deserialize(reader);
}

I'm used to doing the object as Type casting, so I was a little confused when I found that I couldn't just do that with T. Then I found the question above and in that a solution to the as T compiler error.

But why is where T : class necessary when using object as T and not when using (T)object?
What is the actual difference between the two ways of casting the object?


问:
Dynamically Create Views from parameters/variables SQL SSIS
I have a table that contains just under a million rows. I'm building a form using SSIS that asks for user input and uses the values as parameters to build a view from source data. I'm having trouble getting SSIS to create the view from a variable.

The purpose of this 'tool' is to provide a dialogue that programmatically builds a view and later an update statement based upon parameters defined via a form that will execute an SSIS package. A number of the ppl on my team know 0 SQL. Therefore this circumvents any SQL knowledge. Creating an entirely standalone app is not ideal as it would require too much additional overhead on my side and would deviate from a number of our existing processes that currently use SSIS/SQL to achieve similar results.

With that here is what I've tried/trying.

I have an SSIS package that contains 'Execute SQL Task'

This task brings up a form with 5 inputs (variables)
var1,var2,var3,var4,var5.
some vars are strings others are doubles, ints etc... (they all vary)

You populate the fields and hit okay.
These variables are passed to an 'Execute Package Task'.
Inside this package (Package B)
the vars are used in an 'Execute SQL Task'.

This task is attempting to take the users input and create a view with a where clause containing 4 other variables.

example:

```<code>Create View ? AS Select col1,col2,col3,col4 WHERE
col1 = ?
AND col2 =?
AND col3 =?.........
</code>```

First it appears that using ? in the create view is invalid.
The error being:

```<code>Error: 0x0 at Build_Query: Incorrect syntax near '@P1'.
Error: 0xC002F210 at Build_Query, Execute SQL Task: Executing the query "CREATE VIEW ? as Select * from S_t_equip_template
..." failed with the following error: "The batch could not be analyzed because of compile errors.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established

 correctly.
Task failed: Build_Query
</code>```

If I use the create view variable as an expression and remove the variables/paramerters for the where statements, I can create the view no problem.
However the where statements throw errors once I add them back in. I've tried evaluating these as an expression in the 'Execute SQL Task' but as these are of various types I get the error:

```<code>[Execute SQL Task] Error: Executing the query "
CREATE VIEW testing AS SELECT
P.label,P.uniq..." failed with the following error: "The metadata could not
be determined because statement 'CREATE VIEW testingagain AS SELECT
P.label,P.uniqueid,C.label as Child_Label,C.uniqueid as Child_uni' does not
support metadata discovery.". Possible failure reasons: Problems with the
query, "ResultSet" property not set correctly, parameters not set correctly,
or connection not established correctly.
</code>```

No idea what is going on. Any help would be appreciated

I've googled the error and found some info but the other use-cases are so different that it's difficult to understand the actual cause, or another work around.

AS requested (simplified example):
I've created a package variable (datatype string) called: View_Name

Execute SQL Task:

```<code>CREATE VIEW @[User::View_Name] AS SELECT
* from table1
where col1 = 100;
</code>```

Specifically it does not like that I use a variable here.
If I set the View name everything works until: I move on to my Where clauses that contain variables.

Create a variable called type (datatype int)

I map the variable/parameter in my sql task

Example:

```<code>CREATE VIEW tempTable AS SELECT
    * from table1
    where col1 = ?;
</code>```

This won't work, same error.

If i attempt to do the above via an expression or expressions I get the following error

```<code>[Execute SQL Task] Error: Executing the query "CREATE VIEW test_45678 AS SELECT P.label,P.uniquei..." failed with the following error: "Must declare the scalar variable "@".". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
</code>```

Generally having to due with the variables cannot be evaluated this way. I'm guessing I'd need to evaluate each piece individually and build the expression piece by piece. That's fine but very inefficient and not maintainable.

答:
I had some fundamental misunderstanding in my attempt to evaluate my expressions. Specifically syntax issues and having to cast each variable to a string.
My SQLstatement variable

```<code>ON C.pid = P.ID
where
C.width >="+(DT_WSTR, 8)@[User::Width] +"-"+ (DT_WSTR, 8)@[User::Range]+........
</code>```

The final expression looks like so:

```<code>"Create View "+@[User::View_Name] + " AS SELECT " + @[User::SQLStatement]
</code>```

Body:
I have a table that contains just under a million rows. I'm building a form using SSIS that asks for user input and uses the values as parameters to build a view from source data. I'm having trouble getting SSIS to create the view from a variable.

The purpose of this 'tool' is to provide a dialogue that programmatically builds a view and later an update statement based upon parameters defined via a form that will execute an SSIS package. A number of the ppl on my team know 0 SQL. Therefore this circumvents any SQL knowledge. Creating an entirely standalone app is not ideal as it would require too much additional overhead on my side and would deviate from a number of our existing processes that currently use SSIS/SQL to achieve similar results.

With that here is what I've tried/trying.

I have an SSIS package that contains 'Execute SQL Task'

This task brings up a form with 5 inputs (variables)
var1,var2,var3,var4,var5.
some vars are strings others are doubles, ints etc... (they all vary)

You populate the fields and hit okay.
These variables are passed to an 'Execute Package Task'.
Inside this package (Package B)
the vars are used in an 'Execute SQL Task'.

This task is attempting to take the users input and create a view with a where clause containing 4 other variables.

example:

Create View ? AS Select col1,col2,col3,col4 WHERE
col1 = ?
AND col2 =?
AND col3 =?.........

First it appears that using ? in the create view is invalid.
The error being:

Error: 0x0 at Build_Query: Incorrect syntax near '@P1'.
Error: 0xC002F210 at Build_Query, Execute SQL Task: Executing the query "CREATE VIEW ? as Select * from S_t_equip_template
..." failed with the following error: "The batch could not be analyzed because of compile errors.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established

 correctly.
Task failed: Build_Query

If I use the create view variable as an expression and remove the variables/paramerters for the where statements, I can create the view no problem.
However the where statements throw errors once I add them back in. I've tried evaluating these as an expression in the 'Execute SQL Task' but as these are of various types I get the error:

[Execute SQL Task] Error: Executing the query "
CREATE VIEW testing AS SELECT
P.label,P.uniq..." failed with the following error: "The metadata could not
be determined because statement 'CREATE VIEW testingagain AS SELECT
P.label,P.uniqueid,C.label as Child_Label,C.uniqueid as Child_uni' does not
support metadata discovery.". Possible failure reasons: Problems with the
query, "ResultSet" property not set correctly, parameters not set correctly,
or connection not established correctly.

No idea what is going on. Any help would be appreciated

I've googled the error and found some info but the other use-cases are so different that it's difficult to understand the actual cause, or another work around.

AS requested (simplified example):
I've created a package variable (datatype string) called: View_Name

Execute SQL Task:

CREATE VIEW @[User::View_Name] AS SELECT
* from table1
where col1 = 100;

Specifically it does not like that I use a variable here.
If I set the View name everything works until: I move on to my Where clauses that contain variables.

Create a variable called type (datatype int)

I map the variable/parameter in my sql task

Example:

CREATE VIEW tempTable AS SELECT
    * from table1
    where col1 = ?;

This won't work, same error.

If i attempt to do the above via an expression or expressions I get the following error

[Execute SQL Task] Error: Executing the query "CREATE VIEW test_45678 AS SELECT P.label,P.uniquei..." failed with the following error: "Must declare the scalar variable "@".". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Generally having to due with the variables cannot be evaluated this way. I'm guessing I'd need to evaluate each piece individually and build the expression piece by piece. That's fine but very inefficient and not maintainable.

Body:
I had some fundamental misunderstanding in my attempt to evaluate my expressions. Specifically syntax issues and having to cast each variable to a string.
My SQLstatement variable

ON C.pid = P.ID
where
C.width >="+(DT_WSTR, 8)@[User::Width] +"-"+ (DT_WSTR, 8)@[User::Range]+........

The final expression looks like so:

"Create View "+@[User::View_Name] + " AS SELECT " + @[User::SQLStatement]


问:
What's the relationship between sed, grep, find, awk, gawk, which one is preferred?
I'm new to Linux/Unix. I find some task can be accomplished by many ways using these commands. Is there some relationship between them? Or which one is preferred? Which one is outdated?

Thanks.

答:
Different tools for different jobs. The question is like "what is a better tool: a hammer, a screwdriver or combination pliers?"

grep - find/filter text in a file/stream. Line matches/doesn't match - stream it to output. Use to reduce amount of output to what you need. Commonly used interactively if you get too much information. Also often used in scripts to pull "that one line containing what I need"

Usually after scripted use of grep you see either awk (either a complicated expression or just an old-school programmer) or cut (which is much faster but pretty simplistic) to extract the one value. (grep chops horizontally, cut/awk chops vertically)

Using awk for fully-featured programming is currently almost unseen.

sed - search-and-replace, usually scripted (a visual editor is much better for that if you want to do it interactively - you see what is being done.)

find - find files conforming to given (advanced) parameters.


问:
Recursive function with type script
I'm playing around with promises and I'm having trouble with an asynchronous recursive promise.

The scenario is that i need to check for token validation inside a function and if the token expires i need to call the function again.
Below is the code i've done so far:

```<code>module.exports={
 frstFun:()=>{...
 },
 secondFun:(param)=>{
  return new Promise((resolve,reject)=>{
  request({
   url:url+'myapi',
   qs:{q:param,acc_token:token},
   method:'GET',
   },function(err,response,body){
    if(error){
    //here i need to call secondFun() method..
    }
    });
  })
  }

};
</code>```

I tried calling this.secondFun() but it's giving error secondFun() is not a method.

答:
I'm not sure if a recursive retry is the best way to do this, but you could pull the function definition out of the exports object:

```<code>let secondFun = (param) => {
    return new Promise((resolve, reject) => {
        request({
            url: url + 'myapi',
            qs: { q: param, acc_token: token },
            method: 'GET',
        }, function (err, response, body) {
            if (err) {
                // secondFun(...)
            }
        });
    })
};

module.exports = {
    frstFun: () => { ... },
    secondFun: secondFun
};
</code>```

Title: Recursive function with type script

Body:
I'm playing around with promises and I'm having trouble with an asynchronous recursive promise.

The scenario is that i need to check for token validation inside a function and if the token expires i need to call the function again.
Below is the code i've done so far:

module.exports={
 frstFun:()=>{...
 },
 secondFun:(param)=>{
  return new Promise((resolve,reject)=>{
  request({
   url:url+'myapi',
   qs:{q:param,acc_token:token},
   method:'GET',
   },function(err,response,body){
    if(error){
    //here i need to call secondFun() method..
    }
    });
  })
  }

};

I tried calling this.secondFun() but it's giving error secondFun() is not a method.

Body:
I'm not sure if a recursive retry is the best way to do this, but you could pull the function definition out of the exports object:

let secondFun = (param) => {
    return new Promise((resolve, reject) => {
        request({
            url: url + 'myapi',
            qs: { q: param, acc_token: token },
            method: 'GET',
        }, function (err, response, body) {
            if (err) {
                // secondFun(...)
            }
        });
    })
};

module.exports = {
    frstFun: () => { ... },
    secondFun: secondFun
};


问:
CSS Media Print - Make table always appear on separate page
Having two tables on a page that is going to be print, I would like that the second table is always print on a separate page.

For example: pages 1 and 2 contain the first table, and on page 2 the table ends right before the middle of the page.

Without any configuration, the second table would begin at page 2, right after the first table. What I want the second table to start on the next page (page 3) instead.

答: page-break-before should do the trick - try  #table2 {page-break-before: always;} in your print styles