问:
How to disconnect from PhotonNetwork after a game is Played in Unity?
Right I found this question asked elsewhere but I am really stuck at the point where none of the solution is unfortunately working.

So when the game gets over, I have to load either the menu screen or random battle screen or the friends screen. But somehow I am trying my heart out to disconnect when I click the random screen button and friends screen button. But it is just not disconnecting.

The code is as follows:

```<code>public class GameOverManagerMP : MonoBehaviourPunCallbacks
{

     public void OnClickRandomScreenButton()
        {
           MultiPlayerScoreManager.instance.NextSceneToBeLoaded =
          "MatchMakingScreen";
           PhotonNetwork.LeaveRoom();
        }

        public void OnClickFriendsScreenButton()
        {
         MultiPlayerScoreManager.instance.NextSceneToBeLoaded = "FriendsScreen";
         PhotonNetwork.LeaveRoom();
        }

         public override void OnLeftRoom()
         {
            Debug.Log("On left room executed in Game Over Manger class.........");
            base.OnLeftRoom();
            PhotonNetwork.Disconnect();
         }

        public override void OnDisconnected(DisconnectCause cause)
        {
            Debug.Log("On OnDisconnected executed in Game Over Manger class.........");
            base.OnDisconnected(cause);
            SceneManager.LoadScene( MultiPlayerScoreManager.instance.NextSceneToBeLoaded );
        }
}
</code>```

So basically I got the error the  is attached here:

```<code>operation leaveRoom(254) not called because Client is not............
</code>```

So what I did was I put

```<code>if(PhotonNetwork.InRoom)
  PhotonNetwork.leaveRoom()
</code>```

The error disappears but nothing happens, meaning the OnDisconnected Callback never executes...

I even tried this code

```<code> if (PhotonNetwork.IsConnected)
        {
         StartCoroutine(Disconnect());
        }

IEnumerator Disconnect()
{
    PhotonNetwork.Disconnect();
    while (PhotonNetwork.IsConnected)
    {
        yield return null;
        Debug.Log("Disconnecting. . .");
    }
    Debug.Log("DISCONNECTED!");
}
</code>```

But it doesn't hit the line "DISCONNECTED!". It is in an infinte loop with saying "Disconnecting..."

The whole part is when I stop playing in Unity, then the OnLeftRoom and OnDisconnected function gets executed . I have highlighed with a red rectangle around it in the screenshot as indicated above.

As per this answer, it is said that the callback OnConnectedToMaster will be executed. I implemented that callback also but nothing inside it is getting printed.Infact I implemented every callback, not is happening

In my game I have to disconnect entirely before connecting again but somehow it is not happening.How do you actually do it?

答:
In the screenshot, you already see your log "On OnDisconnected". It may not load something but the client is disconnected and you got the callback.

Why you get the error logs: You seem to be calling PhotonNetwork.LeaveRoom() more than once while it processes. This is likely because there is no visible feedback to the user that the client will leave the room and reconnect to the Master Server. It does not Disconnect in this case. Call PhotonNetwork.Disconnect(), if you want the client to go offline and wait for the callback.

Body:
Right I found this question asked elsewhere but I am really stuck at the point where none of the solution is unfortunately working.

So when the game gets over, I have to load either the menu screen or random battle screen or the friends screen. But somehow I am trying my heart out to disconnect when I click the random screen button and friends screen button. But it is just not disconnecting.

The code is as follows:

public class GameOverManagerMP : MonoBehaviourPunCallbacks
{

     public void OnClickRandomScreenButton()
        {
           MultiPlayerScoreManager.instance.NextSceneToBeLoaded =
          "MatchMakingScreen";
           PhotonNetwork.LeaveRoom();
        }

        public void OnClickFriendsScreenButton()
        {
         MultiPlayerScoreManager.instance.NextSceneToBeLoaded = "FriendsScreen";
         PhotonNetwork.LeaveRoom();
        }

         public override void OnLeftRoom()
         {
            Debug.Log("On left room executed in Game Over Manger class.........");
            base.OnLeftRoom();
            PhotonNetwork.Disconnect();
         }

        public override void OnDisconnected(DisconnectCause cause)
        {
            Debug.Log("On OnDisconnected executed in Game Over Manger class.........");
            base.OnDisconnected(cause);
            SceneManager.LoadScene( MultiPlayerScoreManager.instance.NextSceneToBeLoaded );
        }
}

So basically I got the error the  is attached here:

operation leaveRoom(254) not called because Client is not............

So what I did was I put

if(PhotonNetwork.InRoom)
  PhotonNetwork.leaveRoom()

The error disappears but nothing happens, meaning the OnDisconnected Callback never executes...

I even tried this code

 if (PhotonNetwork.IsConnected)
        {
         StartCoroutine(Disconnect());
        }

IEnumerator Disconnect()
{
    PhotonNetwork.Disconnect();
    while (PhotonNetwork.IsConnected)
    {
        yield return null;
        Debug.Log("Disconnecting. . .");
    }
    Debug.Log("DISCONNECTED!");
}

But it doesn't hit the line "DISCONNECTED!". It is in an infinte loop with saying "Disconnecting..."

The whole part is when I stop playing in Unity, then the OnLeftRoom and OnDisconnected function gets executed . I have highlighed with a red rectangle around it in the screenshot as indicated above.

As per this answer, it is said that the callback OnConnectedToMaster will be executed. I implemented that callback also but nothing inside it is getting printed.Infact I implemented every callback, not is happening

In my game I have to disconnect entirely before connecting again but somehow it is not happening.How do you actually do it?


来源: stackexchange

问:
What is “assert” in JavaScript?
What does assert mean in JavaScript?

I’ve seen something like:

```<code>assert(function1() && function2() && function3(), "some text");
</code>```

And would like to know what the method assert() does.

答: assert() is the assert function in JavaScript. The main idea of assertion is to find why/where the bug occurs.

ContentLicense: CC BY-SA 3.0

Title: What is “assert” in JavaScript?

Body:
What does assert mean in JavaScript?

I’ve seen something like:

assert(function1() && function2() && function3(), "some text");

And would like to know what the method assert() does.

ContentLicense: CC BY-SA 4.0


问:
jquery selecting elements and removing classes with partial class names
I have the following piece of JQuery code which searches an html document for instances of elements with the class <xyz>-annotation-invisible and replaces it with <xyz>-annotation-visible. The catch is that if a particular element already has class <abc>-annotation-visible, then I want to remove all classes of the form *-annotation-visible and *-annotation-invisible and replace them with the class multiple-annotation-visible. How can I check if a particular element already has <abc>-annotation-visible?

```<code>const urlParams = new URLSearchParams(window.location.search);
const annotationTypes = urlParams.get('annotypes').split(',');
const multipleVisibleClass = "multiple-annotation-visible";

$(document).ready(function () {
  for (var i=0; i<annotationTypes.length; i++)
  {
    var annotype = annotationTypes[i];
    var annotationVisibleClass = `${annotype}-annotation-visible`;
    var annotationInvisibleClass = `${annotype}-annotation-invisible`;

    var elem = $(`.${annotationInvisibleClass}`);
    if (elem.hasClass(anyVisibleClass)) # not sure how to do this part
    {
      elem.removeClass(anyVisibleClass);
      elem.addClass(multipleVisibleClass);
    }
    else
    {
      elem.addClass(annotationVisibleClass);
    }
    elem.removeClass(annotationInvisibleClass);
  }
});
</code>```

答:
You can get the classes of the targeted elements, split the classes into array and then manipulate the array to get desired results. Try this</p>
```<code>const urlParams       = new URLSearchParams(window.location.search);
const annotationTypes = urlParams?.get('annotypes')?.split(',') ?? [];

$(document).ready(function(){
    annotationTypes.forEach(annotype => {
        let visible   = `${annotype}-annotation-visible`;
        let invisible = `${annotype}-annotation-invisible`;
        let multiple  = "multiple-annotation-visible";

        $(`.${invisible}, .${visible}`).each(function(){
            let arr = [];
            $(this).attr('class').split(' ').forEach(cls => {
                if(cls === invisible){
                    arr.push(visible);
                }else if(cls === visible){
                    arr.push(multiple);
                }else{
                    arr.push(cls);
                }
            });
            $(this).attr('class', arr.join(' '));
        })
    })
});
</code>```

Body:
I have the following piece of JQuery code which searches an html document for instances of elements with the class <xyz>-annotation-invisible and replaces it with <xyz>-annotation-visible. The catch is that if a particular element already has class <abc>-annotation-visible, then I want to remove all classes of the form *-annotation-visible and *-annotation-invisible and replace them with the class multiple-annotation-visible. How can I check if a particular element already has <abc>-annotation-visible?

const urlParams = new URLSearchParams(window.location.search);
const annotationTypes = urlParams.get('annotypes').split(',');
const multipleVisibleClass = "multiple-annotation-visible";

$(document).ready(function () {
  for (var i=0; i<annotationTypes.length; i++)
  {
    var annotype = annotationTypes[i];
    var annotationVisibleClass = `${annotype}-annotation-visible`;
    var annotationInvisibleClass = `${annotype}-annotation-invisible`;

    var elem = $(`.${annotationInvisibleClass}`);
    if (elem.hasClass(anyVisibleClass)) # not sure how to do this part
    {
      elem.removeClass(anyVisibleClass);
      elem.addClass(multipleVisibleClass);
    }
    else
    {
      elem.addClass(annotationVisibleClass);
    }
    elem.removeClass(annotationInvisibleClass);
  }
});

Body:
You can get the classes of the targeted elements, split the classes into array and then manipulate the array to get desired results. Try this

const urlParams       = new URLSearchParams(window.location.search);
const annotationTypes = urlParams?.get('annotypes')?.split(',') ?? [];

$(document).ready(function(){
    annotationTypes.forEach(annotype => {
        let visible   = `${annotype}-annotation-visible`;
        let invisible = `${annotype}-annotation-invisible`;
        let multiple  = "multiple-annotation-visible";

        $(`.${invisible}, .${visible}`).each(function(){
            let arr = [];
            $(this).attr('class').split(' ').forEach(cls => {
                if(cls === invisible){
                    arr.push(visible);
                }else if(cls === visible){
                    arr.push(multiple);
                }else{
                    arr.push(cls);
                }
            });
            $(this).attr('class', arr.join(' '));
        })
    })
});


问:
webpack-dev-server 4 with ngrok
In older versions of webpack-dev-server (i.e 3 and below), we can simply expose webpack and webpack-dev-server's websock using ngrok tunnels by setting the value of devServer.public, as shown below:

```<code>// WDS v3
devServer: {
  public: 'react-tunnel.ngrok.io',
  // other webpack devServer config
}
</code>```

This is particularly useful in developing apps in frameworks like React, as we can create a secure tunnel from the local machine, to a public URL to allow the web application to be easily tested.

However, in the latest versions of webpack-dev-server (v4), the public property has been replaced in favour client.webSocketURL object (source). I am unable to find any resources to make this work with ngrok, as the websockets are not properly connected when I point the devServer.client.webSocketURL.hostname to my ngrok tunnel.

```<code>// WDS v4

devServer: {
  client: {
    webSocketURL: {
      hostname: 'react-tunnel.ngrok.io',
    },
  },
}
</code>```

The above implementation is only a partial solution, as the websocket was not properly set up, thus it does not hot-reload.

Does anyone know what is the solution to this, such that ngrok will once again work well with webpack-dev-server?

答:
You also need to provide port and protocol to make it work.
For example,

devServer: {
  client: {
    webSocketURL: {
      hostname: 'react-tunnel.ngrok.io',
      port: 0,
      protocol: 'wss',
    },
  },
}
```
<p>With above settings, your website may work in ngrok tunnel, but wont work in localhost.
To connect to the web socket regardless of url, you can set <code>webSocketURL</code> to <code>auto://0.0.0.0:0/ws</code>, which uses protocol, hostname, and port from browser. doc</p>
<p>This should fix hot-reloading problem as well.</p>
<pre class="lang-json prettyprint-override"><code>devServer: {
  client: {
    webSocketURL: 'auto://0.0.0.0:0/ws'
  },
}
</code>```

Title: webpack-dev-server 4 with ngrok

Body:
In older versions of webpack-dev-server (i.e 3 and below), we can simply expose webpack and webpack-dev-server's websock using ngrok tunnels by setting the value of devServer.public, as shown below:

// WDS v3
devServer: {
  public: 'react-tunnel.ngrok.io',
  // other webpack devServer config
}

This is particularly useful in developing apps in frameworks like React, as we can create a secure tunnel from the local machine, to a public URL to allow the web application to be easily tested.

However, in the latest versions of webpack-dev-server (v4), the public property has been replaced in favour client.webSocketURL object (source). I am unable to find any resources to make this work with ngrok, as the websockets are not properly connected when I point the devServer.client.webSocketURL.hostname to my ngrok tunnel.

// WDS v4

devServer: {
  client: {
    webSocketURL: {
      hostname: 'react-tunnel.ngrok.io',
    },
  },
}

The above implementation is only a partial solution, as the websocket was not properly set up, thus it does not hot-reload.

Does anyone know what is the solution to this, such that ngrok will once again work well with webpack-dev-server?

Body:
You also need to provide port and protocol to make it work.
For example,

devServer: {
  client: {
    webSocketURL: {
      hostname: 'react-tunnel.ngrok.io',
      port: 0,
      protocol: 'wss',
    },
  },
}

With above settings, your website may work in ngrok tunnel, but wont work in localhost.
To connect to the web socket regardless of url, you can set webSocketURL to auto://0.0.0.0:0/ws, which uses protocol, hostname, and port from browser. doc

This should fix hot-reloading problem as well.

devServer: {
  client: {
    webSocketURL: 'auto://0.0.0.0:0/ws'
  },
}


问:
Multiple webpages with common title and navigation bars
I'm making a small personal academic website, which has multiple pages with a common structure.

Question: Is there a way to not repeat the code for the header and the menu (or navigation bar) in each of the html files? It would be great if I could put the code for the header and menu in another file, e.g. header.html and write a statement such as \input{header.html} (using TeX syntax) to include the file into index.html and publications.html.

Below is an example of what the website looks like.

Contents of index.html:

```<code><!DOCTYPE html>

<html>
    <head>
        <title>The Title</title>
        <link type="text/css" rel="stylesheet" href="stylesheet.css">
    </head>
    <body>
        <div id="header">
            <h1>My Name</h1>
        </div>

        <div id="menu">
            <p>
                <a href="index.html">Home</a>
                &nbsp&nbsp
                <a href="publications.html">Publications</a>
                &nbsp&nbsp
                <a href="contact.html">Contact</a>
            </p>
        </div>

        <div id="content">
            <p>
                This is my academic webpage.
            </p>
            <p>
                I am a 15th year PhD student in Filmmaking at Mickey's Institute of Technology (MIT).
            </p>
        </div>
    </body>
</html>
</code>```

Contents of publications.html:

```<code><!DOCTYPE html>

<html>
    <head>
        <title>The Title</title>
        <link type="text/css" rel="stylesheet" href="stylesheet.css">
    </head>
    <body>
        <div id="header">
            <h1>My Name</h1>
        </div>

        <div id="menu">
            <p>
                <a href="index.html">Home</a>
                &nbsp&nbsp
                <a href="publications.html">Publications</a>
                &nbsp&nbsp
                <a href="contact.html">Contact</a>
            </p>
        </div>

        <div id="content">
            <ol>
                <li>Snow White and the Seven Dwarfs, 1937</li>
                <li>Pinocchio, 1940</li>
                <li>The Reluctant Dragon, 1941</li>
            </ol>
        </div>
    </body>
</html>
</code>```

Contents of stylesheet.css:

```<code>    body {font-size: 16px; line-height: 20px; font-weight: light; color: #250517; /*gray*/}
    a:link {text-decoration: none; color: #003399; /*blue*/}
    a:visited {text-decoration: none; color: #003399; /*blue*/}
    a:active {text-decoration: none; color: #003399; /*blue*/}
    a:hover {text-decoration: none; color: #003399; /*blue*/}

    #header {
        width:800px;
        margin-left:auto;
        margin-right:auto;
        text-align:center;
        margin-top:50px;
    }

    #content {
        width:730px;
        margin-left:auto;
        margin-right:auto;
        height:410px;
    }

    #menu {
        width:800px;
        margin-left:auto;
        margin-right:auto;
        text-align:center;
        margin-bottom:50px;
        clear:both;
    }
</code>```

答:
You can use php for do the same job --
like
include "navbar.html;

Body:
I'm making a small personal academic website, which has multiple pages with a common structure.

Question: Is there a way to not repeat the code for the header and the menu (or navigation bar) in each of the html files? It would be great if I could put the code for the header and menu in another file, e.g. header.html and write a statement such as \input{header.html} (using TeX syntax) to include the file into index.html and publications.html.

Below is an example of what the website looks like.

Contents of index.html:

<!DOCTYPE html>

        <title>The Title</title>
        <link type="text/css" rel="stylesheet" href="stylesheet.css">

My Name

                Home
                &nbsp&nbsp
                Publications
                &nbsp&nbsp
                Contact

                This is my academic webpage.

                I am a 15th year PhD student in Filmmaking at Mickey's Institute of Technology (MIT).

Contents of publications.html:

<!DOCTYPE html>

        <title>The Title</title>
        <link type="text/css" rel="stylesheet" href="stylesheet.css">

My Name

                Home
                &nbsp&nbsp
                Publications
                &nbsp&nbsp
                Contact

Snow White and the Seven Dwarfs, 1937

Pinocchio, 1940

The Reluctant Dragon, 1941

Contents of stylesheet.css:

    body {font-size: 16px; line-height: 20px; font-weight: light; color: #250517; /*gray*/}
    a:link {text-decoration: none; color: #003399; /*blue*/}
    a:visited {text-decoration: none; color: #003399; /*blue*/}
    a:active {text-decoration: none; color: #003399; /*blue*/}
    a:hover {text-decoration: none; color: #003399; /*blue*/}

    #header {
        width:800px;
        margin-left:auto;
        margin-right:auto;
        text-align:center;
        margin-top:50px;
    }

    #content {
        width:730px;
        margin-left:auto;
        margin-right:auto;
        height:410px;
    }

    #menu {
        width:800px;
        margin-left:auto;
        margin-right:auto;
        text-align:center;
        margin-bottom:50px;
        clear:both;
    }


问:
How to set length of a combo box to only allow one of two values
I have the combobox minLength set to 5. I want the combobox to require the length to be 5. If it is longer than 5, I want the minLength to be set to 10. So the outcome should be: the min length can be either 5 or 10, nothing else. (The ComboBox will not accept an input with a length of less than 5 or greater than 10, it also will not accept a length equal to 6, 7, 8, or 9).

Here is my code for example:

```<code>  xtype: 'combobox',
  minLength: 5,
  maxLength: 10,
  maskRe: /[0-9.-]/,
  validator: function(v) {
    //this only allows numbers and a hyphen to be entered into the combo box,
    //while also requiring 4 digits to be entered after the hyphen
    //(only if a hyphen is present)
    return /^[0-9]*(-?[0-9]{4})?$/.test(v)? true : 'A Postal Code should only include a hyphen if there are four digits after the hyphen!';
  },
</code>```

答:
As far as I know there is no built-in solution for that, but you can do it. Check the code below and this fiddle, this is for ExtJS 7.5 Classic Material, but it can likely be adopted to other version / toolkit.

Some notes:

You have to set a store, even if it's empty, otherwise the change listener will not be called. (I don't know if it is a bug or a feature.)

The solution uses a ViewModel and binds the minLength to this. The reason you need setMinLength and setMaxLength is that ExtJS doesn't provide it and getter / setter is required for binding.

Important: since this is not an 'official' solution there is no guarantee it will always work.

```<code>Ext.application({
    name: 'MyApp',
    launch: function () {
        Ext.create('Ext.form.Panel', {
            renderTo: Ext.getBody(),
            items: [{
                xtype: 'combo',
                minLength: 5,
                maxLength: 10,
                maskRe: /[0-9.-]/,
                viewModel: {
                    data: {
                        minLength: 5
                    }
                },
                store: [],
                bind: {
                    minLength: '{minLength}'
                },
                setMinLength: function (v) {
                    this.minLength = v;
                },
                getMinLength: function () {
                    return this.minLength;
                },
                validator: function (v) {
                    return /^[0-9]*(-?[0-9]{4})?$/.test(v) ? true : 'A Postal Code should only include a hyphen if there are four digits after the hyphen!';
                },
                listeners: {
                    change: function (combo, newValue, oldValue, eOpts) {
                        const newMinLength = newValue == null ? 5 : newValue.length >= 5 ? 10 : 5;
                        console.log('New min length will be: ' + newMinLength);
                        combo.getViewModel().set('minLength', newMinLength);
                    }
                }
            }]
        });
    }
});
</code>```

Body:
I have the combobox minLength set to 5. I want the combobox to require the length to be 5. If it is longer than 5, I want the minLength to be set to 10. So the outcome should be: the min length can be either 5 or 10, nothing else. (The ComboBox will not accept an input with a length of less than 5 or greater than 10, it also will not accept a length equal to 6, 7, 8, or 9).

Here is my code for example:

  xtype: 'combobox',
  minLength: 5,
  maxLength: 10,
  maskRe: /[0-9.-]/,
  validator: function(v) {
    //this only allows numbers and a hyphen to be entered into the combo box,
    //while also requiring 4 digits to be entered after the hyphen
    //(only if a hyphen is present)
    return /^[0-9]*(-?[0-9]{4})?$/.test(v)? true : 'A Postal Code should only include a hyphen if there are four digits after the hyphen!';
  },

Body:
As far as I know there is no built-in solution for that, but you can do it. Check the code below and this fiddle, this is for ExtJS 7.5 Classic Material, but it can likely be adopted to other version / toolkit.

Some notes:

You have to set a store, even if it's empty, otherwise the change listener will not be called. (I don't know if it is a bug or a feature.)

The solution uses a ViewModel and binds the minLength to this. The reason you need setMinLength and setMaxLength is that ExtJS doesn't provide it and getter / setter is required for binding.

Important: since this is not an 'official' solution there is no guarantee it will always work.

Ext.application({
    name: 'MyApp',
    launch: function () {
        Ext.create('Ext.form.Panel', {
            renderTo: Ext.getBody(),
            items: [{
                xtype: 'combo',
                minLength: 5,
                maxLength: 10,
                maskRe: /[0-9.-]/,
                viewModel: {
                    data: {
                        minLength: 5
                    }
                },
                store: [],
                bind: {
                    minLength: '{minLength}'
                },
                setMinLength: function (v) {
                    this.minLength = v;
                },
                getMinLength: function () {
                    return this.minLength;
                },
                validator: function (v) {
                    return /^[0-9]*(-?[0-9]{4})?$/.test(v) ? true : 'A Postal Code should only include a hyphen if there are four digits after the hyphen!';
                },
                listeners: {
                    change: function (combo, newValue, oldValue, eOpts) {
                        const newMinLength = newValue == null ? 5 : newValue.length >= 5 ? 10 : 5;
                        console.log('New min length will be: ' + newMinLength);
                        combo.getViewModel().set('minLength', newMinLength);
                    }
                }
            }]
        });
    }
});


问:
Anylogic: How to create an objective function using values of two dataset (for optimization experiment)?
In my Anylogic model I have a population of agents (4 terminals) were trucks arrive at, are being served and depart from. The terminals have two parameters (numberOfGates and servicetime) which influence the departures per hour of trucks leaving the terminals. Now I want to tune these two parameters, so that the amount of departures per hour is closest to reality (I know the actual departures per hour). I already have two datasets within each terminal agent, one with de amount of departures per hour that I simulate, and one with the observedDepartures from the data.

I already compare these two datasets in plots for every terminal:

Now I want to create an optimization experiment to tune the numberOfGates and servicetime of the terminals so that the departure dataset is the closest to the observedDepartures dataset. Does anyone know how to do create a(n) (objective) function for this optimization experiment the easiest way?

When I add a variable diff that is updated every hour by abs( departures - observedDepartures) and put root.diff in the optimization experiment, it gives me the eq(null) is not allowed. Use isNull() instead error, in a line that reads the database for the observedDepartures (see last picture), but it works when I run the simulation normally, it only gives this error when running the optimization experiment (I don't know why).

答: You can use the absolute value of the sum of the differences for each replication. That is, create a variable that logs the | difference | for each hour, call it diff. Then in the optimization experiment, minimize the value of the sum of that variable. In fact this is close to a typical regression model's objectives. There they use a more complex objective function, by minimizing the sum of the square of the differences.


问:
Preview a "screen" in android jetpack compose navigation with a PreviewParameter NavController
I discovering android Cetpack Compose (and Navigation) and try to display a preview of a view with a navController as parameter.

To achieve, I use the PreviewParameter and I have no error, but nothing displayed in the Preview window.

Anyone know how pass a fake NavController instance to a Composable?

```<code>class FakeNavController : PreviewParameterProvider<NavController> {
    override val values: Sequence<NavController>
        get() {}
}

@Preview
@Composable
fun Preview(
    @PreviewParameter(FakeNavController::class) fakeNavController: NavController
) {
    HomeView(fakeNavController)
}
</code>```

答:
You don't have to make it nullable and pass null to it.
You just need to pass this: rememberNavController()

```<code>@Preview
@Composable
fun Preview() {
    HomeView(rememberNavController())
}
</code>```

Body:
I discovering android Cetpack Compose (and Navigation) and try to display a preview of a view with a navController as parameter.

To achieve, I use the PreviewParameter and I have no error, but nothing displayed in the Preview window.

Anyone know how pass a fake NavController instance to a Composable?

class FakeNavController : PreviewParameterProvider<NavController> {
    override val values: Sequence<NavController>
        get() {}
}

@Preview
@Composable
fun Preview(
    @PreviewParameter(FakeNavController::class) fakeNavController: NavController
) {
    HomeView(fakeNavController)
}

Body:
You don't have to make it nullable and pass null to it.
You just need to pass this: rememberNavController()

@Preview
@Composable
fun Preview() {
    HomeView(rememberNavController())
}


问:
Check if an agent pool is mapped to a collection project in Azure DevOps?
In Azure DevOps Server, an agent pool is scoped to the entire server, as documented here.
However, only projects that "imported" the agent pool to the project can actually use it. My question is - is there a way to check using REST API whether or not a project is authorized to use a specific agent pool?

I know there's this REST method:

```<code>GET https://dev.azure.com/{organization}/_apis/distributedtask/pools?api-version=6.0
</code>```

Which gives you a list of all agnet pools in the collection.
(By the way - if agent pools are scoped to the entire server, why is it this call scoped to a specific collection?)
But in the response there is no way to know to which projects the agent pool is mapped to.

答:
You should use this API to check if the agent pool bind to specific Azure DevOps project.
Actually the queueName == agentPoolName

```<code>GET https://dev.azure.com/{organization}/{project}/_apis/distributedtask/queues?queueNames={queueNames}&api-version=6.1-preview.1
</code>```

API Document

Body:
In Azure DevOps Server, an agent pool is scoped to the entire server, as documented here.
However, only projects that "imported" the agent pool to the project can actually use it. My question is - is there a way to check using REST API whether or not a project is authorized to use a specific agent pool?

I know there's this REST method:

GET https://dev.azure.com/{organization}/_apis/distributedtask/pools?api-version=6.0

Which gives you a list of all agnet pools in the collection.
(By the way - if agent pools are scoped to the entire server, why is it this call scoped to a specific collection?)
But in the response there is no way to know to which projects the agent pool is mapped to.

Body:
You should use this API to check if the agent pool bind to specific Azure DevOps project.
Actually the queueName == agentPoolName

GET https://dev.azure.com/{organization}/{project}/_apis/distributedtask/queues?queueNames={queueNames}&api-version=6.1-preview.1

API Document


问:
CDK Unable to Add CodeStarNotification to CodePipeline
I use CDK to deploy a codepipeline. It works fine until I try to add notification for codepipeline success/fail events. It gives CREATE_FAILED error with message Resource handler returned message: "Invalid request provided: AWS::CodeStarNotifications::NotificationRule" (RequestToken: bb566fd0-1ac9-5d61-03fe-f9c27b4196fa, HandlerErrorCode: InvalidRequest). What could be the reason? Thanks.

import * as codepipeline from "@aws-cdk/aws-codepipeline";
import * as codepipeline_actions from "@aws-cdk/aws-codepipeline-actions";
import * as codestar_noti from "@aws-cdk/aws-codestarnotifications";
import * as sns from "@aws-cdk/aws-sns";

    const pipeline = new codepipeline.Pipeline(...);
    const topicArn = props.sns_arn_for_developer;
    const targetTopic = sns.Topic.fromTopicArn(
      this,
      "sns-notification-topic",
      topicArn
    );
    new codestar_noti.NotificationRule(this, "Notification", {
      detailType: codestar_noti.DetailType.BASIC,
      events: [
        "codepipeline-pipeline-pipeline-execution-started",
        "codepipeline-pipeline-pipeline-execution-failed",
        "codepipeline-pipeline-pipeline-execution-succeeded",
        "codepipeline-pipeline-pipeline-execution-canceled",
      ],
      source: pipeline,
      targets: [targetTopic],
    });
```
<p>Here is the snippet of generated cloudformation tempalte.</p>
```    "Notification2267453E": {
      "Type": "AWS::CodeStarNotifications::NotificationRule",
      "Properties": {
        "DetailType": "BASIC",
        "EventTypeIds": [
          "codepipeline-pipeline-pipeline-execution-started",
          "codepipeline-pipeline-pipeline-execution-failed",
          "codepipeline-pipeline-pipeline-execution-succeeded",
          "codepipeline-pipeline-pipeline-execution-canceled"
        ],
        "Name": "sagemakerbringyourownNotification36194CEC",
        "Resource": {
          "Fn::Join": [
            "",
            [
              "arn:",
              {
                "Ref": "AWS::Partition"
              },
              ":codepipeline:ap-southeast-1:305326993135:",
              {
                "Ref": "sagemakerbringyourownpipeline0A8C43B1"
              }
            ]
          ]
        },
        "Targets": [
          {
            "TargetAddress": "arn:aws:sns:ap-southeast-1:305326993135:whitespace_alerts",
            "TargetType": "SNS"
          }
        ]
      },
      "Metadata": {
        "aws:cdk:path": "sagemaker-bring-your-own/Notification/Resource"
      }
    },
```

答:
This is because imported resources cannot be modified. As you pointed out in the comments, setting up the notification involves modifying the Topic resource, specifically its access policy.

Reference: https://docs.aws.amazon.com/cdk/v2/guide/resources.html#resources_importing

Body:
I use CDK to deploy a codepipeline. It works fine until I try to add notification for codepipeline success/fail events. It gives CREATE_FAILED error with message Resource handler returned message: "Invalid request provided: AWS::CodeStarNotifications::NotificationRule" (RequestToken: bb566fd0-1ac9-5d61-03fe-f9c27b4196fa, HandlerErrorCode: InvalidRequest). What could be the reason? Thanks.

import * as codepipeline from "@aws-cdk/aws-codepipeline";
import * as codepipeline_actions from "@aws-cdk/aws-codepipeline-actions";
import * as codestar_noti from "@aws-cdk/aws-codestarnotifications";
import * as sns from "@aws-cdk/aws-sns";

    const pipeline = new codepipeline.Pipeline(...);
    const topicArn = props.sns_arn_for_developer;
    const targetTopic = sns.Topic.fromTopicArn(
      this,
      "sns-notification-topic",
      topicArn
    );
    new codestar_noti.NotificationRule(this, "Notification", {
      detailType: codestar_noti.DetailType.BASIC,
      events: [
        "codepipeline-pipeline-pipeline-execution-started",
        "codepipeline-pipeline-pipeline-execution-failed",
        "codepipeline-pipeline-pipeline-execution-succeeded",
        "codepipeline-pipeline-pipeline-execution-canceled",
      ],
      source: pipeline,
      targets: [targetTopic],
    });

Here is the snippet of generated cloudformation tempalte.

    "Notification2267453E": {
      "Type": "AWS::CodeStarNotifications::NotificationRule",
      "Properties": {
        "DetailType": "BASIC",
        "EventTypeIds": [
          "codepipeline-pipeline-pipeline-execution-started",
          "codepipeline-pipeline-pipeline-execution-failed",
          "codepipeline-pipeline-pipeline-execution-succeeded",
          "codepipeline-pipeline-pipeline-execution-canceled"
        ],
        "Name": "sagemakerbringyourownNotification36194CEC",
        "Resource": {
          "Fn::Join": [
            "",
            [
              "arn:",
              {
                "Ref": "AWS::Partition"
              },
              ":codepipeline:ap-southeast-1:305326993135:",
              {
                "Ref": "sagemakerbringyourownpipeline0A8C43B1"
              }
            ]
          ]
        },
        "Targets": [
          {
            "TargetAddress": "arn:aws:sns:ap-southeast-1:305326993135:whitespace_alerts",
            "TargetType": "SNS"
          }
        ]
      },
      "Metadata": {
        "aws:cdk:path": "sagemaker-bring-your-own/Notification/Resource"
      }
    },


问:
How do I fix an invalid syntax error in google colab?
Whenever I try to run this command, an error appears and I amn't sure what I'm doing wrong, here is the image. enter image description here</p>

答: Change the extension from Parse_script .jpynb to Parse_script .ipynb


问:
advice on refreshing incoming messages with mt_rand()?
is this a good way of doing it? or should i use a date time stamp with seconds rather?

while i am on a page, the new message must come through without me refreshing the page

my code is written in php:

```<code><div id='div_longgray_gradient2'>
<div id='div_float_img'>
<table width='96%' border='0'>
<tr>
    <td rowspan='2' width='40px' align='left'>

        <img src='/images/rainbow/arrow.png'>
    </td>

    <td align='left'>
        <span class='spn_big_black_rbc'>MESSAGES</span>
    </td>
</tr>

<tr>
    <td align='left'>
        <span class='spn_med_lightblue_rbc'>Inbox</span>
    </td>
    <td align='left'>
    </td>
</tr>
</table>
<br/>
<br/>

<table width='80%' align='center'>
<tr>
    <td class='td_show_contact_heading' align='left'><span class='spn_med_lightblue_rbc'>Received</span></td>
    <td class='td_show_contact_heading' align='left'><span class='spn_med_lightblue_rbc'>Message</span></td>
    <td class='td_show_contact_heading' align='left'><span class='spn_med_lightblue_rbc'>From</span></td>
</tr>
<?php
$cursor = $pager->getFirstIndice();
foreach ($pager->getResults() as $msg)
{
$has_freechat = false;
//changed id to withid here
$freechat_req_link="profiles/confirmfreechat?withid=".$msg->getRcProfileTableRelatedByProfileIdFrom()->getId();
$freechat_req_link=link_to('Freechat',$freechat_req_link,'class=link_small_dark');

$cc = sizeof ($fc_records);
for($i = 0; $i < $cc; $i++)
{
    if($fc_records[$i]->getProfileIdWith() == $msg->getProfileIdFrom())
    {
        $has_freechat = true;
        break;
    }
}

$unique_code_from = $msg->getRcProfileTableRelatedByProfileIdFrom()->getUniqueCode();
$block_url = link_to('Block User',"blocklist/block?unqiue_code=$unique_code_from",'class=link_medium_blue');
echo "<tr>";
$date = add_date($msg->getCreatedAt(),$hr=2);
echo "<td class='td_show_contact_item' align='left'>".$date."</td>";
$opened_once = $msg->getOpenedOnce();
if($opened_once >= 1)
{
   echo "<td class='td_show_contact_item' align='left'>".link_to($msg->getSubject(),   'messagebox/read?cursor='.$cursor,'class=link_medium_blue')."</td>";
}
else
{ ?>
   <td align='left'>
     <a href="<?php echo url_for('messagebox/read?cursor=').$cursor ?>" style='color:#ff0000 !important' class='spn_small_red_rbc'><?php echo $msg->getSubject();?></a>
   </td>
<?php
}
echo "<td class='td_show_contact_item' align='left'>".$unique_code_from." ( $block_url )</td>";
echo "</tr>";
++$cursor;
}

function add_date($givendate,$hr=2)
{
$cd = strtotime($givendate);
$newdate = date('Y-m-d H:i:s', mktime(date('h',$cd)+$hr, date('i',$cd), date('s',$cd), date('m',$cd), date('d',$cd), date('Y',$cd)));
return $newdate;
}
?>
</table>
<br/>
Displaying results <?php echo $pager->getFirstIndice() ?> to  <?php echo $pager->getLastIndice() ?>.
<br/>

<?php if ($pager->haveToPaginate()): ?>

<?php echo link_to('«', 'messagebox/list?page='.$pager->getFirstPage()) ?>
<?php echo link_to('<', 'messagebox/list?page='.$pager->getPreviousPage()) ?>
<?php $links = $pager->getLinks(); foreach ($links as $page): ?>
<?php echo ($page == $pager->getPage()) ? $page : link_to($page, 'messagebox/list?page='.$page) ?>
<?php if ($page != $pager->getCurrentMaxLink()): ?> - <?php endif ?>
<?php endforeach ?>
<?php echo link_to('>', 'messagebox/list?page='.$pager->getNextPage()) ?>
<?php echo link_to('»', 'messagebox/list?page='.$pager->getLastPage()) ?>
<?php endif ?>

<table width='96%' border='0'>
<tr>
    <td rowspan='2' width='40px' align='left'>
        <img src='/images/rainbow/arrow.png'>
    </td>
    <td align='left'>
        <span class='spn_big_black_rbc'></span>
    </td>
</tr>
<tr>
    <td align='left'>
        <span class='spn_med_lightblue_rbc'>Sent Items</span>
    </td>
</tr>
</table>
<br/>
<br/>
<table width='80%' align='center'>
<tr>
    <td class='td_show_contact_heading' align='left'><span class='spn_med_lightblue_rbc'>Sent</span></td>
    <td class='td_show_contact_heading' align='left'><span class='spn_med_lightblue_rbc'>Message</span></td>
    <td class='td_show_contact_heading' align='left'><span class='spn_med_lightblue_rbc'>To</span></td>
</tr>
<?php
$cursor2 = $pager2->getFirstIndice();
$br = sizeof ($block_records);
foreach ($pager2->getResults() as $item)
{
    $link = link_to('Delete',"messagebox/deleteSentmsg?mid=".$item->getId(),'class=link_medium_blue');
    $id = $item->getRcProfileTableRelatedByProfileIdTo()->getId();
    ?>
    <tr>
        <td class='td_show_contact_item' width='15%' align='left'><?php echo $date = add_date($item->getCreatedAt(),$hr=2); ?></td>
        <td class='td_show_contact_item' width='45%' align='left'><?php echo $item->getMessage()?></td>
        <td class='td_show_contact_item' width='25%' align='left'><?php echo $item->getRcProfileTableRelatedByProfileIdTo()->getUniqueCode()."  ".$link;?></td>
    </tr>
    <?php
     ++$cursor2;
}
?>
</table>
<br/>
Displaying results <?php echo $pager2->getFirstIndice(); ?> to  <?php echo $pager2->getLastIndice(); ?>.
<br/>
<?php if ($pager2->haveToPaginate()): ?>
<?php echo link_to('«', 'messagebox/list?page2='.$pager2->getFirstPage(),'class=link_big_dark') ?>
<?php echo link_to('<', 'messagebox/list?page2='.$pager2->getPreviousPage(),'class=link_big_dark') ?>
<?php $links = $pager2->getLinks(); foreach ($links as $page2): ?>
<?php echo ($page2 == $pager2->getPage()) ? $page2 : link_to($page2, 'messagebox/list?page2='.$page2,'class=link_big_dark') ?>
<?php if ($page2 != $pager2->getCurrentMaxLink()): ?> - <?php endif ?>
<?php endforeach ?>
<?php echo link_to('>', 'messagebox/list?page2='.$pager2->getNextPage(),'class=link_big_dark') ?>
<?php echo link_to('»', 'messagebox/list?page2='.$pager2->getLastPage(),'class=link_big_dark') ?>
<?php endif ?>
</div>
</div>
</code>```

can anyone give some advise please?
i have no ajax/JS here so dont know how i would incorporate it

答:
PHP is a server side language and will not update a page once it has been fetched by the browser. To do this you will need to use a combination of server side and client side scripts.

One way of making your page update it's content is to use AJAX (http://api.jquery.com/jQuery.ajax/) combined with a timer (setInterval() and setTimeout()) to query a PHP script and check for updates every x seconds. The updates can then be added to the page when they are available using JavaScript / jQuery.

Body:
is this a good way of doing it? or should i use a date time stamp with seconds rather?

while i am on a page, the new message must come through without me refreshing the page

my code is written in php:

        MESSAGES

        Inbox

    Received
    Message
    From

<?php
$cursor = $pager->getFirstIndice();
foreach ($pager->getResults() as $msg)
{
$has_freechat = false;
//changed id to withid here
$freechat_req_link="profiles/confirmfreechat?withid=".$msg->getRcProfileTableRelatedByProfileIdFrom()->getId();
$freechat_req_link=link_to('Freechat',$freechat_req_link,'class=link_small_dark');

$cc = sizeof ($fc_records);
for($i = 0; $i < $cc; $i++)
{
    if($fc_records[$i]->getProfileIdWith() == $msg->getProfileIdFrom())
    {
        $has_freechat = true;
        break;
    }
}

$unique_code_from = $msg->getRcProfileTableRelatedByProfileIdFrom()->getUniqueCode();
$block_url = link_to('Block User',"blocklist/block?unqiue_code=$unique_code_from",'class=link_medium_blue');
echo "
";
$date = add_date($msg->getCreatedAt(),$hr=2);
echo "".$date."	";
$opened_once = $msg->getOpenedOnce();
if($opened_once >= 1)
{
   echo "".link_to($msg->getSubject(),   'messagebox/read?cursor='.$cursor,'class=link_medium_blue')."	";
}
else
{ ?>

     <a href="<?php echo url_for('messagebox/read?cursor=').$cursor ?>" style='color:#ff0000 !important' class='spn_small_red_rbc'><?php echo $msg->getSubject();?>

<?php
}
echo "".$unique_code_from." ( $block_url )	";
echo "
";
++$cursor;
}

function add_date($givendate,$hr=2)
{
$cd = strtotime($givendate);
$newdate = date('Y-m-d H:i:s', mktime(date('h',$cd)+$hr, date('i',$cd), date('s',$cd), date('m',$cd), date('d',$cd), date('Y',$cd)));
return $newdate;
}
?>

Displaying results <?php echo $pager->getFirstIndice() ?> to  <?php echo $pager->getLastIndice() ?>.

<?php if ($pager->haveToPaginate()): ?>

<?php echo link_to('«', 'messagebox/list?page='.$pager->getFirstPage()) ?>
<?php echo link_to('<', 'messagebox/list?page='.$pager->getPreviousPage()) ?>
<?php $links = $pager->getLinks(); foreach ($links as $page): ?>
<?php echo ($page == $pager->getPage()) ? $page : link_to($page, 'messagebox/list?page='.$page) ?>
<?php if ($page != $pager->getCurrentMaxLink()): ?> - <?php endif ?>
<?php endforeach ?>
<?php echo link_to('>', 'messagebox/list?page='.$pager->getNextPage()) ?>
<?php echo link_to('»', 'messagebox/list?page='.$pager->getLastPage()) ?>
<?php endif ?>

        Sent Items

    Sent
    Message
    To

<?php
$cursor2 = $pager2->getFirstIndice();
$br = sizeof ($block_records);
foreach ($pager2->getResults() as $item)
{
    $link = link_to('Delete',"messagebox/deleteSentmsg?mid=".$item->getId(),'class=link_medium_blue');
    $id = $item->getRcProfileTableRelatedByProfileIdTo()->getId();
    ?>

        <?php echo $date = add_date($item->getCreatedAt(),$hr=2); ?>
        <?php echo $item->getMessage()?>
        <?php echo $item->getRcProfileTableRelatedByProfileIdTo()->getUniqueCode()."  ".$link;?>

    <?php
     ++$cursor2;
}
?>

Displaying results <?php echo $pager2->getFirstIndice(); ?> to  <?php echo $pager2->getLastIndice(); ?>.

<?php if ($pager2->haveToPaginate()): ?>
<?php echo link_to('«', 'messagebox/list?page2='.$pager2->getFirstPage(),'class=link_big_dark') ?>
<?php echo link_to('<', 'messagebox/list?page2='.$pager2->getPreviousPage(),'class=link_big_dark') ?>
<?php $links = $pager2->getLinks(); foreach ($links as $page2): ?>
<?php echo ($page2 == $pager2->getPage()) ? $page2 : link_to($page2, 'messagebox/list?page2='.$page2,'class=link_big_dark') ?>
<?php if ($page2 != $pager2->getCurrentMaxLink()): ?> - <?php endif ?>
<?php endforeach ?>
<?php echo link_to('>', 'messagebox/list?page2='.$pager2->getNextPage(),'class=link_big_dark') ?>
<?php echo link_to('»', 'messagebox/list?page2='.$pager2->getLastPage(),'class=link_big_dark') ?>
<?php endif ?>

can anyone give some advise please?
i have no ajax/JS here so dont know how i would incorporate it


问:
How do I format two different forms in the same stylesheet?
Looks simple but I'm losing my head.

I want to format two different forms independently. Here is the example.

```<code><h1>FORM 1</h1>
<form>
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>
<br>
<h1>FORM 2</h1>
<form id="form2">
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>
</code>```
```<code>/* Form 1 style */
input[type="text"],
input[type="password"],
input[type="email"],
select{
    display:block;
    width: 100%;
    margin-top: 2px;
    margin-bottom: 2px;
}

/* Form 2 style? */

input[type="text"],
input[type="password"],
input[type="email"],
select{
    display:block;
    width: 50%;
    margin-top: 1px;
    margin-bottom: 1px;
}
</code>```

https://jsfiddle.net/dtpoze0c/

I really appreciate any help.

答:
/* Form 1 style */
.form1 input[type="text"],
.form1 input[type="password"],
.form1 input[type="email"],
.form1 select{
    display:block;
    width: 100%;
    margin-top: 2px;
    margin-bottom: 2px;
}

/* Form 2 style? */

.form2 input[type="text"],
.form2 input[type="password"],
.form2 input[type="email"],
.form2 select{
    display:block;
    width: 50%;
    margin-top: 1px;
    margin-bottom: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>FORM 1</h1>
<form class="form1">
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>
<br>
<h1>FORM 2</h1>
<form class="form2" id="form2">
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form></code>```

Body:
Looks simple but I'm losing my head.

I want to format two different forms independently. Here is the example.

FORM 1

<form>
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>

FORM 2

<form id="form2">
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>

/* Form 1 style */
input[type="text"],
input[type="password"],
input[type="email"],
select{
    display:block;
    width: 100%;
    margin-top: 2px;
    margin-bottom: 2px;
}

/* Form 2 style? */

input[type="text"],
input[type="password"],
input[type="email"],
select{
    display:block;
    width: 50%;
    margin-top: 1px;
    margin-bottom: 1px;
}

https://jsfiddle.net/dtpoze0c/

I really appreciate any help.

Body:
/* Form 1 style */
.form1 input[type="text"],
.form1 input[type="password"],
.form1 input[type="email"],
.form1 select{
    display:block;
    width: 100%;
    margin-top: 2px;
    margin-bottom: 2px;
}

/* Form 2 style? */

.form2 input[type="text"],
.form2 input[type="password"],
.form2 input[type="email"],
.form2 select{
    display:block;
    width: 50%;
    margin-top: 1px;
    margin-bottom: 1px;
}

<h1>FORM 1</h1>
<form class="form1">
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>
<br>
<h1>FORM 2</h1>
<form class="form2" id="form2">
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>

    <input type="submit" value="Register"/>
</form>


问:
Positioning text inside OptionMenu in tkinter python
hy I am working on tkinter python project.

I am trying to position text to the Left inside OptionMenu using anchor option but it does not seem to work. I am using ttk theme widgets.

Here is the code that I am trying currently.

s = ttk.Style()
s.configure('my.TMenubutton', font=("Cambria", fontSize, "bold"), background="white", anchor = W  )
shapeMenu = ttk.OptionMenu(shapeFrame, shape, myShapes[1], *myShapes, style='my.TMenubutton', command=getShapes)
```

What I am doing wrong ?

答:
It seems like there is no anchor option under TMenubutton. I tried TLabel, and it worked. Don't know if there is any side effect though.

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry('300x100')
CHART_TYPES = ('Reticle', 'Circle Grid', 'Checkerboard', 'Grille', 'Slanted Edge MTF')

s = ttk.Style()
s.configure('my.TLabel', font=("Cambria", 10, "bold"), background="white", anchor = 'w'  )

chart_type = tk.StringVar()
chart_type.set(CHART_TYPES[0])
# chart_selector = tk.OptionMenu(root, chart_type, *CHART_TYPES)
chart_selector = ttk.OptionMenu(root, chart_type, *CHART_TYPES, style='my.TLabel')
# chart_selector.configure(anchor='w')
chart_selector.pack(expand=True, fill='x')

root.mainloop()
</code>```

Body:
hy I am working on tkinter python project.

I am trying to position text to the Left inside OptionMenu using anchor option but it does not seem to work. I am using ttk theme widgets.

Here is the code that I am trying currently.

s = ttk.Style()
s.configure('my.TMenubutton', font=("Cambria", fontSize, "bold"), background="white", anchor = W  )
shapeMenu = ttk.OptionMenu(shapeFrame, shape, myShapes[1], *myShapes, style='my.TMenubutton', command=getShapes)

What I am doing wrong ?

Body:
It seems like there is no anchor option under TMenubutton. I tried TLabel, and it worked. Don't know if there is any side effect though.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry('300x100')
CHART_TYPES = ('Reticle', 'Circle Grid', 'Checkerboard', 'Grille', 'Slanted Edge MTF')

s = ttk.Style()
s.configure('my.TLabel', font=("Cambria", 10, "bold"), background="white", anchor = 'w'  )

chart_type = tk.StringVar()
chart_type.set(CHART_TYPES[0])
# chart_selector = tk.OptionMenu(root, chart_type, *CHART_TYPES)
chart_selector = ttk.OptionMenu(root, chart_type, *CHART_TYPES, style='my.TLabel')
# chart_selector.configure(anchor='w')
chart_selector.pack(expand=True, fill='x')

root.mainloop()


问:
Create new column using data from If Else Loop in R
I have data frame that consist of names and scores of certain individual

```<code>       name  score
0       Ted     90
1   Rebecca     88
2       Roy     78
3    Leslie     85
4    Nathan     75
5     Jamie     70
6       Sam     78
7     Isaac     70
8    Keeley     85
9     Beard     90
10    Colin     70
11     Will     70
12      Jan     82
13  Richard     70
</code>```

I want to add new column called verdict that contain their degree based on their score. I used loping to do that with hope that the result would be like this

```<code>       name  score               verdict
0       Ted     90     Passed, Cum Laude
1   Rebecca     88     Passed, Cum Laude
2       Roy     78          Passed, Good
3    Leslie     85     Passed, Cum Laude
4    Nathan     75          Passed, Good
5     Jamie     70          Passed, Good
6       Sam     78          Passed, Good
7     Isaac     70          Passed, Good
8    Keeley     85     Passed, Cum Laude
9     Beard     90     Passed, Cum Laude
10    Colin     70          Passed, Good
11     Will     70          Passed, Good
12      Jan     82     Passed, Excellent
13  Richard     70          Passed, Good
</code>```

I'm using this code below to do that, but nothing happened. The new column didnt exist and there is no error or warning message in R console

```<code>df$verdict <-
  for (score in df$score){
    if (score >= 85)
      return('Passed, Cum Laude')
    else if (score < 85 & score >= 80)
      return('Passed, Excellent')
    else if (score < 80 & score >= 70)
      return('Passed, Good')
    else if (score < 70 & score >= 60)
      return('Passed')
    else
      return('Not Passed')
}
</code>```

答:
The return function is used only to return value from a function, in the definition of the function itself. R should tell you there is no function to return from.

Also, by looping along score values, you're not telling R the row and column coordinates where to add this value.

If you want to avoid to load a full library to get access to the case_when function, you can change a little bit your code.

First example, using apply to loop along the rows.

```<code>df$verdict <-apply(df, MARGIN = 1, FUN=function(X){
    if (X[2] >= 85)
        return('Passed, Cum Laude')
    else if (X[2] < 85 & X[2] >= 80)
        return('Passed, Excellent')
    else if (X[2] < 80 & X[2] >= 70)
        return('Passed, Good')
    else if (X[2] < 70 & X[2] >= 60)
        return('Passed') else   return('Not Passed')
    })
</code>```

Or, you can use the ifelse function which is vectorised. However, it is not easy to read or debug.

```<code>df$verdict<-ifelse(df$score>=85,'Passed, Cum Laude',
                   ifelse(df$score < 85 & df$score >= 80,'Passed, Excellent',
                          ifelse(df$score < 80 & df$score >= 70,'Passed, Good',
                                 ifelse(df$score < 70 & df$score >= 60,'Passed',
                                        'Not Passed'))))
</code>```

If you want to loop along the rows, you should loop along their index :

```<code>for (r in 1:nrow(df)){
  if (df$score[r] >= 85)
    df$verdict[r]<-'Passed, Cum Laude'
  else if (df$score[r] < 85 & df$score[r] >= 80)
    df$verdict[r]<-'Passed, Excellent'
  else if (df$score[r] < 80 & df$score[r] >= 70)
    df$verdict[r]<-'Passed, Good'
  else if (df$score[r] < 70 & df$score[r] >= 60)
    df$verdict[r]<-'Passed'
  else
    df$verdict[r]<-'Not Passed'
}
rm(r)
</code>```

Body:
I have data frame that consist of names and scores of certain individual

       name  score
0       Ted     90
1   Rebecca     88
2       Roy     78
3    Leslie     85
4    Nathan     75
5     Jamie     70
6       Sam     78
7     Isaac     70
8    Keeley     85
9     Beard     90
10    Colin     70
11     Will     70
12      Jan     82
13  Richard     70

I want to add new column called verdict that contain their degree based on their score. I used loping to do that with hope that the result would be like this

       name  score               verdict
0       Ted     90     Passed, Cum Laude
1   Rebecca     88     Passed, Cum Laude
2       Roy     78          Passed, Good
3    Leslie     85     Passed, Cum Laude
4    Nathan     75          Passed, Good
5     Jamie     70          Passed, Good
6       Sam     78          Passed, Good
7     Isaac     70          Passed, Good
8    Keeley     85     Passed, Cum Laude
9     Beard     90     Passed, Cum Laude
10    Colin     70          Passed, Good
11     Will     70          Passed, Good
12      Jan     82     Passed, Excellent
13  Richard     70          Passed, Good

I'm using this code below to do that, but nothing happened. The new column didnt exist and there is no error or warning message in R console

df$verdict <-
  for (score in df$score){
    if (score >= 85)
      return('Passed, Cum Laude')
    else if (score < 85 & score >= 80)
      return('Passed, Excellent')
    else if (score < 80 & score >= 70)
      return('Passed, Good')
    else if (score < 70 & score >= 60)
      return('Passed')
    else
      return('Not Passed')
}

Body:
The return function is used only to return value from a function, in the definition of the function itself. R should tell you there is no function to return from.

Also, by looping along score values, you're not telling R the row and column coordinates where to add this value.

If you want to avoid to load a full library to get access to the case_when function, you can change a little bit your code.

First example, using apply to loop along the rows.

df$verdict <-apply(df, MARGIN = 1, FUN=function(X){
    if (X[2] >= 85)
        return('Passed, Cum Laude')
    else if (X[2] < 85 & X[2] >= 80)
        return('Passed, Excellent')
    else if (X[2] < 80 & X[2] >= 70)
        return('Passed, Good')
    else if (X[2] < 70 & X[2] >= 60)
        return('Passed') else   return('Not Passed')
    })

Or, you can use the ifelse function which is vectorised. However, it is not easy to read or debug.

df$verdict<-ifelse(df$score>=85,'Passed, Cum Laude',
                   ifelse(df$score < 85 & df$score >= 80,'Passed, Excellent',
                          ifelse(df$score < 80 & df$score >= 70,'Passed, Good',
                                 ifelse(df$score < 70 & df$score >= 60,'Passed',
                                        'Not Passed'))))

If you want to loop along the rows, you should loop along their index :

for (r in 1:nrow(df)){
  if (df$score[r] >= 85)
    df$verdict[r]<-'Passed, Cum Laude'
  else if (df$score[r] < 85 & df$score[r] >= 80)
    df$verdict[r]<-'Passed, Excellent'
  else if (df$score[r] < 80 & df$score[r] >= 70)
    df$verdict[r]<-'Passed, Good'
  else if (df$score[r] < 70 & df$score[r] >= 60)
    df$verdict[r]<-'Passed'
  else
    df$verdict[r]<-'Not Passed'
}
rm(r)


问:
Flask - Accessing the config variable in the template
I am using Flask version 0.7.  I have stored the path of static content in a configuration file and loaded it using </p>

```<code>app.config.from_envvar(<file_name>)
</code>```

<p>Can I be able to access this config variable in the template without passing the variables through the view? </p>

答:
There are a few global variables that are passed in the templates context by default by flask (here is the complete list), one of them being config, which allows you to access the application configuration from templates.  Being a dictionary, it can be accessed using the syntax config['MY_CONFIGURATION'] or config.MY_CONFIGURATION (this syntax for accessing dict items is specific to Jinja).

On the other hand, if you wanted to pass arbitrary data to your templates without having to pass it explicitely in each view, you would have to use context processors.

Body:
I am using Flask version 0.7.  I have stored the path of static content in a configuration file and loaded it using

app.config.from_envvar(<file_name>)

Can I be able to access this config variable in the template without passing the variables through the view?


问:
Getting error every time Error: Permission denied @ rb_file_s_rename on linkage.json
I have MacOs Catilina 10.15 OS and Homebrew 3.0.11. At every time whenever I am installing package by brew then getting Error: Permission denied @ rb_file_s_rename (/Users/username/Library/Caches/Homebrew/.linkage.json20210406-4110-onnsth, /Users/username/Library/Caches/Homebrew/linkage.json)

After run this command sudo chown -R $(whoami):admin /Users/vineet/Library/Caches/Homebrew then I can able to install. Here I do not want run sudo chown.. command for remove Error: Permission denied @ rb_file_s_rename.... I want to remove Permission denied @ rb_file_s_rename linkage.json error for forever.

答: I received a warning like "Do you trust these scripts" whenever opening the rails project with Visual Studio Code. Simply I selected "NO". I generated a controller home with a method named index and wanted to navigate the route (http://localhost:3000/home/index). I faced such types of error. I closed my Visual Studio Code and the route (http://localhost:3000/home/index) worked.</p>


问:
how to use dcc.loading to a tab with dataTable
I have a tab with DataTable. I am trying to use dcc.Loading() to the DataTable to see rendering and it didn't work.  Thanks for your help.

Here is my code:

```<code>
    well_table = DataTable(
        id="well-table",
        columns=columns,
        data=data,
        derived_virtual_data=data,)

    well_table_loading=dcc.Loading(
                                id='loading-well-table',
                                type='default',
                                children=well_table     # wrap contour in loading's children
                                )
    well_tab=dcc.Tab(
            well_table_loading,
            label=label,
            value=value,
            id='well-tab")

</code>```

in callback

```<code>
@app.callback(
    [
    Output("well-tab", "children"),
    ],
    [
    Input('load-area-data','n_clicks'),
    ],
    [
     State('date-range','start_date'),
     State('date-range','end_date'),
    ],
    prevent_initial_call=True,
)
def change_area_data(n_clicks,start_date,end_date):

    datatable_thisarea=DataTable(
        id="well-table",
        columns=columns,
        data=data,
        derived_virtual_data=data,)

    return [datatable_thisarea]
</code>```

答: When you are triggering the callback, you are overwriting the loading component with a datatable. You should wrap the tab with a loading since you are returning the datatable to the tab component and that needs to load since it's the output of the callback.</p>

Body:
I have a tab with DataTable. I am trying to use dcc.Loading() to the DataTable to see rendering and it didn't work.  Thanks for your help.

Here is my code:

    well_table = DataTable(
        id="well-table",
        columns=columns,
        data=data,
        derived_virtual_data=data,)

    well_table_loading=dcc.Loading(
                                id='loading-well-table',
                                type='default',
                                children=well_table     # wrap contour in loading's children
                                )
    well_tab=dcc.Tab(
            well_table_loading,
            label=label,
            value=value,
            id='well-tab")

in callback

@app.callback(
    [
    Output("well-tab", "children"),
    ],
    [
    Input('load-area-data','n_clicks'),
    ],
    [
     State('date-range','start_date'),
     State('date-range','end_date'),
    ],
    prevent_initial_call=True,
)
def change_area_data(n_clicks,start_date,end_date):

    datatable_thisarea=DataTable(
        id="well-table",
        columns=columns,
        data=data,
        derived_virtual_data=data,)

    return [datatable_thisarea]


问:
Convert nested list to JSON using Python
I'm using the following SQL query to get data for every month in a given year:

```<code>SELECT DATE_FORMAT(tour_date , '%M'), COUNT(*)
FROM _673338137185
WHERE tour_date LIKE '{tour_year}%'
GROUP BY DATE_FORMAT(tour_date , '%M')
</code>```

When I'm returning this via Python, I'm getting the following result:

```<code>[
    [
        [
            "April",
            9
        ],
        [
            "August",
            5
        ],
        [
            "February",
            3
        ],
        [
            "July",
            6
        ],
        [
            "June",
            3
        ],
        [
            "March",
            1
        ],
        [
            "May",
            8
        ],
        [
            "November",
            1
        ],
        [
            "October",
            2
        ],
        [
            "September",
            4
        ]
    ]
]
</code>```

Also, there are \n everywhere in the result.
I need the result in JSON format, but I can't get it right. How can I do it?

答:
Since you are using GROUP_BY counts are grouped by month.

You can convert it into JSON like this.

```<code>import json
    data = [
    [
        [
            "April",
            9
        ],
        [
            "August",
            5
        ],
        [
            "February",
            3
        ],
        [
            "July",
            6
        ],
        [
            "June",
            3
        ],
        [
            "March",
            1
        ],
        [
            "May",
            8
        ],
        [
            "November",
            1
        ],
        [
            "October",
            2
        ],
        [
            "September",
            4
        ]
    ]
]

   new_data = [{i[0]:i[1]} for i in data[0]]

   print(json.dumps(new_data))
</code>```

Body:
I'm using the following SQL query to get data for every month in a given year:

SELECT DATE_FORMAT(tour_date , '%M'), COUNT(*)
FROM _673338137185
WHERE tour_date LIKE '{tour_year}%'
GROUP BY DATE_FORMAT(tour_date , '%M')

When I'm returning this via Python, I'm getting the following result:

[
    [
        [
            "April",
            9
        ],
        [
            "August",
            5
        ],
        [
            "February",
            3
        ],
        [
            "July",
            6
        ],
        [
            "June",
            3
        ],
        [
            "March",
            1
        ],
        [
            "May",
            8
        ],
        [
            "November",
            1
        ],
        [
            "October",
            2
        ],
        [
            "September",
            4
        ]
    ]
]

Also, there are \n everywhere in the result.
I need the result in JSON format, but I can't get it right. How can I do it?

Body:
Since you are using GROUP_BY counts are grouped by month.

You can convert it into JSON like this.

import json
    data = [
    [
        [
            "April",
            9
        ],
        [
            "August",
            5
        ],
        [
            "February",
            3
        ],
        [
            "July",
            6
        ],
        [
            "June",
            3
        ],
        [
            "March",
            1
        ],
        [
            "May",
            8
        ],
        [
            "November",
            1
        ],
        [
            "October",
            2
        ],
        [
            "September",
            4
        ]
    ]
]

   new_data = [{i[0]:i[1]} for i in data[0]]

   print(json.dumps(new_data))


问:
Can I use implements and extends at the same time?
Can i use the implements and the extends at the same time? Because I need to inherit something on the other class while i used implements on the same class.

```<code>public class DetailActivity extends AppCompatActivity
implementsView.OnClickListener "extends ListActivity"
</code>```

How can it be like that?

答:
```<code>class Human extends Monkey implements BasicAnimals, xyz
</code>```

in this way you can extend a class as well as implement interfaces.

Body:
Can i use the implements and the extends at the same time? Because I need to inherit something on the other class while i used implements on the same class.

public class DetailActivity extends AppCompatActivity
implementsView.OnClickListener "extends ListActivity"

How can it be like that?

Body:
class Human extends Monkey implements BasicAnimals, xyz

in this way you can extend a class as well as implement interfaces.


问:
LINQPad: How do I add a property to each row being dumped?
In LINQPad, I frequently want to Dump some SQL table, but add a property to each row. I usually default to the simple:

Publishers
.Select(p => new { p, AppCount = p.Apps.Count() })
```
<p>But of course this results in messy output, because each item is formatted as a vertical table, with an extra column containing the added property. I could create a new object, but that's very verbose, and you lose the table traversal links:</p>
<pre class="lang-cs prettyprint-override"><code>Publishers
.Select(p => new { p.PublisherId, p.Name, p.Added, ..., AppCount = p.Apps.Count() })
</code>```

What I'd love is some sort of merge syntax, which creates a dynamic object to dump with the added property:

Publishers
.Select(p => p.Merge(new { AppCount = p.Apps.Count() })
```

I've tried a few different ways to accomplish that: using JsonConvert.SerializeObject (this goes haywire trying to serialize all the foreign key references and repeating loops, using ExpandoObject (couldn't come up with a nice clean syntax), and libraries like https://github.com/kfinley/TypeMerger, which I haven't gotten to work either.

Has anyone come up with a clean way to do this? Does LINQPad have some built in synax for this I can use? Thanks!

UPDATE: I uploaded a sample script to demonstrate the issue and let anyone try their solutions against: http://share.linqpad.net/kclxpl.linq

To run, you'll need to populate the Nutshell database, which you can do using the "Populate demo database" sample in LINQPad.

答:
This is a tricky problem to solve. Part of the problem is that the metadata that allows LINQPad to identity lazily loaded properties is lost when they're taken out of their "entity" home and moved to an ExpandoObject, causing excessive round-tripping.

To avoid the pain, I've added a Util.Merge method to LINQPad 7.2.7. Here's its simplest use:

```<code>var o1 = new { A = 1, B = 2 };
var o2 = new { C = 3, D = 4 };

Util.Merge (o1, o2).Dump();
</code>```

and for the problem at hand:

```<code>Publishers
   .Select(p => Util.Merge (p, new { AppCount = p.Apps.Count() }))
</code>```

Body:
In LINQPad, I frequently want to Dump some SQL table, but add a property to each row. I usually default to the simple:

Publishers
.Select(p => new { p, AppCount = p.Apps.Count() })

But of course this results in messy output, because each item is formatted as a vertical table, with an extra column containing the added property. I could create a new object, but that's very verbose, and you lose the table traversal links:

Publishers
.Select(p => new { p.PublisherId, p.Name, p.Added, ..., AppCount = p.Apps.Count() })

What I'd love is some sort of merge syntax, which creates a dynamic object to dump with the added property:

Publishers
.Select(p => p.Merge(new { AppCount = p.Apps.Count() })

I've tried a few different ways to accomplish that: using JsonConvert.SerializeObject (this goes haywire trying to serialize all the foreign key references and repeating loops, using ExpandoObject (couldn't come up with a nice clean syntax), and libraries like https://github.com/kfinley/TypeMerger, which I haven't gotten to work either.

Has anyone come up with a clean way to do this? Does LINQPad have some built in synax for this I can use? Thanks!

UPDATE: I uploaded a sample script to demonstrate the issue and let anyone try their solutions against: http://share.linqpad.net/kclxpl.linq

To run, you'll need to populate the Nutshell database, which you can do using the "Populate demo database" sample in LINQPad.

Body:
This is a tricky problem to solve. Part of the problem is that the metadata that allows LINQPad to identity lazily loaded properties is lost when they're taken out of their "entity" home and moved to an ExpandoObject, causing excessive round-tripping.

To avoid the pain, I've added a Util.Merge method to LINQPad 7.2.7. Here's its simplest use:

var o1 = new { A = 1, B = 2 };
var o2 = new { C = 3, D = 4 };

Util.Merge (o1, o2).Dump();

and for the problem at hand:

Publishers
   .Select(p => Util.Merge (p, new { AppCount = p.Apps.Count() }))


问:
Add placeholder text inside UITextView in Swift?
How can I add a placeholder in a UITextView, similar to the one you can set for UITextField, in Swift?

答:
Probably the most simple out-of-the-box solution for UITextView  placeholder implementation that does not suffer from:

using UILabel instead of UITextView that might perform differently

switching to and from placeholder 'UITextView' copy that would capture first typed character that will miss from main UITextView control

messing with main UITextView controls text content replacing placeholder with empty string or first typed character. Border case is that if user enters placeholder text, some proposed implementation will treat it as a placeholder itself.

Swift 5:

```<code>import UIKit
import SnapKit
import RxSwift
import RxCocoa

class TextAreaView: UIView {
    let textArea = UITextView()
    let textAreaPlaceholder = UITextView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonSetup()
    }

    private func commonSetup() {

        addSubview(textAreaPlaceholder)
        addSubview(textArea)

        textArea.isScrollEnabled = false
        textArea.delegate = self

        textAreaPlaceholder.isScrollEnabled = false
        textAreaPlaceholder.textColor = UIColor.lightGray

        textArea.snp.makeConstraints { make in
            make.top.bottom.leading.trailing.equalToSuperview()
        }

        textAreaPlaceholder.snp.makeConstraints { make in
            make.top.bottom.leading.trailing.equalTo(textArea.snp.top)
        }

        textAreaPlaceholder.text = "Placeholder"

        updatePlaceholder()
    }

    func updatePlaceholder() {
        if textArea.text.count > 0 {
            textArea.alpha = 1.0
        } else {
            textArea.alpha = 0.0
        }
    }
}

extension TextAreaView: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        updatePlaceholder()
    }
}
</code>```

Body:
Probably the most simple out-of-the-box solution for UITextView  placeholder implementation that does not suffer from:

using UILabel instead of UITextView that might perform differently

switching to and from placeholder 'UITextView' copy that would capture first typed character that will miss from main UITextView control

messing with main UITextView controls text content replacing placeholder with empty string or first typed character. Border case is that if user enters placeholder text, some proposed implementation will treat it as a placeholder itself.

Swift 5:

import UIKit
import SnapKit
import RxSwift
import RxCocoa

class TextAreaView: UIView {
    let textArea = UITextView()
    let textAreaPlaceholder = UITextView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonSetup()
    }

    private func commonSetup() {

        addSubview(textAreaPlaceholder)
        addSubview(textArea)

        textArea.isScrollEnabled = false
        textArea.delegate = self

        textAreaPlaceholder.isScrollEnabled = false
        textAreaPlaceholder.textColor = UIColor.lightGray

        textArea.snp.makeConstraints { make in
            make.top.bottom.leading.trailing.equalToSuperview()
        }

        textAreaPlaceholder.snp.makeConstraints { make in
            make.top.bottom.leading.trailing.equalTo(textArea.snp.top)
        }

        textAreaPlaceholder.text = "Placeholder"

        updatePlaceholder()
    }

    func updatePlaceholder() {
        if textArea.text.count > 0 {
            textArea.alpha = 1.0
        } else {
            textArea.alpha = 0.0
        }
    }
}

extension TextAreaView: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        updatePlaceholder()
    }
}


问:
How to add recycler view animation like telegram?
I am currently making a chat app and i want to add a feature like telegram. As you can see here, there is a animation in the recycler view as if i=t zooming or decreasing its size. You can also notice that animation while opening and closing the navigation drawer. I too tried to do that using this but i get no animation in the recycler view. See this. Actually not this but like this. I took this gif from the README of the repo. So is that possible? If so, can you please tell me a simple implementation ?

Thanks in advance and i will be waiting

答:
To me it looks like an Activity transition where the translateZ value is modified. But since the Telegram Android client is open source, we can just take a look at it.

It looks like the Telegram devs use a lot of custom code instead of relying on the android SDK.

The DialogsActivity which extends a BaseFragment but is neither an Android Activity nor an Android Fragment since BaseFragmentdoesn't extend any of them, has the following method for the transition:

```<code>    private void setSlideTransitionProgress(float progress) {
        if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) {
            return;
        }
        slideFragmentProgress = progress;
        if (fragmentView != null) {
            fragmentView.invalidate();
        }

        if (filterTabsView != null) {
            float s = 1f - 0.05f * (1f - slideFragmentProgress);
            filterTabsView.getListView().setScaleX(s);
            filterTabsView.getListView().setScaleY(s);
            filterTabsView.getListView().setTranslationX((isDrawerTransition ? AndroidUtilities.dp(4) : -AndroidUtilities.dp(4)) * (1f - slideFragmentProgress));
            filterTabsView.getListView().setPivotX(isDrawerTransition ? filterTabsView.getMeasuredWidth() : 0);
            filterTabsView.getListView().setPivotY(0);
            filterTabsView.invalidate();
        }
    }
</code>```

Body:
To me it looks like an Activity transition where the translateZ value is modified. But since the Telegram Android client is open source, we can just take a look at it.

It looks like the Telegram devs use a lot of custom code instead of relying on the android SDK.

The DialogsActivity which extends a BaseFragment but is neither an Android Activity nor an Android Fragment since BaseFragmentdoesn't extend any of them, has the following method for the transition:

    private void setSlideTransitionProgress(float progress) {
        if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) {
            return;
        }
        slideFragmentProgress = progress;
        if (fragmentView != null) {
            fragmentView.invalidate();
        }

        if (filterTabsView != null) {
            float s = 1f - 0.05f * (1f - slideFragmentProgress);
            filterTabsView.getListView().setScaleX(s);
            filterTabsView.getListView().setScaleY(s);
            filterTabsView.getListView().setTranslationX((isDrawerTransition ? AndroidUtilities.dp(4) : -AndroidUtilities.dp(4)) * (1f - slideFragmentProgress));
            filterTabsView.getListView().setPivotX(isDrawerTransition ? filterTabsView.getMeasuredWidth() : 0);
            filterTabsView.getListView().setPivotY(0);
            filterTabsView.invalidate();
        }
    }


问:
How to declare two or multiple words as a single word although it contain space
I am creating a search for blood donors and everything is working fine and after completing the search I am facing some issues in it. My search is working but it's not showing perfect result. Let me elaborate,

```<code>#My Table Structure

    #Table 1- blood_donor
    +----+------+----------+-------------+
    | id | name | blood_id | location_id | // columns
    +----+------+----------+-------------+
    |  1 | rony |     1    |       1     |
    +----+------+----------+-------------+
    |  2 | jony |     2    |       2     |
    +----+------+----------+-------------+
    |  3 | tony |     3    |       3     |
    +----+------+----------+-------------+ // Data example

    #Table 2- blood_group
    +----+------------+
    | id | group_name | // columns
    +----+------------+
    |  1 | a positive |
    +----+------------+
    |  2 | b positive |
    +----+------------+
    |  3 | o negative |
    +----+------------+ // Data example

    #Table 3- location
    +----+---------------+
    | id | location_name | // columns
    +----+---------------+
    |  1 |     khulna    |
    +----+---------------+
    |  2 |     dhaka     |
    +----+---------------+
    |  3 |     sylhet    |
    +----+---------------+ // Data example
</code>```

My keyword

$keyword = "o negative blood donor in khulna";
```
<p>Now I separated the words</p>
<pre class="lang-php prettyprint-override"><code>$keyword_array = explode(" ",$keyword);
</code>```

Here is my query

$query ="SELECT * FROM
    blood_donor AS bd
LEFT JOIN blood_group AS bg ON bg.id = bd.blood_id
LEFT JOIN location    AS lo ON lo.id = bd.location_id
WHERE
bd.name          LIKE '%$keyword%' OR
bg.group_name    LIKE '%$keyword%' OR
lo.location_name LIKE '%$keyword%' OR";

// this above part giving me a result set for 100% match for the full keyword

// Now I generate another result set for separated keyword below

if (count($keyword_array) > 1) {
    foreach ($keyword_array as $array) {
        $query = $query . "
            bd.name          LIKE '%$array%' OR
            bg.group_name    LIKE '%$array%' OR
            lo.location_name LIKE '%$array%' OR";
    }
}

$query = substr($query,0,-3); // Removed the extra OR from the end

// My order by section
$query = $query . " ORDER BY
    CASE
        // If full match found, then bring them top
        WHEN bd.name LIKE '%$keyword%' THEN 1";

        // If partial match found, then bring them afterwards
        if (count($keyword_array) > 1) {
            $keyword_count = count($keyword_array);
            $query = $query . " WHEN";
            for ($i = 0; $i < $keyword_count; $i++) {
                $query = $query . " bd.name LIKE '%$keyword_array[$i]%' AND";
            }
            $query = substr($query,0,-3); // To remove the last AND
            $query = $query . " THEN 2";
        }
        $query = $query . " ELSE 3
    END
LIMIT $items_to_skip, $items_per_page"; // These two variables are OFFSET and LIMIT
```
<p>The keyword I am searching with, in the full match section it has nothing to do because there are no such sentence available in my database as `o negative blood donor in khulna that is okay but when the keywords getting separated then in the separated result section it's generating result what actually I am not looking for!</p>
<p>My separated keywords generating an array which is</p>
<pre class="lang-php prettyprint-override"><code>Array
(
    [0] => o
    [1] => negative
    [2] => blood
    [3] => donor
    [4] => in
    [5] => khulna
)
</code>```

And my SQL generating the query like this

bd.name          LIKE '%o%'        OR
bg.group_name    LIKE '%o%'        OR
lo.location_name LIKE '%o%'        OR
bd.name          LIKE '%negative%' OR
bg.group_name    LIKE '%negative%' OR
lo.location_name LIKE '%negative%' OR
bd.name          LIKE '%blood%'    OR
bg.group_name    LIKE '%blood%'    OR
lo.location_name LIKE '%blood%'    OR
bd.name          LIKE '%donor%'    OR
bg.group_name    LIKE '%donor%'    OR
lo.location_name LIKE '%donor%'    OR
bd.name          LIKE '%in%'       OR
bg.group_name    LIKE '%in%'       OR
lo.location_name LIKE '%in%'       OR
bd.name          LIKE '%khulna%'   OR
bg.group_name    LIKE '%khulna%'   OR
lo.location_name LIKE '%khulna%'
```
<p>This query giving me all the three rows because all the name contain the letter <code>o</code> but I don't want that! I want <code>o negative</code> as a single word so the result must be two rows. row 1 and 3. But how to achieve that? I really can't figure it out. Also I don't know how to make two different word as a single word.</p>
<p>There are eight blood groups and I want to treat every blood group name as a single word!
Example: A Negative is two word, but I want them as one word and how am I going to do it, is it possible?</p>
<p>I need an array like this. And how to do it?</p>
<pre class="lang-php prettyprint-override"><code>$keyword = "o negative blood donor in khulna";
$keyword_array = explode(" ",$keyword);
print_r($keyword_array);
Array
(
    [0] => o negative
    [1] => blood
    [2] => donor
    [3] => in
    [4] => khulna
)
</code>```

Thanks in advance.

答:
You could use a pattern to match the words that you want:

```<code>(?i)\b[abo]\s+(?:posi|nega)tive\b|\S+
</code>```

The pattern in parts matches:

(?i) Inline modifier for a case insensitive match

\b A word boundary to prevent a partial word match

[abo]\s+ match either a b or  o and 1 or more whitespace characters

(?:posi|nega)tive\b Match either positive or negative followed by a word boundary

| Or

\S+ Match 1 or more non whitespace chars (All other words)

See a Regex demo or a PHP demo.

```<code>$keyword = "o negative blood donor in khulna";
$pattern = "/(?i)\b[abo]\s+(?:posi|nega)tive\b|\S+/";
preg_match_all($pattern, $keyword, $keyword_array);
print_r($keyword_array[0]);
</code>```

Output

```<code>Array
(
    [0] => o negative
    [1] => blood
    [2] => donor
    [3] => in
    [4] => khulna
)
</code>```

Body:
I am creating a search for blood donors and everything is working fine and after completing the search I am facing some issues in it. My search is working but it's not showing perfect result. Let me elaborate,

#My Table Structure

    #Table 1- blood_donor
    +----+------+----------+-------------+
    | id | name | blood_id | location_id | // columns
    +----+------+----------+-------------+
    |  1 | rony |     1    |       1     |
    +----+------+----------+-------------+
    |  2 | jony |     2    |       2     |
    +----+------+----------+-------------+
    |  3 | tony |     3    |       3     |
    +----+------+----------+-------------+ // Data example

    #Table 2- blood_group
    +----+------------+
    | id | group_name | // columns
    +----+------------+
    |  1 | a positive |
    +----+------------+
    |  2 | b positive |
    +----+------------+
    |  3 | o negative |
    +----+------------+ // Data example

    #Table 3- location
    +----+---------------+
    | id | location_name | // columns
    +----+---------------+
    |  1 |     khulna    |
    +----+---------------+
    |  2 |     dhaka     |
    +----+---------------+
    |  3 |     sylhet    |
    +----+---------------+ // Data example

My keyword

$keyword = "o negative blood donor in khulna";

Now I separated the words

$keyword_array = explode(" ",$keyword);

Here is my query

$query ="SELECT * FROM
    blood_donor AS bd
LEFT JOIN blood_group AS bg ON bg.id = bd.blood_id
LEFT JOIN location    AS lo ON lo.id = bd.location_id
WHERE
bd.name          LIKE '%$keyword%' OR
bg.group_name    LIKE '%$keyword%' OR
lo.location_name LIKE '%$keyword%' OR";

// this above part giving me a result set for 100% match for the full keyword

// Now I generate another result set for separated keyword below

if (count($keyword_array) > 1) {
    foreach ($keyword_array as $array) {
        $query = $query . "
            bd.name          LIKE '%$array%' OR
            bg.group_name    LIKE '%$array%' OR
            lo.location_name LIKE '%$array%' OR";
    }
}

$query = substr($query,0,-3); // Removed the extra OR from the end

// My order by section
$query = $query . " ORDER BY
    CASE
        // If full match found, then bring them top
        WHEN bd.name LIKE '%$keyword%' THEN 1";

        // If partial match found, then bring them afterwards
        if (count($keyword_array) > 1) {
            $keyword_count = count($keyword_array);
            $query = $query . " WHEN";
            for ($i = 0; $i < $keyword_count; $i++) {
                $query = $query . " bd.name LIKE '%$keyword_array[$i]%' AND";
            }
            $query = substr($query,0,-3); // To remove the last AND
            $query = $query . " THEN 2";
        }
        $query = $query . " ELSE 3
    END
LIMIT $items_to_skip, $items_per_page"; // These two variables are OFFSET and LIMIT

The keyword I am searching with, in the full match section it has nothing to do because there are no such sentence available in my database as `o negative blood donor in khulna that is okay but when the keywords getting separated then in the separated result section it's generating result what actually I am not looking for!

My separated keywords generating an array which is

Array
(
    [0] => o
    [1] => negative
    [2] => blood
    [3] => donor
    [4] => in
    [5] => khulna
)

And my SQL generating the query like this

bd.name          LIKE '%o%'        OR
bg.group_name    LIKE '%o%'        OR
lo.location_name LIKE '%o%'        OR
bd.name          LIKE '%negative%' OR
bg.group_name    LIKE '%negative%' OR
lo.location_name LIKE '%negative%' OR
bd.name          LIKE '%blood%'    OR
bg.group_name    LIKE '%blood%'    OR
lo.location_name LIKE '%blood%'    OR
bd.name          LIKE '%donor%'    OR
bg.group_name    LIKE '%donor%'    OR
lo.location_name LIKE '%donor%'    OR
bd.name          LIKE '%in%'       OR
bg.group_name    LIKE '%in%'       OR
lo.location_name LIKE '%in%'       OR
bd.name          LIKE '%khulna%'   OR
bg.group_name    LIKE '%khulna%'   OR
lo.location_name LIKE '%khulna%'

This query giving me all the three rows because all the name contain the letter o but I don't want that! I want o negative as a single word so the result must be two rows. row 1 and 3. But how to achieve that? I really can't figure it out. Also I don't know how to make two different word as a single word.

There are eight blood groups and I want to treat every blood group name as a single word!
Example: A Negative is two word, but I want them as one word and how am I going to do it, is it possible?

I need an array like this. And how to do it?

$keyword = "o negative blood donor in khulna";
$keyword_array = explode(" ",$keyword);
print_r($keyword_array);
Array
(
    [0] => o negative
    [1] => blood
    [2] => donor
    [3] => in
    [4] => khulna
)

Thanks in advance.

Body:
You could use a pattern to match the words that you want:

(?i)\b[abo]\s+(?:posi|nega)tive\b|\S+

The pattern in parts matches:

(?i) Inline modifier for a case insensitive match

\b A word boundary to prevent a partial word match

[abo]\s+ match either a b or  o and 1 or more whitespace characters

(?:posi|nega)tive\b Match either positive or negative followed by a word boundary

| Or

\S+ Match 1 or more non whitespace chars (All other words)

See a Regex demo or a PHP demo.

$keyword = "o negative blood donor in khulna";
$pattern = "/(?i)\b[abo]\s+(?:posi|nega)tive\b|\S+/";
preg_match_all($pattern, $keyword, $keyword_array);
print_r($keyword_array[0]);

Output

Array
(
    [0] => o negative
    [1] => blood
    [2] => donor
    [3] => in
    [4] => khulna
)


问:
How can I find out the pid of a running equinox instance, is there a pid file?
How can I find out the pid of a running equinox instance, is there a pid file somewhere or is it configurable where it places a pid file?

UPDATE: to make it clear, I have a bunch of instances running, and they are configured roughly the same, so any user only looking for equinox will not know which instance is which

答:
```<code>$ pidof equinox
</code>```

From the man page:

PIDOF(8)              Linux System Administrator's Manual             PIDOF(8)

NAME
       pidof -- find the process ID of a running program.

SYNOPSIS
       pidof [-s] [-c] [-x] [-o omitpid] [-o omitpid..]  program [program..]

DESCRIPTION
       Pidof  finds  the  process id's (pids) of the named programs. It prints
       those id's on the standard output. This program is on some systems used
       in  run-level change scripts, especially when the system has a System-V
       like  rc  structure.  In  that  case  these  scripts  are  located   in
       /etc/rc?.d,  where  ?  is the runlevel. If the system has a start-stop-
       daemon (8) program that should be used instead.

OPTIONS

-s     Single shot - this instructs the program to only return one pid.

-c     Only return process ids that are  running  with  the  same  root
              directory.   This  option is ignored for non-root users, as they
              will be unable to check the current root directory of  processes
              they do not own.

-x     Scripts  too  -  this  causes the program to also return process
              id's of shells running the named scripts.

-o omitpid
              Tells pidof to omit processes with that process id. The  special
              pid  %PPID  can  be used to name the parent process of the pidof
              program, in other words the calling shell or shell script.

EXIT STATUS

0      At least one program was found with the requested name.

1      No program was found with the requested name.

Body:
$ pidof equinox

From the man page:

PIDOF(8)              Linux System Administrator's Manual             PIDOF(8)

NAME
       pidof -- find the process ID of a running program.

SYNOPSIS
       pidof [-s] [-c] [-x] [-o omitpid] [-o omitpid..]  program [program..]

DESCRIPTION
       Pidof  finds  the  process id's (pids) of the named programs. It prints
       those id's on the standard output. This program is on some systems used
       in  run-level change scripts, especially when the system has a System-V
       like  rc  structure.  In  that  case  these  scripts  are  located   in
       /etc/rc?.d,  where  ?  is the runlevel. If the system has a start-stop-
       daemon (8) program that should be used instead.

OPTIONS

-s     Single shot - this instructs the program to only return one pid.

-c     Only return process ids that are  running  with  the  same  root
              directory.   This  option is ignored for non-root users, as they
              will be unable to check the current root directory of  processes
              they do not own.

-x     Scripts  too  -  this  causes the program to also return process
              id's of shells running the named scripts.

-o omitpid
              Tells pidof to omit processes with that process id. The  special
              pid  %PPID  can  be used to name the parent process of the pidof
              program, in other words the calling shell or shell script.

EXIT STATUS

0      At least one program was found with the requested name.

1      No program was found with the requested name.


答:
If l is the list you display, simple use json.dumps:

```<code>import json

print(json.dumps(l))

# Output
[[["April", 9], ["August", 5], ["February", 3], ["July", 6], ["June", 3], ["March", 1], ["May", 8], ["November", 1], ["October", 2], ["September", 4]]]
</code>```

Title: Convert nested list to JSON using Python

Body:
If l is the list you display, simple use json.dumps:

import json

print(json.dumps(l))

# Output
[[["April", 9], ["August", 5], ["February", 3], ["July", 6], ["June", 3], ["March", 1], ["May", 8], ["November", 1], ["October", 2], ["September", 4]]]


答:
I believe you are pretty printing a Python list of lists.

Instead, try this:

```<code>import json

print(json.dumps(the_list_of_lists))
</code>```

Body:
I believe you are pretty printing a Python list of lists.

Instead, try this:

import json

print(json.dumps(the_list_of_lists))