问:
WCF 4 REST service can't return a StatusDescription, only StatusCode
I'm currently migrating my WCF RESTful service from .NET 3.5 (Starter Kit) to .NET 4. I started my project using a WCF Rest service template from Visual Studio 2010.
I had to figure out how to keep my authorization scheme (formely done with RequestInterceptor) using ServiceAuthorizationManager. After some work and researching I got it done.
But now I have a collateral problem. My service used to feedback my client of any processing errors using HTTP status code and a brief description. I was using WebOperationContext at many points of my service method to describe to clients what went wrong, like this:

```<code>protected void returnCode(HttpStatusCode code, string description)
{
    WebOperationContext ctx = WebOperationContext.Current;
    ctx.OutgoingResponse.StatusDescription = description;
    ctx.OutgoingResponse.StatusCode = code;
}
</code>```

But in WCF 4, only StatusCode works - StatusDescription silently fails. I can't figure out why.
My only guess is that WebOperationContext doesn't work in this new WCF 4 scenario, and I should be using OperationContext instead, but that also doesn't work. The following method is used in my custom class extending ServiceAuthorizationManager, informing clients a request couldn't be access because auth digest was malformed:

```<code>private void GenerateBadDigestMessage(ref OperationContext operationContext)
{
    Message reply = Message.CreateMessage(MessageVersion.None, null, null, new DataContractJsonSerializer(typeof(object)));

    HttpResponseMessageProperty hrp = new HttpResponseMessageProperty();
    hrp.StatusCode = HttpStatusCode.Forbidden;
    hrp.StatusDescription = "bad digest";
    reply.Properties[HttpResponseMessageProperty.Name] = hrp;

    operationContext.RequestContext.Reply(reply);
    operationContext.RequestContext = null;
}
</code>```

Even by using OperationContext direclty here (insted of WebOperationContext), StatusDescription doesn't work.

What I'm missing here? Why such a small thing can break from .NET 3.5 to 4?

答:
One potential problem is that you are setting the RequestContext to null:

```<code>operationContext.RequestContext.Reply(reply);
operationContext.RequestContext = null;
</code>```

Another possibility is that the parameter "description" is not set.

Also on the client side are you checking:

```<code>WebOperationContext.Current.IncomingResponse.StatusDescription
</code>```

One more possibility, could the values have been overwritten after returnCode was called?

Body:
I'm currently migrating my WCF RESTful service from .NET 3.5 (Starter Kit) to .NET 4. I started my project using a WCF Rest service template from Visual Studio 2010.
I had to figure out how to keep my authorization scheme (formely done with RequestInterceptor) using ServiceAuthorizationManager. After some work and researching I got it done.
But now I have a collateral problem. My service used to feedback my client of any processing errors using HTTP status code and a brief description. I was using WebOperationContext at many points of my service method to describe to clients what went wrong, like this:

protected void returnCode(HttpStatusCode code, string description)
{
    WebOperationContext ctx = WebOperationContext.Current;
    ctx.OutgoingResponse.StatusDescription = description;
    ctx.OutgoingResponse.StatusCode = code;
}

But in WCF 4, only StatusCode works - StatusDescription silently fails. I can't figure out why.
My only guess is that WebOperationContext doesn't work in this new WCF 4 scenario, and I should be using OperationContext instead, but that also doesn't work. The following method is used in my custom class extending ServiceAuthorizationManager, informing clients a request couldn't be access because auth digest was malformed:

private void GenerateBadDigestMessage(ref OperationContext operationContext)
{
    Message reply = Message.CreateMessage(MessageVersion.None, null, null, new DataContractJsonSerializer(typeof(object)));

    HttpResponseMessageProperty hrp = new HttpResponseMessageProperty();
    hrp.StatusCode = HttpStatusCode.Forbidden;
    hrp.StatusDescription = "bad digest";
    reply.Properties[HttpResponseMessageProperty.Name] = hrp;

    operationContext.RequestContext.Reply(reply);
    operationContext.RequestContext = null;
}

Even by using OperationContext direclty here (insted of WebOperationContext), StatusDescription doesn't work.

What I'm missing here? Why such a small thing can break from .NET 3.5 to 4?

Body:
One potential problem is that you are setting the RequestContext to null:

operationContext.RequestContext.Reply(reply);
operationContext.RequestContext = null;

Another possibility is that the parameter "description" is not set.

Also on the client side are you checking:

WebOperationContext.Current.IncomingResponse.StatusDescription

One more possibility, could the values have been overwritten after returnCode was called?


来源: stackexchange

问:
Akka Streams - jump over FlowShape
I have the following Graph.

At the inflateFlow stage, I check if there is already a request processed in DB. If there is already a processed message, I want to return MsgSuccess and not a RequestProcess, but the next FlowShape won't accept that, it needs a RequestProcess. Is there a way to jump from flowInflate to flowWrap without adding Either everywhere?

GraphDSL.create() { implicit builder: GraphDSL.Builder[NotUsed] =>
  import GraphDSL.Implicits._

  val flowInflate = builder.add(wrapFunctionInFlowShape[MsgRequest, RequestProcess](inflateFlow))
  val flowProcess = builder.add(wrapFunctionInFlowShape[RequestProcess, SuccessProcess](convertFlow))
  val flowWrite = builder.add(wrapFunctionInFlowShape[SuccessProcess, SuccessProcess](writeFlow))
  val flowWrap = builder.add(wrapFunctionInFlowShape[SuccessProcess, MsgSuccess](wrapFlow))

  flowInflate ~> flowProcess ~> flowWrite ~> flowWrap

  FlowShape(flowInflate.in, flowWrap.out)
}

def wrapFunctionInFlowShape[Input, Output](f: Input => Output): Flow[Input, Output, NotUsed] = {
  Flow.fromFunction { input =>
    f(input)
  }
}

//check for cache
def inflateFlow(msgRequest: MsgRequest): Either[RequestProcess, MsgSuccess] = {
  val hash: String = hashMethod(msgRequest)
  if(existisInDataBase(hash))
    Right(MsgSuccess(hash))
  else
    Left(inflate(msgRequest))
}

def convertFlow(requestPorocess: RequestPocess): SuccessProcess = {}//process the request}
def writeFlow(successProcess: SuccessProcess): SuccessProcess = {}//write to DB}
def wrapFlow(successProcess: SuccessProcess): MsgSuccess = {}//wrap and return the message}
```

答:
You can define alternative paths in a stream with a partition. In your case, the PartitionWith stage in the Akka Stream Contrib project could be helpful. Unlike the Partition stage in the standard Akka Streams API, PartitionWith allows the output types to be different: in your case, the output types are RequestProcess and MsgSuccess.

First, to use PartitionWith, add the following dependency to your build.sbt:

```<code>libraryDependencies += "com.typesafe.akka" %% "akka-stream-contrib" % "0.8"
</code>```

Second, replace inflateFlow with the partition:

```<code>def split = PartitionWith[MsgRequest, RequestProcess, MsgSuccess] { msgRequest =>
  val hash = hashMethod(msgRequest)
  if (!existisInDataBase(hash))
    Left(inflate(msgRequest))
  else
    Right(MsgSuccess(hash))
}
</code>```

Then incorporate that stage into your graph:

```<code>val flow = Flow.fromGraph(GraphDSL.create() { implicit builder: GraphDSL.Builder[NotUsed] =>
  import GraphDSL.Implicits._

  val pw = builder.add(split)
  val flowProcess = builder.add(wrapFunctionInFlowShape[RequestProcess, SuccessProcess](convertFlow))
  val flowWrite = builder.add(wrapFunctionInFlowShape[SuccessProcess, SuccessProcess](writeFlow))
  val flowWrap = builder.add(wrapFunctionInFlowShape[SuccessProcess, MsgSuccess](wrapFlow))

  val mrg = builder.add(Merge[MsgSuccess](2))

  pw.out0 ~> flowProcess ~> flowWrite ~> flowWrap ~> mrg.in(0)
  pw.out1 ~> mrg.in(1)

  FlowShape(pw.in, mrg.out)
})
</code>```

If an incoming MsgRequest is not found in the database and is converted to a RequestProcess, then that message goes through your original flow path. If an incoming MsgRequest is in the database and resolves to a MsgSuccess, then it bypasses the intermediate steps in the flow. In both cases, the resulting MsgSuccess messages are merged from the two alternative paths into one flow outlet.

ContentLicense: CC BY-SA 3.0

Title: Akka Streams - jump over FlowShape

Body:
You can define alternative paths in a stream with a partition. In your case, the PartitionWith stage in the Akka Stream Contrib project could be helpful. Unlike the Partition stage in the standard Akka Streams API, PartitionWith allows the output types to be different: in your case, the output types are RequestProcess and MsgSuccess.

First, to use PartitionWith, add the following dependency to your build.sbt:

libraryDependencies += "com.typesafe.akka" %% "akka-stream-contrib" % "0.8"

Second, replace inflateFlow with the partition:

def split = PartitionWith[MsgRequest, RequestProcess, MsgSuccess] { msgRequest =>
  val hash = hashMethod(msgRequest)
  if (!existisInDataBase(hash))
    Left(inflate(msgRequest))
  else
    Right(MsgSuccess(hash))
}

Then incorporate that stage into your graph:

val flow = Flow.fromGraph(GraphDSL.create() { implicit builder: GraphDSL.Builder[NotUsed] =>
  import GraphDSL.Implicits._

  val pw = builder.add(split)
  val flowProcess = builder.add(wrapFunctionInFlowShape[RequestProcess, SuccessProcess](convertFlow))
  val flowWrite = builder.add(wrapFunctionInFlowShape[SuccessProcess, SuccessProcess](writeFlow))
  val flowWrap = builder.add(wrapFunctionInFlowShape[SuccessProcess, MsgSuccess](wrapFlow))

  val mrg = builder.add(Merge[MsgSuccess](2))

  pw.out0 ~> flowProcess ~> flowWrite ~> flowWrap ~> mrg.in(0)
  pw.out1 ~> mrg.in(1)

  FlowShape(pw.in, mrg.out)
})

If an incoming MsgRequest is not found in the database and is converted to a RequestProcess, then that message goes through your original flow path. If an incoming MsgRequest is in the database and resolves to a MsgSuccess, then it bypasses the intermediate steps in the flow. In both cases, the resulting MsgSuccess messages are merged from the two alternative paths into one flow outlet.


问:
How to test if the first three characters in a string are letters or numbers in r?
The example of the dataset I have is given below, note that I have more than two columns in the total dataset.

```<code>ID   X
1   MJF34
2   GA249D
3   DEW235R
4   4SDFR3
5   DAS3
</code>```

I want to test whether the first three characters in X are letters, if they are then I want to replace that value to show only the first three letters. If the first three characters aren't letters then I want to replace those values with "FR". Hence the result would be as follows.

```<code>ID    X
1    MJF
2    FR
3    DEW
4    FR
5    DAS
</code>```

Currently X is a character data type.

Thanks in advance for any help.

答:
I would try:

```<code>x <- substr(dt$X, 1, 3)
dt$X <- ifelse(grepl('[0-9]', x), 'FR', x)
dt
#   ID   X
# 1  1 MJF
# 2  2  FR
# 3  3 DEW
# 4  4  FR
# 5  5 DAS
</code>```

The data:

```<code>structure(list(ID = 1:5, X = c("MJF34", "GA249D", "DEW235R",
"4SDFR3", "DAS3")), .Names = c("ID", "X"), class = "data.frame",
row.names = c(NA,
-5L))
</code>```

Body:
The example of the dataset I have is given below, note that I have more than two columns in the total dataset.

ID   X
1   MJF34
2   GA249D
3   DEW235R
4   4SDFR3
5   DAS3

I want to test whether the first three characters in X are letters, if they are then I want to replace that value to show only the first three letters. If the first three characters aren't letters then I want to replace those values with "FR". Hence the result would be as follows.

ID    X
1    MJF
2    FR
3    DEW
4    FR
5    DAS

Currently X is a character data type.

Thanks in advance for any help.

Body:
I would try:

x <- substr(dt$X, 1, 3)
dt$X <- ifelse(grepl('[0-9]', x), 'FR', x)
dt
#   ID   X
# 1  1 MJF
# 2  2  FR
# 3  3 DEW
# 4  4  FR
# 5  5 DAS

The data:

structure(list(ID = 1:5, X = c("MJF34", "GA249D", "DEW235R",
"4SDFR3", "DAS3")), .Names = c("ID", "X"), class = "data.frame",
row.names = c(NA,
-5L))


问:
How can I deserialize an array of objects in Symfony Serializer?
Is is possible in Symfony Serializer to deserialize an array of objects in a property? I have a Boss class with the $Npc = [] property that needs to hold a array of Npc objects. I did see some examples in the documentation, but they do not state this feature.  I have a json string with an array of NPC's For example:

```<code>class Boss {

    private $Npc = [];

    /**
    * @return Npc[]
    */
    public function getNpcs(): array
    {
        return $this->npcs;
    }
}
</code>```

I am using php7.1 and symfony/serializer version ^3.3.

Edit:
I already tried PhpDocExtractor, but it would not let me install it. :(

Edit:
This is a possible JSON value:

```<code>{
    "bossname": "Epic boss!",
    "npcs": [{
        "id": 24723,
        "name": "Selin Fireheart",
        "urlSlug": "selin-fireheart",
        "creatureDisplayId": 22642
    }]
}
</code>```

答:
I found a way to do this :). I installed the Symfony PropertyAccess package through Composer. With this package, you can add adders, removers and hassers. This way Symfony Serializer will automaticly fill the array with the correct objects.
Example:

```<code>private $npcs = [];

public function addNpc(Npc $npc): void
{
    $this->npcs[] = $npc;
}

public function hasNpcs(): bool
{
    return count($this->npcs) > 0
}
</code>```

etc.

This way you can use the ObjectNormalizer with:

```<code>$normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
</code>```

Edit: At least since v3.4 you have to create a remover method as well. Otherwise it just won't work (no error or warning).

Body:
Is is possible in Symfony Serializer to deserialize an array of objects in a property? I have a Boss class with the $Npc = [] property that needs to hold a array of Npc objects. I did see some examples in the documentation, but they do not state this feature.  I have a json string with an array of NPC's For example:

class Boss {

    private $Npc = [];

    /**
    * @return Npc[]
    */
    public function getNpcs(): array
    {
        return $this->npcs;
    }
}

I am using php7.1 and symfony/serializer version ^3.3.

Edit:
I already tried PhpDocExtractor, but it would not let me install it. :(

Edit:
This is a possible JSON value:

{
    "bossname": "Epic boss!",
    "npcs": [{
        "id": 24723,
        "name": "Selin Fireheart",
        "urlSlug": "selin-fireheart",
        "creatureDisplayId": 22642
    }]
}

Body:
I found a way to do this :). I installed the Symfony PropertyAccess package through Composer. With this package, you can add adders, removers and hassers. This way Symfony Serializer will automaticly fill the array with the correct objects.
Example:

private $npcs = [];

public function addNpc(Npc $npc): void
{
    $this->npcs[] = $npc;
}

public function hasNpcs(): bool
{
    return count($this->npcs) > 0
}

etc.

This way you can use the ObjectNormalizer with:

$normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());

Edit: At least since v3.4 you have to create a remover method as well. Otherwise it just won't work (no error or warning).

ContentLicense: CC BY-SA 4.0


问:
How to configure iOs UITextViews and UILabels so that their height is determined by their content
I am basically trying to find the correct way to design a UITableViewCell that has two UITextViews and three UILabels inside it. The two UITextViews have dynamic content and their size cannot be determined until runtime.

I have tried various methods of recalculating the height of my UITextViews based on the content that is loaded in them at runtime, and though very laborious and inane, I have gotten that to work, but they then bleed over the UILabels positioned in the xib below them.

Do I really have to recalculate the y coordinates of every UILabel after calculating the new size of the UITextViews? Is there a way to simply have the elements in the xib 'push' the elements below them down based on their new size?

What is the correct approach to configuring a UITableViewCell with multiple dynamic text views so that my entire application is not comprised of code to calculate heights and coordinates?

Or is the answer that I should not be putting more than one dynamic UITextView in the same UITableViewCell ?

答:
I found it useful to add this sort of behavior as a category on UIView so a view can resize one of its subviews to fit some arbitrary text, and optionally resize the parent view to fit the newly enlarged subview as needed.

http://blog.carbonfive.com/2009/07/10/resizing-uilabel-to-fit-text/

ContentLicense: CC BY-SA 2.5


问:
Ionic2 - Base64 PDF
I am currently developing a mobile project using Cordova and Ionic2 using an external database resource that connects to the mobile via REST webServices.

The database has documents pdf saved that you have to send to the mobile and view the same. I am using the pdf in enconding Base64 through the webservices by Json.

I can get the string in base64, but I do not quite understand how to decode it and save it on mobile, which is Android to be able to see it.

答:
Use the native File component from Ionic 2.

ionic cordova plugin add cordova-plugin-file

npm install --save @ionic-native/file

To save the base64 string on the device you call the createFile(path, fileName, replace) method.

More info: Ionic 2 File

Title: Ionic2 - Base64 PDF


答:
You can use standard base R commands

```<code># Your data, dt$X in your case
x = c("MJF34", "GA249D", "DEW235R", "4SDFR3", "DAS3")
</code>```

First use substr to extract characters 1 to 3

```<code>sub_str = substr(x, 1, 3)
</code>```

Then test for a number

```<code>has_numbers = grep("[0-9]", sub_str)
</code>```

Then replace

```<code>sub_str[has_numbers] = "FR"
</code>```

Title: How to test if the first three characters in a string are letters or numbers in r?

Body:
You can use standard base R commands

# Your data, dt$X in your case
x = c("MJF34", "GA249D", "DEW235R", "4SDFR3", "DAS3")

First use substr to extract characters 1 to 3

sub_str = substr(x, 1, 3)

Then test for a number

has_numbers = grep("[0-9]", sub_str)

Then replace

sub_str[has_numbers] = "FR"


问:
Java 8 Interface vs Abstract Class
I went through this question:
Interface with default methods vs Abstract class in Java 8

The following part is not clear to me:

The constraint on the default method is that it can be implemented
  only in the terms of calls to other interface methods, with no
  reference to a particular implementation's state. So the main use case
  is higher-level and convenience methods.

I tried creating objects of a concrete class (implementation) inside default method and invoked its instance method, it is working fine. i.e, I don't need to use Interface type as reference to the object.

Then what is meant by the quoted paragraph.

答:
That sentence means that a default method is implemented inside an interface, so it doesn't have any access to a real state of an object but just to what the interface itself exposes, since an interface can't declare instance variables.

For example:

```<code>abstract class Foo {
 int result;
 int getResult() { return result; }
}
</code>```

This can't be done in an interface because you can't have any member variable. The only thing you can do is to combine multiple interface methods, which is what it is specified as convenience / higher-level methods, eg:

```<code>interface Foo {
  void preProcess();
  void process();
  void postProcess();

  default void processAll() {
    preProcess();
    process();
    postProcess();
  }
}
</code>```

Title: Java 8 Interface vs Abstract Class

Body:
That sentence means that a default method is implemented inside an interface, so it doesn't have any access to a real state of an object but just to what the interface itself exposes, since an interface can't declare instance variables.

For example:

abstract class Foo {
 int result;
 int getResult() { return result; }
}

This can't be done in an interface because you can't have any member variable. The only thing you can do is to combine multiple interface methods, which is what it is specified as convenience / higher-level methods, eg:

interface Foo {
  void preProcess();
  void process();
  void postProcess();

  default void processAll() {
    preProcess();
    process();
    postProcess();
  }
}


问:
Row to string with space between items
I have this:

```<code>| col1 | col2 | col 3 |
|    5 |   FA |   OFF |
|  107 |   FA |    ON |
|   96 |   FO |    ON |
</code>```

and I want to MsgBox each row like that

```<code>Dim str As String
Dim r As Long

r = 2
While Celles(r,1).Value <> ""
    str = Rows(r)                    ' don't know how get row with space between items
    MsgBox str
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec("""C:\mypath\prog.exe"" " & str)

    r = r+1
Wend
</code>```

I want 3 MsgBox to appear  5 FA OFF 107 FA ON 96 FO ON.

Therefore, how to get a row properly and add space between items ?

(After i want to call WshShellExec with parameters)

答:
Try the code below to combine the Strings per row:

```<code>Option Explicit

Sub CombStringinRow()

Dim str As String
Dim r As Long, Col As Long
Dim LastCol As Long
Dim LastRow As Long

LastRow = Cells(Rows.Count, "A").End(xlUp).Row ' get last row with data from column "A"

For r = 2 To LastRow
    LastCol = Cells(r, Columns.Count).End(xlToLeft).Column ' get last column in current row

    For Col = 1 To LastCol
        If str <> "" Then
            str = str & " " & Cells(r, Col)
        Else
            str = Cells(r, Col)
        End If
    Next Col

    MsgBox str
    str = ""
Next r

End Sub
</code>```

Title: Row to string with space between items

Body:
I have this:

| col1 | col2 | col 3 |
|    5 |   FA |   OFF |
|  107 |   FA |    ON |
|   96 |   FO |    ON |

and I want to MsgBox each row like that

Dim str As String
Dim r As Long

r = 2
While Celles(r,1).Value <> ""
    str = Rows(r)                    ' don't know how get row with space between items
    MsgBox str
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec("""C:\mypath\prog.exe"" " & str)

    r = r+1
Wend

I want 3 MsgBox to appear  5 FA OFF 107 FA ON 96 FO ON.

Therefore, how to get a row properly and add space between items ?

(After i want to call WshShellExec with parameters)

Body:
Try the code below to combine the Strings per row:

Option Explicit

Sub CombStringinRow()

Dim str As String
Dim r As Long, Col As Long
Dim LastCol As Long
Dim LastRow As Long

LastRow = Cells(Rows.Count, "A").End(xlUp).Row ' get last row with data from column "A"

For r = 2 To LastRow
    LastCol = Cells(r, Columns.Count).End(xlToLeft).Column ' get last column in current row

    For Col = 1 To LastCol
        If str <> "" Then
            str = str & " " & Cells(r, Col)
        Else
            str = Cells(r, Col)
        End If
    Next Col

    MsgBox str
    str = ""
Next r

End Sub


问:
Import data from transaction CKIS
Does anybody have any knowledge of how to extract data from SAP system through VBA?

I would like to extract data from eg. CKIS (product costing).

It would be helpful with any kind of code, that would connect me to SAP system.

答:
You should have a look at SAP Gui Scripting. Check the link VBA pulling data from SAP for dummies for some useful information.

SAP Gui Scripting can be used with VBA to pull data from the SAP System

Title: Import data from transaction CKIS


问:
python - write row by row tuples inside a list
My issue is to write what is in my file, row by row in my function.

Here's my code:

```<code>def read_operators_file(file_name):
"""Read a file with operators into a collection.

Requires: file_name, str with the name of a text file with a list of operators.
Ensures: list, with the operators in the file; each operators is a tuple with the various element
concerning that operator, in the order provided in the file.
"""
inputFile1 = open("operators14h55.txt",'r+')
import constants
for i in range(constants.HEADER_TOTAL_LINES):  # read some lines to skip the header
    inputFile1.readline()
operators = []
for line in inputFile1:
    name, language, domain, last_hour, total_minutes = line.strip().split(', ')
    operators.append((name, language, domain, last_hour, total_minutes))
inputFile1.close()
return operators
</code>```

that return's all in a row, and I want each tuple in a single row.

```<code>[('Henry Miller', 'english', 'laptops', 'premium', 3), ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]
</code>```

I want something similar to this:

```<code>[('Henry Miller', 'english', 'laptops', 'premium', 3),
 ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6),
 ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]
</code>```

答:
Sample: this writes each tuple in separate lines to xyz.txt

```<code>l=[('Henry Miller', 'english', 'laptops', 'premium', 3), ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

with open('xyz.txt', 'w') as f:
    for x in l:
        f.write(str(x) + "\n")
</code>```

Body:
My issue is to write what is in my file, row by row in my function.

Here's my code:

def read_operators_file(file_name):
"""Read a file with operators into a collection.

Requires: file_name, str with the name of a text file with a list of operators.
Ensures: list, with the operators in the file; each operators is a tuple with the various element
concerning that operator, in the order provided in the file.
"""
inputFile1 = open("operators14h55.txt",'r+')
import constants
for i in range(constants.HEADER_TOTAL_LINES):  # read some lines to skip the header
    inputFile1.readline()
operators = []
for line in inputFile1:
    name, language, domain, last_hour, total_minutes = line.strip().split(', ')
    operators.append((name, language, domain, last_hour, total_minutes))
inputFile1.close()
return operators

that return's all in a row, and I want each tuple in a single row.

[('Henry Miller', 'english', 'laptops', 'premium', 3), ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

I want something similar to this:

[('Henry Miller', 'english', 'laptops', 'premium', 3),
 ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6),
 ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

Body:
Sample: this writes each tuple in separate lines to xyz.txt

l=[('Henry Miller', 'english', 'laptops', 'premium', 3), ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

with open('xyz.txt', 'w') as f:
    for x in l:
        f.write(str(x) + "\n")


答:
I think all you need to do is: </p>

```<code>list_of_tuples = [(1,2),(4,5),(5,6)]
with open("out.txt") as new_file:
    new_file.write("\n".join( str(tuple) for tuple in list_of_tuples)
</code>```

Title: python - write row by row tuples inside a list

Body:
I think all you need to do is:

list_of_tuples = [(1,2),(4,5),(5,6)]
with open("out.txt") as new_file:
    new_file.write("\n".join( str(tuple) for tuple in list_of_tuples)


问:
In an Aurelia Dialog, how to create routes for the viewModel?
When opening an Aurelia Dialog you usually pass it a viewModel.

This is how I'm currently doing this but it would be better if the path wasn't hard-coded here.

```<code>            let lookupResponse = await this.dialogService.open(
            {
                model:
                {
                    configuration: this.LookupConfiguration
                    caption: 'Select an item'
                },
                viewModel: 'App/Components/Lookup/LookupDialog'
            });
</code>```

I'd rather be able to reference the viewModel path like a route

```<code>            let lookupResponse = await this.dialogService.open(
            {
                model:
                {
                    configuration: this.LookupConfiguration
                    caption: 'Select an item'
                },
                viewModel: App.routes.components.lookupdialog
            });
</code>```

If you just add a Routes.js for the components and try to use it you get this error:

Uncaught (in promise) Error: Cannot determine default view strategy
  for object.

So what needs to be added for this to work? A custom view strategy of some kind?

答:
You can import the dialogs into your class and use them like this:

```<code>import { LookupDialog } from "app/components/lookup/lookup-dialog.ts";

export class Foo {
  bar() {
    let lookupResponse = await this.dialogService.open(
       {
         model:
         {
           configuration: this.LookupConfiguration
           caption: 'Select an item'
         },
         viewModel: LookupDialog
       });
  }
}
</code>```

Body:
When opening an Aurelia Dialog you usually pass it a viewModel.

This is how I'm currently doing this but it would be better if the path wasn't hard-coded here.

            let lookupResponse = await this.dialogService.open(
            {
                model:
                {
                    configuration: this.LookupConfiguration
                    caption: 'Select an item'
                },
                viewModel: 'App/Components/Lookup/LookupDialog'
            });

I'd rather be able to reference the viewModel path like a route

            let lookupResponse = await this.dialogService.open(
            {
                model:
                {
                    configuration: this.LookupConfiguration
                    caption: 'Select an item'
                },
                viewModel: App.routes.components.lookupdialog
            });

If you just add a Routes.js for the components and try to use it you get this error:

Uncaught (in promise) Error: Cannot determine default view strategy
  for object.

So what needs to be added for this to work? A custom view strategy of some kind?

Body:
You can import the dialogs into your class and use them like this:

import { LookupDialog } from "app/components/lookup/lookup-dialog.ts";

export class Foo {
  bar() {
    let lookupResponse = await this.dialogService.open(
       {
         model:
         {
           configuration: this.LookupConfiguration
           caption: 'Select an item'
         },
         viewModel: LookupDialog
       });
  }
}


答:
You can use pprint.

```<code>from pprint import pprint

operators = [('Henry Miller', 'english', 'laptops', 'premium', 3), ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]
pprint(source)

# results
[('Henry Miller', 'english', 'laptops', 'premium', 3),
 ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6),
 ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]
</code>```

Body:
You can use pprint.

from pprint import pprint

operators = [('Henry Miller', 'english', 'laptops', 'premium', 3), ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]
pprint(source)

# results
[('Henry Miller', 'english', 'laptops', 'premium', 3),
 ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6),
 ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]


问:
applicationDidBecomeActive runs after ViewController loaded
I'm using socket.io to use the real-time mechanism. Problem that I'm facing right now is that Socket.io's object created after the viewController is loaded

I'm using Singleton design

```<code>import SocketIO

class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    var socket: SocketIOClient!

    func establishConnection() {
       socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
       socket.connect()

    }

    func closeConnection() {
        socket.disconnect()
    }

}
</code>```

I need to set the socket in the establishConnection no matter what to make sure that user has establish the connection to the server together with the token. If I follow Vlad's answer, the connection will be never be established because the token is empty before hand thus user won't get connected.

User logs in

```<code>func logIn() {
   // Getting it from alamofire
   keychain["token"] = token
   //then only establish connection
   SocketIOManager.sharedInstance.establishConnection()
}
</code>```

If I use Init method then the socket will be nil because in the applicationDidBecomeActive there's the SocketIOManager.sharedInstance.establishConnection(), so the logic is whenever user loads up the app the applicationDidBecomeActive will run

so technically I'm using sharedInstance to run the socket.io object.

```<code>func applicationDidBecomeActive(_ application: UIApplication) {
        SocketIOManager.sharedInstance.establishConnection()
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }
</code>```

Right now the socket object in the didBecomeActive runs after the view loaded

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    listeningOnMerchant()

}

func listeningOnMerchant() {
   // I got error around here
   SocketIOManager.sharedInstance.socket.on("listening") { ack, data in
      print("something")

   }
  }
}
</code>```

Which will crash because socket is nil. How do I make the viewController not crash. I could use the let method to stop the crash

```<code>if let socket = SocketIOManager.sharedInstance.socket {

}
</code>```

But it will be nil if I use socket and socket won't be running. How do I not make the socket not crash?

Because i really need to put the socket.connect on applicationDidBecomeActive to make it consistent as in the connection vs didLaunch

Thanks!

答:
As I understand, your problem is in setting SocketIOClient at the establishConnection func. If it crashes with nil, probably your constructor returns nil here:

```<code>SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
</code>```

I don't see a reason also to do this inside this func. It's easy to make a mistake and leave socket var uninitialised at some point. I would rather make it let and set it inside of constructor, something like this:

```<code>import SocketIO

class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    let socket: SocketIOClient!

    init() {
        super.init()
        socket = YourFixedConstructorHere()
    }
}
</code>```

If you want to make sure it's initialised, you can also make it lazy var, like this:

```<code>lazy var socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
</code>```

Body:
I'm using socket.io to use the real-time mechanism. Problem that I'm facing right now is that Socket.io's object created after the viewController is loaded

I'm using Singleton design

import SocketIO

class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    var socket: SocketIOClient!

    func establishConnection() {
       socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])
       socket.connect()

    }

    func closeConnection() {
        socket.disconnect()
    }

}

I need to set the socket in the establishConnection no matter what to make sure that user has establish the connection to the server together with the token. If I follow Vlad's answer, the connection will be never be established because the token is empty before hand thus user won't get connected.

User logs in

func logIn() {
   // Getting it from alamofire
   keychain["token"] = token
   //then only establish connection
   SocketIOManager.sharedInstance.establishConnection()
}

If I use Init method then the socket will be nil because in the applicationDidBecomeActive there's the SocketIOManager.sharedInstance.establishConnection(), so the logic is whenever user loads up the app the applicationDidBecomeActive will run

so technically I'm using sharedInstance to run the socket.io object.

func applicationDidBecomeActive(_ application: UIApplication) {
        SocketIOManager.sharedInstance.establishConnection()
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

Right now the socket object in the didBecomeActive runs after the view loaded

override func viewDidLoad() {
    super.viewDidLoad()
    listeningOnMerchant()

}

func listeningOnMerchant() {
   // I got error around here
   SocketIOManager.sharedInstance.socket.on("listening") { ack, data in
      print("something")

   }
  }
}

Which will crash because socket is nil. How do I make the viewController not crash. I could use the let method to stop the crash

if let socket = SocketIOManager.sharedInstance.socket {

}

But it will be nil if I use socket and socket won't be running. How do I not make the socket not crash?

Because i really need to put the socket.connect on applicationDidBecomeActive to make it consistent as in the connection vs didLaunch

Thanks!

Body:
As I understand, your problem is in setting SocketIOClient at the establishConnection func. If it crashes with nil, probably your constructor returns nil here:

SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])

I don't see a reason also to do this inside this func. It's easy to make a mistake and leave socket var uninitialised at some point. I would rather make it let and set it inside of constructor, something like this:

import SocketIO

class SocketIOManager: NSObject {

    static let sharedInstance = SocketIOManager()

    let socket: SocketIOClient!

    init() {
        super.init()
        socket = YourFixedConstructorHere()
    }
}

If you want to make sure it's initialised, you can also make it lazy var, like this:

lazy var socket = SocketIOClient(socketURL: URL(string: mainURL)!, config: [.log(false), .compress, .connectParams(["token": "asdasdasdsa"])])


问:
Converting {integer} to f32 in Rust
I want to convert a value from {integer} to f32:

```<code>struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}
</code>```

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

```<code>for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}
</code>```

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

```<code>for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}
</code>```

But with my usecase this turns into:

```<code>for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}
</code>```

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

答:
It is not necessary to specify the i32s when using as, since this works fine (playground):

```<code>for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo = Vector3 { // no need to specify the type of foo
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // etc.
        }
    }
}
</code>```

As Klitos Kyriacou's answer observes, there is no such type as {integer}; the compiler gives that error message because it couldn't infer a concrete type for x. It doesn't actually matter, because there are no implicit conversions from integer types to floating-point types in Rust, or from integer types to other integer types, for that matter. In fact, Rust is quite short on implicit conversions of any sort (the most notable exception being Deref coercions).

Casting the type with as permits the compiler to reconcile the type mismatch, and it will eventually fill in {integer} with i32 (unconstrained integer literals always default to i32, not that the concrete type matters in this case).

Another option you may prefer, especially if you use x, y and z for other purposes in the loop, is to shadow them with f32 versions instead of creating new names:

```<code>for x in -5..5 {
    let x = x as f32;
    for y in -5..5 {
        let y = y as f32;
        for z in -5..5 {
            let z = z as f32;
            let foo = Vector3 { x, y, z };
            // etc.
        }
    }
}
</code>```

(You don't have to write x: x, y: y, z: z -- Rust does the right thing when the variable name is the same as the struct member name.)

Another option (last one, I promise) is to convert the iterators instead using map:

```<code>for x in (-5..5).map(|x| x as f32) {
    for y in (-5..5).map(|y| y as f32) {
        for z in (-5..5).map(|z| z as f32) {
            let foo = Vector3 { x, y, z };
            // etc.
        }
    }
}
</code>```

However it is a little more dense and may be harder to read than the previous version.

Title: Converting {integer} to f32 in Rust

Body:
I want to convert a value from {integer} to f32:

struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}

But with my usecase this turns into:

for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

Body:
It is not necessary to specify the i32s when using as, since this works fine (playground):

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo = Vector3 { // no need to specify the type of foo
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // etc.
        }
    }
}

As Klitos Kyriacou's answer observes, there is no such type as {integer}; the compiler gives that error message because it couldn't infer a concrete type for x. It doesn't actually matter, because there are no implicit conversions from integer types to floating-point types in Rust, or from integer types to other integer types, for that matter. In fact, Rust is quite short on implicit conversions of any sort (the most notable exception being Deref coercions).

Casting the type with as permits the compiler to reconcile the type mismatch, and it will eventually fill in {integer} with i32 (unconstrained integer literals always default to i32, not that the concrete type matters in this case).

Another option you may prefer, especially if you use x, y and z for other purposes in the loop, is to shadow them with f32 versions instead of creating new names:

for x in -5..5 {
    let x = x as f32;
    for y in -5..5 {
        let y = y as f32;
        for z in -5..5 {
            let z = z as f32;
            let foo = Vector3 { x, y, z };
            // etc.
        }
    }
}

(You don't have to write x: x, y: y, z: z -- Rust does the right thing when the variable name is the same as the struct member name.)

Another option (last one, I promise) is to convert the iterators instead using map:

for x in (-5..5).map(|x| x as f32) {
    for y in (-5..5).map(|y| y as f32) {
        for z in (-5..5).map(|z| z as f32) {
            let foo = Vector3 { x, y, z };
            // etc.
        }
    }
}

However it is a little more dense and may be harder to read than the previous version.


问:
Generating random transition probability matrix python
I was wondering whether there is an easy way to generate a square matrix filled with random numbers in python, given some conditions:

the rows have to sum up to 1.

the values on the diagonal should be significantly higher than the
other values.

This is a stochastic matrix, and generating one is possible, however the tricky part is the condition about the diagonal.
e.g. for a 4x4 matrix the output should look something like this:

```<code>[[0.90, 0.03, 0.03, 0.04],
[0.01, 0.98, 0.005, 0.005],
[0.04, 0.01, 0.92, 0.03],
[0.00, 0.02, 0.03, 0.95]]
</code>```

Are there good ways to generate such matrix for a variable size?

答:
Here's a method with numpy.identity, starting with a k x k identity matrix, adding a drift term to it, and then normalizing.

```<code>import numpy as np

k = 4
result = np.identity(4)

# Add a random drift term.  We can guarantee that the diagonal terms
#     will be larger by specifying a `high` parameter that is < 1.
# How much larger depends on that term.  Here, it is 0.25.
result = result + np.random.uniform(low=0., high=.25, size=(k, k))

# Lastly, divide by row-wise sum to normalize to 1.
result = result / result.sum(axis=1, keepdims=1)

# Check
print(result)
print(result.sum(axis=1))

# [[ 0.80736896  0.00663004  0.06474194  0.12125906]
#  [ 0.03545472  0.79746194  0.10495657  0.06212678]
#  [ 0.08566011  0.02632533  0.79709851  0.09091605]
#  [ 0.07298408  0.05698381  0.1585878   0.71144431]]
#
# [ 1.  1.  1.  1.]
</code>```

The above condensed to two lines:

```<code>result = np.identity(k) + np.random.uniform(low=0., high=.25, size=(k, k))
result /= result.sum(axis=1, keepdims=1)
</code>```

Specifying a larger high parameter will get you a smaller ratio of "diagonals to the rest":

```<code>result = np.identity(k) + np.random.uniform(low=0., high=.60, size=(k, k))
result /= result.sum(axis=1, keepdims=1)
print(result.round(2))
# [[ 0.53  0.02  0.25  0.2 ]
#  [ 0.05  0.58  0.19  0.18]
#  [ 0.02  0.04  0.72  0.22]
#  [ 0.07  0.23  0.08  0.62]]
</code>```

Body:
I was wondering whether there is an easy way to generate a square matrix filled with random numbers in python, given some conditions:

the rows have to sum up to 1.

the values on the diagonal should be significantly higher than the
other values.

This is a stochastic matrix, and generating one is possible, however the tricky part is the condition about the diagonal.
e.g. for a 4x4 matrix the output should look something like this:

[[0.90, 0.03, 0.03, 0.04],
[0.01, 0.98, 0.005, 0.005],
[0.04, 0.01, 0.92, 0.03],
[0.00, 0.02, 0.03, 0.95]]

Are there good ways to generate such matrix for a variable size?

Body:
Here's a method with numpy.identity, starting with a k x k identity matrix, adding a drift term to it, and then normalizing.

import numpy as np

k = 4
result = np.identity(4)

# Add a random drift term.  We can guarantee that the diagonal terms
#     will be larger by specifying a `high` parameter that is < 1.
# How much larger depends on that term.  Here, it is 0.25.
result = result + np.random.uniform(low=0., high=.25, size=(k, k))

# Lastly, divide by row-wise sum to normalize to 1.
result = result / result.sum(axis=1, keepdims=1)

# Check
print(result)
print(result.sum(axis=1))

# [[ 0.80736896  0.00663004  0.06474194  0.12125906]
#  [ 0.03545472  0.79746194  0.10495657  0.06212678]
#  [ 0.08566011  0.02632533  0.79709851  0.09091605]
#  [ 0.07298408  0.05698381  0.1585878   0.71144431]]
#
# [ 1.  1.  1.  1.]

The above condensed to two lines:

result = np.identity(k) + np.random.uniform(low=0., high=.25, size=(k, k))
result /= result.sum(axis=1, keepdims=1)

Specifying a larger high parameter will get you a smaller ratio of "diagonals to the rest":

result = np.identity(k) + np.random.uniform(low=0., high=.60, size=(k, k))
result /= result.sum(axis=1, keepdims=1)
print(result.round(2))
# [[ 0.53  0.02  0.25  0.2 ]
#  [ 0.05  0.58  0.19  0.18]
#  [ 0.02  0.04  0.72  0.22]
#  [ 0.07  0.23  0.08  0.62]]


问:
Get an API URL by route name in Laravel 5.5
Is there a way to specify the prefix when getting a route URL by its name in Laravel 5.5? For example,

In routes/web.php

```<code>Route::resource('users', 'UserController', ['only' => 'index', 'create', 'edit']);
</code>```

In routes/api.php

```<code>Routes::resource('users', 'UserController', ['only' => 'index', 'store', 'update', 'destroy']);
</code>```

Both routes to the index methods have the name users.index, as confirmed when calling php artisan route:list. However, the URL for the web route is /users and the URL for the api route is /api/users.

To get the web route URL, I can do route('users.index'). Is there a way to get the URL for the api route using the route name?

答:
You can give the resource controller's routes a prefix via the as option:

```<code>Route::resource('users', 'UserController', [
    'as' => 'your.prefix',
    'only' => ['index', 'store', 'update', 'destroy'],
]);
</code>```

Body:
Is there a way to specify the prefix when getting a route URL by its name in Laravel 5.5? For example,

In routes/web.php

Route::resource('users', 'UserController', ['only' => 'index', 'create', 'edit']);

In routes/api.php

Routes::resource('users', 'UserController', ['only' => 'index', 'store', 'update', 'destroy']);

Both routes to the index methods have the name users.index, as confirmed when calling php artisan route:list. However, the URL for the web route is /users and the URL for the api route is /api/users.

To get the web route URL, I can do route('users.index'). Is there a way to get the URL for the api route using the route name?

Body:
You can give the resource controller's routes a prefix via the as option:

Route::resource('users', 'UserController', [
    'as' => 'your.prefix',
    'only' => ['index', 'store', 'update', 'destroy'],
]);


问:
Cant style 2nd image in

#header {
  width: auto;
  height: 200px;
  background: silver;
  margin: 20 30 0;
}

#logo img {
  height: 160px;
  margin: 16 20 0 15;
  border: 4px double gray;
}

#title {
  margin: -195 570;
  font-family: Cooper;
  text-decoration: underline;
}

#Picture {
  width: 340px;
}

#firstimage img {
  height: 250;
  width: 340;
  margin: 0 20 0 30;
}

#2ndpic img {
  height: 25;
  float: left;
  width: 342;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <div id="logo">
    <img src="img.jpg" alt="Logo">
  </div>
  <div id="title">
    <h1> Welcome To My Site :) </h2>
  </div>
</div>
<Div id="picture">
  <Div id="firstimage">
    <img src="2nd.jpg" alt="banner">
  </div>
  <div id="2ndpic">
    <img src="3rd.jpg" alt="2ndimg">
  </div>
</div>
</div></code>```

I am trying to show both images same size and align them left right in              Picture . Help! these aint working, on <2ndpic> the styling isnt working, its not resizing by width height and is neither margin workin. Help!
.
By the way i am just learner if i have made any mistakes please point them out and tell me way to correct them, so i can fix them next time. thank you :)
and i am learning from Youtube so you can understand.

答:
Hey you cant access ID's starting with a number like this.

I would recommend renaming it into imgTwo or smth.

If you cant rename it you can access it via:

```<code>[id='2ndpic'] {

}
</code>```

Title: Cant style 2nd image in <div>

Body:
#header {
  width: auto;
  height: 200px;
  background: silver;
  margin: 20 30 0;
}

#logo img {
  height: 160px;
  margin: 16 20 0 15;
  border: 4px double gray;
}

#title {
  margin: -195 570;
  font-family: Cooper;
  text-decoration: underline;
}

#Picture {
  width: 340px;
}

#firstimage img {
  height: 250;
  width: 340;
  margin: 0 20 0 30;
}

#2ndpic img {
  height: 25;
  float: left;
  width: 342;
}

 Welcome To My Site :)

I am trying to show both images same size and align them left right in              Picture . Help! these aint working, on <2ndpic> the styling isnt working, its not resizing by width height and is neither margin workin. Help!
.
By the way i am just learner if i have made any mistakes please point them out and tell me way to correct them, so i can fix them next time. thank you :)
and i am learning from Youtube so you can understand.

Body:
Hey you cant access ID's starting with a number like this.

I would recommend renaming it into imgTwo or smth.

If you cant rename it you can access it via:

[id='2ndpic'] {

}


问:
Unable to import a vuejs library
I am making a tiny vuejs library just to learn how to make one. Let's call it swing and this is how the file is structured.

The conf/, dist/, test/ files are empty

I have pushed this library to github and published it to npm.
I installed it into my app using

```<code>npm install --save vuejs-swing
</code>```

I can see it's installed in package.json and node_modules folder, but when I do:

```<code>import swing from 'vuejs-swing'
</code>```

I get this error:

```<code> ERROR  Failed to compile with 1 errors                                                                                11:42:41 AM

This dependency was not found:

* vuejs-swing in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/c
omponents/HelloWorld.vue

To install it, you can run: npm install --save vuejs-swing
</code>```

It is obviously intalled so it must be a configuration issue

This is my webpack.config.js

```<code>var path = require('path')
var webpack = require('webpack')

module.exports = {
  module: {
    rules: [
      // use babel-loader for js files
      { test: /\.js$/, use: 'babel-loader' },
      // use vue-loader for .vue files
      { test: /\.vue$/, use: 'vue-loader' }
    ]
  },
  // default for pretty much every project
  context: __dirname,
  // specify your entry/main file
  entry: {
    app: './src/swing.js',

  },
  output: {
    // specify your output directory...
    path: path.resolve(__dirname, 'output'),
    // and filename
    filename: 'index.min.js'
  },
  resolve: {
    // this is optional, but it lets you import .vue files without the .vue extension.
    extensions: ['.js', '.json', '.vue']
  }
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}
</code>```

EDIT:

I will award the bounty to whomever who can provide the tools, configs necessary to publish a package in npm and be able to impor/use it.

答:
Follow these steps:

Make sure your output folder is not ignored by git (shouldn't be in the .gitignore file)

Build your package for production (run Webpack)

In your package.json point the main file to ./output/index.min.js and NOT to ./src/swing.js

{
  "name": "vuejs-swing",
  "version": "0.1.2",
  "main": "./output/index.min.js",
  // ...
}
```

Don't except your package's users to build the sources (run Webpack) for you, you need to point them to a pre-packaged javascript file.

As a side note, the package vuejs-swing is not publicly published on npm as for now. I don't know if you changed the package name or working on a private repository.

Title: Unable to import a vuejs library

Body:
I am making a tiny vuejs library just to learn how to make one. Let's call it swing and this is how the file is structured.

The conf/, dist/, test/ files are empty

I have pushed this library to github and published it to npm.
I installed it into my app using

npm install --save vuejs-swing

I can see it's installed in package.json and node_modules folder, but when I do:

import swing from 'vuejs-swing'

I get this error:

 ERROR  Failed to compile with 1 errors                                                                                11:42:41 AM

This dependency was not found:

* vuejs-swing in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/c
omponents/HelloWorld.vue

To install it, you can run: npm install --save vuejs-swing

It is obviously intalled so it must be a configuration issue

This is my webpack.config.js

var path = require('path')
var webpack = require('webpack')

module.exports = {
  module: {
    rules: [
      // use babel-loader for js files
      { test: /\.js$/, use: 'babel-loader' },
      // use vue-loader for .vue files
      { test: /\.vue$/, use: 'vue-loader' }
    ]
  },
  // default for pretty much every project
  context: __dirname,
  // specify your entry/main file
  entry: {
    app: './src/swing.js',

  },
  output: {
    // specify your output directory...
    path: path.resolve(__dirname, 'output'),
    // and filename
    filename: 'index.min.js'
  },
  resolve: {
    // this is optional, but it lets you import .vue files without the .vue extension.
    extensions: ['.js', '.json', '.vue']
  }
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

EDIT:

I will award the bounty to whomever who can provide the tools, configs necessary to publish a package in npm and be able to impor/use it.

Body:
Follow these steps:

Make sure your output folder is not ignored by git (shouldn't be in the .gitignore file)

Build your package for production (run Webpack)

In your package.json point the main file to ./output/index.min.js and NOT to ./src/swing.js

{
  "name": "vuejs-swing",
  "version": "0.1.2",
  "main": "./output/index.min.js",
  // ...
}

Don't except your package's users to build the sources (run Webpack) for you, you need to point them to a pre-packaged javascript file.

As a side note, the package vuejs-swing is not publicly published on npm as for now. I don't know if you changed the package name or working on a private repository.


问:
Portability of binary serialization of double/float type in C++
The C++ standard does not discuss the underlying layout of float and double types, only the range of values they should represent.  (This is also true for signed types, is it two's compliment or something else)

My question is: What the are techniques used to serialize/deserialize POD types such as double and float in a portable manner? At the moment it seems the only way to do this is to have the value represented literally(as in "123.456"), The ieee754 layout for double is not standard on all architectures.

答:
You should convert them to a format you will always be able to use in order to recreate your floats/doubles.

This could use a string representation or, if you need something that takes less space, represent your number in ieee754 (or any other format you choose) and then parse it as you would do with a string.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.


问:
Training data has columns with all missing values but same columns in the Test data has some values, how to handle such situation?
I have been given a training and test datasets separately. Both data sets have exactly same structure (same columns/features). There are some columns in the training data set that have missing values in all the rows. If I wanted to build a predictive model, I could simply delete those columns as they are not giving any information at all! But the trouble is that those same columns have some values in the test dataset. So, if I remove those columns from the training dataset, I will have to remove them from the test dataset too. I can do that too, but the problem is that the number of such columns are pretty large (about 150 out of total 250 columns). I’m very hesitant in removing those columns. Any idea or solution to preserve those columns would be really helpful. Thanks!</p>

答:
if your train/test data are appropriately split, then a useless column in one is useless in the other

alternatively, you can try to interpolate missing data


问:
Print address for a Google Maps map
I need to rearrange the code here, but I can't figure it out.  I'm trying to put the geocoded street address in the pop-up window.  I know it has something to do with variable access outside of functions but I'm just moving code around now and getting nowhere.

Please see the two comment lines in the code.

```<code>map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(37.725685, -122.156830),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
var places = <%= @locations.to_json.html_safe %>
var infowindow = new google.maps.InfoWindow();
var marker, i;

for (i = 0; i < places.length; i++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(places[i].lat, places[i].lng),
        map: map
    });

    var lat = (places[i].lat);
    var lng = (places[i].lng);

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({
        'location': new google.maps.LatLng(places[i].lat, places[i].lng)
    }, function (results, status) {
        if (status === 'OK') {

            // THIS CONSOLE LOG WORKS.  IT PRINTS THE ADDRESS AS EXPECTED
            console.log(results[0].formatted_address);

        }
    });

    google.maps.event.addListener(marker, 'click', (function (marker, i) {

        return function () {
            infowindow.setContent(places[i].location_name + " <br /> " +
                places[i].location_description + " <br /> " +

                //HERE the variable "results" throws a Reference error, not defined
                results[0].formatted_address);
            infowindow.open(map, marker);
        }
    })(marker, i));
}
</code>```

答:
results is passed as a callback from the geocoder.geocode() function, yet you're referencing it in the google.maps.event.addListener function.

If you insist on your structure, put the addListener call in the if ( status === 'OK' ) { block.

The short answer is - you have a scope issue because you're trying to access one function's argument in another function.

Title: Print address for a Google Maps map

Body:
I need to rearrange the code here, but I can't figure it out.  I'm trying to put the geocoded street address in the pop-up window.  I know it has something to do with variable access outside of functions but I'm just moving code around now and getting nowhere.

Please see the two comment lines in the code.

map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(37.725685, -122.156830),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
var places = <%= @locations.to_json.html_safe %>
var infowindow = new google.maps.InfoWindow();
var marker, i;

for (i = 0; i < places.length; i++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(places[i].lat, places[i].lng),
        map: map
    });

    var lat = (places[i].lat);
    var lng = (places[i].lng);

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({
        'location': new google.maps.LatLng(places[i].lat, places[i].lng)
    }, function (results, status) {
        if (status === 'OK') {

            // THIS CONSOLE LOG WORKS.  IT PRINTS THE ADDRESS AS EXPECTED
            console.log(results[0].formatted_address);

        }
    });

    google.maps.event.addListener(marker, 'click', (function (marker, i) {

        return function () {
            infowindow.setContent(places[i].location_name + "
 " +
                places[i].location_description + "
 " +

                //HERE the variable "results" throws a Reference error, not defined
                results[0].formatted_address);
            infowindow.open(map, marker);
        }
    })(marker, i));
}


答:
This is not an answer but a remark. You can reduce your code drastically by using a list comprehension:

```<code>operators = []
for line in inputFile1:
    name, language, domain, last_hour, total_minutes = line.strip().split(', ')
    operators.append((name, language, domain, last_hour, total_minutes))
</code>```

How about changing those 4 lines to:

```<code>operators = [tuple(line.strip().split(', ')) for line in inputFile1]
</code>```

Or why not a full remake:

```<code>import constants # imports are always made first (very few exceptions)

def read_operators_file(file_name):
    """Read a file with operators into a collection.

    Requires: file_name, str with the name of a text file with a list of operators.
    Ensures: list, with the operators in the file;
             each operators is a tuple with the various element
             concerning that operator, in the order provided in the file.
    """

    with open(file_name,'r+') as inputFile1: # with ensures file closes, no need to worry
        # read some lines to skip the header
        for i in range(constants.HEADER_TOTAL_LINES):
            next(inputFile1)
        operators = [tuple(line.strip().split(', ')) for line in inputFile1]

    return operators

# Function call
operators1 = read_operators_file("operators14h55.txt")
</code>```

Now to your actual question. The operators is a list with tuples. You cannot format variables in Python. It is only when you print or write that you have that option.

Body:
My issue is to write what is in my file, row by row in my function.

Here's my code:

def read_operators_file(file_name):
"""Read a file with operators into a collection.

Requires: file_name, str with the name of a text file with a list of operators.
Ensures: list, with the operators in the file; each operators is a tuple with the various element
concerning that operator, in the order provided in the file.
"""
inputFile1 = open("operators14h55.txt",'r+')
import constants
for i in range(constants.HEADER_TOTAL_LINES):  # read some lines to skip the header
    inputFile1.readline()
operators = []
for line in inputFile1:
    name, language, domain, last_hour, total_minutes = line.strip().split(', ')
    operators.append((name, language, domain, last_hour, total_minutes))
inputFile1.close()
return operators

that return's all in a row, and I want each tuple in a single row.

[('Henry Miller', 'english', 'laptops', 'premium', 3), ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

I want something similar to this:

[('Henry Miller', 'english', 'laptops', 'premium', 3),
 ('FranÃ§ois Greenwich', 'spanish', 'cameras', 'premium', 6),
 ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

Body:
This is not an answer but a remark. You can reduce your code drastically by using a list comprehension:

operators = []
for line in inputFile1:
    name, language, domain, last_hour, total_minutes = line.strip().split(', ')
    operators.append((name, language, domain, last_hour, total_minutes))

How about changing those 4 lines to:

operators = [tuple(line.strip().split(', ')) for line in inputFile1]

Or why not a full remake:

import constants # imports are always made first (very few exceptions)

def read_operators_file(file_name):
    """Read a file with operators into a collection.

    Requires: file_name, str with the name of a text file with a list of operators.
    Ensures: list, with the operators in the file;
             each operators is a tuple with the various element
             concerning that operator, in the order provided in the file.
    """

    with open(file_name,'r+') as inputFile1: # with ensures file closes, no need to worry
        # read some lines to skip the header
        for i in range(constants.HEADER_TOTAL_LINES):
            next(inputFile1)
        operators = [tuple(line.strip().split(', ')) for line in inputFile1]

    return operators

# Function call
operators1 = read_operators_file("operators14h55.txt")

Now to your actual question. The operators is a list with tuples. You cannot format variables in Python. It is only when you print or write that you have that option.


问:
Using email address from external HTML file to send email via google apps script
I'm creating a function within Google Apps whereby I need to email the spreadsheet I am working on as a PDF. The user should click on a button and a dialogue box should open whereby they can enter email address, subject and message and send the email from there.

I've created the email dialogue as a sidebar with the following HTML:

```<code><!DOCTYPE html>
<html>
    <head>
       <link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
       <base target="_top">
    </head>
    <body>
       <form>
         <div class="form-group">
           <label for="exampleInputEmail1">Email address</label>
           <input type="email" class="form-control" id="exampleInputEmail1" ar.  ia-describedby="emailHelp" value="d.bage@group-miki.com">
         </div>
         <div class="form-group">
            <label for="subject">Subject</label>
            <input type="input" class="form-control" id="subject" value="Contract    renewal - Miki Travel">
         </div>
         <div class="form-group">
             <label for="subject">Message</label>
             <textarea class="form-control" rows="12" id="text"></textarea>
         </div>

         <button type="submit" class="btn btn-primary">Submit</button>
       </form>
    </body>
</html>
</code>```

However, when I'm writing the script to send the email, how do I store the content of the email box here as variable to use for sending the email? The same will apply obviously to the subject and the message itself.

答:
1) Define name properties for your inputs. Currently, none of your form fields has the 'name' property. Here's the example of how it should look like

```<code>   <input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="d.bage@group-miki.com">
</code>```

This will allow you to access the properties of the form object when the form is submitted (e.g., form.email, form.subject, etc);

2) On the client-side (html), you must write the code to handle the 'submit' event. Add the following before the closing  tag:

```<code><script>

window.onload = function() {

    document.getElementsByTagName('form')[0]
            .addEventListener('submit', function(e){

              e.preventDefault(); // intercept redirect to another page
              google.script.run.handleFormSubmit(this); // pass the form object to the server-side function.

            });

 }

 </script>
</code>```

You can also use jQuery to achieve the same result.
Here's my server-side (.gs) function that logs the contents of the input fields

```<code>function handleFormSubmit(form) {

  Logger.log(form.email);
  Logger.log(form.subject);
  Logger.log(form.message);

}
</code>```

Use google.script.run for client-server communication. See the docs for more details https://developers.google.com/apps-script/guides/html/communication

Body:
I'm creating a function within Google Apps whereby I need to email the spreadsheet I am working on as a PDF. The user should click on a button and a dialogue box should open whereby they can enter email address, subject and message and send the email from there.

I've created the email dialogue as a sidebar with the following HTML:

<!DOCTYPE html>

       <link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
       <base target="_top">

       <form>

           Email address
           <input type="email" class="form-control" id="exampleInputEmail1" ar.  ia-describedby="emailHelp" value="d.bage@group-miki.com">

            Subject
            <input type="input" class="form-control" id="subject" value="Contract    renewal - Miki Travel">

             Message
             <textarea class="form-control" rows="12" id="text"></textarea>

         <button type="submit" class="btn btn-primary">Submit</button>
       </form>

However, when I'm writing the script to send the email, how do I store the content of the email box here as variable to use for sending the email? The same will apply obviously to the subject and the message itself.

Body:
1) Define name properties for your inputs. Currently, none of your form fields has the 'name' property. Here's the example of how it should look like

   <input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="d.bage@group-miki.com">

This will allow you to access the properties of the form object when the form is submitted (e.g., form.email, form.subject, etc);

2) On the client-side (html), you must write the code to handle the 'submit' event. Add the following before the closing </body> tag:

<script>

window.onload = function() {

    document.getElementsByTagName('form')[0]
            .addEventListener('submit', function(e){

              e.preventDefault(); // intercept redirect to another page
              google.script.run.handleFormSubmit(this); // pass the form object to the server-side function.

            });

 }

 </script>

You can also use jQuery to achieve the same result.
Here's my server-side (.gs) function that logs the contents of the input fields

function handleFormSubmit(form) {

  Logger.log(form.email);
  Logger.log(form.subject);
  Logger.log(form.message);

}

Use google.script.run for client-server communication. See the docs for more details https://developers.google.com/apps-script/guides/html/communication


问:
How to host and refer to static content from within your ear file
We have several j2ee applications (e.g. A.ear, B.ear, C.war) running in a single jboss instance, we have a requirement to share a set of static files across these applications. So I should be in a position to access these files as http://myhost/folderA/fileA.htm or http://myhost/folderB/file.js from within my ear or war files.

How should I tell the jboss appserver (5.1.0) to look for these files, how should I deploy this static content in my server/default/deploy directory or the docs folder

答:
If you're using jboss with the Jetty server, you can re-use the org.mortbay.jetty.servlet.DefaultServlet. I am sure tomcat has something similar or you can just add the jetty one (because it's a servlet, it will run on any servlet container).
Even though it's relatively easy to write it yourself, it's not because there are a bunch of things a quality implementation needs.

Take a look at the documentation of the DefaultServlet on how to configure it, it has many features.


答:
just build str from values in all columns</p>

```<code>Dim i as Long 'HERE EDITED
For i = 0 To 2
str = str & " " & Cells(r, 1).Offset(,i) 'HERE EDITED
Next i
MsgBox str
str = ""
</code>```

Title: Row to string with space between items

Body:
I have this:

| col1 | col2 | col 3 |
|    5 |   FA |   OFF |
|  107 |   FA |    ON |
|   96 |   FO |    ON |

and I want to MsgBox each row like that

Dim str As String
Dim r As Long

r = 2
While Celles(r,1).Value <> ""
    str = Rows(r)                    ' don't know how get row with space between items
    MsgBox str
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec("""C:\mypath\prog.exe"" " & str)

    r = r+1
Wend

I want 3 MsgBox to appear  5 FA OFF 107 FA ON 96 FO ON.

Therefore, how to get a row properly and add space between items ?

(After i want to call WshShellExec with parameters)

Body:
just build str from values in all columns

Dim i as Long 'HERE EDITED
For i = 0 To 2
str = str & " " & Cells(r, 1).Offset(,i) 'HERE EDITED
Next i
MsgBox str
str = ""


问:
can we join two rdd with two keys using join function in pyspark?
Like for instance :

rdd1 = [('magnus', 'nordea', 13000), ('Erik', 'nordea', 13000), ('Ola', 'nordea', 19000), ('rohit', 'nordea', 23030)]
rdd2 = [('magnus', 'jpmc', 14000), ('Erik', 'jpmc', 2100), ('Ola', 'jpmc', 18400), ('rohit', 'jpmc', 25000)]

rdd1.join(rdd2).collect() gives me :
[('Ola', ('nordea', 'jpmc')), ('Erik', ('nordea', 'jpmc')), ('rohit', ('nordea', 'jpmc')), ('magnus', ('nordea', 'jpmc'))]
```

<p>The above rdd loses its amount value :(</p>

<p>Required output :</p>

<pre class="lang-python prettyprint-override"><code>[(('Ola','nordea'),13000),
 (('Ola','jpmc'),14000),
 (('Erik','nordea'),13000),
 (('Erik','jpmc'),2100),
 (('rohit','nordea'),23030),
 (('rohit','jpmc'),25000),
 (('magnus','nordea'),13000),
 (('magnus', 'jpmc'),14000)]
</code>```

Any suggestions on it or what function I should refer to?

Body:
Like for instance :

rdd1 = [('magnus', 'nordea', 13000), ('Erik', 'nordea', 13000), ('Ola', 'nordea', 19000), ('rohit', 'nordea', 23030)]
rdd2 = [('magnus', 'jpmc', 14000), ('Erik', 'jpmc', 2100), ('Ola', 'jpmc', 18400), ('rohit', 'jpmc', 25000)]

rdd1.join(rdd2).collect() gives me :
[('Ola', ('nordea', 'jpmc')), ('Erik', ('nordea', 'jpmc')), ('rohit', ('nordea', 'jpmc')), ('magnus', ('nordea', 'jpmc'))]

The above rdd loses its amount value :(

Required output :

[(('Ola','nordea'),13000),
 (('Ola','jpmc'),14000),
 (('Erik','nordea'),13000),
 (('Erik','jpmc'),2100),
 (('rohit','nordea'),23030),
 (('rohit','jpmc'),25000),
 (('magnus','nordea'),13000),
 (('magnus', 'jpmc'),14000)]

Any suggestions on it or what function I should refer to?

Body:
     rdd1.union(rdd2).collect()

Output:

    [('magnus', 'nordea', 13000),
     ('Erik', 'nordea', 13000),
     ('Ola', 'nordea', 19000),
     ('rohit', 'nordea', 23030),
     ('magnus', 'jpmc', 14000),
     ('Erik', 'jpmc', 2100),
     ('Ola', 'jpmc', 18400),
     ('rohit', 'jpmc', 25000)]


问:
asp.net core 2.0 docker image for projects targeting full framework
Microsoft has multiple docker image flavours for a different kind of .net projects. like

.Net Framework

Asp.Net

.Net Core

Asp.Net Core

Now I have project in asp.net core 2 targeting full net framework 4.6.1 (not targeting netcore2)

I want to use Docker for deployment of this project, where can I find a suitable docker image? asp.net core docker image only allows targeting .net core 2, not a full .net framework.

答:
You can use the .NET Framework based docker images here. Since ASP.NET Core on .NET Framework images will contain everything that is needed in the published output, the app should run fine on just .NET Framework dependencies.

The docker image for ASP.NET Core on .NET Core only contains the runtime store for the requested ASP.NET Core version in addition to the .NET Core runtime so that the dependencies that aren't included in the published output and expected on the target machine are found.


问:
Patterned gradients in modern browsers
I get more and more complaints regarding badly rendered gradients (CSS, Canvas, and SVG).

As it highly depends on the browser and OS. I can't propose a global MCVE. So I'll focus on this simple CSS gradient which is badly rendered on Chrome/Ubuntu (vertical stripes):

body {
    background: linear-gradient(90deg, #111, #444);
}```

Of course I'd be interested in a solution for this specific case. But I'd value more a general solution to get smooth monotonous gradients. Canvas or image based solutions are not acceptable as my gradients are in great number, dynamic, and usually partially transparent.

答:
The lines you are seeing is called banding. Chrome in Win10 dithers gradients, FF does not. This differs per browser.

Some informative links related to this question:

https://smerity.com/articles/2013/dithering.html

Bug 627771 - Add dithering to gradient color transitions to address banding in 24-bit
"truecolor"

https://forum.webflow.com/t/managing-website-banding-on-retina-4k-screens/24343

https://graphicdesign.stackexchange.com/questions/8426/gradient-banding-in-chrome

Without using an image as the gradient it is not possible to solve this as far as I know. Perhaps FireFox will dither gradients in a future version.

Title: Patterned gradients in modern browsers

Body:
I get more and more complaints regarding badly rendered gradients (CSS, Canvas, and SVG).

As it highly depends on the browser and OS. I can't propose a global MCVE. So I'll focus on this simple CSS gradient which is badly rendered on Chrome/Ubuntu (vertical stripes):

body {
    background: linear-gradient(90deg, #111, #444);
}

Of course I'd be interested in a solution for this specific case. But I'd value more a general solution to get smooth monotonous gradients. Canvas or image based solutions are not acceptable as my gradients are in great number, dynamic, and usually partially transparent.


问:
LNK2022 Error When Using /clr
I'm having a problem linking a C++ project in VS2008 when using the /clr compile option.  I am getting the following build errors:

```<code>Class1.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046f).
Class1.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000473).
Class2.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046f).
Class2.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000473).
Class3.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046e).
Class3.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000472).
Class4.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046e).
Class4.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000472).
Class5.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046e).
Class5.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000472).
Class6.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046e).
Class6.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000472).
LINK : fatal error LNK1255: link failed because of metadata errors
</code>```

I have no idea what PROPSHEETPAGEA and PROPSHEETPAGEW are referring to.  I checked online to see Microsoft's description of the error but am at a loss as to what it means.
http://support.microsoft.com/kb/324088

To resolve this problem, add unique identifiers when you use Managed Extensions for C++ so that you avoid using anonymous structures as global variables.

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article. This bug was corrected in Microsoft Visual C++ .NET (2003).

Any ideas would be greatly appreciated.

EDIT

After doing a ildasm on Class1.obj I extracted two messages:

```<code>// TypeDef #1134 (0200046f)
// -------------------------------------------------------
//  TypDefName: _PROPSHEETPAGEA  (0200046F)
//  Flags     : [NotPublic] [SequentialLayout] [Class] [Sealed] [AnsiClass] [BeforeFieldInit]  (00100108)
//  Extends   : 0100000B [TypeRef] System.ValueType
//  Layout    : Packing:0, Size:56
//  CustomAttribute #1 (0c0012a0)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000003
//      CustomAttributeName: Microsoft.VisualC.MiscellaneousBitsAttribute :: instance void .ctor(int32)
//      Length: 8
//      Value : 01 00 41 00 00 00 00 00                          >  A             <
//      ctor args: (65)
//
//  CustomAttribute #2 (0c0012a1)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000001
//      CustomAttributeName: Microsoft.VisualC.DebugInfoInPDBAttribute :: instance void .ctor()
//      Length: 4
//      Value : 01 00 00 00                                      >                <
//      ctor args: ()
//
//  CustomAttribute #3 (0c0012a2)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000004
//      CustomAttributeName: System.Runtime.CompilerServices.NativeCppClassAttribute :: instance void .ctor()
//      Length: 4
//      Value : 01 00 00 00                                      >                <
//      ctor args: ()

// TypeDef #1138 (02000473)
// -------------------------------------------------------
//  TypDefName: _PROPSHEETPAGEW  (02000473)
//  Flags     : [NotPublic] [SequentialLayout] [Class] [Sealed] [AnsiClass] [BeforeFieldInit]  (00100108)
//  Extends   : 0100000B [TypeRef] System.ValueType
//  Layout    : Packing:0, Size:56
//  CustomAttribute #1 (0c0012b0)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000004
//      CustomAttributeName: System.Runtime.CompilerServices.NativeCppClassAttribute :: instance void .ctor()
//      Length: 4
//      Value : 01 00 00 00                                      >                <
//      ctor args: ()
//
//  CustomAttribute #2 (0c0012b1)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000001
//      CustomAttributeName: Microsoft.VisualC.DebugInfoInPDBAttribute :: instance void .ctor()
//      Length: 4
//      Value : 01 00 00 00                                      >                <
//      ctor args: ()
//
//  CustomAttribute #3 (0c0012b2)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000003
//      CustomAttributeName: Microsoft.VisualC.MiscellaneousBitsAttribute :: instance void .ctor(int32)
//      Length: 8
//      Value : 01 00 41 00 00 00 00 00                          >  A             <
//      ctor args: (65)
</code>```

I'm not sure what all this means, but it looks as if the second entry is identical to the first with the exception of the attributes being defined backwards.

答:
I had the same problem today, migrating my project from vs2008 to vs2010. While compiling a CLI project that links with other C++ libs, i got this link error on:

```<code>MSVCMRTD.lib(locale0_implib.obj) : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (std.basic_string<char,std::char_traits<char>,std::allocator<char> >): (0x0200004f).
MSVCMRTD.lib(locale0_implib.obj) : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (std.basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >): (0x02000075).
</code>```

I tried ildasm as the documentation suggest, but could not find any type definitions that seems the same but having a different names.

moreover, I must say I do not completely understand this error. The fact that two errors appear means that there are two different problems with both types (char string and wchar string) or does it mean that there is one problem that these two types are causing. What is the meaning of the numbers in the end of the line (i did find two typedefs on the ildasm log with these numbers, though). There is nothing about that in the documentation.

BTW - same projects -same configuration compiles and links perfectly with vs2008.

Anyway, lost in the dark, I turned my other C++ lib, which link with the CLI project, into a CLI project as well (compiling it with /clr flag). relinking the main CLI project seems to solve the problem. Somehow adding the clr support or linking with clr resolve this types collision.

If someone have an educated explanation to this issue I would love to read it.

Title: LNK2022 Error When Using /clr

Body:
I'm having a problem linking a C++ project in VS2008 when using the /clr compile option.  I am getting the following build errors:

Class1.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046f).
Class1.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000473).
Class2.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046f).
Class2.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000473).
Class3.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046e).
Class3.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000472).
Class4.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046e).
Class4.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000472).
Class5.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046e).
Class5.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000472).
Class6.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEA): (0x0200046e).
Class6.obj : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (_PROPSHEETPAGEW): (0x02000472).
LINK : fatal error LNK1255: link failed because of metadata errors

I have no idea what PROPSHEETPAGEA and PROPSHEETPAGEW are referring to.  I checked online to see Microsoft's description of the error but am at a loss as to what it means.
http://support.microsoft.com/kb/324088

To resolve this problem, add unique identifiers when you use Managed Extensions for C++ so that you avoid using anonymous structures as global variables.

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article. This bug was corrected in Microsoft Visual C++ .NET (2003).

Any ideas would be greatly appreciated.

EDIT

After doing a ildasm on Class1.obj I extracted two messages:

// TypeDef #1134 (0200046f)
// -------------------------------------------------------
//  TypDefName: _PROPSHEETPAGEA  (0200046F)
//  Flags     : [NotPublic] [SequentialLayout] [Class] [Sealed] [AnsiClass] [BeforeFieldInit]  (00100108)
//  Extends   : 0100000B [TypeRef] System.ValueType
//  Layout    : Packing:0, Size:56
//  CustomAttribute #1 (0c0012a0)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000003
//      CustomAttributeName: Microsoft.VisualC.MiscellaneousBitsAttribute :: instance void .ctor(int32)
//      Length: 8
//      Value : 01 00 41 00 00 00 00 00                          >  A             <
//      ctor args: (65)
//
//  CustomAttribute #2 (0c0012a1)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000001
//      CustomAttributeName: Microsoft.VisualC.DebugInfoInPDBAttribute :: instance void .ctor()
//      Length: 4
//      Value : 01 00 00 00                                      >                <
//      ctor args: ()
//
//  CustomAttribute #3 (0c0012a2)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000004
//      CustomAttributeName: System.Runtime.CompilerServices.NativeCppClassAttribute :: instance void .ctor()
//      Length: 4
//      Value : 01 00 00 00                                      >                <
//      ctor args: ()

// TypeDef #1138 (02000473)
// -------------------------------------------------------
//  TypDefName: _PROPSHEETPAGEW  (02000473)
//  Flags     : [NotPublic] [SequentialLayout] [Class] [Sealed] [AnsiClass] [BeforeFieldInit]  (00100108)
//  Extends   : 0100000B [TypeRef] System.ValueType
//  Layout    : Packing:0, Size:56
//  CustomAttribute #1 (0c0012b0)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000004
//      CustomAttributeName: System.Runtime.CompilerServices.NativeCppClassAttribute :: instance void .ctor()
//      Length: 4
//      Value : 01 00 00 00                                      >                <
//      ctor args: ()
//
//  CustomAttribute #2 (0c0012b1)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000001
//      CustomAttributeName: Microsoft.VisualC.DebugInfoInPDBAttribute :: instance void .ctor()
//      Length: 4
//      Value : 01 00 00 00                                      >                <
//      ctor args: ()
//
//  CustomAttribute #3 (0c0012b2)
//  -------------------------------------------------------
//      CustomAttribute Type: 0a000003
//      CustomAttributeName: Microsoft.VisualC.MiscellaneousBitsAttribute :: instance void .ctor(int32)
//      Length: 8
//      Value : 01 00 41 00 00 00 00 00                          >  A             <
//      ctor args: (65)

I'm not sure what all this means, but it looks as if the second entry is identical to the first with the exception of the attributes being defined backwards.

Body:
I had the same problem today, migrating my project from vs2008 to vs2010. While compiling a CLI project that links with other C++ libs, i got this link error on:

MSVCMRTD.lib(locale0_implib.obj) : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (std.basic_string<char,std::char_traits<char>,std::allocator<char> >): (0x0200004f).
MSVCMRTD.lib(locale0_implib.obj) : error LNK2022: metadata operation failed (8013118D) : Inconsistent layout information in duplicated types (std.basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >): (0x02000075).

I tried ildasm as the documentation suggest, but could not find any type definitions that seems the same but having a different names.

moreover, I must say I do not completely understand this error. The fact that two errors appear means that there are two different problems with both types (char string and wchar string) or does it mean that there is one problem that these two types are causing. What is the meaning of the numbers in the end of the line (i did find two typedefs on the ildasm log with these numbers, though). There is nothing about that in the documentation.

BTW - same projects -same configuration compiles and links perfectly with vs2008.

Anyway, lost in the dark, I turned my other C++ lib, which link with the CLI project, into a CLI project as well (compiling it with /clr flag). relinking the main CLI project seems to solve the problem. Somehow adding the clr support or linking with clr resolve this types collision.

If someone have an educated explanation to this issue I would love to read it.