问:
failing to launch virtual box ubuntu VM on Windows
I installed VirtualBox on Windows.  I set it up to boot Ubuntu14.  I enabled the virtualization option for the CPU to enabled (before that, the VM would not boot up complaining about i686 CPU).  I rebooted the OS.  After this, when I try starting the VM, it gives the following error:

```<code>The VM session was closed before any attempt to power it on.

Result Code:
E_FAIL (0x80004005)
Component:
SessionMachine
Interface:
ISession {7844aa05-b02e-4cdd-a04f-ade4a762e6b7}
</code>```

What did I do wrong and how can I fix it?  Thanks.  I did not post on serverfault since this is not a server but a laptop.

答: It was a permissions issue for me because I changed the VM folder to a different drive, either try running as administrator or just change the security permissions of the VM root folder to allow full control by anyone. The latter worked for me!

Body:
I installed VirtualBox on Windows.  I set it up to boot Ubuntu14.  I enabled the virtualization option for the CPU to enabled (before that, the VM would not boot up complaining about i686 CPU).  I rebooted the OS.  After this, when I try starting the VM, it gives the following error:

The VM session was closed before any attempt to power it on.

Result Code:
E_FAIL (0x80004005)
Component:
SessionMachine
Interface:
ISession {7844aa05-b02e-4cdd-a04f-ade4a762e6b7}

What did I do wrong and how can I fix it?  Thanks.  I did not post on serverfault since this is not a server but a laptop.


来源: stackexchange

问:
Terraform-12 (AWS): Create Subnets according to provided input variables using for/for_each
I want to create a module that can accept inputs for environments(dev,test,prod) and create the number of subnets ("app" and "db" subnet for each environment) with proper tags. e.g Name=dev-app
The module should be flexible to add/delete subnets as input variables are updated.
My template looks like below

```<code>variable "environments" {
  type = map(object({
    app_subnet_cidr    = string
    db_subnet_cidr = string
  }))

  default = {
dev = {
    app_subnet_cidr = "192.168.219.0/24"
    db_subnet_cidr = "192.168.218.0/24"
  }
test = {
    app_subnet_cidr = "192.168.118.0/24"
    db_subnet_cidr = "192.168.119.0/24"
  }
}
}

resource "aws_subnet" "this" {
  for_each = var.environments
  vpc_id     = var.vpc_id
  cidr_block = {Don't know what to use here}

  tags {
  Name = {Don't know what to use here}
}
}
</code>```

I was referring to the below articles.
https://www.hashicorp.com/blog/terraform-0-12-rich-value-types/
Question-2: How "networks" variable could be defined for below module

```<code>module "subnets" {
  source = "./subnets"

  parent_vpc_id = "vpc-abcd1234"
  networks = {
    production_a = {
      network_number    = 1
      availability_zone = "us-east-1a"
    }
    production_b = {
      network_number    = 2
      availability_zone = "us-east-1b"
    }
    staging_a = {
      network_number    = 1
      availability_zone = "us-east-1a"
    }
  }
}
</code>```

https://www.hashicorp.com/blog/hashicorp-terraform-0-12-preview-for-and-for-each/

答:
The blog posts you are referring to were previews of forthcoming features not yet finished, so they are not the best reference for the final functionality that shipped. Instead, refer to the official documentation for resource for_each.

The documentation includes an example of declaring a number of azurerm_resource_group resource instances based on a map. We can adapt that example to work with your var.environments, with one resource block describing the "app" subnets, and a separate resource block describing the "db" subnets:

```<code>resource "aws_subnet" "app" {
  for_each = var.environments

  vpc_id     = var.vpc_id
  cidr_block = each.value.app_subnet_cidr

  tags = {
    Name = "${each.key}-app"
  }
}

resource "aws_subnet" "db" {
  for_each = var.environments

  vpc_id     = var.vpc_id
  cidr_block = each.value.db_subnet_cidr

  tags = {
    Name = "${each.key}-db"
  }
}
</code>```

I'm not sure exactly how your second question relates to the first, but here's how to declare a variable networks so that it would accept a value like the one you showed in the second example.

```<code>variable "networks" {
  type = map(object({
    network_number    = number
    availability_zone = string
  }))
}
</code>```

If you want to see more about that second example, I'd suggest starting a new separate question on Stack Overflow about it. The convention on Stack Overflow is to have a separate question for each topic, rather than to ask multiple questions at once.

ContentLicense: CC BY-SA 4.0

Body:
I want to create a module that can accept inputs for environments(dev,test,prod) and create the number of subnets ("app" and "db" subnet for each environment) with proper tags. e.g Name=dev-app
The module should be flexible to add/delete subnets as input variables are updated.
My template looks like below

variable "environments" {
  type = map(object({
    app_subnet_cidr    = string
    db_subnet_cidr = string
  }))

  default = {
dev = {
    app_subnet_cidr = "192.168.219.0/24"
    db_subnet_cidr = "192.168.218.0/24"
  }
test = {
    app_subnet_cidr = "192.168.118.0/24"
    db_subnet_cidr = "192.168.119.0/24"
  }
}
}

resource "aws_subnet" "this" {
  for_each = var.environments
  vpc_id     = var.vpc_id
  cidr_block = {Don't know what to use here}

  tags {
  Name = {Don't know what to use here}
}
}

I was referring to the below articles.
https://www.hashicorp.com/blog/terraform-0-12-rich-value-types/
Question-2: How "networks" variable could be defined for below module

module "subnets" {
  source = "./subnets"

  parent_vpc_id = "vpc-abcd1234"
  networks = {
    production_a = {
      network_number    = 1
      availability_zone = "us-east-1a"
    }
    production_b = {
      network_number    = 2
      availability_zone = "us-east-1b"
    }
    staging_a = {
      network_number    = 1
      availability_zone = "us-east-1a"
    }
  }
}

https://www.hashicorp.com/blog/hashicorp-terraform-0-12-preview-for-and-for-each/

Body:
The blog posts you are referring to were previews of forthcoming features not yet finished, so they are not the best reference for the final functionality that shipped. Instead, refer to the official documentation for resource for_each.

The documentation includes an example of declaring a number of azurerm_resource_group resource instances based on a map. We can adapt that example to work with your var.environments, with one resource block describing the "app" subnets, and a separate resource block describing the "db" subnets:

resource "aws_subnet" "app" {
  for_each = var.environments

  vpc_id     = var.vpc_id
  cidr_block = each.value.app_subnet_cidr

  tags = {
    Name = "${each.key}-app"
  }
}

resource "aws_subnet" "db" {
  for_each = var.environments

  vpc_id     = var.vpc_id
  cidr_block = each.value.db_subnet_cidr

  tags = {
    Name = "${each.key}-db"
  }
}

I'm not sure exactly how your second question relates to the first, but here's how to declare a variable networks so that it would accept a value like the one you showed in the second example.

variable "networks" {
  type = map(object({
    network_number    = number
    availability_zone = string
  }))
}

If you want to see more about that second example, I'd suggest starting a new separate question on Stack Overflow about it. The convention on Stack Overflow is to have a separate question for each topic, rather than to ask multiple questions at once.


问:
Visual Studio 2010 Web deployment task failed
I am trying to use VS2010's 1-Click Publish feature to deploy a test site from my laptop to my server. I have the firewall turned off on both machines and the MS Deployment Service is up and running on both my laptop and the server.

However, when I try and publish from VS2010 on my laptop I get the following error:

Error 1 Web deployment task failed.(Remote agent (URL https://192.168.1.181/:8172/msdeploy.axd?site=LocationsTest) could not be contacted.  Make sure the remote agent service is installed and started on the target computer.)

  The requested resource does not exist, or the requested URL is incorrect.

  Error details:

  Remote agent (URL https://192.168.1.181/:8172/msdeploy.axd?site=LocationsTest) could not be contacted.  Make sure the remote agent service is installed and started on the target computer.

  An unsupported response was received. The response header 'MSDeploy.Response' was '' but 'v1' was expected.

  The remote server returned an error: (404) Not Found.  0 0 Test.Web

Any idea what I am doing wrong here?

答:
This same message would occur almost at random when publishing projects from visual studio 2010.

The fix was to delete the $projectname.Publish.xml file (in the root directory of the project) and re-create it.

ContentLicense: CC BY-SA 3.0


问:
SQL Transaction overlap between C# and T-SQL
I have a C# process that is inserting records into a table within a transaction.  During this time another process (an SQL stored procedure) is updating this table.  The C# process is using serializable isolation mode and the SP is using read commit.

The table being updated has a datetime field named DateShipped which the C# process is inserting using the current time.  It takes about 1s for the C# process to determine the values to use and execute the insert statement.  Looking at the data in the table you can see all the records added within the transaction have about a 1s difference in the DateShipped field.  Let's not worry about how to make this process better.  I'm currently concerned with understanding how the SP is able to update a record that is within the transaction of another process and has not been committed.

There is another field TransID in the table defined as INT.  The C# process is not specifying a value for this field when inserting so it defaults to NULL.  The SP runs on a schedule and the first thing it does is update all the records where TransID IS NULL to a specified value.  The SP is running within an explicit transaction.

There are times (not sure if it is always as I don't know how often they both run at the exact same time) when some of the records (the first so many) get updated with a TransID when the others within the same transaction do not.

How is it that the SP can see the first so many records, but not all of them?

Is there a way to use Extended Events to capture this?

Insert Results:

```<code>DateShipped             TransID
2020-02-12 00:26:47.680 514928
2020-02-12 00:26:49.090 514929
2020-02-12 00:26:50.057 514929
2020-02-12 00:26:51.027 514929
2020-02-12 00:26:51.963 514929
2020-02-12 00:26:52.887 514929
2020-02-12 00:26:53.807 514929
2020-02-12 00:26:54.747 514929
2020-02-12 00:26:55.713 514929
2020-02-12 00:26:56.700 514929
2020-02-12 00:26:57.700 514929
2020-02-12 00:26:58.653 514929
2020-02-12 00:26:59.620 514929
2020-02-12 00:27:00.573 514929
</code>```

Can someone recommend a way to prevent this (updating an uncommitted insert from a different transaction) or capture relative information to show this is happening?

Additional Information

Process 1 Code (c#)

```<code>ADODB.Connection.BeginTrans()

... Several inline SELECTs and INSERTs via ADODB.Connection.Execute()

ADODB.Connection.CommitTrans()
</code>```

The insert is setting the DateShipped field to the current date/time. So the DateShipped is the date/time of the insert.

Process 2 Code (stored procedure)

```<code>BEGIN TRANSACTION

SELECT @ID = (MAX(TransID) + 1) FROM dbo.tHostInterfaceExport
INSERT INTO dbo.tHostInterfaceExport ( TransID ) VALUES (@ID)

EXEC dbo.dloc_UpdateActivityTables @ID

COMMIT TRANSACTION
</code>```

PROCEDURE dbo.dloc_UpdateActivityTables @TransID INT

```<code>UPDATE dbo.tActivityShipments
SET TransID = @TransID
WHERE TransID IS NULL
</code>```

The issue is this UPDATE statement sometimes (probably only when the 2 processes run at the same time) only updates some of the first records inserted in process 1.

Here's another sample of data where the issue has happened.
All of these records were written within the same transaction of process 1.

```<code>DateShipped             TransID
2020-02-12 10:54:29.157 244878
2020-02-12 10:54:30.063 244878
2020-02-12 10:54:30.940 244878
...
2020-02-12 10:56:31.290 244878
2020-02-12 10:56:31.867 244878
2020-02-12 10:56:32.493 244878  <-- why was this one and the above ones updated
2020-02-12 10:56:33.087 244879  <-- and not this one and the ones below?
2020-02-12 10:56:33.730 244879
2020-02-12 10:56:34.353 244879
...
2020-02-12 10:57:32.360 244879
2020-02-12 10:57:33.093 244879
2020-02-12 10:57:33.970 244879
</code>```

Addition information as to when the TransID are created.
The TransID is created at the start of process 2.  This shows that process 2 was called at 2 separate times and 3 minutes apart.

```<code>TransID DateCreated
244878  2020-02-12 10:54:56.817
244879  2020-02-12 10:57:56.880
</code>```

What's interesting here is that process 2 is scheduled to run every 60s, yet it was held up (waiting for process 1 to finish and commit the transaction) before finishing TransID 244878.  I say this because the entry for TransID = 244879 should of happened at 10:55:56 or 10:56:56, but the process was still waiting for the previous update that was being blocked by the insert transaction which finished after the last insert at 10:57:33.970.

答:
The issue turned out to be a COMMIT within process 1 which was ending the transaction prematurely.

Process 1 was starting a transaction and then doing a bunch of work.  Part of the work was calling a stored procedure that had a COMMIT.  Once this was executed the transaction was ended and process 2 was able to continue.

I still need to understand why process 1 did not throw an error when it executed the intended commit transaction.

Thanks to Piotr for suggesting using a trigger to get additional information.

Body:
I have a C# process that is inserting records into a table within a transaction.  During this time another process (an SQL stored procedure) is updating this table.  The C# process is using serializable isolation mode and the SP is using read commit.

The table being updated has a datetime field named DateShipped which the C# process is inserting using the current time.  It takes about 1s for the C# process to determine the values to use and execute the insert statement.  Looking at the data in the table you can see all the records added within the transaction have about a 1s difference in the DateShipped field.  Let's not worry about how to make this process better.  I'm currently concerned with understanding how the SP is able to update a record that is within the transaction of another process and has not been committed.

There is another field TransID in the table defined as INT.  The C# process is not specifying a value for this field when inserting so it defaults to NULL.  The SP runs on a schedule and the first thing it does is update all the records where TransID IS NULL to a specified value.  The SP is running within an explicit transaction.

There are times (not sure if it is always as I don't know how often they both run at the exact same time) when some of the records (the first so many) get updated with a TransID when the others within the same transaction do not.

How is it that the SP can see the first so many records, but not all of them?

Is there a way to use Extended Events to capture this?

Insert Results:

DateShipped             TransID
2020-02-12 00:26:47.680 514928
2020-02-12 00:26:49.090 514929
2020-02-12 00:26:50.057 514929
2020-02-12 00:26:51.027 514929
2020-02-12 00:26:51.963 514929
2020-02-12 00:26:52.887 514929
2020-02-12 00:26:53.807 514929
2020-02-12 00:26:54.747 514929
2020-02-12 00:26:55.713 514929
2020-02-12 00:26:56.700 514929
2020-02-12 00:26:57.700 514929
2020-02-12 00:26:58.653 514929
2020-02-12 00:26:59.620 514929
2020-02-12 00:27:00.573 514929

Can someone recommend a way to prevent this (updating an uncommitted insert from a different transaction) or capture relative information to show this is happening?

Additional Information

Process 1 Code (c#)

ADODB.Connection.BeginTrans()

... Several inline SELECTs and INSERTs via ADODB.Connection.Execute()

ADODB.Connection.CommitTrans()

The insert is setting the DateShipped field to the current date/time. So the DateShipped is the date/time of the insert.

Process 2 Code (stored procedure)

BEGIN TRANSACTION

SELECT @ID = (MAX(TransID) + 1) FROM dbo.tHostInterfaceExport
INSERT INTO dbo.tHostInterfaceExport ( TransID ) VALUES (@ID)

EXEC dbo.dloc_UpdateActivityTables @ID

COMMIT TRANSACTION

PROCEDURE dbo.dloc_UpdateActivityTables @TransID INT

UPDATE dbo.tActivityShipments
SET TransID = @TransID
WHERE TransID IS NULL

The issue is this UPDATE statement sometimes (probably only when the 2 processes run at the same time) only updates some of the first records inserted in process 1.

Here's another sample of data where the issue has happened.
All of these records were written within the same transaction of process 1.

DateShipped             TransID
2020-02-12 10:54:29.157 244878
2020-02-12 10:54:30.063 244878
2020-02-12 10:54:30.940 244878
...
2020-02-12 10:56:31.290 244878
2020-02-12 10:56:31.867 244878
2020-02-12 10:56:32.493 244878  <-- why was this one and the above ones updated
2020-02-12 10:56:33.087 244879  <-- and not this one and the ones below?
2020-02-12 10:56:33.730 244879
2020-02-12 10:56:34.353 244879
...
2020-02-12 10:57:32.360 244879
2020-02-12 10:57:33.093 244879
2020-02-12 10:57:33.970 244879

Addition information as to when the TransID are created.
The TransID is created at the start of process 2.  This shows that process 2 was called at 2 separate times and 3 minutes apart.

TransID DateCreated
244878  2020-02-12 10:54:56.817
244879  2020-02-12 10:57:56.880

What's interesting here is that process 2 is scheduled to run every 60s, yet it was held up (waiting for process 1 to finish and commit the transaction) before finishing TransID 244878.  I say this because the entry for TransID = 244879 should of happened at 10:55:56 or 10:56:56, but the process was still waiting for the previous update that was being blocked by the insert transaction which finished after the last insert at 10:57:33.970.


问:
How do I remove the time zone from a POSIXct timestamp for conversion to XTS?
For some reason when I convert my time series data from a data frame to an xts object, the timezone is included in the index.  I suspect this is what the issue is when I try to run time series modelling on the object because I keep getting errors.  When I go to check the structure of the xts object, the data inside the xts object are somehow converted to chr.  They should be num which is what they originally were before the conversion.  Here are some data:

```<code>full_timestamp             PRICE
2015-01-02 10:02:27.389055  85.4
2015-01-02 10:03:30.926059  85.3
2015-01-02 10:04:52.231750  85.4
2015-01-02 10:05:37.139763  85.5
2015-01-02 10:06:54.926069  85.5
2015-01-02 10:07:57.253187  85.3
</code>```

Here is the structure of the dataframe:

```<code>Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   89026 obs. of  2 variables:
 $ full_timestamp: POSIXct, format: "2015-01-02 10:02:27.389055" "2015-01-02 10:03:30.926059" "2015-01-02 10:04:52.231750" ...
 $ PRICE         : num  85.4 85.3 85.4 85.5 85.5 ...
</code>```

The code that I used to convert the timestamp from a character vector to a POSIXct timestamp:

```<code>testing_eq_4xts$full_timestamp <- as.POSIXct(strptime(testing_eq_4xts$full_timestamp,
                                                      format = "%Y-%m-%d:%H:%M:%OS",
                                                      tz = ""))
</code>```

I have tried to include tz = "", not include the tz part at all, and even Sys.unsetenv("TZ") to stop the conversion picking up the timezone. I should also stress that I need the granularity in the timestamp for what I am modelling.
Here is the code I use to convert to xts:

```<code>testing_eq_xts <- as.xts(testing_eq_4xts[, names(testing_eq_4xts) != "full_timestamp"],
                  order.by = testing_eq_4xts$full_timestamp, unique = F)
</code>```

and this is what the structure looks like:

```<code>An ‘xts’ object on 2015-01-02 10:02:27.389055/2015-12-31 14:37:07.969814 containing:
  Data: num [1:89026, 1] 85.4 85.3 85.4 85.5 85.5 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "PRICE"
  Indexed by objects of class: [POSIXct,POSIXt] TZ:
  xts Attributes:
 NULL
</code>```

also the index of the xts:

```<code>[1] "2015-01-02 10:02:27.389055 AEDT" "2015-01-02 10:03:30.926059 AEDT"
[3] "2015-01-02 10:04:52.231750 AEDT" "2015-01-02 10:05:37.139763 AEDT"
</code>```

Leaving the timestamp as a character vector and trying to convert it to POSIXct when converting to xts also does not work, using:

```<code>testing_eq_xts2 = xts(testing_eq_4xts[, 2], as.POSIXct(testing_eq_4xts[, 1]))
</code>```

gives this error:

```<code>Error in as.POSIXct.default(testing_eq_4xts[, 1]) :
  do not know how to convert 'testing_eq_4xts[, 1]' to class “POSIXct”
</code>```

Am I on the right track as to why PRICE has been converted to chr in the xts object, and if so, how do I fix it?  If I am incorrect in my assumptions, then what is it that I need to do to fix this? Thanks.

答:
You have already figured out that the 'tz' value is sometimes "", but if you look at ?strptime you will see that using tz="" is really saying to use your current timezone which will get pulled from your system settings. You should instead use tz="GMT" (assuming that UTC/UCT is what you mean when you say "no time zone".) There's really no way to have "no time zone", since time is always measured in some time  zone or another.

AND ... you cannot have a POSIXct column in an xts (or zoo) object (and probably not a character value either, since you would generally expect an xts object to hold numeric values). That is because xts and zoo objects are actually R matrices and they cannot hold columns with attributes. Since POSIXct objects are actually doubles (seconds since origin) with a class attribute of 'POSIXct', they cannot be elements in the xts or zoo matrices. ( They can be xts INDEXes, because there are different rules for that part of the structure.)

```<code> myxts <- as.xts(read.csv.zoo(text="full_timestamp,             PRICE
 2015-01-02 10:02:27.389055,  85.4
 2015-01-02 10:03:30.926059,  85.3
 2015-01-02 10:04:52.231750,  85.4
 2015-01-02 10:05:37.139763,  85.5
 2015-01-02 10:06:54.926069,  85.5
 2015-01-02 10:07:57.253187,  85.3", sep=",", index=1, tz="GMT"))
 myxts
#-----------------
                    [,1]
2015-01-02 10:02:27 85.4
2015-01-02 10:03:30 85.3
2015-01-02 10:04:52 85.4
2015-01-02 10:05:37 85.5
2015-01-02 10:06:54 85.5
2015-01-02 10:07:57 85.3
Warning message:
timezone of object (GMT) is different than current timezone ().

 dput(myxts)
#-------------
structure(c(85.4, 85.3, 85.4, 85.5, 85.5, 85.3), .Dim = c(6L,
1L), index = structure(c(1420192947.38906, 1420193010.92606,
1420193092.23175, 1420193137.13976, 1420193214.92607, 1420193277.25319
), tzone = "GMT", tclass = c("POSIXct", "POSIXt")), class = c("xts",
"zoo"))

 index(myxts)
 #--------------
[1] "2015-01-02 10:02:27 GMT" "2015-01-02 10:03:30 GMT" "2015-01-02 10:04:52 GMT"
[4] "2015-01-02 10:05:37 GMT" "2015-01-02 10:06:54 GMT" "2015-01-02 10:07:57 GMT"
</code>```

Body:
For some reason when I convert my time series data from a data frame to an xts object, the timezone is included in the index.  I suspect this is what the issue is when I try to run time series modelling on the object because I keep getting errors.  When I go to check the structure of the xts object, the data inside the xts object are somehow converted to chr.  They should be num which is what they originally were before the conversion.  Here are some data:

full_timestamp             PRICE
2015-01-02 10:02:27.389055  85.4
2015-01-02 10:03:30.926059  85.3
2015-01-02 10:04:52.231750  85.4
2015-01-02 10:05:37.139763  85.5
2015-01-02 10:06:54.926069  85.5
2015-01-02 10:07:57.253187  85.3

Here is the structure of the dataframe:

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   89026 obs. of  2 variables:
 $ full_timestamp: POSIXct, format: "2015-01-02 10:02:27.389055" "2015-01-02 10:03:30.926059" "2015-01-02 10:04:52.231750" ...
 $ PRICE         : num  85.4 85.3 85.4 85.5 85.5 ...

The code that I used to convert the timestamp from a character vector to a POSIXct timestamp:

testing_eq_4xts$full_timestamp <- as.POSIXct(strptime(testing_eq_4xts$full_timestamp,
                                                      format = "%Y-%m-%d:%H:%M:%OS",
                                                      tz = ""))

I have tried to include tz = "", not include the tz part at all, and even Sys.unsetenv("TZ") to stop the conversion picking up the timezone. I should also stress that I need the granularity in the timestamp for what I am modelling.
Here is the code I use to convert to xts:

testing_eq_xts <- as.xts(testing_eq_4xts[, names(testing_eq_4xts) != "full_timestamp"],
                  order.by = testing_eq_4xts$full_timestamp, unique = F)

and this is what the structure looks like:

An ‘xts’ object on 2015-01-02 10:02:27.389055/2015-12-31 14:37:07.969814 containing:
  Data: num [1:89026, 1] 85.4 85.3 85.4 85.5 85.5 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "PRICE"
  Indexed by objects of class: [POSIXct,POSIXt] TZ:
  xts Attributes:
 NULL

also the index of the xts:

[1] "2015-01-02 10:02:27.389055 AEDT" "2015-01-02 10:03:30.926059 AEDT"
[3] "2015-01-02 10:04:52.231750 AEDT" "2015-01-02 10:05:37.139763 AEDT"

Leaving the timestamp as a character vector and trying to convert it to POSIXct when converting to xts also does not work, using:

testing_eq_xts2 = xts(testing_eq_4xts[, 2], as.POSIXct(testing_eq_4xts[, 1]))

gives this error:

Error in as.POSIXct.default(testing_eq_4xts[, 1]) :
  do not know how to convert 'testing_eq_4xts[, 1]' to class “POSIXct”

Am I on the right track as to why PRICE has been converted to chr in the xts object, and if so, how do I fix it?  If I am incorrect in my assumptions, then what is it that I need to do to fix this? Thanks.

Body:
You have already figured out that the 'tz' value is sometimes "", but if you look at ?strptime you will see that using tz="" is really saying to use your current timezone which will get pulled from your system settings. You should instead use tz="GMT" (assuming that UTC/UCT is what you mean when you say "no time zone".) There's really no way to have "no time zone", since time is always measured in some time  zone or another.

AND ... you cannot have a POSIXct column in an xts (or zoo) object (and probably not a character value either, since you would generally expect an xts object to hold numeric values). That is because xts and zoo objects are actually R matrices and they cannot hold columns with attributes. Since POSIXct objects are actually doubles (seconds since origin) with a class attribute of 'POSIXct', they cannot be elements in the xts or zoo matrices. ( They can be xts INDEXes, because there are different rules for that part of the structure.)

 myxts <- as.xts(read.csv.zoo(text="full_timestamp,             PRICE
 2015-01-02 10:02:27.389055,  85.4
 2015-01-02 10:03:30.926059,  85.3
 2015-01-02 10:04:52.231750,  85.4
 2015-01-02 10:05:37.139763,  85.5
 2015-01-02 10:06:54.926069,  85.5
 2015-01-02 10:07:57.253187,  85.3", sep=",", index=1, tz="GMT"))
 myxts
#-----------------
                    [,1]
2015-01-02 10:02:27 85.4
2015-01-02 10:03:30 85.3
2015-01-02 10:04:52 85.4
2015-01-02 10:05:37 85.5
2015-01-02 10:06:54 85.5
2015-01-02 10:07:57 85.3
Warning message:
timezone of object (GMT) is different than current timezone ().

 dput(myxts)
#-------------
structure(c(85.4, 85.3, 85.4, 85.5, 85.5, 85.3), .Dim = c(6L,
1L), index = structure(c(1420192947.38906, 1420193010.92606,
1420193092.23175, 1420193137.13976, 1420193214.92607, 1420193277.25319
), tzone = "GMT", tclass = c("POSIXct", "POSIXt")), class = c("xts",
"zoo"))

 index(myxts)
 #--------------
[1] "2015-01-02 10:02:27 GMT" "2015-01-02 10:03:30 GMT" "2015-01-02 10:04:52 GMT"
[4] "2015-01-02 10:05:37 GMT" "2015-01-02 10:06:54 GMT" "2015-01-02 10:07:57 GMT"


问:
Why pyspark.sql lower function not accept literal col name and length function do?
Why in the next example the lower function not accept the col name as a literal and the length do?

```<code>import pyspark.sql.functions as func
df = spark.createDataFrame([('Tom', 80)], ["name", "height"])
df.select (df.name, func.length('name')).show()
df.select (df.name, func.lower('name')).show()
</code>```

```
+----+------------+
|name|length(name)|
+----+------------+
| Tom|           3|
+----+------------+

Py4JError: An error occurred while calling z:org.apache.spark.sql.functions.lower. Trace:
py4j.Py4JException: Method lower([class java.lang.String]) does not exist
....
```

In the documentation pyspark.sql.length sais that accept a column as parameter and the pyspark.sql.lower sais same. Why don't accept 'name'?

If I change for

```<code>df.select (df.name, func.lower(func.col('name'))).show()
</code>```

run ok

```
+----+-----------+
|name|lower(name)|
+----+-----------+
| Tom|        tom|
+----+-----------+
```

Can someone explain me why?

thanks in advance.

答:
I had the same issue. While Googling I landed on the issue: https://issues.apache.org/jira/browse/SPARK-22212.

It appears to be a bug (minor) and the workaround seems to be what you actually did.

Hope this helps.

Body:
Why in the next example the lower function not accept the col name as a literal and the length do?

import pyspark.sql.functions as func
df = spark.createDataFrame([('Tom', 80)], ["name", "height"])
df.select (df.name, func.length('name')).show()
df.select (df.name, func.lower('name')).show()

+----+------------+
|name|length(name)|
+----+------------+
| Tom|           3|
+----+------------+

Py4JError: An error occurred while calling z:org.apache.spark.sql.functions.lower. Trace:
py4j.Py4JException: Method lower([class java.lang.String]) does not exist
....

In the documentation pyspark.sql.length sais that accept a column as parameter and the pyspark.sql.lower sais same. Why don't accept 'name'?

If I change for

df.select (df.name, func.lower(func.col('name'))).show()

run ok

+----+-----------+
|name|lower(name)|
+----+-----------+
| Tom|        tom|
+----+-----------+

Can someone explain me why?

thanks in advance.


问:
CDC for multiple Consumers of same table where each consumer reads different set of Columns
I have a table (let's say Employee) with around 130 Columns depicting different attributes/characteristics of an Employee record. Now I have multiple downstream systems who need data as file (batch process) which runs periodically (every 12 hrs or 1 day).

Each consumer is intrested in certain column values only and not the entire set of emoployee record.
E.g. Consumer 1 : Needs Column 1, 2, 5, 10, 15, 100, 121, 130
Consumer 2 : Needs 3, 4, 15, 125, 126

And so on. There are currently 10-12 different consumers who need different set of columns.

Intrestingly each consumber is intrested only in DELTA information which is based on columns which that consumer is intrested in.
E.g. So Consumer 1 should get get DELTA ONLY IF there are changes in Column 1, 2, 5, 10, 15, 100, 121, 130.

Are there any CDC or any other tools which help us to achieve this requirement ?

PS : Following solutions were thought and being planned. Not sure which one to pick  :

Maintain previous-day (historic) data table for Employee and then use Minus ('-') operator in Oracle to capture difference. E.g. (Select Col 1, Col2, Col5, Col10.. from current-day-employee) - (Select Col 1, Col2, Col5, Col10.. from previous-day-employee).

This option was not considered because (1) data in current-day-employee table keeps on changing in real-time from source and (2) Will have to create table for each downstream consumer.

Please suggest a tool or solution.

答:
The IBM IDR product has "KCOP" (Kafka Custom Operation Processor) feature.  It allows you to define any number of records to write to Kafka in response to a DML event.  Thus off a single CDC event you could write to different topics customized data for each application, which need only read its respective topic then.

In addition there are KCOP's which provide before and after values, you could thus programatically determine when to write out the record based on whether there was a change between the before and after columns of interest.  So Each resulting topic could then only contain an entry if there was an applicable column change in it.

https://www.ibm.com/support/knowledgecenter/en/SSTRGZ_11.4.0/com.ibm.cdcdoc.cdckafka.doc/concepts/kafkakcop.html

There are other potential means of achieving some of your objectives, but this is an example of one way the IBM product IDR, could meet your objective.


问:
Find and Replace text in Eclipse
I am using eclipse IDE.I need to modify thousands of hbm.xml file by replacing the text generate="always" to generate="never". Please tell  me the easiest way.

答: Click on the "Search" button, click on the "File Search" tab, set the filename to hbm.xml, set the text to generate="always" and click on the "Replace" button at the bottom. When it's search for all matches, it'll offer you another dialog to say what to replace it with.

Title: Find and Replace text in Eclipse


问:
How do I properly test the char[ ] fields in my custom object for nulls, blanks, or empty? and Why do char[ ] indicate a length of 11?
I am researching how to use reflection to initialize a custom object. As an example,
my object has several fields of differing types, however NONE of the fields are of the
String type. I used chararrays instead of strings because I want to clear the objects
out and not worry about immutable Strings being around in the heap should the applictation crash.

In addition, because the class implements CharSequence, the static fields
buff, offset, and count are required. Also worth mentioning, the getters and setters are
synchronized since this object will be used in a multi-threaded environment. Finally,
there is a custom list of Person objects called People which lives in its own People.java file and
is a customized collection of Person objects. Additional details about the object are elided for brevity.

The question is, how do I test for empty, blank, or null fields in my Person object? In my main class,
I want to test for null, empty, or blank before inserting said object into a backend database. I have
tried creating both a Person.isNull() and a similar Person.hasNull() function to test for empty values
in the char[] fields, but the results are ABSOLUTELY NOT what I expected. The println statemnt inside
the test for isCharArray revealed some THINGS I CURRENTLY DO NOT UNDERSTAND.....

Here is some sample output:

Size of byte: 1 bytes.
Size of short: 2 bytes.
Size of int: 4 bytes.
Size of long: 8 bytes.
Size of char: 2 bytes.
Size of float: 4 bytes.
Size of double: 8 bytes.
buff: char[] 11
personID: char[] 11
personTitle: char[] 11
personFirstName: char[] 11
personLastName: char[] 11
```

<p>which was created using the following System.out.println statement:</p>

<pre class="lang-java prettyprint-override"><code>System.out.println(f.getName() + ": " + f.getType().getCanonicalName() + " " +  String.valueOf(value).length());
</code>```

and raises 2 questions:

Why 11?!!!!!

How do I properly test for blank, empty, or zero-length fields?!!!

Please help....

public class Person  implements Serializable,
                                Comparable<Person>,
                                CharSequence,
                                Cloneable   { // the object to model

    //  Fields 0, 1, and 2 are required to implement CharSequence
    //  http://www.java2s.com/Tutorial/Java/0040__Data-Type/implementsCharSequence.htm
    private  static char[] buff = {'\0'};   // No static fields are ever                    // Field 0
    private  static int offset  = 0;        // written to file. Their values                // Field 1
    private  static int count   = 0;        // must be reconstructed.                       // Field 2

    // default serialVersion id
    private static final long serialVersionUID = 7891011129876814235L;                      // Field 3
    private final static LocalDateTime rightNow = LocalDateTime.now();

    private long   localSerialVersionUID= serialVersionUID;  //1st field written to file    // Field 4
    private LocalDateTime personCreatedDateTime= rightNow;                                  // Field 5
    private LocalDateTime  personLastUpdate    =  rightNow; // (YYYY-MM-DD)                 // Field 6
    private char[] personID              = {'\0'}; // (PK)  possibly int auto increment     // Field 7
    private char[] personTitle           = {'\0'};                                          // Field 8
    private char[] personFirstName       = {'\0'};                                          // Field 9
    private char[] personLastName        = {'\0'};                                          // Field 10
    private LocalDate   personDOB        =  LocalDate.parse("1010-10-10"); // (YYYY-MM-DD)  // Field 11

    public Person(
            final long serialUID,                           //4
            final LocalDateTime createdDateTime,            //5
            final LocalDateTime lastUpdate,                 //6
            final char[] id,                                //7
            final char[] title,                             //8
            final char[] firstName,                         //9
            final char[] lastName,                          //10
            final LocalDate   DOB                           //11
    ) {
        this.localSerialVersionUID(serialUID);           //4
        this.personCreatedDateTime(LocalDateTime.now()); //5
        this.personLastUpdate(lastUpdate);               //6
        this.personID(id);                               //7
        this.personTitle(title);                         //8
        this.personFirstName(firstName);                 //9
        this.personLastName(lastName);                   //10
        this.personDOB(DOB);                             //11
    }

    public boolean hasNull() {
        Field fields[] = this.getClass().getDeclaredFields();

        for (Field f : fields) {
            f.setAccessible(true);

            try{
                    Object value = f.get(this);
                    if ( value == null) {return true; } // default condition

                    boolean isCharArray =  f.getType().getCanonicalName().equals("char[]" );

                    // No need to check fields that are not char[]
                    if (( isCharArray) ) {

    // ************* this compiles and executes (doesn't crash), but it doesn't produce intended results *********

                        System.out.println(f.getName() + ": " + f.getType().getCanonicalName() + " " +  String.valueOf(value).length());

                        if ( String.valueOf(value).length() == 0)  {return true;}
                        if ( String.valueOf(value).isEmpty())      {return true;}
                        if ( String.valueOf(value).isBlank())      {return true;}
                        if ( String.valueOf(value).equals('\0'))   {return true;}

                    }

    // ************* this compiles and executes (doesn't crash), but it doesn't produce intended results *********

                } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return false;
        }
    }

    //enter code here

    /**
     * @param args
     */
    public static void main(String[] args)  {
        People<Person> people = new People()<>; //customized list of person objects
        People<Person> people2 = new People()<>; //customized list of person objects

        Person thomas = new Person().personFirstName("Thomas".toCharArray());
                // all other char array fields = {'\0'}
        people.add(thomas);

        Person sybil =  new Person().personFirstName("Sybil".toCharArray());
                // all other char array fields = {'\0'}
        people2.add(sybil);

        if (!thomas.hasNull() ){    // ******* currently this test fails and a Person gets inserted to the People list
            People.insertPerson(thomas);
        }
        if (!sybil.hasNull() ){     // ******* currently this test fails and a Person gets inserted to the People list
            People.insertPerson(sybil);
        }
    }
}
```

答: String.valueOf().length() returns 11 because that is the number of digits/characters in the output (i.e. [@936016386 - an address - has 11 characters)</p>

Body:
I am researching how to use reflection to initialize a custom object. As an example,
my object has several fields of differing types, however NONE of the fields are of the
String type. I used chararrays instead of strings because I want to clear the objects
out and not worry about immutable Strings being around in the heap should the applictation crash.

In addition, because the class implements CharSequence, the static fields
buff, offset, and count are required. Also worth mentioning, the getters and setters are
synchronized since this object will be used in a multi-threaded environment. Finally,
there is a custom list of Person objects called People which lives in its own People.java file and
is a customized collection of Person objects. Additional details about the object are elided for brevity.

The question is, how do I test for empty, blank, or null fields in my Person object? In my main class,
I want to test for null, empty, or blank before inserting said object into a backend database. I have
tried creating both a Person.isNull() and a similar Person.hasNull() function to test for empty values
in the char[] fields, but the results are ABSOLUTELY NOT what I expected. The println statemnt inside
the test for isCharArray revealed some THINGS I CURRENTLY DO NOT UNDERSTAND.....

Here is some sample output:

Size of byte: 1 bytes.
Size of short: 2 bytes.
Size of int: 4 bytes.
Size of long: 8 bytes.
Size of char: 2 bytes.
Size of float: 4 bytes.
Size of double: 8 bytes.
buff: char[] 11
personID: char[] 11
personTitle: char[] 11
personFirstName: char[] 11
personLastName: char[] 11

which was created using the following System.out.println statement:

System.out.println(f.getName() + ": " + f.getType().getCanonicalName() + " " +  String.valueOf(value).length());

and raises 2 questions:

Why 11?!!!!!

How do I properly test for blank, empty, or zero-length fields?!!!

Please help....

public class Person  implements Serializable,
                                Comparable<Person>,
                                CharSequence,
                                Cloneable   { // the object to model

    //  Fields 0, 1, and 2 are required to implement CharSequence
    //  http://www.java2s.com/Tutorial/Java/0040__Data-Type/implementsCharSequence.htm
    private  static char[] buff = {'\0'};   // No static fields are ever                    // Field 0
    private  static int offset  = 0;        // written to file. Their values                // Field 1
    private  static int count   = 0;        // must be reconstructed.                       // Field 2

    // default serialVersion id
    private static final long serialVersionUID = 7891011129876814235L;                      // Field 3
    private final static LocalDateTime rightNow = LocalDateTime.now();

    private long   localSerialVersionUID= serialVersionUID;  //1st field written to file    // Field 4
    private LocalDateTime personCreatedDateTime= rightNow;                                  // Field 5
    private LocalDateTime  personLastUpdate    =  rightNow; // (YYYY-MM-DD)                 // Field 6
    private char[] personID              = {'\0'}; // (PK)  possibly int auto increment     // Field 7
    private char[] personTitle           = {'\0'};                                          // Field 8
    private char[] personFirstName       = {'\0'};                                          // Field 9
    private char[] personLastName        = {'\0'};                                          // Field 10
    private LocalDate   personDOB        =  LocalDate.parse("1010-10-10"); // (YYYY-MM-DD)  // Field 11

    public Person(
            final long serialUID,                           //4
            final LocalDateTime createdDateTime,            //5
            final LocalDateTime lastUpdate,                 //6
            final char[] id,                                //7
            final char[] title,                             //8
            final char[] firstName,                         //9
            final char[] lastName,                          //10
            final LocalDate   DOB                           //11
    ) {
        this.localSerialVersionUID(serialUID);           //4
        this.personCreatedDateTime(LocalDateTime.now()); //5
        this.personLastUpdate(lastUpdate);               //6
        this.personID(id);                               //7
        this.personTitle(title);                         //8
        this.personFirstName(firstName);                 //9
        this.personLastName(lastName);                   //10
        this.personDOB(DOB);                             //11
    }

    public boolean hasNull() {
        Field fields[] = this.getClass().getDeclaredFields();

        for (Field f : fields) {
            f.setAccessible(true);

            try{
                    Object value = f.get(this);
                    if ( value == null) {return true; } // default condition

                    boolean isCharArray =  f.getType().getCanonicalName().equals("char[]" );

                    // No need to check fields that are not char[]
                    if (( isCharArray) ) {

    // ************* this compiles and executes (doesn't crash), but it doesn't produce intended results *********

                        System.out.println(f.getName() + ": " + f.getType().getCanonicalName() + " " +  String.valueOf(value).length());

                        if ( String.valueOf(value).length() == 0)  {return true;}
                        if ( String.valueOf(value).isEmpty())      {return true;}
                        if ( String.valueOf(value).isBlank())      {return true;}
                        if ( String.valueOf(value).equals('\0'))   {return true;}

                    }

    // ************* this compiles and executes (doesn't crash), but it doesn't produce intended results *********

                } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return false;
        }
    }

    //enter code here

    /**
     * @param args
     */
    public static void main(String[] args)  {
        People<Person> people = new People()<>; //customized list of person objects
        People<Person> people2 = new People()<>; //customized list of person objects

        Person thomas = new Person().personFirstName("Thomas".toCharArray());
                // all other char array fields = {'\0'}
        people.add(thomas);

        Person sybil =  new Person().personFirstName("Sybil".toCharArray());
                // all other char array fields = {'\0'}
        people2.add(sybil);

        if (!thomas.hasNull() ){    // ******* currently this test fails and a Person gets inserted to the People list
            People.insertPerson(thomas);
        }
        if (!sybil.hasNull() ){     // ******* currently this test fails and a Person gets inserted to the People list
            People.insertPerson(sybil);
        }
    }
}


问:
Clickable prototype contains SVG instead of image
We are developing clickable prototype using Adobe XD. We know that the prototype can be exported as SVG file using the export option. We wanted to know if it is possible to have the clickable prototype which is shared via URL contain SVG instead of a single image. If not directly through XD , does any plugins help in this?</p>

答:
The XD prototype view can't be expressed as plain SVG because it includes animation, interaction, and rendering features that SVG doesn't support. And since XD is tech-stack agnostic, it doesn't try to generate complete production code for you.

There are a number of XD plugins that can export code for several different web frameworks – with varying degrees of fidelity and varying degrees of turnkey production-readiness. You might be interested in plugins like Yotako, Flutter Export, Generate Flutter Code, Fireblade, Component to Vue, or Export as React Component.


问:
While conditional loop in Python
I am writing a simple book recommender function in Python that takes in an answer and recommends a book called "Undoctored". In the code below, when the input is equal to "None", the loop still gives me the last answer of "Interesting read." What is wrong with my while loop?

```<code>def recommend_book():
    current_book = input("What book are you reading currently? ")
    while input != "Undoctored":
      if input == "None":
        return("Go pick up a book!")
      else:
        return(f'"{current_book}" is an interesting read. I also recommend "Undoctored" by Dr. William Davis.')
</code>```

I also tried adding "break" after the first if statement and that still didn't work.

答:
Like others have said, you are calling input but need to call current_book. Try this code:</p>

```<code>def recommend_book():
    current_book = input("What book are you reading currently? ")
    while current_book != "Undoctored":
      if current_book == "None":
        return(print("Go pick up a book!"))
      else:
        return(print(f'"{current_book}" is an interesting read. I also recommend "Undoctored" by Dr. William Davis.'))
</code>```

Title: While conditional loop in Python

Body:
I am writing a simple book recommender function in Python that takes in an answer and recommends a book called "Undoctored". In the code below, when the input is equal to "None", the loop still gives me the last answer of "Interesting read." What is wrong with my while loop?

def recommend_book():
    current_book = input("What book are you reading currently? ")
    while input != "Undoctored":
      if input == "None":
        return("Go pick up a book!")
      else:
        return(f'"{current_book}" is an interesting read. I also recommend "Undoctored" by Dr. William Davis.')

I also tried adding "break" after the first if statement and that still didn't work.

Body:
Like others have said, you are calling input but need to call current_book. Try this code:

def recommend_book():
    current_book = input("What book are you reading currently? ")
    while current_book != "Undoctored":
      if current_book == "None":
        return(print("Go pick up a book!"))
      else:
        return(print(f'"{current_book}" is an interesting read. I also recommend "Undoctored" by Dr. William Davis.'))


问:
animatedPositioned is not animated on Flutter
I need to animate widget and I used AnimatedPositioned. but not animated. just change position without animate

Full Code

```<code>Column(
      children: <Widget>[
        Container(
          height: 50,
            width: width,
            color: Palette.white,
          child: Padding(
            padding: const EdgeInsets.only(left:20.0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  width: 200,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Palette.lightSilver,
                    borderRadius: BorderRadius.all(Radius.circular(20))
                  ),
                  child: Stack(
                    children: <Widget>[
                      AnimatedPositioned(
                        right:check? 0:null,
                          left:check?null: 0,
                          child: InkWell(
                            onTap: (){
                              setState(() =>
                                check = !check
                              );
                            },
                            child: Container(
                              width: 110,
                              height: 40,
                              decoration: BoxDecoration(
                                  color: Palette.darkSilver2,
                                  borderRadius: BorderRadius.all(Radius.circular(20))
                              ),
                            ),
                          ),
                        duration: const Duration(milliseconds: 50000),
                        curve: Curves.bounceOut,
                      )
                    ],
                  ),
                ),
              ],
            ),
          )
        ),
</code>```

答:
You just need to set a distance not equal to null from the right and left sides all the time so the container doesn't Jump, I modified the code a little (try it):

```<code>Column(
      children: <Widget>[
        Container(
            height: 50,
            width: 400,
            color: Colors.green,
            child: Padding(
              padding: const EdgeInsets.only(left: 20.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    width: 300,
                    height: 40,
                    decoration: BoxDecoration(
                        color: Colors.grey,
                        borderRadius:
                            BorderRadius.all(Radius.circular(20))),
                    child: Stack(
                      children: <Widget>[
                        AnimatedPositioned(
                          right: check ? 0 : 200,
                          left: check ? 200 : 0,
                          onEnd: () {
                            print('done');
                          },
                          child: InkWell(
                            onTap: () {
                              setState(() => check = !check);
                            },
                            child: Container(
                              width: 50,
                              height: 40,
                              decoration: BoxDecoration(
                                  color: Colors.black54,
                                  borderRadius: BorderRadius.all(
                                      Radius.circular(20))),
                            ),
                          ),
                          duration: const Duration(milliseconds: 5000),
                          curve: Curves.bounceOut,
                        )
                      ],
                    ),
                  ),
                ],
              ),
            )),
      ],
    ),
</code>```

Body:
I need to animate widget and I used AnimatedPositioned. but not animated. just change position without animate

Full Code

Column(
      children: <Widget>[
        Container(
          height: 50,
            width: width,
            color: Palette.white,
          child: Padding(
            padding: const EdgeInsets.only(left:20.0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  width: 200,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Palette.lightSilver,
                    borderRadius: BorderRadius.all(Radius.circular(20))
                  ),
                  child: Stack(
                    children: <Widget>[
                      AnimatedPositioned(
                        right:check? 0:null,
                          left:check?null: 0,
                          child: InkWell(
                            onTap: (){
                              setState(() =>
                                check = !check
                              );
                            },
                            child: Container(
                              width: 110,
                              height: 40,
                              decoration: BoxDecoration(
                                  color: Palette.darkSilver2,
                                  borderRadius: BorderRadius.all(Radius.circular(20))
                              ),
                            ),
                          ),
                        duration: const Duration(milliseconds: 50000),
                        curve: Curves.bounceOut,
                      )
                    ],
                  ),
                ),
              ],
            ),
          )
        ),

Body:
You just need to set a distance not equal to null from the right and left sides all the time so the container doesn't Jump, I modified the code a little (try it):

Column(
      children: <Widget>[
        Container(
            height: 50,
            width: 400,
            color: Colors.green,
            child: Padding(
              padding: const EdgeInsets.only(left: 20.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    width: 300,
                    height: 40,
                    decoration: BoxDecoration(
                        color: Colors.grey,
                        borderRadius:
                            BorderRadius.all(Radius.circular(20))),
                    child: Stack(
                      children: <Widget>[
                        AnimatedPositioned(
                          right: check ? 0 : 200,
                          left: check ? 200 : 0,
                          onEnd: () {
                            print('done');
                          },
                          child: InkWell(
                            onTap: () {
                              setState(() => check = !check);
                            },
                            child: Container(
                              width: 50,
                              height: 40,
                              decoration: BoxDecoration(
                                  color: Colors.black54,
                                  borderRadius: BorderRadius.all(
                                      Radius.circular(20))),
                            ),
                          ),
                          duration: const Duration(milliseconds: 5000),
                          curve: Curves.bounceOut,
                        )
                      ],
                    ),
                  ),
                ],
              ),
            )),
      ],
    ),


问:
how do I save samples in an array or matrix in R?
I am okay with Python, Numpy but trying R and this seemingly simple operation has me stuck in R.

This is what I have but I get a number of items to replace is not a multiple of replacement length error.

```<code># find sample variance with n
samples <- matrix(0, nrow=num_samples, ncol=samp_size)
for(i in 1:10000){
  temp <- sample(population, samp_size, replace=TRUE)
  samples[i] = temp
}
samples[0]
</code>```

I am not hung up on using matrices, can be an array or vector or list or anything but just some standard ways of doing this because searching online did not give me a quick answer for this basic operation.

答:
The simplest solution is just to initialize samples with your actual samples:

```<code>set.seed(123)
n_samples <- 5
n_obs <- 10
population <- letters

samples <- matrix(sample(population, n_obs*n_samples, replace=TRUE),
                  nrow=n_samples, ncol=n_obs)
</code>```

But to do it the way you've started, you just need to let R know you'd like to put entries into all columns of samples, like this: samples[i,  ].

It's similar to using : syntax in Numpy: array[i, :].

```<code>samples <- matrix(0, nrow=n_samples, ncol=n_obs)

for(i in 1:n_samples){
  temp <- sample(population, n_obs, replace=TRUE)
  samples[i,] = temp
}
</code>```

Either way, the output is the same:

```<code>samples
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "h"  "u"  "k"  "w"  "y"  "b"  "n"  "x"  "o"  "l"
[2,] "y"  "l"  "r"  "o"  "c"  "x"  "g"  "b"  "i"  "y"
[3,] "x"  "s"  "q"  "z"  "r"  "s"  "o"  "p"  "h"  "d"
[4,] "z"  "x"  "r"  "u"  "a"  "m"  "t"  "f"  "i"  "g"
[5,] "d"  "k"  "k"  "j"  "d"  "d"  "g"  "m"  "g"  "w"
</code>```

Body:
I am okay with Python, Numpy but trying R and this seemingly simple operation has me stuck in R.

This is what I have but I get a number of items to replace is not a multiple of replacement length error.

# find sample variance with n
samples <- matrix(0, nrow=num_samples, ncol=samp_size)
for(i in 1:10000){
  temp <- sample(population, samp_size, replace=TRUE)
  samples[i] = temp
}
samples[0]

I am not hung up on using matrices, can be an array or vector or list or anything but just some standard ways of doing this because searching online did not give me a quick answer for this basic operation.

Body:
The simplest solution is just to initialize samples with your actual samples:

set.seed(123)
n_samples <- 5
n_obs <- 10
population <- letters

samples <- matrix(sample(population, n_obs*n_samples, replace=TRUE),
                  nrow=n_samples, ncol=n_obs)

But to do it the way you've started, you just need to let R know you'd like to put entries into all columns of samples, like this: samples[i,  ].

It's similar to using : syntax in Numpy: array[i, :].

samples <- matrix(0, nrow=n_samples, ncol=n_obs)

for(i in 1:n_samples){
  temp <- sample(population, n_obs, replace=TRUE)
  samples[i,] = temp
}

Either way, the output is the same:

samples
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "h"  "u"  "k"  "w"  "y"  "b"  "n"  "x"  "o"  "l"
[2,] "y"  "l"  "r"  "o"  "c"  "x"  "g"  "b"  "i"  "y"
[3,] "x"  "s"  "q"  "z"  "r"  "s"  "o"  "p"  "h"  "d"
[4,] "z"  "x"  "r"  "u"  "a"  "m"  "t"  "f"  "i"  "g"
[5,] "d"  "k"  "k"  "j"  "d"  "d"  "g"  "m"  "g"  "w"


问:
Why the newtype syntax creates a function
I look at this declaration:

```<code>newtype Parser a = Parser { parse :: String -> Maybe (a,String) }
</code>```

Here is what I understand:

1) Parser  is declared as a type with a type parameter a

2) You can instantiate Parser by providing a parser function for example p = Parser  (\s -> Nothing)

What I observed is that suddenly I have a function name parse defined and it is capable of running Parsers.

For example, I can run:

```<code>parse (Parser  (\s -> Nothing)) "my input"
</code>```

and get Nothing as output.

How was this parse function got defined with this specific signature? How does this function "know" to execute the Parser given to it? Hope that someone can clear my confusion.

Thanks!

答:
First, let’s have a look at a parser newtype without record syntax:

newtype Parser' a = Parser' (String -> Maybe (a,String))
```
<p>It should be obvious what this type does: it stores a function <code>String -> Maybe (a,String)</code>. To run this parser, we will need to make a new function:</p>
<pre class="lang-hs prettyprint-override"><code>runParser' :: Parser' a -> String -> Maybe (a,String)
runParser' (Parser' p) i = p i
</code>```

And now we can run parsers like runParser' (Parser' $ \s -> Nothing) "my input".

But now note that, since Haskell functions are curried, we can simply remove the reference to the input i to get:

runParser'' :: Parser' a -> (String -> Maybe (a,String))
runParser'' (Parser' p) = p
```
<p>This function is exactly equivalent to <code>runParser'</code>, but you could think about it differently: instead of applying the parser function to the value explicitly, it simply takes a parser and fetches the parser function from it; however, thanks to currying, <code>runParser''</code> can still be used with two arguments.</p>
<p>Now, let’s go back to back to your original type:</p>
<pre class="lang-hs prettyprint-override"><code>newtype Parser a = Parser { parse :: String -> Maybe (a,String) }
</code>```

The only difference between your type and mine is that your type uses record syntax, although it may be a bit hard to recognise since a newtype can only have one field; this record syntax automatically defines a function parse :: Parser a -> (String -> Maybe (a,String)), which extracts the String -> Maybe (a,String) function from the Parser a. Hopefully the rest should be obvious: thanks to currying, parse can be used with two arguments rather than one, and this simply has the effect of running the function stored within the Parser a. In other words, your definition is exactly equivalent to the following code:

newtype Parser a = Parser (String -> Maybe (a,String))

parse :: Parser a -> (String -> Maybe (a,String))
parse (Parser p) = p
```

Body:
I look at this declaration:

newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

Here is what I understand:

1) Parser  is declared as a type with a type parameter a

2) You can instantiate Parser by providing a parser function for example p = Parser  (\s -> Nothing)

What I observed is that suddenly I have a function name parse defined and it is capable of running Parsers.

For example, I can run:

parse (Parser  (\s -> Nothing)) "my input"

and get Nothing as output.

How was this parse function got defined with this specific signature? How does this function "know" to execute the Parser given to it? Hope that someone can clear my confusion.

Thanks!

Body:
First, let’s have a look at a parser newtype without record syntax:

newtype Parser' a = Parser' (String -> Maybe (a,String))

It should be obvious what this type does: it stores a function String -> Maybe (a,String). To run this parser, we will need to make a new function:

runParser' :: Parser' a -> String -> Maybe (a,String)
runParser' (Parser' p) i = p i

And now we can run parsers like runParser' (Parser' $ \s -> Nothing) "my input".

But now note that, since Haskell functions are curried, we can simply remove the reference to the input i to get:

runParser'' :: Parser' a -> (String -> Maybe (a,String))
runParser'' (Parser' p) = p

This function is exactly equivalent to runParser', but you could think about it differently: instead of applying the parser function to the value explicitly, it simply takes a parser and fetches the parser function from it; however, thanks to currying, runParser'' can still be used with two arguments.

Now, let’s go back to back to your original type:

newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

The only difference between your type and mine is that your type uses record syntax, although it may be a bit hard to recognise since a newtype can only have one field; this record syntax automatically defines a function parse :: Parser a -> (String -> Maybe (a,String)), which extracts the String -> Maybe (a,String) function from the Parser a. Hopefully the rest should be obvious: thanks to currying, parse can be used with two arguments rather than one, and this simply has the effect of running the function stored within the Parser a. In other words, your definition is exactly equivalent to the following code:

newtype Parser a = Parser (String -> Maybe (a,String))

parse :: Parser a -> (String -> Maybe (a,String))
parse (Parser p) = p


问:
Getting the body of a Reddit submission?
I am trying to search for some data by scraping Reddit. I want to get the self-text of the posts in the subreddit, not the title/url. How can I do this? Here's my code that I am using to get the titles, but how can I get the text written in the posts with this title?

reddit = praw.Reddit(client_id=cid,
                     client_secret=secret, password=pass_word,
                     user_agent='mmm', username=user_name)

subreddit = reddit.subreddit('python')
subreddit_hot=subreddit.hot(limit=5)
for submission in subreddit_hot:
    if not submission.stickied:
        print(submission.title)
```

答:
Replace print(submission.title) with print(submission.selftext).

To see other attributes of a Submission object, take a look at the PRAW docs, which has a table of common attributes for the model. PRAW's documentation also features a guide for discovering attributes on any model.


问:
Transform dataframe from request into structured format
I have a request from a website stored in a dataframe with one column that looks like this (each line is a new row):

```<code>request
{"Title":"Birds","Year":"2019","Rated":"R","Runtime":"122 min"}
{"Title":"Chernob","Year":"2019","Rated":"R","Runtime":"111 min"}
{"Title":"Fame","Year":"2019","Rated":"R"}
</code>```

I would like to transform this dataframe into another dataframe like this:

```<code>Title    Year    Rated    Runtime
Birds    2019    R        122 min
Cherno   2019    R        111 min
Fame     2019    R        NaN
</code>```

Is this possible? I have tried with Pandas but cannot find a function to do this.

Thanks!

答:
use ast.literal_eval to parse the strings, then unpack with pd.DataFrame:

```<code>import ast
pd.DataFrame(df['request'].map(ast.literal_eval).tolist())

     Title  Year Rated  Runtime
0    Birds  2019     R  122 min
1  Chernob  2019     R  111 min
2     Fame  2019     R      NaN
</code>```

Body:
I have a request from a website stored in a dataframe with one column that looks like this (each line is a new row):

request
{"Title":"Birds","Year":"2019","Rated":"R","Runtime":"122 min"}
{"Title":"Chernob","Year":"2019","Rated":"R","Runtime":"111 min"}
{"Title":"Fame","Year":"2019","Rated":"R"}

I would like to transform this dataframe into another dataframe like this:

Title    Year    Rated    Runtime
Birds    2019    R        122 min
Cherno   2019    R        111 min
Fame     2019    R        NaN

Is this possible? I have tried with Pandas but cannot find a function to do this.

Thanks!

Body:
use ast.literal_eval to parse the strings, then unpack with pd.DataFrame:

import ast
pd.DataFrame(df['request'].map(ast.literal_eval).tolist())

     Title  Year Rated  Runtime
0    Birds  2019     R  122 min
1  Chernob  2019     R  111 min
2     Fame  2019     R      NaN


问:
Node.js decrypting encrypted string from MySQL causes EVP_DecryptFinal_ex:wrong final block length
I have 2 functions in an encryption service class. 1 to encrypt data, and 1 to decrypt data.

```<code>export default class EncryptionService {

    private static algorithm = 'aes-256-cbc';

    private static key = createHash('sha256').update(String('keyString')).digest('base64').substr(0, 32);
    private static iv = Buffer.from('ivString');

    public static encryptData(data: string): string {
        const cipher = createCipheriv(this.algorithm, this.key, this.iv);
        let encrypted = cipher.update(data);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        const encryptedStr = encrypted.toString('base64');
        console.log('encryptedStr: ' + encryptedStr);
        return encryptedStr;
    }

    public static decryptData(data: string): string {
        const decipher = createDecipheriv(this.algorithm, this.key, this.iv);
        const decrypted = decipher.update(data, 'base64');
        const decryptedData = Buffer.concat([decrypted, decipher.final()]).toString();
        console.log('decryptedData: ' + decryptedData);
        return decryptedData;
    }
}
</code>```

In my controller, when I call the encryptData function then immediately call the decryptData function, passing in the encrypted data returned from the encryptData function, I get the correct unencrypted string back.

```<code>import EncryptionService from '../services/encryption-service';

export default class MyController {
  public async postData(request: Request, response: Response) {

    const encryptedAudioFileName = EncryptionService.encryptData(request.body.audio_file_name);
    EncryptionService.decryptData(encryptedAudioFileName);
  }
}
</code>```

However - when I store the encrypted Data returned from encryptData into mySQL via a post function in the controller and then attempt to decrypt the data retrieved from mySQL via a get function in the controller, an error occurs in the decryptData function stating "EVP_DecryptFinal_ex:wrong final block length".

```<code>  public async postData(request: Request, response: Response) {
    Logger.info(request, response, 'Request Received');

    try {
      if (request.body) {
        const dataEntity = new dataEntity();
        dataEntity.audio_file_name = EncryptionService.encryptData(request.body.audio_file_name);

        const result = await getManager().save<dataEntity>(dataEntity);
        if (result) {
          const responseObject = {
            timestamp: new Date().toUTCString(),
            method: request.method,
            status: 'Success',
            statusCode: 201,
            message: 'successfully created.',
            path: request.originalUrl,
            reference: result.id,
          };
          Logger.success(request, response, responseObject);
          response.status(201).json(responseObject);
        } else {
          response.status(400).json(
            ResponseService.badRequestErrorResponseObject(request, response));
        }
      } else {
        response.status(400).json(
          ResponseService.badRequestErrorResponseObject(request, response, 'Body is invalid'));
      }
    } catch (error) {
      response.status(500).json(
        ResponseService.internalErrorResponseObject(request, response, error));
    }
  }

  public async getData(request: Request, response: Response) {
    Logger.info(request, response, 'Request Received');

    try {
      const allData: dataEntity[] =
        await getConnectionManager().get().getRepository(dataEntity).find();
      if (allData) {
        const entityResponseArray = [] as object[];
        allData.forEach( (entity) => {
          const dataResponse = {} as {id: number, audioFileName: string};
          dataResponse.id = entity.id!;
          dataResponse.audioFileName = EncryptionService.decryptData(entity.audio_file_name!);

          entityResponseArray.push(dataResponse);
        });

        Logger.success(request, response, 'Get list of data');
        response.json(entityResponseArray);
      } else {
        response.status(404).json(
          ResponseService.notFoundErrorResponseObject(request, response));
        return;
      }
    } catch (error) {
      response.status(500).json(
        ResponseService.internalErrorResponseObject(request, response, error));
    }
  }
</code>```

It happens at this line in decryptData:

```<code>const decryptedData = Buffer.concat([decrypted, decipher.final()]).toString();
</code>```

What am I doing incorrectly?

答: The issue was my column length and or type. The encrypt and decrypt code works fine. The data returning from mysql was being cut off so it couldn't decrypt properly. Stupid mistake. Thanks for the insight.</p>

Body:
I have 2 functions in an encryption service class. 1 to encrypt data, and 1 to decrypt data.

export default class EncryptionService {

    private static algorithm = 'aes-256-cbc';

    private static key = createHash('sha256').update(String('keyString')).digest('base64').substr(0, 32);
    private static iv = Buffer.from('ivString');

    public static encryptData(data: string): string {
        const cipher = createCipheriv(this.algorithm, this.key, this.iv);
        let encrypted = cipher.update(data);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        const encryptedStr = encrypted.toString('base64');
        console.log('encryptedStr: ' + encryptedStr);
        return encryptedStr;
    }

    public static decryptData(data: string): string {
        const decipher = createDecipheriv(this.algorithm, this.key, this.iv);
        const decrypted = decipher.update(data, 'base64');
        const decryptedData = Buffer.concat([decrypted, decipher.final()]).toString();
        console.log('decryptedData: ' + decryptedData);
        return decryptedData;
    }
}

In my controller, when I call the encryptData function then immediately call the decryptData function, passing in the encrypted data returned from the encryptData function, I get the correct unencrypted string back.

import EncryptionService from '../services/encryption-service';

export default class MyController {
  public async postData(request: Request, response: Response) {

    const encryptedAudioFileName = EncryptionService.encryptData(request.body.audio_file_name);
    EncryptionService.decryptData(encryptedAudioFileName);
  }
}

However - when I store the encrypted Data returned from encryptData into mySQL via a post function in the controller and then attempt to decrypt the data retrieved from mySQL via a get function in the controller, an error occurs in the decryptData function stating "EVP_DecryptFinal_ex:wrong final block length".

  public async postData(request: Request, response: Response) {
    Logger.info(request, response, 'Request Received');

    try {
      if (request.body) {
        const dataEntity = new dataEntity();
        dataEntity.audio_file_name = EncryptionService.encryptData(request.body.audio_file_name);

        const result = await getManager().save<dataEntity>(dataEntity);
        if (result) {
          const responseObject = {
            timestamp: new Date().toUTCString(),
            method: request.method,
            status: 'Success',
            statusCode: 201,
            message: 'successfully created.',
            path: request.originalUrl,
            reference: result.id,
          };
          Logger.success(request, response, responseObject);
          response.status(201).json(responseObject);
        } else {
          response.status(400).json(
            ResponseService.badRequestErrorResponseObject(request, response));
        }
      } else {
        response.status(400).json(
          ResponseService.badRequestErrorResponseObject(request, response, 'Body is invalid'));
      }
    } catch (error) {
      response.status(500).json(
        ResponseService.internalErrorResponseObject(request, response, error));
    }
  }

  public async getData(request: Request, response: Response) {
    Logger.info(request, response, 'Request Received');

    try {
      const allData: dataEntity[] =
        await getConnectionManager().get().getRepository(dataEntity).find();
      if (allData) {
        const entityResponseArray = [] as object[];
        allData.forEach( (entity) => {
          const dataResponse = {} as {id: number, audioFileName: string};
          dataResponse.id = entity.id!;
          dataResponse.audioFileName = EncryptionService.decryptData(entity.audio_file_name!);

          entityResponseArray.push(dataResponse);
        });

        Logger.success(request, response, 'Get list of data');
        response.json(entityResponseArray);
      } else {
        response.status(404).json(
          ResponseService.notFoundErrorResponseObject(request, response));
        return;
      }
    } catch (error) {
      response.status(500).json(
        ResponseService.internalErrorResponseObject(request, response, error));
    }
  }

It happens at this line in decryptData:

const decryptedData = Buffer.concat([decrypted, decipher.final()]).toString();

What am I doing incorrectly?


问:
Kotlin map() reuse the same value
I have the following method

```<code>    val dateFormat = SimpleDateFormat("yyyy-MM-dd")
    fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")
        return lines.map { l -> Pair(dateFormat.parse(l.split(" ")[0]), l.split(" ")[1]) }
    }
</code>```

where  l.split(" ") is called twice.

How to write in a smarter way in functional programming style ?

PS 1: I 'm curious for a solution with fold if possible

PS 2 : For readability, the original version was written as

```<code> fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")

        var results = mutableListOf<Pair<Date, String>>()
        for (line in lines) {
            val content = line.split(" ")
            val date: Date = dateFormat.parse(content[0])
            val firstName = content[1]
            results.add(Pair(date,firstName))
        }
        return results
    }
</code>```

答:
This is a bit simpler. I don't see a way to use fold without making it way more convoluted.

```<code>val dateFormat = SimpleDateFormat("yyyy-MM-dd")
fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> =
    paragraph.split("\n")
        .map {
            with(it.split(" ")) { dateFormat.parse(this[0]) to this[1] }
        }
</code>```

Title: Kotlin map() reuse the same value

Body:
I have the following method

    val dateFormat = SimpleDateFormat("yyyy-MM-dd")
    fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")
        return lines.map { l -> Pair(dateFormat.parse(l.split(" ")[0]), l.split(" ")[1]) }
    }

where  l.split(" ") is called twice.

How to write in a smarter way in functional programming style ?

PS 1: I 'm curious for a solution with fold if possible

PS 2 : For readability, the original version was written as

 fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")

        var results = mutableListOf<Pair<Date, String>>()
        for (line in lines) {
            val content = line.split(" ")
            val date: Date = dateFormat.parse(content[0])
            val firstName = content[1]
            results.add(Pair(date,firstName))
        }
        return results
    }

Body:
This is a bit simpler. I don't see a way to use fold without making it way more convoluted.

val dateFormat = SimpleDateFormat("yyyy-MM-dd")
fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> =
    paragraph.split("\n")
        .map {
            with(it.split(" ")) { dateFormat.parse(this[0]) to this[1] }
        }


问:
ASP.NET Setup Project - how to include static files not in VS?
I am working on an ASP.NET MVC web application, and am working on the Web Setup portion. We are using SVN for version control. One of the issues is that the we are currently having is that the web designers modify and add a lot of html, css and js files that end up in the Content folders, but they don't add them to the VS project, so the new files don't get included in the installer.

One option is that we have to try to teach them to always go into VS and manually add the files, but we're on a large project and it's getting down to crunch time, so trying to get people to learn something new in a technology that they don't know will result in too many mistakes, so I'd like to work around that if possible.

Is there some way to get the setup project just to include files from a folder on the file system, instead of a project's designated content files?

Thanks!

答:
Unfortunately I don't think there is an out of the box way to do this, as projects maintains references to the files individually.

You could achieve what you need via a custom macro, or asking your other team to edit the .csproj XML file (perhaps simpler or riskier, depending on their background).

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: MattH


问:
Problem with Rails page caching and automatic extensions
I have a JSON and XML based API that needs to be page cached. I have setup my routes on the api to include the format as part of the URL, such that URL's like this work:

```<code>http://example.com/foo/1/bar/2/xml
http://example.com/foo/1/bar/2/json
</code>```

The problem I am seeing is that in the server's public folder, the files are being saved as xml.xml and json.json, and this causes cache misses the next time the URL is accessed.

Is there a way to either:

Turn off the auto extension generation so that they are saved without an extension at all? (EX: RAILS_ROOT/public/foo/1/bar/2/json)

Force all the extensions to be .html for every call. (EX: RAILS_ROOT/public/foo/1/bar/2/json.html)

Either of these would cause my server to return the cached file instead of a miss. How can I do this?

EDIT:

Somebody asked for the relevant route:

```<code>scope '(foo/:foo_id)', :foo_id => /\d+/ do
  get '/bar/:bar_id/:format' => 'bars#show', :bar_id => /\d+/, :format => /json|xml|html/
end
</code>```

SOLUTION:

While I was looking for an official way to make this happen using the built in page caching support, I ended up just using an after filter and my own page cache method, as suggested by Anton

```<code># application_controller.rb
def cache_api_page
  if REDACTEDServer::Application.config.action_controller.perform_caching
    self.class.cache_page(response.body, request.path, '')
    puts "CACHED PATH: #{request.path}"
  end
end

# bar_controller.rb
 after_filter :cache_api_page, :only => [ :show, :index ]
</code>```

答:
You can do that like this:

```<code>class FooController < ApplicationController

  after_filter(:only => :show, :if => Proc.new { |c| c.request.format.json? }) do |controller|
    controller.class.cache_page(controller.response.body, controller.request.path, '.html')
  end

end
</code>```

When http://example.com/foo/1/bar/2/json is accessed, it will write page to cache (RAILS_ROOT/public/foo/1/bar/2/json.html)

And if you get http://example.com/foo/1/bar/2/json again, you receive RAILS_ROOT/public/foo/1/bar/2/json.html, but your http server(Apache?) should know about content type of this files.

Otherwise content type will set to 'text/html'

UPDATE

To you .htaccess

```<code><FilesMatch "\/json$">
<IfModule mod_headers.c>
  Header set Content-Type "text/json"
</IfModule>
</FilesMatch>

<FilesMatch "\/xml$">
<IfModule mod_headers.c>
  Header set Content-Type "text/xml"
</IfModule>
</FilesMatch>
</code>```

Body:
I have a JSON and XML based API that needs to be page cached. I have setup my routes on the api to include the format as part of the URL, such that URL's like this work:

http://example.com/foo/1/bar/2/xml
http://example.com/foo/1/bar/2/json

The problem I am seeing is that in the server's public folder, the files are being saved as xml.xml and json.json, and this causes cache misses the next time the URL is accessed.

Is there a way to either:

Turn off the auto extension generation so that they are saved without an extension at all? (EX: RAILS_ROOT/public/foo/1/bar/2/json)

Force all the extensions to be .html for every call. (EX: RAILS_ROOT/public/foo/1/bar/2/json.html)

Either of these would cause my server to return the cached file instead of a miss. How can I do this?

EDIT:

Somebody asked for the relevant route:

scope '(foo/:foo_id)', :foo_id => /\d+/ do
  get '/bar/:bar_id/:format' => 'bars#show', :bar_id => /\d+/, :format => /json|xml|html/
end

SOLUTION:

While I was looking for an official way to make this happen using the built in page caching support, I ended up just using an after filter and my own page cache method, as suggested by Anton

# application_controller.rb
def cache_api_page
  if REDACTEDServer::Application.config.action_controller.perform_caching
    self.class.cache_page(response.body, request.path, '')
    puts "CACHED PATH: #{request.path}"
  end
end

# bar_controller.rb
 after_filter :cache_api_page, :only => [ :show, :index ]

Body:
You can do that like this:

class FooController < ApplicationController

  after_filter(:only => :show, :if => Proc.new { |c| c.request.format.json? }) do |controller|
    controller.class.cache_page(controller.response.body, controller.request.path, '.html')
  end

end

When http://example.com/foo/1/bar/2/json is accessed, it will write page to cache (RAILS_ROOT/public/foo/1/bar/2/json.html)

And if you get http://example.com/foo/1/bar/2/json again, you receive RAILS_ROOT/public/foo/1/bar/2/json.html, but your http server(Apache?) should know about content type of this files.

Otherwise content type will set to 'text/html'

UPDATE

To you .htaccess

<FilesMatch "\/json$">
<IfModule mod_headers.c>
  Header set Content-Type "text/json"
</IfModule>
</FilesMatch>

<FilesMatch "\/xml$">
<IfModule mod_headers.c>
  Header set Content-Type "text/xml"
</IfModule>
</FilesMatch>


问:
Data Export in Essbase
I took data Export of a database and the export should be saved in the according app or essbase server. The problem here is I am unable to find the extracted data. Somewhere they must have been stored. Since I could execute those calculations but when opening in loadrules I cannot find them </p>

答:
If you used a Rule File and was successful, then the data is already stored in the cube.

To retrieve the data you must use smartview or a predefined web form.

Title: Data Export in Essbase


问:
How to correctly add characters to a C String in C Language?
Currently I am coding a program that can go through a text file and analyze each character. If a character is alphanumeric and a valid identifier, I want to be able to add that character into a string.
My current code to do so is this:

```<code>char final[256]={'\0'};
unsigned int len = 0;
static int current = ' ';
static int temp = ' ';

if(isalpha(current)){
   final[0]=current;
   len = 1;
   for (temp = fgetc(file); isalnum(temp) || temp == '_';){
      for(int i = len; i <= len; i++){
      final[i] = temp;
      len++;
  }
}

final[len] = '\0';
</code>```

Am I correct to approach this problem the current way? Can you add characters to index positions of strings in C?

答:
The code itself is simple.

```<code>char final[256];
unsigned int len = 0;

final[len] = fgetc(file); //we read the character but do not "approve" it.
//while (!isalpha(final[len])) final[len] = fgetc(file); //uncomment if you want to read the file until a valid identifier begins. Also it's barely an example: it lacks EOF check.

if(isalpha(final[len])){
   len = 1; //We "approve" the first character
   while ( isalnum( final[len] = fgetc(file) ) || final[len] == '_') //In C, conditions are checked left to right so if isalnum()==0 we check for '_' with correctly updated final[len] value.
      len++; //We "approve" the next character;
  }
}

final[len] = 0; //The last character has been read but not "approved" so we overwrite it with null-term.
</code>```

About the second question... yes, you can add a character to an indexed position. But it must be either last position or it'll overwrite an existing one. If you want to insert some characters, use memmove() function first.

Body:
Currently I am coding a program that can go through a text file and analyze each character. If a character is alphanumeric and a valid identifier, I want to be able to add that character into a string.
My current code to do so is this:

char final[256]={'\0'};
unsigned int len = 0;
static int current = ' ';
static int temp = ' ';

if(isalpha(current)){
   final[0]=current;
   len = 1;
   for (temp = fgetc(file); isalnum(temp) || temp == '_';){
      for(int i = len; i <= len; i++){
      final[i] = temp;
      len++;
  }
}

final[len] = '\0';

Am I correct to approach this problem the current way? Can you add characters to index positions of strings in C?

Body:
The code itself is simple.

char final[256];
unsigned int len = 0;

final[len] = fgetc(file); //we read the character but do not "approve" it.
//while (!isalpha(final[len])) final[len] = fgetc(file); //uncomment if you want to read the file until a valid identifier begins. Also it's barely an example: it lacks EOF check.

if(isalpha(final[len])){
   len = 1; //We "approve" the first character
   while ( isalnum( final[len] = fgetc(file) ) || final[len] == '_') //In C, conditions are checked left to right so if isalnum()==0 we check for '_' with correctly updated final[len] value.
      len++; //We "approve" the next character;
  }
}

final[len] = 0; //The last character has been read but not "approved" so we overwrite it with null-term.

About the second question... yes, you can add a character to an indexed position. But it must be either last position or it'll overwrite an existing one. If you want to insert some characters, use memmove() function first.


问:
Server Socket Programming can't find file
In this program I am trying to develop a web server that handles one HTTP request at a time. The web server should accept and parse the HTTP request, get the requested ﬁle from the server’s ﬁle system, create an HTTP response message consisting of the requested ﬁle preceded by header lines, and then send the response directly to the client. If the requested ﬁle is not present in the server, the server should return an HTTP 404 “Not Found” msg.

Here is the code I attempted to make it work:

```<code>#import socket module
from socket import *
serverPort = 6789
import sys #In order to terminate the program

serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a server socket on a particular port
# Fill in code to set up the port
serverSocket.bind(('',serverPort))
serverSocket.listen(1)

while True:
    # Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept() # Fill in code to get a connection
    try:
        message = connectionSocket.recv(1024)#Fill in code to read GET request
        filename = message.split()[1]
        # Fill in security code
        f = open(filename)
        outputdata = f.read()# Fill in code to read data from the file
        # Send http HEADER LINE (s) into socket
        #Fill in code to send header(s)
        # Send the content of the requested file to the client
        print(outputdata)
        connectionSocket.send('\nHTTP/1.1 200 OK\n\n')
        connectionSocket.send(outputdata)
        for i in range(0, len(outputdata)):
          connectionSocket.send(outputdata[i].encode())
        connectionSocket.send("\r\n".encode())
        connectionSocket.close()
    except IOError:
        #Send response message for file not found
        #Fill in
        print ("404 Page Not Found")
        connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
        #Close client socket
        # Fill in
        connectionSocket.close
serverSocket.close()
sys.exit()
</code>```

Then I try to access a file called HelloWorld.html by typing localhost:6789/HelloWorld.html in a browser address bar to make the program work, but I get this error:

```<code>Ready to serve...
404 Page Not Found
Traceback (most recent call last):
  File "C:/Users/jcdos/Desktop/CS436/hw2.py", line 21, in <module>
    f = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: b'/HelloWorld.html'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/jcdos/Desktop/CS436/hw2.py", line 37, in <module>
    connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
TypeError: a bytes-like object is required, not 'str'
</code>```

I am getting the 404 not found error, but I the HTML file is in the same directory as my python file. The HelloWorld.html is in the same desktop folder as the python file. In addition, when typing the localhost into the web browser, the browser pops up with this:

答:
If the file exists in the directory then it could be to do with the wrong file name.
I see that in the file name it's checking for '/HelloWorld.html' whereas, it should be 'HelloWorld.html'.

So simply update in your code to exclude the leading forward slash.

```<code>filename = message.split()[1]
</code>```

To

```<code>file= message.split()[1]
filename = file[1:]
</code>```

Body:
In this program I am trying to develop a web server that handles one HTTP request at a time. The web server should accept and parse the HTTP request, get the requested ﬁle from the server’s ﬁle system, create an HTTP response message consisting of the requested ﬁle preceded by header lines, and then send the response directly to the client. If the requested ﬁle is not present in the server, the server should return an HTTP 404 “Not Found” msg.

Here is the code I attempted to make it work:

#import socket module
from socket import *
serverPort = 6789
import sys #In order to terminate the program

serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a server socket on a particular port
# Fill in code to set up the port
serverSocket.bind(('',serverPort))
serverSocket.listen(1)

while True:
    # Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept() # Fill in code to get a connection
    try:
        message = connectionSocket.recv(1024)#Fill in code to read GET request
        filename = message.split()[1]
        # Fill in security code
        f = open(filename)
        outputdata = f.read()# Fill in code to read data from the file
        # Send http HEADER LINE (s) into socket
        #Fill in code to send header(s)
        # Send the content of the requested file to the client
        print(outputdata)
        connectionSocket.send('\nHTTP/1.1 200 OK\n\n')
        connectionSocket.send(outputdata)
        for i in range(0, len(outputdata)):
          connectionSocket.send(outputdata[i].encode())
        connectionSocket.send("\r\n".encode())
        connectionSocket.close()
    except IOError:
        #Send response message for file not found
        #Fill in
        print ("404 Page Not Found")
        connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
        #Close client socket
        # Fill in
        connectionSocket.close
serverSocket.close()
sys.exit()

Then I try to access a file called HelloWorld.html by typing localhost:6789/HelloWorld.html in a browser address bar to make the program work, but I get this error:

Ready to serve...
404 Page Not Found
Traceback (most recent call last):
  File "C:/Users/jcdos/Desktop/CS436/hw2.py", line 21, in <module>
    f = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: b'/HelloWorld.html'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/jcdos/Desktop/CS436/hw2.py", line 37, in <module>
    connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
TypeError: a bytes-like object is required, not 'str'

I am getting the 404 not found error, but I the HTML file is in the same directory as my python file. The HelloWorld.html is in the same desktop folder as the python file. In addition, when typing the localhost into the web browser, the browser pops up with this:

Body:
If the file exists in the directory then it could be to do with the wrong file name.
I see that in the file name it's checking for '/HelloWorld.html' whereas, it should be 'HelloWorld.html'.

So simply update in your code to exclude the leading forward slash.

filename = message.split()[1]

To

file= message.split()[1]
filename = file[1:]