问:
Email address columns in SQL Server
What's the correct way to add a check constraint for columns that should only contain email addresses?

We've had buggy software in the past that's added garbage to email columns and I would like to prevent that from happening again.

Please note that "perfect" solutions are not expected. While full RFC compliance would be great, I think most of us can agree just catching obvious mistakes such as "domain/username" and "2017-12-3" would be enough.

And of course it cannot reject any valid email address.

答:
You can use this :</p>

```<code>alter table your_table add constraint chk_email
CHECK
(
     email like '%_@__%.__%'
AND (CHARINDEX('.@', email) = 0 AND CHARINDEX('..', email) = 0)  -- prevent patterns like '.@' and '..'
AND LEN(LTRIM(RTRIM(email))) - LEN(REPLACE(LTRIM(RTRIM([email])),'@','')) = 1 -- Single '@' is allowed
)
</code>```

Title: Email address columns in SQL Server

Body:
You can use this :

alter table your_table add constraint chk_email
CHECK
(
     email like '%_@__%.__%'
AND (CHARINDEX('.@', email) = 0 AND CHARINDEX('..', email) = 0)  -- prevent patterns like '.@' and '..'
AND LEN(LTRIM(RTRIM(email))) - LEN(REPLACE(LTRIM(RTRIM([email])),'@','')) = 1 -- Single '@' is allowed
)


来源: stackexchange

问:
Convert recursive binary tree traversal to iterative
I was asked to write the iterative version, but I wrote the recursive version i.e.

```<code>void inorderTraverse(BinaryTree root)
{
    if(root==NULL)
        printf("%d",root->id);
    else
    {
        inorderTraverse(root->left);
        printf("%d",root->id);
        inorderTraverse(root->right);
    }
}
</code>```

I'm not looking for the code, I want to understand how this can be done. Had it been just the last recursive call, I would have done

```<code>void inorderTraverse(BinaryTree root)
{
    while(root!=NULL)
    {
        printf("%d",root->id);
        root=root->right;
    }
}
</code>```

But how do I convert to an iterative program when there are two recursive calls?

Here are the type definitions.

```<code>struct element{
    struct element* parent;
    int id;
    char* name;
    struct element* left;
    struct element* right;
};
typedef element* BinaryTree;
</code>```

This is what I thought of, am I on the right track?

```<code>temp=root;
while(1)
{
    while(temp!=NULL)
    {
     push(s,temp);
     temp=temp->left;
     continue;
    }

    temp=pop(s);
    if(temp==NULL)
    return;
    printf("%d\t",temp->data);
    temp=temp->right;
}
</code>```

答: There is a general way of converting recursive traversal to iterator by using a lazy iterator which concatenates multiple iterator suppliers (lambda expression which returns an iterator). See my Converting Recursive Traversal to Iterator.</p>

ContentLicense: CC BY-SA 3.0

Body:
I was asked to write the iterative version, but I wrote the recursive version i.e.

void inorderTraverse(BinaryTree root)
{
    if(root==NULL)
        printf("%d",root->id);
    else
    {
        inorderTraverse(root->left);
        printf("%d",root->id);
        inorderTraverse(root->right);
    }
}

I'm not looking for the code, I want to understand how this can be done. Had it been just the last recursive call, I would have done

void inorderTraverse(BinaryTree root)
{
    while(root!=NULL)
    {
        printf("%d",root->id);
        root=root->right;
    }
}

But how do I convert to an iterative program when there are two recursive calls?

Here are the type definitions.

struct element{
    struct element* parent;
    int id;
    char* name;
    struct element* left;
    struct element* right;
};
typedef element* BinaryTree;

This is what I thought of, am I on the right track?

temp=root;
while(1)
{
    while(temp!=NULL)
    {
     push(s,temp);
     temp=temp->left;
     continue;
    }

    temp=pop(s);
    if(temp==NULL)
    return;
    printf("%d\t",temp->data);
    temp=temp->right;
}


问:
Elm ports not working in Firefox
I am having a problem getting Elm ports working with Firefox.

Here is my index.html:

```<code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Firefox Ports</title>
</head>

<body>
    <script src="/app.js"></script>
</body>

</html>
</code>```

This is my index.js:

```<code>"use strict";

require("./index.html");

const Elm = require("./Main.elm");
const app = Elm.Main.fullscreen();
console.log("here");

window.onload = function() {
    console.log("window.onload");
    app.ports.sayHello.subscribe(function(who) {
        console.log("Greetings,", who);
    });
};
</code>```

And here is my Main.elm:

```<code>port module Main exposing (main)

import Html exposing (Html, div, text)

type Msg
    = None

type alias Model =
    {}

initialModel : Model
initialModel =
    {}

init : ( Model, Cmd Msg )
init =
    ( initialModel, sayHello "Foo" )

port sayHello : String -> Cmd msg

main : Program Never Model Msg
main =
    Html.program
        { init = init
        , update = update
        , subscriptions = subscriptions
        , view = view
        }

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    ( model, Cmd.none )

subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.none

view : Model -> Html Msg
view model =
    div []
        [ text "Hello" ]
</code>```

In the chrome console, the output shows that the port function is called when the model is initialized (init):

```<code>11:00:47.320 app.js:9181 here
11:00:47.371 app.js:9184 window.onload
11:00:47.464 app.js:9186 Greetings, Foo
</code>```

clearly showing that the port function is called, but in Firefox, the last line (Greetings, Foo) is missing:

```<code>here
window.onload
</code>```

What am I doing wrong?

答:
You could try moving the subscribe() call to occur right after the call to fullscreen() to remove the possibility of a race condition:

```<code>const app = Elm.Main.fullscreen();
app.ports.sayHello.subscribe(function(who) {
    console.log("Greetings,", who);
});
console.log("here");

window.onload = function() {
    console.log("window.onload");
};
</code>```

My hunch is that the event cycles in Firefox ran the Elm code prior to window.onload at a time when there were no subscriptions to the port. This is just a hunch, but I think best practice dictates that you set up your subscriptions as soon as you create the app.

Title: Elm ports not working in Firefox

Body:
I am having a problem getting Elm ports working with Firefox.

Here is my index.html:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Firefox Ports</title>

This is my index.js:

"use strict";

require("./index.html");

const Elm = require("./Main.elm");
const app = Elm.Main.fullscreen();
console.log("here");

window.onload = function() {
    console.log("window.onload");
    app.ports.sayHello.subscribe(function(who) {
        console.log("Greetings,", who);
    });
};

And here is my Main.elm:

port module Main exposing (main)

import Html exposing (Html, div, text)

type Msg
    = None

type alias Model =
    {}

initialModel : Model
initialModel =
    {}

init : ( Model, Cmd Msg )
init =
    ( initialModel, sayHello "Foo" )

port sayHello : String -> Cmd msg

main : Program Never Model Msg
main =
    Html.program
        { init = init
        , update = update
        , subscriptions = subscriptions
        , view = view
        }

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    ( model, Cmd.none )

subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.none

view : Model -> Html Msg
view model =
    div []
        [ text "Hello" ]

In the chrome console, the output shows that the port function is called when the model is initialized (init):

11:00:47.320 app.js:9181 here
11:00:47.371 app.js:9184 window.onload
11:00:47.464 app.js:9186 Greetings, Foo

clearly showing that the port function is called, but in Firefox, the last line (Greetings, Foo) is missing:

here
window.onload

What am I doing wrong?

Body:
You could try moving the subscribe() call to occur right after the call to fullscreen() to remove the possibility of a race condition:

const app = Elm.Main.fullscreen();
app.ports.sayHello.subscribe(function(who) {
    console.log("Greetings,", who);
});
console.log("here");

window.onload = function() {
    console.log("window.onload");
};

My hunch is that the event cycles in Firefox ran the Elm code prior to window.onload at a time when there were no subscriptions to the port. This is just a hunch, but I think best practice dictates that you set up your subscriptions as soon as you create the app.


问:
What is wrong with this function call
Behold the code:

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(qi,Qt::AutoColor));
</code>```

Why does this give me an error? What is it trying to get me to change the qi argument to in the call to fromImage? I am relatively new to C++ and it seems like I am setting this up correctly. It works if I change the line to

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
    ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));
</code>```

But is that the correct way to do this?

答:
Generally it might help, if you give the error message in your question. Now from looking at qts online documentation I think your problem is the following:

you are trying to pass qi which is of type QImage* to QPixMap::fromImage, which exepects a const QImage&, so a reference to QImage. Therefore what you have to do is dereference qi:

```<code>ui->viewLabel->setPixmap(QPixmap::fromImage(*qi,Qt::AutoColor));
</code>```

This is basically identical to your second version ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));, since ptr[i] is defined as *(ptr+i), so ptr[0] means basically *(ptr+0) which is *ptr. However using * for dereferencing here makes it clearer that you dereference a pointer to a single object, instead of an array.

ContentLicense: CC BY-SA 2.5

Title: What is wrong with this function call

Body:
Behold the code:

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(qi,Qt::AutoColor));

Why does this give me an error? What is it trying to get me to change the qi argument to in the call to fromImage? I am relatively new to C++ and it seems like I am setting this up correctly. It works if I change the line to

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
    ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));

But is that the correct way to do this?

Body:
Generally it might help, if you give the error message in your question. Now from looking at qts online documentation I think your problem is the following:

you are trying to pass qi which is of type QImage* to QPixMap::fromImage, which exepects a const QImage&, so a reference to QImage. Therefore what you have to do is dereference qi:

ui->viewLabel->setPixmap(QPixmap::fromImage(*qi,Qt::AutoColor));

This is basically identical to your second version ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));, since ptr[i] is defined as *(ptr+i), so ptr[0] means basically *(ptr+0) which is *ptr. However using * for dereferencing here makes it clearer that you dereference a pointer to a single object, instead of an array.


问:
How to ignore the .xml documentation files for reference .dll in Sandcastle
I have a project targeting .NET Framework 4.5.2

I checked the XML documentation file checkbox in Build tab, allowing me to document my own code.

I then built the .chm file using Sandcastle Help File Builder GUI. All is well so far.

Now I added some functionality using Tuples and since I target framework version 4.5.2 and not later where it's included, I added the System.ValueTuple.dll reference.

Now the problem starts: in my release catalog, apart from my doc.xml file containing my summaries and whatnot for the code, there is a System.ValueTuple.xml containing documentation for the .dll file. However, after trying to rebuild the Sandcastle file after some changes, the following error appeared:

```<code>> SHFB: Error BE0065: BUILD FAILED: Tag początkowy „p” w wierszu 1241 na
pozycji 2 nie pasuje do tagu końcowego „th”. wiersz 1241, pozycja 92.
   w System.Xml.XmlTextReaderImpl.Throw(Exception e)
   w System.Xml.XmlTextReaderImpl.ThrowTagMismatch(NodeData startTag)
   w System.Xml.XmlTextReaderImpl.ParseEndElement()
   w System.Xml.XmlTextReaderImpl.ParseElementContent()
   w System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
   w System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
   w System.Xml.XmlDocument.Load(XmlReader reader)
   w System.Xml.XmlDocument.LoadXml(String xml)
   w SandcastleBuilder.Utils.BuildEngine.XmlCommentsFile.get_Comments()
   w SandcastleBuilder.Utils.BuildEngine.XmlCommentsFile.get_Members()
   w SandcastleBuilder.Utils.BuildEngine.XmlCommentsFileCollection.get_ContainsInheritedDocumentation()
w SandcastleBuilder.Utils.BuildEngine.BuildProcess.Build()
</code>```

The first line reads Starting tag "p" in line 1241, position 2 does not match end tag "th" line 1241, position 92.

After some quick lookaround I found that indeed it's the documentation file for System.ValueTuple.dll that's broken (and badly so). Since I don't really need it in my help file, and don't feel like fixing a hundred errors, how do I tell Sandcastle to ignore it?

So far I tried:

Manually removing the file from Release catalog

Adding AllowedReferenceRelatedFileExtensions in .csproj file

Checking/unchecking various fields in Visibility tab in Sandcastle project properties including the API Filter (the offending .dll is not there)

Google also returns me nothing, although I may be trying wrong search terms.

答:
As a test I added a NuGet package PdfSharp.dll to a small c# project. The resulting documentation was a 4.5 MB CHM file.

So, from the Sandcastle Help File Builder GUI's Solution Explorer I did a right click and removed the PdfSharp.dll and PdfSharp.xml like shown in this screenshot. The resulting CHM has a size of 122 KB.

Body:
I have a project targeting .NET Framework 4.5.2

I checked the XML documentation file checkbox in Build tab, allowing me to document my own code.

I then built the .chm file using Sandcastle Help File Builder GUI. All is well so far.

Now I added some functionality using Tuples and since I target framework version 4.5.2 and not later where it's included, I added the System.ValueTuple.dll reference.

Now the problem starts: in my release catalog, apart from my doc.xml file containing my summaries and whatnot for the code, there is a System.ValueTuple.xml containing documentation for the .dll file. However, after trying to rebuild the Sandcastle file after some changes, the following error appeared:

> SHFB: Error BE0065: BUILD FAILED: Tag początkowy „p” w wierszu 1241 na
pozycji 2 nie pasuje do tagu końcowego „th”. wiersz 1241, pozycja 92.
   w System.Xml.XmlTextReaderImpl.Throw(Exception e)
   w System.Xml.XmlTextReaderImpl.ThrowTagMismatch(NodeData startTag)
   w System.Xml.XmlTextReaderImpl.ParseEndElement()
   w System.Xml.XmlTextReaderImpl.ParseElementContent()
   w System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
   w System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
   w System.Xml.XmlDocument.Load(XmlReader reader)
   w System.Xml.XmlDocument.LoadXml(String xml)
   w SandcastleBuilder.Utils.BuildEngine.XmlCommentsFile.get_Comments()
   w SandcastleBuilder.Utils.BuildEngine.XmlCommentsFile.get_Members()
   w SandcastleBuilder.Utils.BuildEngine.XmlCommentsFileCollection.get_ContainsInheritedDocumentation()
w SandcastleBuilder.Utils.BuildEngine.BuildProcess.Build()

The first line reads Starting tag "p" in line 1241, position 2 does not match end tag "th" line 1241, position 92.

After some quick lookaround I found that indeed it's the documentation file for System.ValueTuple.dll that's broken (and badly so). Since I don't really need it in my help file, and don't feel like fixing a hundred errors, how do I tell Sandcastle to ignore it?

So far I tried:

Manually removing the file from Release catalog

Adding AllowedReferenceRelatedFileExtensions in .csproj file

Checking/unchecking various fields in Visibility tab in Sandcastle project properties including the API Filter (the offending .dll is not there)

Google also returns me nothing, although I may be trying wrong search terms.


问:
How to load images in html whose src contain {{}} through webpack 2?
I use html-loader to load img in html, and it works well when img's src is invariable.as. BUT my when my write like this:, it will be error:Can't resolve '../../../assets/images/device_{{key.deviceName}}.png' in '/Users/zhangxu/Desktop/LicenseServer/angular/src/app/components/home'.
this is my webpack.config.js:

module: {
        rules: [
            {
                test: /\.ts$/,
                loaders:['awesome-typescript-loader', 'angular2-template-loader']
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]',
            },

            {
                test:/\.html$/,
                loader: 'html-loader',
                exclude: helper.root('src','index.html')

            },

            {
                test: /\.css$/,
                exclude: helper.root('src', 'app'),
                loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
            },
            {
                test:/\.css$/,
                include: helper.root('src', 'app'),
                loader:'raw-loader'

            },
            {
                test: /\.scss$/,
                loaders: ['style', 'css', 'postcss', 'sass']
            }
        ],

    },```
</div>
</div>

this is my HTML:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div *ngFor="let key of devices;let i = index;">
       <div class="device" *ngIf="key.selected && !key.out_select" (click)="cancelSelectDevice(i)">
         <img src="../../../assets/images/device_{{key.deviceName}}.png" width="75">

        </div>

</div></code>```

How can I solve this error? Thanks

答:
The problem here is that webpack only packs that files for you that it can resolve during build time. But your image paths are computed during runtime, so webpack can't know what image/images you need.

One dirty way is to import every single image in your javascript files. When you do this, webpack has a chance to know what images you want during compile time.

Probably the cleaner way would be to put these images in an assets folder and let your webserver serve this folder.

Body:
I use html-loader to load img in html, and it works well when img's src is invariable.as. BUT my when my write like this:, it will be error:Can't resolve '../../../assets/images/device_{{key.deviceName}}.png' in '/Users/zhangxu/Desktop/LicenseServer/angular/src/app/components/home'.
this is my webpack.config.js:

module: {
        rules: [
            {
                test: /\.ts$/,
                loaders:['awesome-typescript-loader', 'angular2-template-loader']
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]',
            },

            {
                test:/\.html$/,
                loader: 'html-loader',
                exclude: helper.root('src','index.html')

            },

            {
                test: /\.css$/,
                exclude: helper.root('src', 'app'),
                loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
            },
            {
                test:/\.css$/,
                include: helper.root('src', 'app'),
                loader:'raw-loader'

            },
            {
                test: /\.scss$/,
                loaders: ['style', 'css', 'postcss', 'sass']
            }
        ],

    },

this is my HTML:

How can I solve this error? Thanks


问:
Unable to export D3 chart Properly
I am trying to export the d3 chart as png image on button click.Also,i have mentioned below the function which i am using here:

```<code>$(function() {
  $('#btnSave').click(function(){
    html2canvas($('#test'),
    {
      onrendered: function (canvas) {
        var a = document.createElement('a');
        // toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
        a.href = canvas.toDataURL();
        a.download = 'somefilename.jpg';
        a.click();
      }
    });
  });

});
</code>```

When i am clicking on export button i am not getting the chart properly.Also i have mentioned the screen shot which i am getting after export.

答:
I would suggest not to use html2Canvas here because capturing any SVG images would create taint on the canvas and this library does not allow that (unless you force allowTaint: true which isn't a good option either).
Here's the issue you can go through: SVG Taint on canvas

Here's an approach to capture the SVG:

JS FIDDLE

Relevant code to capture image without any special library:

```<code>var svgString = new XMLSerializer().serializeToString(d3.select('body svg#custom_id').node()),
    blob = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"}),
  url = window.URL.createObjectURL(blob);

var img = d3.select('body').append('img').classed('exportImg', true).node();
img.onload = function () {
    var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');
    canvas.width = w + m[1] + m[3];
    canvas.height = h + m[0] + m[2];
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
   // $('body').append(canvas);
    d3.select('img.exportImg').remove();

    // create link
    var a = document.createElement('a');
    a.href = canvas.toDataURL();
    a.download = 'somefilename';
    a.click();
};
img.src = url;
</code>```

And by adding style to the paths, I meant, NOT using CSS (I'm sorry I wasn't clear there). Here is what I was talking about:

```<code> .enter().append("svg:path")
 .attr("d", path).style('fill', 'none').style('stroke', 'steelblue').style('stroke-opacity', 0.7).style('stroke-width', 1.5);
</code>```

Added the same to foreground and background. You can do the styling to the axes too in a similar fashion. CSS properties aren't captured while creating the SVG string.

Hope this helps. (And I've used sample base64 code for the image as those images weren't available, you can change that) :)

Title: Unable to export D3 chart Properly

Body:
I am trying to export the d3 chart as png image on button click.Also,i have mentioned below the function which i am using here:

$(function() {
  $('#btnSave').click(function(){
    html2canvas($('#test'),
    {
      onrendered: function (canvas) {
        var a = document.createElement('a');
        // toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
        a.href = canvas.toDataURL();
        a.download = 'somefilename.jpg';
        a.click();
      }
    });
  });

});

When i am clicking on export button i am not getting the chart properly.Also i have mentioned the screen shot which i am getting after export.

Body:
I would suggest not to use html2Canvas here because capturing any SVG images would create taint on the canvas and this library does not allow that (unless you force allowTaint: true which isn't a good option either).
Here's the issue you can go through: SVG Taint on canvas

Here's an approach to capture the SVG:

JS FIDDLE

Relevant code to capture image without any special library:

var svgString = new XMLSerializer().serializeToString(d3.select('body svg#custom_id').node()),
    blob = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"}),
  url = window.URL.createObjectURL(blob);

var img = d3.select('body').append('img').classed('exportImg', true).node();
img.onload = function () {
    var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');
    canvas.width = w + m[1] + m[3];
    canvas.height = h + m[0] + m[2];
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
   // $('body').append(canvas);
    d3.select('img.exportImg').remove();

    // create link
    var a = document.createElement('a');
    a.href = canvas.toDataURL();
    a.download = 'somefilename';
    a.click();
};
img.src = url;

And by adding style to the paths, I meant, NOT using CSS (I'm sorry I wasn't clear there). Here is what I was talking about:

 .enter().append("svg:path")
 .attr("d", path).style('fill', 'none').style('stroke', 'steelblue').style('stroke-opacity', 0.7).style('stroke-width', 1.5);

Added the same to foreground and background. You can do the styling to the axes too in a similar fashion. CSS properties aren't captured while creating the SVG string.

Hope this helps. (And I've used sample base64 code for the image as those images weren't available, you can change that) :)


问:
How to concatenate images of different shapes using python and opencv?
I have some images(say 5) and each having different shapes. I want to concatenate into one single image for my project report. Can you please provide an easy way using opencv and python?

The resulting image is similar to below.

In numpy I tried something like this, it works but only for two images.

```<code>r = np.concatenate((images[1][:, :, 1], images[1][:, :, 3]), axis=1)
</code>```

答:
I modified code to make it a simple function, may be useful for others.     </p>

```<code>def get_one_image(images):
        img_list = []
        padding = 200
        for img in images:
            img_list.append(cv2.imread(img))
        max_width = []
        max_height = 0
        for img in img_list:
            max_width.append(img.shape[0])
            max_height += img.shape[1]
        w = np.max(max_width)
        h = max_height + padding

        # create a new array with a size large enough to contain all the images
        final_image = np.zeros((h, w, 3), dtype=np.uint8)

        current_y = 0  # keep track of where your current image was last placed in the y coordinate
        for image in img_list:
            # add an image to the final array and increment the y coordinate
            final_image[current_y:image.shape[0] + current_y, :image.shape[1], :] = image
            current_y += image.shape[0]
        cv2.imwrite('out.png', final_image)
</code>```

Body:
I have some images(say 5) and each having different shapes. I want to concatenate into one single image for my project report. Can you please provide an easy way using opencv and python?

The resulting image is similar to below.

In numpy I tried something like this, it works but only for two images.

r = np.concatenate((images[1][:, :, 1], images[1][:, :, 3]), axis=1)

Body:
I modified code to make it a simple function, may be useful for others.

def get_one_image(images):
        img_list = []
        padding = 200
        for img in images:
            img_list.append(cv2.imread(img))
        max_width = []
        max_height = 0
        for img in img_list:
            max_width.append(img.shape[0])
            max_height += img.shape[1]
        w = np.max(max_width)
        h = max_height + padding

        # create a new array with a size large enough to contain all the images
        final_image = np.zeros((h, w, 3), dtype=np.uint8)

        current_y = 0  # keep track of where your current image was last placed in the y coordinate
        for image in img_list:
            # add an image to the final array and increment the y coordinate
            final_image[current_y:image.shape[0] + current_y, :image.shape[1], :] = image
            current_y += image.shape[0]
        cv2.imwrite('out.png', final_image)


问:
Why use isolated storage in an ASP.NET application?
I need to store user preferences on a per page basis in my application.  For example, several pages use a custom grid pager control that needs to keep its current page size between postbacks.  Most of the settings don't need to persist once the user leaves the page, but in some situations they do need to be restored.  Note: Session is disabled in this application and will not be used.

I did some reading on isolated storage and understand that it can be used to store these user settings.  Obviously cookies have been around a long time and are a proven approach to this scenario, but what about isolated storage?  Is it going to work for all browsers and in all environments?  Are permissions a problem?  Does it require configuring anything on the end-user's side?  Just how widely used is it?  Why should one use isolated storage in an application for the given example?

Thanks!

答:
You can always use hidden form field variables on a per-page basis, as a way to keep track of that page's state.

This is my preference to a session state strategy to deal with the scenario of users having say 2 FireFox browser instances open to the same page. No need to deal with session state issues in that scenario.


问:
Annotation to invoke REST service by Content-Type parameter
I have tried to google but was not able to find something on this topic.
The question is:

I have

```<code>Content-Type: multipart/mixed; TYPE=<paramValue>; boundary=----WebKitFormBoundaryMfWZACtN4mYmJK06;
</code>```

where paramValue could be paramValue1 and ParamValue2

Is there anyway to defer REST calls by TYPE parameter value. Something like:

```<code>@Consumes("multipart/mixed; TYPE=paramValue1")
@POST
postParameterValue1()
</code>```

and

```<code>@Consumes("multipart/mixed; TYPE=param**Value2**")
@POST
postParameterValue2()
</code>```

答:
You can not do that with annotation.
I suggest you to write a small logic to handle this situation.

First you should create a rest method to receive all the requests. The input parameter of this method should  be the value of the Content-Type header. Then you can check the value and do anything what you want:

```<code>private static final String CASE_1 = "paramValue1"

@POST
postParameterValue(@HeaderParam("Content-Type") final String contentType) {
    if (CASE_1.equals(contentType)) {
        handleCase1Request();
    } else {
        handleCase2Request();
    }

}

private void handleCase1Request() {
    // do anything what you like
}

private void handleCase2Request() {
    // do anything what you like
}
</code>```

Body:
I have tried to google but was not able to find something on this topic.
The question is:

I have

Content-Type: multipart/mixed; TYPE=<paramValue>; boundary=----WebKitFormBoundaryMfWZACtN4mYmJK06;

where paramValue could be paramValue1 and ParamValue2

Is there anyway to defer REST calls by TYPE parameter value. Something like:

@Consumes("multipart/mixed; TYPE=paramValue1")
@POST
postParameterValue1()

and

@Consumes("multipart/mixed; TYPE=param**Value2**")
@POST
postParameterValue2()

Body:
You can not do that with annotation.
I suggest you to write a small logic to handle this situation.

First you should create a rest method to receive all the requests. The input parameter of this method should  be the value of the Content-Type header. Then you can check the value and do anything what you want:

private static final String CASE_1 = "paramValue1"

@POST
postParameterValue(@HeaderParam("Content-Type") final String contentType) {
    if (CASE_1.equals(contentType)) {
        handleCase1Request();
    } else {
        handleCase2Request();
    }

}

private void handleCase1Request() {
    // do anything what you like
}

private void handleCase2Request() {
    // do anything what you like
}


问:
Validate Google id token with C#
I'm currently creating a web application on which the user can login via his Google account. This works client side but I would also like to secure REST API calls. To do so, I send the "Google id token" with each request via the "Authorization" header. Now, I would like to verify in C# that the token passed is valid. I found that there is a .NET library to do so but I didn't find anywhere any clear documentation on how to simply validate the token.

Does anyone have some pointer for this?

答:
My answer is the same as the answer above with a little bit more details.

```<code>using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;

GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(Token);
...
</code>```

The payload object contains all the information that you need.

Title: Validate Google id token with C#

Body:
My answer is the same as the answer above with a little bit more details.

using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;

GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(Token);
...

The payload object contains all the information that you need.

ContentLicense: CC BY-SA 4.0


问:
JavaScript setAttribute ID to row is Undefined
I am attempting to give each row that is dynamically added a unique ID. Basically by adding to the number each time the user clicks the add button. It is adding an ID, but not correctly, it is showing up as "undefined" in the dev tools.

var counter = 0;
function appendRow(id, style) {
  var table = document.getElementById(id); // table reference
  length = table.length,
  row = table.insertRow(table.rows.length, 'id');      // append table row
  row.setAttribute('id', style);
  row.setAttribute('idName', style);
  var i;
  // insert table cells to the new row
  for (i = 0; i < table.rows[0].cells.length; i++) {
      createCell(row.insertCell(i), i, 'cust' + counter);
      counter++
  }
}

function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
      txt = document.createTextNode('_'); // create text node
  div.appendChild(txt);               // append text node to the DIV
  div.setAttribute('id', style);        // set DIV class attribute
  div.setAttribute('idName', style);    // set DIV class attribute for IE (?!)
  cell.appendChild(div);                   // append DIV to the table cell
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  text-align: center;
}
td {
  width: 100px;
}

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

<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>

            Customers
            Main Location

            Someone
            Somewhere

```

答:
The reason why the new elements are showing up as "undefined" is because the style argument of appendRow has not been provided.

To get the functionality that you're going for you have to remove style from the appendRow arguments and replace the references to style inside appendRow with 'cust' + counter.

Body:
I am attempting to give each row that is dynamically added a unique ID. Basically by adding to the number each time the user clicks the add button. It is adding an ID, but not correctly, it is showing up as "undefined" in the dev tools.

var counter = 0;
function appendRow(id, style) {
  var table = document.getElementById(id); // table reference
  length = table.length,
  row = table.insertRow(table.rows.length, 'id');      // append table row
  row.setAttribute('id', style);
  row.setAttribute('idName', style);
  var i;
  // insert table cells to the new row
  for (i = 0; i < table.rows[0].cells.length; i++) {
      createCell(row.insertCell(i), i, 'cust' + counter);
      counter++
  }
}

function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
      txt = document.createTextNode('_'); // create text node
  div.appendChild(txt);               // append text node to the DIV
  div.setAttribute('id', style);        // set DIV class attribute
  div.setAttribute('idName', style);    // set DIV class attribute for IE (?!)
  cell.appendChild(div);                   // append DIV to the table cell
}

table {
  text-align: center;
}
td {
  width: 100px;
}

tr:nth-child(even) {
  background-color: #fff;
}
tr:nth-child(odd) {
  background-color: #eee;
}

<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>

            Customers
            Main Location

            Someone
            Somewhere


问:
Why I can store null in Int when doing conversion from Java but not otherwise?
In the following code, I am creating a Java collection. Later when I convert it to Scala, I can store null in Int. But I cannot store null if I straightaway create a scala map. Why?

```<code>scala> import collection.JavaConverters._
import collection.JavaConverters._

scala> val mapJava:java.util.HashMap[String,java.lang.Integer] =  new java.util.HashMap[String,java.lang.Integer]
mapJava: java.util.HashMap[String,Integer] = {}

scala> mapJava.put("key",null)
res2: Integer = null

scala> println(mapJava)
{key=null}

scala> val mapScala = mapJava.asScala
mapScala: scala.collection.mutable.Map[String,Integer] = Map(key -> null)

scala> val mapScalaI = mapScala.asInstanceOf[scala.collection.Map[String,Int]]
mapScalaI: scala.collection.Map[String,Int] = Map(key -> null) //storing null in Int

//but I cannot store null in Int in following code. why?
scala> val mapScalaI2 = Map[String,Int]("key"->null)
<console>:14: error: an expression of type Null is ineligible for implicit conversion
       val mapScalaI2 = Map[String,Int]("key"->null)
                                               ^
</code>```

答:
In Java null can be value of any reference type, e.g. java.lang.Integer.

In Scala null is of type Null, which is a subtype of any reference type. scala.Int is a primitive type, not reference one.

an expression of type Null is ineligible for implicit conversion

Body:
In the following code, I am creating a Java collection. Later when I convert it to Scala, I can store null in Int. But I cannot store null if I straightaway create a scala map. Why?

scala> import collection.JavaConverters._
import collection.JavaConverters._

scala> val mapJava:java.util.HashMap[String,java.lang.Integer] =  new java.util.HashMap[String,java.lang.Integer]
mapJava: java.util.HashMap[String,Integer] = {}

scala> mapJava.put("key",null)
res2: Integer = null

scala> println(mapJava)
{key=null}

scala> val mapScala = mapJava.asScala
mapScala: scala.collection.mutable.Map[String,Integer] = Map(key -> null)

scala> val mapScalaI = mapScala.asInstanceOf[scala.collection.Map[String,Int]]
mapScalaI: scala.collection.Map[String,Int] = Map(key -> null) //storing null in Int

//but I cannot store null in Int in following code. why?
scala> val mapScalaI2 = Map[String,Int]("key"->null)
<console>:14: error: an expression of type Null is ineligible for implicit conversion
       val mapScalaI2 = Map[String,Int]("key"->null)
                                               ^


问:
Open file by filename wildcard
I have a directory of text files that all have the extension .txt. My goal is to print the contents of the text file. I wish to be able use the wildcard *.txt to specify the file name I wish to open (I'm thinking along the lines of something like F:\text\*.txt?), split the lines of the text file, then print the output.

Here is an example of what I want to do, but I want to be able to change somefile when executing my command.

```<code>f = open('F:\text\somefile.txt', 'r')
for line in f:
    print line,
</code>```

I had checked out the glob module earlier, but I couldn't figure out how to actually do anything to the files.  Here is what I came up with, not working.

```<code>filepath = "F:\irc\as\*.txt"
txt = glob.glob(filepath)

lines = string.split(txt, '\n') #AttributeError: 'list' object has no attribute 'split'
print lines
</code>```

答:
This problem just came up for me and I was able to fix it with pure python:

Link to the python docs is found here: 10.8. fnmatch — Unix filename pattern matching

Quote: "This example will print all file names in the current directory with the extension .txt:"

```<code>import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
</code>```

Title: Open file by filename wildcard

Body:
I have a directory of text files that all have the extension .txt. My goal is to print the contents of the text file. I wish to be able use the wildcard *.txt to specify the file name I wish to open (I'm thinking along the lines of something like F:\text\*.txt?), split the lines of the text file, then print the output.

Here is an example of what I want to do, but I want to be able to change somefile when executing my command.

f = open('F:\text\somefile.txt', 'r')
for line in f:
    print line,

I had checked out the glob module earlier, but I couldn't figure out how to actually do anything to the files.  Here is what I came up with, not working.

filepath = "F:\irc\as\*.txt"
txt = glob.glob(filepath)

lines = string.split(txt, '\n') #AttributeError: 'list' object has no attribute 'split'
print lines

Body:
This problem just came up for me and I was able to fix it with pure python:

Link to the python docs is found here: 10.8. fnmatch — Unix filename pattern matching

Quote: "This example will print all file names in the current directory with the extension .txt:"

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)


问:
VBA Input Box will not close
I currently have a code shown below for entering a password to have the code start. I am a VBA noob so please go easy on me.

Issue: When the input box prompt appears it works fine if the password is correct. If it is incorrect you are given more opportunities to enter it again but lets say you do not know the password and want to close the window, you cannot. The "x" option and cancel options will just cause the input box prompt to refresh rather than closing the window. How can I set the window up to close?

Here is the code in written form:

```<code>    Sub Pword()

        Dim Ans As Boolean
        Const Pword As String = "black2"

        Ans = False

        Do While Ans = False
            If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
                Ans = True
            End If
        Loop

Sheets("Workshop").Range("B15:B20") = ""
Sheets("Workshop").Range("B24:B29") = ""
Sheets("Workshop").Range("B33:B35") = ""
Sheets("Workshop").Range("E5:E11") = ""
Sheets("Workshop").Range("E15:E26") = ""
Sheets("Workshop").Range("H5:H17") = ""

MsgBox "All data has been cleared."

End Sub
</code>```

答:
@braX suggestion is an excellent solution.
Also, you can limit the attemps to n in this case I limit the attempts to 3

```<code> Dim sResult As String
 Dim Attmp As Integer
 Attmp = 0
    Do While Ans = False
        sResult = InputBox("Please enter password to continue.", "Enter Password")
        If sResult = Pword Then
            Ans = True
        ElseIf sResult = "" Then
            Attmp = Attmp + 1
            If Attmp = 3 Then
                Msgbox "Maximum attempts reached."
                Exit Do
            End If
        End If
    Loop
</code>```

Title: VBA Input Box will not close

Body:
I currently have a code shown below for entering a password to have the code start. I am a VBA noob so please go easy on me.

Issue: When the input box prompt appears it works fine if the password is correct. If it is incorrect you are given more opportunities to enter it again but lets say you do not know the password and want to close the window, you cannot. The "x" option and cancel options will just cause the input box prompt to refresh rather than closing the window. How can I set the window up to close?

Here is the code in written form:

    Sub Pword()

        Dim Ans As Boolean
        Const Pword As String = "black2"

        Ans = False

        Do While Ans = False
            If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
                Ans = True
            End If
        Loop

Sheets("Workshop").Range("B15:B20") = ""
Sheets("Workshop").Range("B24:B29") = ""
Sheets("Workshop").Range("B33:B35") = ""
Sheets("Workshop").Range("E5:E11") = ""
Sheets("Workshop").Range("E15:E26") = ""
Sheets("Workshop").Range("H5:H17") = ""

MsgBox "All data has been cleared."

End Sub

Body:
@braX suggestion is an excellent solution.
Also, you can limit the attemps to n in this case I limit the attempts to 3

 Dim sResult As String
 Dim Attmp As Integer
 Attmp = 0
    Do While Ans = False
        sResult = InputBox("Please enter password to continue.", "Enter Password")
        If sResult = Pword Then
            Ans = True
        ElseIf sResult = "" Then
            Attmp = Attmp + 1
            If Attmp = 3 Then
                Msgbox "Maximum attempts reached."
                Exit Do
            End If
        End If
    Loop


问:
Microsoft ClickOnce Deployment Question
I want to deploy an application using ClickOnce Technology. The application depends on .xml file. The location of the .xml file is provided in the App.config file. This .xml file can be changed by the user. With ClickOnce, i only see (.appref-ms) file downloaded. Is it possible to download dependent files that can be modified by users?

Thanks

答:
First, be sure you're looking in the right place for the files.  Applicaitons deployed via ClickOnce are not stored where you'd expect if you haven't run across this before.  See here: http://msdn.microsoft.com/en-us/library/267k390a.aspx

Second, you can include additional files (termed here as local data).  See here: http://msdn.microsoft.com/en-us/library/d8saf4wy.aspx

Added  This might be more helful than the link above.  It's a how-to that covers choosing which files are installed.  It more directly answers your question.

http://msdn.microsoft.com/en-us/library/kzy0fky2.aspx

Title: Microsoft ClickOnce Deployment Question


问:
Unable to create a Angular 5 Universal server application application bundle using @ngtools/webpack
am trying to build a universal app with Angular 5 and WebPack without the cli.

The issue I am having is that I cannot seem to get the express application to work and I am met with this error every time I hit the server

```<code>Error: You must pass in a NgModule or NgModuleFactory to be bootstrapped
    at View.engine (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/@nguniversal/express-engine/src/main.js:34:23)
    at View.render (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/view.js:135:8)
    at tryRender (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/application.js:640:10)
    at Function.render (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/response.js:1008:7)
    at /Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/dist/server.js:122:47
    at Layer.handle [as handle_request] (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/router/layer.js:95:5)
    at next (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/router/layer.js:95:5)
</code>```

I believe the issue is to do with the server application bundle that's then consumed by server.ts because if I console log out AppServerModuleNgFactory it comes up as undefined.

I've tried to base my server config to match that as close as possible to the one generated by the CLI project in the angular/universal-starter repo but it just doesn't generate an app bundle that the server can use

You can find a repo at https://github.com/mogusbi/ng5-universal-webpack. Clone that, run npm start and go to localhost:4000

答:
I've eventually worked out why the ModuleNgFactories weren't being generated after delving into nitty gritty of the CLI source code and it's literally just because there's an undocumented option in the AngularCompilerPlugin called platform - it needs to be set to 1 to generate the server application bundle that then gets consumed by ngExpressEngine in the express application.

Once you do that, everything works as you expect it to!

I hope anyone else who has trouble getting the isomorphic stuff to work without the CLI finds this helpful

Body:
am trying to build a universal app with Angular 5 and WebPack without the cli.

The issue I am having is that I cannot seem to get the express application to work and I am met with this error every time I hit the server

Error: You must pass in a NgModule or NgModuleFactory to be bootstrapped
    at View.engine (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/@nguniversal/express-engine/src/main.js:34:23)
    at View.render (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/view.js:135:8)
    at tryRender (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/application.js:640:10)
    at Function.render (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/response.js:1008:7)
    at /Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/dist/server.js:122:47
    at Layer.handle [as handle_request] (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/router/layer.js:95:5)
    at next (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Volumes/Data/Users/mo/Desktop/ng5-universal-webpack/node_modules/express/lib/router/layer.js:95:5)

I believe the issue is to do with the server application bundle that's then consumed by server.ts because if I console log out AppServerModuleNgFactory it comes up as undefined.

I've tried to base my server config to match that as close as possible to the one generated by the CLI project in the angular/universal-starter repo but it just doesn't generate an app bundle that the server can use

You can find a repo at https://github.com/mogusbi/ng5-universal-webpack. Clone that, run npm start and go to localhost:4000


问:
PHP Multidimensional Array Iterating From Text File
I have a text file named C.txt. The contens of the text file goes as following:

Name,      BPrice, SPrice, Display

  Nokia 520,  20000,  21000,  1

  Xiaomi123,  15000,  17000,  0

  Xiaomi Redmi,   30000,  32000,  1

I have accessed the file using the following code:

```<code><?php

    $file = fopen("C.txt", "r");
    while(!feof($file)){
        $content = fgets($file);
        $products[] = $content;
    }

    var_dump($products);

?>
</code>```

var_dump($products) gives output:

array(4) { [0]=> string(33) "Name, BPrice, SPrice, Display " [1]=> string(29) "Nokia 520,  20000,  21000,  1   " [2]=> string(29) "Xiaomi123,  15000,  17000,  0   " [3]=> string(30) "Xiaomi Redmi,   30000,  32000,  1   " }

What I wanted to do, is to separate the Name, BPrice, SPrice and Display columns and their values using explode() method. So, I tried the following:

```<code><?php

        for($i=1; $i<count($products); $i++){

              $contents[] = explode(",", $products[$i]);

        }

        var_dump($contents);

?>
</code>```

var_dump($contents) yields:

array(3) { [0]=> array(4) { [0]=> string(9) "Nokia 520" [1]=> string(6) "  20000" [2]=> string(6) "    21000" [3]=> string(5) "    1   " } [1]=> array(4) { [0]=> string(9) "Xiaomi123" [1]=> string(6) "  15000" [2]=> string(6) "    17000" [3]=> string(5) "    0   " } [2]=> array(4) { [0]=> string(12) "Xiaomi Redmi" [1]=> string(6) "  30000" [2]=> string(6) "    32000" [3]=> string(3) "    1   " } }

NOTE: I wanted to access only the values of the columns and not the headers, hence for($i=1; $i<count($products); $i++)

Now here is where I'm facing the problem. How do I access this two dimensional array $contents?

I have tried the foreach loop as following:

```<code>foreach ($contents as $key => $value) {
    echo $value[$key];
}
</code>```

But that results in:

Nokia 520  15000   32000

I cannot seem to figure out why it is not printing the rest of the two rows! Any help would be greatly appreciated. Thanks in advance! :)

答:
Your array in more readable terms looks like this

```<code>[["Nokia 520", "20000", "21000", "1"],
 ["Xiaomi123", "15000", "17000", "0"],
 ["Xiaomi Redmi", "30000", "32000", "1"]]
</code>```

This means that in your foreach, the value of your first key is

```<code>["Nokia 520", "20000", "21000", "1"]
</code>```

The reason you are only getting those values is that you are doing

```<code>echo $value[$key];
</code>```

So essentially you are returning positions 0 1 and 2 of ["Nokia 520", "20000", "21000", "1"], which are the values Nokia 520, 20000 and 21000

To get the values you actually want, you need to perform two foreach loops

```<code>foreach ($arr as $keys) {
    foreach($keys as $value) {
        echo "{$value} ";
    }
    echo "\n";
}
</code>```

Body:
I have a text file named C.txt. The contens of the text file goes as following:

Name,      BPrice, SPrice, Display

  Nokia 520,  20000,  21000,  1

  Xiaomi123,  15000,  17000,  0

  Xiaomi Redmi,   30000,  32000,  1

I have accessed the file using the following code:

<?php

    $file = fopen("C.txt", "r");
    while(!feof($file)){
        $content = fgets($file);
        $products[] = $content;
    }

    var_dump($products);

?>

var_dump($products) gives output:

array(4) { [0]=> string(33) "Name, BPrice, SPrice, Display " [1]=> string(29) "Nokia 520,  20000,  21000,  1   " [2]=> string(29) "Xiaomi123,  15000,  17000,  0   " [3]=> string(30) "Xiaomi Redmi,   30000,  32000,  1   " }

What I wanted to do, is to separate the Name, BPrice, SPrice and Display columns and their values using explode() method. So, I tried the following:

<?php

        for($i=1; $i<count($products); $i++){

              $contents[] = explode(",", $products[$i]);

        }

        var_dump($contents);

?>

var_dump($contents) yields:

array(3) { [0]=> array(4) { [0]=> string(9) "Nokia 520" [1]=> string(6) "  20000" [2]=> string(6) "    21000" [3]=> string(5) "    1   " } [1]=> array(4) { [0]=> string(9) "Xiaomi123" [1]=> string(6) "  15000" [2]=> string(6) "    17000" [3]=> string(5) "    0   " } [2]=> array(4) { [0]=> string(12) "Xiaomi Redmi" [1]=> string(6) "  30000" [2]=> string(6) "    32000" [3]=> string(3) "    1   " } }

NOTE: I wanted to access only the values of the columns and not the headers, hence for($i=1; $i<count($products); $i++)

Now here is where I'm facing the problem. How do I access this two dimensional array $contents?

I have tried the foreach loop as following:

foreach ($contents as $key => $value) {
    echo $value[$key];
}

But that results in:

Nokia 520  15000   32000

I cannot seem to figure out why it is not printing the rest of the two rows! Any help would be greatly appreciated. Thanks in advance! :)

Body:
Your array in more readable terms looks like this

[["Nokia 520", "20000", "21000", "1"],
 ["Xiaomi123", "15000", "17000", "0"],
 ["Xiaomi Redmi", "30000", "32000", "1"]]

This means that in your foreach, the value of your first key is

["Nokia 520", "20000", "21000", "1"]

The reason you are only getting those values is that you are doing

echo $value[$key];

So essentially you are returning positions 0 1 and 2 of ["Nokia 520", "20000", "21000", "1"], which are the values Nokia 520, 20000 and 21000

To get the values you actually want, you need to perform two foreach loops

foreach ($arr as $keys) {
    foreach($keys as $value) {
        echo "{$value} ";
    }
    echo "\n";
}


问:
pass variable into dynamically created button click event handler
I am creating a textbox and button dynamically like this inside a FlowLayoutPanel:

```<code>        Dim txtRating As New TextBox
        txtRating.Name = "buildingRating_" + intCount.ToString

        Dim btnAddRating As New Button
        btnAddRating.Name = "addRating_" + intCount.ToString
</code>```

And then I create an event handler for the button:

```<code>    AddHandler btnAddRating.Click, AddressOf HandleAddRatingButtonClick
</code>```

Each textbox and button will be associated with each other with the intCount value, so it would look like this:

```<code>buildingRating_1   addRating_1
buildingRating_2   addRating_2
buildingRating_3   addRating_3
etc....
</code>```

I need to get the value of the textbox that is in associated with the button.

For example, if the user clicks the button named addRating_1, the text value of buildingRating_1 will be saved a database...

Is there a way to get that association or pass intCount into the btnAddRating.Click event that I am creating?

Thanks!

答:
Extract the index from the name of the button, and use it to recreate the name of the textbox. Then find the textbox on the form.

```<code>Private Sub HandleAddRatingButtonClick(sender As Object, e As EventArgs)
    Dim button = DirectCast(sender, Button)
    Dim index = button.Name.Split("_"c).Last()
    Dim textboxname = "buildingRating_" & index
    Dim textbox = Me.Controls.OfType(Of TextBox).Single(Function(tb) tb.Name = textboxname)
    Dim text = textbox.Text ' this is the text
End Sub
</code>```

If the textbox is in a container (panel, groupbox, etc.) then instead of Me.Controls... do Container.Controls...

Body:
I am creating a textbox and button dynamically like this inside a FlowLayoutPanel:

        Dim txtRating As New TextBox
        txtRating.Name = "buildingRating_" + intCount.ToString

        Dim btnAddRating As New Button
        btnAddRating.Name = "addRating_" + intCount.ToString

And then I create an event handler for the button:

    AddHandler btnAddRating.Click, AddressOf HandleAddRatingButtonClick

Each textbox and button will be associated with each other with the intCount value, so it would look like this:

buildingRating_1   addRating_1
buildingRating_2   addRating_2
buildingRating_3   addRating_3
etc....

I need to get the value of the textbox that is in associated with the button.

For example, if the user clicks the button named addRating_1, the text value of buildingRating_1 will be saved a database...

Is there a way to get that association or pass intCount into the btnAddRating.Click event that I am creating?

Thanks!

Body:
Extract the index from the name of the button, and use it to recreate the name of the textbox. Then find the textbox on the form.

Private Sub HandleAddRatingButtonClick(sender As Object, e As EventArgs)
    Dim button = DirectCast(sender, Button)
    Dim index = button.Name.Split("_"c).Last()
    Dim textboxname = "buildingRating_" & index
    Dim textbox = Me.Controls.OfType(Of TextBox).Single(Function(tb) tb.Name = textboxname)
    Dim text = textbox.Text ' this is the text
End Sub

If the textbox is in a container (panel, groupbox, etc.) then instead of Me.Controls... do Container.Controls...


问:
CSS Font-size not working properly on mobile device
I'm working on a small project for school, where we have to incorporate html5 and css3. It's just in the begin stage now, as I'm trying to create two separate css-files for a mobile and a desktop version.

For the mobile version, I'm trying to get the menu to just show as a list, but with a bigger font. I can in no way get this working though.

This is the css for the menu:

```<code>nav ul {
    list-style: none;
    background-color: green;
    padding: 0;
}

nav li {
    border-bottom: 1px solid black;
    padding: 5px;
}

nav {
    margin-top: -36px;
    width: 100%
}

nav h1{
    margin: 0;
}
</code>```

This creates the following on my desktop
And on my iPhone

The font-size is set to 1em in the HTML in the top of the file. But 1em is not big enough for mobile devices, so I want it bigger, which seems impossible.

Even when I give the nav h1 a font-size of 10em, it doesn't get bigger than this:

While on my desktop it does work without a problem, there it looks like this:

The same problem occurs when trying to make the "blog posts" bigger, they just won't do it.

I normally have no trouble working with CSS, but this time I can't figure it out. Hope anyone can help! I have the feeling it's something very obvious.

Here is the complete CSS: http://snipt.org/zLic5

Here is the html: http://snipt.org/zLid2

答:
Try css property text-size-adjust to scale text on mobile devices. Something like:

```<code>nav {
    text-size-adjust: 200%;
}
nav ul {
    text-size-adjust: 300%;
}
nav h1 {
    text-size-adjust: 400%;
}
</code>```

Body:
I'm working on a small project for school, where we have to incorporate html5 and css3. It's just in the begin stage now, as I'm trying to create two separate css-files for a mobile and a desktop version.

For the mobile version, I'm trying to get the menu to just show as a list, but with a bigger font. I can in no way get this working though.

This is the css for the menu:

nav ul {
    list-style: none;
    background-color: green;
    padding: 0;
}

nav li {
    border-bottom: 1px solid black;
    padding: 5px;
}

nav {
    margin-top: -36px;
    width: 100%
}

nav h1{
    margin: 0;
}

This creates the following on my desktop
And on my iPhone

The font-size is set to 1em in the HTML in the top of the file. But 1em is not big enough for mobile devices, so I want it bigger, which seems impossible.

Even when I give the nav h1 a font-size of 10em, it doesn't get bigger than this:

While on my desktop it does work without a problem, there it looks like this:

The same problem occurs when trying to make the "blog posts" bigger, they just won't do it.

I normally have no trouble working with CSS, but this time I can't figure it out. Hope anyone can help! I have the feeling it's something very obvious.

Here is the complete CSS: http://snipt.org/zLic5

Here is the html: http://snipt.org/zLid2

Body:
Try css property text-size-adjust to scale text on mobile devices. Something like:

nav {
    text-size-adjust: 200%;
}
nav ul {
    text-size-adjust: 300%;
}
nav h1 {
    text-size-adjust: 400%;
}


问:
Reading button's background image
I'm trying to read a button's background image, this is what i'm trying:

```<code>  ImageView btn_java1 = (ImageView)findViewById(R.id.background);
  int draw = R.drawable.ic_launcher;

    btn1.setOnClickListener(new OnClickListener() {
        public void onClick(View var1) {

        if (btn_java1.getBackground().equals(draw)){
            a.setVisibility(View.VISIBLE);
        }
        else{
            a.setVisibility(View.INVISIBLE);
        }

        }
    });
</code>```

But it's not working and I can't see the problem

答:
getBackground() returns a Drawable. draw is an integer. So comparing them is not going to go well....

Maybe you could use:

```<code> Drawable draw= getResources().getDrawable(R.drawable.ic_luncher);
</code>```

Hopefully you realize "luncher" is not "launcher".

Title: Reading button's background image

Body:
I'm trying to read a button's background image, this is what i'm trying:

  ImageView btn_java1 = (ImageView)findViewById(R.id.background);
  int draw = R.drawable.ic_launcher;

    btn1.setOnClickListener(new OnClickListener() {
        public void onClick(View var1) {

        if (btn_java1.getBackground().equals(draw)){
            a.setVisibility(View.VISIBLE);
        }
        else{
            a.setVisibility(View.INVISIBLE);
        }

        }
    });

But it's not working and I can't see the problem

Body:
getBackground() returns a Drawable. draw is an integer. So comparing them is not going to go well....

Maybe you could use:

 Drawable draw= getResources().getDrawable(R.drawable.ic_luncher);

Hopefully you realize "luncher" is not "launcher".


问:
Adding "hoverIntent" to .live function
Real simple question here - how do I add the .hoverIntent plugin from Brian Cherne to the following code in place of the .live("hover", function

```<code>        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });
</code>```

Here's the full code:

```<code>    $(document).ready(function(){

        $('#sliding_grid li').hover(function() {
          $(this).css('z-index',1).data('origTop',$(this).css('top')).data('origLeft',$(this).css('left')).addClass('highlight');

        }, function() {
          $(this).css('z-index', 0);
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"0", "margin-left":"0"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":$(this).data('origTop'), "left":$(this).data('origLeft'), "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });
</code>```

答:
Try replacing this code:

```<code>$(".highlight").live("hover", function(){
    $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"0", "margin-left":"0"}, 500);

});
</code>```

With this:

```<code>$('.highlight').live('mouseover', function() {
  if (!$(this).data('init')) {
    $(this).data('init', true);
    $(this).hoverIntent(function(){
      $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"0", "margin-left":"0"}, 500);
    },
    function(){
      /* mouseout logic */
    });
    $(this).trigger('mouseover');
  }
});
</code>```

Source

Title: Adding "hoverIntent" to .live function

Body:
Real simple question here - how do I add the .hoverIntent plugin from Brian Cherne to the following code in place of the .live("hover", function

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"-94px", "margin-left":"-152px"}, 500);

        });

Here's the full code:

    $(document).ready(function(){

        $('#sliding_grid li').hover(function() {
          $(this).css('z-index',1).data('origTop',$(this).css('top')).data('origLeft',$(this).css('left')).addClass('highlight');

        }, function() {
          $(this).css('z-index', 0);
        });

        $(".highlight").live("hover", function(){
            $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"0", "margin-left":"0"}, 500);

        });

        $(".highlight").live("mouseout", function(){
            $(this).animate({"width": "148px", "height":"90px", "top: ":$(this).data('origTop'), "left":$(this).data('origLeft'), "margin-top: ":"0", "margin-left":"0"}, 500, function(){
             $(this).removeClass('highlight');
            });

        });

    });

Body:
Try replacing this code:

$(".highlight").live("hover", function(){
    $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"0", "margin-left":"0"}, 500);

});

With this:

$('.highlight').live('mouseover', function() {
  if (!$(this).data('init')) {
    $(this).data('init', true);
    $(this).hoverIntent(function(){
      $(this).animate({"width": "454px", "height":"282px", "top: ":"94px", "left":"152px", "margin-top: ":"0", "margin-left":"0"}, 500);
    },
    function(){
      /* mouseout logic */
    });
    $(this).trigger('mouseover');
  }
});

Source


问:
python sympy does not factor well polynomials of booleans
I am trying to factor a polynomial of booleans to get the minimal form of a logic net. My variables are a1, a2, a3 ... and the negative counterparts na1, na2, na3 ...

If would expect a function

```<code>f = a1*a2*b2*nb1 + a1*b1*na2*nb2 + a1*b1*na2 + a2*b2*na1*nb1
</code>```

to be factored like this (at least) :

```<code>f = a1*b1*(b2*nb1 + na2*(nb2 + 1)) + a2*b2*na1*nb1
</code>```

I run this script:

```<code>import sympy
a1,a2,b1,b2,b3,na1,na2,na3,nb1,nb2,nb3 = \
            sympy.symbols("a1:3, b1:4, na1:4, nb1:4", bool=True)
f = "a1*na2*b1 + a1*a2*nb1*b2 + a1*na2*b1*nb2 + na1*a2*nb1*b2"
sympy.init_printing(use_unicode=True)
sympy.factor(f)
</code>```

and this returns me the same function, not factored.

```<code>a1*a2*b2*nb1 + a1*b1*na2*nb2 + a1*b1*na2 + a2*b2*na1*nb1
</code>```

What am I doing wrong ?

答:
Your expected output

```<code>f = a1*b1*(b2*nb1 + na2*(nb2 + 1)) + a2*b2*na1*nb1
</code>```

is not a factorization of f, so factor is not going to produce it. To factor something means to write it as a product, not "a product plus some other stuff".

If you give a polynomial that can actually be factored, say f = a1*na2*b1 + a1*a2*nb1*b2 + a1*na2*b1*nb2, then factor(f) has an effect.

What you are looking for is closer to collecting the terms with the same variable, which is done with collect.

```<code>f = a1*na2*b1 + a1*a2*nb1*b2 + a1*na2*b1*nb2 + na1*a2*nb1*b2
collect(f, a1)
</code>```

outputs

```<code>a1*(a2*b2*nb1 + b1*na2*nb2 + b1*na2) + a2*b2*na1*nb1
</code>```

The method coeff also works in that direction, e.g., f.coeff(a1) returns the contents of the parentheses in the previous formula.

Body:
I am trying to factor a polynomial of booleans to get the minimal form of a logic net. My variables are a1, a2, a3 ... and the negative counterparts na1, na2, na3 ...

If would expect a function

f = a1*a2*b2*nb1 + a1*b1*na2*nb2 + a1*b1*na2 + a2*b2*na1*nb1

to be factored like this (at least) :

f = a1*b1*(b2*nb1 + na2*(nb2 + 1)) + a2*b2*na1*nb1

I run this script:

import sympy
a1,a2,b1,b2,b3,na1,na2,na3,nb1,nb2,nb3 = \
            sympy.symbols("a1:3, b1:4, na1:4, nb1:4", bool=True)
f = "a1*na2*b1 + a1*a2*nb1*b2 + a1*na2*b1*nb2 + na1*a2*nb1*b2"
sympy.init_printing(use_unicode=True)
sympy.factor(f)

and this returns me the same function, not factored.

a1*a2*b2*nb1 + a1*b1*na2*nb2 + a1*b1*na2 + a2*b2*na1*nb1

What am I doing wrong ?

Body:
Your expected output

f = a1*b1*(b2*nb1 + na2*(nb2 + 1)) + a2*b2*na1*nb1

is not a factorization of f, so factor is not going to produce it. To factor something means to write it as a product, not "a product plus some other stuff".

If you give a polynomial that can actually be factored, say f = a1*na2*b1 + a1*a2*nb1*b2 + a1*na2*b1*nb2, then factor(f) has an effect.

What you are looking for is closer to collecting the terms with the same variable, which is done with collect.

f = a1*na2*b1 + a1*a2*nb1*b2 + a1*na2*b1*nb2 + na1*a2*nb1*b2
collect(f, a1)

outputs

a1*(a2*b2*nb1 + b1*na2*nb2 + b1*na2) + a2*b2*na1*nb1

The method coeff also works in that direction, e.g., f.coeff(a1) returns the contents of the parentheses in the previous formula.


问:
how to perform complete code coverage with selenium web
I am testing a web app based on sencha touch with selenium web driver. My test code is written in Java using testng framework of eclipse.I am using selenium web driver for accessing my web app. Now I want to measure my test code coverage i.e. how much of my js code is hit by the tests. After googling i came to know about istanbul and jSCover but i am not sure they can we used with my tests. Are there any alternative i can use.??

My webapp is running on apache server

答:
By a quick search , I could find out that these are some code coverage tools currently widely used for javascript

```<code>Istanbul
Karma (formerly Testacular)
Blanket.js
JSCover
</code>```

Here is a question and a blog on same topic, you asked.

Mocha with wallaby.js can also be used for code coverage

I think Istanbul can integrate with Sencha applications as is mentioned about Sencha test here.In the link above, have a look at the section "How Sencha Test Can Help You"
and I am quoting from their site

It should be very simple for developers and test automation engineers
  to identify and write tests for Ext JS components.

Body:
By a quick search , I could find out that these are some code coverage tools currently widely used for javascript

Istanbul
Karma (formerly Testacular)
Blanket.js
JSCover

Here is a question and a blog on same topic, you asked.

Mocha with wallaby.js can also be used for code coverage

I think Istanbul can integrate with Sencha applications as is mentioned about Sencha test here.In the link above, have a look at the section "How Sencha Test Can Help You"
and I am quoting from their site

It should be very simple for developers and test automation engineers
  to identify and write tests for Ext JS components.


问:
Android - Firebase Authentication not working with Email/Password setup
So, I have my Firebase project setup, and all plugins that should be needed in the build.gradle (I quintuple checked). However, when I run my app and try to run the following method:

```<code>createUserWithEmailAndPassword(email, password)
</code>```

It does not work and I constantly get something - which I will show below - in the log, and a notification manager popping up saying "Channel not found." I am not using a Notification Manager, but I believe it is done deep within the Android Runtime environment.

This method is called after the user types in the username and password in a GUI, and uses the method above to try to create a connection with my firebase project.

```<code>1-12 01:36:17.181 6593-6593/com.example.sarah.whosthere I/BiChannelGoogleApi: [FirebaseAuth: ] No Fallback module; NOT setting up for lazy initialization
11-12 01:37:50.967 6593-6593/com.example.sarah.whosthere W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms
11-12 01:37:51.140 1681-3474/system_process E/NotificationService: No Channel found for pkg=com.example.sarah.whosthere, channelId=null, id=10436, tag=null, opPkg=com.example.sarah.whosthere, callingUid=10085, userId=0, incomingUserId=0, notificationUid=10085, notification=Notification(channel=null pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x110 color=0x00000000 vis=PRIVATE)
</code>```

Also, in debug mode, during this method call I get a "no such instance field" error for my mAuth variable, which is set to an instance of FirebaseAuth. I tried looking this up, but what I have found and tried does not seem relevant towards my case.

If anyone has any reasons why this method would not be doing anything, I would appreciate the help as I have been banging my head against the wall for the past 4 hours trying to figure this out.

Thanks in advance.

UPDATE I got this working by changing the version from 11.6.0 down to 10.2.6 for all firebase services, including google play.

答: Had the same Issue here, after updating the Google Play Store it works like a charm. I hope it will work for you too</p>

Body:
So, I have my Firebase project setup, and all plugins that should be needed in the build.gradle (I quintuple checked). However, when I run my app and try to run the following method:

createUserWithEmailAndPassword(email, password)

It does not work and I constantly get something - which I will show below - in the log, and a notification manager popping up saying "Channel not found." I am not using a Notification Manager, but I believe it is done deep within the Android Runtime environment.

This method is called after the user types in the username and password in a GUI, and uses the method above to try to create a connection with my firebase project.

1-12 01:36:17.181 6593-6593/com.example.sarah.whosthere I/BiChannelGoogleApi: [FirebaseAuth: ] No Fallback module; NOT setting up for lazy initialization
11-12 01:37:50.967 6593-6593/com.example.sarah.whosthere W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms
11-12 01:37:51.140 1681-3474/system_process E/NotificationService: No Channel found for pkg=com.example.sarah.whosthere, channelId=null, id=10436, tag=null, opPkg=com.example.sarah.whosthere, callingUid=10085, userId=0, incomingUserId=0, notificationUid=10085, notification=Notification(channel=null pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x110 color=0x00000000 vis=PRIVATE)

Also, in debug mode, during this method call I get a "no such instance field" error for my mAuth variable, which is set to an instance of FirebaseAuth. I tried looking this up, but what I have found and tried does not seem relevant towards my case.

If anyone has any reasons why this method would not be doing anything, I would appreciate the help as I have been banging my head against the wall for the past 4 hours trying to figure this out.

Thanks in advance.

UPDATE I got this working by changing the version from 11.6.0 down to 10.2.6 for all firebase services, including google play.


问:
Action<T> Get parameter value
Goal: Pass an Action< T > to a method to be ran. The idea is if the method uses T then we can specify the type we will be passing into the method as a parameter rather than having to use dynamics.

Issue: I'm unable to get the parameter value, what is the best way to do this (most likely using reflection)?

Code:

```<code>public static void RunVoidMethod<T>(Action<T> methodToRun)
{
    try
    {
        // Below is a ParameterInfo, I want the parameter value for methodToRun
        var parameterValue = methodToRun.Method.GetParameters()[0];
        methodToRun(parameterValue);
    }
    catch (Exception e)
    {
        throw;
    }
}
</code>```

The worst case scenario is I can add an optional parameter which can also be of type T but I'm hoping to avoid this if possible.

答:
I don't really understand the purpose of using a delegate this way, but even if you did you can always use the delegate to call the method that takes the parameter instead.

```<code>    static void Main(string[] args)
    {
        PrintTest(() => DelegateTest("Hello"));
    }

    public static void DelegateTest(string test)
    {
        Console.WriteLine(test);
        throw new ArgumentException();
    }
    public static void PrintTest(Action action)
    {
        try
        {
            action.Invoke();
        }
        catch (Exception w)
        {

            throw;
        }
    }
</code>```

Otherwise, there is an article on MSDN that explains how to invoke delegates if the Type isn't known until runtime: https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-hook-up-a-delegate-using-reflection

Title: Action<T> Get parameter value

Body:
Goal: Pass an Action< T > to a method to be ran. The idea is if the method uses T then we can specify the type we will be passing into the method as a parameter rather than having to use dynamics.

Issue: I'm unable to get the parameter value, what is the best way to do this (most likely using reflection)?

Code:

public static void RunVoidMethod<T>(Action<T> methodToRun)
{
    try
    {
        // Below is a ParameterInfo, I want the parameter value for methodToRun
        var parameterValue = methodToRun.Method.GetParameters()[0];
        methodToRun(parameterValue);
    }
    catch (Exception e)
    {
        throw;
    }
}

The worst case scenario is I can add an optional parameter which can also be of type T but I'm hoping to avoid this if possible.

Body:
I don't really understand the purpose of using a delegate this way, but even if you did you can always use the delegate to call the method that takes the parameter instead.

    static void Main(string[] args)
    {
        PrintTest(() => DelegateTest("Hello"));
    }

    public static void DelegateTest(string test)
    {
        Console.WriteLine(test);
        throw new ArgumentException();
    }
    public static void PrintTest(Action action)
    {
        try
        {
            action.Invoke();
        }
        catch (Exception w)
        {

            throw;
        }
    }

Otherwise, there is an article on MSDN that explains how to invoke delegates if the Type isn't known until runtime: https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-hook-up-a-delegate-using-reflection


问:
Execute Select Statement at Cassandra
I have been a problem in Cassandra. Please help me..

I am executing Select statement at 500K rows table at intervals 1 millisecond. After some time I get message "All host(s) tried for query failed. First host tried, 10.1.60.12:9042: Host considered as DOWN. See innerErrors".

I run select statement the fallowing:

```<code>select * from demo.users
</code>```

this returning to me 5K rows. There are 500K rows in the users table.

I don't know what is wrong. I have not changed the cassandra.yaml file.

I need to make settings for the memory cache? There is too much disk i/o when I run select statement.

Please help me

答:
A range query (select * with no primary key or token ranges) can be a very expensive query that has to hit at least 1 of every replica set (depend on size of dataset). If your trying to read the entire dataset or doing batch processing either be best to use spark connector or behave like it, and query individual token ranges to prevent putting too much load on coordinators.

If you are going to be using inefficient queries (which is fine, just don't expect the same throughput as normal reads) you will probably need more resources or some specialized tuning. You could add more nodes or look into whats causing it to go DOWN. Most likely its GCs from heap load, so can check GC log. If you have the memory available you can increase heap. Would be good idea to max heap size since with reading everything, system caches are not going to be as meaningful. Use G1 once over 16gb (which you should be) in the jvm.options.

Title: Execute Select Statement at Cassandra

Body:
I have been a problem in Cassandra. Please help me..

I am executing Select statement at 500K rows table at intervals 1 millisecond. After some time I get message "All host(s) tried for query failed. First host tried, 10.1.60.12:9042: Host considered as DOWN. See innerErrors".

I run select statement the fallowing:

select * from demo.users

this returning to me 5K rows. There are 500K rows in the users table.

I don't know what is wrong. I have not changed the cassandra.yaml file.

I need to make settings for the memory cache? There is too much disk i/o when I run select statement.

Please help me


问:
phpmyadmin - default to structure instead of browse
Can I set the default in phpMyAdmin to open in structure instead of browse?

thanks

答: I was following the instructions from etheros and wasn't able to find that configuration option, but it can just be added (to the confic.inc.php file). In my config file, I added it to the "Left frame setup" section, around line 160.</p>


问:
How to make subcommand required in Go CLI using cobra
I am using Cobra to make some cli updated to my app. I want to make this command required, meaning the application should fail if it doesn't find the argument it is looking for.

```<code>package commands

import (
    "github.com/spf13/cobra"
    "errors"
    "fmt"
)

var (
    Env string
)

var RootCmd = &cobra.Command{
    Use:   "myapp",
    Short: "tool",
    Long:  `tool`,
    Run: func(cmd *cobra.Command, args []string)  {
        // Root command does nothing
    },
}

func init() {
    RootCmd.AddCommand(Environment)
}

var Environment = &cobra.Command{
    Use:   "env",
    Short: "Specify Environment to run against",
    Long: `Can be dev or prod`,
    Args: func(cmd *cobra.Command, args []string) error {
        if len(args) != 1 {
            return errors.New("requires at least one arg")
        }

        if args[0] == "dev" || args[0] == "prod" {
            return nil
        }else {
            return errors.New("input can only be dev or prod")
        }
        return fmt.Errorf("invalid env specified: %s", args[0])
    },
    PreRunE: func(cmd *cobra.Command, args []string) error {
        if len(args) != 1 {
          return fmt.Errorf("env is required")
        }
      return nil
    },
    Run: func(cmd *cobra.Command, args []string) {
        Env = args[0]
    },
}
</code>```

and main package is

```<code>package main

import (
    "fmt"
    "log"
    "os"
    "util"
    "commands"
)

func main() {
    log.Println("Executing")

    if err := commands.RootCmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    log.Println("Executing")
}
</code>```

Now if I run this as ./myApp without any env, it doesn't complain about it. However if I use env after myapp then it activates the function and runs all the validations.

答:
You can just make the body of the function handle it, perhaps by printing help and exiting as non-successful:</p>

```<code>Run: func(cmd *cobra.Command, args []string)  {
    // Root command does nothing
    cmd.Help()
    os.Exit(1)
},
</code>```

Body:
I am using Cobra to make some cli updated to my app. I want to make this command required, meaning the application should fail if it doesn't find the argument it is looking for.

package commands

import (
    "github.com/spf13/cobra"
    "errors"
    "fmt"
)

var (
    Env string
)

var RootCmd = &cobra.Command{
    Use:   "myapp",
    Short: "tool",
    Long:  `tool`,
    Run: func(cmd *cobra.Command, args []string)  {
        // Root command does nothing
    },
}

func init() {
    RootCmd.AddCommand(Environment)
}

var Environment = &cobra.Command{
    Use:   "env",
    Short: "Specify Environment to run against",
    Long: `Can be dev or prod`,
    Args: func(cmd *cobra.Command, args []string) error {
        if len(args) != 1 {
            return errors.New("requires at least one arg")
        }

        if args[0] == "dev" || args[0] == "prod" {
            return nil
        }else {
            return errors.New("input can only be dev or prod")
        }
        return fmt.Errorf("invalid env specified: %s", args[0])
    },
    PreRunE: func(cmd *cobra.Command, args []string) error {
        if len(args) != 1 {
          return fmt.Errorf("env is required")
        }
      return nil
    },
    Run: func(cmd *cobra.Command, args []string) {
        Env = args[0]
    },
}

and main package is

package main

import (
    "fmt"
    "log"
    "os"
    "util"
    "commands"
)

func main() {
    log.Println("Executing")

    if err := commands.RootCmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    log.Println("Executing")
}

Now if I run this as ./myApp without any env, it doesn't complain about it. However if I use env after myapp then it activates the function and runs all the validations.

Body:
You can just make the body of the function handle it, perhaps by printing help and exiting as non-successful:

Run: func(cmd *cobra.Command, args []string)  {
    // Root command does nothing
    cmd.Help()
    os.Exit(1)
},


问:
Run command from C#
Folks,
I have a simple expression that I am able to run by pasting it in the "search program and files" :

"C:\Program Files (x86)\notepad.exe" /BF: "D:\BatchMerge\DcaBatch.bpf"

If I have use the same expression in the C# code, what should I use? I searched on stackflow and found "Process.startinfo". I tried using it as below:

```<code>Process.Start(""C:\Program Files (x86)\notepad.exe" /BF: "D:\BatchMerge\DcaBatch.bpf"");
</code>```

That does not work!

答:
You should separate the executable from the arguments. Look at this overload. So you'd do this instead:</p>

```<code>Process.Start(@"C:\Program Files (x86)\notepad.exe", "/BF: \"D:\\BatchMerge\\DcaBatch.bpf\"");
</code>```

Title: Run command from C#

Body:
Folks,
I have a simple expression that I am able to run by pasting it in the "search program and files" :

"C:\Program Files (x86)\notepad.exe" /BF: "D:\BatchMerge\DcaBatch.bpf"

If I have use the same expression in the C# code, what should I use? I searched on stackflow and found "Process.startinfo". I tried using it as below:

Process.Start(""C:\Program Files (x86)\notepad.exe" /BF: "D:\BatchMerge\DcaBatch.bpf"");

That does not work!

Body:
You should separate the executable from the arguments. Look at this overload. So you'd do this instead:

Process.Start(@"C:\Program Files (x86)\notepad.exe", "/BF: \"D:\\BatchMerge\\DcaBatch.bpf\"");


问:
What are these "none" at the bottom of my output?
Brand new to python. When using the map function in python, i get a series of the word "none" as an output when i run my function. ive added screenshot below.

Code

```<code>def rawGradeToLetter(grade):
   if grade >= 90:
      print ("A")
   elif grade < 90 and grade >= 80:
      print ("B")
   elif grade < 80 and grade >= 70:
      print ("C")
   elif grade < 70 and grade >= 60:
      print ("D")
   elif grade < 60:
      print ("F")

def convertRawsToLetters(myList):
   return list(map(rawGradeToLetter, myList))
</code>```

Example run:

```<code>>>> convertRawsToLetters([90,80,70])
A
B
C
[None, None, None]
</code>```

I have a feeling it has something to do with the word list before the map function, but if I remove that all I get is the address of the map like "map object at 0x8g9b7ea51950".

答:
```<code>def rawGradeToLetter(grade):
    if grade >= 90:
        print ("A")
    elif grade < 90 and grade >= 80:
        print ("B")
    elif grade < 80 and grade >= 70:
        print ("C")
    elif grade < 70 and grade >= 60:
        print ("D")
    elif grade < 60:
        print ("F")

def convertRawsToLetters(myList):
    for grade in myList:
        rawGradeToLetter(grade)
</code>```

I think you are over complicating it by using map() if all you want to do is print the grades.

Body:
Brand new to python. When using the map function in python, i get a series of the word "none" as an output when i run my function. ive added screenshot below.

Code

def rawGradeToLetter(grade):
   if grade >= 90:
      print ("A")
   elif grade < 90 and grade >= 80:
      print ("B")
   elif grade < 80 and grade >= 70:
      print ("C")
   elif grade < 70 and grade >= 60:
      print ("D")
   elif grade < 60:
      print ("F")

def convertRawsToLetters(myList):
   return list(map(rawGradeToLetter, myList))

Example run:

>>> convertRawsToLetters([90,80,70])
A
B
C
[None, None, None]

I have a feeling it has something to do with the word list before the map function, but if I remove that all I get is the address of the map like "map object at 0x8g9b7ea51950".

Body:
def rawGradeToLetter(grade):
    if grade >= 90:
        print ("A")
    elif grade < 90 and grade >= 80:
        print ("B")
    elif grade < 80 and grade >= 70:
        print ("C")
    elif grade < 70 and grade >= 60:
        print ("D")
    elif grade < 60:
        print ("F")

def convertRawsToLetters(myList):
    for grade in myList:
        rawGradeToLetter(grade)

I think you are over complicating it by using map() if all you want to do is print the grades.


问:
Fatal Exception: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}
I am seeing this error in a live app thus I have no clue why this happening. All I have is this exception log (see below).
At first, I thought I applied style editTextBackgroungWhite(see below)to the editText inside my XML but removing it has no effect on the problem.

I'll be glad if someone could guide me towards the right direction.

P.S I am not able to replicate this bug on my device seems that it's a problem with some Samsung note series device only.

```<code> <style name="editTextBackgWhite"parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorControlNormal">#ffffff</item>
    <item name="colorControlActivated">#ffffff</item>
    <item name="colorControlHighlight">#ffffff</item>
</style>

Fatal Exception: java.lang.UnsupportedOperationException: Failed to     resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}
   at android.content.res.TypedArray.getColorStateList(TypedArray.java:484)
   at android.text.style.TextAppearanceSpan.(TextAppearanceSpan.java)
   at android.text.style.TextAppearanceSpan.(TextAppearanceSpan.java)
   at android.widget.Editor$SuggestionsPopupWindow$SuggestionInfo.(Editor.java)
   at android.widget.Editor$SuggestionsPopupWindow$SuggestionInfo.(Editor.java)
   at android.widget.Editor$SuggestionsPopupWindow.initContentView(Editor.java:2995)
   at android.widget.Editor$PinnedPopupWindow.(Editor.java)
   at android.widget.Editor$SuggestionsPopupWindow.(Editor.java)
   at android.widget.Editor.showSuggestions(Editor.java:2229)
   at android.widget.Editor$2.run(Editor.java:2109)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:158)
   at android.app.ActivityThread.main(ActivityThread.java:7225)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

答:
according to the answer of @Abhinav Pawar, I used

android:inputType="textAutoCorrect"

instead of

android:inputType="textNoSuggestions"

In fact, textNoSuggestions remove all suggested words by the keyboard at typing. While textAutoCorrect replace the wrong word by the good one. And the user is free to use the one he wants.

Body:
I am seeing this error in a live app thus I have no clue why this happening. All I have is this exception log (see below).
At first, I thought I applied style editTextBackgroungWhite(see below)to the editText inside my XML but removing it has no effect on the problem.

I'll be glad if someone could guide me towards the right direction.

P.S I am not able to replicate this bug on my device seems that it's a problem with some Samsung note series device only.

Fatal Exception: java.lang.UnsupportedOperationException: Failed to     resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}
   at android.content.res.TypedArray.getColorStateList(TypedArray.java:484)
   at android.text.style.TextAppearanceSpan.(TextAppearanceSpan.java)
   at android.text.style.TextAppearanceSpan.(TextAppearanceSpan.java)
   at android.widget.Editor$SuggestionsPopupWindow$SuggestionInfo.(Editor.java)
   at android.widget.Editor$SuggestionsPopupWindow$SuggestionInfo.(Editor.java)
   at android.widget.Editor$SuggestionsPopupWindow.initContentView(Editor.java:2995)
   at android.widget.Editor$PinnedPopupWindow.(Editor.java)
   at android.widget.Editor$SuggestionsPopupWindow.(Editor.java)
   at android.widget.Editor.showSuggestions(Editor.java:2229)
   at android.widget.Editor$2.run(Editor.java:2109)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:158)
   at android.app.ActivityThread.main(ActivityThread.java:7225)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)