问:
What are the chronological steps in building a cross browser compatible site?
I am working on my first project that requires me to worry about cross browser compatibility.  Since this is my first time doing so, I dont know how to go about completing the project.  I am specifically worried about IE.  Should I complete my project in a more graceful browser then hack it to work in IE, or should I simultaneously build my program up in both environments?</p>

答:
A few tips:

Code to Standards — Start by ensuring that what you've just developed works in Firefox and Chrome, and then verify it in IE.  I'll usually then check it out in Safari.  It's always better to make sure your markup/code works in a more standards compliant browser first.

Validate Early, Validate Often — You don't want your design to look perfect in one browser, find out that it's broken in another, discover that to fix the broken layout you needed to correct some invalid HTML/CSS, only to find that now the first browser looks wrong.

Progressive enhancement — will be your friend.  Start basic, with simple HTML and simple CSS, and no JavaScript whatsoever.  Repeat tips #1 and #2, then move on to more complex styles and layout.  Contiue this iterative process until you are happy with the design in all browsers.  Only then should you consider JavaScript to polish the site.

Check each browser often — Don't develop the entire website in a single, compliant browser like Firefox, and then decide to "see what's broken" in IE.  If you've got a complex, dynamic website, there could be MANY problems in Internet Explorer.  Trying to decipher each one when they are compounding on each other is a nightmare.

Reset Stylesheet — As @Eir mentioned in the comments, find a good reset stylesheet.  Although, they have fallen out of favor for some people, I find putting every browser on the same footing from the start helps tremendously.

Use a Framework — I find CSS Frameworks to be excessive, but some people swear by them, so to each his own.  On the other hand, as soon as you have made it to the JavaScript phase of development, I highly recommended using jQuery or MooTools.  They are very focused on circumventing cross-browser inconsistencies.

Let JSLint hurt your feelings —  Even when using a JavaScript framework, there are certain standards of coding to which JSLint will help you conform.  Some of the options are a bit overly strict, but I promise that if you clean your scripts through this tool often enough during development, you will almost never encounter those strange times when everything seems to work in all browsers except IE.

And some great tools!  Everything in the above list you should consider mandatory practice.  The following can spice it up for you in a pinch, but is optional:

CSS Browser Selector — it is rare that you will need this, but if all else fails, it's way cooler than using a separate stylesheet just for one browser (I despise conditional comments).  It basically adds classes to your  tag, so you can do things like the following in your main stylesheet:  .ie7 #header {/*stylese here for IE7 only*/}.  It supports a lot of browsers on many operating systems.  And it's fast.

Browsershots — Nothing beats the real thing, but if you can't install a suite of browsers, this and other tools like it can help.

IE6 CSS Fixer — I outright refuse to debug my designs in IE6.  I coerced my company (via many chagrin-filled meetings with IT and management) to drop support for it (thank god).  It's just counter-productive to waste so much time forcing this pile-of-ahem...  Anyway, if you aren't like me and need to support IE6, this tool can help.

Body:
A few tips:

Code to Standards — Start by ensuring that what you've just developed works in Firefox and Chrome, and then verify it in IE.  I'll usually then check it out in Safari.  It's always better to make sure your markup/code works in a more standards compliant browser first.

Validate Early, Validate Often — You don't want your design to look perfect in one browser, find out that it's broken in another, discover that to fix the broken layout you needed to correct some invalid HTML/CSS, only to find that now the first browser looks wrong.

Progressive enhancement — will be your friend.  Start basic, with simple HTML and simple CSS, and no JavaScript whatsoever.  Repeat tips #1 and #2, then move on to more complex styles and layout.  Contiue this iterative process until you are happy with the design in all browsers.  Only then should you consider JavaScript to polish the site.

Check each browser often — Don't develop the entire website in a single, compliant browser like Firefox, and then decide to "see what's broken" in IE.  If you've got a complex, dynamic website, there could be MANY problems in Internet Explorer.  Trying to decipher each one when they are compounding on each other is a nightmare.

Reset Stylesheet — As @Eir mentioned in the comments, find a good reset stylesheet.  Although, they have fallen out of favor for some people, I find putting every browser on the same footing from the start helps tremendously.

Use a Framework — I find CSS Frameworks to be excessive, but some people swear by them, so to each his own.  On the other hand, as soon as you have made it to the JavaScript phase of development, I highly recommended using jQuery or MooTools.  They are very focused on circumventing cross-browser inconsistencies.

Let JSLint hurt your feelings —  Even when using a JavaScript framework, there are certain standards of coding to which JSLint will help you conform.  Some of the options are a bit overly strict, but I promise that if you clean your scripts through this tool often enough during development, you will almost never encounter those strange times when everything seems to work in all browsers except IE.

And some great tools!  Everything in the above list you should consider mandatory practice.  The following can spice it up for you in a pinch, but is optional:

CSS Browser Selector — it is rare that you will need this, but if all else fails, it's way cooler than using a separate stylesheet just for one browser (I despise conditional comments).  It basically adds classes to your <html> tag, so you can do things like the following in your main stylesheet:  .ie7 #header {/*stylese here for IE7 only*/}.  It supports a lot of browsers on many operating systems.  And it's fast.

Browsershots — Nothing beats the real thing, but if you can't install a suite of browsers, this and other tools like it can help.

IE6 CSS Fixer — I outright refuse to debug my designs in IE6.  I coerced my company (via many chagrin-filled meetings with IT and management) to drop support for it (thank god).  It's just counter-productive to waste so much time forcing this pile-of-ahem...  Anyway, if you aren't like me and need to support IE6, this tool can help.


来源: stackexchange

问:
MySQL query aggregate MAX and subquery
Is there a way to get value from a subquery in where inside select?

stop_link Table

```<code>id | duid | domain_id
1  | 1    | 1
2  | 2    | 1
3  | 1    | 2
4  | 2    | 2
5  | 3    | 1
</code>```

Result that I want (assume domain_id = 2)

```<code>duid    | domain_id
3       | 2
</code>```

Query (not working):

```<code>INSERT INTO stop_link (
              duid,

              domain_id)
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)
</code>```

Query working but I wish to avoid the Set Variable:

```<code>SET @domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1);
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid
  , @domain_id
FROM
  stop_link sl
WHERE sl.domain_id = @domain_id;
</code>```

答:
Do you mean something like this:</p>

```<code>/*Your example Table*/

DECLARE @T
TABLE(ID INT,duid INT,domain_id INT)

INSERT INTO @T
VALUES
(1 , 1    , 1 ),
(2  , 2    , 1),
(3  , 1    , 2),
(4  , 2    , 2),
(5  , 3    , 1)

--The query
SELECT domain_id,Isnull(max(duid),0)+1 [newId]
FROM @T
GROUP BY domain_id
</code>```

ContentLicense: CC BY-SA 3.0

Title: MySQL query aggregate MAX and subquery

Body:
Is there a way to get value from a subquery in where inside select?

stop_link Table

id | duid | domain_id
1  | 1    | 1
2  | 2    | 1
3  | 1    | 2
4  | 2    | 2
5  | 3    | 1

Result that I want (assume domain_id = 2)

duid    | domain_id
3       | 2

Query (not working):

INSERT INTO stop_link (
              duid,

              domain_id)
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)

Query working but I wish to avoid the Set Variable:

SET @domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1);
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid
  , @domain_id
FROM
  stop_link sl
WHERE sl.domain_id = @domain_id;

Body:
Do you mean something like this:

/*Your example Table*/

DECLARE @T
TABLE(ID INT,duid INT,domain_id INT)

INSERT INTO @T
VALUES
(1 , 1    , 1 ),
(2  , 2    , 1),
(3  , 1    , 2),
(4  , 2    , 2),
(5  , 3    , 1)

--The query
SELECT domain_id,Isnull(max(duid),0)+1 [newId]
FROM @T
GROUP BY domain_id


问:
Parse date with split seconds using read_delim
Using the read_delim function from the readr package I would like to parse a csv file including a date time column in the format 2016-12-29 09:00:18.456, explicitly stating the format.

From the following sources (https://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html , https://www.rdocumentation.org/packages/readr/versions/1.0.0/topics/parse_datetime), I understand that I should use this: "%Y-%m-%d %H:%M:%OS" as part of the code:

```<code>a <- read_delim("file.csv", col_names = TRUE, delim = ";",
                locale = locale(decimal_mark = ","), col_types = cols(
                'Start time' = col_datetime("%Y-%m-%d %H:%M:%OS")))
</code>```

However, I get the following error:

```<code>Warning: * parsing failures.
row        col                     expected                  actual
  1 Start time date like %Y-%m-%d %H:%M:%OS 2016-12-29 09:00:18.456
</code>```

Here is a short reproducible example of the problem:

```<code>parse_datetime("2016-12-29 09:00:18.456", "%Y-%m-%d H%:M%:%OS")
</code>```

What am I doing wrong?

答:
The decimal mark is inconsistent with the . in the seconds.  I also had to set options("digits.secs"=3) to get this to work

```<code>a <- read_delim("file.csv", col_names = TRUE, delim = ";",
                locale = locale(decimal_mark = "."),
                col_types = cols(`Start time` = col_datetime("%Y-%m-%d %H:%M:%OS")))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using the read_delim function from the readr package I would like to parse a csv file including a date time column in the format 2016-12-29 09:00:18.456, explicitly stating the format.

From the following sources (https://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html , https://www.rdocumentation.org/packages/readr/versions/1.0.0/topics/parse_datetime), I understand that I should use this: "%Y-%m-%d %H:%M:%OS" as part of the code:

a <- read_delim("file.csv", col_names = TRUE, delim = ";",
                locale = locale(decimal_mark = ","), col_types = cols(
                'Start time' = col_datetime("%Y-%m-%d %H:%M:%OS")))

However, I get the following error:

Warning: * parsing failures.
row        col                     expected                  actual
  1 Start time date like %Y-%m-%d %H:%M:%OS 2016-12-29 09:00:18.456

Here is a short reproducible example of the problem:

parse_datetime("2016-12-29 09:00:18.456", "%Y-%m-%d H%:M%:%OS")

What am I doing wrong?

Body:
The decimal mark is inconsistent with the . in the seconds.  I also had to set options("digits.secs"=3) to get this to work

a <- read_delim("file.csv", col_names = TRUE, delim = ";",
                locale = locale(decimal_mark = "."),
                col_types = cols(`Start time` = col_datetime("%Y-%m-%d %H:%M:%OS")))


问:
Drop Shadow effect on Windows SDK 10240
I know there are a lot of ways of adding shadows with the Anniversary Update and previous SDKs with Windows.Composition. Unfortunately I have to stick with version 10240 and this APIs are not available. I tried with Win2D but did not succeed. Any ideas on how to add a shadow to a Grid XAML element?</p>

答:
To my knowledge you can't make a real drop shadow without the anniversary update in xaml (without using specific shadow bitmaps that you'd need to create yourself).

In case you only need a shadow to rectangular xaml components, you can make a 3x3 grid with gradients along the edges, and place it under the component with a certain offset (depending on where you want the light to come from).

Here is an example of that:

```<code><UserControl
x:Class="YourProject.UserControls.CustomShadow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:YourProject.UserControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">

<Grid>
    <Grid x:Name="ShadowGrid" Opacity="0.2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition x:Name="LeftColumn" Width="40"/>
            <ColumnDefinition x:Name="CenterColumn" />
            <ColumnDefinition x:Name="RightColumn" Width="40" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition x:Name="TopRow" Height="40"/>
            <RowDefinition x:Name="CenterRow" />
            <RowDefinition x:Name="BottomRow" Height="40"/>
        </Grid.RowDefinitions>

        <Grid Grid.Row="0" Grid.Column="0">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0.5,0.5" EndPoint="1,1">
                        <GradientStop Color="#4b4b50" Offset="1" />
                        <GradientStop Color="Transparent" Offset="0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="0" Grid.Column="1">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,1" EndPoint="0,0">
                        <GradientStop Color="#4b4b50" Offset="0" />
                        <GradientStop Color="Transparent" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="0" Grid.Column="2">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0.5,0.5" EndPoint="0,1">
                        <GradientStop Color="#4b4b50" Offset="1" />
                        <GradientStop Color="Transparent" Offset="0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="1" Grid.Column="0">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="1,0" EndPoint="0,0">
                        <GradientStop Color="#4b4b50" Offset="0" />
                        <GradientStop Color="Transparent" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="1" Grid.Column="1">
            <Rectangle Fill="#4b4b50"/>
        </Grid>
        <Grid Grid.Row="1" Grid.Column="2">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                        <GradientStop Color="#4b4b50" Offset="0" />
                        <GradientStop Color="Transparent" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="2" Grid.Column="0">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0.5,0.5" EndPoint="1,0">
                        <GradientStop Color="#4b4b50" Offset="1" />
                        <GradientStop Color="Transparent" Offset="0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="2" Grid.Column="1">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                        <GradientStop Color="#4b4b50" Offset="0" />
                        <GradientStop Color="Transparent" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="2" Grid.Column="2">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0.5,0.5" EndPoint="0,0">
                        <GradientStop Color="#4b4b50" Offset="1" />
                        <GradientStop Color="Transparent" Offset="0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
    </Grid>
    <Grid>
        <Rectangle Fill="Transparent" Width="350" Height="250" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10"/>
    </Grid>
</Grid>
</code>```

When resizing the object, adjust the width/height of CenterColumn/CenterRow, and keep the other parts of the grid the same size. A radial gradient would've looked better in the corners, but radial gradients don't exist in uwp either.

Title: Drop Shadow effect on Windows SDK 10240

Body:
To my knowledge you can't make a real drop shadow without the anniversary update in xaml (without using specific shadow bitmaps that you'd need to create yourself).

In case you only need a shadow to rectangular xaml components, you can make a 3x3 grid with gradients along the edges, and place it under the component with a certain offset (depending on where you want the light to come from).

Here is an example of that:

<UserControl
x:Class="YourProject.UserControls.CustomShadow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:YourProject.UserControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">

<Grid>
    <Grid x:Name="ShadowGrid" Opacity="0.2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition x:Name="LeftColumn" Width="40"/>
            <ColumnDefinition x:Name="CenterColumn" />
            <ColumnDefinition x:Name="RightColumn" Width="40" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition x:Name="TopRow" Height="40"/>
            <RowDefinition x:Name="CenterRow" />
            <RowDefinition x:Name="BottomRow" Height="40"/>
        </Grid.RowDefinitions>

        <Grid Grid.Row="0" Grid.Column="0">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0.5,0.5" EndPoint="1,1">
                        <GradientStop Color="#4b4b50" Offset="1" />
                        <GradientStop Color="Transparent" Offset="0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="0" Grid.Column="1">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,1" EndPoint="0,0">
                        <GradientStop Color="#4b4b50" Offset="0" />
                        <GradientStop Color="Transparent" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="0" Grid.Column="2">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0.5,0.5" EndPoint="0,1">
                        <GradientStop Color="#4b4b50" Offset="1" />
                        <GradientStop Color="Transparent" Offset="0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="1" Grid.Column="0">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="1,0" EndPoint="0,0">
                        <GradientStop Color="#4b4b50" Offset="0" />
                        <GradientStop Color="Transparent" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="1" Grid.Column="1">
            <Rectangle Fill="#4b4b50"/>
        </Grid>
        <Grid Grid.Row="1" Grid.Column="2">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                        <GradientStop Color="#4b4b50" Offset="0" />
                        <GradientStop Color="Transparent" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="2" Grid.Column="0">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0.5,0.5" EndPoint="1,0">
                        <GradientStop Color="#4b4b50" Offset="1" />
                        <GradientStop Color="Transparent" Offset="0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="2" Grid.Column="1">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                        <GradientStop Color="#4b4b50" Offset="0" />
                        <GradientStop Color="Transparent" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
        <Grid Grid.Row="2" Grid.Column="2">
            <Rectangle>
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0.5,0.5" EndPoint="0,0">
                        <GradientStop Color="#4b4b50" Offset="1" />
                        <GradientStop Color="Transparent" Offset="0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Grid>
    </Grid>
    <Grid>
        <Rectangle Fill="Transparent" Width="350" Height="250" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10"/>
    </Grid>
</Grid>

When resizing the object, adjust the width/height of CenterColumn/CenterRow, and keep the other parts of the grid the same size. A radial gradient would've looked better in the corners, but radial gradients don't exist in uwp either.


问:
Draw a map of a specific country with leaflet
I would like to use the package leaflet with R to draw a map of a specific countries such as Italy, Spain, etc.

I checked the basic examples with the function setView() and I tried to give a vector of two values for the arg of latitude and longitutde :

```<code>m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  setView(lng=c(46.00,48.00), lat=c(2.00,6.00), zoom = 4)
m  # Print the map (map is not centered on a country, it's just a test)
</code>```

But I will never be able to have a specific country on my screen such as the result of this function :

```<code>library(maps)
map('italy', fill = TRUE, col = 1:10)
</code>```

In the end, I just want to draw some points by geographically locating them on my maps (with latitude and longtitude)

Is it possible or is the package maps is adequate for this task (even though I didn't find a way to zoom in) ?

答:
The maps package ships shapefile data as vertices. Afaik nothing like this is included in leaflet. So you will have to get your data elsewhere. Here is my suggestion:

```<code># Get an Italy shapefile
download.file(url = 'http://biogeo.ucdavis.edu/data/diva/adm/ITA_adm.zip',
              destfile = 'italy.zip')
unzip(zipfile = 'italy.zip')

# Load libraries
library(sp)
library(rgdal)
italy <- readOGR('ITA_adm0.shp')

library(leaflet)
leaflet(italy) %>%
  addPolygons() %>%
  addTiles()
</code>```

ADD-ON:

You can look at the vertices that make up italy as saved in the maps package with the code below.

```<code>library(maps)
italy <- map('italy', fill = TRUE, col = 1:10)
italy_coords <- cbind(italy$x, italy$y)
plot(italy_coords)
</code>```

Body:
I would like to use the package leaflet with R to draw a map of a specific countries such as Italy, Spain, etc.

I checked the basic examples with the function setView() and I tried to give a vector of two values for the arg of latitude and longitutde :

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  setView(lng=c(46.00,48.00), lat=c(2.00,6.00), zoom = 4)
m  # Print the map (map is not centered on a country, it's just a test)

But I will never be able to have a specific country on my screen such as the result of this function :

library(maps)
map('italy', fill = TRUE, col = 1:10)

In the end, I just want to draw some points by geographically locating them on my maps (with latitude and longtitude)

Is it possible or is the package maps is adequate for this task (even though I didn't find a way to zoom in) ?

Body:
The maps package ships shapefile data as vertices. Afaik nothing like this is included in leaflet. So you will have to get your data elsewhere. Here is my suggestion:

# Get an Italy shapefile
download.file(url = 'http://biogeo.ucdavis.edu/data/diva/adm/ITA_adm.zip',
              destfile = 'italy.zip')
unzip(zipfile = 'italy.zip')

# Load libraries
library(sp)
library(rgdal)
italy <- readOGR('ITA_adm0.shp')

library(leaflet)
leaflet(italy) %>%
  addPolygons() %>%
  addTiles()

ADD-ON:

You can look at the vertices that make up italy as saved in the maps package with the code below.

library(maps)
italy <- map('italy', fill = TRUE, col = 1:10)
italy_coords <- cbind(italy$x, italy$y)
plot(italy_coords)


问:
Microsoft Graph CSharp SDK - Fetching DriveItems- paging not working, only able to retrieve 200 items out of 1000 items
I am coding against the Microsoft Graph CSharp SDK while testing my application for a mass collect. I noticed that there is a paging issue with my code. I added 1000 1kb files to a test OneDrive account - which I then ran my code against to see if I could access all the file. Unfortunately, I was only able to see 200 files within a single folder - not the full 1000.

I looked online and found this GitHub (now closed) bug.

While stepping through my code I am seeing the NextPageRequest as being null. I just wanted to make sure there is no bug with this and making sure I am correctly using the NextPageRequest.

Code:

```<code>public Collection<DriveItem> GetSubItems(string id, string username)
{
    Collection<DriveItem> response = new Collection<DriveItem>();
    var retryCount = 0;

    try
    {

        response = RetryPolicy.Default.Retry<Exception, Collection<DriveItem>>(
        this.maxRetryCount,
        RetryDurationStrategies.ExponentialBackoff,
        (exception, timeSpan) =>
        {
            retryCount++;
            this.LogInfo(Strings.RetryPolicyMessage, exception.Message, timeSpan);
        },
        () =>
        {
            var driveItems = new List<DriveItem>();
            var driveItemsPage = this.GraphServiceClient.GetItemAndChildrenTask(id, username);
            var result = driveItemsPage.Result;
            driveItems.AddRange(result.Children.CurrentPage);

            while (result.Children.NextPageRequest != null)
            {
                var nextPageResult = result.Children.NextPageRequest.GetAsync();
                var nextPage = nextPageResult.Result;
                driveItems.AddRange(nextPage.CurrentPage);
            }

            Collection<DriveItem> driveItemsList = new Collection<DriveItem>(driveItems);

            return driveItemsList;
        });
    }
    catch (ServiceException ex)
    {
        switch (ex.Error.Code)
        {
            case ItemNotFound:
                this.LogWarning(ex, Strings.OneDriveItemNotFound, ex.Message);
                break;
            case InvalidRequestItemId:
                this.LogWarning(ex, Strings.OneDriveUserNotFound, ex.Message);
                break;
            default:
                this.LogWarning(ex, Strings.OneDriveGenericException, ex.Message);
                break;
        }
    }
    catch (AdalServiceException ex)
    {
        switch (ex.ErrorCode)
        {
            case InvalidClient:
                this.LogWarning(ex, Strings.AdalInvalidClientErrorMsg, ex.Message);
                break;
            case UnauthorizedClient:
                this.LogWarning(ex, Strings.AdalUnauthorizedClientErrorMsg, ex.Message);
                break;
            case InvalidRequestSecret:
                this.LogWarning(ex, Strings.AdalInvalidRequestErrorMsg, ex.Message);
                break;
            default:
                this.LogWarning(ex, Strings.AdalGenericErrorMsg, ex.Message);
                break;
        }

        throw new PluginException(string.Format(Strings.AuthenticationToOneDriveWasUnsuccessful, ex.Message), ex.InnerException);
    }
    catch (Exception ex)
    {
        this.LogWarning(ex, Strings.OneDriveGenericException, ex.Message);

        throw new PluginException(Strings.GenericPluginException, ex.InnerException);
    }

    return response;
}
</code>```

The call to Microsoft Graph SDK:

```<code>public Task<DriveItem> GetItemAndChildrenTask(string id, string username)
{
    return this.GraphServiceClient.Drives[username].Items[id].Request().Expand(ExpandValue).GetAsync();
}
</code>```

Below is a screen shot of the for the result variable:

答:
Your underlying Graph request needs to be made specifically on the children for the NextPageRequest to not be null.

```<code>graphServiceClient.Drives[username].Items[id].Children.Request().GetAsync();
</code>```

If you do something like:

```<code>graphServiceClient.Drives[username].Items[id].Request().Expand('children').GetAsync();
</code>```

Then the NextPageRequest will not be populated.

Body:
I am coding against the Microsoft Graph CSharp SDK while testing my application for a mass collect. I noticed that there is a paging issue with my code. I added 1000 1kb files to a test OneDrive account - which I then ran my code against to see if I could access all the file. Unfortunately, I was only able to see 200 files within a single folder - not the full 1000.

I looked online and found this GitHub (now closed) bug.

While stepping through my code I am seeing the NextPageRequest as being null. I just wanted to make sure there is no bug with this and making sure I am correctly using the NextPageRequest.

Code:

public Collection<DriveItem> GetSubItems(string id, string username)
{
    Collection<DriveItem> response = new Collection<DriveItem>();
    var retryCount = 0;

    try
    {

        response = RetryPolicy.Default.Retry<Exception, Collection<DriveItem>>(
        this.maxRetryCount,
        RetryDurationStrategies.ExponentialBackoff,
        (exception, timeSpan) =>
        {
            retryCount++;
            this.LogInfo(Strings.RetryPolicyMessage, exception.Message, timeSpan);
        },
        () =>
        {
            var driveItems = new List<DriveItem>();
            var driveItemsPage = this.GraphServiceClient.GetItemAndChildrenTask(id, username);
            var result = driveItemsPage.Result;
            driveItems.AddRange(result.Children.CurrentPage);

            while (result.Children.NextPageRequest != null)
            {
                var nextPageResult = result.Children.NextPageRequest.GetAsync();
                var nextPage = nextPageResult.Result;
                driveItems.AddRange(nextPage.CurrentPage);
            }

            Collection<DriveItem> driveItemsList = new Collection<DriveItem>(driveItems);

            return driveItemsList;
        });
    }
    catch (ServiceException ex)
    {
        switch (ex.Error.Code)
        {
            case ItemNotFound:
                this.LogWarning(ex, Strings.OneDriveItemNotFound, ex.Message);
                break;
            case InvalidRequestItemId:
                this.LogWarning(ex, Strings.OneDriveUserNotFound, ex.Message);
                break;
            default:
                this.LogWarning(ex, Strings.OneDriveGenericException, ex.Message);
                break;
        }
    }
    catch (AdalServiceException ex)
    {
        switch (ex.ErrorCode)
        {
            case InvalidClient:
                this.LogWarning(ex, Strings.AdalInvalidClientErrorMsg, ex.Message);
                break;
            case UnauthorizedClient:
                this.LogWarning(ex, Strings.AdalUnauthorizedClientErrorMsg, ex.Message);
                break;
            case InvalidRequestSecret:
                this.LogWarning(ex, Strings.AdalInvalidRequestErrorMsg, ex.Message);
                break;
            default:
                this.LogWarning(ex, Strings.AdalGenericErrorMsg, ex.Message);
                break;
        }

        throw new PluginException(string.Format(Strings.AuthenticationToOneDriveWasUnsuccessful, ex.Message), ex.InnerException);
    }
    catch (Exception ex)
    {
        this.LogWarning(ex, Strings.OneDriveGenericException, ex.Message);

        throw new PluginException(Strings.GenericPluginException, ex.InnerException);
    }

    return response;
}

The call to Microsoft Graph SDK:

public Task<DriveItem> GetItemAndChildrenTask(string id, string username)
{
    return this.GraphServiceClient.Drives[username].Items[id].Request().Expand(ExpandValue).GetAsync();
}

Below is a screen shot of the for the result variable:

Body:
Your underlying Graph request needs to be made specifically on the children for the NextPageRequest to not be null.

graphServiceClient.Drives[username].Items[id].Children.Request().GetAsync();

If you do something like:

graphServiceClient.Drives[username].Items[id].Request().Expand('children').GetAsync();

Then the NextPageRequest will not be populated.


问:
Running nosetests using pypy
PyPy is compatible with nose, so how can I use that? I already use:</p>

```<code>nosetests-2.7 ; nosetests3
</code>```

答:
If you look inside nosetests script (on my PC: /usr/local/bin/nosetests) it turns out it's a python script with a header like #!/usr/bin/python.

Therefore, to make sure you run nosetests with a particular interpreter, run:

python /usr/local/bin/nosetests

pypy /usr/local/bin/nosetests

Title: Running nosetests using pypy

Body:
PyPy is compatible with nose, so how can I use that? I already use:

nosetests-2.7 ; nosetests3


问:
Scalikejdbc result set iterator
I'm using scalikejdbc to access a huge table. My understanding stand - it fetches all rows into memory before I can map or iterate over them.

Currently I have an implementation using rxscala Observable, which is very simple. But the receiver is slower than reading sql, and then I get OutOfMemory because of buffering. Here is my current producer as could observable:

```<code>  def fetchProductsAsObservable(
    sql: SQL[Nothing,NoExtractor],
    extractor: (WrappedResultSet) => ProductItem)
  ) =
    Observable[ProductItem](o =>
      try {
          sql.foreach(row => o.onNext(extractor(row)))
          o.onCompleted()
      } catch {
        case e: Throwable => o.onError(e)
      }
    )
</code>```

I'm aware of SQL.foreach method, but it gets an callback method and returns Unit.
My background is in .NET. Can't figure out myself how to implement properly a simple Iterator in scala with scalikejdbc, which I can give around for parallel processing?

答:
Your question is not related to the ScalikeJDBC behavior but to RxJava.
Since your Observable is alimented by a hot source you need to use a backpressure strategy.</p>

Title: Scalikejdbc result set iterator

Body:
I'm using scalikejdbc to access a huge table. My understanding stand - it fetches all rows into memory before I can map or iterate over them.

Currently I have an implementation using rxscala Observable, which is very simple. But the receiver is slower than reading sql, and then I get OutOfMemory because of buffering. Here is my current producer as could observable:

  def fetchProductsAsObservable(
    sql: SQL[Nothing,NoExtractor],
    extractor: (WrappedResultSet) => ProductItem)
  ) =
    Observable[ProductItem](o =>
      try {
          sql.foreach(row => o.onNext(extractor(row)))
          o.onCompleted()
      } catch {
        case e: Throwable => o.onError(e)
      }
    )

I'm aware of SQL.foreach method, but it gets an callback method and returns Unit.
My background is in .NET. Can't figure out myself how to implement properly a simple Iterator in scala with scalikejdbc, which I can give around for parallel processing?


问:
Angular2 function call from html element with no load event (or similiar)
I am new to Angular and have run into a problem that seems to have a javascript work around but they aren't very elegant.

I have a model with an array property. I ngfor the list property to build some html selection options. This is all working nicely. The problem comes when I am trying to set default value...the html elements don't have a load event.

I tried numerous html elements and they don't appear to have a load event either but I certainly could be doing it wrong.

I have seen a solution to put javascript tag right after the html and I could do that but I was really looking for a more elegant way in Angular.

I saw this SO post and thought that was my answer but there is a warning given that I agree with and thus it doesn't appear to be a good solution.
Regardless I tried it just to see if it would work and I got:

Failed to execute 'setAttribute' on 'Element': '{{loadDefaults()}}' is not a valid attribute name

```<code><span {{loadDefaults()}} ></span>
</code>```

So how can I fire an AS2 function in the component to load the default values?

HTML (btw this is NOT a full page load so there is no body tag):

```<code><tr>
   <td *ngFor="let loc of locOptions;">
      <span>{{loc.text}}</span>
      <input type="radio" name="radiogroup" [value]="loc.value" (change)="onSelectionChange(loc.value)">
  </td>
</tr>
</code>```

Edit

I thought perhaps mistakenly that ngoninit would fire too soon...before the html elements are rendered.

So perhaps what is being suggested is that I add a boolean is default to the model and bind THAT as the element is rendered.

答: In your ngonit function set this.locOptions to your default values. The value can be changed later on in any function and the change will be reflected in the view. Hope this helps you.</p>

Body:
I am new to Angular and have run into a problem that seems to have a javascript work around but they aren't very elegant.

I have a model with an array property. I ngfor the list property to build some html selection options. This is all working nicely. The problem comes when I am trying to set default value...the html elements don't have a load event.

I tried numerous html elements and they don't appear to have a load event either but I certainly could be doing it wrong.

I have seen a solution to put javascript tag right after the html and I could do that but I was really looking for a more elegant way in Angular.

I saw this SO post and thought that was my answer but there is a warning given that I agree with and thus it doesn't appear to be a good solution.
Regardless I tried it just to see if it would work and I got:

Failed to execute 'setAttribute' on 'Element': '{{loadDefaults()}}' is not a valid attribute name

So how can I fire an AS2 function in the component to load the default values?

HTML (btw this is NOT a full page load so there is no body tag):

      {{loc.text}}
      <input type="radio" name="radiogroup" [value]="loc.value" (change)="onSelectionChange(loc.value)">

Edit

I thought perhaps mistakenly that ngoninit would fire too soon...before the html elements are rendered.

So perhaps what is being suggested is that I add a boolean is default to the model and bind THAT as the element is rendered.


问:
sharepoint feature upgrade failing to update module
Ok guys, I've been bending my head over this problem for quite some time now. Let me give you a little bit of context here. I have a site collection feature (FileCentral) working on it's version '1.0.0.0'. What this feature does is to create a document library in which I can upload files that will be stored on a network share. So each item in this document library stores a link to the file path. No problem here. Recently I've got the following requirement: "It should be possible to synchronize files from the folder to the document library". In other words, I need some way to scan for files placed in the network share and create the respective list items pointing to these files. The proposed solution is to create a custom action on this document library that when clicked would open a dialog with a page called SyncFiles.aspx in it. This page would then call an asynchronous service responsible for listing the files that have not been synchronized. The user would then select the files he wants to sync and confirm the operation. The project structure for this solution is:

```<code>|Features
|-- FileCentral (Site scoped feature)
|---- FileCentral.feature
|------ FileCentral.Template.xml

|branding (module)
|-- js (folder)
|---- app (folder)
|------ fileCentral (folder)
|-------- home.js
|-- Elements.xml

|Pages (module)
|-- Home.aspx (file)

|Updates (folder)
|-- SyncFileCentral (folder)
|---- Assets (module)
|------ js (folder)
|-------- app (folder)
|---------- fileCentral (folder)
|------------ sync.js
|------ Elements.xml
|---- Button (custom action)
|------ Elements.xml
|---- Pages (module)
|------ SyncFiles.aspx
|------ Elements.xml
</code>```

The Assets module deploys to the Masterpage Gallery the necessary javascript e css files for the SyncFiles.aspx page to work:

```<code><!-- Assets module -->
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="branding" Url="_catalogs/masterpage" RootWebOnly="TRUE">
    <File Path="branding\js\app\fileCentral\sync.js" Url="branding/js/app/fileCentral/sync.js" ReplaceContent="TRUE" IgnoreIfAlreadyExists="TRUE" Type="GhostableInLibrary" Level="Published"/>
  </Module>
</Elements>
</code>```

The Button custom action deploys the (guess what?) the custom action. And the Pages modules deploys the SyncFiles.aspx page to the Pages document library.

```<code><-- Pages module -->
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Pages" Url="Pages" RootWebOnly="TRUE">
    <File Path="Pages\SyncFiles.aspx" Url="Pages/SyncFiles.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" ReplaceContent="TRUE" Level="Published" />
  </Module>
</Elements>
</code>```

The FileCentral.Template.xml looks like:

```<code><?xml version="1.0" encoding="utf-8"?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" **Version="2.0.0.0"** Title="File Central" ActivateOnDefault="FALSE" AlwaysForceInstall="TRUE" Description="DESCRIPTION HERE" Id="XXX" Scope="Site">
  <!-- Feature Upgrade -->
  <UpgradeActions>
    <VersionRange BeginVersion="2.0.0.0" EndVersion="3.0.0.0">
      <ApplyElementManifests>
        <ElementManifest Location="Assets\Elements.xml" />
        <ElementFile Location="Assets\js\app\fileCentral\sync.js" />
        <ElementManifest Location="Button\Elements.xml" />
        <ElementManifest Location="Pages\Elements.xml" />
        <ElementFile Location="Pages\SyncFiles.aspx" />
      </ApplyElementManifests>
    </VersionRange>
  </UpgradeActions>
  <ElementManifests>
    <ElementManifest Location="branding\Elements.xml" />
    <ElementFile Location="branding\js\app\fileCentral\home.js" />
    <ElementManifest Location="Assets\Elements.xml" />
    <ElementFile Location="Assets\js\app\fileCentral\sync.js" />
    <ElementManifest Location="Button\Elements.xml" />
    <ElementManifest Location="Pages\Elements.xml" />
    <ElementFile Location="Pages\SyncFiles.aspx" />
  </ElementManifests>
</Feature>
</code>```

Ok, enough of context. Here is the problem: When I Update-SPSolution -Identity "FileCentralSolution.wsp" -LiteralPath "X" -GACDeployment, I can see ($site.QueryFeatures([Microsoft.SharePoint.SPFeatureScope]::Site, $true)) that there are features needing update. Then, when I update the features, I'm not able to see neither my assets nor my pages changes. The only thing that gets deployed is my custom action. So when I click the button a blank dialog open up. And if I inspect the network tab, I can see the assets and page requests return 404 status responses. WHAT HAVE I DONE WRONG?

答: Have you checked your file system to see if the files have indeed been deployed to the correct hive? If this is SharePoint 2013, are your solution files being deployed to the folder appropriate to your selected UI mode? (CompatibilityLevel 14,15?)</p>

Body:
Ok guys, I've been bending my head over this problem for quite some time now. Let me give you a little bit of context here. I have a site collection feature (FileCentral) working on it's version '1.0.0.0'. What this feature does is to create a document library in which I can upload files that will be stored on a network share. So each item in this document library stores a link to the file path. No problem here. Recently I've got the following requirement: "It should be possible to synchronize files from the folder to the document library". In other words, I need some way to scan for files placed in the network share and create the respective list items pointing to these files. The proposed solution is to create a custom action on this document library that when clicked would open a dialog with a page called SyncFiles.aspx in it. This page would then call an asynchronous service responsible for listing the files that have not been synchronized. The user would then select the files he wants to sync and confirm the operation. The project structure for this solution is:

|Features
|-- FileCentral (Site scoped feature)
|---- FileCentral.feature
|------ FileCentral.Template.xml

|branding (module)
|-- js (folder)
|---- app (folder)
|------ fileCentral (folder)
|-------- home.js
|-- Elements.xml

|Pages (module)
|-- Home.aspx (file)

|Updates (folder)
|-- SyncFileCentral (folder)
|---- Assets (module)
|------ js (folder)
|-------- app (folder)
|---------- fileCentral (folder)
|------------ sync.js
|------ Elements.xml
|---- Button (custom action)
|------ Elements.xml
|---- Pages (module)
|------ SyncFiles.aspx
|------ Elements.xml

The Assets module deploys to the Masterpage Gallery the necessary javascript e css files for the SyncFiles.aspx page to work:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="branding" Url="_catalogs/masterpage" RootWebOnly="TRUE">
    <File Path="branding\js\app\fileCentral\sync.js" Url="branding/js/app/fileCentral/sync.js" ReplaceContent="TRUE" IgnoreIfAlreadyExists="TRUE" Type="GhostableInLibrary" Level="Published"/>
  </Module>
</Elements>

The Button custom action deploys the (guess what?) the custom action. And the Pages modules deploys the SyncFiles.aspx page to the Pages document library.

<-- Pages module -->
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Pages" Url="Pages" RootWebOnly="TRUE">
    <File Path="Pages\SyncFiles.aspx" Url="Pages/SyncFiles.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" ReplaceContent="TRUE" Level="Published" />
  </Module>
</Elements>

The FileCentral.Template.xml looks like:

<?xml version="1.0" encoding="utf-8"?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" **Version="2.0.0.0"** Title="File Central" ActivateOnDefault="FALSE" AlwaysForceInstall="TRUE" Description="DESCRIPTION HERE" Id="XXX" Scope="Site">

  <UpgradeActions>
    <VersionRange BeginVersion="2.0.0.0" EndVersion="3.0.0.0">
      <ApplyElementManifests>
        <ElementManifest Location="Assets\Elements.xml" />
        <ElementFile Location="Assets\js\app\fileCentral\sync.js" />
        <ElementManifest Location="Button\Elements.xml" />
        <ElementManifest Location="Pages\Elements.xml" />
        <ElementFile Location="Pages\SyncFiles.aspx" />
      </ApplyElementManifests>
    </VersionRange>
  </UpgradeActions>
  <ElementManifests>
    <ElementManifest Location="branding\Elements.xml" />
    <ElementFile Location="branding\js\app\fileCentral\home.js" />
    <ElementManifest Location="Assets\Elements.xml" />
    <ElementFile Location="Assets\js\app\fileCentral\sync.js" />
    <ElementManifest Location="Button\Elements.xml" />
    <ElementManifest Location="Pages\Elements.xml" />
    <ElementFile Location="Pages\SyncFiles.aspx" />
  </ElementManifests>
</Feature>

Ok, enough of context. Here is the problem: When I Update-SPSolution -Identity "FileCentralSolution.wsp" -LiteralPath "X" -GACDeployment, I can see ($site.QueryFeatures([Microsoft.SharePoint.SPFeatureScope]::Site, $true)) that there are features needing update. Then, when I update the features, I'm not able to see neither my assets nor my pages changes. The only thing that gets deployed is my custom action. So when I click the button a blank dialog open up. And if I inspect the network tab, I can see the assets and page requests return 404 status responses. WHAT HAVE I DONE WRONG?


问:
Replacing an string on a field via MySQL
I have the following field (which is a string) of one of my tables:

```<code>'[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
  {"id":"7","value":"Reuters"},
  {"id":"20","value":"2017/03/17"}]'`
</code>```

As you can see, the last part, the one with id=20 has a date on it, 2017/03/17.

Can someone tell me how can I update that field so I can get the output 2017-03-17?

My desired output after the update would be:

```<code>'[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
 {"id":"7","value":"Reuters"},
 {"id":"20","value":"2017-03-17"}]'`
</code>```

If I use:

```<code>UPDATE mytable
SET myfield = replace(myfield , '/', '-');
</code>```

It removes the / of the links, and I want to mantain them.

PS: The ids of the fields are always the same (the one for the date is always 20 for example) the only thing that changes are the values.

Body:
I have the following field (which is a string) of one of my tables:

'[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
  {"id":"7","value":"Reuters"},
  {"id":"20","value":"2017/03/17"}]'`

As you can see, the last part, the one with id=20 has a date on it, 2017/03/17.

Can someone tell me how can I update that field so I can get the output 2017-03-17?

My desired output after the update would be:

'[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
 {"id":"7","value":"Reuters"},
 {"id":"20","value":"2017-03-17"}]'`

If I use:

UPDATE mytable
SET myfield = replace(myfield , '/', '-');

It removes the / of the links, and I want to mantain them.

PS: The ids of the fields are always the same (the one for the date is always 20 for example) the only thing that changes are the values.

Body:
you can do it with a query like this:

UPDATE  mytable
    SET myfield = CONCAT (
        SUBSTRING_INDEX(myfield, '"id":"20","value":', 1)
        , '"id":"20","value":',
        , REPLACE (SUBSTRING_INDEX(myfield, '"id":"20","value":', -1),'/','-')
    )
WHERE ....:

sample

mysql> SELECT
    ->     CONCAT (
    ->     SUBSTRING_INDEX('[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
    '>  {"id":"7","value":"Reuters"},
    '>  {"id":"20","value":"2017/03/17"}]', '"id":"20","value":', 1),
    ->  '"id":"20","value":',
    ->  REPLACE (SUBSTRING_INDEX('[{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
    '>  {"id":"7","value":"Reuters"},
    '>  {"id":"20","value":"2017/03/17"}]', '"id":"20","value":', -1),'/','-')
    ->  ) AS result;
+------------------------------------------------------------------------------------------------------------------------------------------------+
| result                                                                                |
+------------------------------------------------------------------------------------------------------------------------------------------------+
| [{"id":"6","value":["http://www.google.com","http://www.google.com","new"]},
 {"id":"7","value":"Reuters"},
 {"id":"20","value":"2017-03-17"}] |
+------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0,00 sec)

mysql>


问:
How to join two tables in SocialEngine, based on ZF
My code in SocialEngine is:

```<code>$coreLikesTable = Engine_Api::_()->getDbTable('likes', 'core');
$coreLikesTableName = $coreLikesTable->info('name');

$select = $usersTable->select()->from(array('l' => 'engine4_core_likes'), array('poster_id'))->join(array('u' => 'engine4_users'), 'l.poster_id = u.user_id')->group('u.user_id');

result = $coreLikesTable->fetchAll($select);
print_r($result);die;
</code>```

But it doesn't output anything. What's the problem?

Thanks

答:
Try this:</p>

```<code>$select = $this->_db->select()
    ->from('table1',array('col1','col2'…..))
    ->joinInner('table2','table1.id=table2.some_id',array('col1','col3'…))
    ->where('where condition here')
    ->order('column name ASC/DESC');
</code>```

Body:
My code in SocialEngine is:

$coreLikesTable = Engine_Api::_()->getDbTable('likes', 'core');
$coreLikesTableName = $coreLikesTable->info('name');

$select = $usersTable->select()->from(array('l' => 'engine4_core_likes'), array('poster_id'))->join(array('u' => 'engine4_users'), 'l.poster_id = u.user_id')->group('u.user_id');

result = $coreLikesTable->fetchAll($select);
print_r($result);die;

But it doesn't output anything. What's the problem?

Thanks

Body:
Try this:

$select = $this->_db->select()
    ->from('table1',array('col1','col2'…..))
    ->joinInner('table2','table1.id=table2.some_id',array('col1','col3'…))
    ->where('where condition here')
    ->order('column name ASC/DESC');


问:
Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED?
I am developing a small application that lists all the applications present/ installed on the android device.  But I'm getting the below error while i'm trying to run the code.

Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED

Please can any one help me to sort out this error.

答: Target <activity> needs to be specified before the <activity-alias>.


问:
List sorting - two lists into one
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

```<code>names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])
</code>```

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

答:
You can use a functionality similar to numpy.argsort: sort a list of the indices into the correct order, and then use that to rearrange both lists:

```<code>inds = list(range(len(wages))) # This can be converted into a while loop that appends elements until `len(wages)` is reached
inds.sort(key=lambda x: wages[x]) # Or did you want names[x] here?
sorted_wages = []
sorted_names = []
for ind in inds:
    sorted_wages.append(wages[ind])
    sorted_names.append(names[ind])
</code>```

You can use a key that selects either the wage (lambda x: wages[x] as shown) or the name (lambda x: names[x]) for sorting. If you really want, the first line can be replaced with something like

```<code>inds = []
count = 0
while count < len(wages):
    inds.append(count)
    count += 1
</code>```

The results are as expected:

```<code>>>> sorted_wages
[200, 1500, 2600, 14500, 15000]
>>> sorted_names
['Aneta', 'Łukasz', 'Mikołaj', 'Ola', 'Asia']
</code>```

Title: List sorting - two lists into one

Body:
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

Body:
You can use a functionality similar to numpy.argsort: sort a list of the indices into the correct order, and then use that to rearrange both lists:

inds = list(range(len(wages))) # This can be converted into a while loop that appends elements until `len(wages)` is reached
inds.sort(key=lambda x: wages[x]) # Or did you want names[x] here?
sorted_wages = []
sorted_names = []
for ind in inds:
    sorted_wages.append(wages[ind])
    sorted_names.append(names[ind])

You can use a key that selects either the wage (lambda x: wages[x] as shown) or the name (lambda x: names[x]) for sorting. If you really want, the first line can be replaced with something like

inds = []
count = 0
while count < len(wages):
    inds.append(count)
    count += 1

The results are as expected:

>>> sorted_wages
[200, 1500, 2600, 14500, 15000]
>>> sorted_names
['Aneta', 'Łukasz', 'Mikołaj', 'Ola', 'Asia']


问:
Replace div with another div (ASP.NET MVC)
I have PartialView

Here is code

```<code>  <div id="question1" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question1)
</div>
<div id="question2" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question2)
</div>
<div id="question3" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question3)
</div>
<div  id="question4" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question4)
</div>
</code>```

I call PartialView via AJAX

Code here:

```<code><script>
$(document).ready(function () {
    var full_url = document.URL; // Get current url
    var url_array = full_url.split('/') // Split the string into an array with / as separator
    var id = url_array[url_array.length - 1];  // Get the last part of the array (-1)

    $.ajax({
        type: "GET",
        url: "/interwier/QuestionBlock",
        data: { id: id },
        success: function (data) {
            $("#questions").html(data);

        },
        error: function () {
            alert("Smth wrong in controller");
        }
    });
});
</code>```

How I can display div with id=question1 when I click button replace it with div with id= question2? Button is not in PartialView.

Update

I decide to change logic and delete PartialView

I make code in div like this

```<code> <div id="questions" class="qustion-div-one">
        <div id="question1" style="font-size:20px; margin-bottom:10px;">
            @Html.DisplayFor(modelItem => Model.Question1)
        </div>
        <div id="question2" style="font-size:20px; margin-bottom:10px; display:none">
            @Html.DisplayFor(modelItem => Model.Question2)
        </div>
        <div id="question3" style="font-size:20px; margin-bottom:10px; display:none">
            @Html.DisplayFor(modelItem => Model.Question3)
        </div>
        <div id="question4" style="font-size:20px; margin-bottom:10px; display:none">
            @Html.DisplayFor(modelItem => Model.Question4)
        </div>
    </div>
</code>```

I need on button click make question1 hidden, and question2 visible, on next click question2 will be hidden and question3 visible and etc.

Or just simple remove question1 and change  for question2 etc.

How I can do this?

UPDATE 2

I try to do this script

```<code> $('#next').click(function () {
    $('#questions>div').toggle();
});
</code>```

but it opens all 3 divs, but i need question2 div

答:
I think you could try this: decorate your div with a data-* attribute, like data-position, and another attribute on #next button like a counter :

```<code><div id="questions" class="qustion-div-one" data-pos="1">
    <div id="question1" style="font-size:20px; margin-bottom:10px;">
        @Html.DisplayFor(modelItem => Model.Question1)
    </div>
    <div id="question2" style="font-size:20px; margin-bottom:10px; display:none" data-pos="2">
        @Html.DisplayFor(modelItem => Model.Question2)
    </div>
    <div id="question3" style="font-size:20px; margin-bottom:10px; display:none" data-pos="3">
        @Html.DisplayFor(modelItem => Model.Question3)
    </div>
    <div id="question4" style="font-size:20px; margin-bottom:10px; display:none" data-pos="4">
        @Html.DisplayFor(modelItem => Model.Question4)
    </div>
</div>

<button id="next" data-target"1">Next</button>
</code>```

Then on click you increment data-target if < of number of divs.
Something like this older question

Show & hide elements by data attribute

Body:
I have PartialView

Here is code

    @Html.DisplayFor(modelItem => Model.Question1)

    @Html.DisplayFor(modelItem => Model.Question2)

    @Html.DisplayFor(modelItem => Model.Question3)

    @Html.DisplayFor(modelItem => Model.Question4)

I call PartialView via AJAX

Code here:

Body:
I think you could try this: decorate your div with a data-* attribute, like data-position, and another attribute on #next button like a counter :

<div id="questions" class="qustion-div-one" data-pos="1">
    <div id="question1" style="font-size:20px; margin-bottom:10px;">
        @Html.DisplayFor(modelItem => Model.Question1)
    </div>
    <div id="question2" style="font-size:20px; margin-bottom:10px; display:none" data-pos="2">
        @Html.DisplayFor(modelItem => Model.Question2)
    </div>
    <div id="question3" style="font-size:20px; margin-bottom:10px; display:none" data-pos="3">
        @Html.DisplayFor(modelItem => Model.Question3)
    </div>
    <div id="question4" style="font-size:20px; margin-bottom:10px; display:none" data-pos="4">
        @Html.DisplayFor(modelItem => Model.Question4)
    </div>
</div>

<button id="next" data-target"1">Next</button>

Then on click you increment data-target if < of number of divs.
Something like this older question

Show & hide elements by data attribute


问:
Why is the extension of my ini files nothing?
I have a procedure to save a file, which is an ini file. The procedure below is just where the user chooses the directory and name of the file:

```<code>procedure TForm1.SaveFile(Sender: TObject);
var
  Dialog : TSaveDialog;
begin
  Dialog := TSaveDialog.Create(self);
  try
    //dialog properties go here
    Dialog.Filter := 'Title (*.ini)|*.ini';
    Dialog.Options := Dialog.Options + [ofOverwritePrompt];
    if Dialog.Execute then
    begin
      //any saving procedures go here if required

      ShowMessage('File saved: ' + Dialog.FileName);
    end
  else
      ShowMessage('Save file was cancelled');
  finally
    Dialog.Free;
  end;
end;
</code>```

As you can see I set the filter to ini but no files show at all (it still saves)
The procedure below is where the user can select a previously saved file

```<code>procedure TForm1.LoadFileBtnClick(Sender: TObject);
Var
FileName, FileExtension : String;
SelectedFile : TOpenDialog;
begin
SelectedFile := TOpenDialog.Create(nil);
Try
  if SelectedFile.Execute() then
   FileName := SelectedFile.FileName
   else
   //Do whatever here if user doesn't select file
Finally
  SelectedFile.Free;  //Free dialog from memory

End;
  FileExtension := ExtractFileExt(FileName);

  if not (FileExtension = 'ini') then
    exit
    else
//Do whatever here if file extension matches specified type
end;
</code>```

I get the extension of the filename and check if its ini. The ShowMessage is there to see what value is returned for testing purposes. When i click an ini file nothing is returned but when i click a text file '.txt' is returned. Why do my ini files save with the type as 'File' when they are ini files.

How could i change my load file procedure to detect if its an ini file and if not then exit?

答:
Set the property DefaultExt in the SaveDialog to '.ini'
These will solve your problem</p>

Body:
I have a procedure to save a file, which is an ini file. The procedure below is just where the user chooses the directory and name of the file:

procedure TForm1.SaveFile(Sender: TObject);
var
  Dialog : TSaveDialog;
begin
  Dialog := TSaveDialog.Create(self);
  try
    //dialog properties go here
    Dialog.Filter := 'Title (*.ini)|*.ini';
    Dialog.Options := Dialog.Options + [ofOverwritePrompt];
    if Dialog.Execute then
    begin
      //any saving procedures go here if required

      ShowMessage('File saved: ' + Dialog.FileName);
    end
  else
      ShowMessage('Save file was cancelled');
  finally
    Dialog.Free;
  end;
end;

As you can see I set the filter to ini but no files show at all (it still saves)
The procedure below is where the user can select a previously saved file

procedure TForm1.LoadFileBtnClick(Sender: TObject);
Var
FileName, FileExtension : String;
SelectedFile : TOpenDialog;
begin
SelectedFile := TOpenDialog.Create(nil);
Try
  if SelectedFile.Execute() then
   FileName := SelectedFile.FileName
   else
   //Do whatever here if user doesn't select file
Finally
  SelectedFile.Free;  //Free dialog from memory

End;
  FileExtension := ExtractFileExt(FileName);

  if not (FileExtension = 'ini') then
    exit
    else
//Do whatever here if file extension matches specified type
end;

I get the extension of the filename and check if its ini. The ShowMessage is there to see what value is returned for testing purposes. When i click an ini file nothing is returned but when i click a text file '.txt' is returned. Why do my ini files save with the type as 'File' when they are ini files.

How could i change my load file procedure to detect if its an ini file and if not then exit?


问:
Number of Duplicate Rows in multiple columns (more than 10) in SQL Server
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

```<code>Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3
</code>```

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

```<code>Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2
</code>```

答:
To get your disired result you can use the following query, I'm guessing you don't want to see customers who have the same x,y,z value over all rows of that customer. If so, the follwing query should work.

```<code>SELECT t.*
FROM <table> AS t INNER JOIN
    (
    SELECT DISTINCT customer
    FROM <table>
    GROUP BY customer, x,y,z
    HAVING COUNT(*) < 2
    ) AS difacc
    ON difacc.customer = t.customer
</code>```

Result

```<code>Customer  Account X   Y   Z
A         001     X1  Y1  Z1
A         002     X2  Y1  Z1
A         003     X1  Y1  Z1
B         004     X3  Y2  Z2
B         005     X4  Y2  Z2
</code>```

Body:
I have a table in SQL Server and I need to find the number of customers and accounts who have different values across the row.

For example

Customer  Account    X   Y   Z
-------------------------------
A             001   X1   Y1  Z1
A             002   X2   Y1  Z1
A             003   X1   Y1  Z1
B             004   X3   Y2  Z2
B             005   X4   Y2  Z2
C             006   X5   Y3  Z3
C             007   X5   Y3  Z3

and I want the result to be Number of Customers with different X,Y,Z are 2, Number of accounts affected are 5.

Customer  Account   X   Y   Z
-------------------------------
A            001    X1  Y1  Z1
A            002    X2  Y1  Z1
A            003    X1  Y1  Z1
B            004    X3  Y2  Z2
B            005    X4  Y2  Z2

Body:
To get your disired result you can use the following query, I'm guessing you don't want to see customers who have the same x,y,z value over all rows of that customer. If so, the follwing query should work.

SELECT t.*
FROM <table> AS t INNER JOIN
    (
    SELECT DISTINCT customer
    FROM <table>
    GROUP BY customer, x,y,z
    HAVING COUNT(*) < 2
    ) AS difacc
    ON difacc.customer = t.customer

Result

Customer  Account X   Y   Z
A         001     X1  Y1  Z1
A         002     X2  Y1  Z1
A         003     X1  Y1  Z1
B         004     X3  Y2  Z2
B         005     X4  Y2  Z2


问:
How I can get text enclosed inside custom tag
I need to get Data1,'Data2' and 'Data3' from the below text using JavaScript functions or regular expressions.

```<code>var myText= "<ls>  <data id="1">Data1</data> <data id="2">Data2</data> <data id="3">Data3</data> </ls>";
</code>```

myText variable will hold the data as above, i need to extract Data 1 ,Data 2, and Data from it.

答:
You can still use document.getElementById

```<code>document.getElementById('1').innerHTML
</code>```

DEMO

Body:
I need to get Data1,'Data2' and 'Data3' from the below text using JavaScript functions or regular expressions.

var myText= "<ls>  <data id="1">Data1</data> <data id="2">Data2</data> <data id="3">Data3</data> </ls>";

myText variable will hold the data as above, i need to extract Data 1 ,Data 2, and Data from it.

Body:
You can still use document.getElementById

document.getElementById('1').innerHTML

DEMO


问:
Why is std::exchange not noexcept?
According to the Standard (N4659, §23.2.4, [utility.exchange]), std::exchange should do a std::move and a std::forward:

template <class T, class U = T> T exchange(T& obj, U&& new_val);

Effects: Equivalent to:

```<code>T old_val = std::move(obj);
obj = std::forward<U>(new_val);
return old_val;
</code>```

Both move and forward are marked as noexcept:

(N4659, §23.2.5, [forward]):

template <class T> constexpr T&& forward(remove_reference_t<T>& t) noexcept;
template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;

Returns: static_cast<T&&>(t).

(...)

template <class T> constexpr remove_reference_t<T>&& move(T&& t) noexcept;

Returns: static_cast<remove_reference_t<T>&&>(t).

So why isn't exchange noexcept? Is there some other reason for this or did the committee simply overlook this? Is this being proposed or can I write one?

答: The code is also using constructors and the assignment operator for type T. One of these might throw.

Title: Why is std::exchange not noexcept?

Body:
According to the Standard (N4659, §23.2.4, [utility.exchange]), std::exchange should do a std::move and a std::forward:

template <class T, class U = T> T exchange(T& obj, U&& new_val);

Effects: Equivalent to:

T old_val = std::move(obj);
obj = std::forward(new_val);
return old_val;

Both move and forward are marked as noexcept:

(N4659, §23.2.5, [forward]):

template <class T> constexpr T&& forward(remove_reference_t<T>& t) noexcept;
template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;

Returns: static_cast<T&&>(t).

(...)

template <class T> constexpr remove_reference_t<T>&& move(T&& t) noexcept;

Returns: static_cast<remove_reference_t<T>&&>(t).

So why isn't exchange noexcept? Is there some other reason for this or did the committee simply overlook this? Is this being proposed or can I write one?


问:
How to get rid of white space in palindrome (Java)
```<code>public class reverserapp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Please Enter a word");
      String str = scan.nextLine();

      String reverse = "";
      for( int i = str.length() - 1; i >= 0; i--)
          reverse += str.charAt(i);

      if(reverse.equalsIgnoreCase(str))
          System.out.println("Palindrome");
      else System.out.println("Not Palindrome");

    }

}
</code>```

This is my palindrome code. I'm doing this for a small assignment. I can get single words to work but if I write a something like "Don’t nod" it shows up as not palindrome. How can I achieve this? I'd like for my code to ignore punctuation's and white space.

So in the end result should be like "dontnod"

Thanks in advance for any help, complete noob at this.

答:
You can use the replace function from StringUtils.

Example:

```<code>StringUtils.replace("asdasd aaaa", " ", ""); //-> output: asdasdaaaa
</code>```

Body:
public class reverserapp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Please Enter a word");
      String str = scan.nextLine();

      String reverse = "";
      for( int i = str.length() - 1; i >= 0; i--)
          reverse += str.charAt(i);

      if(reverse.equalsIgnoreCase(str))
          System.out.println("Palindrome");
      else System.out.println("Not Palindrome");

    }

}

This is my palindrome code. I'm doing this for a small assignment. I can get single words to work but if I write a something like "Don’t nod" it shows up as not palindrome. How can I achieve this? I'd like for my code to ignore punctuation's and white space.

So in the end result should be like "dontnod"

Thanks in advance for any help, complete noob at this.

Body:
You can use the replace function from StringUtils.

Example:

StringUtils.replace("asdasd aaaa", " ", ""); //-> output: asdasdaaaa


问:
Is there a method to know when the focus of an internal frame has changed to a different one within a desktop pane?
I have a JDesktopPane which creates several JInternalFrame components. The desktop keeps some variables which each internal frame needs to know, so every time an internal frame is clicked, it needs to check the desktop variables and copy them. When an internal frame is created, I can just copy them, but once the frame has been created I don't know how to make it check the variables every time it is clicked.

The thing is that if I use the listener on the internal frame, I can't use desktop's methods and from the desktop I don't know how to check if an internal frame has been clicked (because it creates the internal frames on run-time). What I thought was to use a method in the JDesktopPanethat copies the variables and is called every time any of the internal frames is clicked (for example, if any part of the desktop is clicked at all), but I don't know what event is triggered in then desktop when the internal frames are clikced (if there's any at all).

So, is there any method on the desktop pane (or wherever) which is activated every time an internal frame is selected?

答:
but I don't know what event is triggered in then desktop when the internal frames are clikced

You can use an InternalFrameListener.

Read the section from the Swing tutorial on How to Write and InternalFrameListener for more information and working examples.

I can't use desktop's methods

Why not?

You can get the desktop pane using the getDesktopPane() method of the internal frame.


问:
How to inverse a conditional in JavaScript
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

```<code>       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }
</code>```

答:
if I understand well:

```<code>    var capitalisation = "lowercase";
    var inverse = false;

   function switchCase(text, inverse) {
        if (capitalisation === "lowercase") {
            text = text.toLowerCase();
        } else {
            text = text.toUpperCase();
        }
        return text;
    }

   function switchCase2(text, inverse) {
        return inverse ? text.toLowerCase() : text.toUpperCase() ;
    }

    alert(switchCase2('GGFGFF',inverse));
</code>```

Demo

Body:
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }

Body:
if I understand well:

    var capitalisation = "lowercase";
    var inverse = false;

   function switchCase(text, inverse) {
        if (capitalisation === "lowercase") {
            text = text.toLowerCase();
        } else {
            text = text.toUpperCase();
        }
        return text;
    }

   function switchCase2(text, inverse) {
        return inverse ? text.toLowerCase() : text.toUpperCase() ;
    }

    alert(switchCase2('GGFGFF',inverse));

Demo


答:
Remove all non-letter characters, then put the resulting String to lower case .

```<code>str = str.replaceAll("[^a-zA-Z]", "");
str = str.toLowerCase();
</code>```

Title: How to get rid of white space in palindrome (Java)

Body:
Remove all non-letter characters, then put the resulting String to lower case .

str = str.replaceAll("[^a-zA-Z]", "");
str = str.toLowerCase();


问:
SQL query return a result on group by expression (Oracle)
When I run the following query, I get a sum of amount per accounting period. However in some accounting periods, I do not have any amount, so naturally, those periods with no sum of amount (null) are not shown in the result set.

I would like to know how to return those with the sum of amount 0 for them.

```<code>SELECT
    ACCOUNTING_PERIOD,
    SUM(RESOURCE_AMOUNT) AS TOTAL,
FROM
    RESOURCE_TBL
GROUP BY
    ACCOUNTING_PERIOD
</code>```

I get the following result set

```<code>accounting_period   TOTAL
-------------------------
1                   234
3                    65
5                   943
6                   299
.                   .
.                   .
.                   .
</code>```

In the above period 2 and 4 is left out since the sum is zero or null but I would like to get

```<code>accounting_period   TOTAL
-------------------------
1                   234
2                     0
3                    65
4                     0
5                   943
6                   299
.                   .
.                   .
.                   .
</code>```

答:
Generate a list of all the possible accounting periods and then LEFT OUTER JOIN that with your table:

```<code>WITH accounting_periods ( accounting_period ) AS (
  SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 12
)
SELECT a.ACCOUNTING_PERIOD,
       COALESCE( SUM(RESOURCE_AMOUNT), 0 ) AS TOTAL
FROM   accounting_periods a
       LEFT OUTER JOIN
       RESOURCE_TBL r
       ON ( a.accounting_period = r.accounting_period )
GROUP BY a.ACCOUNTING_PERIOD
</code>```

Body:
When I run the following query, I get a sum of amount per accounting period. However in some accounting periods, I do not have any amount, so naturally, those periods with no sum of amount (null) are not shown in the result set.

I would like to know how to return those with the sum of amount 0 for them.

SELECT
    ACCOUNTING_PERIOD,
    SUM(RESOURCE_AMOUNT) AS TOTAL,
FROM
    RESOURCE_TBL
GROUP BY
    ACCOUNTING_PERIOD

I get the following result set

accounting_period   TOTAL
-------------------------
1                   234
3                    65
5                   943
6                   299
.                   .
.                   .
.                   .

In the above period 2 and 4 is left out since the sum is zero or null but I would like to get

accounting_period   TOTAL
-------------------------
1                   234
2                     0
3                    65
4                     0
5                   943
6                   299
.                   .
.                   .
.                   .

Body:
Generate a list of all the possible accounting periods and then LEFT OUTER JOIN that with your table:

WITH accounting_periods ( accounting_period ) AS (
  SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 12
)
SELECT a.ACCOUNTING_PERIOD,
       COALESCE( SUM(RESOURCE_AMOUNT), 0 ) AS TOTAL
FROM   accounting_periods a
       LEFT OUTER JOIN
       RESOURCE_TBL r
       ON ( a.accounting_period = r.accounting_period )
GROUP BY a.ACCOUNTING_PERIOD


问:
initial= not working on Form inputs
I have a simple search form on my page /.

```<code>class SearchForm(Form):
    query = CharField(max_length=256,
                      label="Search",
                      required=False,
                      widget=TextInput(attrs={'placeholder': 'Search …',
                                              'class': 'form-control'}))

    page = IntegerField(min_value=8, initial=1, widget=HiddenInput())
    sort = CharField(max_length=16, initial="id", widget=HiddenInput())
    order = CharField(max_length=4, initial="asc", widget=HiddenInput())
</code>```

My (simplified) view is this:

```<code>def search(request):
    search_form = SearchForm(request.GET)
    return render(request, "search.html", {'search_form': search_form})
</code>```

My goal is to have search_form.cleaned_data['<FIELD>'] return the initial values I set in the class SearchForm, without having to check wether they are exist None or are empty ''.

Unfortunately my code does not work as the input elements are renderd like this:

```<code><input id="id_page" name="page" type="hidden" />
<input id="id_sort" maxlength="16" name="sort" type="hidden" />
<input id="id_order" maxlength="4" name="order" type="hidden" />
</code>```

Any ideas?

答:
The reason the code would not work was because

```<code>search_form = SearchForm(request.GET)
</code>```

creates a bound form. And bound forms don't have initial values.

I ended up with this gem. It checks if request.GET contains at least one of the form's fields (regardless of value, e. g. /?page=) and then creates a bound form where validation can happen. Otherwise the user visited / or submitted other parameters not related to the form (e. g. /?foo=bar).

```<code>if request.GET & SearchForm.base_fields.keys():
    search_form = SearchForm(request.GET)
else:
    ...
    search_form = SearchForm(initial={...})
</code>```

Title: initial= not working on Form inputs

Body:
I have a simple search form on my page /.

class SearchForm(Form):
    query = CharField(max_length=256,
                      label="Search",
                      required=False,
                      widget=TextInput(attrs={'placeholder': 'Search …',
                                              'class': 'form-control'}))

    page = IntegerField(min_value=8, initial=1, widget=HiddenInput())
    sort = CharField(max_length=16, initial="id", widget=HiddenInput())
    order = CharField(max_length=4, initial="asc", widget=HiddenInput())

My (simplified) view is this:

def search(request):
    search_form = SearchForm(request.GET)
    return render(request, "search.html", {'search_form': search_form})

My goal is to have search_form.cleaned_data['<FIELD>'] return the initial values I set in the class SearchForm, without having to check wether they are exist None or are empty ''.

Unfortunately my code does not work as the input elements are renderd like this:

<input id="id_page" name="page" type="hidden" />
<input id="id_sort" maxlength="16" name="sort" type="hidden" />
<input id="id_order" maxlength="4" name="order" type="hidden" />

Any ideas?

Body:
The reason the code would not work was because

search_form = SearchForm(request.GET)

creates a bound form. And bound forms don't have initial values.

I ended up with this gem. It checks if request.GET contains at least one of the form's fields (regardless of value, e. g. /?page=) and then creates a bound form where validation can happen. Otherwise the user visited / or submitted other parameters not related to the form (e. g. /?foo=bar).

if request.GET & SearchForm.base_fields.keys():
    search_form = SearchForm(request.GET)
else:
    ...
    search_form = SearchForm(initial={...})


问:
Program that verifies if a word is in a file and prints the number of the line and the line itself
As the title indicates I'm trying to make a program that verifies if a word is in a file and prints the number of the line and the line itself. The exercise tells us to use the function strstr.

Here is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DIM_WORDS 1000

int main(void)
{
    char word[DIM_WORDS]={'\0'};
    char textname[DIM_WORDS]={'\0'};
    char stringtoread[DIM_WORDS]={'\0'};
    char line[DIM_WORDS]={'\0'};
    char* verify;
    FILE* fp=NULL;
    int ret=0 , num=0;

    do{
        printf("Introduza o nome do ficheiro e a palavra a procurar\n");
        // Lê ambas as informações e guarda-as numa string
        fgets(stringtoread, DIM_WORDS, stdin);
        // Separa as duas informações em 2 strings
        ret=sscanf(stringtoread, "%s %s", textname, word);
    }while(ret!=2);

    fp=fopen(textname, "r");

    if(fp==NULL)
    {
        printf("Error: That file doesn't exist or could not be open\n");
        exit(EXIT_FAILURE);
    }

    while(fgets(line, sizeof(line), fp))
    {

        verify = strstr(word, line);

        if(verify!=NULL)
        {
            printf("The word was encountered in line %d\n", num);
            printf("%s", line);
        }

        num++;

    }

    fclose(fp);

    return EXIT_SUCCESS;

}#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DIM_WORDS 1000

int main(void)
{
    char word[DIM_WORDS]={'\0'};
    char textname[DIM_WORDS]={'\0'};
    char stringtoread[DIM_WORDS]={'\0'};
    char line[DIM_WORDS]={'\0'};
    char* verify;
    FILE* fp=NULL;
    int ret=0 , num=0;

    do{
        printf("Introduza o nome do ficheiro e a palavra a procurar\n");
        fgets(stringtoread, DIM_WORDS, stdin);
        ret=sscanf(stringtoread, "%s %s", textname, word);
    }while(ret!=2);

    fp=fopen(textname, "r");

    if(fp==NULL)
    {
        printf("Error: That file doesn't exist or could not be open\n");
        exit(EXIT_FAILURE);
    }

    while(fgets(line, sizeof(line), fp))
    {

        verify = strstr(word, line);

        if(verify!=NULL)
        {
            printf("The word was encountered in line %d\n", num);
            printf("%s", line);
        }

        num++;

    }

    fclose(fp);

    return EXIT_SUCCESS;

}
</code>```

I tried my program with a file text.txt and trying to find the word file:

A text file (sometimes spelled "textfile": an old alternative name is "flatfile") is a kind of computer file that is structured as a sequence of lines of electronic text.

A text file exists within a computer file system.

The end of a text file is often denoted by placing one or more special characters, known as an end-of-file marker, after the last line in a text file.

Such markers were required under the CP/M and MS-DOS operating systems.

On modern operating systems such as Windows and Unix-like systems, text files do not contain any special EOF character.

"Text file" refers to a type of container, while plain text refers to a type of content. Text files can contain plain text, but they are not limited to such.

At a generic level of description, there are two kinds of computer files: text files and binary files.[1]

Problem is my program is not printing anything.
I think the problem might be here:

```<code>    while(fgets(line, sizeof(line), fp))
    {

        verify = strstr(word, line);

        if(verify!=NULL)
        {
            printf("The word was encountered in line %d\n", num);
            printf("%s", line);
        }

        num++;

    }
</code>```

Since if I remove most of the code just to print all the lines of the file it prints them:

```<code>    while(fgets(line, sizeof(line), fp)
        printf("%s", line);
</code>```

Can someone help me to fix this? Thanks!

答:
You've got this backwards

```<code>verify = strstr(word, line);
</code>```

you're searching for line in word when it should be

```<code>verify = strstr(line, word);
</code>```

Body:
As the title indicates I'm trying to make a program that verifies if a word is in a file and prints the number of the line and the line itself. The exercise tells us to use the function strstr.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DIM_WORDS 1000

int main(void)
{
    char word[DIM_WORDS]={'\0'};
    char textname[DIM_WORDS]={'\0'};
    char stringtoread[DIM_WORDS]={'\0'};
    char line[DIM_WORDS]={'\0'};
    char* verify;
    FILE* fp=NULL;
    int ret=0 , num=0;

    do{
        printf("Introduza o nome do ficheiro e a palavra a procurar\n");
        // Lê ambas as informações e guarda-as numa string
        fgets(stringtoread, DIM_WORDS, stdin);
        // Separa as duas informações em 2 strings
        ret=sscanf(stringtoread, "%s %s", textname, word);
    }while(ret!=2);

    fp=fopen(textname, "r");

    if(fp==NULL)
    {
        printf("Error: That file doesn't exist or could not be open\n");
        exit(EXIT_FAILURE);
    }

    while(fgets(line, sizeof(line), fp))
    {

        verify = strstr(word, line);

        if(verify!=NULL)
        {
            printf("The word was encountered in line %d\n", num);
            printf("%s", line);
        }

        num++;

    }

    fclose(fp);

    return EXIT_SUCCESS;

}#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DIM_WORDS 1000

int main(void)
{
    char word[DIM_WORDS]={'\0'};
    char textname[DIM_WORDS]={'\0'};
    char stringtoread[DIM_WORDS]={'\0'};
    char line[DIM_WORDS]={'\0'};
    char* verify;
    FILE* fp=NULL;
    int ret=0 , num=0;

    do{
        printf("Introduza o nome do ficheiro e a palavra a procurar\n");
        fgets(stringtoread, DIM_WORDS, stdin);
        ret=sscanf(stringtoread, "%s %s", textname, word);
    }while(ret!=2);

    fp=fopen(textname, "r");

    if(fp==NULL)
    {
        printf("Error: That file doesn't exist or could not be open\n");
        exit(EXIT_FAILURE);
    }

    while(fgets(line, sizeof(line), fp))
    {

        verify = strstr(word, line);

        if(verify!=NULL)
        {
            printf("The word was encountered in line %d\n", num);
            printf("%s", line);
        }

        num++;

    }

    fclose(fp);

    return EXIT_SUCCESS;

}

I tried my program with a file text.txt and trying to find the word file:

A text file (sometimes spelled "textfile": an old alternative name is "flatfile") is a kind of computer file that is structured as a sequence of lines of electronic text.

A text file exists within a computer file system.

The end of a text file is often denoted by placing one or more special characters, known as an end-of-file marker, after the last line in a text file.

Such markers were required under the CP/M and MS-DOS operating systems.

On modern operating systems such as Windows and Unix-like systems, text files do not contain any special EOF character.

"Text file" refers to a type of container, while plain text refers to a type of content. Text files can contain plain text, but they are not limited to such.

At a generic level of description, there are two kinds of computer files: text files and binary files.[1]

Problem is my program is not printing anything.
I think the problem might be here:

    while(fgets(line, sizeof(line), fp))
    {

        verify = strstr(word, line);

        if(verify!=NULL)
        {
            printf("The word was encountered in line %d\n", num);
            printf("%s", line);
        }

        num++;

    }

Since if I remove most of the code just to print all the lines of the file it prints them:

    while(fgets(line, sizeof(line), fp)
        printf("%s", line);

Can someone help me to fix this? Thanks!

Body:
You've got this backwards

verify = strstr(word, line);

you're searching for line in word when it should be

verify = strstr(line, word);


问:
Delphi Trunc behaving strangely
I have the following code:

```<code>function Extenso(nb: real); string;
var
  total: real;
begin
  total := Trunc(nb);
  ...
  Result := ...;
end;
</code>```

This function returns a string describing the number in full, for a country that has no cents, therefore the Trunc.

When input param nb comes in as 790209.00 (my error case, with decimals 0), strangely enough the result of Trunc is 790208 on debugger. Can someone please try to explain that ?!? I'm on Delphi XE3 update 2, with IDE fix pack 5.93, Windows 10 Pro 64.

Edit: as a clarification to the question, there's a business rule involved here, customer will accept rounds up to the result, but not down. Thanks @Dsm and @CraigYoung to your contributions.

答:
You need to use round rather than trunc here. With type real, the value is not quite exact, so 790209.00 might really be 790208.999999999 for example, and truncing this will give the value shown. Of course, if you might have a value ending in .5, rounding might not give you what you want every time, and you might need to consider some function like</p>

```<code>Trunc( nb + 0.000001);
</code>```

Title: Delphi Trunc behaving strangely

Body:
I have the following code:

function Extenso(nb: real); string;
var
  total: real;
begin
  total := Trunc(nb);
  ...
  Result := ...;
end;

This function returns a string describing the number in full, for a country that has no cents, therefore the Trunc.

When input param nb comes in as 790209.00 (my error case, with decimals 0), strangely enough the result of Trunc is 790208 on debugger. Can someone please try to explain that ?!? I'm on Delphi XE3 update 2, with IDE fix pack 5.93, Windows 10 Pro 64.

Edit: as a clarification to the question, there's a business rule involved here, customer will accept rounds up to the result, but not down. Thanks @Dsm and @CraigYoung to your contributions.

Body:
You need to use round rather than trunc here. With type real, the value is not quite exact, so 790209.00 might really be 790208.999999999 for example, and truncing this will give the value shown. Of course, if you might have a value ending in .5, rounding might not give you what you want every time, and you might need to consider some function like

Trunc( nb + 0.000001);