问:
Reproduce clip-path polygon for browsers not supporting it?
How can i reproduce the design (see below), so browsers that does not support clip-path polygon can see it? I want it to angle the top edge, without rotating
 or skewing the entire div. Is that possible?

HTML:

```<code><div class="angledbox">
    <div class="textstuff">
    <p class="title">Title</p>
    <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent malesuada, turpis vitae hendrerit interdum, mauris augue viverra enim, id ultrices dui felis scelerisque ligula.</p>
    </div>
</div>
</code>```

CSS:

```<code>.angledbox {
    background-color: #5EA359;
  width: 100%;
  padding-top: 80px;
  padding-bottom: 20px;
  -webkit-clip-path: polygon(0 0, 6000px 100%, 100% 100%, 0 100%);
  clip-path: polygon(0 0, 6000px 100%, 100% 100%, 0 100%);
}
.title {
    font-size:30px;
    margin:0px;
    padding:0px;
    font-weight:bold;
    text-align:center;
    color:white;
    text-transform:uppercase;
}
.text {
    color:white;
    text-align:center;
    margin:0px;
    padding:0px;
    font-size: 18px;
}
.textstuff {
    width:20%;
    margin:auto;
    padding-bottom:20px;
}
</code>```

DEMO

Codepen

答:
Have play around a bit with your code pen and I don't think you get it by using border triangles.

But maybe this help you a little bit. I used linear gradient, which most browsers can handle.

.angledbox {
  position: relative;
  background-color: #5EA359;
  width: 100%;
  padding-top: 80px;
  padding-bottom: 20px;
}

.angledbox::before {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 80px;
  content: '';
  background-image: linear-gradient( to left bottom, white 50%, transparent 50%);
}```
</div>
</div>
</p>

<p>Please add/replace this in your code pen.</p>

<p>Or here a full Example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.angledbox {
 position: relative;
 background-color: #5EA359;
  width: 100%;
  padding-top: 80px;
  padding-bottom: 20px;
}

.angledbox::before {
 position: absolute;
 top: 0;
 left: 0;
 right: 0;
 height: 80px;
 content: '';
 background-image: linear-gradient( to left bottom, white 50%, transparent 50%);
}

.title {
 font-size:30px;
 margin:0px;
 padding:0px;
 font-weight:bold;
 text-align:center;
 color:white;
 text-transform:uppercase;
}
.text {
 color:white;
 text-align:center;
 margin:0px;
 padding:0px;
 font-size: 18px;
}
.textstuff {
 width:20%;
 margin:auto;
 padding-bottom:20px;
}</code>```

Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent malesuada, turpis vitae hendrerit interdum, mauris augue viverra enim, id ultrices dui felis scelerisque ligula.

```

Body:
How can i reproduce the design (see below), so browsers that does not support clip-path polygon can see it? I want it to angle the top edge, without rotating
 or skewing the entire div. Is that possible?

HTML:

Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent malesuada, turpis vitae hendrerit interdum, mauris augue viverra enim, id ultrices dui felis scelerisque ligula.

CSS:

.angledbox {
    background-color: #5EA359;
  width: 100%;
  padding-top: 80px;
  padding-bottom: 20px;
  -webkit-clip-path: polygon(0 0, 6000px 100%, 100% 100%, 0 100%);
  clip-path: polygon(0 0, 6000px 100%, 100% 100%, 0 100%);
}
.title {
    font-size:30px;
    margin:0px;
    padding:0px;
    font-weight:bold;
    text-align:center;
    color:white;
    text-transform:uppercase;
}
.text {
    color:white;
    text-align:center;
    margin:0px;
    padding:0px;
    font-size: 18px;
}
.textstuff {
    width:20%;
    margin:auto;
    padding-bottom:20px;
}

DEMO

Codepen

Body:
Have play around a bit with your code pen and I don't think you get it by using border triangles.

But maybe this help you a little bit. I used linear gradient, which most browsers can handle.

.angledbox {
  position: relative;
  background-color: #5EA359;
  width: 100%;
  padding-top: 80px;
  padding-bottom: 20px;
}

.angledbox::before {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 80px;
  content: '';
  background-image: linear-gradient( to left bottom, white 50%, transparent 50%);
}

Please add/replace this in your code pen.

Or here a full Example:

.angledbox {
 position: relative;
 background-color: #5EA359;
  width: 100%;
  padding-top: 80px;
  padding-bottom: 20px;
}

.angledbox::before {
 position: absolute;
 top: 0;
 left: 0;
 right: 0;
 height: 80px;
 content: '';
 background-image: linear-gradient( to left bottom, white 50%, transparent 50%);
}

.title {
 font-size:30px;
 margin:0px;
 padding:0px;
 font-weight:bold;
 text-align:center;
 color:white;
 text-transform:uppercase;
}
.text {
 color:white;
 text-align:center;
 margin:0px;
 padding:0px;
 font-size: 18px;
}
.textstuff {
 width:20%;
 margin:auto;
 padding-bottom:20px;
}

<div class="angledbox">
 <div class="textstuff">
 <p class="title">Title</p>
 <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent malesuada, turpis vitae hendrerit interdum, mauris augue viverra enim, id ultrices dui felis scelerisque ligula.</p>
 </div>
</div>


来源: stackexchange

问:
Running Node app via PM2 on port 80
I have an express that I want to run on port 80. --> app.listen(80);

I'm using PM2 to manage the app (restarting, stopping, monitoring, etc.) . I have a deployment shell script whose last command is PM2 restart index.  From the console output, I see no errors and PM2 reports that it successfully completed the command.  Yet when I got to my.ec2.ip.address:80 the site is not up.  Furthermore, if I run node index.js in my server project directory, I get a Error: listen EACCES 0.0.0.0:80.  This makes some sense to me as port 80 is below 1024 and therefore a privileged port.  sudo node index.js will allow the launch to work.

I'm a newbie to unix, servers, permissions, and deployment, so in addition to the solution, an explanation of the fundamental concepts contributing to my problem would be greatly appreciated.  For instance.. is it bad to simply run my node app as super-user?  Is it good practice to run PM2 (therefore possibly running node as..?) root/super-user?  The command sudo PM2 restart index leads to sudo: pm2: command not found.  Why is PM2 not found when running sudo PM2.. if PM2 is in my path?

Ultimately though, when using PM2 how can I ensure that my server runs on port 80?  not found.

答:
It's good to run as little as possible as a priviliged user, as you want to restrict the potential damage in case someone exploits your program. You don't want to run your Node code as root unless you absolutely have to.

Therefore, it's better to run your Node program on an unprivileged port (say, port 8000), and instead have a lightweight web server such as Nginx listen on port 80 and simply forward traffic to your Node program.

If you want to go with Nginx, you can use this configuration to do exactly what I described above, and then just listen with your Node program on port 3000:

```<code>server {
  listen 80 default;
  listen [::]:80 default;

  location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for;
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Running Node app via PM2 on port 80

Body:
It's good to run as little as possible as a priviliged user, as you want to restrict the potential damage in case someone exploits your program. You don't want to run your Node code as root unless you absolutely have to.

Therefore, it's better to run your Node program on an unprivileged port (say, port 8000), and instead have a lightweight web server such as Nginx listen on port 80 and simply forward traffic to your Node program.

If you want to go with Nginx, you can use this configuration to do exactly what I described above, and then just listen with your Node program on port 3000:

server {
  listen 80 default;
  listen [::]:80 default;

  location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for;
  }
}


问:
Tool strip Menu Item has no invoke method, how to update with background thread
IntelliSense states that Tool strip Menu Item has no invoke method. I get red squiggly lines. How do I update without delegate / invoke?</p>

```<code>      Private Delegate Sub AppendTSMIDelegate(ByVal TMSI As ToolStripMenuItem, ByVal b As Boolean)
Private Sub AppendTSMI(ByVal TSMI As ToolStripMenuItem, ByVal b As Boolean)
    If **TSMI.InvokeRequired** Then
        TSMI.Invoke(New AppendTSMIDelegate(AddressOf AppendTSMI), New Object() {TSMI, b})
    Else
        'TSMI.
    End If
</code>```

答:
The answer is to check the invoke status on the toolstrip instead. Much thought and reading finally gave me the answer!</p>
```<code>Private Sub AppendTSMI(ByVal TSMI As ToolStripMenuItem, ByVal b As Boolean)

    Dim ST1 As StatusStrip = StatusStrip1

    If ST1.InvokeRequired Then
        ST1.Invoke(New AppendTSMIDelegate(AddressOf AppendTSMI), New Object() {TSMI, b})
    Else
        TSMI.Checked = b
    End If

End Sub
</code>```

Body:
IntelliSense states that Tool strip Menu Item has no invoke method. I get red squiggly lines. How do I update without delegate / invoke?

      Private Delegate Sub AppendTSMIDelegate(ByVal TMSI As ToolStripMenuItem, ByVal b As Boolean)
Private Sub AppendTSMI(ByVal TSMI As ToolStripMenuItem, ByVal b As Boolean)
    If **TSMI.InvokeRequired** Then
        TSMI.Invoke(New AppendTSMIDelegate(AddressOf AppendTSMI), New Object() {TSMI, b})
    Else
        'TSMI.
    End If

Body:
The answer is to check the invoke status on the toolstrip instead. Much thought and reading finally gave me the answer!

Private Sub AppendTSMI(ByVal TSMI As ToolStripMenuItem, ByVal b As Boolean)

    Dim ST1 As StatusStrip = StatusStrip1

    If ST1.InvokeRequired Then
        ST1.Invoke(New AppendTSMIDelegate(AddressOf AppendTSMI), New Object() {TSMI, b})
    Else
        TSMI.Checked = b
    End If

End Sub

ContentLicense: CC BY-SA 4.0


问:
How to use Red Gate Ants Profiler on the Command Line
I am trying to use Redgate Ants memory profiler with the command line. I have seen the redgate page on the command line but did not find it very informative. Does anyone have a more detailed description on how to do this?

Thanks for any help.

答: There's no command line in ANTS Memory Profiler v4.3 or later. The ability to take a snapshot from within your code will however be re-introduced in v.7 due out mid January (See http://www.red-gate.com/messageboard/viewforum.php?f=134 for access to beta builds as part of the early-access program).</p>

ContentLicense: CC BY-SA 2.5


问:
Cakephp 3 elasticsearch issue
I have installed elasticsearch on cakephp 3 As told here https://book.cakephp.org/3.0/en/elasticsearch.html.
But I am getting an error

Error: Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]])
File /vendor/ruflin/elastica/lib/Elastica/Exception/ResponseException.php
Line: 34
Elasticsearch version -> 5.0 AND PHP version -> 5.6.30

Please help me if any one knows the solution.

答:
There's no stable release yet that works with Elastica 5.x:

https://github.com/cakephp/elastic-search/issues/116

The 1.0 branch is said to be somewhat 5.x compatible, so if you're up for an adventure, try using cakephp/elastic-search:1.0.x-dev.

Title: Cakephp 3 elasticsearch issue


问:
AWS "Missing required client configuration options" exception with Yii::createObject() default configuration
I'm trying to get a simple web application working with the Yii 2 framework, a DynamoDB database hosted on AWS and the AWS SDK for PHP. I'm just saving/retrieving movie details to/from the database.

(For the purposes of copying code here, I am not going to copy my real AWS key/secret.)

Everything works as I want when I create my Aws\Sdk object like this:

```<code>$sdk = new Aws\Sdk([
    'region'   => 'us-west-2',
    'version'  => 'latest',
    'credentials' => [
        'key'     => 'KEYKEYKEYKEYKEYKEYKE',
        'secret'  => 'SECRETSECRETSECRETSECRETSECRETSECRETSECR'
    ]
]);
$dynamodb = $sdk->createDynamoDb();
</code>```

But I want to take advantage of Yii's default configurations with the Yii::createObject() method, so that I don't have to specify the region, version and credentials every place I create an Aws\Sdk object. So, as per the Yii documentation, I have saved into my application configuration:

```<code>\Yii::$container->set('Aws\Sdk', [
    'region'      => 'us-west-2',
    'version'     => 'latest',
    'credentials' => [
        'key'     => 'KEYKEYKEYKEYKEYKEYKE',
        'secret'  => 'SECRETSECRETSECRETSECRETSECRETSECRETSECR'
    ]
]);
</code>```

and now wherever I create an Aws\Sdk object, my code looks like this:

```<code>$sdk = Yii::createObject('Aws\Sdk');
$dynamodb = $sdk->createDynamoDb();
</code>```

However, when I do it like this, I get an InvalidArgumentException from AWS about "Missing required client configuration options". If I var_dump() the $sdk variable immediately after it is assigned, I can see that the object has the required region, version and credentials attributes, but the next line where I assign the $dynamodb variable throws the exception.

I am hoping that someone can show me where I am going wrong.

答:
First off you shouldn't be putting credentials in your code. I recommend the following:

If you have this code running on an EC2 instance, instead apply an IAM role to it. With roles you declare exactly what permissions you any CLI/SDK calls that will be running in the instance. When the SDK goes to make a call, it will contact the instance metadata server and get a set of temporary credentials. Of course this happens all transparently without you needing to do anything. As the credentials expire after a period of time (your SDK will of course grab new credentials when this happens transparently). This the best option as you no longer need to worry about credentials, other SDKs or the CLI can use it, and it's all temporary.

Use a credentials file. You should only really do this if your code is outside of AWS territory and cannot utilize IAM roles. While your credentials become more centralized they're at least not part of your code base where they could potentially be leaked. Also it makes it so that you can easily utilize other languages and still have the credentials automatically pulled up.

Now then on to the other part:

```<code>\Yii::$container->set('Aws\Sdk', [
    'region'      => 'us-west-2',
    'version'     => 'latest',
    'credentials' => [
        'key'     => 'KEYKEYKEYKEYKEYKEYKE',
        'secret'  => 'SECRETSECRETSECRETSECRETSECRETSECRETSECR'
    ]
]);
</code>```

This isn't what you think it is, if you look at the source code:

```<code> * If a class definition with the same name already exists, it will be overwritten with the new one.
 * You may use [[has()]] to check if a class definition already exists.
 *
 * @param string $class class name, interface name or alias name
 * @param mixed $definition the definition associated with `$class`. It can be one of the following:
 *
 * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable
 *   should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor
 *   parameters, `$config` the object configuration, and `$container` the container object. The return value
 *   of the callable will be returned by [[get()]] as the object instance requested.
 * - a configuration array: the array contains name-value pairs that will be **used to initialize the property**
 *   **values of the newly created object** when [[get()]] is called. The `class` element stands for the
 *   the class of the object to be created. If `class` is not specified, `$class` will be used as the class name.
 * - a string: a class name, an interface name or an alias name.
 * @param array $params the list of constructor parameters. The parameters will be passed to the class
 * constructor when [[get()]] is called.
 * @return $this the container itself
 */
</code>```

Note the "**" marked areas. In other words the second parameter is not a set of constructor arguments which is probably what you want, but instead an array of parameters that will be set after your constructor is called. Instead you want your second parameter blank, and the third parameter an array something like:

```<code>\Yii::$container->set('Aws\Sdk', [], [[
    'region'      => 'us-west-2',
    'version'     => 'latest'
]]);
</code>```

The array within an array looks kind of weird but that's because the parameters array basically goes index by index and set each parameter as positional arguments. Hopefully this helps.

Body:
I'm trying to get a simple web application working with the Yii 2 framework, a DynamoDB database hosted on AWS and the AWS SDK for PHP. I'm just saving/retrieving movie details to/from the database.

(For the purposes of copying code here, I am not going to copy my real AWS key/secret.)

Everything works as I want when I create my Aws\Sdk object like this:

$sdk = new Aws\Sdk([
    'region'   => 'us-west-2',
    'version'  => 'latest',
    'credentials' => [
        'key'     => 'KEYKEYKEYKEYKEYKEYKE',
        'secret'  => 'SECRETSECRETSECRETSECRETSECRETSECRETSECR'
    ]
]);
$dynamodb = $sdk->createDynamoDb();

But I want to take advantage of Yii's default configurations with the Yii::createObject() method, so that I don't have to specify the region, version and credentials every place I create an Aws\Sdk object. So, as per the Yii documentation, I have saved into my application configuration:

\Yii::$container->set('Aws\Sdk', [
    'region'      => 'us-west-2',
    'version'     => 'latest',
    'credentials' => [
        'key'     => 'KEYKEYKEYKEYKEYKEYKE',
        'secret'  => 'SECRETSECRETSECRETSECRETSECRETSECRETSECR'
    ]
]);

and now wherever I create an Aws\Sdk object, my code looks like this:

$sdk = Yii::createObject('Aws\Sdk');
$dynamodb = $sdk->createDynamoDb();

However, when I do it like this, I get an InvalidArgumentException from AWS about "Missing required client configuration options". If I var_dump() the $sdk variable immediately after it is assigned, I can see that the object has the required region, version and credentials attributes, but the next line where I assign the $dynamodb variable throws the exception.

I am hoping that someone can show me where I am going wrong.

Body:
First off you shouldn't be putting credentials in your code. I recommend the following:

If you have this code running on an EC2 instance, instead apply an IAM role to it. With roles you declare exactly what permissions you any CLI/SDK calls that will be running in the instance. When the SDK goes to make a call, it will contact the instance metadata server and get a set of temporary credentials. Of course this happens all transparently without you needing to do anything. As the credentials expire after a period of time (your SDK will of course grab new credentials when this happens transparently). This the best option as you no longer need to worry about credentials, other SDKs or the CLI can use it, and it's all temporary.

Use a credentials file. You should only really do this if your code is outside of AWS territory and cannot utilize IAM roles. While your credentials become more centralized they're at least not part of your code base where they could potentially be leaked. Also it makes it so that you can easily utilize other languages and still have the credentials automatically pulled up.

Now then on to the other part:

\Yii::$container->set('Aws\Sdk', [
    'region'      => 'us-west-2',
    'version'     => 'latest',
    'credentials' => [
        'key'     => 'KEYKEYKEYKEYKEYKEYKE',
        'secret'  => 'SECRETSECRETSECRETSECRETSECRETSECRETSECR'
    ]
]);

This isn't what you think it is, if you look at the source code:

 * If a class definition with the same name already exists, it will be overwritten with the new one.
 * You may use [[has()]] to check if a class definition already exists.
 *
 * @param string $class class name, interface name or alias name
 * @param mixed $definition the definition associated with `$class`. It can be one of the following:
 *
 * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable
 *   should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor
 *   parameters, `$config` the object configuration, and `$container` the container object. The return value
 *   of the callable will be returned by [[get()]] as the object instance requested.
 * - a configuration array: the array contains name-value pairs that will be **used to initialize the property**
 *   **values of the newly created object** when [[get()]] is called. The `class` element stands for the
 *   the class of the object to be created. If `class` is not specified, `$class` will be used as the class name.
 * - a string: a class name, an interface name or an alias name.
 * @param array $params the list of constructor parameters. The parameters will be passed to the class
 * constructor when [[get()]] is called.
 * @return $this the container itself
 */

Note the "**" marked areas. In other words the second parameter is not a set of constructor arguments which is probably what you want, but instead an array of parameters that will be set after your constructor is called. Instead you want your second parameter blank, and the third parameter an array something like:

\Yii::$container->set('Aws\Sdk', [], [[
    'region'      => 'us-west-2',
    'version'     => 'latest'
]]);

The array within an array looks kind of weird but that's because the parameters array basically goes index by index and set each parameter as positional arguments. Hopefully this helps.


问:
How I can upload videos from my iPhone with PHP
I want the user to be able to upload video files to my site from iPhone.

my PHP is here:

```<code> <?php

$allowedExts = array("jpg", "JPG", "jpeg", "JPEG", "gif", "GIF", "png", "PNG", "mp4", "MP4", "mov", "MOV");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

// RANDOM Code
function name_file($length = 20) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$name_file = name_file();
// END RANDOM Code

if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "video/MP4")
|| ($_FILES["file"]["type"] == "video/mov")
|| ($_FILES["file"]["type"] == "video/MOV")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/JPEG")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/GIF")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/PNG")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/JPG")
)
</code>```

The code is work with all extensions except iPhone extension "mov".
Thanks for help :)

答: As documented in Apples developer documentation the MIME type (what PHP calls $_FILES["file"]["type"]) is video/quicktime.

Body:
I want the user to be able to upload video files to my site from iPhone.

my PHP is here:

 <?php

$allowedExts = array("jpg", "JPG", "jpeg", "JPEG", "gif", "GIF", "png", "PNG", "mp4", "MP4", "mov", "MOV");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

// RANDOM Code
function name_file($length = 20) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$name_file = name_file();
// END RANDOM Code

if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "video/MP4")
|| ($_FILES["file"]["type"] == "video/mov")
|| ($_FILES["file"]["type"] == "video/MOV")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/JPEG")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/GIF")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/PNG")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/JPG")
)

The code is work with all extensions except iPhone extension "mov".
Thanks for help :)


问:
Place holder in C#
```<code>   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace switch_calculator
    {
        class Program
        {
            static void Main(string[] args)
            {
                double num1, num2;
                char opt;

                Console.WriteLine("Enter num1");
                num1 = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter num2");
                num2 = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Select the operation you would like to perform" );
       Console.WriteLine("Press \n 'A' for Add \n 'S' for subtraction
\n 'D' for Division \n 'M' for multiplicatiion \n 'R' for Remainder");

                opt = Convert.ToChar(Console.ReadLine());
                switch(opt)
                {
                    case 'A':

                        Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);
                        break;
                }

                Console.ReadLine();

            }
        }
    }
</code>```

Here it's my C# code , I'm very new to programming I was just
wondering can I assign place holder value to other number like
{0},{7} or {1},{3} instead of {0},{1} in the switch case statement
case A ?? can someone pls explain the place holder concept here ?

答:
No, the placeholders require a number that indexes from the first argument after the format string, zero-based.

So Console.WriteLine("Hello, {0}!", "World") will print "Hello, World!", and Console.WriteLine("Hello, {1}!", "ignored", "World") will print the same.

You can't index into arguments that don't exist.

I guess you want to change for example the word "Add" for each operation, without having to repeat the entire format string.

You could do that by preparing a string with all the proper placeholders, and then assign them in the proper case block:

```<code>string format = "Your {0} result is {1} {2} {3} = {4}";

string operation = "";
string symbol = "";
double result = 0;

switch(opt)
{
    case 'A':
        operation = "Add";
        symbol = "+";
        result = num1 + num2;
        break;
    case 'S':
        operation = "Subtract";
        symbol = "-";
        result = num1 - num2;
        break;
    break;
    ...
}
</code>```

Now you can print the whole line:

```<code>string format = "Your {0} result is {1} {2} {3} = {4}";

...

Console.WriteLine(format, operation, num1, symbol, num2, result);
</code>```

Title: Place holder in C#

Body:
   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace switch_calculator
    {
        class Program
        {
            static void Main(string[] args)
            {
                double num1, num2;
                char opt;

                Console.WriteLine("Enter num1");
                num1 = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter num2");
                num2 = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Select the operation you would like to perform" );
       Console.WriteLine("Press \n 'A' for Add \n 'S' for subtraction
\n 'D' for Division \n 'M' for multiplicatiion \n 'R' for Remainder");

                opt = Convert.ToChar(Console.ReadLine());
                switch(opt)
                {
                    case 'A':

                        Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);
                        break;
                }

                Console.ReadLine();

            }
        }
    }

Here it's my C# code , I'm very new to programming I was just
wondering can I assign place holder value to other number like
{0},{7} or {1},{3} instead of {0},{1} in the switch case statement
case A ?? can someone pls explain the place holder concept here ?

Body:
No, the placeholders require a number that indexes from the first argument after the format string, zero-based.

So Console.WriteLine("Hello, {0}!", "World") will print "Hello, World!", and Console.WriteLine("Hello, {1}!", "ignored", "World") will print the same.

You can't index into arguments that don't exist.

I guess you want to change for example the word "Add" for each operation, without having to repeat the entire format string.

You could do that by preparing a string with all the proper placeholders, and then assign them in the proper case block:

string format = "Your {0} result is {1} {2} {3} = {4}";

string operation = "";
string symbol = "";
double result = 0;

switch(opt)
{
    case 'A':
        operation = "Add";
        symbol = "+";
        result = num1 + num2;
        break;
    case 'S':
        operation = "Subtract";
        symbol = "-";
        result = num1 - num2;
        break;
    break;
    ...
}

Now you can print the whole line:

string format = "Your {0} result is {1} {2} {3} = {4}";

...

Console.WriteLine(format, operation, num1, symbol, num2, result);


问:
c++ new and delete overloading
new and delete operator overloading might or might not work when compiled using different compilers and different c++ standards. Is that the normal behavior?

I used the following code to test the compilers.

```<code>#include <iostream>

void * operator new(size_t size)
{
    std::cout << "1\n";
    return malloc(size);
}

void operator delete(void *ptr) noexcept
{
    std::cout << "2\n";
    free(ptr);
}

int main(void)
{
    int *n1 = new int;
    delete n1;

    int *n2 = new int[10];
    delete[] n2;

    return 0;
}
</code>```

Here are the results I got from several compilers I have tested the code on.

mingw-w64 official build - x86_64-7.1.0-release-posix-seh-rt_v5-rev0.7z

```<code>c++11
1
2

c++14
1
</code>```

clang x86_64 - v4.0.0 manually built without patches using the compiler above

```<code>c++11 and c++14
1
2
</code>```

msvc - platform toolset v141 & sdk v10.0.15063.0

```<code>/std:c++14 and /std:c++latest
1
2
1
2
</code>```

All tests are performed on Windows 7. I can't test compilers on GNU/Linux OS because I don't have any VMs set up.

答:
By the standard, the default behavior of both operator new[] is ([new.delete.array]/4):

Returns operator new(size), or operator new(size, alignment), respectively.

Something similar goes for operator delete[] ([new.delete.array]/15):

The functions that have a size parameter forward their other parameters to the corresponding function without a size parameter. The functions that do not have a size parameter forward their parameters to the corresponding operator delete (single-object) function.

The default versions of these functions simply call the non-array forms. Therefore, Visual Studio and GCC 6.3 are correct: overloading just the non-array versions should be enough to overload the allocators.

Title: c++ new and delete overloading

Body:
new and delete operator overloading might or might not work when compiled using different compilers and different c++ standards. Is that the normal behavior?

I used the following code to test the compilers.

#include <iostream>

void * operator new(size_t size)
{
    std::cout << "1\n";
    return malloc(size);
}

void operator delete(void *ptr) noexcept
{
    std::cout << "2\n";
    free(ptr);
}

int main(void)
{
    int *n1 = new int;
    delete n1;

    int *n2 = new int[10];
    delete[] n2;

    return 0;
}

Here are the results I got from several compilers I have tested the code on.

mingw-w64 official build - x86_64-7.1.0-release-posix-seh-rt_v5-rev0.7z

c++11
1
2

c++14
1

clang x86_64 - v4.0.0 manually built without patches using the compiler above

c++11 and c++14
1
2

msvc - platform toolset v141 & sdk v10.0.15063.0

/std:c++14 and /std:c++latest
1
2
1
2

All tests are performed on Windows 7. I can't test compilers on GNU/Linux OS because I don't have any VMs set up.


问:
C++ Binary >> no operator found which takes a right hand operand type of const char error
im trying to learn c++ and can't figure out the reason for this error it seems to match up with my other cout lines that aren't getting any errors </p>

```<code>#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    int number = 42;
    int guess;
    bool notguessed = true;
    while (notguessed);

    cout << "Guess my number";
    cin  >> "Guess";
    if (guess == number)
    {
        cout << "You got it" << endl;
        notguessed = false;
    }
    if (guess < number)
    {
        cout << "To low try again" << endl;
    }
    if (guess > number)
    {
        cout << "To high try again" << endl;
    }

    return 0;
}
</code>```

答:
Try this code :-

```<code># your code goes here
#include <iostream>
using namespace std;

int main()
{
    int number = 42;
    int guess;
    bool notguessed = true;
    cout << "Guess my number";
    while (notguessed)
    {
        cin  >> guess;
        if (guess == number)
        {
            cout << "You got it" << endl;
            notguessed = false;
        }
        if (guess < number)
        {
            cout << "To low try again" << endl;
        }
        if (guess > number)
        {
            cout << "To high try again" << endl;
        }
    }
    return 0;
}
</code>```

You were trying to input a string "Guess". Change that to cin>>guess.
And change the while loop semicolon.

Body:
im trying to learn c++ and can't figure out the reason for this error it seems to match up with my other cout lines that aren't getting any errors

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    int number = 42;
    int guess;
    bool notguessed = true;
    while (notguessed);

    cout << "Guess my number";
    cin  >> "Guess";
    if (guess == number)
    {
        cout << "You got it" << endl;
        notguessed = false;
    }
    if (guess < number)
    {
        cout << "To low try again" << endl;
    }
    if (guess > number)
    {
        cout << "To high try again" << endl;
    }

    return 0;
}

Body:
Try this code :-

# your code goes here
#include <iostream>
using namespace std;

int main()
{
    int number = 42;
    int guess;
    bool notguessed = true;
    cout << "Guess my number";
    while (notguessed)
    {
        cin  >> guess;
        if (guess == number)
        {
            cout << "You got it" << endl;
            notguessed = false;
        }
        if (guess < number)
        {
            cout << "To low try again" << endl;
        }
        if (guess > number)
        {
            cout << "To high try again" << endl;
        }
    }
    return 0;
}

You were trying to input a string "Guess". Change that to cin>>guess.
And change the while loop semicolon.


问:
Filling in missing data using populated row in Pandas dataframe
I have a dataframe that is missing data in a particular column. For a concrete example, take it to be df below.

```<code>my_list = ["A", " ",31, "A", 5,32, " " ,5, 35, "B", " " , 14, "B", 4, 23, " " , 4, 26, "B", 7, 25, " ", 7, 15]
df = pd.DataFrame(np.array(my_list).reshape(8,3), columns = list("xyz"))
</code>```

which looks like

```<code>   x  y   z
0  A     31
1  A  5  32
2     5  35
3  B     14
4  B  4  23
5     4  26
6  B  7  25
7     7  15
</code>```

The missing data might not necessarily be arranged as conveniently as above.

What I want to do is populate all the empty cells in column x from the case where both column x and y are populated. In the df above, for row 1, y=5 is associated with x = "A". So when I go to row 2, I will populate the x with "A". The x to y relationship should be one-to-many. So different values of y can be associated to the same valueof x. However, the y to x relationship should be unique. The desired end result is

```<code>   x  y   z
0  A     31
1  A  5  32
2  A  5  35
3  B     14
4  B  4  23
5  B  4  26
6  B  7  25
7  B  7  15
</code>```

I have two questions here:

How do I check the relationship that x-to-y is indeed one-to-many?

If the relationship holds, how do I then populate the missing cells in column x with the reference row where both x and y are populated?

I tried looping over the rows and picking up the x and y column values to form a dictionary with y being the key and x the value. Then armed with the dictionary, I looped through the dataframe again to populate column x. Is there a more Pandas efficient way of doing it?

答:
How about, grouping on y and shifting x values, and set values of df where x == ' ' ?

```<code>In [31]: df.loc[df.x == ' ', 'x'] = df.groupby(['y'])['x'].transform('shift')

In [32]: df
Out[32]:
   x  y   z
0  A     31
1  A  5  32
2  A  5  35
3  B     14
4  B  4  23
5  B  4  26
6  B  7  25
7  B  7  15
</code>```

Body:
I have a dataframe that is missing data in a particular column. For a concrete example, take it to be df below.

my_list = ["A", " ",31, "A", 5,32, " " ,5, 35, "B", " " , 14, "B", 4, 23, " " , 4, 26, "B", 7, 25, " ", 7, 15]
df = pd.DataFrame(np.array(my_list).reshape(8,3), columns = list("xyz"))

which looks like

   x  y   z
0  A     31
1  A  5  32
2     5  35
3  B     14
4  B  4  23
5     4  26
6  B  7  25
7     7  15

The missing data might not necessarily be arranged as conveniently as above.

What I want to do is populate all the empty cells in column x from the case where both column x and y are populated. In the df above, for row 1, y=5 is associated with x = "A". So when I go to row 2, I will populate the x with "A". The x to y relationship should be one-to-many. So different values of y can be associated to the same valueof x. However, the y to x relationship should be unique. The desired end result is

   x  y   z
0  A     31
1  A  5  32
2  A  5  35
3  B     14
4  B  4  23
5  B  4  26
6  B  7  25
7  B  7  15

I have two questions here:

How do I check the relationship that x-to-y is indeed one-to-many?

If the relationship holds, how do I then populate the missing cells in column x with the reference row where both x and y are populated?

I tried looping over the rows and picking up the x and y column values to form a dictionary with y being the key and x the value. Then armed with the dictionary, I looped through the dataframe again to populate column x. Is there a more Pandas efficient way of doing it?

Body:
How about, grouping on y and shifting x values, and set values of df where x == ' ' ?

In [31]: df.loc[df.x == ' ', 'x'] = df.groupby(['y'])['x'].transform('shift')

In [32]: df
Out[32]:
   x  y   z
0  A     31
1  A  5  32
2  A  5  35
3  B     14
4  B  4  23
5  B  4  26
6  B  7  25
7  B  7  15


问:
Load/Deserialize faster Json data to C# object
In my code I use Newtonsoft.Json :

```<code>MyCSharpTargetClass foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);
</code>```

The content of the json_string is constant (loaded from a file that never changes).

The functionality is fine but the deserializing process is slow at execution.

My question: is there a way to pre-calculate the object, or to put it in a constant*, or whatever to speed up the execution ?

Note: Actually I didn't manage to put it a constant the result of JsonConvert.DeserializeObject<...>(), but I'm new to C#, so I should have missed something.

Thanks for your help

[EDIT] Solution : Force the Newtonsoft assembly to be loaded at the start of the application.

答:
You do it the same way you would any other object: make it a private member variable, whose value is computed exactly once:

```<code>private static readonly MyCSharpTargetClass foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);
</code>```

Or do it in the constructor:

```<code>private readonly MyCSharpTargetClass foo;

public MyObject()
{
    foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);
}
</code>```

That way the work to deserialize the string is done exactly once.

Body:
In my code I use Newtonsoft.Json :

MyCSharpTargetClass foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);

The content of the json_string is constant (loaded from a file that never changes).

The functionality is fine but the deserializing process is slow at execution.

My question: is there a way to pre-calculate the object, or to put it in a constant*, or whatever to speed up the execution ?

Note: Actually I didn't manage to put it a constant the result of JsonConvert.DeserializeObject<...>(), but I'm new to C#, so I should have missed something.

Thanks for your help

[EDIT] Solution : Force the Newtonsoft assembly to be loaded at the start of the application.

Body:
You do it the same way you would any other object: make it a private member variable, whose value is computed exactly once:

private static readonly MyCSharpTargetClass foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);

Or do it in the constructor:

private readonly MyCSharpTargetClass foo;

public MyObject()
{
    foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);
}

That way the work to deserialize the string is done exactly once.


问:
defining a new function in nodejs throws reference error
i have a .js file as follows:

```<code>module.exports = {
    metadata: () => ({
        "name": "HrScheduleApi",
        "properties": {
             "scheduleDate": {"type": "string", "required": false}
        }
    }),
    invoke: (conversation, done) => {
        var actionType = conversation.properties().actionType;
        logger.info("start of HrScheduleApi with action type:" + actionType);

       if(isBeyondThreeDays(scheduleDate)  == false){
                dayFromNow = '2 days from now';
                var tomorrow = new Date(new Date().getTime() + 48 * 60 * 60 * 1000);
                schDate = tomorrow.toDateString();
             }else{
                 console.log('asked schedule is beyond 48 hours');
             }
    },
    isBeyondThreeDays: (scheduleDate) => {
        // ...
    }
};
</code>```

so when i needed a new function (isBeyondThreeDays) in my invoke function i just defined as below. but seems nodejs does not like it. I get the error
at run time as:

```<code>Error in component, details={}
ReferenceError: isBeyondThreeDays is not defined
</code>```

答:
I guess this one

```<code>if(isBeyondThreeDays(scheduleDate)  == false){
</code>```

should be

```<code>if(module.exports.isBeyondThreeDays(scheduleDate)  == false){
</code>```

Or

```<code>const myModule = { ... your methods}
</code>```

and

```<code>if(myModule.isBeyondThreeDays(scheduleDate)  == false){

...

module.exports = myModule
</code>```

Body:
i have a .js file as follows:

module.exports = {
    metadata: () => ({
        "name": "HrScheduleApi",
        "properties": {
             "scheduleDate": {"type": "string", "required": false}
        }
    }),
    invoke: (conversation, done) => {
        var actionType = conversation.properties().actionType;
        logger.info("start of HrScheduleApi with action type:" + actionType);

       if(isBeyondThreeDays(scheduleDate)  == false){
                dayFromNow = '2 days from now';
                var tomorrow = new Date(new Date().getTime() + 48 * 60 * 60 * 1000);
                schDate = tomorrow.toDateString();
             }else{
                 console.log('asked schedule is beyond 48 hours');
             }
    },
    isBeyondThreeDays: (scheduleDate) => {
        // ...
    }
};

so when i needed a new function (isBeyondThreeDays) in my invoke function i just defined as below. but seems nodejs does not like it. I get the error
at run time as:

Error in component, details={}
ReferenceError: isBeyondThreeDays is not defined

Body:
I guess this one

if(isBeyondThreeDays(scheduleDate)  == false){

should be

if(module.exports.isBeyondThreeDays(scheduleDate)  == false){

Or

const myModule = { ... your methods}

and

if(myModule.isBeyondThreeDays(scheduleDate)  == false){

...

module.exports = myModule


问:
Calling function in a mxml component from a main flex application
In my main application I have a viewstack with 3 child views. In the viewstack change handler, I programmatically change the selectedchild property.

I understand that the initialize method for the view is not called every time I change the selectedChild Property. So I tried to invoke the init method programmatically too..

view1.mxml

```<code>    <fx:Script>
    <![CDATA[
    public function init():void{
     //something
    }
    ]]>
    </fx:Script>
</code>```

main.mxml

```<code>viewStack.selectedChild = viewStack.getChildByName("viewname") as NavigatorContent;
var v1:view1 = new view1();
v1.init();
</code>```

But I get a null pointer error. Am I missing anything?
Any help would be appreciated. I am a beginner here.

答:
In your main.mxml app, you are creating a new instance of the view1 component and what you need is to execute the init() method of the current instance of the viewstack.

Why don't you try doing somethig like this:

var view:View1 = viewStack.getChildByName("viewname").getChildByName("yourComponentId") as View1;

view.init();

where yourComponentId is your component inside the navigatorContent inside your Viewstack.

Anyway you should't be doing this, at least not this way.

Greetings!

Gabriel.-

Body:
In my main application I have a viewstack with 3 child views. In the viewstack change handler, I programmatically change the selectedchild property.

I understand that the initialize method for the view is not called every time I change the selectedChild Property. So I tried to invoke the init method programmatically too..

view1.mxml

    <fx:Script>
    <![CDATA[
    public function init():void{
     //something
    }
    ]]>
    </fx:Script>

main.mxml

viewStack.selectedChild = viewStack.getChildByName("viewname") as NavigatorContent;
var v1:view1 = new view1();
v1.init();

But I get a null pointer error. Am I missing anything?
Any help would be appreciated. I am a beginner here.


问:
How to execute maven plugins from gradle without having maven and java installed
I need to execute a maven plugin on a system that does not have both maven and java installed and installing both of them on the system is not an option. While searching for the ways, I found out that by using gradle we can build executable binaries that does not even require gradle to get executed, which perfectly fits my situation :) . Is there any way to execute maven plugins by using gradle. Thanks in advance

答:
Gradle is a build system. You can build anything with it, including native binaries.

And yes, you can call Maven Plugins from Gradle, as Maven Plugins are written in Java and Gradle is based on Groovy and thus on Java.

But both facts have nothing to do with each other.

You can of course also use Gradle (or any other build system including manually stuffing things together) to build a distributable that includes a Java runtime environment. But then Java is, as said, shipped with your result. You cannot run Java code without having Java around, besides porting the Java code to something else like C++ that compiles to a native binary.

Yes, you can also call Java code from native code if you do some glueing, but no, also this will not work without having Java around, because that's the way Java works.


问:
Replace a certain character in WooCommerce cart item variations title by a pipe
How to remove a comma separation from product attribute on my checkout.

Example:

```<code>Blue Black Raw Denim - 37, Slimfit
</code>```

37 is attribute product and slimfit is model product I want remove comma or replace with |. how can I do that?

For cart code like this :

```<code><td class="product-name" data-title="<?php esc_attr_e( 'Product', 'woocommerce' ); ?>">
    <?php
      if ( ! $product_permalink ) {
        echo apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key ) . ' ';
      } else {
        echo apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key );
      }
</code>```

If I delete this part item product name and attribute will gone but instead gone.
 I want replace comma with a |...

How can I achieve this?

Thanks

Reference Image:

答:
So you should use a custom function hooked in woocommerce_cart_item_name filter hook, where you will replace the coma by a pipe using str_replace() php function, this way:

```<code>// Tested on WooCommerce version 3+
add_filter( 'woocommerce_cart_item_name', 'custom_item_name', 10, 3 );
function custom_item_name( $item_name, $cart_item, $cart_item_key ){
    $new_item_name = str_replace(',', ' |', $item_name);
    return $new_item_name;
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works. It will replace the coma by a pipe in cart and checkout items title.

Related answer: WooCommerce 3.0 - hide variation info in product title

Body:
How to remove a comma separation from product attribute on my checkout.

Example:

Blue Black Raw Denim - 37, Slimfit

37 is attribute product and slimfit is model product I want remove comma or replace with |. how can I do that?

For cart code like this :

<td class="product-name" data-title="<?php esc_attr_e( 'Product', 'woocommerce' ); ?>">
    <?php
      if ( ! $product_permalink ) {
        echo apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key ) . ' ';
      } else {
        echo apply_filters( 'woocommerce_cart_item_name', sprintf( '%s', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key );
      }

If I delete this part item product name and attribute will gone but instead gone.
 I want replace comma with a |...

How can I achieve this?

Thanks

Reference Image:

Body:
So you should use a custom function hooked in woocommerce_cart_item_name filter hook, where you will replace the coma by a pipe using str_replace() php function, this way:

// Tested on WooCommerce version 3+
add_filter( 'woocommerce_cart_item_name', 'custom_item_name', 10, 3 );
function custom_item_name( $item_name, $cart_item, $cart_item_key ){
    $new_item_name = str_replace(',', ' |', $item_name);
    return $new_item_name;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works. It will replace the coma by a pipe in cart and checkout items title.

Related answer: WooCommerce 3.0 - hide variation info in product title


问:
Trying to get the element in xslt 1.0.But unable to get in response xml
Reqeust xml is attached

```<code><xsl:if test="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:id/evt0:idContext/evt0:value">
        <tns:projectIdentifier>

                        <tns:idContext>
                                                            <tns:value>
                                    <xsl:value-of
                                        select="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:id/evt0:idContext/evt0:value" />
                                </tns:value>
                                </tns:idContext>
                                                    [Response xsd attached][2]

                </tns:projectIdentifier>
</code>```

This is the xsl code that is written but not working

答:
I solved it like this:

```<code><xsl:if test="../../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:idContext/evt0:value">
</code>```

I kept everything else unchanged.

Body:
Reqeust xml is attached

<xsl:if test="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:id/evt0:idContext/evt0:value">
        <tns:projectIdentifier>

                        <tns:idContext>
                                                            <tns:value>
                                    <xsl:value-of
                                        select="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:id/evt0:idContext/evt0:value" />
                                </tns:value>
                                </tns:idContext>
                                                    [Response xsd attached][2]

                </tns:projectIdentifier>

This is the xsl code that is written but not working

Body:
I solved it like this:

<xsl:if test="../../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:idContext/evt0:value">

I kept everything else unchanged.


问:
JPA 2, JSF, setting id of OneToOne mapped entity problem
we havent used JPA or any other ORM tools in our web application, now we have been on updating whole stuff to Java EE 6,

my problem about is JPA
,i have been looking for an answer,and learn how people solve that kinda issue,
i have 2 entites,

```
<code>
@Entity Person
{
@Id
private long id;

@JoinColumn(name="CITY_ID")
@OneToOne(fetch=FetchType.LAZY)
private City city;
....
}

</code>
```

and my second entity

```

@Entity City
{
@Id
private long id;
private String name;
.....
}
```

i am querying person entity and i show one on my jsf page

i have 2 input fields for Person.city to show on my jsf page
inputhidden for id and inputtext for name
people are selecting cities from a popup then
i set hidden  component for city id, with new selected new value,
and the same for name,
everthing goes fine till now,
when i merge Person Entity, it tries to merge City also, but with an id already defined on table, so constraint error for Cirty Id.

what are you doing for this kinda problem?

i thought valueChange action for inputHidden,but at jsf Life cycle it happens before update model so even if i replace Person.City entity with new one in action ,
it will updated again (actually with the same values but it will be done twice)
,So what is the best workaround for this situation?

thanx

答: You are trying to save a new Person and assign it to an existing City? If so, and if you are using PersistantManager.persist(person) than it tries to create a new City, which fails. You can tell the relationship from Person to City what options to follow, see Cascading (MERGE in your case i guess). </p>

Body:
we havent used JPA or any other ORM tools in our web application, now we have been on updating whole stuff to Java EE 6,

my problem about is JPA
,i have been looking for an answer,and learn how people solve that kinda issue,
i have 2 entites,

@Entity Person
{
@Id
private long id;

@JoinColumn(name="CITY_ID")
@OneToOne(fetch=FetchType.LAZY)
private City city;
....
}

and my second entity

@Entity City
{
@Id
private long id;
private String name;
.....
}

i am querying person entity and i show one on my jsf page

i have 2 input fields for Person.city to show on my jsf page
inputhidden for id and inputtext for name
people are selecting cities from a popup then
i set hidden  component for city id, with new selected new value,
and the same for name,
everthing goes fine till now,
when i merge Person Entity, it tries to merge City also, but with an id already defined on table, so constraint error for Cirty Id.

what are you doing for this kinda problem?

i thought valueChange action for inputHidden,but at jsf Life cycle it happens before update model so even if i replace Person.City entity with new one in action ,
it will updated again (actually with the same values but it will be done twice)
,So what is the best workaround for this situation?

thanx


问:
GPS location not displayed on button click
I am trying to get the gps location through a button click.
The code is given below :

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

protected LocationManager locationManager;

protected Button retrieveLocationButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;

    }

    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MINIMUM_TIME_BETWEEN_UPDATES,
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );

    retrieveLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
    });

}

protected void showCurrentLocation() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;
    }
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();
    }

}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}
</code>```

}

The problem here is that the Toast is not getting displayed where the location i.e. latitude and longitude is displayed. I have added the runtime permission for API level 23. I have also added the following permissions in the manifest file :

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</code>```

Thank you for your help :)

答:
I solved it by adding onRequestPermissionsResult.. above the MyLocationListener class. The code below is the corrected code :

MainActivity.java

public class MainActivity extends AppCompatActivity {

```<code>private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

protected LocationManager locationManager;

protected Button retrieveLocationButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;

    }

    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MINIMUM_TIME_BETWEEN_UPDATES,
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );

    retrieveLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
    });

}

protected void showCurrentLocation() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;
    }
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode==1252){
        if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
            Log.i("Permission Granted : ", String.valueOf(grantResults));

        }
    }
}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}
</code>```

}

Thank you @Pavneet_Singh

Body:
I am trying to get the gps location through a button click.
The code is given below :

MainActivity.java

public class MainActivity extends AppCompatActivity {

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

protected LocationManager locationManager;

protected Button retrieveLocationButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;

    }

    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MINIMUM_TIME_BETWEEN_UPDATES,
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );

    retrieveLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
    });

}

protected void showCurrentLocation() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;
    }
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();
    }

}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}

}

The problem here is that the Toast is not getting displayed where the location i.e. latitude and longitude is displayed. I have added the runtime permission for API level 23. I have also added the following permissions in the manifest file :

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Thank you for your help :)

Body:
I solved it by adding onRequestPermissionsResult.. above the MyLocationListener class. The code below is the corrected code :

MainActivity.java

public class MainActivity extends AppCompatActivity {

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

protected LocationManager locationManager;

protected Button retrieveLocationButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;

    }

    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MINIMUM_TIME_BETWEEN_UPDATES,
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );

    retrieveLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
    });

}

protected void showCurrentLocation() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;
    }
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode==1252){
        if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
            Log.i("Permission Granted : ", String.valueOf(grantResults));

        }
    }
}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}

}

Thank you @Pavneet_Singh


问:
List of fonts that can be used with SpriteKit's labelNodeWithFontNamed method
How can I get the list of font names that can be used with SpriteKit's labelNodeWithFontNamed method?

There is a method of SKLabelNode where I can specify the font name but I would like to know which fonts are supported and what are their names.

Example:

```<code>[SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
</code>```

答:
Try to get your fonts with names by this code:</p>

```<code>for (NSString* family in [UIFont familyNames]) {
    NSLog(@"%@",family);
    for (NSString* name in [UIFont fontNamesForFamilyName:family]) {
        NSLog(@"--- %@",name);
    }
}
</code>```

Body:
How can I get the list of font names that can be used with SpriteKit's labelNodeWithFontNamed method?

There is a method of SKLabelNode where I can specify the font name but I would like to know which fonts are supported and what are their names.

Example:

[SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];

Body:
Try to get your fonts with names by this code:

for (NSString* family in [UIFont familyNames]) {
    NSLog(@"%@",family);
    for (NSString* name in [UIFont fontNamesForFamilyName:family]) {
        NSLog(@"--- %@",name);
    }
}


问:
Hide value in filter - Tableau
I have a problem with Filters.

I have a dimension with the values (0, 1, 2, 3, 4, 5).
I want to use this dimension as a filter, but not to let the user the option to filter out the value "0".
I don't want to exclude the values 0, the opposite - I want these values to ALWAYS be in the view, and let the user the chance to filter only between (1, 2, 3, 4, 5).

Is that an option? To remove a value from the filter but not from the data?

Any help would be very appreciated
Thank you!!

答:
If I understood your question correctly then my answer is - Yes, there is a way to do so.

Let's say your dimension name is 'dim_field' having value (0, 1, 2, 3, 4, 5) then

Create a parameter - let's name it as 'parm_field'. In create parameter window select 'data type' as string, 'Allowable values' as list, 'set from field' as dim_field (i.e. you dimension) and add one more row in this list as 'All'. Drag this row to top and select 'current value' as 'All'. Most importantly delete row having '0', as you don't want this to be in your filter and click ok.

Click on this parameter and select 'Show Parameter Control'

Create a calculated field 'is_DimField_selected' and define it as:

```<code>IF [parm_field] == 'All' THEN 'Y'
ELSE
  IF [parm_field]=[dim_field] THEN 'Y'
  ELSE 'N'
  END
END
</code>```

Add this calculated field to filter and select 'Y'. Voila!

Kindly don't forget to mark as answer if it solves your problem ;)

Title: Hide value in filter - Tableau

Body:
If I understood your question correctly then my answer is - Yes, there is a way to do so.

Let's say your dimension name is 'dim_field' having value (0, 1, 2, 3, 4, 5) then

Create a parameter - let's name it as 'parm_field'. In create parameter window select 'data type' as string, 'Allowable values' as list, 'set from field' as dim_field (i.e. you dimension) and add one more row in this list as 'All'. Drag this row to top and select 'current value' as 'All'. Most importantly delete row having '0', as you don't want this to be in your filter and click ok.

Click on this parameter and select 'Show Parameter Control'

Create a calculated field 'is_DimField_selected' and define it as:

IF [parm_field] == 'All' THEN 'Y'
ELSE
  IF [parm_field]=[dim_field] THEN 'Y'
  ELSE 'N'
  END
END

Add this calculated field to filter and select 'Y'. Voila!

Kindly don't forget to mark as answer if it solves your problem ;)


问:
sed & protobuf: need to delete dots
I need to delete dots using sed, but not all dots.

```<code>- repeated .CBroadcast_GetBroadcastChatUserNames_Response.PersonaName persona_names = 1
+ repeated CBroadcast_GetBroadcastChatUserNames_Response.PersonaName persona_names = 1
</code>```

Here the dot after repeated, (repeated also can beoptional | required | extend) should be deleted

```<code>- rpc NotifyBroadcastViewerState (.CBroadcast_BroadcastViewerState_Notification) returns (.NoResponse)
+ rpc NotifyBroadcastViewerState (CBroadcast_BroadcastViewerState_Notification) returns (NoResponse)
</code>```

And here delete dot after (

It should work on multiple files with different content.

Full code can be found here

答:
Assuming only the leading . needs removal, here's some GNU sed code:

```<code>echo '.a_b.c c.d  (.e_f.g) ' |
sed 's/^/& /;s/\([[:space:]{([]\+\)\.\([[:alpha:]][[:alpha:]_.]*\)/\1\2/g;s/^ //'
</code>```

Output:

```<code>a_b.c c.d  (e_f.g)
</code>```

Besides the ., it checks for two fields, which are left intact:

Leading whitespace, or any opening (, [, or {.

Trailing alphabetical chars or also _ or ..

Unfortunately, while the \+ regexp matches one or more spaces et al, it fails if the . is at the beginning of the line.  (Replacing the \* with a '*' would match the beginning, but would incorrectly change c.d to cd.)  So there's a kludge...  s/^/& / inserts a dummy space at the beginning of the line, that way the \+ works as desired, then a s/^ // removes the dummy space.

Title: sed & protobuf: need to delete dots

Body:
I need to delete dots using sed, but not all dots.

- repeated .CBroadcast_GetBroadcastChatUserNames_Response.PersonaName persona_names = 1
+ repeated CBroadcast_GetBroadcastChatUserNames_Response.PersonaName persona_names = 1

Here the dot after repeated, (repeated also can beoptional | required | extend) should be deleted

- rpc NotifyBroadcastViewerState (.CBroadcast_BroadcastViewerState_Notification) returns (.NoResponse)
+ rpc NotifyBroadcastViewerState (CBroadcast_BroadcastViewerState_Notification) returns (NoResponse)

And here delete dot after (

It should work on multiple files with different content.

Full code can be found here

Body:
Assuming only the leading . needs removal, here's some GNU sed code:

echo '.a_b.c c.d  (.e_f.g) ' |
sed 's/^/& /;s/\([[:space:]{([]\+\)\.\([[:alpha:]][[:alpha:]_.]*\)/\1\2/g;s/^ //'

Output:

a_b.c c.d  (e_f.g)

Besides the ., it checks for two fields, which are left intact:

Leading whitespace, or any opening (, [, or {.

Trailing alphabetical chars or also _ or ..

Unfortunately, while the \+ regexp matches one or more spaces et al, it fails if the . is at the beginning of the line.  (Replacing the \* with a '*' would match the beginning, but would incorrectly change c.d to cd.)  So there's a kludge...  s/^/& / inserts a dummy space at the beginning of the line, that way the \+ works as desired, then a s/^ // removes the dummy space.


答:
```<code>cin  >> "Guess";
</code>```

should be

```<code>cin >> guess;
</code>```

Title: C++ Binary >> no operator found which takes a right hand operand type of const char error

Body:
im trying to learn c++ and can't figure out the reason for this error it seems to match up with my other cout lines that aren't getting any errors

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    int number = 42;
    int guess;
    bool notguessed = true;
    while (notguessed);

    cout << "Guess my number";
    cin  >> "Guess";
    if (guess == number)
    {
        cout << "You got it" << endl;
        notguessed = false;
    }
    if (guess < number)
    {
        cout << "To low try again" << endl;
    }
    if (guess > number)
    {
        cout << "To high try again" << endl;
    }

    return 0;
}

Body:
cin  >> "Guess";

should be

cin >> guess;


问:
iPad IOS 4.2 popViewControllerAnimated animation is now vertical
When I updated iPad to iOS 4.2.1 animation for popViewControllerAnimated suddenly changed from slide left to right to vertical slide top to bottom. The pushViewControllerAnimated works as expected.</p>

```<code>- (void)back
{
    if ([self currentLevel] > 0)
    {
        [[self navigationController] popViewControllerAnimated:YES];
        [[self model]setSlideDirection:kBackward];
        [[self model]setSlideNum:[self currentLevel] - 1];

    }
}
</code>```

答: I guess I have found at least one solution - since it now works for me. Does your NavigationController override ShouldAutorotateToInterfaceOrientation? If so ensure that all "child" view controller you push / pop from / to the navigation stack also override ShouldAutorotateToInterfaceOrientation with the same result! </p>

Body:
When I updated iPad to iOS 4.2.1 animation for popViewControllerAnimated suddenly changed from slide left to right to vertical slide top to bottom. The pushViewControllerAnimated works as expected.

- (void)back
{
    if ([self currentLevel] > 0)
    {
        [[self navigationController] popViewControllerAnimated:YES];
        [[self model]setSlideDirection:kBackward];
        [[self model]setSlideNum:[self currentLevel] - 1];

    }
}


问:
Service fabric and WCF
We are planning to redesign our services to micro services using service fabric, I have some questions that I hope you can help me with, here we go:

Communication Stack

All our services are on WCF using net.tcp so in theory we can reuse the  WCF Communication stack but I'm not sure that's the best way, what are the differences between the default communication stack and the WCF one?

Extensibility

We have a lot of implementation using the extensibility points of WCF, if we choose the WCF communication stack can we still use this? We are basically using IServiceBehavior,IOperationInvoker, OperationContext and ServiceSecurityContext for this:

1. Security ServiceSecurityContext/OperationContext to get the IP and if the call is in the intranet the domain account who is making the call, I checked in StatelessServiceContext but could not find any property where i could get this info.

2. Parameters and time IOperationInvoker to log the parameters of the method and how much it took to finish the operation, reading this it appears that if implement the Start/Stop methods the time duration is done automatically, what I'm not sure is if this will work in the context of an attribute and with IErrorHandler when an error happens.

3. Notifications IErrorHandler to log the exception and then send an email to the developer team, we are currently doing this using an SMTP server, is there a better way to send notifications in azure?.

Thanks for your time

答:
Answering this:

Communication Stack
Never did a comparison in performance between the default listener and WcfCommunicationListener but we opted for WCF to reuse all our components and as a first version to understand how service fabric works.

Extensibility

Security All the code worked the same, we needed to make some changes to the way the context works, but all the info needed was there (plus some data on the node it was running)

Parameters and time We used Azure Service Profiler with our own implementation of Microsoft.Diagnostics.Tracing.EventSource capturing the data  using IOperationInvoker, awesome

Notifications IErrorHandler continued to work but we used sendgrid for the emails.

Title: Service fabric and WCF


问:
PDFsharp DrawString Text Invisible for certain PDF
The system I am working on stamps PDF's with certain information. It does this by creating a lime green text box in the top right corner of the document. It then draws a certain string on top of the green space. This works for thousands of PDFs but for one the text is invisible even though the box is drawn. I can still select the text and copy it to something else, but it is invisible in the PDF.

Unfortunately, I cannot share the PDF but it is a PDF 1.4. What would cause this?

The code for stamping:

```<code>    private static XGraphics drawString(XGraphics xgr, PdfPage page, string printString, int pageNumber = 0)
    {
        XFont font = new XFont("Verdana", 10, XFontStyle.BoldItalic);

        var textSize = xgr.MeasureString(printString, font);
        var width = textSize.Width;
        var height = textSize.Height;

        double xMin = 0;
        double yMin = 0;

        if (page.Rotate == 90)
        {
            xMin = page.Height - textSize.Width;
            var state = xgr.Save();
            xgr.DrawRectangle(XBrushes.LimeGreen, xMin, yMin, width, height);
            xgr.Restore(state);
            xgr.DrawString(printString, font, XBrushes.Black, new XRect(0, 0, page.Height, page.Width), topRight());
        }
        else
        {
            xMin = page.Width - textSize.Width;
            var state = xgr.Save();
            xgr.DrawRectangle(XBrushes.LimeGreen, xMin, yMin, width, height);
            xgr.Restore(state);
            xgr.DrawString(printString, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), topRight());
        }

        return xgr;
    }

    private static XStringFormat topRight()
    {
        XStringFormat format = new XStringFormat();
        format.Alignment = XStringAlignment.Far;
        format.LineAlignment = XLineAlignment.Near;
        return format;
    }
</code>```

I have tried using Dipose() on xgr and reinitialising it before each of its draw actions. I have tried saving and restoring the state of xgr between draw actions as seen in the code. I have tried various fonts and font sizes with no luck either.

Let me know what metadata about the PDF is relevant and I will share that.

答:
Using PdfSharp 1.5 GDI, I have been having this issue as well.  Some pdfs would be ok, others would have 1 or 2 pages that were ok, and then others would have no pages that were ok.  Text could be selected, but text could not be seen. Changing the renderMode fixes the issue.

In PdfGraphicsState.cs, there is a condition to check if _realizedRenderingMode != renderMode.  However, _realizedRenderingMode and renderMode is 0 by default, so it never enters codeblock, nor does it look like there is a method for changing the renderMode unless you change the font to italic, bold, strikeout, or underline:

```<code>    int _realizedRenderingMode;  // Reference: TABLE 5.2  Text state operators / Page 398

    public void RealizeFont(XFont font, XBrush brush, int renderingMode)
    {
        const string format = Config.SignificantFigures3;

        // So far rendering mode 0 (fill text) and 2 (fill, then stroke text) only.
        RealizeBrush(brush, _renderer._colorMode, renderingMode, font.Size); // _renderer.page.document.Options.ColorMode);

        // Realize rendering mode.
        if (_realizedRenderingMode != renderingMode)
        {
            _renderer.AppendFormatInt("{0} Tr\n", renderingMode);
            _realizedRenderingMode = renderingMode;
        }
</code>```

Removing the condition would suffice in fixing the issue, but the renderingMode seems to only be needed 1 time for the BT (Begin Text) in XGraphicsPdfRenderer.cs.

```<code>    internal void BeginTextMode()
    {
        if (_streamMode != StreamMode.Text)
        {
            _streamMode = StreamMode.Text;
            _content.Append("BT\n");
            // Text matrix is empty after BT
            _gfxState.RealizedTextPosition = new XPoint();
            _gfxState.ItalicSimulationOn = false;
        }
    }
</code>```

So, I ended up modifying XGraphics to include XGraphicsPdfRendererOptions and passing the variable to the various methods so it can be changed regardless of location:

```<code>    private XGraphicsPdfRendererOptions _renderOptions { get; set; }
    public XGraphicsPdfRendererOptions RenderOptions
    {
        get
        {
            if (_renderOptions == null)
            {
                _renderOptions = new XGraphicsPdfRendererOptions();
            }

            return _renderOptions;
        }
        set
        {
            _renderOptions = value;
        }
    }
</code>```

Keep in mind that the renderMode is originally based on whether the font is italic, bold, strikeout, or underline, which I don't really see how those relate to renderMode, in XGraphicsPdfRenderer.cs:

```<code>            //bool bold = (font.Style & XFontStyle.Bold) != 0;
        //bool italic = (font.Style & XFontStyle.Italic) != 0;
        bool italicSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.ItalicSimulation) != 0;
        bool boldSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.BoldSimulation) != 0;
        bool strikeout = (font.Style & XFontStyle.Strikeout) != 0;
        bool underline = (font.Style & XFontStyle.Underline) != 0;

        Realize(font, brush, boldSimulation ? 2 : 0);
</code>```

Class and enum:

```<code>public class XGraphicsPdfRendererOptions
{
    public XGraphicsPdfRenderMode RenderMode { get; set; }
    public bool IncludeRenderModeForPage { get; set; }
    public bool IncludeRenderModeForObject { get; set; }
}

public enum XGraphicsPdfRenderMode
{
    Text_Render_Mode_Fill = 0,
    Text_Render_Mode_Stroke = 1,
    Text_Render_Mode_Fill_Stroke = 2,
    Text_Render_Mode_Invisible = 3
}
</code>```

Usage:

```<code>gfx.RenderOptions = new XGraphicsPdfRendererOptions() { RenderMode = XGraphicsPdfRenderMode.Text_Render_Mode_Fill, IncludeRenderModeForPage = true };
</code>```

https://github.com/zaryk/PDFsharp

Body:
The system I am working on stamps PDF's with certain information. It does this by creating a lime green text box in the top right corner of the document. It then draws a certain string on top of the green space. This works for thousands of PDFs but for one the text is invisible even though the box is drawn. I can still select the text and copy it to something else, but it is invisible in the PDF.

Unfortunately, I cannot share the PDF but it is a PDF 1.4. What would cause this?

The code for stamping:

    private static XGraphics drawString(XGraphics xgr, PdfPage page, string printString, int pageNumber = 0)
    {
        XFont font = new XFont("Verdana", 10, XFontStyle.BoldItalic);

        var textSize = xgr.MeasureString(printString, font);
        var width = textSize.Width;
        var height = textSize.Height;

        double xMin = 0;
        double yMin = 0;

        if (page.Rotate == 90)
        {
            xMin = page.Height - textSize.Width;
            var state = xgr.Save();
            xgr.DrawRectangle(XBrushes.LimeGreen, xMin, yMin, width, height);
            xgr.Restore(state);
            xgr.DrawString(printString, font, XBrushes.Black, new XRect(0, 0, page.Height, page.Width), topRight());
        }
        else
        {
            xMin = page.Width - textSize.Width;
            var state = xgr.Save();
            xgr.DrawRectangle(XBrushes.LimeGreen, xMin, yMin, width, height);
            xgr.Restore(state);
            xgr.DrawString(printString, font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), topRight());
        }

        return xgr;
    }

    private static XStringFormat topRight()
    {
        XStringFormat format = new XStringFormat();
        format.Alignment = XStringAlignment.Far;
        format.LineAlignment = XLineAlignment.Near;
        return format;
    }

I have tried using Dipose() on xgr and reinitialising it before each of its draw actions. I have tried saving and restoring the state of xgr between draw actions as seen in the code. I have tried various fonts and font sizes with no luck either.

Let me know what metadata about the PDF is relevant and I will share that.

Body:
Using PdfSharp 1.5 GDI, I have been having this issue as well.  Some pdfs would be ok, others would have 1 or 2 pages that were ok, and then others would have no pages that were ok.  Text could be selected, but text could not be seen. Changing the renderMode fixes the issue.

In PdfGraphicsState.cs, there is a condition to check if _realizedRenderingMode != renderMode.  However, _realizedRenderingMode and renderMode is 0 by default, so it never enters codeblock, nor does it look like there is a method for changing the renderMode unless you change the font to italic, bold, strikeout, or underline:

    int _realizedRenderingMode;  // Reference: TABLE 5.2  Text state operators / Page 398

    public void RealizeFont(XFont font, XBrush brush, int renderingMode)
    {
        const string format = Config.SignificantFigures3;

        // So far rendering mode 0 (fill text) and 2 (fill, then stroke text) only.
        RealizeBrush(brush, _renderer._colorMode, renderingMode, font.Size); // _renderer.page.document.Options.ColorMode);

        // Realize rendering mode.
        if (_realizedRenderingMode != renderingMode)
        {
            _renderer.AppendFormatInt("{0} Tr\n", renderingMode);
            _realizedRenderingMode = renderingMode;
        }

Removing the condition would suffice in fixing the issue, but the renderingMode seems to only be needed 1 time for the BT (Begin Text) in XGraphicsPdfRenderer.cs.

    internal void BeginTextMode()
    {
        if (_streamMode != StreamMode.Text)
        {
            _streamMode = StreamMode.Text;
            _content.Append("BT\n");
            // Text matrix is empty after BT
            _gfxState.RealizedTextPosition = new XPoint();
            _gfxState.ItalicSimulationOn = false;
        }
    }

So, I ended up modifying XGraphics to include XGraphicsPdfRendererOptions and passing the variable to the various methods so it can be changed regardless of location:

    private XGraphicsPdfRendererOptions _renderOptions { get; set; }
    public XGraphicsPdfRendererOptions RenderOptions
    {
        get
        {
            if (_renderOptions == null)
            {
                _renderOptions = new XGraphicsPdfRendererOptions();
            }

            return _renderOptions;
        }
        set
        {
            _renderOptions = value;
        }
    }

Keep in mind that the renderMode is originally based on whether the font is italic, bold, strikeout, or underline, which I don't really see how those relate to renderMode, in XGraphicsPdfRenderer.cs:

            //bool bold = (font.Style & XFontStyle.Bold) != 0;
        //bool italic = (font.Style & XFontStyle.Italic) != 0;
        bool italicSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.ItalicSimulation) != 0;
        bool boldSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.BoldSimulation) != 0;
        bool strikeout = (font.Style & XFontStyle.Strikeout) != 0;
        bool underline = (font.Style & XFontStyle.Underline) != 0;

        Realize(font, brush, boldSimulation ? 2 : 0);

Class and enum:

public class XGraphicsPdfRendererOptions
{
    public XGraphicsPdfRenderMode RenderMode { get; set; }
    public bool IncludeRenderModeForPage { get; set; }
    public bool IncludeRenderModeForObject { get; set; }
}

public enum XGraphicsPdfRenderMode
{
    Text_Render_Mode_Fill = 0,
    Text_Render_Mode_Stroke = 1,
    Text_Render_Mode_Fill_Stroke = 2,
    Text_Render_Mode_Invisible = 3
}

Usage:

gfx.RenderOptions = new XGraphicsPdfRendererOptions() { RenderMode = XGraphicsPdfRenderMode.Text_Render_Mode_Fill, IncludeRenderModeForPage = true };

https://github.com/zaryk/PDFsharp