问:
Mocking ref parameters
I've cross posted this on the #moq discussion group at:
http://groups.google.com/group/moqdisc/browse_thread/thread/569b75fd2cc1829d

hey folks,

I have come across a problem with a mocked ref param that I'm sure
must be obvious, but being new to the framework I just can't work it
out.

I have the following repository method:

```<code>public int SaveCard(int userId, CardPaymentMethodDto
cardPaymentMethodDto)
{
        int? cardId = 0;
        try
        {
                int result = this.dataContext.usp_PaymentMethod_Card_Insert(userId,
                                cardPaymentMethodDto.UserAccountReference,
                                cardPaymentMethodDto.EncryptedCardNumber,
                                cardPaymentMethodDto.BinRange,
                                cardPaymentMethodDto.LastFourDigits,
                                cardPaymentMethodDto.ExpiryMonth,
                                cardPaymentMethodDto.ExpiryYear,
                                cardPaymentMethodDto.IssueNumber,
                                cardPaymentMethodDto.IssuingBank,
                                cardPaymentMethodDto.IssuingCountry,
                                cardPaymentMethodDto.Scheme,
                                cardPaymentMethodDto.StartMonth,
                                cardPaymentMethodDto.StartYear,
                                cardPaymentMethodDto.BillingAddress.House,
                                cardPaymentMethodDto.BillingAddress.SubPremises,
                                cardPaymentMethodDto.BillingAddress.Street,
                                cardPaymentMethodDto.BillingAddress.Town,
                                cardPaymentMethodDto.BillingAddress.County,
                                cardPaymentMethodDto.BillingAddress.Postcode,
                                cardPaymentMethodDto.BillingAddress.Country,
                                cardPaymentMethodDto.DateRegistered,
                                ref cardId);

                if (result <= 0)
                {
                        CompanySystemSqlException tex = new
CompanySystemSqlException("Database communications error");
                        tex.Data.Add("UserId", userId);
                        tex.Data.Add("PaymentMethod", cardPaymentMethodDto.ToString());
                        Logger.LogException("SaveCard: result <= 0", tex);
                        throw tex;
                }
        }
        catch (DbException ex)
        {
                CompanySystemSqlException tex = new
CompanySystemSqlException("Database communications error", ex);
                tex.Data.Add("UserId", userId);
                tex.Data.Add("PaymentMethod", cardPaymentMethodDto.ToString());
                Logger.LogException("SaveCard: DbException", tex);
                throw tex;
        }

        return cardId ?? 0;

}
</code>```

a the unit test I have is:

```<code>[Test]
public void SaveCard_ValidData_ShouldReturnValidCardId()
{
        int cardId;
        int? refCardId = 0;
        dataContext.DefaultValue = DefaultValue.Mock;
        dataContext.Setup( x =>
x.usp_PaymentMethod_Card_Insert(It.IsAny<int>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(),
                It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(),
                It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
                It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<DateTime>(), ref refCardId)).Returns(1);

        cardId = paymentRepository.SaveCard(1, new CardPaymentMethodDto
{ BillingAddress = new AddressDto { Country = "", County = "", House =
"", Postcode = "", Street = "", SubPremises = "", Town = ""},
                                                                                BinRange = "", Cv2 = 123,
                                                                                DateRegistered = DateTime.Now, EncryptedCardNumber =
"jumble",
                                                                                ExpiryMonth = "02", ExpiryYear = "2030", Id = 1,
IssueNumber = 1, IssuingBank = "", IssuingCountry = "",
                                                                                LastFourDigits = "", LastUsed = DateTime.MinValue, Scheme
= "", StartMonth = "", StartYear = "",
                                                                                UserAccountReference = ""});

        Assert.That(cardId, Is.EqualTo(1));

}
</code>```

Now obviously I've had to create the ref param (refCardId) in the unit
test, or I can't setup the expected result, but refCardId <> the
repository cardId variable, so it's obviously failing (result from the
first method is coming back as zero).

I'm sure I'm missing something, but what...?

Thanks for any help,
Cheers,
Terry

答:
Starting with Moq 4.8 (which isn't released yet, but there's a pre-release version), you can match ref parameters using It.Ref<T>.IsAny:

```<code>dataContext.Setup(x => x.usp_PaymentMethod_Card_Insert(
                           It.IsAny<int>(),
                           It.IsAny<string>(),
                           ...
                           It.IsAny<DateTime>(),
                           ref It.Ref<int?>.IsAny))
           .Returns(1);
</code>```

Title: Mocking ref parameters

Body:
I've cross posted this on the #moq discussion group at:
http://groups.google.com/group/moqdisc/browse_thread/thread/569b75fd2cc1829d

hey folks,

I have come across a problem with a mocked ref param that I'm sure
must be obvious, but being new to the framework I just can't work it
out.

I have the following repository method:

public int SaveCard(int userId, CardPaymentMethodDto
cardPaymentMethodDto)
{
        int? cardId = 0;
        try
        {
                int result = this.dataContext.usp_PaymentMethod_Card_Insert(userId,
                                cardPaymentMethodDto.UserAccountReference,
                                cardPaymentMethodDto.EncryptedCardNumber,
                                cardPaymentMethodDto.BinRange,
                                cardPaymentMethodDto.LastFourDigits,
                                cardPaymentMethodDto.ExpiryMonth,
                                cardPaymentMethodDto.ExpiryYear,
                                cardPaymentMethodDto.IssueNumber,
                                cardPaymentMethodDto.IssuingBank,
                                cardPaymentMethodDto.IssuingCountry,
                                cardPaymentMethodDto.Scheme,
                                cardPaymentMethodDto.StartMonth,
                                cardPaymentMethodDto.StartYear,
                                cardPaymentMethodDto.BillingAddress.House,
                                cardPaymentMethodDto.BillingAddress.SubPremises,
                                cardPaymentMethodDto.BillingAddress.Street,
                                cardPaymentMethodDto.BillingAddress.Town,
                                cardPaymentMethodDto.BillingAddress.County,
                                cardPaymentMethodDto.BillingAddress.Postcode,
                                cardPaymentMethodDto.BillingAddress.Country,
                                cardPaymentMethodDto.DateRegistered,
                                ref cardId);

                if (result <= 0)
                {
                        CompanySystemSqlException tex = new
CompanySystemSqlException("Database communications error");
                        tex.Data.Add("UserId", userId);
                        tex.Data.Add("PaymentMethod", cardPaymentMethodDto.ToString());
                        Logger.LogException("SaveCard: result <= 0", tex);
                        throw tex;
                }
        }
        catch (DbException ex)
        {
                CompanySystemSqlException tex = new
CompanySystemSqlException("Database communications error", ex);
                tex.Data.Add("UserId", userId);
                tex.Data.Add("PaymentMethod", cardPaymentMethodDto.ToString());
                Logger.LogException("SaveCard: DbException", tex);
                throw tex;
        }

        return cardId ?? 0;

}

a the unit test I have is:

[Test]
public void SaveCard_ValidData_ShouldReturnValidCardId()
{
        int cardId;
        int? refCardId = 0;
        dataContext.DefaultValue = DefaultValue.Mock;
        dataContext.Setup( x =>
x.usp_PaymentMethod_Card_Insert(It.IsAny<int>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(),
                It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(),
                It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
                It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<DateTime>(), ref refCardId)).Returns(1);

        cardId = paymentRepository.SaveCard(1, new CardPaymentMethodDto
{ BillingAddress = new AddressDto { Country = "", County = "", House =
"", Postcode = "", Street = "", SubPremises = "", Town = ""},
                                                                                BinRange = "", Cv2 = 123,
                                                                                DateRegistered = DateTime.Now, EncryptedCardNumber =
"jumble",
                                                                                ExpiryMonth = "02", ExpiryYear = "2030", Id = 1,
IssueNumber = 1, IssuingBank = "", IssuingCountry = "",
                                                                                LastFourDigits = "", LastUsed = DateTime.MinValue, Scheme
= "", StartMonth = "", StartYear = "",
                                                                                UserAccountReference = ""});

        Assert.That(cardId, Is.EqualTo(1));

}

Now obviously I've had to create the ref param (refCardId) in the unit
test, or I can't setup the expected result, but refCardId <> the
repository cardId variable, so it's obviously failing (result from the
first method is coming back as zero).

I'm sure I'm missing something, but what...?

Thanks for any help,
Cheers,
Terry

Body:
Starting with Moq 4.8 (which isn't released yet, but there's a pre-release version), you can match ref parameters using It.Ref<T>.IsAny:

dataContext.Setup(x => x.usp_PaymentMethod_Card_Insert(
                           It.IsAny<int>(),
                           It.IsAny<string>(),
                           ...
                           It.IsAny<DateTime>(),
                           ref It.Ref<int?>.IsAny))
           .Returns(1);


来源: stackexchange

问:
multiple pies with scatterpie or ggforce
I am trying to plot multiple piecharts on top of an image. I want to use custom_annotation to plot the rastered image. But right now I can't even get the multiple piecharts.

Ultimately I want 6 pies plotting in differnet spots over top of an image. imX and imY give the coordinates of where the pies should be on the image.

```<code>head(wholebody_cutLH_wide_t[c(1,2,102,103,104)])
Acidobacteriaceae Actinomycetaceae  imX imY radius
1      0.000000e+00     7.665687e-05 2.00 5.5    0.5
2      0.000000e+00     4.580237e-04 1.50 1.0    0.5
3      0.000000e+00     4.112573e-04 1.75 2.0    0.5
4      6.431473e-04     3.856008e-02 0.30 1.0    0.5
5      0.000000e+00     3.013013e-04 1.50 4.8    0.5
6      3.399756e-05     1.372986e-02 1.50 5.2    0.5
</code>```

Now here is my attempt with scatterpie:

```<code>ggplot(wholebody_cutLH_wide_t) +
 #  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
 geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t, cols=NA,color=sample(allcolors,101)) +
 scale_color_manual(values=sample(allcolors,101)) +
 scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
 scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
 theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
  )
</code>```

Now my error is:

```<code>Error: Only strings can be converted to symbols
</code>```

Here is my attempt with dplyr and ggforce:

```<code>dat_pies<-left_join(wholebody_cutLH,
                wholebody_cutLH %>%
                  group_by(tax_rank) %>%
                  summarize(Cnt_total = sum(count_norm))) %>%
group_by(tax_rank) %>%
mutate(end_angle = 2*pi*cumsum(count_norm)/Cnt_total,      # ending angle for   each pie slice
     start_angle = lag(end_angle, default = 0),   # starting angle for each pie slice
     mid_angle = 0.5*(start_angle + end_angle))

ggplot(dat_pies) +
geom_arc_bar(aes(x0 = imX, y0 = imY, r0 = 0, r = rpie,
               start = start_angle, end = end_angle, fill = Volume)) +
geom_text(aes(x = rlabel*sin(mid_angle), y = rlabel*cos(mid_angle), label = Cnt),
        hjust = 0.5, vjust = 0.5) +
coord_fixed() +
scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
</code>```

Here my error is :

```<code>Error in ggplot(dat_pies) + geom_arc_bar(aes(x0 = imX, y0 = imY, r0 = 0,  :
could not find function "+<-"
</code>```

Any help with either of these methods would be great.
thanks

答:
It doesn't look like you've actually adapted your code to your data. Here's the ggforce example fixed up:

```<code>wholebody_cutLH_wide_t <- read.table(text = "Acidobacteriaceae Actinomycetaceae  imX imY radius
      0.000000e+00     7.665687e-05 2.00 5.5    0.5
      0.000000e+00     4.580237e-04 1.50 1.0    0.5
      0.000000e+00     4.112573e-04 1.75 2.0    0.5
      6.431473e-04     3.856008e-02 0.30 1.0    0.5
      0.000000e+00     3.013013e-04 1.50 4.8    0.5
      3.399756e-05     1.372986e-02 1.50 5.2    0.5", header = TRUE)

library(tidyr)
library(dplyr)
library(ggforce)

# convert to long format, add a grouping variable to keep track of which pies go together
wholebody_cutLH_long <- mutate(wholebody_cutLH_wide_t, group=letters[1:6]) %>%
  gather(type, amount, -imX, -imY, -radius, -group)

dat_pies<-left_join(wholebody_cutLH_long,
                    wholebody_cutLH_long %>%
                      group_by(group) %>%
                      summarize(amount_total = sum(amount))) %>%
  group_by(group) %>%
  mutate(end_angle = 2*pi*cumsum(amount)/amount_total,
         start_angle = lag(end_angle, default = 0))

# now draw
ggplot(dat_pies) +
  geom_arc_bar(aes(x0 = imX, y0 = imY, r0 = 0, r = radius,
                   start = start_angle, end = end_angle, fill = type)) +
  coord_fixed()
</code>```

And now drawing the same on top of the image of a human skeleton:

```<code>library(cowplot)

ggplot(dat_pies) +
  draw_image("https://upload.wikimedia.org/wikipedia/commons/1/15/Human_skeleton_diagram.png",
             x=0, y=0, width = 2.2, height = 6) +
  geom_arc_bar(aes(x0 = imX, y0 = imY, r0 = 0, r = radius,
                   start = start_angle, end = end_angle, fill = type)) +
  coord_fixed()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to plot multiple piecharts on top of an image. I want to use custom_annotation to plot the rastered image. But right now I can't even get the multiple piecharts.

Ultimately I want 6 pies plotting in differnet spots over top of an image. imX and imY give the coordinates of where the pies should be on the image.

head(wholebody_cutLH_wide_t[c(1,2,102,103,104)])
Acidobacteriaceae Actinomycetaceae  imX imY radius
1      0.000000e+00     7.665687e-05 2.00 5.5    0.5
2      0.000000e+00     4.580237e-04 1.50 1.0    0.5
3      0.000000e+00     4.112573e-04 1.75 2.0    0.5
4      6.431473e-04     3.856008e-02 0.30 1.0    0.5
5      0.000000e+00     3.013013e-04 1.50 4.8    0.5
6      3.399756e-05     1.372986e-02 1.50 5.2    0.5

Now here is my attempt with scatterpie:

ggplot(wholebody_cutLH_wide_t) +
 #  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
 geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t, cols=NA,color=sample(allcolors,101)) +
 scale_color_manual(values=sample(allcolors,101)) +
 scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
 scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
 theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
  )

Now my error is:

Error: Only strings can be converted to symbols

Here is my attempt with dplyr and ggforce:

dat_pies<-left_join(wholebody_cutLH,
                wholebody_cutLH %>%
                  group_by(tax_rank) %>%
                  summarize(Cnt_total = sum(count_norm))) %>%
group_by(tax_rank) %>%
mutate(end_angle = 2*pi*cumsum(count_norm)/Cnt_total,      # ending angle for   each pie slice
     start_angle = lag(end_angle, default = 0),   # starting angle for each pie slice
     mid_angle = 0.5*(start_angle + end_angle))

ggplot(dat_pies) +
geom_arc_bar(aes(x0 = imX, y0 = imY, r0 = 0, r = rpie,
               start = start_angle, end = end_angle, fill = Volume)) +
geom_text(aes(x = rlabel*sin(mid_angle), y = rlabel*cos(mid_angle), label = Cnt),
        hjust = 0.5, vjust = 0.5) +
coord_fixed() +
scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +

Here my error is :

Error in ggplot(dat_pies) + geom_arc_bar(aes(x0 = imX, y0 = imY, r0 = 0,  :
could not find function "+<-"

Any help with either of these methods would be great.
thanks

Body:
It doesn't look like you've actually adapted your code to your data. Here's the ggforce example fixed up:

wholebody_cutLH_wide_t <- read.table(text = "Acidobacteriaceae Actinomycetaceae  imX imY radius
      0.000000e+00     7.665687e-05 2.00 5.5    0.5
      0.000000e+00     4.580237e-04 1.50 1.0    0.5
      0.000000e+00     4.112573e-04 1.75 2.0    0.5
      6.431473e-04     3.856008e-02 0.30 1.0    0.5
      0.000000e+00     3.013013e-04 1.50 4.8    0.5
      3.399756e-05     1.372986e-02 1.50 5.2    0.5", header = TRUE)

library(tidyr)
library(dplyr)
library(ggforce)

# convert to long format, add a grouping variable to keep track of which pies go together
wholebody_cutLH_long <- mutate(wholebody_cutLH_wide_t, group=letters[1:6]) %>%
  gather(type, amount, -imX, -imY, -radius, -group)

dat_pies<-left_join(wholebody_cutLH_long,
                    wholebody_cutLH_long %>%
                      group_by(group) %>%
                      summarize(amount_total = sum(amount))) %>%
  group_by(group) %>%
  mutate(end_angle = 2*pi*cumsum(amount)/amount_total,
         start_angle = lag(end_angle, default = 0))

# now draw
ggplot(dat_pies) +
  geom_arc_bar(aes(x0 = imX, y0 = imY, r0 = 0, r = radius,
                   start = start_angle, end = end_angle, fill = type)) +
  coord_fixed()

And now drawing the same on top of the image of a human skeleton:

library(cowplot)

ggplot(dat_pies) +
  draw_image("https://upload.wikimedia.org/wikipedia/commons/1/15/Human_skeleton_diagram.png",
             x=0, y=0, width = 2.2, height = 6) +
  geom_arc_bar(aes(x0 = imX, y0 = imY, r0 = 0, r = radius,
                   start = start_angle, end = end_angle, fill = type)) +
  coord_fixed()


问:
Wrapping multi-line custom header using react-navigation
I am using a react-navigation stack navigator embedded in a drawer navigator.  I would like to be able to have two lines for the header text if the header text is long.  Here is what I have tried:

```<code> static navigationOptions = ({ navigation }) => {
    return {
        title: (
            <Text
                numberOfLines = {2}
            >
                Let's see how long the title can be
            </Text>
        ),
        headerTitleStyle:
            {
                color: Colors.ORANGE,
            },
        headerTintColor: Colors.ORANGE,
        headerRight:
          <MenuIcon
              navigation = {navigation}
          />,
    };
};
</code>```

This doesn't work. Instead, the title is displayed as "Let's see how lo...".  When I try to create a similar text component in one of my screens, it wraps the text as intended.

How can I implement a multi-line title using react-navigation?

答:
This was what I finally used to have 2 lines of text in the title:</p>

```<code>static navigationOptions = ({ navigation }) => {
        return {
            title: (
                <View
                    style = {{width: 220, height: 50}}
                >
                    <Text
                        numberOfLines = {2}
                        style = {{color: Colors.ORANGE, fontWeight: '700', fontSize: 14, textAlign: 'center', marginRight: 60, marginTop: 12}}
                    >
                        Let's see how long the title can be
                    </Text>
                </View>
            ),
            headerTintColor: Colors.ORANGE,
            headerRight:
          <MenuIcon
              navigation = {navigation}
          />,
        };
    }
</code>```

Body:
I am using a react-navigation stack navigator embedded in a drawer navigator.  I would like to be able to have two lines for the header text if the header text is long.  Here is what I have tried:

 static navigationOptions = ({ navigation }) => {
    return {
        title: (
            <Text
                numberOfLines = {2}
            >
                Let's see how long the title can be
            </Text>
        ),
        headerTitleStyle:
            {
                color: Colors.ORANGE,
            },
        headerTintColor: Colors.ORANGE,
        headerRight:
          <MenuIcon
              navigation = {navigation}
          />,
    };
};

This doesn't work. Instead, the title is displayed as "Let's see how lo...".  When I try to create a similar text component in one of my screens, it wraps the text as intended.

How can I implement a multi-line title using react-navigation?

Body:
This was what I finally used to have 2 lines of text in the title:

static navigationOptions = ({ navigation }) => {
        return {
            title: (
                <View
                    style = {{width: 220, height: 50}}
                >
                    <Text
                        numberOfLines = {2}
                        style = {{color: Colors.ORANGE, fontWeight: '700', fontSize: 14, textAlign: 'center', marginRight: 60, marginTop: 12}}
                    >
                        Let's see how long the title can be
                    </Text>
                </View>
            ),
            headerTintColor: Colors.ORANGE,
            headerRight:
          <MenuIcon
              navigation = {navigation}
          />,
        };
    }


问:
pass multiple variables to module
I can't seem to get to figure out how to pass hashrefs to a module correctly.

```<code>#module helper.pm

my %helpers;

sub import {
    shift @_; #returns "helper"
    %SOME_CONFIG = %{shift @_};
    foreach my $hashref (%{@_}){
        $helpers{$hashref->{key}} = $hashref->{value};
    }
}

#main

use helper(
    \%SOME_CONFIG,
    "first_helper" => (
        sub {
            return do_something();
        },
        sub {
            return do_something_else();
        }
    ),
    "second_helper" => (
        sub {
            return something_else();
        }
    )
);
</code>```

I'm not sure how to convert the array to a hash correctly. I thought it work because the anonymous function are passed as references. However it still indexes over @_ as if it is an array and the keys become the indexes of @_.

答:
Lowercase module names are reserved by Perl, and the convention is to use them for pragmas. That's two misses, so let's rename the module to Helper. (Don't forget to change the file name to match!)

The arguments are

"Helper"

\%SOME_CONFIG

"first_helper"

sub { 1 }

sub { 2 }

"second_helper"

sub { 3 }

You probably meant to pass the sub refs in arrays, but you used parens. Parens just change precedence. Instead, you should have used the following:

```<code>use Helper (
    \%SOME_CONFIG,
    "first_helper" => [
        sub {
            return do_something();
        },
        sub {
            return do_something_else();
        }
    ],
    "second_helper" => [
        sub {
            return something_else();
        }
    ],
);
</code>```

Now, the arguments are

"Helper"

\%SOME_CONFIG

"first_helper"

[ sub { 1 }, sub { 2 } ]

"second_helper"

[ sub { 3 } ]

There's no hash in there other than \%SOME_CONFIG, but you have a hash dereference. That's no good. We could build a hash in the caller, but there's no need to make that any longer since we can handle the data as-is. Solutions:

```<code>sub import {
    my $class = shift;
    my $config = shift;
    my %new_helpers = @_;
    for my $id (keys(%new_helpers)) {
        $helpers{$id} = $new_helpers{$id};
    }
}
</code>```

or

```<code>sub import {
    my $class = shift;
    my $config = shift;
    %helpers = ( %helpers, @_ );
}
</code>```

or

```<code>sub import {
    my $class = shift;
    my $config = shift;
    while (@_) {
       my $id = shift;
       $helpers{$id} = shift;
    }
}
</code>```

Title: pass multiple variables to module

Body:
I can't seem to get to figure out how to pass hashrefs to a module correctly.

#module helper.pm

my %helpers;

sub import {
    shift @_; #returns "helper"
    %SOME_CONFIG = %{shift @_};
    foreach my $hashref (%{@_}){
        $helpers{$hashref->{key}} = $hashref->{value};
    }
}

#main

use helper(
    \%SOME_CONFIG,
    "first_helper" => (
        sub {
            return do_something();
        },
        sub {
            return do_something_else();
        }
    ),
    "second_helper" => (
        sub {
            return something_else();
        }
    )
);

I'm not sure how to convert the array to a hash correctly. I thought it work because the anonymous function are passed as references. However it still indexes over @_ as if it is an array and the keys become the indexes of @_.

Body:
Lowercase module names are reserved by Perl, and the convention is to use them for pragmas. That's two misses, so let's rename the module to Helper. (Don't forget to change the file name to match!)

The arguments are

"Helper"

\%SOME_CONFIG

"first_helper"

sub { 1 }

sub { 2 }

"second_helper"

sub { 3 }

You probably meant to pass the sub refs in arrays, but you used parens. Parens just change precedence. Instead, you should have used the following:

use Helper (
    \%SOME_CONFIG,
    "first_helper" => [
        sub {
            return do_something();
        },
        sub {
            return do_something_else();
        }
    ],
    "second_helper" => [
        sub {
            return something_else();
        }
    ],
);

Now, the arguments are

"Helper"

\%SOME_CONFIG

"first_helper"

[ sub { 1 }, sub { 2 } ]

"second_helper"

[ sub { 3 } ]

There's no hash in there other than \%SOME_CONFIG, but you have a hash dereference. That's no good. We could build a hash in the caller, but there's no need to make that any longer since we can handle the data as-is. Solutions:

sub import {
    my $class = shift;
    my $config = shift;
    my %new_helpers = @_;
    for my $id (keys(%new_helpers)) {
        $helpers{$id} = $new_helpers{$id};
    }
}

or

sub import {
    my $class = shift;
    my $config = shift;
    %helpers = ( %helpers, @_ );
}

or

sub import {
    my $class = shift;
    my $config = shift;
    while (@_) {
       my $id = shift;
       $helpers{$id} = shift;
    }
}


问:
Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)
I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.

The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.

Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.

What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)

What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.

function save() {
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var telephone = document.getElementById('telephone');

    $.ajax({
        url: "save.php",
        method: "POST",
        data: { name: name.value, email: email.value, telephone: telephone.value },
        success: $("List").load(" List")
    });
}```

Thank you in advanced and if I need include further info don't hesitate to ask.

答:
From this comment

as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam

I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)

I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.

Thanks!

(Won't let me mark as answered until 2 days)

Body:
I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.

The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.

Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.

What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)

What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.

function save() {
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var telephone = document.getElementById('telephone');

    $.ajax({
        url: "save.php",
        method: "POST",
        data: { name: name.value, email: email.value, telephone: telephone.value },
        success: $("List").load(" List")
    });
}

Thank you in advanced and if I need include further info don't hesitate to ask.


问:
Load and store contents of a webpage on local host with PHP or Javascript
I need to read and store contents of a page, stored on my local PC, with PHP or JavaScript .
I am running a loaclhost on my PC at the following address and it has contents that I like to load the page and store the contents:

http://10.0.0.210:10009

obviously, I cannot use CURL or file_get_contents() from PHP as they pertain to the server side.
I could do a Location : url and open the local page, but I need to get the content and store it in a variable, so I can parse them.
What is the best way to achieve this? Javascript, jQuery. How? Thank you

答: I think both CURL and jQuery (ajax) could do this. CURL is not server side only.</p>


问:
Should i orphan OpenCL buffers?
In OpenGL it is a common practice to orphan buffers that are used frequently. Ideally the drivers notices that a buffer of the same size is requested and if possible returns the old buffer if it is not needed anymore. The buffer only allocates new memory when the old buffer is still in use and can't be reused.

In OpenCL (on NVIDIA Hardware using the latest developer drivers) i am not sure about this technic. I got a 256kB buffer that is handled by the c++ wrapper refcounting which i reallocate frequently. Most of the time this works fine but in some cases OpenCL throws a CL_OUT_OF_MEMORY error while allocating a new buffer.

Do you think that i should switch my approach (e.g. using a constant number of buffers)? Or should i investigate in an other possible cause for this problem?

Kind regards,
Florian

答: OpenCL uses the C semantics for memory allocation and deallocation. As such, it will not automatically reuse buffers. You have to explicitly release a buffer and allocate a new buffer later. Alternatively, it seems to be a good practice to reuse buffers manually. Allocation can be a quite expensive operation.

ContentLicense: CC BY-SA 2.5

Title: Should i orphan OpenCL buffers?


问:
deploying production mode with Vue-cli created project
Bit of a n00b question:
I created project with vue-cli using webpack.
On my windows machine I run "npm un dev" and I get a frontend server with HMR and so on.
Now I want to deploy my app to a production machine - ubuntu on DigitalOcean.

What are the steps I must take? I'm not very familiar with the logic of how it's supposed to work. If my ubuntu machine has NODE_ENV set to production, it won't install any of the devDependancies and i'm not able to build anything. So I guess I'll have to change that? If yes then it doesn't make any sense since it's a production machine.

And do I have to create another node/express server to serve index.html? Won't it supposed to work out-of-the-box somehow?

Thanks :)

答:
TL;DR Build on your local machine and everything you need will be outputted in the ./dist/ directory, just copy the contents over to the webroot on your production server and you're good to go.

The webpack template handles most of the stuff for you.

Step you need to take to release:

Run npm run build on your local machine

Copy the contents of the generated ./dist/ directory to your server webroot

That's it!

When you run npm run build, the pre-configured build script sets the node environment to production, and builds with only the stuff that should be in production, it also optimizes the code and removes debug capabilities. When it comes to dependencies webpack takes care of that and includes them in the generated javascript files located in the ./dist/js/, so you need not concern yourself with copying over the node_modules/ directory either.
It also copies over everything in your static directory and src/assets directory to the ./dist/ directory to be prepare for a release. And resolves all the references to the new path generated by webpack.

The production server should not be concerned with building the vue app, run the build command on your local machine to keep dev dependencies away from your production server. I recommend against installing webpack and other dev tools on your production server. It just pollutes the server with things not needed there.
Some development tools could potentially produce alot of issues on production servers. So best practice is to never install them.

You could optionally create your own release script that uses ftp or rsync, whatver you prefer to copy everything in the ./dist/ directory to the production server webroot. This could be a script in bash, if on windows, run it in git bash or something similar for example.

Hope that cleared things up, congrats on your first vue release!


问:
WPF MVVM Binding Text of TextBlock to ObservableCollection Member
I would like to bind the value of an ObservableCollection to the "Text" of TextBlock in WindowMain.  The DataContext of WindowMain points to its ViewModel(WindowMainVM.cs). INotifyPropertyChanged is held in ObservableObject.  I have a separate Model class for the ObservableCollection called OPEmpName.cs.  I have combed Google for days and have not found a viable solution.

After the Username and Password are entered, the name of the User should appear in the TextBlock. (Demonstration Purposes Only) As it stands, the TextBlock remains blank after the method fires.  Where am I going wrong?  Thank you so much for the help!

WindowMain.xaml

```<code>    <Grid>
        <Label x:Name="lblUsername" Content="Username" HorizontalAlignment="Left" Margin="45,57,0,0" VerticalAlignment="Top"/>
        <Label x:Name="lblPassword" Content="Password" HorizontalAlignment="Left" Margin="48,104,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtUsername" Text="{Binding Textbox1Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Left" Height="23" Margin="128,60,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="txtPassword" Text="{Binding Textbox2Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Left" Height="23" Margin="128,108,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>

        <TextBlock HorizontalAlignment="Left" Height="23" Margin="91,214,0,0" TextWrapping="Wrap" Text="{Binding OPEmpNameList.Name}" VerticalAlignment="Top" Width="120"/>

    </Grid>
</code>```

WindowMainVM.cs

```<code>public class WindowMainVM : ObservableObject
{
    private string _textbox1Input;
    private string _textbox2Input;
    private string _name;
    private int _empNum;
    private ObservableCollection<OPEmpName> _opEmpNameList;

    public String Textbox1Input
    {
        get { return _textbox1Input; }
        set { SetProperty(ref _textbox1Input, value, () => Textbox1Input); }
    }

    public String Textbox2Input
    {
        get { return _textbox2Input; }
        set
        {
            SetProperty(ref _textbox2Input, value, () => Textbox2Input);
            if (Textbox2Input != null)
            {
                fillNAME();
            }
        }
    }

    public String NAME
    {
        get { return _name; }
        set { SetProperty(ref _name, value, () => NAME); }
    }

    public int OPEMPNUM
    {
        get { return _empNum; }
        set { SetProperty(ref _empNum, value, () => OPEMPNUM); }
    }

    public ObservableCollection<OPEmpName> OPEmpNameList
    {
        get { return _opEmpNameList; }
        set
        {
            SetProperty(ref _opEmpNameList, value, () => OPEmpNameList);
        }
    }

    public WindowMainVM() : base()
    {
        OPEmpNameList = new ObservableCollection<OPEmpName>();
    }

    private void fillNAME()
    {
        if (Textbox2Input != null)
        {
            using (MySqlConnection con = new MySqlConnection(dbConnectionString))
            {
                OPEmpNameList = new ObservableCollection<OPEmpName>();
                con.Open();
                string Query = "SELECT first_name FROM op_rep_users WHERE username='" + Textbox1Input + "' AND password='" + Textbox2Input + "' ";
                MySqlCommand createCommand = new MySqlCommand(Query, con);
                MySqlDataReader dr = createCommand.ExecuteReader();
                int count = 1;
                while (dr.Read())
                {
                    string Name = dr.GetString(0);
                    OPEmpName name = new OPEmpName(count, Name);
                    OPEmpNameList.Add(name);
                    count++;
                }
                con.Close();
            }

        }

    }
}
</code>```

OPEmpName.cs

```<code>    public class OPEmpName : ObservableObject
{
    private Int32 _count;
    private String _name;
    private ObservableCollection<OPEmpName> _opEmpNameList;

    public Int32 Count
    {
        get { return _count; }
        set { SetProperty(ref _count, value, () => Count); }
    }

    public String Name
    {
        get { return _name; }
        set { SetProperty(ref _name, value, () => Name); }
    }

    public ObservableCollection<OPEmpName> OPEmpNameList
    {
        get { return _opEmpNameList; }
        set { SetProperty(ref _opEmpNameList, value, () => OPEmpNameList); }
    }

    public OPEmpName() : base()
    {
        Count = 0;
        Name = "";
        OPEmpNameList = new ObservableCollection<OPEmpName>();
    }

    public OPEmpName(int count, string name) : base()
    {
        Count = count;
        Name = name;
        OPEmpNameList = new ObservableCollection<OPEmpName>();
    }
}
</code>```

答:
You seem to be doing a search that returns a list, but you have only one item bound to that list. You set the TextBlock to "{Binding OPEmpNameList.Name}", but OPEmpNameList is a list. You should put the results into a container like:</p>

```<code><ListBox ItemsSource="{Binding OEmpNameList}" DisplayMemberPath="Name" />
</code>```

Body:
I would like to bind the value of an ObservableCollection to the "Text" of TextBlock in WindowMain.  The DataContext of WindowMain points to its ViewModel(WindowMainVM.cs). INotifyPropertyChanged is held in ObservableObject.  I have a separate Model class for the ObservableCollection called OPEmpName.cs.  I have combed Google for days and have not found a viable solution.

After the Username and Password are entered, the name of the User should appear in the TextBlock. (Demonstration Purposes Only) As it stands, the TextBlock remains blank after the method fires.  Where am I going wrong?  Thank you so much for the help!

WindowMain.xaml

    <Grid>

        <TextBox x:Name="txtUsername" Text="{Binding Textbox1Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Left" Height="23" Margin="128,60,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="txtPassword" Text="{Binding Textbox2Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             HorizontalAlignment="Left" Height="23" Margin="128,108,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>

        <TextBlock HorizontalAlignment="Left" Height="23" Margin="91,214,0,0" TextWrapping="Wrap" Text="{Binding OPEmpNameList.Name}" VerticalAlignment="Top" Width="120"/>

    </Grid>

WindowMainVM.cs

public class WindowMainVM : ObservableObject
{
    private string _textbox1Input;
    private string _textbox2Input;
    private string _name;
    private int _empNum;
    private ObservableCollection<OPEmpName> _opEmpNameList;

    public String Textbox1Input
    {
        get { return _textbox1Input; }
        set { SetProperty(ref _textbox1Input, value, () => Textbox1Input); }
    }

    public String Textbox2Input
    {
        get { return _textbox2Input; }
        set
        {
            SetProperty(ref _textbox2Input, value, () => Textbox2Input);
            if (Textbox2Input != null)
            {
                fillNAME();
            }
        }
    }

    public String NAME
    {
        get { return _name; }
        set { SetProperty(ref _name, value, () => NAME); }
    }

    public int OPEMPNUM
    {
        get { return _empNum; }
        set { SetProperty(ref _empNum, value, () => OPEMPNUM); }
    }

    public ObservableCollection<OPEmpName> OPEmpNameList
    {
        get { return _opEmpNameList; }
        set
        {
            SetProperty(ref _opEmpNameList, value, () => OPEmpNameList);
        }
    }

    public WindowMainVM() : base()
    {
        OPEmpNameList = new ObservableCollection<OPEmpName>();
    }

    private void fillNAME()
    {
        if (Textbox2Input != null)
        {
            using (MySqlConnection con = new MySqlConnection(dbConnectionString))
            {
                OPEmpNameList = new ObservableCollection<OPEmpName>();
                con.Open();
                string Query = "SELECT first_name FROM op_rep_users WHERE username='" + Textbox1Input + "' AND password='" + Textbox2Input + "' ";
                MySqlCommand createCommand = new MySqlCommand(Query, con);
                MySqlDataReader dr = createCommand.ExecuteReader();
                int count = 1;
                while (dr.Read())
                {
                    string Name = dr.GetString(0);
                    OPEmpName name = new OPEmpName(count, Name);
                    OPEmpNameList.Add(name);
                    count++;
                }
                con.Close();
            }

        }

    }
}

OPEmpName.cs

    public class OPEmpName : ObservableObject
{
    private Int32 _count;
    private String _name;
    private ObservableCollection<OPEmpName> _opEmpNameList;

    public Int32 Count
    {
        get { return _count; }
        set { SetProperty(ref _count, value, () => Count); }
    }

    public String Name
    {
        get { return _name; }
        set { SetProperty(ref _name, value, () => Name); }
    }

    public ObservableCollection<OPEmpName> OPEmpNameList
    {
        get { return _opEmpNameList; }
        set { SetProperty(ref _opEmpNameList, value, () => OPEmpNameList); }
    }

    public OPEmpName() : base()
    {
        Count = 0;
        Name = "";
        OPEmpNameList = new ObservableCollection<OPEmpName>();
    }

    public OPEmpName(int count, string name) : base()
    {
        Count = count;
        Name = name;
        OPEmpNameList = new ObservableCollection<OPEmpName>();
    }
}

Body:
You seem to be doing a search that returns a list, but you have only one item bound to that list. You set the TextBlock to "{Binding OPEmpNameList.Name}", but OPEmpNameList is a list. You should put the results into a container like:

<ListBox ItemsSource="{Binding OEmpNameList}" DisplayMemberPath="Name" />


问:
Generate random tokens (unique id's) for users in a table in SQL server
I want to create a table in sql server and fill it up with data (people's info). The goal is to get every person a unique ID in the first row which has to start with fixed alphabets GM followed by A-Z or 2-9 numeric , initial of First name, Initial of Last name and A-Z or 2-9.

答:
There are a couple of ambiguities in your question, but hopefully by reading through this you will be able to fill in the blanks.

One question you may want to ask is if you truly want to go within the ID constraints you've provided. It may make a lot more sense to use an identity column (see: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property).

The exact syntax depends on which dialect of SQL you're working with. Take a look at this: https://www.w3schools.com/sql/sql_autoincrement.asp

For MS SQL server it would look something like this:

```<code>create table User (
   [UserID] int IDENTITY(1,1) PRIMARY KEY,
   [FirstName] varchar(50) not null,
   [LastName] varchar(50) not null
)
</code>```

Let's say you populated this table with a few entries. If for some arbitrary requirement you needed "GM" in the front and the user's initials at the end, you could do something like:

```<code>select 'GM'+UserID+'substring(FirstName,0,1)+substring(LastName,0,1) from User
</code>```

To answer your question more directly, it appears that you are asking for each user to have an ID that looks like GM[A-Z or 2-9][FirstInitial][LastInitial][A-Z or 2-9)]

This setup will give you a lot more of a headache, but it's certainly doable. Note that, as I understand your request, having just one character of A-Z/0-9 after GM and another character after the initials will give you a very limited # of possible unique ID's.

You did not give a max ID character length, so I'm assuming the entire length is fixed at 6 characters ("G","M","A-Z/2-9","F","L","A-Z/2-9"). If I'm misunderstanding you then it will definitely change the answer but hopefully this is still useful.

You could create a User table and a table that holds your possible characters like this:

```<code>create table UserTable  (
    ID varchar(50),
    FirstName varchar(50),
    LastName varchar(50)
)

create table PChars (
    Possibility varchar(1)
)

insert into PChars (Possibility) values
('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H'),('I'),('J'),('K'),('L'),('M'),('N'),('O'),('P'),('Q'),('R'),('S'),('T'),('U'),('V'),('W'),('X'),('Y'),('Z'),('2'),('3'),('4'),('5'),('6'),('7'),('8'),('9')
</code>```

Then you can run the following over and over, note that John and Jane will never have the same ID even though they have the same initials. The while clause forbids it.

Also note that eventually this will break. If enough people with the same initials were in the table, the while clause could turn into an infinite loop. That's why this is kind of a bad idea!!!

```<code>delete UserTable /*this is just here so you can run this code over and over*/

/*John Doe*/
declare @FirstName varchar(50) = 'John'
declare @LastName varchar(50) = 'Doe'
declare @newID varchar(50) = ''
while(@newID = '' or @newID in (select distinct ID from UserTable))
  begin
    select @newID = 'GM'+(select top 1 Possibility from PChars order by newid())+substring(@FirstName,1,1)+substring(@LastName,1,1)+(select top 1 Possibility from PChars order by newid())
  end
insert into UserTable select @newID,@FirstName,@LastName

/*Jane Doe*/
select @FirstName = 'Jane'
select @LastName = 'Doe'
select @newID = ''
while(@newID = '' or @newID in (select distinct ID from UserTable))
  begin
    select @newID = 'GM'+(select top 1 Possibility from PChars order by newid())+substring(@FirstName,1,1)+substring(@LastName,1,1)+(select top 1 Possibility from PChars order by newid())
  end
insert into UserTable select @newID,@FirstName,@LastName

select * from UserTable
</code>```

Here is some sample output:

```
+--------+-----------+----------+
|   ID   | FirstName | LastName |
+--------+-----------+----------+
| GMOJDF | John      | Doe      |
| GM2JDD | Jane      | Doe      |
+--------+-----------+----------+
```

So again, I feel like I am somewhat misinterpreting your question, but I think this gives you a good launching point.

Body:
There are a couple of ambiguities in your question, but hopefully by reading through this you will be able to fill in the blanks.

One question you may want to ask is if you truly want to go within the ID constraints you've provided. It may make a lot more sense to use an identity column (see: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property).

The exact syntax depends on which dialect of SQL you're working with. Take a look at this: https://www.w3schools.com/sql/sql_autoincrement.asp

For MS SQL server it would look something like this:

create table User (
   [UserID] int IDENTITY(1,1) PRIMARY KEY,
   [FirstName] varchar(50) not null,
   [LastName] varchar(50) not null
)

Let's say you populated this table with a few entries. If for some arbitrary requirement you needed "GM" in the front and the user's initials at the end, you could do something like:

select 'GM'+UserID+'substring(FirstName,0,1)+substring(LastName,0,1) from User

To answer your question more directly, it appears that you are asking for each user to have an ID that looks like GM[A-Z or 2-9][FirstInitial][LastInitial][A-Z or 2-9)]

This setup will give you a lot more of a headache, but it's certainly doable. Note that, as I understand your request, having just one character of A-Z/0-9 after GM and another character after the initials will give you a very limited # of possible unique ID's.

You did not give a max ID character length, so I'm assuming the entire length is fixed at 6 characters ("G","M","A-Z/2-9","F","L","A-Z/2-9"). If I'm misunderstanding you then it will definitely change the answer but hopefully this is still useful.

You could create a User table and a table that holds your possible characters like this:

create table UserTable  (
    ID varchar(50),
    FirstName varchar(50),
    LastName varchar(50)
)

create table PChars (
    Possibility varchar(1)
)

insert into PChars (Possibility) values
('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H'),('I'),('J'),('K'),('L'),('M'),('N'),('O'),('P'),('Q'),('R'),('S'),('T'),('U'),('V'),('W'),('X'),('Y'),('Z'),('2'),('3'),('4'),('5'),('6'),('7'),('8'),('9')

Then you can run the following over and over, note that John and Jane will never have the same ID even though they have the same initials. The while clause forbids it.

Also note that eventually this will break. If enough people with the same initials were in the table, the while clause could turn into an infinite loop. That's why this is kind of a bad idea!!!

delete UserTable /*this is just here so you can run this code over and over*/

/*John Doe*/
declare @FirstName varchar(50) = 'John'
declare @LastName varchar(50) = 'Doe'
declare @newID varchar(50) = ''
while(@newID = '' or @newID in (select distinct ID from UserTable))
  begin
    select @newID = 'GM'+(select top 1 Possibility from PChars order by newid())+substring(@FirstName,1,1)+substring(@LastName,1,1)+(select top 1 Possibility from PChars order by newid())
  end
insert into UserTable select @newID,@FirstName,@LastName

/*Jane Doe*/
select @FirstName = 'Jane'
select @LastName = 'Doe'
select @newID = ''
while(@newID = '' or @newID in (select distinct ID from UserTable))
  begin
    select @newID = 'GM'+(select top 1 Possibility from PChars order by newid())+substring(@FirstName,1,1)+substring(@LastName,1,1)+(select top 1 Possibility from PChars order by newid())
  end
insert into UserTable select @newID,@FirstName,@LastName

select * from UserTable

Here is some sample output:

+--------+-----------+----------+
|   ID   | FirstName | LastName |
+--------+-----------+----------+
| GMOJDF | John      | Doe      |
| GM2JDD | Jane      | Doe      |
+--------+-----------+----------+

So again, I feel like I am somewhat misinterpreting your question, but I think this gives you a good launching point.


问:
bootstrap 4 center items except first element

.c-footer {
  background: #000;
  padding: 20px 0;
  color: #fff; }
  .c-footer__logo {
    display: inline; }
  .c-footer__link {
    color: inherit; }
    .c-footer__link a {
      color: inherit; }
      .c-footer__link a:hover {
        color: #fff; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="c-footer text-center">
 <div class="c-footer__logo">
  <img src="http://dynamicdog.se/wp-content/themes/dynamicdog/img/logo.png">
 </div>
 <span class="c-footer__link">
  Malmö<span> - </span>
 </span>
 <span class="c-footer__link">
  Stockholm<span> - </span>
 </span>
  <span class="c-footer__link">
  Malmö<span> - </span>
 </span>
 <span class="c-footer__link">
  Stockholm<span> - </span>
 </span>
  <span class="c-footer__link">
  Malmö<span> - </span>
 </span>
 <span class="c-footer__link">
  Stockholm
 </span>
</div></code>```

I want to accomplish the picture below:

Centering the text while having the image floated to the left. I tried with the bootstrap class center-text however it centers all elements...

Heres my markup:

```<code><div class="c-footer">
 <div class="c-footer__logo">
  <img src="/static/media/q-logo.98ed5701.png">
 </div>
 <span class="c-footer__link">
  <a href="#">Malmö</a><span> - </span>
 </span>
 <span class="c-footer__link">
  <a href="#">Stockholm</a><span> - </span>
 </span>
</div>
</code>```

How would you accomplish this?

答:
Using the flex properties, you can just have a div on each side. Since the logo is 100px in my example, I have it set as 100px. Remember to the have the img have a class of img-fluid.

I've also attached a codepen for you.
https://codepen.io/Gwapedwink/pen/yPmaVN?editors=1100#0

```<code><footer>
  <div class="container d-flex align-items-center">
    <div class="footer-side">
      <img src="http://placehold.it/400/fff/999&text=LOGO" class="img-fluid" />
    </div>
    <div class="mx-auto d-flex">
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
    </div>
    <div class="footer-side">
      <!-- nothing here, homie -->
    </div>
  </div>
</footer>

<style>
/* this is all that matters */
footer .footer-side {
  width: 100px; /* whatever you want the logo width to be */
}
</style>
</code>```

Body:
.c-footer {
  background: #000;
  padding: 20px 0;
  color: #fff; }
  .c-footer__logo {
    display: inline; }
  .c-footer__link {
    color: inherit; }
    .c-footer__link a {
      color: inherit; }
      .c-footer__link a:hover {
        color: #fff; }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

  Malmö -

  Stockholm -

  Malmö -

  Stockholm -

  Malmö -

  Stockholm

I want to accomplish the picture below:

Centering the text while having the image floated to the left. I tried with the bootstrap class center-text however it centers all elements...

Heres my markup:

  Malmö -

  Stockholm -

How would you accomplish this?

Body:
Using the flex properties, you can just have a div on each side. Since the logo is 100px in my example, I have it set as 100px. Remember to the have the img have a class of img-fluid.

I've also attached a codepen for you.
https://codepen.io/Gwapedwink/pen/yPmaVN?editors=1100#0

<footer>
  <div class="container d-flex align-items-center">
    <div class="footer-side">
      <img src="http://placehold.it/400/fff/999&text=LOGO" class="img-fluid" />
    </div>
    <div class="mx-auto d-flex">
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
      <a href="#" class="d-inline-block p-3 mx-2">Link Label</a>
    </div>
    <div class="footer-side">
      <!-- nothing here, homie -->
    </div>
  </div>
</footer>

<style>
/* this is all that matters */
footer .footer-side {
  width: 100px; /* whatever you want the logo width to be */
}
</style>


问:
Using ReBex to upload different files to FTP server?
I think im headed in the right direction, but would like anyones input.
I am working on a console app that is supposed to look for files in multiple folders, and then upload any files found to each corresponding folder on the FTP server (which is mirrored to match my local directory). Im new to using Rebex and FTP uploads in general. So far my code looks like this: </p>

```<code>            //Connect to SFTP server
            Sftp ftp = new Sftp();
            ftp.Connect(ftpServerURL);
            ftp.Login(ftpUserName, ftpPassword);

            //Upload local files to SFTP Server
            if (ftp.IsConnected == true)
            {
                ftp.PutFile(sourceFilePath, sftpTargetFolder);
            }
</code>```

<p>My question is: Will this code read through each folder in my local directory and upload them to the sftpTargetFolder? (sourceFilePath and sftpTargetFolder are currently defined in App.Config). Is this even the best method to do this? How do I go about catching errors during the upload? ANY input is appreciated greatly!!! Thank you. </p>

答:
I think I found the solution, it seems to work in testing. Take it if you will. </p>

```<code>            //Upload local files to FTP server

            ftp.Upload(sourceFilePath, "/", Rebex.IO.TraversalMode.Recursive, Rebex.IO.TransferMethod.Copy, Rebex.IO.ActionOnExistingFiles.OverwriteOlder);
            ftp.Disconnect();
</code>```

Body:
I think im headed in the right direction, but would like anyones input.
I am working on a console app that is supposed to look for files in multiple folders, and then upload any files found to each corresponding folder on the FTP server (which is mirrored to match my local directory). Im new to using Rebex and FTP uploads in general. So far my code looks like this:

            //Connect to SFTP server
            Sftp ftp = new Sftp();
            ftp.Connect(ftpServerURL);
            ftp.Login(ftpUserName, ftpPassword);

            //Upload local files to SFTP Server
            if (ftp.IsConnected == true)
            {
                ftp.PutFile(sourceFilePath, sftpTargetFolder);
            }

My question is: Will this code read through each folder in my local directory and upload them to the sftpTargetFolder? (sourceFilePath and sftpTargetFolder are currently defined in App.Config). Is this even the best method to do this? How do I go about catching errors during the upload? ANY input is appreciated greatly!!! Thank you.

Body:
I think I found the solution, it seems to work in testing. Take it if you will.

            //Upload local files to FTP server

            ftp.Upload(sourceFilePath, "/", Rebex.IO.TraversalMode.Recursive, Rebex.IO.TransferMethod.Copy, Rebex.IO.ActionOnExistingFiles.OverwriteOlder);
            ftp.Disconnect();


问:
Error while installing nuget package nuget package Kentor.OwinCookieSaver
I have ASP.NET MVC 5 application with .NET 4.5.1. The application is having issue as described in this SO post.

So as per the suggestion i am trying to install https://github.com/Sustainsys/owin-cookie-saver nuget package However i am getting error

Severity Code Description Project File    Line    Suppression State
  Error Could not install package 'Kentor.OwinCookieSaver 1.1.1'. You
  are trying to install this package into a project that targets
  '.NETFramework,Version=v4.5.1', but the package does not contain any
  assembly references or content files that are compatible with that
  framework. For more information, contact the package author.  0

any idea?

答:
Right now, the ASP.NET MVC 5 app you have is targeting .NET 4.5.1. No surprise there. The error says "You are trying to install this package into a project that targets '.NETFramework,Version=v4.5.1', but the package does not contain any assembly references or content files that are compatible with that framework."

The highlighted line indicates that the package you are trying to install is not built for .NET 4.5.1. I went ahead and downloaded the package itself (from NuGet.org). The package is currently targeting .NET 4.5.2. So if you change your target framework to .NET 4.5.2 and try to install, you will find it works out for you.

Ideally, packages available to the public would be built for a wider range of Target Frameworks but occasionally I do run into this. If you run into this again, go grab the package from the previous link (see the Manual Download on the right hand side of the page). Open up the .nupkg using 7-zip and open up the lib folder. There you will find what frameworks it is targeting and can adjust accordingly (or decide to try another package if you can't change).


问:
Java - Unzipping files compressed differently
Creating this application has become a pain in the ass! Using Java I want to unzip .zip files created by many different applications:
Using my 7-zip this works perfectly fine, Using somebodys winrar to compress the files completely messes them up!
Here's my code:

```<code> public static void ExtractModZip(File Zip, File Dest) {
        try {
            if (Zip.getName().toLowerCase().endsWith(".zip")) {
            }
            ZipFile zip = new ZipFile(Zip);
            System.out.println(zip.getName() + " opened.");
            Enumeration entries = zip.entries();
            String ModName = Zip.getName().substring(0, Zip.getName().length() - 4);
            File base = new File(Dest + File.separator + ModName);
            base.mkdirs();
            InputStream entryStream = null;
            FileOutputStream fos = null;
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                entryStream = zip.getInputStream(entry);
                String entryName = entry.getName().replace('/', File.separatorChar);
                entryName = entryName.replace('\\', File.separatorChar);

                if (!entry.isDirectory()) {
                    File file = new File(base + File.separator + entryName);
                    File Base = new File(base + File.separator);
                    if (!Base.exists()) {
                        Base.mkdirs();
                    }

                    fos = new FileOutputStream(file);
                    try {
                        // Allocate a buffer for reading the entry data.
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        // Read the entry data and write it to the output file.
                        while ((bytesRead = entryStream.read(buffer)) != -1) {
                            fos.write(buffer, 0, bytesRead);
                        }
                        System.out.println(entry.getName() + " extracted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    File file = new File(base + File.separator + entryName);
                    file.mkdir();
                }
            }
            fos.close();
            entryStream.close();
        } catch (ZipException ex) {
            Logger.getLogger(fileUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(fileUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
</code>```

Example:
I unzipped the fie using this method, it completely missed out a folder and certain files inside...

答: Try a different unzip (decompression) implementation. TrueZIP is well known.</p>

Body:
Creating this application has become a pain in the ass! Using Java I want to unzip .zip files created by many different applications:
Using my 7-zip this works perfectly fine, Using somebodys winrar to compress the files completely messes them up!
Here's my code:

 public static void ExtractModZip(File Zip, File Dest) {
        try {
            if (Zip.getName().toLowerCase().endsWith(".zip")) {
            }
            ZipFile zip = new ZipFile(Zip);
            System.out.println(zip.getName() + " opened.");
            Enumeration entries = zip.entries();
            String ModName = Zip.getName().substring(0, Zip.getName().length() - 4);
            File base = new File(Dest + File.separator + ModName);
            base.mkdirs();
            InputStream entryStream = null;
            FileOutputStream fos = null;
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                entryStream = zip.getInputStream(entry);
                String entryName = entry.getName().replace('/', File.separatorChar);
                entryName = entryName.replace('\\', File.separatorChar);

                if (!entry.isDirectory()) {
                    File file = new File(base + File.separator + entryName);
                    File Base = new File(base + File.separator);
                    if (!Base.exists()) {
                        Base.mkdirs();
                    }

                    fos = new FileOutputStream(file);
                    try {
                        // Allocate a buffer for reading the entry data.
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        // Read the entry data and write it to the output file.
                        while ((bytesRead = entryStream.read(buffer)) != -1) {
                            fos.write(buffer, 0, bytesRead);
                        }
                        System.out.println(entry.getName() + " extracted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    File file = new File(base + File.separator + entryName);
                    file.mkdir();
                }
            }
            fos.close();
            entryStream.close();
        } catch (ZipException ex) {
            Logger.getLogger(fileUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(fileUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Example:
I unzipped the fie using this method, it completely missed out a folder and certain files inside...


问:
Flexbox layout - Transition not working
I am working on the flexbox layout which has header, footer, and content.
In the content section i have multiple clickable flex items. When ever i click on anyone of the flex items, it will fill the whole width and height of the content section. I used transition:all for all the flex items to implement a simple animation; but its not working?

Please find the codepen link https://codepen.io/yesvin/pen/XzvdQo?editors=0100

HTML

```<code><div class="flxWrapper">
  <div class="flxHeader">
  </div>
<div class="flxContainer">
  <div class="flxItem"></div>
  <div class="flxItem"></div>
  <div class="flxItem"></div>
  <div class="flxItem"></div>
  <div class="flxItem" style="background-color:#ff0088;"></div>
  <div class="flxItem"></div>
  <div class="flxItem"></div>
  <div class="flxItem" style="background-color:#ff8800;"></div>
</div>
  <div class="flxFooter">
  </div>
</div>
</code>```

CSS

```<code>html, body {
  height:80vh;
}
.flxWrapper {
  width:600px;
  margin:0 auto;
  height:100%;
  border:solid 1px #ff0000;

  display:flex;
  align-items:stretch;
  justify-content:center;
  flex-direction:column;
}
.flxHeader {
  padding:20px;
  border-bottom:solid 1px #ccc;
}
.flxFooter {
  padding:20px;
  min-height:100px;
  border-top:solid 1px #ccc;
}
.flxContainer {
  display:flex;
  flex:1;

  flex-wrap:wrap;
  width:100%;
  border:none;
  margin:0 auto;
  position:relative;
}
.flxItem {
  padding:10px;
  margin:10px;
  border:solid 1px #000;
  transistion:all 2s ease-in-out 2s;
  width:calc(100% * (1/4));
  flex:1 0 auto;
  align-self:stretch;
}

.active {
  background:rgba(125,125,125,1);
  z-index:10;
  width:calc(100% * (1/1) - 40px);
  height:calc(100% * (1/1) - 40px);
  position:absolute;
  top:0;
  left:0;
  align-self:stretch;
}
</code>```

JS

```<code>$(document).on('click','.flxItem', function(){
  $(this).toggleClass('active');
});
</code>```

NOTE:

I am using in-line style for 2 flex items, to check the active clicked flex item.

Width is calculated based on no. of columns per row.

Any help would be greatly appreciated. Thanks in advance.

答:
You have a typo in the rule for .flxItem: "transistion" instead of "transition"

https://codepen.io/anon/pen/pdMErJ

Title: Flexbox layout - Transition not working

Body:
I am working on the flexbox layout which has header, footer, and content.
In the content section i have multiple clickable flex items. When ever i click on anyone of the flex items, it will fill the whole width and height of the content section. I used transition:all for all the flex items to implement a simple animation; but its not working?

Please find the codepen link https://codepen.io/yesvin/pen/XzvdQo?editors=0100

HTML

CSS

html, body {
  height:80vh;
}
.flxWrapper {
  width:600px;
  margin:0 auto;
  height:100%;
  border:solid 1px #ff0000;

  display:flex;
  align-items:stretch;
  justify-content:center;
  flex-direction:column;
}
.flxHeader {
  padding:20px;
  border-bottom:solid 1px #ccc;
}
.flxFooter {
  padding:20px;
  min-height:100px;
  border-top:solid 1px #ccc;
}
.flxContainer {
  display:flex;
  flex:1;

  flex-wrap:wrap;
  width:100%;
  border:none;
  margin:0 auto;
  position:relative;
}
.flxItem {
  padding:10px;
  margin:10px;
  border:solid 1px #000;
  transistion:all 2s ease-in-out 2s;
  width:calc(100% * (1/4));
  flex:1 0 auto;
  align-self:stretch;
}

.active {
  background:rgba(125,125,125,1);
  z-index:10;
  width:calc(100% * (1/1) - 40px);
  height:calc(100% * (1/1) - 40px);
  position:absolute;
  top:0;
  left:0;
  align-self:stretch;
}

JS

$(document).on('click','.flxItem', function(){
  $(this).toggleClass('active');
});

NOTE:

I am using in-line style for 2 flex items, to check the active clicked flex item.

Width is calculated based on no. of columns per row.

Any help would be greatly appreciated. Thanks in advance.


问:
output a column group by another column shell
I have a pathway.text file. The columns are separated by "\t".

The first column and second column are like:

```<code>Y123W    AB - CD - ED    ...
Y948W    ED - WG - SG -EG  ...
Y9368    AB - UE  ...
Y024W    AB - UE  ...
YOWB3    AB - CD - ED  ...
...
</code>```

I want to output elements in the first columns group by unique elements in the second column. It should be like (the format doesn't matter):

```<code>AB - CD - ED:
Y123W, YOWB3, ...
AB - UE:
Y9368, Y024W, ...
ED - WG - SG -EG:
Y948W, ...
...
</code>```

I first tried to read second column into an array:

```<code>pathways=( $(awk -F"\t" '{print $2}' pathway.txt) )
</code>```

Then I tried to sort the pathways to get unique pathways:

```<code>uniq=($(printf "%s\n" "${pathways[@]}" | sort -u))
</code>```

However, maybe because the elements of second column contain spaces " ", so the array uniq I got was in a mess.

```<code>echo "${uniq[@]}"
</code>```

The output is like:

```<code>AB AB AB AB CD CD ...
</code>```

I am new with shell. So i just tried to achieve it step by step with what I would do with python or R... Please help! Thanks a lot

答:
Try:

```<code>$ awk -F'\t' '{if ($2 in a) a[$2]=a[$2]", "$1; else a[$2]=$2":\n"$1} END{for (x in a)print a[x]}' file
AB - UE:
Y9368, Y024W
ED - WG - SG -EG:
Y948W
AB - CD - ED:
Y123W, YOWB3
</code>```

How it works

-F'\t'

This sets the field separator to a tab.

if ($2 in a) a[$2]=a[$2]", "$1; else a[$2]=$2":\n"$1

If the second field is already in array a, then append on the current field 1.  If it isn't, then start a new entry in a.

END{for (x in a)print a[x]}

After we have read the entire input file, print out the results.

Alternative

This version uses a ternary statement in the place of the if-else statement.

```<code>$ awk -F'\t' '{a[$2]=a[$2](a[$2]?", "$1:$1)} END{for (x in a)printf "%s:\n%s\n",x,a[x]}' file
AB - UE:
Y9368, Y024W
ED - WG - SG -EG:
Y948W
AB - CD - ED:
Y123W, YOWB3
</code>```

Body:
I have a pathway.text file. The columns are separated by "\t".

The first column and second column are like:

Y123W    AB - CD - ED    ...
Y948W    ED - WG - SG -EG  ...
Y9368    AB - UE  ...
Y024W    AB - UE  ...
YOWB3    AB - CD - ED  ...
...

I want to output elements in the first columns group by unique elements in the second column. It should be like (the format doesn't matter):

AB - CD - ED:
Y123W, YOWB3, ...
AB - UE:
Y9368, Y024W, ...
ED - WG - SG -EG:
Y948W, ...
...

I first tried to read second column into an array:

pathways=( $(awk -F"\t" '{print $2}' pathway.txt) )

Then I tried to sort the pathways to get unique pathways:

uniq=($(printf "%s\n" "${pathways[@]}" | sort -u))

However, maybe because the elements of second column contain spaces " ", so the array uniq I got was in a mess.

echo "${uniq[@]}"

The output is like:

AB AB AB AB CD CD ...

I am new with shell. So i just tried to achieve it step by step with what I would do with python or R... Please help! Thanks a lot

Body:
Try:

$ awk -F'\t' '{if ($2 in a) a[$2]=a[$2]", "$1; else a[$2]=$2":\n"$1} END{for (x in a)print a[x]}' file
AB - UE:
Y9368, Y024W
ED - WG - SG -EG:
Y948W
AB - CD - ED:
Y123W, YOWB3

How it works

-F'\t'

This sets the field separator to a tab.

if ($2 in a) a[$2]=a[$2]", "$1; else a[$2]=$2":\n"$1

If the second field is already in array a, then append on the current field 1.  If it isn't, then start a new entry in a.

END{for (x in a)print a[x]}

After we have read the entire input file, print out the results.

Alternative

This version uses a ternary statement in the place of the if-else statement.

$ awk -F'\t' '{a[$2]=a[$2](a[$2]?", "$1:$1)} END{for (x in a)printf "%s:\n%s\n",x,a[x]}' file
AB - UE:
Y9368, Y024W
ED - WG - SG -EG:
Y948W
AB - CD - ED:
Y123W, YOWB3


问:
panic: json: cannot unmarshal array into Go value of type main.Structure

What are you trying to accomplish?

I am trying to parse data from a json api.

Paste the part of the code that shows the problem.

```<code>package main

import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "net/http"
)

type Structure struct {
        stuff []interface{}
}

func main() {
        url := "https://api.coinmarketcap.com/v1/ticker/?start=0&limit=100"
        response, err := http.Get(url)
        if err != nil {
                panic(err)
        }
        body, err := ioutil.ReadAll(response.Body)
        if err != nil {
                panic(err)
        }
        decoded := &Structure{}
        fmt.Println(url)
        err = json.Unmarshal(body, decoded)
        if err != nil {
                panic(err)
        }
        fmt.Println(decoded)
}
</code>```

What do you expect the result to be?

I expected for the code to return a list of interface objects.

What is the actual result you get?

I got an error: panic: json: cannot unmarshal array into Go value of type main.Structure

答:
The application is unmarshalling a JSON array to a struct. Unmarshal to a slice:

```<code> var data []interface{}
 err = json.Unmarshal(body, &data)
</code>```

Consider unmarshalling to a slice of structs specific to the response data:

```<code> type Tick struct {
     ID string
     Name string
     Symbol string
     Rank string
     Price_USD string
     ... and so on
}

 var data []Tick
 err = json.Unmarshal(body, &data)
</code>```

Body:
What are you trying to accomplish?

I am trying to parse data from a json api.

Paste the part of the code that shows the problem.

package main

import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "net/http"
)

type Structure struct {
        stuff []interface{}
}

func main() {
        url := "https://api.coinmarketcap.com/v1/ticker/?start=0&limit=100"
        response, err := http.Get(url)
        if err != nil {
                panic(err)
        }
        body, err := ioutil.ReadAll(response.Body)
        if err != nil {
                panic(err)
        }
        decoded := &Structure{}
        fmt.Println(url)
        err = json.Unmarshal(body, decoded)
        if err != nil {
                panic(err)
        }
        fmt.Println(decoded)
}

What do you expect the result to be?

I expected for the code to return a list of interface objects.

What is the actual result you get?

I got an error: panic: json: cannot unmarshal array into Go value of type main.Structure

Body:
The application is unmarshalling a JSON array to a struct. Unmarshal to a slice:

 var data []interface{}
 err = json.Unmarshal(body, &data)

Consider unmarshalling to a slice of structs specific to the response data:

 type Tick struct {
     ID string
     Name string
     Symbol string
     Rank string
     Price_USD string
     ... and so on
}

 var data []Tick
 err = json.Unmarshal(body, &data)

ContentLicense: CC BY-SA 4.0


答:
Using a RegEx approach that cuts all numbers to two decimal places is pretty naive. Not all decimals are the same. Consider for example the following matrix transform:

```<code>transform="matrix(0.999848,0.017452,-0.034905,0.999543,-4.0838,-3.8401)"
</code>```

Cutting these numbers to two decimal places changes the second number by 41%. Is that significant? Yes, in fact you can use it for a nice embossing effect:

<svg viewBox="0 0 20 20" width="100" height="100">
  <text x="7" y="22" style="font-size:20;fill:#000000"
        transform="matrix(0.999848,0.017452,-0.034905,0.999543,-4.0838,-3.8401)">A</text>
  <text x="7" y="22" style="font-size:20;fill:#ffffff;opacity:0.8"
        transform="matrix(0.99,0.01,-0.03,0.99,-4.08,-3.84)">A</text>
</svg>```

This is why Inkscape uses the term "precision" in its settings and rounds to a fixed number of significant digits (123.4, 0.01234,...)

The second problem is that you might have a scaling transformation somewhere in your SVG. Did you see in the above snippet that the given size of the rectangle is scaled with a factor 5? It is implicit in the viewBox, ẁidth and height attributes. What if the scaling had been not 5, but 1000? And yes, I have seen these kind of relations in the wild. Especially if the grafic has been produced with Inkscape.

So: handle with care.

Title: Trim Decimal Places from Numbers in a Text Editor

Body:
I have a set of SVG definition exported from Inkspace and as anyone who has done this themselves will know the resulting definition often contains far more accuracy that is actually justified. For example for a 32 x32 icon definition shown below, Inkspace has generated 6 (or more!) decimal places of accuracy per pixel. Now I know that means it will scale but in my case I would rather save space in my app which requires input of hundreds of such icon definitions.

<svg width="32" height="32"><path d="M 14.576172 5.453125 L 13.78125 8.8222656 L 12.464844 9.3691406 L 9.5625 7.5898438 L 7.5898438 9.5351562 L 9.3691406 12.576172 L 8.8222656 13.78125 L 5.4785156 14.630859 L 5.4785156 17.369141 L 8.8496094 18.246094 L 9.3691406 19.507812 L 7.5625 22.464844 L 9.5351562 24.410156 L 12.548828 22.658203 L 13.808594 23.177734 L 14.603516 26.494141 L 17.396484 26.521484 L 18.191406 23.177734 L 19.505859 22.658203 L 22.410156 24.410156 L 24.355469 22.410156 L 22.658203 19.451172 L 23.150391 18.191406 L 26.492188 17.369141 L 26.492188 14.630859 L 23.123047 13.726562 L 22.630859 12.521484 L 24.410156 9.5351562 L 22.410156 7.5898438 L 19.451172 9.3417969 L 18.246094 8.8222656 L 17.396484 5.453125 L 14.576172 5.453125 z M 15.984375 12.082031 A 3.9078221 3.9078221 0 0 1 19.892578 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 19.896484 A 3.9078221 3.9078221 0 0 1 12.078125 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 12.082031 Z" fill="#f9f9f9" /></svg>

So my question is how can I trim the definitions using a text editor to say 2 decimal places.

I have found that by using TextWrangler with the following grep search and replace string

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9][0-9])
\1

that I can search for all 6 decimal places strings and replace them with 2 decimal places. Then I can change the search and replace to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9])
\1

and then to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9])
\1

and finally to

(\.[0-9][0-9])([0-9][0-9][0-9])
\1

and this works.

However if someone with slightly (or a lot) more brain pixels than me, could show me how to do all of the above with just one search and replace operation, I would be very happy.

Body:
Using a RegEx approach that cuts all numbers to two decimal places is pretty naive. Not all decimals are the same. Consider for example the following matrix transform:

transform="matrix(0.999848,0.017452,-0.034905,0.999543,-4.0838,-3.8401)"

Cutting these numbers to two decimal places changes the second number by 41%. Is that significant? Yes, in fact you can use it for a nice embossing effect:

<svg viewBox="0 0 20 20" width="100" height="100">
  <text x="7" y="22" style="font-size:20;fill:#000000"
        transform="matrix(0.999848,0.017452,-0.034905,0.999543,-4.0838,-3.8401)">A</text>
  <text x="7" y="22" style="font-size:20;fill:#ffffff;opacity:0.8"
        transform="matrix(0.99,0.01,-0.03,0.99,-4.08,-3.84)">A</text>
</svg>

This is why Inkscape uses the term "precision" in its settings and rounds to a fixed number of significant digits (123.4, 0.01234,...)

The second problem is that you might have a scaling transformation somewhere in your SVG. Did you see in the above snippet that the given size of the rectangle is scaled with a factor 5? It is implicit in the viewBox, ẁidth and height attributes. What if the scaling had been not 5, but 1000? And yes, I have seen these kind of relations in the wild. Especially if the grafic has been produced with Inkscape.

So: handle with care.