问:
Change uib-modal size dynamically
I was wondering the best way, if possible to change the size of a uibootsrap modal on the fly. I have implemented a paging of sorts where within the same modal body, if the user presses a 'next' button in the footer of the modal, it will load in another template, like so:

```<code><div id="rule-values-page"
    ng-show="rcw.page ==='Rule Values'">

    <first-template-values ng-show="rcw.provider=== 'First Template'"
        rule-fields="rcw.fields"></first-template-values>

    <second-template-values ng-show="rcw.provider === 'Second Template'"
        rule-fields="rcw.fields"></second-template-values>

    <third-template-values ng-show="rcw.provider=== 'Third Template'"
        rule-fields="rcw.fields"></third-template-values>

</div>
</code>```

There is some JavaScript behind the scenes that determines what happens when the next button is clicked (above is just an approximation of what it looks like).
When I launch the original modal that contains a previous page which leads to this one, I use

```<code>var ruleModalTemplate = {
        templateUrl: 'app/indicator/rule-create-wizard.html',
        backdrop: 'static',
        controller: 'ruleCreateWizard',
        controllerAs: 'rcw',
        windowClass: 'app-modal-window',
        resolve: {
          ruleCreateWizardControllerInput: function() {
            return {
              name: vm.name,
              desc: vm.description
            };
          }
        }
      };
</code>```

The key here being windowClass as you can set the size to whatever you want there sm, lg, or custom like I have. Now the issue I have is the size is okay for some of the subsequent pages, but looks silly for other pages. I want to be able to control the size whenever. Would this be done by applying an ng-class or something to the modal body? Any help is appreciated.

EDIT: So I went down the ng-class route and am having some trouble. I tried to apply the ng-class to the template being called from the previous directive 'app/indicator/rule-create-wizard.html' like so:

```<code><div id="rule-create-wizard"
    ng-form="ruleFormMaster"
    ng-class="rcw.modalSize()">
    ...
</div>
</code>```

and let the decision of what class to be applied to in the method modalSize() method which looks as :

```<code>function modalSize() {
  switch (vm.page) {
    case 'Rule Provider Selection':
      return 'app-modal-window-sm';
      break;
    case 'Rule Selection':
      console.debug('in rule selection modal size method');
      return 'app-modal-window-lg';
      break;
  }
}
</code>```

just returning the string of the css class :

```<code>.app-modal-window-lg .modal-dialog {
  width: 65%;
}

.app-modal-window-sm .modal-dialog {
  width: 20%;
}
</code>```

The issue is that it isn't applying it to the modal, because the directive for the modal doesn't actually have access (i believe) to the root instance of the html of the modal. See picture below:

It is applying it I correctly (though not where I thought) to the template, but not the actual modal. If I were to use the default values for uibootstrap inside of the calling directive windowClass: sm etc that appears in the correct location (blue arrow in the pic) but not in the highlighted location.

Still looking for input - thanks!

答:
Okay so after some comparison to some regular bootstrap (non-angular) modal questions, I found using jquery provided a simple solution. Might not be the most optimized but works for the use case.

Also keep in mind, if you are looking for a similar this isn't necessarily the best (if good at all) ux, just fit the requirements I was working with.

Anyways, I passed in a dummy class that was for sure to be unique into the windowClass parameter of the uib-modal - in my case app-dummy as well as my initial class in which I wanted to apply to the modal app-modal-window-md:

```<code>  var ruleModalTemplate = {
    templateUrl: 'app/indicator/rule-create-wizard.html',
    backdrop: 'static',
    controller: 'ruleCreateWizard',
    controllerAs: 'rcw',
    windowClass: 'app-dummy app-modal-window-md',
    resolve: {
      ruleCreateWizardControllerInput: function() {
        return {
          name: vm.name,
          desc: vm.description
        };
      }
    }
  };
</code>```

Then I created a resize() method which would get called during the page changes inside of the modal:

```<code>function resize() {
  switch (vm.page) {
    case 'Rule Provider Selection':
      $('.app-dummy .modal-dialog ')
        .css({
          'width': '30%'
        });
      break;
    case 'Rule Selection':
      var test = $('.app-dummy .modal-dialog ')
        .css({
          'width': '40%'
        });
      break;
    case 'Rule Values':
      $('.app-dummy .modal-dialog')
        .css({ 'width': '70%' })
      break;
  }
}
</code>```

The JQuery targets the app-dummy class each time on page change and depending on the page will apply the width. My needs weren't too complex so this could be more robust, but for the question being asked this was my solution.

Title: Change uib-modal size dynamically

Body:
I was wondering the best way, if possible to change the size of a uibootsrap modal on the fly. I have implemented a paging of sorts where within the same modal body, if the user presses a 'next' button in the footer of the modal, it will load in another template, like so:

    <first-template-values ng-show="rcw.provider=== 'First Template'"
        rule-fields="rcw.fields"></first-template-values>

    <second-template-values ng-show="rcw.provider === 'Second Template'"
        rule-fields="rcw.fields"></second-template-values>

    <third-template-values ng-show="rcw.provider=== 'Third Template'"
        rule-fields="rcw.fields"></third-template-values>

There is some JavaScript behind the scenes that determines what happens when the next button is clicked (above is just an approximation of what it looks like).
When I launch the original modal that contains a previous page which leads to this one, I use

var ruleModalTemplate = {
        templateUrl: 'app/indicator/rule-create-wizard.html',
        backdrop: 'static',
        controller: 'ruleCreateWizard',
        controllerAs: 'rcw',
        windowClass: 'app-modal-window',
        resolve: {
          ruleCreateWizardControllerInput: function() {
            return {
              name: vm.name,
              desc: vm.description
            };
          }
        }
      };

The key here being windowClass as you can set the size to whatever you want there sm, lg, or custom like I have. Now the issue I have is the size is okay for some of the subsequent pages, but looks silly for other pages. I want to be able to control the size whenever. Would this be done by applying an ng-class or something to the modal body? Any help is appreciated.

EDIT: So I went down the ng-class route and am having some trouble. I tried to apply the ng-class to the template being called from the previous directive 'app/indicator/rule-create-wizard.html' like so:

    ...

and let the decision of what class to be applied to in the method modalSize() method which looks as :

function modalSize() {
  switch (vm.page) {
    case 'Rule Provider Selection':
      return 'app-modal-window-sm';
      break;
    case 'Rule Selection':
      console.debug('in rule selection modal size method');
      return 'app-modal-window-lg';
      break;
  }
}

just returning the string of the css class :

.app-modal-window-lg .modal-dialog {
  width: 65%;
}

.app-modal-window-sm .modal-dialog {
  width: 20%;
}

The issue is that it isn't applying it to the modal, because the directive for the modal doesn't actually have access (i believe) to the root instance of the html of the modal. See picture below:

It is applying it I correctly (though not where I thought) to the template, but not the actual modal. If I were to use the default values for uibootstrap inside of the calling directive windowClass: sm etc that appears in the correct location (blue arrow in the pic) but not in the highlighted location.

Still looking for input - thanks!

Body:
Okay so after some comparison to some regular bootstrap (non-angular) modal questions, I found using jquery provided a simple solution. Might not be the most optimized but works for the use case.

Also keep in mind, if you are looking for a similar this isn't necessarily the best (if good at all) ux, just fit the requirements I was working with.

Anyways, I passed in a dummy class that was for sure to be unique into the windowClass parameter of the uib-modal - in my case app-dummy as well as my initial class in which I wanted to apply to the modal app-modal-window-md:

  var ruleModalTemplate = {
    templateUrl: 'app/indicator/rule-create-wizard.html',
    backdrop: 'static',
    controller: 'ruleCreateWizard',
    controllerAs: 'rcw',
    windowClass: 'app-dummy app-modal-window-md',
    resolve: {
      ruleCreateWizardControllerInput: function() {
        return {
          name: vm.name,
          desc: vm.description
        };
      }
    }
  };

Then I created a resize() method which would get called during the page changes inside of the modal:

function resize() {
  switch (vm.page) {
    case 'Rule Provider Selection':
      $('.app-dummy .modal-dialog ')
        .css({
          'width': '30%'
        });
      break;
    case 'Rule Selection':
      var test = $('.app-dummy .modal-dialog ')
        .css({
          'width': '40%'
        });
      break;
    case 'Rule Values':
      $('.app-dummy .modal-dialog')
        .css({ 'width': '70%' })
      break;
  }
}

The JQuery targets the app-dummy class each time on page change and depending on the page will apply the width. My needs weren't too complex so this could be more robust, but for the question being asked this was my solution.


来源: stackexchange

问:
What is the simplest way in C++98 to get and continue to call a class method, the type of which the current class does not know?
Example:
Suppose we are developing a simple graphical interface:

We have windows and controls. What do we want:

There is a base window class that implements the GUI functionality
hidden from the user.

From the base window, the user inherits a specific window.

There is a class of a button, an instance of which the user can add to his window.

The user can transfer the method of his window to button, and it will be executed when clicking this button.

I'm interested in how to reach the last point.

Kind of pseudo-code:

```<code>class BaseWindow;

class Button
{
public:
            Button(BaseWindow* parent)
            {
                        parent->AddButton(this);
            }

            void SetBehavior(/*Owners pointer and owner's methos*/)
            {
                        /* Save Owner pointer and owner's method*/
            }

            void Clicked(/*coords*/)
            {
                        if(/*coords == my coords*/)
                        {
                                    /*Call Owner's method*/
                        }
            }
};

class BaseWindow
{
            vector<Button*> Buttons;

            WindowClicked(/*coords*/)
            {
                    for (std::vector<Button*>::iterator it = Buttons.begin(); it != Buttons.end(); ++it)
                    {
                                it->Clicked(/*coords*/);
                    }
            }

public:
            void AddButton(Button* butt)
            {
                            Buttons<<butt;
            }

};

class UserWindow:public BaseWindow
{
            Button MyButton;
public:
            void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";}

            UserWindow():MyButton(this)
            {
                        MyButton.SetBehavior(/*Put here my Function for Button and my pointer*/);
            }
};
</code>```

答:
Use a std::function<ReturnCode(Args...)>.

Suppose you have a UI context struct:

```<code>struct UI_context {
  mouse_position mouse;
  keyboard_state keyboard;
};
</code>```

And suppose the button supports a few kinds of actions:

```<code>struct button_trigger {
  bool click;
  bool enter;
  bool touch;
  bool pen;
};
</code>```

and there are a few things you can ask the button to do:

```<code>struct click_result {
  bool toggle;
  bool flash;
  bool wiggle;
};
</code>```

then you'd store a std::function< click_result( button_trigger, UI_context ) >.

Of course, a std::function<void()> might be all you want.  Or a std::function<void(mouse_location)>.

Anything with an operator() that is compatible with the signature you provide std::function will work.  A function pointer or a lambda are the two most common.

You may want to add a way to register and remove callbacks, and/or have a token system.

ContentLicense: CC BY-SA 3.0

Body:
Example:
Suppose we are developing a simple graphical interface:

We have windows and controls. What do we want:

There is a base window class that implements the GUI functionality
hidden from the user.

From the base window, the user inherits a specific window.

There is a class of a button, an instance of which the user can add to his window.

The user can transfer the method of his window to button, and it will be executed when clicking this button.

I'm interested in how to reach the last point.

Kind of pseudo-code:

class BaseWindow;

class Button
{
public:
            Button(BaseWindow* parent)
            {
                        parent->AddButton(this);
            }

            void SetBehavior(/*Owners pointer and owner's methos*/)
            {
                        /* Save Owner pointer and owner's method*/
            }

            void Clicked(/*coords*/)
            {
                        if(/*coords == my coords*/)
                        {
                                    /*Call Owner's method*/
                        }
            }
};

class BaseWindow
{
            vector<Button*> Buttons;

            WindowClicked(/*coords*/)
            {
                    for (std::vector<Button*>::iterator it = Buttons.begin(); it != Buttons.end(); ++it)
                    {
                                it->Clicked(/*coords*/);
                    }
            }

public:
            void AddButton(Button* butt)
            {
                            Buttons<<butt;
            }

};

class UserWindow:public BaseWindow
{
            Button MyButton;
public:
            void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";}

            UserWindow():MyButton(this)
            {
                        MyButton.SetBehavior(/*Put here my Function for Button and my pointer*/);
            }
};

Body:
Use a std::function<ReturnCode(Args...)>.

Suppose you have a UI context struct:

struct UI_context {
  mouse_position mouse;
  keyboard_state keyboard;
};

And suppose the button supports a few kinds of actions:

struct button_trigger {
  bool click;
  bool enter;
  bool touch;
  bool pen;
};

and there are a few things you can ask the button to do:

struct click_result {
  bool toggle;
  bool flash;
  bool wiggle;
};

then you'd store a std::function< click_result( button_trigger, UI_context ) >.

Of course, a std::function<void()> might be all you want.  Or a std::function<void(mouse_location)>.

Anything with an operator() that is compatible with the signature you provide std::function will work.  A function pointer or a lambda are the two most common.

You may want to add a way to register and remove callbacks, and/or have a token system.


问:
Filter Queryset on empty ImageField
I have the following class:

```<code>class Book(models.Model):
    picture = models.ImageField(upload_to='books/', blank=True, null=True)
    ...
</code>```

I now want to filter the books without a picture. I tried the following:

```<code>Book.objects.filter(picture__isnull=True)
</code>```

The problem is, that the picture is an empty varchar ('') in the db and not null. What to do?

答:
Just run the exclude method:

```<code>Books.objects.exclude(picture='')
</code>```

Title: Filter Queryset on empty ImageField

Body:
I have the following class:

class Book(models.Model):
    picture = models.ImageField(upload_to='books/', blank=True, null=True)
    ...

I now want to filter the books without a picture. I tried the following:

Book.objects.filter(picture__isnull=True)

The problem is, that the picture is an empty varchar ('') in the db and not null. What to do?

Body:
Just run the exclude method:

Books.objects.exclude(picture='')


问:
R: Sum columns based on match table, merging column names
I have a data frame like this (where the letters are column names):

```<code>a   b   c   B   C   A
1   2   3   6   7   8
1   2   3   6   7   8
1   2   3   6   7   8
1   2   3   6   7   8
</code>```

And I would like to sum the columns based on this match table:

```<code>a   A
b   B
c   C
</code>```

While also merging the column names, so that the result would be:

```<code>a/A b/B c/C
9   8   10
9   8   10
9   8   10
9   8   10
</code>```

Please keep in mind that the solution need to be applicable to large data frames, so I cannot be specifying the new column names manually.

Thanks a lot!

答:
You could do this:

```<code>res <- apply(df.match, 1, function(x) rowSums(df[,c(x[1], x[2])]))
colnames(res) <- paste0(df.match[,1], "/", df.match[,2])

#     a/A    b/B   c/C
#[1,]    9    8   10
#[2,]    9    8   10
#[3,]    9    8   10
#[4,]    9    8   10
#[5,]    9    8   10
</code>```

where df is your data frame and df.match is your matched col-names.

Body:
I have a data frame like this (where the letters are column names):

a   b   c   B   C   A
1   2   3   6   7   8
1   2   3   6   7   8
1   2   3   6   7   8
1   2   3   6   7   8

And I would like to sum the columns based on this match table:

a   A
b   B
c   C

While also merging the column names, so that the result would be:

a/A b/B c/C
9   8   10
9   8   10
9   8   10
9   8   10

Please keep in mind that the solution need to be applicable to large data frames, so I cannot be specifying the new column names manually.

Thanks a lot!

Body:
You could do this:

res <- apply(df.match, 1, function(x) rowSums(df[,c(x[1], x[2])]))
colnames(res) <- paste0(df.match[,1], "/", df.match[,2])

#     a/A    b/B   c/C
#[1,]    9    8   10
#[2,]    9    8   10
#[3,]    9    8   10
#[4,]    9    8   10
#[5,]    9    8   10

where df is your data frame and df.match is your matched col-names.


问:
ExtJS auto-resize form
I'm using Extjs5 and I have a form where I wish it to be auto resize according to it's container.

Currently, I have:

container->items->layout:vbox->items->layout:{type:column,columns:2}->items->my forms(consist of comboboxes and textfields)

when I resize to a small width, I wish it to be one column. Currently it will remain 2 columns and the space will be too small to fit 2 column design. Is there a way to resize it to 1 column?

答:
If you want to achieve this with a column layout, you can listen for the resize event and adjust the column percentages in the handler function.  The handler function could look like:

```<code>formResize = function (item, width, height, oldWidth, oldHeight, eOpts) {
    if (!item.narrow) return;
    if (oldWidth === undefined) oldWidth = 9999999;
    if (oldHeight === undefined) oldHeight = 9999999;
    item.suspendLayouts();
    if (width <= item.narrow && oldWidth > item.narrow) {
        item.items.each(function (item, i) {
            if (!item.originalColumnWidth) item.originalColumnWidth = item.columnWidth;
            item.columnWidth = 1;
        });
    }
    if (width > item.narrow && oldWidth <= item.narrow) {
        item.items.each(function (item, i) {
            item.columnWidth = item.originalColumnWidth;
        });
    }
    item.resumeLayouts(true);
};
</code>```

This requires a property called narrow to be defined on the panel that is being adjusted.  You could set narrow=700 to use a single column layout when the width is less than 700 and keep the original layout otherwise.  The originalColumnWidth is saved on the first execution so it can be restored if the form is resized to be wide enough for multiple columns.

See fiddle here with an example form.

(A similar result can be achieved using the responsive plugin.  See fiddle).

Title: ExtJS auto-resize form

Body:
If you want to achieve this with a column layout, you can listen for the resize event and adjust the column percentages in the handler function.  The handler function could look like:

formResize = function (item, width, height, oldWidth, oldHeight, eOpts) {
    if (!item.narrow) return;
    if (oldWidth === undefined) oldWidth = 9999999;
    if (oldHeight === undefined) oldHeight = 9999999;
    item.suspendLayouts();
    if (width <= item.narrow && oldWidth > item.narrow) {
        item.items.each(function (item, i) {
            if (!item.originalColumnWidth) item.originalColumnWidth = item.columnWidth;
            item.columnWidth = 1;
        });
    }
    if (width > item.narrow && oldWidth <= item.narrow) {
        item.items.each(function (item, i) {
            item.columnWidth = item.originalColumnWidth;
        });
    }
    item.resumeLayouts(true);
};

This requires a property called narrow to be defined on the panel that is being adjusted.  You could set narrow=700 to use a single column layout when the width is less than 700 and keep the original layout otherwise.  The originalColumnWidth is saved on the first execution so it can be restored if the form is resized to be wide enough for multiple columns.

See fiddle here with an example form.

(A similar result can be achieved using the responsive plugin.  See fiddle).


问:
invalid argument supplied for foreach
I am parsing XML in PHP code and getting a warning "invalid argument supplied for foreach".
Below is the XML:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<BookStore>
    <book>
        <title>Computer Concepts</title>
        <auther>Goerge Arthar</auther>
        <category>Computer Science</category>
        <price>24.00</price>
    </book>
    <book>
        <title>Algebra</title>
        <auther>Mike</auther>
        <category>Mathematics</category>
        <price>34.00</price>
    </book>
</BookStore>
</code>```

and using the following code:

```<code><?php
$xmlDOM = new DOMDocument();
$xmlDOM->load("Books.xml");
$document = $xmlDOM->documentElement;
foreach ($document->childNodes as $node) {
    foreach($node->childNodes as $temp) {
        echo $temp->nodeName."=".$temp->nodeValue."<br />";
    }
}
?>
</code>```

NOTE: I get the output that I require but with a warning. It shows that array is not empty.
Please see output also:

```<code>Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Computer Concepts
#text=
auther=Goerge Arthar
#text=
category=Computer Science
#text=
price=24.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Algebra
#text=
auther=Mike
#text=
category=Mathematics
#text=
price=34.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
</code>```

答:
```<code>foreach ($document->childNodes as $node) {
    if ($node->hasChildNodes()) {
        foreach($node->childNodes as $temp) {
            echo $temp->nodeName."=".$temp->nodeValue."<br />";
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: invalid argument supplied for foreach

Body:
I am parsing XML in PHP code and getting a warning "invalid argument supplied for foreach".
Below is the XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<BookStore>
    <book>
        <title>Computer Concepts</title>
        <auther>Goerge Arthar</auther>
        <category>Computer Science</category>
        <price>24.00</price>
    </book>
    <book>
        <title>Algebra</title>
        <auther>Mike</auther>
        <category>Mathematics</category>
        <price>34.00</price>
    </book>
</BookStore>

and using the following code:

<?php
$xmlDOM = new DOMDocument();
$xmlDOM->load("Books.xml");
$document = $xmlDOM->documentElement;
foreach ($document->childNodes as $node) {
    foreach($node->childNodes as $temp) {
        echo $temp->nodeName."=".$temp->nodeValue."
";
    }
}
?>

NOTE: I get the output that I require but with a warning. It shows that array is not empty.
Please see output also:

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Computer Concepts
#text=
auther=Goerge Arthar
#text=
category=Computer Science
#text=
price=24.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Algebra
#text=
auther=Mike
#text=
category=Mathematics
#text=
price=34.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8


问:
Dynamically create a tuple with all the same type and a known number of elements
I am looking to dynamically create tuples of a given size that have all the same type.

So if I wanted a tuple of strings of size three I would get Tuple<string, string, string>

I have tried both to pass strings into the angle brackets for Tuple like this:

```<code>string foo = "string, string, string";
Tuple<foo> testTuple = Tuple<foo>(~parameters~);
</code>```

and to pass an array of types into the angle brackets like this:

```<code>List<Type> types = new List<Type>() {"".GetType(), "".GetType(), "".GetType()};
Tuple<types> testTuple = Tuple<foo>(~parameters~);
</code>```

Neither one of these worked. Does anyone know how to make the described dynamic tuples?

(The reason I want to do this is to use tuples inside of a dictionary like

```<code>Dictionary<Tuple<# strings>, int> testDictionary = new Dictionary<Tuple<x # strings>, int>();
</code>```

Using tuples here is more useful than HashSets because the comparison in tuples is by components instead of by reference so that if I have

```<code>Tuple<string, string> testTuple1 = new Tuple<string, string>("yes", "no");
Tuple<string, string> testTuple2 = new Tuple<string, string>("yes", "no");
Dictionary<Tuple<string, string>, string> testDictionary = new Dictionary<Tuple<string, string>, string>() {
    {testTuple1, "maybe"}
};
Console.WriteLine(testDict[testTuple2]);
</code>```

it writes "maybe". If you run this same test with HashSets, it throws an error. If there is a better way to accomplish this same thing, that would also be useful.)

答:
Make custom type with List<string> inside (or List<T> if you want generic solution)

Override object.Equals: Use Enumerable.SequenceEqual for inner list in your custom class

Override object.GetHashCode() in order to use your type in dictionary

Body:
I am looking to dynamically create tuples of a given size that have all the same type.

So if I wanted a tuple of strings of size three I would get Tuple<string, string, string>

I have tried both to pass strings into the angle brackets for Tuple like this:

string foo = "string, string, string";
Tuple<foo> testTuple = Tuple<foo>(~parameters~);

and to pass an array of types into the angle brackets like this:

List<Type> types = new List<Type>() {"".GetType(), "".GetType(), "".GetType()};
Tuple<types> testTuple = Tuple<foo>(~parameters~);

Neither one of these worked. Does anyone know how to make the described dynamic tuples?

(The reason I want to do this is to use tuples inside of a dictionary like

Dictionary<Tuple<# strings>, int> testDictionary = new Dictionary<Tuple<x # strings>, int>();

Using tuples here is more useful than HashSets because the comparison in tuples is by components instead of by reference so that if I have

Tuple<string, string> testTuple1 = new Tuple<string, string>("yes", "no");
Tuple<string, string> testTuple2 = new Tuple<string, string>("yes", "no");
Dictionary<Tuple<string, string>, string> testDictionary = new Dictionary<Tuple<string, string>, string>() {
    {testTuple1, "maybe"}
};
Console.WriteLine(testDict[testTuple2]);

it writes "maybe". If you run this same test with HashSets, it throws an error. If there is a better way to accomplish this same thing, that would also be useful.)


问:
Preprocessing messages in queue on rabbitmq broker
Is it possible to do some preprocessing messages on broker of rabbitmq ?

The thing that I would like to do is:

```<code>0. Let assume that that we catch message at the while before it was published to queue.
1. This message is string (by assumption)
2. preprocess message and split it to many messages by some delimiter (`,`)
3. Publish to queue many messages instead of one
</code>```

Is it possible to do it  ?   I wouldn't like to split message before publishing because I concat many messages to reduce IO (I would like to reduce TCP packets, headers overcome and so on).

答:
I've never heard of processing a message on the broker side in Rabbit MQ. Since a broker in Rabbit MQ is a "virtual entity" I'm not sure its possible to do so.

If if its possible, I'm not sure that introducing a business logic to the broker sounds like a good idea - but its only my subjective opinion of course.

In any case maybe you should consider saving up the traffic by changing the protocol:
Store everthing you need in some storage (like redis or aerospike) which is supposed to be super fast along with ID. In Rabbit MQ just send the message with ID that will be stored in that Redis along with the message.

Hope you'll find this useful

Body:
Is it possible to do some preprocessing messages on broker of rabbitmq ?

The thing that I would like to do is:

0. Let assume that that we catch message at the while before it was published to queue.
1. This message is string (by assumption)
2. preprocess message and split it to many messages by some delimiter (`,`)
3. Publish to queue many messages instead of one

Is it possible to do it  ?   I wouldn't like to split message before publishing because I concat many messages to reduce IO (I would like to reduce TCP packets, headers overcome and so on).


问:
Facebook like wall
I would like to know if someone knows about a already open source api for a facebook like wall?</p>

答: If you mean a list of recent posts, then you just get the data from the database and display it in a "wall-like" way.</p>

Title: Facebook like wall


问:
Redshift JDBC connection fails authentication when user password with # character in it
I've run into a problem with JDBC connections to Redshift that I can't quite solve.  Using the example given in the documentation I can easily connect to a Redshift cluster when a user has a plain password, but when a user has a password with a # character in it I get an authentication failure.  I am able to connect to the cluster using SQL Workbench/J using both sets of credentials.  When I use the following, no connection problem.

```<code>        DriverManager.setLoginTimeout(60);
        Properties props = new Properties();
        props.setProperty("user", "johndoe");
        props.setProperty("password", "superSecret");
        props.setProperty("tcpKeepAlive", "true");

        Connection connection = DriverManager.getConnection("jdbc:redshift://xxxxxxx.us-east-1.redshift.amazonaws.com:5439/dev", props);
</code>```

When I use the following,

```<code>        DriverManager.setLoginTimeout(60);
        Properties props = new Properties();
        props.setProperty("user", "johndoehash");
        props.setProperty("password", "superDouble#Secret");
        props.setProperty("tcpKeepAlive", "true");

        Connection connection = DriverManager.getConnection("jdbc:redshift://xxxxxxx.us-east-1.redshift.amazonaws.com:5439/dev", props);
</code>```

I get the an authentication error

```<code>java.sql.SQLException: [Amazon](500310) Invalid operation: password authentication failed for user "johndoehash";
  at com.amazon.redshift.client.messages.inbound.ErrorResponse.toErrorException(ErrorResponse.java:1830)
  at com.amazon.redshift.client.InboundDataHandler.read(InboundDataHandler.java:454)
  at com.amazon.support.channels.AbstractSocketChannel.readCallback(Unknown Source)
  at com.amazon.support.channels.PlainSocketChannel.read(Unknown Source)
Caused by: com.amazon.support.exceptions.ErrorException: [Amazon](500310) Invalid operation: password authentication failed for user "johndoehash";
</code>```

I can log onto the cluster with both accounts using SQL Workbench/J but for some reason I can't connect through my application.  Any ideas on what I'm doing wrong?

答:
This is really odd but if I use a year old version of Java 8 with my application

```<code>java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)
</code>```

The problem goes away ...  Go figure.

Body:
I've run into a problem with JDBC connections to Redshift that I can't quite solve.  Using the example given in the documentation I can easily connect to a Redshift cluster when a user has a plain password, but when a user has a password with a # character in it I get an authentication failure.  I am able to connect to the cluster using SQL Workbench/J using both sets of credentials.  When I use the following, no connection problem.

        DriverManager.setLoginTimeout(60);
        Properties props = new Properties();
        props.setProperty("user", "johndoe");
        props.setProperty("password", "superSecret");
        props.setProperty("tcpKeepAlive", "true");

        Connection connection = DriverManager.getConnection("jdbc:redshift://xxxxxxx.us-east-1.redshift.amazonaws.com:5439/dev", props);

When I use the following,

        DriverManager.setLoginTimeout(60);
        Properties props = new Properties();
        props.setProperty("user", "johndoehash");
        props.setProperty("password", "superDouble#Secret");
        props.setProperty("tcpKeepAlive", "true");

        Connection connection = DriverManager.getConnection("jdbc:redshift://xxxxxxx.us-east-1.redshift.amazonaws.com:5439/dev", props);

I get the an authentication error

java.sql.SQLException: [Amazon](500310) Invalid operation: password authentication failed for user "johndoehash";
  at com.amazon.redshift.client.messages.inbound.ErrorResponse.toErrorException(ErrorResponse.java:1830)
  at com.amazon.redshift.client.InboundDataHandler.read(InboundDataHandler.java:454)
  at com.amazon.support.channels.AbstractSocketChannel.readCallback(Unknown Source)
  at com.amazon.support.channels.PlainSocketChannel.read(Unknown Source)
Caused by: com.amazon.support.exceptions.ErrorException: [Amazon](500310) Invalid operation: password authentication failed for user "johndoehash";

I can log onto the cluster with both accounts using SQL Workbench/J but for some reason I can't connect through my application.  Any ideas on what I'm doing wrong?

Body:
This is really odd but if I use a year old version of Java 8 with my application

java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)

The problem goes away ...  Go figure.


问:
Is having a lot of render methods within a components bad practice?
I had written a component and there are some other instances of small components within that components. Is it a bad practice to use a renderxxx for each instance? thank you</p>

答:
It depends. If you are using some kind of logic for rendering your components, then you should go with dedicated renderX methods. But if all you are doing is to return the components, you should simply describe it with JSX.

Without logic

```<code>const MyComponent = ({ options }) => (
  <div>
    <SelectList options={options} />
  </div>
);
</code>```

With logic

```<code>const MyComponent = ({ options }) => {
  const renderOptions = () => {
    if (options.length < 5) {
      return <RadioButtonGroup options={options} />;
    }

    return <SelectList options={options} />;
  };

  return (
    <div>
      {renderOptions()}
    </div>
  );
};
</code>```

Another approch would be wrapping another component around every renderX method.

```<code>const OptionsRenderer = ({ options }) => {
  if (options.length < 5) {
    return <RadioButtonGroup options={options} />;
  }

  return <SelectList options={options} />;
};

const MyComponent = ({ options }) => (
  <div>
    <OptionsRenderer options={options} />
  </div>
);
</code>```

Body:
It depends. If you are using some kind of logic for rendering your components, then you should go with dedicated renderX methods. But if all you are doing is to return the components, you should simply describe it with JSX.

Without logic

const MyComponent = ({ options }) => (
  <div>
    <SelectList options={options} />
  </div>
);

With logic

const MyComponent = ({ options }) => {
  const renderOptions = () => {
    if (options.length < 5) {
      return <RadioButtonGroup options={options} />;
    }

    return <SelectList options={options} />;
  };

  return (
    <div>
      {renderOptions()}
    </div>
  );
};

Another approch would be wrapping another component around every renderX method.

const OptionsRenderer = ({ options }) => {
  if (options.length < 5) {
    return <RadioButtonGroup options={options} />;
  }

  return <SelectList options={options} />;
};

const MyComponent = ({ options }) => (
  <div>
    <OptionsRenderer options={options} />
  </div>
);


问:
Bookmarkable GET link with Express
I have a website that uses Express to serve pages. Currently it works fine with a form that uses a POST query to populate the page with data, ajax-style.

I'd like the page and its contents to be bookmarkable, so I'm trying to convert this to GET. However I'm running into this problem:

The GET form works fine if I load the root page, fill out the form, and submit. However if I use the bookmark, all I get is the object as plain text.

I understand why this is happening. I don't understand what the right thing to do is to fix it. It doesn't appear that I can send both index.html and the object at the same time.

My server code:

```<code>app.get("/", function (request, response) {
  response.sendFile(__dirname + '/views/index.html');
});

app.post("/formpg", main);

app.get("/formpg", main);

function main(request, response) {
  var params = request.query;
  // * and a miracle occurs *
  response.send({data:miracle});
}
</code>```

答:
Your question is poorly formed, but if I understand it you have a bookmark to the same place as the form submit occurs (/formpg): this will obviously return the same data the form post returns, which is the raw json (or the object as plain text).

What you're going to need to do is make the bookmark point to /?param1=xxxx&param2=xxxxx so it loads the HTML page, and then either parse the request query and inject the appropriate data into the page, or use JS in the views/index.html page to autosubmit the form with the fields populated.

Title: Bookmarkable GET link with Express

Body:
I have a website that uses Express to serve pages. Currently it works fine with a form that uses a POST query to populate the page with data, ajax-style.

I'd like the page and its contents to be bookmarkable, so I'm trying to convert this to GET. However I'm running into this problem:

The GET form works fine if I load the root page, fill out the form, and submit. However if I use the bookmark, all I get is the object as plain text.

I understand why this is happening. I don't understand what the right thing to do is to fix it. It doesn't appear that I can send both index.html and the object at the same time.

My server code:

app.get("/", function (request, response) {
  response.sendFile(__dirname + '/views/index.html');
});

app.post("/formpg", main);

app.get("/formpg", main);

function main(request, response) {
  var params = request.query;
  // * and a miracle occurs *
  response.send({data:miracle});
}


问:
Sorting a map of keys and values please to order a list in ES6 with Lodash (Keeping Firebase Key: UID)?
I'm currently trying to sort a list of employees in order of names but I'm having difficulty in such.

I'm using React-Native, with ES6, Lodash and firebase.

Firebase structure appears as:

The state.employees structure appears as:

{"-KgMYnBrqXCIPqjs0n7x":{"name":"James","phone":"123766","shift":"Monday"},  "-KgRiK6qiJsoZ_HBXt7K":{"name":"Nick","phone":"123767","shift":"Tuesday"},"-KgRiM77VTOejvYPWPIp":{"name":"Henry","phone":"123","shift":"Thursday"},"-KgRiOaN14OeSjaYWb1O":{"name":"Charlie","phone":"5643","shift":"Saturday"}}

and continues with more employees each having a UID and then properties such as name, phone and shift.

Although I am able to order the list with _.orderBy provided by Lodash, it appears that when doing so the UID as the key provided by firebase is removed when applied say before _.map.

This is what I currently have which orders but the UID is removed, the _.map works fine keeping the UID with the properties but is unordered.

```<code>const mapStateToProps = state => {
    const sortedEmployees = _.orderBy(
        state.employees,
        [employee => employee.name.toLowerCase()]
    );
    const employees = _.map(sortedEmployees, (val, uid) => {
        return { ...val, uid };
    });

    return { employees };
};
</code>```

Thanks very much

答:
Thanks for your response @agent_hunt. I tried implementing it as suggested having the same structure as that of _.map but it then complained about TypeError: "Cannot convert undefined or null to object" where it is not null nor undefined and actually matches the original _.map but this time ordered.

To stop it complaining about, I added as a final thought the _.map again but this time taking the sortedEmployees and returning { ...val, uid} and it works.

Couldn't get the firebase query approach to work, as I had to order by a child of a child (key) not knowing the key for each employee.

Here's what I implemented following your above arrWithKeys and sortedEmployees adding _.map as an after thought works

```<code>const mapStateToProps = state => {
    const arrWithKeys = Object.keys(state.employees).map((uid) => {
        return {
            ...state.employees[uid],
            uid,
        };
    });

    const sortedEmployees = _.orderBy(
        arrWithKeys,
        [employee => employee.name.toLowerCase()],
    );

    const employees = _.map(sortedEmployees);

    return { employees };
};
</code>```

https://lodash.com/docs/4.17.4#map

https://lodash.com/docs/4.17.4#orderBy

Body:
I'm currently trying to sort a list of employees in order of names but I'm having difficulty in such.

I'm using React-Native, with ES6, Lodash and firebase.

Firebase structure appears as:

The state.employees structure appears as:

{"-KgMYnBrqXCIPqjs0n7x":{"name":"James","phone":"123766","shift":"Monday"},  "-KgRiK6qiJsoZ_HBXt7K":{"name":"Nick","phone":"123767","shift":"Tuesday"},"-KgRiM77VTOejvYPWPIp":{"name":"Henry","phone":"123","shift":"Thursday"},"-KgRiOaN14OeSjaYWb1O":{"name":"Charlie","phone":"5643","shift":"Saturday"}}

and continues with more employees each having a UID and then properties such as name, phone and shift.

Although I am able to order the list with _.orderBy provided by Lodash, it appears that when doing so the UID as the key provided by firebase is removed when applied say before _.map.

This is what I currently have which orders but the UID is removed, the _.map works fine keeping the UID with the properties but is unordered.

const mapStateToProps = state => {
    const sortedEmployees = _.orderBy(
        state.employees,
        [employee => employee.name.toLowerCase()]
    );
    const employees = _.map(sortedEmployees, (val, uid) => {
        return { ...val, uid };
    });

    return { employees };
};

Thanks very much

Body:
Thanks for your response @agent_hunt. I tried implementing it as suggested having the same structure as that of _.map but it then complained about TypeError: "Cannot convert undefined or null to object" where it is not null nor undefined and actually matches the original _.map but this time ordered.

To stop it complaining about, I added as a final thought the _.map again but this time taking the sortedEmployees and returning { ...val, uid} and it works.

Couldn't get the firebase query approach to work, as I had to order by a child of a child (key) not knowing the key for each employee.

Here's what I implemented following your above arrWithKeys and sortedEmployees adding _.map as an after thought works

const mapStateToProps = state => {
    const arrWithKeys = Object.keys(state.employees).map((uid) => {
        return {
            ...state.employees[uid],
            uid,
        };
    });

    const sortedEmployees = _.orderBy(
        arrWithKeys,
        [employee => employee.name.toLowerCase()],
    );

    const employees = _.map(sortedEmployees);

    return { employees };
};

https://lodash.com/docs/4.17.4#map

https://lodash.com/docs/4.17.4#orderBy


问:
Environment variables with dotnet run on mac os using port 80 with kestrel
I'm trying to run an aspnet core application on port 80 on mac os sierra.

There are a few issues:

To run on port 80, I need to run dotnet run as root.

Running as root does not give the application access to the environment variable that I need for it to determine what port to run on, ie ASPNETCORE_URLS.

I've tried adding the environment variable to ~/.bash_profile, ~/.bashrc, ~/.profile and then adding this environment key to sudoers using sudo visudoer.

None of this has given the root user access to the ASPNETCORE_URLS. I also have other environment variables that the app needs to read.

So the question: How can I set environment variables for an app that is running as root?

答: Fixed. I wasn't using as root user. Follow this to enable root user privileges > https://support.apple.com/en-us/HT204012</p>


问:
How do stream data to a Bokeh plot in Jupyter with a high refresh rate?
I am trying to use Bokeh to plot a streaming dataset within a Jupyter notebook.  Here is what I have so far.

From the command line I start the bokeh server by running the command

```<code>$> bokeh server
</code>```

Here is the code from my Jupyter notebook

```<code>import numpy as np
from IPython.display import clear_output
# ------------------- new cell ---------------------#

from bokeh.models.sources import ColumnDataSource
from bokeh.client import push_session
from bokeh.driving import linear
from bokeh.plotting import figure
from bokeh.io import curdoc, output_notebook, show
# ------------------- new cell ---------------------#

output_notebook()
# ------------------- new cell ---------------------#

my_figure = figure(plot_width=800, plot_height=400)
test_data = ColumnDataSource(data=dict(x=[0], y=[0]))
linea = my_figure.line("x", "y", source=test_data)
# ------------------- new cell ---------------------#

new_data=dict(x=[0], y=[0])
x = []
y = []

step_size = 0.1  # increment for increasing step
@linear(m=step_size, b=0)
def update(step):
    x.append(step)
    y.append(np.random.rand())
    new_data['x'] = x
    new_data['y'] = y

    test_data.stream(new_data, 10)

    clear_output()
    show(my_figure)

    if step > 10:
        session.close()
# ------------------- new cell ---------------------#

# open a session to keep our local document in sync with server
session = push_session(curdoc())

period = 100  # in ms
curdoc().add_periodic_callback(update, period)

session.show()  # open a new browser tab with the updating plot

session.loop_until_closed()
</code>```

Currently, the result I get is a flashing plot within the Jupyter notebook and also a nicely updating plot in a new browser tab.  I would like either of the following

a nicely updating plot in Jupyter, without the flashing

just the plot in the new browser tab

I tried removing show(my_figure) but each update opened a new tab.  I also tried reducing the refresh rate to 10 ms, period = 10; session.show() works great but the notebook eventually crashes because it cannot refresh that fast.

How do I get a good refresh rate of the bokeh plot in Jupyter?  Or how do I turn off the Jupyter plot and only have one tab showing the updating plot?

答:
Here is the code for a modified notebook, following @bigreddot's comment, which uses push_notebook to produce a much cleaner result within the notebook (it does not require you run bokeh serve for the plotting). It does not use a callback; I'm not sure if this is an advantage or not.  As is, if you want the plot to update when a new data point comes in you could add an if data_event: statement at the beginning of the while loop, then tune the sleep time according to work well with the event rate.

This page from the official documentation provides additional helpful information regarding using Bokeh in a Jupyter notebook.

```<code>import time
import numpy as np
# ------------------- new cell ---------------------#

from bokeh.models.sources import ColumnDataSource
from bokeh.plotting import figure
from bokeh.io import output_notebook, show, push_notebook
# ------------------- new cell ---------------------#

output_notebook()
# ------------------- new cell ---------------------#

my_figure = figure(plot_width=800, plot_height=400)
test_data = ColumnDataSource(data=dict(x=[0], y=[0]))
line = my_figure.line("x", "y", source=test_data)
handle = show(my_figure, notebook_handle=True)

new_data=dict(x=[0], y=[0])
x = []
y = []

step = 0
step_size = 0.1  # increment for increasing step
max_step = 10  # arbitrary stop point for example
period = .1  # in seconds (simulate waiting for new data)
n_show = 10  # number of points to keep and show
while step < max_step:
    x.append(step)
    y.append(np.random.rand())
    new_data['x'] = x = x[-n_show:]  # prevent filling ram
    new_data['y'] = y = y[-n_show:]  # prevent filling ram

    test_data.stream(new_data, n_show)

    push_notebook(handle=handle)
    step += step_size
    time.sleep(period)
</code>```

Note the addition of new_data['x'] = x = x[-n_show] (same for y) so this could in theory run indefinitely without filling your memory.  Also, it would be nice to actually stream some kind of data source (maybe from the web) to make this a more realistic example.  Lastly, you probably realize this, but after you run the cell with the streaming plot, the kernel will be locked until it completes or is interupted; you cannot execute additional cells/code.  If you want to have analysis/control features, they should go inside the while loop.

Body:
I am trying to use Bokeh to plot a streaming dataset within a Jupyter notebook.  Here is what I have so far.

From the command line I start the bokeh server by running the command

$> bokeh server

Here is the code from my Jupyter notebook

import numpy as np
from IPython.display import clear_output
# ------------------- new cell ---------------------#

from bokeh.models.sources import ColumnDataSource
from bokeh.client import push_session
from bokeh.driving import linear
from bokeh.plotting import figure
from bokeh.io import curdoc, output_notebook, show
# ------------------- new cell ---------------------#

output_notebook()
# ------------------- new cell ---------------------#

my_figure = figure(plot_width=800, plot_height=400)
test_data = ColumnDataSource(data=dict(x=[0], y=[0]))
linea = my_figure.line("x", "y", source=test_data)
# ------------------- new cell ---------------------#

new_data=dict(x=[0], y=[0])
x = []
y = []

step_size = 0.1  # increment for increasing step
@linear(m=step_size, b=0)
def update(step):
    x.append(step)
    y.append(np.random.rand())
    new_data['x'] = x
    new_data['y'] = y

    test_data.stream(new_data, 10)

    clear_output()
    show(my_figure)

    if step > 10:
        session.close()
# ------------------- new cell ---------------------#

# open a session to keep our local document in sync with server
session = push_session(curdoc())

period = 100  # in ms
curdoc().add_periodic_callback(update, period)

session.show()  # open a new browser tab with the updating plot

session.loop_until_closed()

Currently, the result I get is a flashing plot within the Jupyter notebook and also a nicely updating plot in a new browser tab.  I would like either of the following

a nicely updating plot in Jupyter, without the flashing

just the plot in the new browser tab

I tried removing show(my_figure) but each update opened a new tab.  I also tried reducing the refresh rate to 10 ms, period = 10; session.show() works great but the notebook eventually crashes because it cannot refresh that fast.

How do I get a good refresh rate of the bokeh plot in Jupyter?  Or how do I turn off the Jupyter plot and only have one tab showing the updating plot?

Body:
Here is the code for a modified notebook, following @bigreddot's comment, which uses push_notebook to produce a much cleaner result within the notebook (it does not require you run bokeh serve for the plotting). It does not use a callback; I'm not sure if this is an advantage or not.  As is, if you want the plot to update when a new data point comes in you could add an if data_event: statement at the beginning of the while loop, then tune the sleep time according to work well with the event rate.

This page from the official documentation provides additional helpful information regarding using Bokeh in a Jupyter notebook.

import time
import numpy as np
# ------------------- new cell ---------------------#

from bokeh.models.sources import ColumnDataSource
from bokeh.plotting import figure
from bokeh.io import output_notebook, show, push_notebook
# ------------------- new cell ---------------------#

output_notebook()
# ------------------- new cell ---------------------#

my_figure = figure(plot_width=800, plot_height=400)
test_data = ColumnDataSource(data=dict(x=[0], y=[0]))
line = my_figure.line("x", "y", source=test_data)
handle = show(my_figure, notebook_handle=True)

new_data=dict(x=[0], y=[0])
x = []
y = []

step = 0
step_size = 0.1  # increment for increasing step
max_step = 10  # arbitrary stop point for example
period = .1  # in seconds (simulate waiting for new data)
n_show = 10  # number of points to keep and show
while step < max_step:
    x.append(step)
    y.append(np.random.rand())
    new_data['x'] = x = x[-n_show:]  # prevent filling ram
    new_data['y'] = y = y[-n_show:]  # prevent filling ram

    test_data.stream(new_data, n_show)

    push_notebook(handle=handle)
    step += step_size
    time.sleep(period)

Note the addition of new_data['x'] = x = x[-n_show] (same for y) so this could in theory run indefinitely without filling your memory.  Also, it would be nice to actually stream some kind of data source (maybe from the web) to make this a more realistic example.  Lastly, you probably realize this, but after you run the cell with the streaming plot, the kernel will be locked until it completes or is interupted; you cannot execute additional cells/code.  If you want to have analysis/control features, they should go inside the while loop.


问:
Scan image in vba with cannon scanner not work
I have a vba code that scan image from scanner , the code works and doesnt have any problem with type hp an brother scanner but when I used it with canon can not find the scanner and send message no wia device. How can solve this problem </p>

```<code>  Private Sub Command10_Click()
    Const wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"
    On Error GoTo Handle_Err
    Dim Dialog1 As New WIA.CommonDialog, DPI As Integer, PP As Integer, l As Integer
    Dim Scanner As WIA.Device
    Dim img As WIA.ImageFile
    Dim intPages As Integer
    Dim strFileJPG As String
    Dim blnContScan As Boolean ' to activate the scanner to start scan
    Dim ContScan As String    'msgbox to chk if more pages are to be scanned
    Dim strFilePDF As String
    Dim RptName As String
    Dim strProcName As String

    strProcName = "ScanDocs"
    DoCmd.SetWarnings False
    DoCmd.RunSQL "delete from scantemp"
    DoCmd.SetWarnings False

    blnContScan = True

    intPages = 0

    Do While blnContScan = True
        DPI = 200
        PP = 1 'No of pages
        Set Scanner = Dialog1.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, True, False)
       Set img = Dialog1.ShowTransfer(Scanner.Items(1), wiaFormatJPEG, True)
       strFileJPG = ""

        intPages = intPages + 1

    strFileJPG = "\\User-pc\saveimage\" & num & Trim(str(intPages)) & ".jpg"

       img.SaveFile (strFileJPG)

        DoCmd.RunSQL "insert into scantemp (picture) values ('" & strFileJPG & "')"

        DoCmd.SetWarnings False
        Set Scanner = Nothing
        Set img = Nothing
       ' strFileJPG = ""

         'Prompt user if there are additional pages to scan

        ContScan = MsgBox("?save another page ", vbQuestion + vbYesNoCancel)
              If ContScan = vbNo Then
            blnContScan = False

            ElseIf ContScan = vbCancel Then

            DoCmd.RunSQL "delete from scantemp where picture = '" & strFileJPG & "'"

        End If

            '''''''''''''''
    Loop

       Dim Image_Path As String
        GoTo StartPDFConversion
    StartPDFConversion:
     Dim s As String
    strFilePDF = "\\User-pc\saveimage\" & (num) & ".pdf"
    RptName = "rptScan"
    DoCmd.OpenReport RptName, acViewReport, , , acHidden
    DoCmd.Close acReport, RptName, acSaveYes
    DoCmd.OutputTo acOutputReport, RptName, acFormatPDF, strFilePDF
     Me.imgp = strFilePDF
    DoCmd.RunSQL "delete from scantemp" 'delete all data from table scantemp after converted it to pdf

    '/*******************************\

    '/********************************************\

    Handle_Exit:

        Exit Sub

    Handle_Err:
        Select Case Err.Number
            Case 2501
                Resume Handle_Exit

            Case Else

                MsgBox "the." & vbCrLf & vbCrLf & _
                "In Function:" & vbTab & strProcName & vbCrLf & _
                "Err Number: " & vbTab & Err.Number & vbCrLf & _
                "Description: " & vbTab & Err.Description, 0, _
                "Error in " & Chr$(34) & strProcName & Chr$(34)
                Resume Handle_Exit
        End Select

        Exit Sub
    End Sub
</code>```

答:
```<code>    Option Compare Database

Private Declare Function TWAIN_AcquireToFilename Lib "TWAIN32d.DLL" (ByVal hwndApp As Long, ByVal bmpFileName As String) As Integer
Private Declare Function TWAIN_IsAvailable Lib "TWAIN32d.DLL" () As Long
Private Declare Function TWAIN_SelectImageSource Lib "TWAIN32d.DLL" (ByVal hwndApp As Long) As Long

Private Sub cmdScan_Click()
Dim Ret As Long, PictureFile As String
Dim intPages As Integer
Dim blnContScan As Boolean
Dim ContScan As String    'msgbox to chk if more pages are to be scanned

blnContScan = True

intPages = 0
Do While blnContScan = True
    DPI = 200
    PP = 1 'No of pages
     intPages = intPages + 1
   PictureFile = CurrentProject.Path & "\" & myfolder & "\" & Me.number & Trim(Str(intPages)) & ".jpg"

Ret = TWAIN_AcquireToFilename(Me.hwnd, PictureFile)

     ContScan = MsgBox("? ÍÝÙ ÕæÑÉ ÇÎÑì ", vbQuestion + vbYesNo, "ÊäÈíÉ")
    If ContScan = vbNo Then
        blnContScan = False
    End If

Loop
</code>```

Body:
I have a vba code that scan image from scanner , the code works and doesnt have any problem with type hp an brother scanner but when I used it with canon can not find the scanner and send message no wia device. How can solve this problem

  Private Sub Command10_Click()
    Const wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"
    On Error GoTo Handle_Err
    Dim Dialog1 As New WIA.CommonDialog, DPI As Integer, PP As Integer, l As Integer
    Dim Scanner As WIA.Device
    Dim img As WIA.ImageFile
    Dim intPages As Integer
    Dim strFileJPG As String
    Dim blnContScan As Boolean ' to activate the scanner to start scan
    Dim ContScan As String    'msgbox to chk if more pages are to be scanned
    Dim strFilePDF As String
    Dim RptName As String
    Dim strProcName As String

    strProcName = "ScanDocs"
    DoCmd.SetWarnings False
    DoCmd.RunSQL "delete from scantemp"
    DoCmd.SetWarnings False

    blnContScan = True

    intPages = 0

    Do While blnContScan = True
        DPI = 200
        PP = 1 'No of pages
        Set Scanner = Dialog1.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, True, False)
       Set img = Dialog1.ShowTransfer(Scanner.Items(1), wiaFormatJPEG, True)
       strFileJPG = ""

        intPages = intPages + 1

    strFileJPG = "\\User-pc\saveimage\" & num & Trim(str(intPages)) & ".jpg"

       img.SaveFile (strFileJPG)

        DoCmd.RunSQL "insert into scantemp (picture) values ('" & strFileJPG & "')"

        DoCmd.SetWarnings False
        Set Scanner = Nothing
        Set img = Nothing
       ' strFileJPG = ""

         'Prompt user if there are additional pages to scan

        ContScan = MsgBox("?save another page ", vbQuestion + vbYesNoCancel)
              If ContScan = vbNo Then
            blnContScan = False

            ElseIf ContScan = vbCancel Then

            DoCmd.RunSQL "delete from scantemp where picture = '" & strFileJPG & "'"

        End If

            '''''''''''''''
    Loop

       Dim Image_Path As String
        GoTo StartPDFConversion
    StartPDFConversion:
     Dim s As String
    strFilePDF = "\\User-pc\saveimage\" & (num) & ".pdf"
    RptName = "rptScan"
    DoCmd.OpenReport RptName, acViewReport, , , acHidden
    DoCmd.Close acReport, RptName, acSaveYes
    DoCmd.OutputTo acOutputReport, RptName, acFormatPDF, strFilePDF
     Me.imgp = strFilePDF
    DoCmd.RunSQL "delete from scantemp" 'delete all data from table scantemp after converted it to pdf

    '/*******************************\

    '/********************************************\

    Handle_Exit:

        Exit Sub

    Handle_Err:
        Select Case Err.Number
            Case 2501
                Resume Handle_Exit

            Case Else

                MsgBox "the." & vbCrLf & vbCrLf & _
                "In Function:" & vbTab & strProcName & vbCrLf & _
                "Err Number: " & vbTab & Err.Number & vbCrLf & _
                "Description: " & vbTab & Err.Description, 0, _
                "Error in " & Chr$(34) & strProcName & Chr$(34)
                Resume Handle_Exit
        End Select

        Exit Sub
    End Sub


问:
Make SQL Calls on WindowsServices
I'm making an application as follows: I have a webservice running on a local server, this webservice returns json like this:

```<code>[{"Id":1,"Titulo":"Live to win","Link":"https://www.youtube.com/embed/DPHlGVe8wxI","BandaId":1,"BandaNome":"Paul Stanley","GeneroId":1,"GeneroNome":"Rock","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":false},{"Id":2,"Titulo":"Welcome to the jungle","Link":null,"BandaId":2,"BandaNome":"Guns n´ roses","GeneroId":1,"GeneroNome":"Rock","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":3,"Titulo":"Something just like this","Link":null,"BandaId":3,"BandaNome":"The Chainsmokers","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":4,"Titulo":"Beliver","Link":null,"BandaId":4,"BandaNome":"Imagine Dragons","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":5,"Titulo":"Radioactive","Link":null,"BandaId":4,"BandaNome":"Imagine Dragons","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":6,"Titulo":"Friends - Original Mix","Link":null,"BandaId":5,"BandaNome":"Steener","GeneroId":2,"GeneroNome":"EDM","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":7,"Titulo":"Amanheceu","Link":null,"BandaId":6,"BandaNome":"Scalene","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":8,"Titulo":"Sonhador II","Link":null,"BandaId":6,"BandaNome":"Scalene","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":9,"Titulo":"Amianto","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":10,"Titulo":"Monstros","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":11,"Titulo":"Piloto Automático","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":12,"Titulo":"Eutanásia","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":13,"Titulo":"Shots - Broiler Remix","Link":null,"BandaId":4,"BandaNome":"Imagine Dragons","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-24T16:55:46","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true}]
</code>```

But now I need to create a Windows Services that communicates with this WebService and what it receives in a database, I spent all day doing this webservice in several ways, but I did not find anything about good practices with webservices or etc. I'll show you what I did, but I'd like some tips on windows services, thank you

Here is my code

Service:

```<code>private Timer _worker;
    private readonly int _interval = Convert.ToInt32(ConfigurationManager.AppSettings["timer"]);
    private readonly string _connection = ConfigurationManager.AppSettings["connection"];
    //private readonly Connector _usuarioConnector;
    private readonly Connector _bandaConnector;
    //private readonly Connector _generoConnector;
    private readonly Connector _musicaConnector;
    private SqlConnection conn;

    public Service1()
    {
        //_usuarioConnector = new Connector("UsuarioBase");
        _bandaConnector = new Connector("BandaBase");
        //_generoConnector = new Connector("GeneroBase");
        _musicaConnector = new Connector("MusicaBase");
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _worker = new Timer((Update), null, 0, _interval);
    }

    protected override void OnStop()
    {

    }

    private void Update(Object state)
    {
        using (SqlConnection connection = new SqlConnection(
           _connection))
        {
            SqlCommand command = new SqlCommand("insert into Genero(nome, descricao, dtcriacao, criadorid, ativo) values('teste', 'teste', getdate(), 1, 1)", connection);
            command.Connection.Open();
            command.ExecuteNonQuery();
            EventLog.WriteEntry("Query executada", EventLogEntryType.Warning);
        }
    }
</code>```

Loader

```<code>public class Loader
{
    public static List<Usuario> LoadUsuarios(Connector usuarioConnector)
    {
        return (List<Usuario>)Newtonsoft.Json.JsonConvert.DeserializeObject(usuarioConnector.GetData(), typeof(List<Usuario>));
    }
    public static List<Banda> LoadBandas(Connector bandaConnector)
    {
        var bandasDtos = (List<BandaDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(bandaConnector.GetData(), typeof(List<BandaDto>));
        return bandasDtos.Select(dto => dto.ConvertToBanda()).ToList();
    }
    //public static List<Genero> LoadGeneros(Connector generoConnector)
    //{
        //var musicasDtos = (List<MusicaDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(musicaConnector.GetData(), typeof(List<MusicaDto>));
        //return musicasDtos.Select(dto => dto.ConvertToMusica()).ToList();
    //}
    public static List<Musica> LoadMusicas(Connector musicaConnector)
    {
        var musicasDtos = (List<MusicaDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(musicaConnector.GetData(), typeof(List<MusicaDto>));
        return musicasDtos.Select(dto => dto.ConvertToMusica()).ToList();
    }
}
</code>```

Connector

```<code> private string Host { get; }
    private WebRequest _request;
    public WebResponse Response;
    public string ConnectionStatus;
    private Stream _dataStream;
    private StreamReader _reader;

    public Connector(string config)
    {
        Host = ConfigurationManager.AppSettings[config];

    }

    public string GetData()
    {
        StartConnection();
        _dataStream = Response.GetResponseStream();
        _reader = new StreamReader(_dataStream);
        var toReturn = _reader.ReadToEnd();
        EndConnection();
        return toReturn;
    }

    private void StartConnection()
    {
        _request = WebRequest.Create(Host);
        _request.Credentials = CredentialCache.DefaultCredentials;
        Response = _request.GetResponse();
        ConnectionStatus = (((HttpWebResponse)Response).StatusDescription);
    }

    private void EndConnection()
    {
        _reader.Close();
        Response.Close();
    }
</code>```

Edit1 In the current code it is doing a select, however in what I intend to do it will do inserts

答: I discovered, unfortunately the timer was not working, so I just changed it to a thread.</p>

Title: Make SQL Calls on WindowsServices

Body:
I'm making an application as follows: I have a webservice running on a local server, this webservice returns json like this:

[{"Id":1,"Titulo":"Live to win","Link":"https://www.youtube.com/embed/DPHlGVe8wxI","BandaId":1,"BandaNome":"Paul Stanley","GeneroId":1,"GeneroNome":"Rock","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":false},{"Id":2,"Titulo":"Welcome to the jungle","Link":null,"BandaId":2,"BandaNome":"Guns n´ roses","GeneroId":1,"GeneroNome":"Rock","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":3,"Titulo":"Something just like this","Link":null,"BandaId":3,"BandaNome":"The Chainsmokers","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":4,"Titulo":"Beliver","Link":null,"BandaId":4,"BandaNome":"Imagine Dragons","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":5,"Titulo":"Radioactive","Link":null,"BandaId":4,"BandaNome":"Imagine Dragons","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":6,"Titulo":"Friends - Original Mix","Link":null,"BandaId":5,"BandaNome":"Steener","GeneroId":2,"GeneroNome":"EDM","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":7,"Titulo":"Amanheceu","Link":null,"BandaId":6,"BandaNome":"Scalene","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":8,"Titulo":"Sonhador II","Link":null,"BandaId":6,"BandaNome":"Scalene","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":9,"Titulo":"Amianto","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":10,"Titulo":"Monstros","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":11,"Titulo":"Piloto Automático","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":2,"CriadorNome":"Usuário Teste","Ativo":true},{"Id":12,"Titulo":"Eutanásia","Link":null,"BandaId":7,"BandaNome":"Supercombo","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-23T16:42:54","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true},{"Id":13,"Titulo":"Shots - Broiler Remix","Link":null,"BandaId":4,"BandaNome":"Imagine Dragons","GeneroId":3,"GeneroNome":"Indie","DtCriacao":"2017-03-24T16:55:46","CriadorId":1,"CriadorNome":"Márcio Eric","Ativo":true}]

But now I need to create a Windows Services that communicates with this WebService and what it receives in a database, I spent all day doing this webservice in several ways, but I did not find anything about good practices with webservices or etc. I'll show you what I did, but I'd like some tips on windows services, thank you

Here is my code

Service:

private Timer _worker;
    private readonly int _interval = Convert.ToInt32(ConfigurationManager.AppSettings["timer"]);
    private readonly string _connection = ConfigurationManager.AppSettings["connection"];
    //private readonly Connector _usuarioConnector;
    private readonly Connector _bandaConnector;
    //private readonly Connector _generoConnector;
    private readonly Connector _musicaConnector;
    private SqlConnection conn;

    public Service1()
    {
        //_usuarioConnector = new Connector("UsuarioBase");
        _bandaConnector = new Connector("BandaBase");
        //_generoConnector = new Connector("GeneroBase");
        _musicaConnector = new Connector("MusicaBase");
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _worker = new Timer((Update), null, 0, _interval);
    }

    protected override void OnStop()
    {

    }

    private void Update(Object state)
    {
        using (SqlConnection connection = new SqlConnection(
           _connection))
        {
            SqlCommand command = new SqlCommand("insert into Genero(nome, descricao, dtcriacao, criadorid, ativo) values('teste', 'teste', getdate(), 1, 1)", connection);
            command.Connection.Open();
            command.ExecuteNonQuery();
            EventLog.WriteEntry("Query executada", EventLogEntryType.Warning);
        }
    }

Loader

public class Loader
{
    public static List<Usuario> LoadUsuarios(Connector usuarioConnector)
    {
        return (List<Usuario>)Newtonsoft.Json.JsonConvert.DeserializeObject(usuarioConnector.GetData(), typeof(List<Usuario>));
    }
    public static List<Banda> LoadBandas(Connector bandaConnector)
    {
        var bandasDtos = (List<BandaDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(bandaConnector.GetData(), typeof(List<BandaDto>));
        return bandasDtos.Select(dto => dto.ConvertToBanda()).ToList();
    }
    //public static List<Genero> LoadGeneros(Connector generoConnector)
    //{
        //var musicasDtos = (List<MusicaDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(musicaConnector.GetData(), typeof(List<MusicaDto>));
        //return musicasDtos.Select(dto => dto.ConvertToMusica()).ToList();
    //}
    public static List<Musica> LoadMusicas(Connector musicaConnector)
    {
        var musicasDtos = (List<MusicaDto>)Newtonsoft.Json.JsonConvert.DeserializeObject(musicaConnector.GetData(), typeof(List<MusicaDto>));
        return musicasDtos.Select(dto => dto.ConvertToMusica()).ToList();
    }
}

Connector

 private string Host { get; }
    private WebRequest _request;
    public WebResponse Response;
    public string ConnectionStatus;
    private Stream _dataStream;
    private StreamReader _reader;

    public Connector(string config)
    {
        Host = ConfigurationManager.AppSettings[config];

    }

    public string GetData()
    {
        StartConnection();
        _dataStream = Response.GetResponseStream();
        _reader = new StreamReader(_dataStream);
        var toReturn = _reader.ReadToEnd();
        EndConnection();
        return toReturn;
    }

    private void StartConnection()
    {
        _request = WebRequest.Create(Host);
        _request.Credentials = CredentialCache.DefaultCredentials;
        Response = _request.GetResponse();
        ConnectionStatus = (((HttpWebResponse)Response).StatusDescription);
    }

    private void EndConnection()
    {
        _reader.Close();
        Response.Close();
    }

Edit1 In the current code it is doing a select, however in what I intend to do it will do inserts


问:
Apache commons io Tailer : Handle log rotation
I am using Tailer to read lines from some log4j log file and write only certain lines into another destination file.

Now I want to rotate the destination file everyday or at least want to delete some old data from the destination file.

What is the best way to do this?

答:
As long as you don't use the reopen parameter, Tailer handles log rotation itself. :)

Sources:

Bug about the reopen parameter not cooperating with log rotation

Source code where it handles log file rotation (approximately)


问:
Destructor causes corruption of the heap.
I'm playing around with destructors and I don't understand why I get an error for this code when the main function terminates.

```<code>#include <iostream>
#include <math.h>
#include <string>
#include <cstdint>
#include <cassert>
using namespace std;

class RGBA {
    uint8_t _red, _blue, _green, _alpha;
    int *_arr;
    int _length;
public:
    RGBA(int *arr, int length, uint8_t r = 0, uint8_t b = 0, uint8_t g = 0, uint8_t a = 255):
      _red (r), _blue (b), _green (g), _alpha (a) {
      _arr = arr;
      _length = length;
      }
      ~RGBA() {
          cout << "Destroying object" << endl;
          delete[] _arr;
      }

    void print() {
        for (int i = 0; i < _length; ++i) {
            cout << _arr[i] << endl;
        }
        cout << static_cast<int>(_red) << " " << static_cast<int>(_blue) << " " << static_cast<int>(_green) << " " << static_cast<int>(_alpha) << endl;
    }
};

int main() {
    int arr[3] = {1,2,3};
    RGBA rgba(arr, 3);
    rgba.print();

    cin.get();
    return 0;
}
</code>```

It outputs, but then when I press Enter, it prints 'Destroying object' with the following error "This may be due to a corruption of the heap, which indicates a bug in testcpp.exe or any of the DLLs it has loaded.".

```<code>1
2
3
0 0 0 255
</code>```

I use VS2010 on Win7.

答:
The automatic storage duration variable int arr[3] will be automatically deallocated when the enclosing function exits.

Trying to delete[] it causes undefined behavior. Only objects allocated with new[] can be deallocated with delete[].

Body:
I'm playing around with destructors and I don't understand why I get an error for this code when the main function terminates.

#include <iostream>
#include <math.h>
#include <string>
#include <cstdint>
#include <cassert>
using namespace std;

class RGBA {
    uint8_t _red, _blue, _green, _alpha;
    int *_arr;
    int _length;
public:
    RGBA(int *arr, int length, uint8_t r = 0, uint8_t b = 0, uint8_t g = 0, uint8_t a = 255):
      _red (r), _blue (b), _green (g), _alpha (a) {
      _arr = arr;
      _length = length;
      }
      ~RGBA() {
          cout << "Destroying object" << endl;
          delete[] _arr;
      }

    void print() {
        for (int i = 0; i < _length; ++i) {
            cout << _arr[i] << endl;
        }
        cout << static_cast<int>(_red) << " " << static_cast<int>(_blue) << " " << static_cast<int>(_green) << " " << static_cast<int>(_alpha) << endl;
    }
};

int main() {
    int arr[3] = {1,2,3};
    RGBA rgba(arr, 3);
    rgba.print();

    cin.get();
    return 0;
}

It outputs, but then when I press Enter, it prints 'Destroying object' with the following error "This may be due to a corruption of the heap, which indicates a bug in testcpp.exe or any of the DLLs it has loaded.".

1
2
3
0 0 0 255

I use VS2010 on Win7.


问:
Random Access in Array
I was reading this, advantages of java, where it states that random access is an advantage of arrays in java. I do not understand how can accessing a random element of an array is an advantage. Shouldn't it be a disadvantage?

Why is java allowing to access elements of an array randomly, if the data is stored continuously, shouldn't the data be accessed in an orderly manner?

答: It means any element in an array has constant access time O(1). Arrays store it's elements in contiguous memory locations. Arrays store objects with fixed size and any object can be accessed by calculating the offset which is (size*index) instead of traversing the entire array sequentially.</p>

Title: Random Access in Array


问:
Can I use react-select in react-native?
I'm trying to implement a search form, in my react-native app. For it, I need something like react-select or select-2, both tools are made for web systems and I don't know if is a good idea to use it for a react-native app.

I already tried to install and use it in react-native but this does not appear to work.

答:
Probably the closest to what you want that comes bundled with React Native is http://facebook.github.io/react-native/docs/picker.html

The Picker component will give you a tumbler thing on iOS and a dropdown on Android

Alternatively maybe this 3rd party component is closer to what you want: https://github.com/bulenttastan/react-native-list-popover

From How to use React native select box

Title: Can I use react-select in react-native?


问:
Connection pool with single connection vs connection for infrequent queries
I am building a Java application which queries my SQL server once a minute. Right now, the application is using a connection pool with a single connection (min pool size 1, max pool size 1).

I figured that a pool size of 1 would be enough because of the infrequent queries (once a minute, as mentioned before).

Do I need a connection pool at all, and if the answer is yes, is 1 connection enough? Or should I just not use a pool and open a new connection every minute?

答: If you're accessing the database that rarely, then in practice having a connection pool will not provide any significant benefit. However, I'd keep it if it's already written. Maybe one day your application will grow and you'll find the pool useful. It's not a bad thing to have.</p>


问:
SKErrorDomain Code=0 "Cannot connect to iTunes Store" in IAP iOS Objective c
when i tested IAP for my app, it throws following error

```<code>Error Domain=SKErrorDomain Code=0 "Cannot connect to iTunes Store"
UserInfo={NSLocalizedDescription=Cannot connect to iTunes Store}
</code>```

i have tried many links related to this problem but nothing helped.
Moreover the "Product Identifier" are also correct and i also created new sandbox user, but no output. Any help would be great.

答: Looks like Apple's servers are down for Sandbox environment. Live purchases are working just fine!</p>

Body:
when i tested IAP for my app, it throws following error

Error Domain=SKErrorDomain Code=0 "Cannot connect to iTunes Store"
UserInfo={NSLocalizedDescription=Cannot connect to iTunes Store}

i have tried many links related to this problem but nothing helped.
Moreover the "Product Identifier" are also correct and i also created new sandbox user, but no output. Any help would be great.


答:
The array you are passing, arr is being allocated on the stack in your main function. You then pass the pointer to your RGBA instance which then deletes the array in its destructor. As it was not dynamically allocated in the first place, this is a bad thing.

Deleting the array in the destructor indicates that you mean to transfer ownership of the array to that class. To do that, you need to either pass a dynamically allocated array or allocate a new array in the constructor and copy the contents of the one passed by parameter.

If you do not need ownership, simply remove the delete call in the destructor.

Title: Destructor causes corruption of the heap.