问:
Output of this javascript and the reason
```<code>function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();
</code>```

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

答:
That function is a Javascript Module. You can have a good reading about it on Javascript: the Good Parts, which is a great book and I highly recommend. A Module uses Javascript closures to create private variables and if assigned to a var the var will retain it's vars each time it's called instead of redefining the vars.

A module works like this

```<code>function moduleName(privateVar1){
    var privateVar1;
    var privateVar2;

    return {
        exposedFunction1: function (var1) {
            // Do stuff... using private vars
            return something;
        },
        exposedFunction2: function (var1, var2) {
            // Do stuff...
            return something;
        }
    }
}

var moduleInstance = moduleName(privateVar1);
moduleInstance.exposedFunction(var1);
</code>```

Body:
function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

Body:
That function is a Javascript Module. You can have a good reading about it on Javascript: the Good Parts, which is a great book and I highly recommend. A Module uses Javascript closures to create private variables and if assigned to a var the var will retain it's vars each time it's called instead of redefining the vars.

A module works like this

function moduleName(privateVar1){
    var privateVar1;
    var privateVar2;

    return {
        exposedFunction1: function (var1) {
            // Do stuff... using private vars
            return something;
        },
        exposedFunction2: function (var1, var2) {
            // Do stuff...
            return something;
        }
    }
}

var moduleInstance = moduleName(privateVar1);
moduleInstance.exposedFunction(var1);


来源: stackexchange

问:
getopt for an optional command line argument of type "--my-option" in C
Basically the title. I've been reading the manual pages and can't seem to make it work. Help would be much appreciated.</p>

答:
Use getopt_long() for function names.

A detailed explanation is given here.

Thanks @Barmar for the suggestion!

ContentLicense: CC BY-SA 4.0


问:
Missing Azure functions template under Add new item in Visual Studio
I'm trying to use Visual studio 2019 to create develop & test Azure function locally. So I did install the ASP.NET & Azure development workload modules from the Visual Studio installer. I was able to create a new project using the azure function template using .NET 2.
This created a boilerplate .cs code.

Now here's where the problem is. I'm trying to add a new azure function to my project using the Add > New Item menu from the context menu when right clicked on the project. In the list of templates there is no Azure function templates listed. I've used the search option to filter the templated but end up getting No items found message.

I am not sure what's wrong with my Visual Studio. Does anyone have faced this issue with missing templates and resolved it? Let me know.

答:
Adding to @HariKrishnaRajoli-MT 's answer that was very helpful to me, I did have to do a little more digging to get the nuget packages in.

A missing microsoft.net.sdk.functions is the reason why we are not seeing the New Azure Functions in the Add Context Menu.

My issue was caused by only having my package source as Microsoft Visual Studio Offline Packages, which gave the message -

microsoft.net.sdk.functions not available in this source

I needed to add a Package Source that had the microsoft.net.sdk.functions available. In order to do that,
in your Solution Explorer, Right-Click on Dependencies and click on "Manage NuGet Packages"

Click on the cogwheel to get the below.
Click the + sign to add a source and enter the values as seen below in Name and Source.

Name: nuget.org

Source: https://api.nuget.org/v3/index.json

Click Update and then close.

Go back to the window in the first image, select the "nuget.org" and wait until update runs.
You should be able to see Your Azure function icon next to the app and the New Azure Function in the context menu.

Ref:

https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file

https://learn.microsoft.com/en-us/nuget/consume-packages/install-use-packages-visual-studio#package-sources


问:
React render component only for few seconds
In my existing react component, I need to render another react component for a specific time period.
As soon as the parent component mounts/or data loads, the new-component (or child component) should be visible after 1-2 seconds and then after another few seconds, the new-component should be hidden. This needs to be done only if there is no data available.

This is what currently I've tried to achieve:

```<code>import React, { useState, useEffect } from "react";

function App() {
  const [showComponent, setShowComponent] = useState(false);
  const sampleData = [];

  useEffect(() => {
    if (sampleData.length === 0) {
      setTimeout(() => {
        setShowComponent(true);
      }, 1000);
    }
  }, [sampleData]);

  useEffect(() => {
    setTimeout(() => {
      setShowComponent(false);
    }, 4000);
  }, []);

  const componentTwo = () => {
    return <h2>found error</h2>;
  };

  return <>First component mounted{showComponent && componentTwo()}</>;
}

export default App;
</code>```

The current implementation is not working as expected. The new-component renders in a blink fashion.

Here is the working snippet attached:

Any help to resolve this is appreciated!

答:
You can try this for conditional rendering.

```<code>import { useEffect, useState } from "react";
import "./styles.css";

const LoadingComponent = () => <div>Loading...</div>;

export default function App() {
    const [isLoading, setLoading] = useState(true);
    const [isError, setIsError] = useState(false);

    const onLoadEffect = () => {
        setTimeout(() => {
            setLoading(false);
        }, 2000);

        setTimeout(() => {
            setIsError(true);
        }, 10000);
    };

    useEffect(onLoadEffect, []);

    if (isLoading) {
        return <LoadingComponent />;
    }
    return (
        <div className="App">
            {isError ? (
                <div style={{ color: "red" }}>Something went wrong</div>
            ) : (
                <div>Data that you want to display</div>
            )}
        </div>
    );
}
</code>```

Body:
In my existing react component, I need to render another react component for a specific time period.
As soon as the parent component mounts/or data loads, the new-component (or child component) should be visible after 1-2 seconds and then after another few seconds, the new-component should be hidden. This needs to be done only if there is no data available.

This is what currently I've tried to achieve:

import React, { useState, useEffect } from "react";

function App() {
  const [showComponent, setShowComponent] = useState(false);
  const sampleData = [];

  useEffect(() => {
    if (sampleData.length === 0) {
      setTimeout(() => {
        setShowComponent(true);
      }, 1000);
    }
  }, [sampleData]);

  useEffect(() => {
    setTimeout(() => {
      setShowComponent(false);
    }, 4000);
  }, []);

  const componentTwo = () => {
    return
found error
;
  };

  return <>First component mounted{showComponent && componentTwo()}</>;
}

export default App;

The current implementation is not working as expected. The new-component renders in a blink fashion.

Here is the working snippet attached:

Any help to resolve this is appreciated!

Body:
You can try this for conditional rendering.

import { useEffect, useState } from "react";
import "./styles.css";

const LoadingComponent = () => <div>Loading...</div>;

export default function App() {
    const [isLoading, setLoading] = useState(true);
    const [isError, setIsError] = useState(false);

    const onLoadEffect = () => {
        setTimeout(() => {
            setLoading(false);
        }, 2000);

        setTimeout(() => {
            setIsError(true);
        }, 10000);
    };

    useEffect(onLoadEffect, []);

    if (isLoading) {
        return <LoadingComponent />;
    }
    return (
        <div className="App">
            {isError ? (
                <div style={{ color: "red" }}>Something went wrong</div>
            ) : (
                <div>Data that you want to display</div>
            )}
        </div>
    );
}


问:
Skip parent if using PHP
Not sure if this is even possible, but the basic idea of the code is as follows:

```<code>if(isset($_POST['submit'])) {
    if($_POST['field'] == 0) {
        // do not process the code in the if statement
    }
    // code to process if the above validation criteria is not met
}
</code>```

I basically want to try and keep it as simple as possible without lots of if's everywhere, just the quick validation statements at the top, and if none of those if statements are triggered, it will process the code to update the database etc.

I have tried the continue statement function with no joy, I believe that only works with loops.

Thanks!

答:
To accomplish this as you originally desired, you need to use the break statement.  From the PHP manual:

```<code>$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

/* Using the optional argument. */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Skip parent if using PHP

Body:
Not sure if this is even possible, but the basic idea of the code is as follows:

if(isset($_POST['submit'])) {
    if($_POST['field'] == 0) {
        // do not process the code in the if statement
    }
    // code to process if the above validation criteria is not met
}

I basically want to try and keep it as simple as possible without lots of if's everywhere, just the quick validation statements at the top, and if none of those if statements are triggered, it will process the code to update the database etc.

I have tried the continue statement function with no joy, I believe that only works with loops.

Thanks!

Body:
To accomplish this as you originally desired, you need to use the break statement.  From the PHP manual:

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

/* Using the optional argument. */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}


问:
Cannot connect to apple id using Virtual Box Mac OS High Sierra
When I try connecting to the app store, itunes, etc. it returns an error that says "Unexpected error occured". That's it, nothing else.

I have a virtual machine running Mac OS High Sierra. I am using Oracle VM VirtualBox Manager. I have given my mac environment a "serial number" using VBoxManage setextradata “MacOS High Sierra” VBoxInternal/Devices/efi/0/Config/DmiSystemSerial "number" When I go to Apple>About this Mac it lists the correct serial number I assigned it too. Before hand, it would just list the serial number as 0.

My question is, how do I connect my mac environment to my apple id for app store, itunes, etc?

答:
Resetting the Keychain did the trick for me.

Keychain Access -> Preferences -> Reset default keychains

Then it takes a minute to log in, but does so eventually.


问:
Redirect two links from old domain to new domain
I'm trying to redirect only 2 links from old domain to new domain not all links from old domain
example :

```<code>https://old-domain.com/profile/teams  to  https://new-domain.com
</code>```

and

```<code>https://old-domain.com/activities  to  https://new-domain.com
</code>```

only this this two links

I did

```<code>RewriteEngine on
RewriteBase https://old-domain.com/profile/teams
RewriteRule (.*) https://new-domain.com [R=301,L]

RewriteEngine on
RewriteBase https://old-domain.com/activities
RewriteRule (.*) https://new-domain.com [R=301,L]
</code>```

but I get 500 error

答:
You can use this redirect rule on site root .htaccess of old domain:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)?old-domain\.com$ [NC]
RewriteRule ^(profile/teams|activities)/?$ https://new-domain.com [L,R=301,NC]
```

Regular expression ^(profile/teams|activities)/?$ matches /(profile/teams or /activities followed by an optional trailing slash.

Body:
I'm trying to redirect only 2 links from old domain to new domain not all links from old domain
example :

https://old-domain.com/profile/teams  to  https://new-domain.com

and

https://old-domain.com/activities  to  https://new-domain.com

only this this two links

I did

RewriteEngine on
RewriteBase https://old-domain.com/profile/teams
RewriteRule (.*) https://new-domain.com [R=301,L]

RewriteEngine on
RewriteBase https://old-domain.com/activities
RewriteRule (.*) https://new-domain.com [R=301,L]

but I get 500 error

Body:
You can use this redirect rule on site root .htaccess of old domain:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)?old-domain\.com$ [NC]
RewriteRule ^(profile/teams|activities)/?$ https://new-domain.com [L,R=301,NC]

Regular expression ^(profile/teams|activities)/?$ matches /(profile/teams or /activities followed by an optional trailing slash.


问:
What is the difference between for (int I = 0; I<n; I++) and int I; for (I = 0; I < n;I++)?
I have a code like this for question 53 of leetcode:

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

int solve(int arr[], int size)
{
    int lmax, qmax, tmp, i, j,  m = (size / 2) - 1;
    for (i = m, tmp = 0, lmax = arr[m]; i >= 0; i--)
    {
        tmp += arr[i];
        if (tmp > lmax)
        {
            lmax = tmp;
        }
        else
        {
            lmax = lmax;
        }
    }
    for (j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
    {

        tmp += arr[j];
        if (tmp > qmax)
        {
            qmax = tmp;
        }
        else
        {
            qmax = qmax;
        }
    }
    return lmax + qmax;
}
</code>```

If i change this code block:

```<code>int lmax, qmax, tmp, i, j,  m = (size / 2) - 1;

for (j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
{

    tmp += arr[j];
    if (tmp > qmax)
    {
        qmax = tmp;
    }
    else
    {
        qmax = qmax;
    }
}
</code>```

to this

```<code>int lmax, qmax, tmp, i, m = (size / 2) - 1;

for (int j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
{

    tmp += arr[j];
    if (tmp > qmax)
    {
        qmax = tmp;
    }
    else
    {
        qmax = qmax;
    }
}
</code>```

which is i change to

int lmax, qmax, tmp, i, m = (size / 2) - 1; -> int lmax, qmax, tmp, i, j,  m = (size / 2) - 1;

j -> int j

My output is printing different results, I could not find the meaningful explanation of this, in "int j" situation I can print correct "qmax" values in scope but when I tried to do "lmax + qmax" it returns sum of addresses.

答:
When you use the type inside the for you are creating a new variable (in your case three variables: j, tmp, and qmax). If there are other variables with the same name, they are shadowed until the loop terminates.

```<code>int solve(int arr[], int size)
{
    int lmax, qmax, tmp,i, j,  m = (size / 2) - 1;

    // qmax exists here

    for (int j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
    {
        // loop with different j, tmp, and qmax
    }

    // back to old uninitialized qmax

    return lmax + qmax; // this qmax does not have the value you "want"
}
</code>```

gcc has the option -Wshadow that may help in this case.

Body:
I have a code like this for question 53 of leetcode:

#include <stdio.h>

int solve(int arr[], int size)
{
    int lmax, qmax, tmp, i, j,  m = (size / 2) - 1;
    for (i = m, tmp = 0, lmax = arr[m]; i >= 0; i--)
    {
        tmp += arr[i];
        if (tmp > lmax)
        {
            lmax = tmp;
        }
        else
        {
            lmax = lmax;
        }
    }
    for (j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
    {

        tmp += arr[j];
        if (tmp > qmax)
        {
            qmax = tmp;
        }
        else
        {
            qmax = qmax;
        }
    }
    return lmax + qmax;
}

If i change this code block:

int lmax, qmax, tmp, i, j,  m = (size / 2) - 1;

for (j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
{

    tmp += arr[j];
    if (tmp > qmax)
    {
        qmax = tmp;
    }
    else
    {
        qmax = qmax;
    }
}

to this

int lmax, qmax, tmp, i, m = (size / 2) - 1;

for (int j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
{

    tmp += arr[j];
    if (tmp > qmax)
    {
        qmax = tmp;
    }
    else
    {
        qmax = qmax;
    }
}

which is i change to

int lmax, qmax, tmp, i, m = (size / 2) - 1; -> int lmax, qmax, tmp, i, j,  m = (size / 2) - 1;

j -> int j

My output is printing different results, I could not find the meaningful explanation of this, in "int j" situation I can print correct "qmax" values in scope but when I tried to do "lmax + qmax" it returns sum of addresses.

Body:
When you use the type inside the for you are creating a new variable (in your case three variables: j, tmp, and qmax). If there are other variables with the same name, they are shadowed until the loop terminates.

int solve(int arr[], int size)
{
    int lmax, qmax, tmp,i, j,  m = (size / 2) - 1;

    // qmax exists here

    for (int j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
    {
        // loop with different j, tmp, and qmax
    }

    // back to old uninitialized qmax

    return lmax + qmax; // this qmax does not have the value you "want"
}

gcc has the option -Wshadow that may help in this case.


问:
About lookup command when the lookup file contains strings and regular expressions
I have a question about the lookup command when the lookup file contains strings and regular expressions.

The following is an example.

field var_1 : String

field var_2 : String

field var_3 : Regex or String

field var_4 : String

lookup file

```<code>------lookup file-----------------------------
var_1, var_2, var_3, var_4
data10, data11, .+(:?aaa|bbb), data13
data20, data21, .+(:?ccc|ddd|eee), data23
data30, data31, .+(:?eee)fff+(:?ggg|hhh), data33
--------------------------------------------------
</code>```

I would like to return var_4 when var_1, var_2, and var_3 are matched by the lookup command, but var_3 may contain a regular expression, and the lookup needs to match the condition of the regular expression.
As you know, regular expressions are not allowed in the lookup-field in the lookup command.

↓↓↓ Regular expressions cannot be used ↓↓↓

```<code>| makeresults
| eval var_1 = "data10", var_2 = "data11" , var_3 = "ABC123aaa"
| lookup var_1 var_2 var_3 OUTPUT var_4
</code>```

It is necessary to use the lookup file (csv). If the lookup command is not the best way to solve this problem, then another command such as join is fine to use. Obviously, I don’t intend to use only the lookup command. I’m looking for other ways to do it as well.

Can someone please help me with this?

Thanks in advance!!

答:
Lookup files support only exact string matching.  Lookup definitions also support wildcard and CIDR matches.

Regular expressions can be used, but are treated as exact strings unless the field is set up for wildcard matching in the lookup definition.  Even then, wildcards in the regex are treated as such and the remaining characters in the regex are matched literally.

The lookup command in the example SPL is invalid because a lookup table or file is not specified.

Body:
I have a question about the lookup command when the lookup file contains strings and regular expressions.

The following is an example.

field var_1 : String

field var_2 : String

field var_3 : Regex or String

field var_4 : String

lookup file

------lookup file-----------------------------
var_1, var_2, var_3, var_4
data10, data11, .+(:?aaa|bbb), data13
data20, data21, .+(:?ccc|ddd|eee), data23
data30, data31, .+(:?eee)fff+(:?ggg|hhh), data33
--------------------------------------------------

I would like to return var_4 when var_1, var_2, and var_3 are matched by the lookup command, but var_3 may contain a regular expression, and the lookup needs to match the condition of the regular expression.
As you know, regular expressions are not allowed in the lookup-field in the lookup command.

↓↓↓ Regular expressions cannot be used ↓↓↓

| makeresults
| eval var_1 = "data10", var_2 = "data11" , var_3 = "ABC123aaa"
| lookup var_1 var_2 var_3 OUTPUT var_4

It is necessary to use the lookup file (csv). If the lookup command is not the best way to solve this problem, then another command such as join is fine to use. Obviously, I don’t intend to use only the lookup command. I’m looking for other ways to do it as well.

Can someone please help me with this?

Thanks in advance!!


问:
How to pass $_SESSION variables to a websocket server?
I have searched a lot on the web but didn't find a useful clue.

I have a websocket server and a web server running together on my local machine.

I need to pass $_SESSION data to the websocket server when a client connects to it using the browser API 'new WebSocket("ws://localhost")' (the request is send to the websocket using a reverse proxy, which knows it when receives requests with an 'Upgrade' header).

The point is that the clients successfully connect to the ws server, but I need to recover also their SESSION data using the $_SESSION variables setted by the HTTP web server.

Actually my situation is this (I am using the Ratchet library):

```<code>use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\MyAppClassChat;

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(new HttpServer(new WsServer(new MyAppClass())), 8080);
$server->run();
</code>```

The MyAppClass is very simple:

```<code> <?php
namespace MyAppClass;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class MyAppClass implements MessageComponentInterface {

    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
            /* I would like to put recover the session infos of the clients here
               but the session_start() call returns an empty array ($_SESSION variables have been previuosly set by the web server)*/
        session_start();
        var_dump($_SESSION) // empty array...
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $numberOfReceivers = count($this->clients) -1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n", $from->resourceId, $msg,
                                 $numberOfReceivers, $numberOfReceivers == 1 ? '' : 's');

        $this->clients->rewind();
        while ($this->clients->valid())
        {
            $client = $this->clients->current();
            if ($client !== $from) {
                $client->send($msg);
            }
            $this->clients->next();
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
</code>```

Is there a way to do that with my actual layout or should I configure apache in order to use
mod_proxy_wstunnel module?

Thanks for help!!!

答:
To complete the answers of dmiller309 and fred, I can't comment yet :(

I wouldn't store the session in database, I would simply use the directory that save the sessions, searching for the one that interest me, using session_save_path().

public function onMessage(ConnectionInterface $from, $msg) {
    $session_file = session_save_path()."/sess_".$from->WebSocket->request->getCookies()['PHPSESSID'];
    if(!file_exists($session_file))
        // The session doesn't exist
        return ;
    $content = file_get_contents($session_file);
    $session_id = "0";
    foreach($sections = explode(";", $content) as $k => $section) {
        $data = explode("|", $section, 2);
        if(isset($data[0]) and $data[0] == "id" and isset($data[1]) and substr_count($data[1], '"') == 2) {
            $session_id = substr($data[1], strpos($data[1], '"')+1, -1);
            break;
        }
    }
    if($session_id == "0")
        // The session has no "id"
        return ;

    // ID stored in $session_id, equivalent to $_SESSION["id"]
}
```

Note: All sessions start with "sess_"

Note 2: I stored the session ID in a string, so I get it between quotes.

Note 3: I didn't use session_decode() for safety reason, as the result is stored in $_SESSION, I assume it might result in a Race Condition.

I didn't test, you can let me know if something doesn't work.

Of course, it's possible to do the same for the other values stored in your session.

Body:
I have searched a lot on the web but didn't find a useful clue.

I have a websocket server and a web server running together on my local machine.

I need to pass $_SESSION data to the websocket server when a client connects to it using the browser API 'new WebSocket("ws://localhost")' (the request is send to the websocket using a reverse proxy, which knows it when receives requests with an 'Upgrade' header).

The point is that the clients successfully connect to the ws server, but I need to recover also their SESSION data using the $_SESSION variables setted by the HTTP web server.

Actually my situation is this (I am using the Ratchet library):

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\MyAppClassChat;

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(new HttpServer(new WsServer(new MyAppClass())), 8080);
$server->run();

The MyAppClass is very simple:

 <?php
namespace MyAppClass;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class MyAppClass implements MessageComponentInterface {

    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
            /* I would like to put recover the session infos of the clients here
               but the session_start() call returns an empty array ($_SESSION variables have been previuosly set by the web server)*/
        session_start();
        var_dump($_SESSION) // empty array...
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $numberOfReceivers = count($this->clients) -1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n", $from->resourceId, $msg,
                                 $numberOfReceivers, $numberOfReceivers == 1 ? '' : 's');

        $this->clients->rewind();
        while ($this->clients->valid())
        {
            $client = $this->clients->current();
            if ($client !== $from) {
                $client->send($msg);
            }
            $this->clients->next();
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}

Is there a way to do that with my actual layout or should I configure apache in order to use
mod_proxy_wstunnel module?

Thanks for help!!!

Body:
To complete the answers of dmiller309 and fred, I can't comment yet :(

I wouldn't store the session in database, I would simply use the directory that save the sessions, searching for the one that interest me, using session_save_path().

public function onMessage(ConnectionInterface $from, $msg) {
    $session_file = session_save_path()."/sess_".$from->WebSocket->request->getCookies()['PHPSESSID'];
    if(!file_exists($session_file))
        // The session doesn't exist
        return ;
    $content = file_get_contents($session_file);
    $session_id = "0";
    foreach($sections = explode(";", $content) as $k => $section) {
        $data = explode("|", $section, 2);
        if(isset($data[0]) and $data[0] == "id" and isset($data[1]) and substr_count($data[1], '"') == 2) {
            $session_id = substr($data[1], strpos($data[1], '"')+1, -1);
            break;
        }
    }
    if($session_id == "0")
        // The session has no "id"
        return ;

    // ID stored in $session_id, equivalent to $_SESSION["id"]
}

Note: All sessions start with "sess_"

Note 2: I stored the session ID in a string, so I get it between quotes.

Note 3: I didn't use session_decode() for safety reason, as the result is stored in $_SESSION, I assume it might result in a Race Condition.

I didn't test, you can let me know if something doesn't work.

Of course, it's possible to do the same for the other values stored in your session.


问:
How to know the number of characters in utf8 string
i want to know is there a simple way to determine the number of characters in UTF8 string.
For example, in windows it can be done by:

converting UTF8 string to wchar_t string

use wcslen function and get result

But I need more simpler and crossplatform solution.

Thanks in advance.

答: UTF-8 characters are either single bytes where the left-most-bit is a 0 or multiple bytes where the first byte has left-most-bit 1..10... (with the number of 1s on the left 2 or more) followed by successive bytes of the form 10... (i.e. a single 1 on the left).  Assuming that your string is well-formed you can loop over all the bytes and increment your "character count" every time you see a byte that is not of the form 10... - i.e. counting only the first bytes in all UTF-8 characters.


问:
Creating pull request after revert
First question so I'm going to try to get this correct.

I created a branch and was working on a project for a couple of weeks.  I created a pull request to merge my branch with the master branch.  When my branch was merged with master it created a lot of various issues (whoops lots of emails in the morning). So, my pull request was reverted and the next day I corrected the issues and pushed back to my branch.  However, when attempting to create the pull request, it does not recognize the changes prior to the revert.

I've attempted 'git checkout (sha for previous commit)' and then 'git checkout -b (new branch)'.  That did not work.  I attempted to use cherry pick, but I'm not confident I did that correctly.

Any suggestions would be greatly appreciated!

答:
Simple Answer, you have two options here:

First, stash your new changes, then either

Option 1 - Create a new branch, and cherry-pick all your changes from your old branch, search on how can you cherry-pick a range of commits.

OR

Option 2 - If you don't want to create a new branch, you will first need to pull in the latest changes from the mainline (including your reverted commit). Then essentially revert your reverted commit in your branch.

Then, stash pop your changes, and commit. Now your pull request will reflect all your changes.

Essentially, the pull request, gets all the commits when you had last separated from mainline.

Title: Creating pull request after revert


问:
Puppet agent upgrade to 6.26 breaks function versioncmp()
recently I upgraded puppet agent from 6.25 to 6.26 on the puppetserver and it seems that after upgrade all agents conected to the puppetserver fail to apply changes due to an internal server error caused by versioncmp() built in function.

The quick fix to keep going is to downgrade puppet agent on the server to 6.25

Error:

```<code>Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Evaluation Error: Error while evaluating a Resource Statement, Evaluation Error: Error while evaluating a Function Call, wrong number of arguments (given 3, expected 2)
</code>```

Anyone managed to find where it breaks, and how versioncmp is changed in such manner that it sees 3 arguments?

Note: The function worked perfectly before and I did not changed anything in code.

Many thanks

答: Please see https://tickets.puppetlabs.com/browse/PA-4189 for details. You need to make sure that the puppetserver package is updated as well.

Body:
recently I upgraded puppet agent from 6.25 to 6.26 on the puppetserver and it seems that after upgrade all agents conected to the puppetserver fail to apply changes due to an internal server error caused by versioncmp() built in function.

The quick fix to keep going is to downgrade puppet agent on the server to 6.25

Error:

Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Evaluation Error: Error while evaluating a Resource Statement, Evaluation Error: Error while evaluating a Function Call, wrong number of arguments (given 3, expected 2)

Anyone managed to find where it breaks, and how versioncmp is changed in such manner that it sees 3 arguments?

Note: The function worked perfectly before and I did not changed anything in code.

Many thanks


问:
Substitute the markdown italic to html using regex in Perl
To convert the markdown italic text $script into html, I've written this:

my $script = "*so what*";
my $res =~ s/\*(.)\*/$1/g;
print "$1\n";
```
<p>The expected result is:</p>
```so what
```
<p>but it gives:</p>
```
```

How to make it give the expected result?

答:
Problems:

You print the wrong variable.

You switch variable names halfway through.

. won't match more than one character.

You always add one EM element, even if no stars are found.

You always add one EM element, even if multiple pairs of stars are found.

You add the EM element around the entire output, not just the portion in stars.

Fix:

$script =~ s{\*([^*]+)\*}{$1}g;
print "$script\n";
```
<p>or</p>
<pre class="lang-perl prettyprint-override"><code>my $res = $script =~ s{\*([^*]+)\*}{<em>$1</em>}gr;
print "$res\n";
</code>```

But that's not it. Even with all the aforementioned problems fixed, your parser still has numerous other bugs. For example, it misapplies italics for all of the following:

**Important**
Correct: Important
Your code: *Important*

4 * 5 * 6 = 120
Correct: 4 * 5 * 6 = 120
Your code: 4  5  6 = 120

4 * 6 = 20 is *wrong*
Correct: 4 * 6 = 20 is wrong
Your code: 4  6 = 20 is wrong*

`foo *bar* baz`
Correct: foo *bar* baz
Your code: `foo <em>bar</em> baz`

\*I like stars\*
Correct: *I like stars*
Your code: \I like stars\

Body:
To convert the markdown italic text $script into html, I've written this:

my $script = "*so what*";
my $res =~ s/\*(.)\*/$1/g;
print "$1\n";

The expected result is:

so what

but it gives:

How to make it give the expected result?

Body:
Problems:

You print the wrong variable.

You switch variable names halfway through.

. won't match more than one character.

You always add one EM element, even if no stars are found.

You always add one EM element, even if multiple pairs of stars are found.

You add the EM element around the entire output, not just the portion in stars.

Fix:

$script =~ s{\*([^*]+)\*}{<em>$1</em>}g;
print "$script\n";

or

my $res = $script =~ s{\*([^*]+)\*}{<em>$1</em>}gr;
print "$res\n";

But that's not it. Even with all the aforementioned problems fixed, your parser still has numerous other bugs. For example, it misapplies italics for all of the following:

**Important**
Correct: Important
Your code: *Important*

4 * 5 * 6 = 120
Correct: 4 * 5 * 6 = 120
Your code: 4  5  6 = 120

4 * 6 = 20 is *wrong*
Correct: 4 * 6 = 20 is wrong
Your code: 4  6 = 20 is wrong*

`foo *bar* baz`
Correct: foo *bar* baz
Your code: `foo <em>bar</em> baz`

\*I like stars\*
Correct: *I like stars*
Your code: \I like stars\


问:
Is it possible to build a custom SQL query in Template Fragment using a Search Term or alternatively the Master doc name which calls the fragment?
I need to build a custom SQL query in a fragment that uses the Master document's name as a parameter. In saved searches we use the  and pass it via the model document's attributes. But in a custom query for a fragment this is not working.

Alternatively - or even better - it would be great if we could get directly in the query the Master document's name as field.

Is this possible?

Here is the query:

```<code>SELECT CONCAT(obj_ds.ea_guid, obj_ds.Name) AS [DS_Name-Hyperlink]
FROM t_object obj_adu
INNER JOIN t_connector tconn
  ON obj_adu.object_id = tconn.end_object_id
INNER JOIN t_object obj_ds
  ON tconn.start_object_id = obj_ds.object_id
  AND tconn.stereotype = 'Conveyed ADU'
  AND obj_ds.stereotype = 'Data-Stream'
INNER JOIN t_objectproperties tobjp_ds
  ON obj_ds.object_id = tobjp_ds.object_id
  AND tobjp_ds.property = 'Source'
INNER JOIN t_object tobj_dm
  ON tobjp_ds.value = tobj_dm.ea_guid
INNER JOIN t_objectproperties tobjp_ds2
  ON obj_ds.object_id = tobjp_ds2.object_id
  AND tobjp_ds2.property = 'Destination'
INNER JOIN t_object tobj_dm2
  ON tobjp_ds2.value = tobj_dm2.ea_guid
INNER JOIN t_objectproperties tobjp_ds3
  ON tobj_dm.ea_guid =  tobjp_ds3.value
  AND (tobjp_ds3.property = 'Element 2' OR tobjp_ds3.property = 'Element 1')
INNER JOIN t_objectproperties tobjp_ds4
  ON tobj_dm2.ea_guid =  tobjp_ds4.value
  AND (tobjp_ds4.property = 'Element 2' OR tobjp_ds4.property = 'Element 1')
INNER JOIN t_object tobj_dm4
  ON tobjp_ds4.Object_id = tobj_dm4.Object_id and tobjp_ds3.Object_id = tobj_dm4.Object_id AND tobj_dm4.stereotype = 'Interface'
INNER JOIN t_attribute tatt
  ON tobj_dm4.Name = tatt.Name
INNER JOIN t_object tobj_dmm
  ON tatt.object_id = tobj_dmm.object_id
  AND tobj_dmm.stereotype = 'model document'
INNER JOIN t_package tpkg_dmm
  on tobj_dmm.package_id = tpkg_dmm.package_id
INNER JOIN t_object tobj_tmmm
  on tpkg_dmm.ea_guid = tobj_tmmm.ea_guid
WHERE obj_adu.object_id = #OBJECTID# AND obj_adu.Stereotype='ADU' AND tobj_tmmm.name LIKE '<Search Term>'
  AND tobj_tmmm.stereotype = 'master document';
</code>```

答:
As mentioned in the manual, the only available parameters are the macros:

#OBJECTID#

#DIAGRAMID#

#PACKAGEID#

These macros are related to the content you are documenting.
Now if you would use the «master document» Package as the content by dragging it into a «model document» element, you can query the properties of the master document and related elements.

Body:
I need to build a custom SQL query in a fragment that uses the Master document's name as a parameter. In saved searches we use the  and pass it via the model document's attributes. But in a custom query for a fragment this is not working.

Alternatively - or even better - it would be great if we could get directly in the query the Master document's name as field.

Is this possible?

Here is the query:

SELECT CONCAT(obj_ds.ea_guid, obj_ds.Name) AS [DS_Name-Hyperlink]
FROM t_object obj_adu
INNER JOIN t_connector tconn
  ON obj_adu.object_id = tconn.end_object_id
INNER JOIN t_object obj_ds
  ON tconn.start_object_id = obj_ds.object_id
  AND tconn.stereotype = 'Conveyed ADU'
  AND obj_ds.stereotype = 'Data-Stream'
INNER JOIN t_objectproperties tobjp_ds
  ON obj_ds.object_id = tobjp_ds.object_id
  AND tobjp_ds.property = 'Source'
INNER JOIN t_object tobj_dm
  ON tobjp_ds.value = tobj_dm.ea_guid
INNER JOIN t_objectproperties tobjp_ds2
  ON obj_ds.object_id = tobjp_ds2.object_id
  AND tobjp_ds2.property = 'Destination'
INNER JOIN t_object tobj_dm2
  ON tobjp_ds2.value = tobj_dm2.ea_guid
INNER JOIN t_objectproperties tobjp_ds3
  ON tobj_dm.ea_guid =  tobjp_ds3.value
  AND (tobjp_ds3.property = 'Element 2' OR tobjp_ds3.property = 'Element 1')
INNER JOIN t_objectproperties tobjp_ds4
  ON tobj_dm2.ea_guid =  tobjp_ds4.value
  AND (tobjp_ds4.property = 'Element 2' OR tobjp_ds4.property = 'Element 1')
INNER JOIN t_object tobj_dm4
  ON tobjp_ds4.Object_id = tobj_dm4.Object_id and tobjp_ds3.Object_id = tobj_dm4.Object_id AND tobj_dm4.stereotype = 'Interface'
INNER JOIN t_attribute tatt
  ON tobj_dm4.Name = tatt.Name
INNER JOIN t_object tobj_dmm
  ON tatt.object_id = tobj_dmm.object_id
  AND tobj_dmm.stereotype = 'model document'
INNER JOIN t_package tpkg_dmm
  on tobj_dmm.package_id = tpkg_dmm.package_id
INNER JOIN t_object tobj_tmmm
  on tpkg_dmm.ea_guid = tobj_tmmm.ea_guid
WHERE obj_adu.object_id = #OBJECTID# AND obj_adu.Stereotype='ADU' AND tobj_tmmm.name LIKE '<Search Term>'
  AND tobj_tmmm.stereotype = 'master document';


问:
Maintaining message integrity
I have a message that I am passing to myself which will be subject to man-in-the-middle attacks.  Because of that, I am concerned about the integrity of the message being maintained between the time I send it, and the time that I receive it back.

It should be assumed that once I send the message to myself, no information about the message sent will be available to me in the future.  The message is completely self-contained.

To that end, I know that should hash the message contents and compare the hashes before I send the message, and after I send the message, if they differ, then the message has been tampered with.

Of course, if the man-in-the-middle knows that the hash is really just the hash of the message contents, as-is, then because the message is self-contained, he can just create new contents and apply the same hash algorithm to the contents.

The question is, to what lengths should I go to randomize the message contents when generating the hash?  When does it reach the point of diminishing returns?

In this scenario, I have a set of key/value pairs.  To that end, the steps that I know I HAVE to take are:

Add a salt to the message.  The salt is a secret to the rest of the world.  It gets attached to the contents of the message before hashing.

Order the key/value pairs in a consistent manner before generating the hash.

While not directly relevant, a timestamp is going to be added to the contents of each message before hashing, to prevent replay attacks.

These are the optional steps that I am considering:

Transforming the keys before I order them.  I've considered reversing them, then ordering by count/key.

Playing with the separators that separate key/value pairs (both for the separator for the key/value and the separator for the pair).

NOTE

Message privacy is not a requirement here, so I am not looking for encryption.  The values must be transmitted in plain-text.

Finally, what hashing algorithms should I avoid?

Specifics

I have an ASP.NET MVC site which I have a controller which handles input validation and persistence.

If (based on a heuristic, it's not important which) the input is determined to be an automated spam attempt, a model of IDictionary<string, string> is created with the input values and a ViewResult is sent to a general CAPTCHA page.

In that view, in the form that contains the CAPTCHA control, the contents of the IDictionary<string, string> will be written out in hidden input fields, and the action of the form will be the same action that the contents were originally posted to.  This way, MVC can pick up the values when the form is resubmitted.

It's because of this I can't encrypt the key/value pairs (or maybe I can and should, tell me why and how!).

Of course, I need to add one more value, which contains the hashed message contents.  If that value is there, then the controller will check to see that the message integrity is maintained, and allow the input to be persisted if it has.

Solution

I've opted to go with the SignedCms class in the System.Security.Cyrptography.Pkcs namespace, which represents the signging and verifying of CMS/PKCS #7 messages.

To elaborate, I've created a self-issued certificate with MAKECERT.EXE and then in my code, I use the example here to digitally sign the data:

http://blogs.msdn.com/shawnfa/archive/2006/02/27/539990.aspx

Now, it should be a matter of keeping the password on the exported private key secure, as well as security on the server, which makes it less about programming.

I'll have to add an extra key for the timestamp for replay attacks, but that won't be too hard.

The answer goes to Kalium, not for his initial post, but for his follow up comments which pointed the way to digital signatures, and eventually my discovery of how to utilize them in .NET.

Thanks to everyone who contributed.

答:
Assuming that you can't pass any information over a "secure" channel (i.e. the hash) here's how you would do it:

Hash the message, then sign the hash with a private key.  Include the signed hash in the message.

When you get the message, use the public key to decrypt the signed hash and verify that it matches the actual hash of the message.

An attacker would not be able to "fake" a message, since they would need to have your private key in order to encrypt their new hash.

As others have mentioned, this is just plain vanilla digital signing and can be handled by something like PGP/GPG

OwnerDisplayName: casperOne

ContentLicense: CC BY-SA 2.5

Title: Maintaining message integrity

LastEditorDisplayName: casperOne

OwnerDisplayName: Eric P

LastEditorDisplayName: Eric P


问:
Create GSI on an attribute which has the value of Set
So i want to create a simple Dynamodb table called reminders which at the moment has 3 columns :

reminder_id : This is the hash key

reminder_tag: I want to have a global secondary index on this field . But at the same time i want to ensure that the tags attribute should have the datatype of Set . Because there can be multiple tags on a reminder.

reminder_title: I also want to have a global secondary index on this field. This will be a string field.

I checked the documentation : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/dynamodb.html#valid-dynamodb-types on what are the possible datatypes available in Boto3 .

So i have come up with this script :

```<code>import boto3

def create_reminders_table():
    """Just create the reminders table."""
    session = boto3.session.Session(profile_name='dynamo_local')
    dynamodb = session.resource('dynamodb', endpoint_url="http://localhost:8000")
    table = dynamodb.create_table(
        TableName='Reminders',
        KeySchema=[
            {
                'AttributeName': 'reminder_id',
                'KeyType': 'HASH'
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'reminder_id',
                'AttributeType': 'S'
            },
            {
                'AttributeName': 'reminder_tag',
                'AttributeType': 'SS'
            },
            {
                'AttributeName': 'reminder_title',
                'AttributeType': 'S'
            }
        ],
        GlobalSecondaryIndexes=[
            {
                'IndexName': 'ReminderTagGsi',
                'KeySchema': [
                    {
                        'AttributeName': 'reminder_tag',
                        'KeyType': 'HASH'
                    }
                ],
                'Projection': {
                    'ProjectionType': 'INCLUDE',
                    'NonKeyAttributes': [
                        'reminder_title'
                    ]
                }
            },
            {
                'IndexName': 'ReminderTitleGsi',
                'KeySchema': [
                    {
                        'AttributeName': 'reminder_title',
                        'KeyType': 'HASH'
                    }
                ],
                'Projection': {
                    'ProjectionType': 'KEYS_ONLY'
                }
            }
        ],
        BillingMode='PAY_PER_REQUEST'
    )
    return table

if __name__ == '__main__':
    movie_table = create_reminders_table()
    print("Table status:", movie_table.table_status)
</code>```

But when i run this i get the below issue:

```<code>botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the CreateTable operation: Member must satisfy enum value set: [B, N, S]
</code>```

I searched and came across this question asked by someone which has the same issue : https://forums.aws.amazon.com/thread.jspa?messageID=613970

Can someone please help me with this since the solution of not providing a datatype either does not work .

Also is it possible to have an index on a an attribute which is of value Set ? I mean i should enable the user to search for reminders with a tag , and for doing that i need to have a set.

Request someone to please help me regarding this.

答:
Is it possible to have an index on an attribute which is of value Set ?

No. As the CreateTable docs say, "the attributes in KeySchema must also be defined in the AttributeDefinitions", to a data type to one of (S)tring, (N)umber or (B)inary."

enable the user to search for reminders with a tag , and for doing that i need to have a set.

A DynamoDB workaround for one-many relations is a composite sort key as in urgent#work. That would only be sensible for a small, fixed number of tags, though.

Your least-bad option is to query by user (and perhaps further narrowing with some sort key), then filtering the results by tag membership outside DynamoDB. (N.B. The IN operator cannot be used in a Query's FilterConditionExpression, so it's of no use to you here).

I want to have a global secondary index on reminder_title

reminder_title is a poor candidate for an index Primary Key.  An index's (and table's) Primary Key must ensure per-record uniqueness. A title would likely not.  You probably need a combination of 3 elements, user_id, request_id and title, to ensure key uniqueness across records.

Consider a composite Primery Key with, say, user_id for the Partition Key (= HASH) and a compound sort key in a new column (SK) that concatenates title#request_id.  You would then search by-user-by-title with:

user_id="Zaphod" AND begins_with(SK, "exercise")
```

Body:
So i want to create a simple Dynamodb table called reminders which at the moment has 3 columns :

reminder_id : This is the hash key

reminder_tag: I want to have a global secondary index on this field . But at the same time i want to ensure that the tags attribute should have the datatype of Set . Because there can be multiple tags on a reminder.

reminder_title: I also want to have a global secondary index on this field. This will be a string field.

I checked the documentation : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/dynamodb.html#valid-dynamodb-types on what are the possible datatypes available in Boto3 .

So i have come up with this script :

import boto3

def create_reminders_table():
    """Just create the reminders table."""
    session = boto3.session.Session(profile_name='dynamo_local')
    dynamodb = session.resource('dynamodb', endpoint_url="http://localhost:8000")
    table = dynamodb.create_table(
        TableName='Reminders',
        KeySchema=[
            {
                'AttributeName': 'reminder_id',
                'KeyType': 'HASH'
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'reminder_id',
                'AttributeType': 'S'
            },
            {
                'AttributeName': 'reminder_tag',
                'AttributeType': 'SS'
            },
            {
                'AttributeName': 'reminder_title',
                'AttributeType': 'S'
            }
        ],
        GlobalSecondaryIndexes=[
            {
                'IndexName': 'ReminderTagGsi',
                'KeySchema': [
                    {
                        'AttributeName': 'reminder_tag',
                        'KeyType': 'HASH'
                    }
                ],
                'Projection': {
                    'ProjectionType': 'INCLUDE',
                    'NonKeyAttributes': [
                        'reminder_title'
                    ]
                }
            },
            {
                'IndexName': 'ReminderTitleGsi',
                'KeySchema': [
                    {
                        'AttributeName': 'reminder_title',
                        'KeyType': 'HASH'
                    }
                ],
                'Projection': {
                    'ProjectionType': 'KEYS_ONLY'
                }
            }
        ],
        BillingMode='PAY_PER_REQUEST'
    )
    return table

if __name__ == '__main__':
    movie_table = create_reminders_table()
    print("Table status:", movie_table.table_status)

But when i run this i get the below issue:

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the CreateTable operation: Member must satisfy enum value set: [B, N, S]

I searched and came across this question asked by someone which has the same issue : https://forums.aws.amazon.com/thread.jspa?messageID=613970

Can someone please help me with this since the solution of not providing a datatype either does not work .

Also is it possible to have an index on a an attribute which is of value Set ? I mean i should enable the user to search for reminders with a tag , and for doing that i need to have a set.

Request someone to please help me regarding this.


问:
Simple Unity Grid Displays In Corrupted Fashion, Upon Camera Move, in Game View, Until Window Resized
I've recently migrated to the Universal Render Pipeline.

Here I have just the simplest scene. I am using an Orthographic camera. I have a prefab with a Sprite Renderer placed in the scene. The material is the Universal Render Pipeline/2D/Sprite-Unlit-Default material.

If I use the Inspector to adjust the tile position to the right, the tile smears in the game view. In the following I used the inspector to move the sprite to the right and then up.

Simply resizing the Game view, makes this smearing effect go away.

Why is this tile smearing in the game view? I did not see this before moving to the new rendering pipeline.

答:
It turns out that the problem seemed to be that the camera was in "Background Type" "Skybox", and this caused some problems with the Universal Rendering Pipeline. Not sure why this caused problems.. Perhaps I need to do something special with the skybox in the universal rendering pipeline.. However I dont want the sky box.. so I'm good for now.

As soon as I changed this to "Solid Color" the smearing issue went away.


问:
Plot() impulse response function - show more than one in one window?
I estimated a VAR - model and I want to show more than one IRF in one window. Is that possible with plot() ? I tried par(mfrow) but that didnt work. Any hints or ideas?

Thanks in advance

```<code>irf1 <- irf(Var1, n.ahead = 10, ortho = T,response="y2")
plot(irf1,main = "",xlab ="years",ylab="growth rate")
</code>```

答:
If ggplot2 is a proper solution for you, this function can help:

Example

library(tidyverse)

tsp.var.irf <- function(irf){

  if (class(irf) %in% "varirf") {
  } else{
    stop("Only 'varirf' class object from vars::irf()")
  }

  fortify <- function(data){
    result <- vector(mode = "list",length = 0L)
    for (d in 1:length(data)) {
      result[[length(result)+1]]<- tibble::tibble(imp = names(data)[d],
                                                  lag = 0:{nrow(data[[d]])-1},
                                                  tibble::as_tibble(data[[d]]))
    }
    data <- tidyr::unnest(tibble::tibble(result),cols = result)
    return(data)}

  data_irf <- fortify(irf$irf)
  data_lower <- fortify(irf$Lower)
  data_upper <- fortify(irf$Upper)
  suppressMessages(
    plot_data <- tibble::add_column(data_irf,type = "mean") %>%
      dplyr::full_join(tibble::add_column(data_lower,type = "lower")) %>%
      dplyr::full_join(tibble::add_column(data_upper,type = "upper")) %>%
      tidyr::pivot_longer(cols = -c(imp,lag,type)) %>%
      dplyr::mutate(imp = paste(imp,"(imp.)"),
                    name = paste(name,"(res.)")))

  plot <- ggplot2::ggplot(plot_data) +
    ggplot2::geom_line(ggplot2::aes(x = lag,value,
                                    lty = type),show.legend = F) +
    ggplot2::facet_grid(cols = ggplot2::vars(imp),
                        rows = ggplot2::vars(name)) +
    ggplot2::scale_linetype_manual(values = c("lower"=2,
                                              "upper"=2,
                                              "mean"=1)) +
    ggplot2::geom_hline(yintercept = 0,lty = 3) +
    ggplot2::scale_x_continuous(labels = as.integer)
  return(plot)
}

library(vars)
#> Loading required package: MASS
#>
#> Attaching package: 'MASS'
#> The following object is masked from 'package:dplyr':
#>
#>     select
#> Loading required package: strucchange
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#>     as.Date, as.Date.numeric
#> Loading required package: sandwich
#>
#> Attaching package: 'strucchange'
#> The following object is masked from 'package:stringr':
#>
#>     boundary
#> Loading required package: urca
#> Loading required package: lmtest
data("Canada")
model <- VAR(Canada,3)
model_irf <- irf(model)
tsp.var.irf(model_irf)
```

Created on 2022-02-11 by the reprex package (v1.0.0)

Body:
I estimated a VAR - model and I want to show more than one IRF in one window. Is that possible with plot() ? I tried par(mfrow) but that didnt work. Any hints or ideas?

Thanks in advance

irf1 <- irf(Var1, n.ahead = 10, ortho = T,response="y2")
plot(irf1,main = "",xlab ="years",ylab="growth rate")

Body:
If ggplot2 is a proper solution for you, this function can help:

Example

library(tidyverse)

tsp.var.irf <- function(irf){

  if (class(irf) %in% "varirf") {
  } else{
    stop("Only 'varirf' class object from vars::irf()")
  }

  fortify <- function(data){
    result <- vector(mode = "list",length = 0L)
    for (d in 1:length(data)) {
      result[[length(result)+1]]<- tibble::tibble(imp = names(data)[d],
                                                  lag = 0:{nrow(data[[d]])-1},
                                                  tibble::as_tibble(data[[d]]))
    }
    data <- tidyr::unnest(tibble::tibble(result),cols = result)
    return(data)}

  data_irf <- fortify(irf$irf)
  data_lower <- fortify(irf$Lower)
  data_upper <- fortify(irf$Upper)
  suppressMessages(
    plot_data <- tibble::add_column(data_irf,type = "mean") %>%
      dplyr::full_join(tibble::add_column(data_lower,type = "lower")) %>%
      dplyr::full_join(tibble::add_column(data_upper,type = "upper")) %>%
      tidyr::pivot_longer(cols = -c(imp,lag,type)) %>%
      dplyr::mutate(imp = paste(imp,"(imp.)"),
                    name = paste(name,"(res.)")))

  plot <- ggplot2::ggplot(plot_data) +
    ggplot2::geom_line(ggplot2::aes(x = lag,value,
                                    lty = type),show.legend = F) +
    ggplot2::facet_grid(cols = ggplot2::vars(imp),
                        rows = ggplot2::vars(name)) +
    ggplot2::scale_linetype_manual(values = c("lower"=2,
                                              "upper"=2,
                                              "mean"=1)) +
    ggplot2::geom_hline(yintercept = 0,lty = 3) +
    ggplot2::scale_x_continuous(labels = as.integer)
  return(plot)
}

library(vars)
#> Loading required package: MASS
#>
#> Attaching package: 'MASS'
#> The following object is masked from 'package:dplyr':
#>
#>     select
#> Loading required package: strucchange
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#>     as.Date, as.Date.numeric
#> Loading required package: sandwich
#>
#> Attaching package: 'strucchange'
#> The following object is masked from 'package:stringr':
#>
#>     boundary
#> Loading required package: urca
#> Loading required package: lmtest
data("Canada")
model <- VAR(Canada,3)
model_irf <- irf(model)
tsp.var.irf(model_irf)

Created on 2022-02-11 by the reprex package (v1.0.0)


问:
Cannot import gradle library in code, although it appears in my external libraries list
I am attempting to import kSOAP2 into my app. I used their instructions to import via Maven and attempted  translate it using Gradle. It shows up on the external repositories list, however when I try to add import com.google.code.ksoap2-android.ksoap2-android.3.6.4 it is not found.

Here is my build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.mylocationjava"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
    mavenCentral()
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation files('libs\\ksoap2-android-3.6.4.jar')

    implementation 'com.google.code.ksoap2-android:ksoap2-android:3.6.4'
}```

答:
I have done it like this:

build.gradle (module):

```<code>dependencies {
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.preference:preference:1.1.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.code.ksoap2-android:ksoap2-android:3.6.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
</code>```

settings.gradle:

```<code>pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
    }
}
rootProject.name = "idt.pda"
include ':app'

    }
</code>```

Body:
I have done it like this:

build.gradle (module):

dependencies {
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.preference:preference:1.1.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.code.ksoap2-android:ksoap2-android:3.6.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

settings.gradle:

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
    }
}
rootProject.name = "idt.pda"
include ':app'

    }


答:
Here's a solution using {tidyverse} packages. It's easiest if you just specify a list of what timestamps you care about in a separate vector. I assumed you just care about the hour but you can change the code if you want to be more granular (e.g. specify HH:MM or even down to HH:MM:SS). Then the rest is just group_by() summarize() and then mutate() to add a total column.

One issue is that it seems like you are sharing example data that doesn't contain the times_of_interest so the summary returns nothing. Similarly you are sharing data from a single date. In these cases the finally summary may not match your expectation. Therefore I first just looked for unique date/time combos to make sure we had a reasonable expectation on what the output would look like. You can also use table() to do this.

Aside from these issues, the code below still seems like it will produce the desired result based on the data you've shared.

library(tidyverse)
library(data.table)
library(lubridate)
library(hms)

d <- structure(list(date = structure(c(19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038), class = "Date"), type = c("USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD"), quantity = c(0.035, 0.011, 0.02, 0.02, 0.019, 0.036, 0.001, 0.003, 0.004, 0.065, 0.002, 0.001, 0.002, 0.002, 0.013), cumvol = c(0.035, 0.046, 0.066, 0.086, 0.105, 0.141, 0.142, 0.145, 0.149, 0.214, 0.216, 0.217, 0.219, 0.221, 0.234), time = structure(c(24422, 24430, 24453, 24463, 24468, 24476, 24485, 24583, 24790, 24862, 24950, 24953, 25047, 25085, 25085), units = "secs", class = c("hms", "difftime"))), row.names = c(NA, -15L), class = c("data.table", "data.frame"))

# check for unique times and dates
d %>%
  mutate(time_hr = hour(time)) %>%
  select(date, time_hr) %>%
  distinct()
#>          date time_hr
#> 1: 2022-02-15       6
## only one unique date and time_hr in sample data so summary should have 1 line

# set times of interest
# must be present in data to have an output
times_of_interest <- c(6)

d %>%
  mutate(time_hr = hour(time)) %>%
  filter(time_hr %in% times_of_interest) %>%
  group_by(date, type, time_hr) %>%
  summarize(cat_total = sum(quantity), .groups = "drop") %>%
  group_by(date) %>%
  mutate(date_total = sum(cat_total)) %>%
  ungroup()
#> # A tibble: 1 x 5
#>   date       type  time_hr cat_total date_total
#>   <date>     <chr>   <int>     <dbl>      <dbl>
#> 1 2022-02-15 USD         6     0.234      0.234
```

Created on 2022-02-15 by the reprex package (v2.0.1)

Title: Summary DataFrame: Aggregating data at specific timestamps for different categories and the day overall

Body:
I have a large dataframe that's updated every day containing the following:

structure(list(date = structure(c(19038, 19038, 19038, 19038,
19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038,
19038, 19038), class = "Date"), type = c("USD", "USD", "USD",
"USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD",
"USD", "USD", "USD"), quantity = c(0.035, 0.011, 0.02, 0.02,
0.019, 0.036, 0.001, 0.003, 0.004, 0.065, 0.002, 0.001, 0.002,
0.002, 0.013), cumvol = c(0.035, 0.046, 0.066, 0.086, 0.105,
0.141, 0.142, 0.145, 0.149, 0.214, 0.216, 0.217, 0.219, 0.221,
0.234), time = structure(c(24422, 24430, 24453, 24463, 24468,
24476, 24485, 24583, 24790, 24862, 24950, 24953, 25047, 25085,
25085), units = "secs", class = c("hms", "difftime"))), row.names = c(NA,
-15L), class = c("data.table", "data.frame"))

This is the code used to attempt to achieve the result (helpfully produced by Dan Adams)

 times_of_interest <- c(7, 9, 11)

d %>%
  mutate(across(everything(), as.character)) %>%
  mutate(across(quantity:cumvol, as.numeric)) %>%
  mutate(type = factor(type)) %>%
  mutate(date = ymd(date)) %>%
  mutate(time = as_hms(time)) %>%
  mutate(date = date + sample(0:1, nrow(.), T)) %>%
  mutate(time_hr = hour(time)) %>%
  filter(time_hr %in% times_of_interest) %>%
  group_by(date, type, time_hr) %>%
  summarize(cat_total = sum(quantity), .groups = "drop") %>%
  group_by(date) %>%
  mutate(date_total = sum(cat_total)) %>%
  ungroup()

The output delivers this:

structure(list(date = structure(c(19034, 19034, 19034, 19034,
19035, 19035, 19035, 19035, 19035, 19035, 19035, 19035, 19037,
19037, 19037, 19037, 19037, 19037, 19037, 19037, 19037, 19038,
19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19039,
19039, 19039), class = "Date"), type = structure(c(3L, 5L, 5L,
5L, 2L, 2L, 3L, 3L, 3L, 5L, 5L, 5L, 2L, 2L, 3L, 3L, 3L, 1L, 5L,
5L, 5L, 2L, 2L, 2L, 3L, 3L, 3L, 5L, 5L, 5L, 2L, 3L, 5L), .Label = c("DNB",
"UKY", "UKS", "T/N cl DBV", "USD"), class = "factor"), time_hr = c(11L,
7L, 9L, 11L, 9L, 11L, 7L, 9L, 11L, 7L, 9L, 11L, 9L, 11L, 7L,
9L, 11L, 11L, 7L, 9L, 11L, 7L, 9L, 11L, 7L, 9L, 11L, 7L, 9L,
11L, 7L, 7L, 7L), cat_total = c(0.739, 8.714, 3.281, 3.263, 0.815,
1.025, 2.071, 0.661, 0.328, 5.633, 0.776, 2.126, 0.465, 0.15,
2.046, 1.203, 0.137, 0.058, 2.341, 4.215, 1.705, 0.01, 0.335,
0.15, 4.323, 1.157, 0.031, 8.607, 3.624, 2.603, 0.865, 1.599,
5.721), date_total = c(9893.441, 9893.441, 9893.441, 9893.441,
9893.441, 9893.441, 9893.441, 9893.441, 9893.441, 9893.441, 9893.441,
9893.441, 9893.441, 9893.441, 9893.441, 9893.441, 9893.441, 9893.441,
9893.441, 9893.441, 9893.441, 9893.441, 9893.441, 9893.441, 9893.441,
9893.441, 9893.441, 9893.441, 9893.441, 9893.441, 9893.441, 9893.441,
9893.441)), row.names = c(NA, -33L), class = c("tbl_df", "tbl",
"data.frame"))

What I'd like to do is change the summary table so that it takes the total quantities in the types (and overall) at some specific timestamps; say 12:00, 15:00, and 16:00, for each day.

Unfortunately, for whatever reason the output for this dataframe is always at two times (the first two in the times_of_interest vector)./

str output is:

Classes ‘data.table’ and 'data.frame':  15 obs. of  5 variables:
 $ date    : Date, format: "2022-02-15" "2022-02-15" "2022-02-15" "2022-02-15" ...
 $ type    : chr  "USD" "USD" "USD" "USD" ...
 $ quantity: num  0.035 0.011 0.02 0.02 0.019 0.036 0.001 0.003 0.004 0.065 ...
 $ cumvol  : num  0.035 0.046 0.066 0.086 0.105 0.141 0.142 0.145 0.149 0.214 ...
 $ time    : 'hms' num  06:47:02 06:47:10 06:47:33 06:47:43 ...
  ..- attr(*, "units")= chr "secs"
 - attr(*, ".internal.selfref")=<externalptr>

Body:
Here's a solution using {tidyverse} packages. It's easiest if you just specify a list of what timestamps you care about in a separate vector. I assumed you just care about the hour but you can change the code if you want to be more granular (e.g. specify HH:MM or even down to HH:MM:SS). Then the rest is just group_by() summarize() and then mutate() to add a total column.

One issue is that it seems like you are sharing example data that doesn't contain the times_of_interest so the summary returns nothing. Similarly you are sharing data from a single date. In these cases the finally summary may not match your expectation. Therefore I first just looked for unique date/time combos to make sure we had a reasonable expectation on what the output would look like. You can also use table() to do this.

Aside from these issues, the code below still seems like it will produce the desired result based on the data you've shared.

library(tidyverse)
library(data.table)
library(lubridate)
library(hms)

d <- structure(list(date = structure(c(19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038, 19038), class = "Date"), type = c("USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD", "USD"), quantity = c(0.035, 0.011, 0.02, 0.02, 0.019, 0.036, 0.001, 0.003, 0.004, 0.065, 0.002, 0.001, 0.002, 0.002, 0.013), cumvol = c(0.035, 0.046, 0.066, 0.086, 0.105, 0.141, 0.142, 0.145, 0.149, 0.214, 0.216, 0.217, 0.219, 0.221, 0.234), time = structure(c(24422, 24430, 24453, 24463, 24468, 24476, 24485, 24583, 24790, 24862, 24950, 24953, 25047, 25085, 25085), units = "secs", class = c("hms", "difftime"))), row.names = c(NA, -15L), class = c("data.table", "data.frame"))

# check for unique times and dates
d %>%
  mutate(time_hr = hour(time)) %>%
  select(date, time_hr) %>%
  distinct()
#>          date time_hr
#> 1: 2022-02-15       6
## only one unique date and time_hr in sample data so summary should have 1 line

# set times of interest
# must be present in data to have an output
times_of_interest <- c(6)

d %>%
  mutate(time_hr = hour(time)) %>%
  filter(time_hr %in% times_of_interest) %>%
  group_by(date, type, time_hr) %>%
  summarize(cat_total = sum(quantity), .groups = "drop") %>%
  group_by(date) %>%
  mutate(date_total = sum(cat_total)) %>%
  ungroup()
#> # A tibble: 1 x 5
#>   date       type  time_hr cat_total date_total
#>   <date>     <chr>   <int>     <dbl>      <dbl>
#> 1 2022-02-15 USD         6     0.234      0.234

Created on 2022-02-15 by the reprex package (v2.0.1)


问:
No available shapes in this compartment and availability domain
I'm using the OCI San Jose region and I'm trying to create a capacity reservation in OCI under Compute -> Capacity Reservation but whenever I try to create a capacity reservation, the Shape dropdown list is greyed out with the message:

```<code>No available shapes in this compartment and availability domain
</code>```

Does this mean that this region is at capacity and is not capable of reservations at this time?  Or is there a limit or restriction I'm not aware of?

I've been trying each day this week but the message remains the same.

答:
It does mean that for that specific shape, the region is at capacity and not capable of taking reservations. You can certainly file a support request to find the capacity situation.  This does seem to indicate that your use of reservations is sound practice.

You can also use the command line interface to check the region for available shapes:

$ oci compute shape list
or better
$ oci compute shape list | jq -r .data[].shape | sort | uniq

Body:
I'm using the OCI San Jose region and I'm trying to create a capacity reservation in OCI under Compute -> Capacity Reservation but whenever I try to create a capacity reservation, the Shape dropdown list is greyed out with the message:

No available shapes in this compartment and availability domain

Does this mean that this region is at capacity and is not capable of reservations at this time?  Or is there a limit or restriction I'm not aware of?

I've been trying each day this week but the message remains the same.


问:
Docker cannot start on Windows
Executing docker version command on Windows returns the following results:

```<code>C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
</code>```

Running the diagnostics produces the following:

```<code>C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at <ScriptBlock>, <No file>: line 27
 [+] Service is running 127ms
 [+] Docker.exe is in path 2.14s
Describing User has permissions to use Docker daemon
 [+] docker.exe should not return access denied 42ms
Describing Windows container settings are correct
 [-] Do not have DisableVSmbOplock set to 1 53ms
   Expected: {0}
   But was:  {1}
   66:              $regvalue.VSmbDisableOplocks | Should Be 0
   at <ScriptBlock>, <No file>: line 66
 [+] Do not have zz values set 42ms
Describing The right container base images are installed
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/images/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
 [-] At least one of 'microsoft/windowsservercore' or 'microsoft/nanoserver' should be installed 129ms
   ValidationMetadataException: The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   ParameterBindingValidationException: Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   at <ScriptBlock>, <No file>: line 90
Describing Container network is created
 [-] Error occurred in Describe block 1.08s
   RuntimeException: Cannot index into a null array.
   at <ScriptBlock>, <No file>: line 119
Showing output from: docker info

Showing output from: docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64

Showing output from: docker network ls

Warnings & errors from the last 24 hours
Logs saved to C:\Projects\logs_20161107-084122.csv
C:\Projects>
</code>```

答: For me on Windows 11, editing %APPDATA%\Docker\settings.json to the following values and then restarting Docker Desktop did the trick (I am using WSL2, not Hyper-V):

Title: Docker cannot start on Windows

Body:
Executing docker version command on Windows returns the following results:

C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

Running the diagnostics produces the following:

C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at


问:
How to trigger “Ok google” from adb shell?
I'm trying to simulate "Ok google" from adb shell on Android O(8.0), but I couldn't find solution.

I've found that the app which shows after "Ok google" has cmp=com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity.
However, I couldn't launch it via adb due to below error.

```<code>$adb shell am start -n com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity
Starting: Intent { cmp=com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity }
Security exception: Permission Denial: starting Intent { flg=0x10000000 cmp=com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity } from null (pid=29706, uid=2000) not exported from uid 10044

java.lang.SecurityException: Permission Denial: starting Intent { flg=0x10000000 cmp=com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity } from null (pid=29706, uid=2000) not exported from uid 10044
    at com.android.server.am.ActivityStackSupervisor.checkStartAnyActivityPermission(ActivityStackSupervisor.java:1688)
    at com.android.server.am.ActivityStarter.startActivity(ActivityStarter.java:460)
    at com.android.server.am.ActivityStarter.startActivityLocked(ActivityStarter.java:277)
    at com.android.server.am.ActivityStarter.startActivityMayWait(ActivityStarter.java:920)
    at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:4693)
    at com.android.server.am.ActivityManagerShellCommand.runStartActivity(ActivityManagerShellCommand.java:410)
    at com.android.server.am.ActivityManagerShellCommand.onCommand(ActivityManagerShellCommand.java:141)
    at android.os.ShellCommand.exec(ShellCommand.java:96)
    at com.android.server.am.ActivityManagerService.onShellCommand(ActivityManagerService.java:15401)
    at android.os.Binder.shellCommand(Binder.java:576)
    at android.os.Binder.onTransact(Binder.java:476)
    at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:4341)
    at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3040)
    at android.os.Binder.execTransact(Binder.java:681)
</code>```

I expect some solution to launch the above app by adb.

Avoid security exception for $adb shell am start -n com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity

By another adb command

答:
```<code>adb root
adb shell am start -n com.google.android.googlequicksearchbox/com.google.android.apps.gsa.binaries.clockwork.assistant.AssistantActivity
</code>```

worked for me on my Galaxy Watch 4 after I installed the Google App.

Body:
I'm trying to simulate "Ok google" from adb shell on Android O(8.0), but I couldn't find solution.

I've found that the app which shows after "Ok google" has cmp=com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity.
However, I couldn't launch it via adb due to below error.

$adb shell am start -n com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity
Starting: Intent { cmp=com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity }
Security exception: Permission Denial: starting Intent { flg=0x10000000 cmp=com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity } from null (pid=29706, uid=2000) not exported from uid 10044

java.lang.SecurityException: Permission Denial: starting Intent { flg=0x10000000 cmp=com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity } from null (pid=29706, uid=2000) not exported from uid 10044
    at com.android.server.am.ActivityStackSupervisor.checkStartAnyActivityPermission(ActivityStackSupervisor.java:1688)
    at com.android.server.am.ActivityStarter.startActivity(ActivityStarter.java:460)
    at com.android.server.am.ActivityStarter.startActivityLocked(ActivityStarter.java:277)
    at com.android.server.am.ActivityStarter.startActivityMayWait(ActivityStarter.java:920)
    at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:4693)
    at com.android.server.am.ActivityManagerShellCommand.runStartActivity(ActivityManagerShellCommand.java:410)
    at com.android.server.am.ActivityManagerShellCommand.onCommand(ActivityManagerShellCommand.java:141)
    at android.os.ShellCommand.exec(ShellCommand.java:96)
    at com.android.server.am.ActivityManagerService.onShellCommand(ActivityManagerService.java:15401)
    at android.os.Binder.shellCommand(Binder.java:576)
    at android.os.Binder.onTransact(Binder.java:476)
    at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:4341)
    at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3040)
    at android.os.Binder.execTransact(Binder.java:681)

I expect some solution to launch the above app by adb.

Avoid security exception for $adb shell am start -n com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.opa.OpaActivity

By another adb command

Body:
adb root
adb shell am start -n com.google.android.googlequicksearchbox/com.google.android.apps.gsa.binaries.clockwork.assistant.AssistantActivity

worked for me on my Galaxy Watch 4 after I installed the Google App.


问:
Php format on save in Visual Studio Code
Can you format on save PHP as well with the Beautify extension of Visual Code ? If yes how do you set it up ? If not which extension does that?

答:
Elaborating on Zain's answer, I'm writing PHP and React and want to auto format both.

First install "PHP Intelephense" extension to format PHP and the "Prettier" extension to format JS. Then open VS Studio Code's settings and:

click the icon in the top right corner to edit as JSON

Remove any generic default formatter setting

Add JavaScript and React formatter settings

Add PHP formatter setting

Save


问:
Django - AttributeError _committed
I have a form that saves an image, and everything is working fine, but I want to be able to crop the image.  However, when I used Pillow to do this, I get a strange error that doesn't really give me much to go on.

Attribute error at /userprofile/addGame/

_committed

Looking further into the traceback, the following sections were highlighted:

I'm not really sure what this error means.  I think it has something to do with the form.save(committed=False), and not being able to edit files after that point, but I'm not positive.  I can edit the user after that line using form.user = request.user, so I think it's the fact that I'm trying to change the image getting uploaded that is part of the issue.

答:
I had faced the same issue trying to save a model with an ImageFileField. My requirement was to save an image from a zip object.

Using pillow gave me the AttributeError: _committed error. Following is what worked for me:

```<code>from django.core.files.images import ImageFile

zf =  zipfile.ZipFile(zip_file, mode='r')
image_list = zf.infolist()

Model.objects.create(img=ImageFile(zipObj.open(image_list[0])),
                     file_name=image_list[0].filename.split("/")[-1].strip(),
                               ...)
</code>```

Title: Django - AttributeError _committed

Body:
I had faced the same issue trying to save a model with an ImageFileField. My requirement was to save an image from a zip object.

Using pillow gave me the AttributeError: _committed error. Following is what worked for me:

from django.core.files.images import ImageFile

zf =  zipfile.ZipFile(zip_file, mode='r')
image_list = zf.infolist()

Model.objects.create(img=ImageFile(zipObj.open(image_list[0])),
                     file_name=image_list[0].filename.split("/")[-1].strip(),
                               ...)


问:
Looping through each cell of a column in Excel using Python
I have an Excel file with data in column A. I want to loop through each cell and stop once i reach the first cell that has a formula.

This is my code:

```<code>wb = openpyxl.load_workbook(r"path\filename.xlsx")

sheet = wb['Sheet1']

names=sheet['A']

for cellObj in names:

  if cellObj.value.str[0] == '=':
     print(cellObj.value)
</code>```

But i get an error...

The response from @John Giorgio worked for that part.

Now what i'm trying to do next is to select the entire row and paste special.

Here's my code:

```<code>import openpyxl
wb=openpyxl.load_workbook(path1)
sheet = wb['Sheet1']

names=sheet['A']

for cellObj in names:
    val = str(cellObj.value)
    if val[0] == "=":
        #print(val)

        excel.Range("A10:TM10").Select() #PART I WANT TO SELECT IF TRUE
        excel.Selection.PasteSpecial(Paste=-4163)
</code>```

So once I come across the first cell with '=' i want to select the entire row or at least from column A to TM and hardcode it / pasteSpecial

答:
```<code>wb = openpyxl.load_workbook(r"path\filename.xlsx")

sheet = wb['Sheet1']

names=sheet['A']

for cellObj in names:
    val = str(cellObj.value)
    if val[0] == "=":
        print(val)
</code>```

Body:
I have an Excel file with data in column A. I want to loop through each cell and stop once i reach the first cell that has a formula.

This is my code:

wb = openpyxl.load_workbook(r"path\filename.xlsx")

sheet = wb['Sheet1']

names=sheet['A']

for cellObj in names:

  if cellObj.value.str[0] == '=':
     print(cellObj.value)

But i get an error...

The response from @John Giorgio worked for that part.

Now what i'm trying to do next is to select the entire row and paste special.

Here's my code:

import openpyxl
wb=openpyxl.load_workbook(path1)
sheet = wb['Sheet1']

names=sheet['A']

for cellObj in names:
    val = str(cellObj.value)
    if val[0] == "=":
        #print(val)

        excel.Range("A10:TM10").Select() #PART I WANT TO SELECT IF TRUE
        excel.Selection.PasteSpecial(Paste=-4163)

So once I come across the first cell with '=' i want to select the entire row or at least from column A to TM and hardcode it / pasteSpecial


问:
How can I check for differences across multiple columns in different datasets (in R)?
I feel like this may be a common question but I haven't been able to find an answer so far. I have two datasets, one "standard" and one "reference" dataset. In practice, the columns in the standard dataset are used to merge many columns from the reference dataset, simulated here as "xtracols". One thing I need to be able to do is know why the merge fails, if that happens. For example, if I have the two dataframes:

```<code>df <- data.frame(
  id = c(1,2,3),
  batch = c(40,45,42),
  dil = c(100, 1000, 2000)
)

refdf <- data.frame(
  id = c(rep(1, 5), rep(2, 5), rep(3, 5)),
  batch = c(rep(40, 5), rep(41, 5), rep(42, 5)),
  dil = rep(c(1, 10, 100, 1000, 10000), 3),
  xtrcols = rep(c("a", "b", "c"), 5)
)
</code>```

and I merge like this:

```<code>merged <- merge(df, refdf, by = c("id", "batch", "dil"), all.x = TRUE)
</code>```

I need to know if the merge for a given "id" failed because the batch is incorrect, such as would be the case for id = 2, or if the merge failed because the value for "dil" does not exist in refdf, as would be the case for id = 3. I've tried a few ways of iterating through the dataframes and using match(), but so far nothing has really worked as anticipated.

This would be my anticipated outcome of running the code above. The merge failed for ids 2 and 3, but for different reasons. I'm trying to find a way to know which of those two reasons the merge failed so I can return a specific error message based on that.

Any insight would be much appreciated.

答:
Update after changed dataframes:
With the changed dataframes:
Again anti_join will help:

```<code>anti_join(df, refdf, by=c("id", "batch", "dil"))
</code>```
```<code>  id batch  dil
1  2    45 1000
2  3    42 2000
</code>```

First answer:
We could use anti_join: anti_join() return all rows from x without a match in y.

```<code>library(dplyr)

anti_join(df, refdf, by=c("id", "batch"))
</code>```
```<code>  id batch  dil
1  2    45 1000
</code>```

Body:
I feel like this may be a common question but I haven't been able to find an answer so far. I have two datasets, one "standard" and one "reference" dataset. In practice, the columns in the standard dataset are used to merge many columns from the reference dataset, simulated here as "xtracols". One thing I need to be able to do is know why the merge fails, if that happens. For example, if I have the two dataframes:

df <- data.frame(
  id = c(1,2,3),
  batch = c(40,45,42),
  dil = c(100, 1000, 2000)
)

refdf <- data.frame(
  id = c(rep(1, 5), rep(2, 5), rep(3, 5)),
  batch = c(rep(40, 5), rep(41, 5), rep(42, 5)),
  dil = rep(c(1, 10, 100, 1000, 10000), 3),
  xtrcols = rep(c("a", "b", "c"), 5)
)

and I merge like this:

merged <- merge(df, refdf, by = c("id", "batch", "dil"), all.x = TRUE)

I need to know if the merge for a given "id" failed because the batch is incorrect, such as would be the case for id = 2, or if the merge failed because the value for "dil" does not exist in refdf, as would be the case for id = 3. I've tried a few ways of iterating through the dataframes and using match(), but so far nothing has really worked as anticipated.

This would be my anticipated outcome of running the code above. The merge failed for ids 2 and 3, but for different reasons. I'm trying to find a way to know which of those two reasons the merge failed so I can return a specific error message based on that.

Any insight would be much appreciated.

Body:
Update after changed dataframes:
With the changed dataframes:
Again anti_join will help:

anti_join(df, refdf, by=c("id", "batch", "dil"))

  id batch  dil
1  2    45 1000
2  3    42 2000

First answer:
We could use anti_join: anti_join() return all rows from x without a match in y.

library(dplyr)

anti_join(df, refdf, by=c("id", "batch"))

  id batch  dil
1  2    45 1000


问:
Getting empty file while converting XML to CSV file Pandas Python
This is my XML file

```<code><Lieferantenbestellungen>
  <Lieferantenbestellung>
    <Jahr>2021</Jahr>
    <Nummer>1</Nummer>
    <Datum>2021-01-07</Datum>
    <Lieferant_ID>459</Lieferant_ID>
    <Positionen>
      <Position Artikel="MCGPXO96" Bezeichnung="Refined Rubber Tuna" Menge="1" />
      <Position Artikel="IYTAFI28" Bezeichnung="Generic Cotton Chicken" Menge="8" />
    </Positionen>
  </Lieferantenbestellung>
</Lieferantenbestellungen>
</code>```

I want to extract the Lieferant_ID, Artikel, Bezeichnung, Bezeichnung and Menge from the file.

I have this python code:

```<code>with open('Lieferantenbestellungen.xml', 'r') as f:
    soup = BeautifulSoup(f.read(), 'lxml')

# Get the data you want
df = pd.DataFrame(list(zip(
  [el.text for el in soup.find_all('Lieferant_ID')],
  [el.text for el in soup.find_all('Artikel')],
  [el.text for el in soup.find_all('Bezeichnung')],
  [el.text for el in soup.find_all('Menge')]
)), columns=['Lieferant_ID', 'Artikel', 'Bezeichnung', 'Menge'])

# Dump to csv
df.to_csv('out.csv', index=False)
</code>```

When I run the code it generates the CSV file but it's empty. Does anyone have any idea of what am I doing wrong?

Expected CSV output:

Thanks in advance

答:
pandas now has .read_xml() which you can use directly.

```<code>>>> pd.read_xml('Lieferantenbestellungen.xml', xpath='.//Lieferant_ID | .//Position')
   Lieferant_ID   Artikel             Bezeichnung  Menge
0         459.0      None                    None    NaN
1           NaN  MCGPXO96     Refined Rubber Tuna    1.0
2           NaN  IYTAFI28  Generic Cotton Chicken    8.0
</code>```

You can .ffill() and .dropna() to "align" the results.

```<code>>>> df = pd.read_xml('Lieferantenbestellungen.xml', xpath='.//Lieferant_ID | .//Position')
>>> df['Lieferant_ID'] = df['Lieferant_ID'].ffill()
>>> df.dropna()
   Lieferant_ID   Artikel             Bezeichnung  Menge
1         459.0  MCGPXO96     Refined Rubber Tuna    1.0
2         459.0  IYTAFI28  Generic Cotton Chicken    8.0
</code>```

Body:
This is my XML file

<Lieferantenbestellungen>
  <Lieferantenbestellung>
    <Jahr>2021</Jahr>
    <Nummer>1</Nummer>
    <Datum>2021-01-07</Datum>
    <Lieferant_ID>459</Lieferant_ID>
    <Positionen>
      <Position Artikel="MCGPXO96" Bezeichnung="Refined Rubber Tuna" Menge="1" />
      <Position Artikel="IYTAFI28" Bezeichnung="Generic Cotton Chicken" Menge="8" />
    </Positionen>
  </Lieferantenbestellung>
</Lieferantenbestellungen>

I want to extract the Lieferant_ID, Artikel, Bezeichnung, Bezeichnung and Menge from the file.

I have this python code:

with open('Lieferantenbestellungen.xml', 'r') as f:
    soup = BeautifulSoup(f.read(), 'lxml')

# Get the data you want
df = pd.DataFrame(list(zip(
  [el.text for el in soup.find_all('Lieferant_ID')],
  [el.text for el in soup.find_all('Artikel')],
  [el.text for el in soup.find_all('Bezeichnung')],
  [el.text for el in soup.find_all('Menge')]
)), columns=['Lieferant_ID', 'Artikel', 'Bezeichnung', 'Menge'])

# Dump to csv
df.to_csv('out.csv', index=False)

When I run the code it generates the CSV file but it's empty. Does anyone have any idea of what am I doing wrong?

Expected CSV output:

Thanks in advance

Body:
pandas now has .read_xml() which you can use directly.

>>> pd.read_xml('Lieferantenbestellungen.xml', xpath='.//Lieferant_ID | .//Position')
   Lieferant_ID   Artikel             Bezeichnung  Menge
0         459.0      None                    None    NaN
1           NaN  MCGPXO96     Refined Rubber Tuna    1.0
2           NaN  IYTAFI28  Generic Cotton Chicken    8.0

You can .ffill() and .dropna() to "align" the results.

>>> df = pd.read_xml('Lieferantenbestellungen.xml', xpath='.//Lieferant_ID | .//Position')
>>> df['Lieferant_ID'] = df['Lieferant_ID'].ffill()
>>> df.dropna()
   Lieferant_ID   Artikel             Bezeichnung  Menge
1         459.0  MCGPXO96     Refined Rubber Tuna    1.0
2         459.0  IYTAFI28  Generic Cotton Chicken    8.0