问:
QShortCut and QSpinBox conflict
I'm writing an application were i use my own shortcut. It looks like this:

```<code>myShortcut= new QShortcut(Qt::SHIFT + Qt::Key_B,this);
connect(myShortcut, SIGNAL(activated()), this, SLOT(setCameraBack()));
</code>```

I defined it in the constructor of main widget and it works fine until i click one of the spinbox buttons which are also located on the main widget. After that my shortcut stop working and it doesn't work until i click push button or check box. When i do that everything is fine again. I'd like to add that after i click spinbox it seems to be "active" (because the cursor is still "blinking" on it) until i click one of the other buttons. Do you have any idea what is wrong? Is it some kind process or event problem? Thanks for all answers
~Marwroc

答:
A shortcut is "listened for" by Qt's
  event loop when the shortcut's parent
  widget is receiving events.

When the QSpinBox has keyboard focus, then the QShortcut object's parent is no longer receiving events. Therefore, the shortcut does not work until keyboard focus is removed form the QSpinBox. You can change this behavior by passing Qt::WidgetWithChildrenShortcut or Qt::ApplicationShortcut to the QShortcut::setContext method of your QShortcut.

Title: QShortCut and QSpinBox conflict

Body:
I'm writing an application were i use my own shortcut. It looks like this:

myShortcut= new QShortcut(Qt::SHIFT + Qt::Key_B,this);
connect(myShortcut, SIGNAL(activated()), this, SLOT(setCameraBack()));

I defined it in the constructor of main widget and it works fine until i click one of the spinbox buttons which are also located on the main widget. After that my shortcut stop working and it doesn't work until i click push button or check box. When i do that everything is fine again. I'd like to add that after i click spinbox it seems to be "active" (because the cursor is still "blinking" on it) until i click one of the other buttons. Do you have any idea what is wrong? Is it some kind process or event problem? Thanks for all answers
~Marwroc


来源: stackexchange

问:
How can I fix this batch file so that it does not error out on the IF statement?
I am pulling my hair out getting an error on this IF statement

```<code>IF %resultis%=="true" (
</code>```

The batch file hits the pause right before it but right after that gets some error that goes by to fast for me to see what it is.

Here is the full script:

```<code>@Echo off
Echo "Adding Chrysaliser user to Users group and removing from Administrators"
REM net localgroup Users Chrysaliser /add
REM net localgroup Administrators Chrysaliser /delete

REM SET /P password= Enter ladmin user password:
REM net user ladmin %password% /ADD
REM net localgroup Administrators ladmin /add

SET /P alaptop= Is this a laptop? (Y/N):
echo %alaptop%
IF %alaptop%=="Y" (SET resultis="true")
IF %alaptop%=="y" (SET resultis="true")
pause
IF %resultis%=="true" (
    pause
    SET /P password= Enter Lockedout user password:
    pause
    net user Lockedout %password% /ADD
    net localgroup Users Lockedout /add
    net localgroup Administrators Chrysaliser /delete

)
Echo Getting install files
mkdir %SYSTEMDRIVE%\files
SET /P username= Enter your domain admin username:
SET/P password= Enter your domain admin password:
net use \\server /user:%username% $password%
pause
</code>```

答: Found it. The %resultis% variable was empty for some reason. I had to remove the "" around Y and y for some reason.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am pulling my hair out getting an error on this IF statement

IF %resultis%=="true" (

The batch file hits the pause right before it but right after that gets some error that goes by to fast for me to see what it is.

Here is the full script:

@Echo off
Echo "Adding Chrysaliser user to Users group and removing from Administrators"
REM net localgroup Users Chrysaliser /add
REM net localgroup Administrators Chrysaliser /delete

REM SET /P password= Enter ladmin user password:
REM net user ladmin %password% /ADD
REM net localgroup Administrators ladmin /add

SET /P alaptop= Is this a laptop? (Y/N):
echo %alaptop%
IF %alaptop%=="Y" (SET resultis="true")
IF %alaptop%=="y" (SET resultis="true")
pause
IF %resultis%=="true" (
    pause
    SET /P password= Enter Lockedout user password:
    pause
    net user Lockedout %password% /ADD
    net localgroup Users Lockedout /add
    net localgroup Administrators Chrysaliser /delete

)
Echo Getting install files
mkdir %SYSTEMDRIVE%\files
SET /P username= Enter your domain admin username:
SET/P password= Enter your domain admin password:
net use \\server /user:%username% $password%
pause


问:
readOGR() cannot open file
```<code>wmap <- readOGR(dsn="~/R/funwithR/data/ne_110m_land", layer="ne_110m_land")
</code>```

This code is not loading the shape file and error is generated as

```<code>Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv,  :
Cannot open file
</code>```

I am sure that the directory is correct one. At the end / is also not there and layer name is also correct.

Inside the ne_110m_land directory files I have are:

```<code>ne_110m_land.dbf
ne_110m_land.prj
ne_110m_land.shp
ne_110m_land.shx
ne_110m_land.VERSION.txt
ne_110m_land.README.html
</code>```

答: As I commented in other post (Error when opening shapefile), using file.choose() and selecting manually will help in the case one file selection is needed. Apparently is related with NaturalEarth shapefiles </p>

Title: readOGR() cannot open file

Body:
wmap <- readOGR(dsn="~/R/funwithR/data/ne_110m_land", layer="ne_110m_land")

This code is not loading the shape file and error is generated as

Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv,  :
Cannot open file

I am sure that the directory is correct one. At the end / is also not there and layer name is also correct.

Inside the ne_110m_land directory files I have are:

ne_110m_land.dbf
ne_110m_land.prj
ne_110m_land.shp
ne_110m_land.shx
ne_110m_land.VERSION.txt
ne_110m_land.README.html


问:
How can I control the Microsoft Bot Framework dialog to repeat the dialog sequence by either starting over or stepping into a particular step?
As the dialog from the bot conversation starts it seems to go on a path i.e.
1 2 3 4. I would like to at point 2 per se go back to path marker 1 and start the process over or even potentially go to marker 2 from 3 to re-address / answer marker 2 over again...

I have attempted to do this with an if statement ( == "Pittsburgh" ) that returns to the previous method but I notice through the bot emulator the dialog moves on regardless of me readdressing the previous method.

In short, I am asking how to traverse through the waterfalldialog and go back to any dialog point I choose based on outcomes of conversation with the bot and luis responses.  Meaning, if I am stepping through from 1 - 5 and at 3 I need to start over how can I conform the waterfalldialog to specifically do this?  The issue I am having is that even though I am calling the previous method i the dialog chain it doesn't officially start from that method called onwards.  That is my concern specifically.

       private async Task<DialogTurnResult> DestinationStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var bookingDetails = (BookingDetails)stepContext.Options;

            if (bookingDetails.Destination == null)
            {
                return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Where would you like to travel to Christian?") }, cancellationToken);
            }
            else
            {
                Console.WriteLine("testing christian" + bookingDetails);
                return await stepContext.NextAsync(bookingDetails.Destination, cancellationToken);
            }
        }

        private async Task<DialogTurnResult> OriginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            Console.WriteLine("testing paul");
            var bookingDetails = (BookingDetails)stepContext.Options;

            //await LuisHelper.ExecuteLuisQuery(Configuration, Logger, stepContext.Context, cancellationToken);

            if ((string)stepContext.Result == "Pittsburgh")
            {
               return await DestinationStepAsync(stepContext, cancellationToken);
            }

            bookingDetails.Destination = (string)stepContext.Result;

            if (bookingDetails.Origin == null)
            {
                Console.WriteLine("testing tall" + bookingDetails.Destination);
                return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Where are you traveling from?") }, cancellationToken);
            }
            else
            {
                return await stepContext.NextAsync(bookingDetails.Origin, cancellationToken);
            }
        }
```

答:
To tuck this into an answer and get it out of comments:

Waterfalls are not designed to be traversed in anyway but step-by-step/down. You can either nest mini waterfalls inside each waterfall step which would allow for looping individual steps shown here or having conditional checks to skip certain steps shown here.

What you seem to be looking for is ComponentDialogs or using ReplaceDialogAsync. Component Dialogs, part of the botbuilder-dialogs library let you break your bot's logic into components (pieces) that can be added into either a DialogSet or even another component dialog. For example, this is the Cancel/Help component of the Core-Bot sample on the bot framework samples github repo. This component is for what happens if in the middle of another waterfall, the user says 'cancel' or 'help'

```<code>public class CancelAndHelpDialog : ComponentDialog
    {
        public CancelAndHelpDialog(string id)
            : base(id)
        {
        }

        protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken)
        {
            var result = await InterruptAsync(innerDc, cancellationToken);
            if (result != null)
            {
                return result;
            }

            return await base.OnBeginDialogAsync(innerDc, options, cancellationToken);
        }

        protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            var result = await InterruptAsync(innerDc, cancellationToken);
            if (result != null)
            {
                return result;
            }

            return await base.OnContinueDialogAsync(innerDc, cancellationToken);
        }

        private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            if (innerDc.Context.Activity.Type == ActivityTypes.Message)
            {
                var text = innerDc.Context.Activity.Text.ToLowerInvariant();

                switch (text)
                {
                    case "help":
                    case "?":
                        await innerDc.Context.SendActivityAsync($"Show Help...");
                        return new DialogTurnResult(DialogTurnStatus.Waiting);

                    case "cancel":
                    case "quit":
                        await innerDc.Context.SendActivityAsync($"Cancelling");
                        return await innerDc.CancelAllDialogsAsync();
                }
            }

            return null;
        }
    }
</code>```

As @Matt-Stannett mentioned: there is a tutorial as of 5/22/19 here on how to make complex dialogs including component dialogs.

Body:
To tuck this into an answer and get it out of comments:

Waterfalls are not designed to be traversed in anyway but step-by-step/down. You can either nest mini waterfalls inside each waterfall step which would allow for looping individual steps shown here or having conditional checks to skip certain steps shown here.

What you seem to be looking for is ComponentDialogs or using ReplaceDialogAsync. Component Dialogs, part of the botbuilder-dialogs library let you break your bot's logic into components (pieces) that can be added into either a DialogSet or even another component dialog. For example, this is the Cancel/Help component of the Core-Bot sample on the bot framework samples github repo. This component is for what happens if in the middle of another waterfall, the user says 'cancel' or 'help'

public class CancelAndHelpDialog : ComponentDialog
    {
        public CancelAndHelpDialog(string id)
            : base(id)
        {
        }

        protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken)
        {
            var result = await InterruptAsync(innerDc, cancellationToken);
            if (result != null)
            {
                return result;
            }

            return await base.OnBeginDialogAsync(innerDc, options, cancellationToken);
        }

        protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            var result = await InterruptAsync(innerDc, cancellationToken);
            if (result != null)
            {
                return result;
            }

            return await base.OnContinueDialogAsync(innerDc, cancellationToken);
        }

        private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            if (innerDc.Context.Activity.Type == ActivityTypes.Message)
            {
                var text = innerDc.Context.Activity.Text.ToLowerInvariant();

                switch (text)
                {
                    case "help":
                    case "?":
                        await innerDc.Context.SendActivityAsync($"Show Help...");
                        return new DialogTurnResult(DialogTurnStatus.Waiting);

                    case "cancel":
                    case "quit":
                        await innerDc.Context.SendActivityAsync($"Cancelling");
                        return await innerDc.CancelAllDialogsAsync();
                }
            }

            return null;
        }
    }

As @Matt-Stannett mentioned: there is a tutorial as of 5/22/19 here on how to make complex dialogs including component dialogs.


问:
Search string in text file and return matching pattern
I've this simple issue with a text file.
I need to list and send into a file a string containing specific characters, let say "sql".
I've used grep but the issue is "grep" returns the entire line,
Below an example. I don't paste from real file because the line make more the 3000 characters, I mean I guess because I didn't count them.

But below, it's a short sample, the idea is to return just the line matching the keyword "sql"

Thank you if you can help

Below the code I used :

```<code>grep -Rw "sql" sql.lst

> /abc/test/01GFG.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjfhdgfskhhjljljljljlkjljljljklj
> /abc/test/02H.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjhghjggjgjgjgjgjgjg
 > /abc/test/03ABY.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjhkhhkljljdjdgjdkjhfjlflfkljfljflkjf
</code>```

What I need is return into a file the result below:

```<code>  /abc/test/01GFG.sql
  /abc/test/02H.sql
  /abc/test/03ABY.sql
</code>```

Thank you in advance if you can help

答:
After the grep, you can refine your result using the "cut" command:

```<code>echo "/abc/test/01GFG.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjfhdgfskhhjljljljljlkjljljljklj
/abc/test/02H.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjhghjggjgjgjgjgjgjg
 /abc/test/03ABY.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjhkhhkljljdjdgjdkjhfjlflfkljfljflkjf" | grep "sql" | cut -f 1 -d:
</code>```

Cheers

Body:
I've this simple issue with a text file.
I need to list and send into a file a string containing specific characters, let say "sql".
I've used grep but the issue is "grep" returns the entire line,
Below an example. I don't paste from real file because the line make more the 3000 characters, I mean I guess because I didn't count them.

But below, it's a short sample, the idea is to return just the line matching the keyword "sql"

Thank you if you can help

Below the code I used :

grep -Rw "sql" sql.lst

> /abc/test/01GFG.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjfhdgfskhhjljljljljlkjljljljklj
> /abc/test/02H.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjhghjggjgjgjgjgjgjg
 > /abc/test/03ABY.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjhkhhkljljdjdgjdkjhfjlflfkljfljflkjf

What I need is return into a file the result below:

  /abc/test/01GFG.sql
  /abc/test/02H.sql
  /abc/test/03ABY.sql

Thank you in advance if you can help

Body:
After the grep, you can refine your result using the "cut" command:

echo "/abc/test/01GFG.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjfhdgfskhhjljljljljlkjljljljklj
/abc/test/02H.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjhghjggjgjgjgjgjgjg
 /abc/test/03ABY.sql:/ryryutuyttuy-gjgjhhfhgdy-
cghdgfdgfsgsgghfjhkhhkljljdjdgjdkjhfjlflfkljfljflkjf" | grep "sql" | cut -f 1 -d:

Cheers


问:
Checking the style of child nodes
I have a search utility where each section has a
 tag title.
Within each section, there is a span that I search through with a filter and either display them or not. The issue I'm running into is I'm not sure how to target the
 tag within the wrapper and display it as well.

I was considering having another script looking at the elements and check if the children have the display none styling or not, although this seems like a barbaric approach.

Here's a small example. If you search the number the list filter's as it should and the title is still there of course. It's that
 tag I want to hide if the list in that section is 'empty' or hidden. Any suggestions?

Could I do something where I grab the parentNode of the parentNode and check the styling?

or prehaps grab the list's (list1,list2,list3) and on filter search also check if their childNodes are being displayed?

 function search() {
  var input, filter, content, txtValue,list;
  input = document.getElementById("search-input");
  filter = input.value.toUpperCase();
  list = document.getElementById("search-list");
  content = list.getElementsByTagName("span");
  for (i = 0; i < content.length; i++) {
   if (content) {
    txtValue = content[i].innerHTML;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
     content[i].parentNode.style.display = "";
    } else {
     content[i].parentNode.style.display = "none";
    }
   }
  }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <input type="text" id="search-input" placeholder="Search for numbers" onkeyup="search()">
  <div id="search-list">
    <div class="list1">
      <h1> List 1</h1>
      <button><span>one</span></button>
      <button><span>two</span></button>
      <button><span>three</span></button>
    </div>
    <div class="list2">
      <h1> List 2</h1>
      <button><span>four</span></button>
      <button><span>five</span></button>
      <button><span>six</span></button>
    </div>
    <div class="list3">
      <h1> List 3</h1>
      <button><span>seven</span></button>
      <button><span>eight</span></button>
      <button><span>nine</span></button>
    </div>
  </div>
</div></code>```

答:
```<code>content[index]
</code>```

returns a span element.

One level up in the hierarchy is it's parent - the button.

Another level up is the button's parent - which is the div.

From there the h1 tag is the next children of the div, so to access it you can use

```<code>content[index].parentNode.parentNode.children[0]
</code>```

Title: Checking the style of child nodes

Body:
I have a search utility where each section has a
 tag title.
Within each section, there is a span that I search through with a filter and either display them or not. The issue I'm running into is I'm not sure how to target the
 tag within the wrapper and display it as well.

I was considering having another script looking at the elements and check if the children have the display none styling or not, although this seems like a barbaric approach.

Here's a small example. If you search the number the list filter's as it should and the title is still there of course. It's that
 tag I want to hide if the list in that section is 'empty' or hidden. Any suggestions?

Could I do something where I grab the parentNode of the parentNode and check the styling?

or prehaps grab the list's (list1,list2,list3) and on filter search also check if their childNodes are being displayed?

 function search() {
  var input, filter, content, txtValue,list;
  input = document.getElementById("search-input");
  filter = input.value.toUpperCase();
  list = document.getElementById("search-list");
  content = list.getElementsByTagName("span");
  for (i = 0; i < content.length; i++) {
   if (content) {
    txtValue = content[i].innerHTML;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
     content[i].parentNode.style.display = "";
    } else {
     content[i].parentNode.style.display = "none";
    }
   }
  }
 }

  <input type="text" id="search-input" placeholder="Search for numbers" onkeyup="search()">

 List 1

      <button>one</button>
      <button>two</button>
      <button>three</button>

 List 2

      <button>four</button>
      <button>five</button>
      <button>six</button>

 List 3

      <button>seven</button>
      <button>eight</button>
      <button>nine</button>

Body:
content[index]

returns a span element.

One level up in the hierarchy is it's parent - the button.

Another level up is the button's parent - which is the div.

From there the h1 tag is the next children of the div, so to access it you can use

content[index].parentNode.parentNode.children[0]


问:
How can I make android app wait till a phone call is completed?
I am trying to make multiple phone calls via my android app one after another, by calling a function inside a loop and providing a phone number as a parameter, then the call is made and the function ends and returns to the loop for next phone call and the function with next number is called.

I have tried adding wait() for a certain time which makes the app run as intended, but if call duration is bigger than wait time it doesn't work.

private void callingStart() {
            while (tempAL.size() > 0) {

```<code>            PhoneNumber = (String) tempAL.get(0);
            PhoneNumber.trim();
            tempAL.remove(callingIndex);
            if (PhoneNumber.length() > 0) {
                finish();
                makePhoneCall(PhoneNumber);
            }
        }
</code>```

}

private void makePhoneCall(String PhoneNumber1) {

```<code>    if (ContextCompat.checkSelfPermission(callresult.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(callresult.this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL);

    }
    else {

            if (COUNT == callMade) {
                startActivity(getIntent());
                String dial = "tel:" + PhoneNumber1;
                Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(dial));
                startActivity(i);
            }
    }
}
</code>```

I was expecting that call would be made one by one.
But all the calls are made at once or only the last call is made.

I want to make phone call only after the previous call ends.
How can I do that?

答: You don't wait for the phone call to finish-  you'd register for notification of phone events.  I have some old code at How to detect incoming calls, in an Android device? which will show how to know when a call is ended.  When it ends, then you unregister and run whatever code you would have waited for.</p>

Body:
I am trying to make multiple phone calls via my android app one after another, by calling a function inside a loop and providing a phone number as a parameter, then the call is made and the function ends and returns to the loop for next phone call and the function with next number is called.

I have tried adding wait() for a certain time which makes the app run as intended, but if call duration is bigger than wait time it doesn't work.

private void callingStart() {
            while (tempAL.size() > 0) {

            PhoneNumber = (String) tempAL.get(0);
            PhoneNumber.trim();
            tempAL.remove(callingIndex);
            if (PhoneNumber.length() > 0) {
                finish();
                makePhoneCall(PhoneNumber);
            }
        }

}

private void makePhoneCall(String PhoneNumber1) {

    if (ContextCompat.checkSelfPermission(callresult.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(callresult.this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL);

    }
    else {

            if (COUNT == callMade) {
                startActivity(getIntent());
                String dial = "tel:" + PhoneNumber1;
                Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(dial));
                startActivity(i);
            }
    }
}

I was expecting that call would be made one by one.
But all the calls are made at once or only the last call is made.

I want to make phone call only after the previous call ends.
How can I do that?


问:
Use PHP to display the local IP address of the server
I need to display the address of the server by which it can be identified in LAN.

I tried using

```<code>echo $_SERVER["SERVER_ADDR"];
</code>```

but this just returns 127.0.0.1 instead of 192.168.xx.xx.

How do i get the second one without the access to WWW?

答:
Hope this will help,

```<code>function getLanIP(){
    exec("ipconfig /all", $output);
        foreach($output as $line){
            if (preg_match("/(.*)IPv4 Address(.*)/", $line)){
                $ip = $line;
                $ip = str_replace("IPv4 Address. . . . . . . . . . . :","",$ip);
                $ip = str_replace("(Preferred)","",$ip);
            }
        }
    return $ip;
}
</code>```

OR something like,

```<code>$ip = getLanIP();
echo $ip;

<?php
function getLocalIp(){
     return gethostbyname(trim(`hostname`));
}
echo getLocalIp();
?>
</code>```

Body:
I need to display the address of the server by which it can be identified in LAN.

I tried using

echo $_SERVER["SERVER_ADDR"];

but this just returns 127.0.0.1 instead of 192.168.xx.xx.

How do i get the second one without the access to WWW?

Body:
Hope this will help,

function getLanIP(){
    exec("ipconfig /all", $output);
        foreach($output as $line){
            if (preg_match("/(.*)IPv4 Address(.*)/", $line)){
                $ip = $line;
                $ip = str_replace("IPv4 Address. . . . . . . . . . . :","",$ip);
                $ip = str_replace("(Preferred)","",$ip);
            }
        }
    return $ip;
}

OR something like,

$ip = getLanIP();
echo $ip;

<?php
function getLocalIp(){
     return gethostbyname(trim(`hostname`));
}
echo getLocalIp();
?>


问:
Flat a list based on property in Kotlin
I have a list of custom objects which look as follows:

```<code>listOf(MyItem(1, listOf("Aus","Ame")), MyItem(2, listOf("Cha", "Tel")))
</code>```

MyItem class:

```<code>data class MyItem(val num: Int, val list: List<String>)
</code>```

I want to expand the list as below based on the property of code in MyItem class:

```<code>listOf(MyItem(1, listOf("Aus")), MyItem(1, listOf("Ame")), MyItem(2, listOf("Cha")), MyItem(2, listOf("Tel")))
</code>```

How can achieve this?

答:
Use flatMap and then another map inside.

```<code>
val input = listOf(MyItem(1, listOf("Aus","Ame")), MyItem(2, listOf("Cha", "Tel")))
val result = input.flatMap { item -> item.list.map { item.copy(list = listOf(it)) } }
println(result)
// listOf(MyItem(1, listOf("Aus")), MyItem(1, listOf("Ame")), MyItem(2, listOf("Cha")), MyItem(2, listOf("Tel")))
</code>```

Title: Flat a list based on property in Kotlin

Body:
I have a list of custom objects which look as follows:

listOf(MyItem(1, listOf("Aus","Ame")), MyItem(2, listOf("Cha", "Tel")))

MyItem class:

data class MyItem(val num: Int, val list: List<String>)

I want to expand the list as below based on the property of code in MyItem class:

listOf(MyItem(1, listOf("Aus")), MyItem(1, listOf("Ame")), MyItem(2, listOf("Cha")), MyItem(2, listOf("Tel")))

How can achieve this?

Body:
Use flatMap and then another map inside.

val input = listOf(MyItem(1, listOf("Aus","Ame")), MyItem(2, listOf("Cha", "Tel")))
val result = input.flatMap { item -> item.list.map { item.copy(list = listOf(it)) } }
println(result)
// listOf(MyItem(1, listOf("Aus")), MyItem(1, listOf("Ame")), MyItem(2, listOf("Cha")), MyItem(2, listOf("Tel")))


问:
Any alternatives to the .Net 4 Code Contracts static analyser?
It seems that the static analyser for use with the .NET 4.0 Code Contracts is only going to be available for Team Suite editions of Visual Studio - this puts it well outside the budget for my team.

Are there any alternatives (open source, free or reasonably priced) which offer similar static analysis for design by contract style code (not necessarily using .net code contracts). I'm guessing the answer will be no as the full worth only comes when the BCL itself has contracts - but are there any which go part of the way?

答: I am using static analysis in VS2010 Premium.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How can I detect whether a symlink is broken in Bash?
I run find and iterate through the results with [ \( -L $F \)  ] to collect certain symbolic links.

I am wondering if there is an easy way to determine if the link is broken (points to a non-existent file) in this scenario.

Here is my code:

```<code>FILES=`find /target/ | grep -v '\.disabled$' | sort`

for F in $FILES; do
    if [ -L $F ]; then
        DO THINGS
    fi
done
</code>```

答:
What's wrong with:

file $f | grep 'broken symbolic link'

Body:
I run find and iterate through the results with [ \( -L $F \)  ] to collect certain symbolic links.

I am wondering if there is an easy way to determine if the link is broken (points to a non-existent file) in this scenario.

Here is my code:

FILES=`find /target/ | grep -v '\.disabled$' | sort`

for F in $FILES; do
    if [ -L $F ]; then
        DO THINGS
    fi
done


问:
Prolog: Creating a frequency list of another list
So, I've written a program that reads input from a .txt file in the form of 2 integers and a list of integers: the first integer is the length of the list, the second is the number of different elements, and the list is the list in question.

I then want to create a list of frequencies for the elements, like so:

```<code>List = [1, 2, 3, 1, 3, 2, 3, 1],
FreqList = [3, 2, 3].
</code>```

Here is my code:

```<code>% Create random list
createList(List) :-
length(List, 10),
maplist(random(0,4), List).

% Count the frequency of an element:
countElement(_, [], 0) :- !.
countElement(_, [], _).
countElement(Element, [Element|Tail], Counter) :-
    countElement(Element, Tail, Counter2),
    Counter is Counter2 + 1.
countElement(Element, [_|Tail], Counter) :-
    countElement(Element, Tail, Counter).

% Create frequency list:
createFreqList(_, _, Numbers, [], CurrentNumber) :-
    Numbers = CurrentNumber.
createFreqList(List, Length, Numbers, [Head|Tail], CurrentNumber) :-
    Numbers \= CurrentNumber,
    countElement(CurrentNumber, List, Head),
    CurrentNumber2 is CurrentNumber + 1,
    createFreqList(List, Length, Numbers, Tail, CurrentNumber2).

frequency(List, FreqList) :-
    createList(List),
    Numbers2 is 4,
    createFreqList(List, 10, Numbers2, FreqList, 1).
</code>```

So, on first execution the program runs ok, and it outputs the correct frequency list. However, if I input ';', instead of giving me 'false' it runs again, outputing a wrong frequency list, and that just repeats for as long as I press ';'.

答:
Just in case you don't want to reinvent the wheel.

There is a quasi standard called library(aggregate). But library(aggregate) can be also implemented on top of the ISO core standard bagof/3, which also gets you there:

```<code>Welcome to SWI-Prolog (threaded, 64 bits, version 8.1.6)

?- aggregate(count, member(X,[1, 2, 3, 1, 3, 2, 3, 1]), R).
X = 1,
R = 3 ;
X = R, R = 2 ;
X = R, R = 3.

?- bagof(hit, member(X,[1, 2, 3, 1, 3, 2, 3, 1]), L), length(L, R).
X = 1,
L = [hit, hit, hit],
R = 3 ;
X = R, R = 2,
L = [hit, hit] ;
X = R, R = 3,
L = [hit, hit, hit].
</code>```

Or in another Prolog system:

```<code>Jekejeke Prolog 3, Runtime Library 1.3.7 (May 23, 2019)

?- use_module(library(advanced/aggregate)).
% 3 consults and 0 unloads in 110 ms.
Yes

?- use_module(library(basic/lists)).
% 0 consults and 0 unloads in 0 ms.
Yes

?- aggregate(count, member(X,[1, 2, 3, 1, 3, 2, 3, 1]), R).
X = 1,
R = 3 ;
X = 2,
R = 2 ;
X = 3,
R = 3

?- bagof(hit, member(X,[1, 2, 3, 1, 3, 2, 3, 1]), L), length(L, R).
X = 1,
L = [hit,hit,hit],
R = 3 ;
X = 2,
L = [hit,hit],
R = 2 ;
X = 3,
L = [hit,hit,hit],
R = 3
</code>```

Body:
So, I've written a program that reads input from a .txt file in the form of 2 integers and a list of integers: the first integer is the length of the list, the second is the number of different elements, and the list is the list in question.

I then want to create a list of frequencies for the elements, like so:

List = [1, 2, 3, 1, 3, 2, 3, 1],
FreqList = [3, 2, 3].

Here is my code:

% Create random list
createList(List) :-
length(List, 10),
maplist(random(0,4), List).

% Count the frequency of an element:
countElement(_, [], 0) :- !.
countElement(_, [], _).
countElement(Element, [Element|Tail], Counter) :-
    countElement(Element, Tail, Counter2),
    Counter is Counter2 + 1.
countElement(Element, [_|Tail], Counter) :-
    countElement(Element, Tail, Counter).

% Create frequency list:
createFreqList(_, _, Numbers, [], CurrentNumber) :-
    Numbers = CurrentNumber.
createFreqList(List, Length, Numbers, [Head|Tail], CurrentNumber) :-
    Numbers \= CurrentNumber,
    countElement(CurrentNumber, List, Head),
    CurrentNumber2 is CurrentNumber + 1,
    createFreqList(List, Length, Numbers, Tail, CurrentNumber2).

frequency(List, FreqList) :-
    createList(List),
    Numbers2 is 4,
    createFreqList(List, 10, Numbers2, FreqList, 1).

So, on first execution the program runs ok, and it outputs the correct frequency list. However, if I input ';', instead of giving me 'false' it runs again, outputing a wrong frequency list, and that just repeats for as long as I press ';'.

Body:
Just in case you don't want to reinvent the wheel.

There is a quasi standard called library(aggregate). But library(aggregate) can be also implemented on top of the ISO core standard bagof/3, which also gets you there:

Welcome to SWI-Prolog (threaded, 64 bits, version 8.1.6)

?- aggregate(count, member(X,[1, 2, 3, 1, 3, 2, 3, 1]), R).
X = 1,
R = 3 ;
X = R, R = 2 ;
X = R, R = 3.

?- bagof(hit, member(X,[1, 2, 3, 1, 3, 2, 3, 1]), L), length(L, R).
X = 1,
L = [hit, hit, hit],
R = 3 ;
X = R, R = 2,
L = [hit, hit] ;
X = R, R = 3,
L = [hit, hit, hit].

Or in another Prolog system:

Jekejeke Prolog 3, Runtime Library 1.3.7 (May 23, 2019)

?- use_module(library(advanced/aggregate)).
% 3 consults and 0 unloads in 110 ms.
Yes

?- use_module(library(basic/lists)).
% 0 consults and 0 unloads in 0 ms.
Yes

?- aggregate(count, member(X,[1, 2, 3, 1, 3, 2, 3, 1]), R).
X = 1,
R = 3 ;
X = 2,
R = 2 ;
X = 3,
R = 3

?- bagof(hit, member(X,[1, 2, 3, 1, 3, 2, 3, 1]), L), length(L, R).
X = 1,
L = [hit,hit,hit],
R = 3 ;
X = 2,
L = [hit,hit],
R = 2 ;
X = 3,
L = [hit,hit,hit],
R = 3


问:
How to set URL query params in Vue with Vue-Router
I am trying to set query params with Vue-router when changing input fields, I don't want to navigate to some other page but just want to modify url query params on the same page, I am doing like this:

```<code>this.$router.replace({ query: { q1: "q1" } })
</code>```

But this also refreshes the page and sets the y position to 0, ie scrolls to the top of the page. Is this the correct way to set the URL query params or is there a better way to do it.

Edited:

Here is my router code:

```<code>export default new Router({
  mode: 'history',
  scrollBehavior: (to, from, savedPosition)  => {
    if (to.hash) {
      return {selector: to.hash}
    } else {
      return {x: 0, y: 0}
    }
  },
  routes: [
    .......
    { path: '/user/:id', component: UserView },
  ]
})
</code>```

答:
To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):

```<code>    setQuery(query){
        let obj = Object.assign({}, this.$route.query);

        Object.keys(query).forEach(key => {
            let value = query[key];
            if(value){
                obj[key] = value
            } else {
                delete obj[key]
            }
        })
        this.$router.replace({
            ...this.$router.currentRoute,
            query: obj
        })
    },

    removeQuery(queryNameArray){
        let obj = {}
        queryNameArray.forEach(key => {
            obj[key] = null
        })
        this.setQuery(obj)
    },
</code>```

Body:
I am trying to set query params with Vue-router when changing input fields, I don't want to navigate to some other page but just want to modify url query params on the same page, I am doing like this:

this.$router.replace({ query: { q1: "q1" } })

But this also refreshes the page and sets the y position to 0, ie scrolls to the top of the page. Is this the correct way to set the URL query params or is there a better way to do it.

Edited:

Here is my router code:

export default new Router({
  mode: 'history',
  scrollBehavior: (to, from, savedPosition)  => {
    if (to.hash) {
      return {selector: to.hash}
    } else {
      return {x: 0, y: 0}
    }
  },
  routes: [
    .......
    { path: '/user/:id', component: UserView },
  ]
})

Body:
To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):

    setQuery(query){
        let obj = Object.assign({}, this.$route.query);

        Object.keys(query).forEach(key => {
            let value = query[key];
            if(value){
                obj[key] = value
            } else {
                delete obj[key]
            }
        })
        this.$router.replace({
            ...this.$router.currentRoute,
            query: obj
        })
    },

    removeQuery(queryNameArray){
        let obj = {}
        queryNameArray.forEach(key => {
            obj[key] = null
        })
        this.setQuery(obj)
    },


问:
Connecting to ravendb using node.js
I'm currently trying to set up a small project with node.js and ravendb. But when I try to connect to the ravendb test server or a local server I get the following error:

```<code>(node:20336) UnhandledPromiseRejectionWarning: AllTopologyNodesDownException: Tried to send BatchCommand request via POST http://live-test.ravendb.net/databases/Northwind/bulk_docs to all configured nodes in the topology, all of them seem to be down or not responding. I've tried to access the following nodes: http://live-test.ravendb.net: socket hang up
at getError (C:\...\node_modules\ravendb\dist\Exceptions\index.js:17:19)
at Object.throwError (C:\...\node_modules\ravendb\dist\Exceptions\index.js:13:11)
at RequestExecutor._throwFailedToContactAllNodes (C:\...\node_modules\ravendb\dist\Http\RequestExecutor.js:669:22)
at RequestExecutor.<anonymous> (C:\...\node_modules\ravendb\dist\Http\RequestExecutor.js:573:26)
at Generator.next (<anonymous>)
at fulfilled (C:\...\node_modules\ravendb\dist\Http\RequestExecutor.js:4:58)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:20336) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
(rejection id: 1)
(node:20336) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

Index.js

```<code>const { DocumentStore } = require('ravendb');

const store = new DocumentStore("http://live-test.ravendb.net", "Northwind");

store.initialize();

const session = store.openSession();

async function asyncFunction() {
    let test = {
        name: 'abc',
        value: '123',
    };

    await session.store(test, 'test/');
    console.log(test.id);
    await session.saveChanges();
}

asyncFunction()

store.dispose();
</code>```

package.json

```<code>{
  "dependencies": {
    "ravendb": "^4.1.5"
  }
}
</code>```

答:
Try like this : </p>

```<code>import { DocumentStore } from "ravendb";

const store = new DocumentStore(["http://live-test.ravendb.net"],"Northwind");

const conventions = store.conventions;

store.initialize();
</code>```

Title: Connecting to ravendb using node.js

Body:
I'm currently trying to set up a small project with node.js and ravendb. But when I try to connect to the ravendb test server or a local server I get the following error:

(node:20336) UnhandledPromiseRejectionWarning: AllTopologyNodesDownException: Tried to send BatchCommand request via POST http://live-test.ravendb.net/databases/Northwind/bulk_docs to all configured nodes in the topology, all of them seem to be down or not responding. I've tried to access the following nodes: http://live-test.ravendb.net: socket hang up
at getError (C:\...\node_modules\ravendb\dist\Exceptions\index.js:17:19)
at Object.throwError (C:\...\node_modules\ravendb\dist\Exceptions\index.js:13:11)
at RequestExecutor._throwFailedToContactAllNodes (C:\...\node_modules\ravendb\dist\Http\RequestExecutor.js:669:22)
at RequestExecutor.<anonymous> (C:\...\node_modules\ravendb\dist\Http\RequestExecutor.js:573:26)
at Generator.next (<anonymous>)
at fulfilled (C:\...\node_modules\ravendb\dist\Http\RequestExecutor.js:4:58)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:20336) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
(rejection id: 1)
(node:20336) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Index.js

const { DocumentStore } = require('ravendb');

const store = new DocumentStore("http://live-test.ravendb.net", "Northwind");

store.initialize();

const session = store.openSession();

async function asyncFunction() {
    let test = {
        name: 'abc',
        value: '123',
    };

    await session.store(test, 'test/');
    console.log(test.id);
    await session.saveChanges();
}

asyncFunction()

store.dispose();

package.json

{
  "dependencies": {
    "ravendb": "^4.1.5"
  }
}

Body:
Try like this :

import { DocumentStore } from "ravendb";

const store = new DocumentStore(["http://live-test.ravendb.net"],"Northwind");

const conventions = store.conventions;

store.initialize();


问:
How can I remove certain characters from a string only if it comes before a specific character
I have a string that has parenthesis in it. I want to write a function to remove the parenthesis if they exist and what's inside only if it comes before a comma. Sometimes in my string, there may be more than 1 set of parenthesis in the string; but I would only like to remove the set before the parenthesis. </p>

```<code>var string1 = "Dog (big), 0"
var string2 = "Dog (medium) (black), 1"
var string3 = "Dog (small) (brown), 1"

What I want:

string1 = "Dog, 0"
string1 = "Dog (medium), 0"
string1 = "Dog (small), 0"
</code>```

答:
You can use Regex to perform this kind of string manipulation. For example:

```<code>Regex regex = new Regex(@"\s\([^\(\)]+\)(?=,)");

var inputs = new[] {
    "Dog (small) (brown), 1",
    "Dog (medium) (black), 1",
    "Dog (big), 0"
};

foreach (var input in inputs)
    Console.WriteLine(regex.Replace(input, ""));

// will output:
// Dog (small), 1
// Dog (medium), 1
// Dog, 0
</code>```

This is what the pattern means:

\s will match white space, to remove spaces before the bracket.

\( will match the opening bracket (the slash escapes because brackets have meaning in regex)

[^\(\)]+ is a character set - ^ negates, so means anything except an open or close bracket - this is to match the content in a pair of brackets, and avoid matching both pairs of brackets. The + is a quantifier meaning one or more times.

\) will match the closing bracket

(?=,) is a positive look ahead. It says what comes before must be followed by a comma.

Body:
I have a string that has parenthesis in it. I want to write a function to remove the parenthesis if they exist and what's inside only if it comes before a comma. Sometimes in my string, there may be more than 1 set of parenthesis in the string; but I would only like to remove the set before the parenthesis.

var string1 = "Dog (big), 0"
var string2 = "Dog (medium) (black), 1"
var string3 = "Dog (small) (brown), 1"

What I want:

string1 = "Dog, 0"
string1 = "Dog (medium), 0"
string1 = "Dog (small), 0"

Body:
You can use Regex to perform this kind of string manipulation. For example:

Regex regex = new Regex(@"\s\([^\(\)]+\)(?=,)");

var inputs = new[] {
    "Dog (small) (brown), 1",
    "Dog (medium) (black), 1",
    "Dog (big), 0"
};

foreach (var input in inputs)
    Console.WriteLine(regex.Replace(input, ""));

// will output:
// Dog (small), 1
// Dog (medium), 1
// Dog, 0

This is what the pattern means:

\s will match white space, to remove spaces before the bracket.

\( will match the opening bracket (the slash escapes because brackets have meaning in regex)

[^\(\)]+ is a character set - ^ negates, so means anything except an open or close bracket - this is to match the content in a pair of brackets, and avoid matching both pairs of brackets. The + is a quantifier meaning one or more times.

\) will match the closing bracket

(?=,) is a positive look ahead. It says what comes before must be followed by a comma.


问:
How can I get every nth item from a List<T>?
I'm using .NET 3.5 and would like to be able to obtain every *n*th item from a List.  I'm not bothered as to whether it's achieved using a lambda expression or LINQ.

Edit

Looks like this question provoked quite a lot of debate (which is a good thing, right?).  The main thing I've learnt is that when you think you know every way to do something (even as simple as this), think again!

答:
@belucha I like this, because the client code is very readable and the Compiler chooses the most efficient Implementation. I would build upon this by reducing the requirements to IReadOnlyList<T> and to save the Division for high-performance LINQ:

```<code>    public static IEnumerable<T> GetNth<T>(this IEnumerable<T> list, int n) {
        if (n <= 0) throw new ArgumentOutOfRangeException(nameof(n), n, null);
        int i = n;
        foreach (var e in list) {
            if (++i < n) { //save Division
                continue;
            }
            i = 0;
            yield return e;
        }
    }

    public static IEnumerable<T> GetNth<T>(this IReadOnlyList<T> list, int n
        , int offset = 0) { //use IReadOnlyList<T>
        if (n <= 0) throw new ArgumentOutOfRangeException(nameof(n), n, null);
        for (var i = offset; i < list.Count; i += n) {
            yield return list[i];
        }
    }
</code>```

OwnerDisplayName: thedorko

LastEditorDisplayName: thedorko

Body:
@belucha I like this, because the client code is very readable and the Compiler chooses the most efficient Implementation. I would build upon this by reducing the requirements to IReadOnlyList<T> and to save the Division for high-performance LINQ:

    public static IEnumerable<T> GetNth<T>(this IEnumerable<T> list, int n) {
        if (n <= 0) throw new ArgumentOutOfRangeException(nameof(n), n, null);
        int i = n;
        foreach (var e in list) {
            if (++i < n) { //save Division
                continue;
            }
            i = 0;
            yield return e;
        }
    }

    public static IEnumerable<T> GetNth<T>(this IReadOnlyList<T> list, int n
        , int offset = 0) { //use IReadOnlyList<T>
        if (n <= 0) throw new ArgumentOutOfRangeException(nameof(n), n, null);
        for (var i = offset; i < list.Count; i += n) {
            yield return list[i];
        }
    }


问:
How to make Post call using RxAlamofire pass json in post body
I want to make a post call using RxAlamofire it provides function requestJson which requires two parameters type get or post and url but there is no parameter to pass post json body how to do that following is my code

```<code> var components = URLComponents(string: url)!
    components.setQueryItems(with: param)
    let url = components.url!
    print("\(url)")

    RxAlamofire.requestJSON(.post, url)
        .subscribe(onNext: { [weak self] (r, json) in
            if let jsonResult = JSON(json) as? JSON {
                if let cartResult = FoodCartResult(jsonResult) as? FoodCartResult {
                    self?.delegate?.showCart(cartresult: cartResult)
                }
            }

            }, onError: {  [weak self] (error) in
                print(error.localizedDescription)
                self?.delegate?.onError()
            },onCompleted: {})
        .disposed(by: disposeBag)
</code>```

答:
Actually the other parameters are included in the definition of requestJson, they just have default parameters. So you can safely say:</p>

```<code>RxAlamofire.requestJSON(.post,
                        url,
                        parameters: ["param1": "value1"],
                        encoding: JSONEncoding.default,
                        headers: nil)
</code>```

Body:
I want to make a post call using RxAlamofire it provides function requestJson which requires two parameters type get or post and url but there is no parameter to pass post json body how to do that following is my code

 var components = URLComponents(string: url)!
    components.setQueryItems(with: param)
    let url = components.url!
    print("\(url)")

    RxAlamofire.requestJSON(.post, url)
        .subscribe(onNext: { [weak self] (r, json) in
            if let jsonResult = JSON(json) as? JSON {
                if let cartResult = FoodCartResult(jsonResult) as? FoodCartResult {
                    self?.delegate?.showCart(cartresult: cartResult)
                }
            }

            }, onError: {  [weak self] (error) in
                print(error.localizedDescription)
                self?.delegate?.onError()
            },onCompleted: {})
        .disposed(by: disposeBag)

Body:
Actually the other parameters are included in the definition of requestJson, they just have default parameters. So you can safely say:

RxAlamofire.requestJSON(.post,
                        url,
                        parameters: ["param1": "value1"],
                        encoding: JSONEncoding.default,
                        headers: nil)


答:
The default shape, 19, doesn't have a fill, so the parameter is ignored.

# Dummy data frame
df <- data.frame(x = rep(1, 10), y = rep(1, 10))

# Load library
library(ggplot2)

# Plot data
g <- ggplot(df) + geom_count(aes(x, y), colour = "black", fill = NA)
g
```

<p><img src="https://i.imgur.com/VdEPlm6.png" alt=""></p>

<p>Whereas, <code>shape = 1</code> <em>does</em> have a fill option.</p>

<pre class="lang-r prettyprint-override"><code># Plot data
g <- ggplot(df) + geom_count(aes(x, y), colour = "black", fill = NA, shape = 1)
g
</code>```

Created on 2019-05-31 by the reprex package (v0.3.0)

A full list of shapes can be found at the bottom of the page here.

Title: Fill aesthetic not working while using geom_count

Body:
I'm trying to set the fill to of my ggplot object to NA. I've done it before using similar code but for some reason this code isn't working. Any ideas?

Here's my data:

structure(list(longitude = c(-81.09397, -81.09397, -81.09397,
-81.09397, -81.09397, -81.15897, -81.15897, -81.15897, -81.15897,
-81.15897, -81.15897, -81.17191, -81.17538, -81.17191, -81.17538,
-81.17191, -81.17538, -81.17191, -81.17538, -81.17191, -81.17538,
-81.16389, -81.17191, -81.17538, -81.17191, -81.17538, -81.17191,
-81.17538, -81.16389, -81.17191, -81.17538, -81.16389, -81.17191,
-81.17538, -81.16389, -81.17191, -81.16127, -81.16389, -81.17191,
-81.16389, -81.17191, -81.16127, -81.17191, -81.17191, -81.25841,
-81.25841, -81.25841, -81.24818, -81.25841, -81.25841, -81.25841,
-81.25841, -81.25841, -81.24818, -81.25841, -81.25841, -81.24818,
-81.25841, -81.25841, -81.25841, -81.24818, -81.25841, -81.24818,
-81.25841, -81.24818, -81.25841, -81.24818, -81.25841, -81.24818,
-81.25841, -81.24818, -81.25841, -81.24818, -81.25841, -81.26803,
-81.24818, -81.25841, -81.24818, -81.25841, -81.24818, -81.25841,
-81.24818, -81.23814, -81.25841, -81.24818, -81.25841, -81.24818,
-81.24818, -81.24818, -81.24818, -81.25841, -81.24818, -81.25841,
-81.24818, -81.24818, -81.24818, -81.24818, -81.24818, -81.25841
), latitude = c(72.35019, 72.35019, 72.35019, 72.35019, 72.35019,
72.32544, 72.32544, 72.32544, 72.32544, 72.32544, 72.32544, 72.294,
72.2963, 72.294, 72.2963, 72.294, 72.2963, 72.294, 72.2963, 72.294,
72.2963, 72.29368, 72.294, 72.2963, 72.294, 72.2963, 72.294,
72.2963, 72.29368, 72.294, 72.2963, 72.29368, 72.294, 72.2963,
72.29368, 72.294, 72.29111, 72.29368, 72.294, 72.29368, 72.294,
72.29111, 72.294, 72.294, 72.26846, 72.26846, 72.26846, 72.26533,
72.26846, 72.26846, 72.26846, 72.26846, 72.26846, 72.26533, 72.26846,
72.26846, 72.26533, 72.26846, 72.26846, 72.26846, 72.26533, 72.26846,
72.26533, 72.26846, 72.26533, 72.26846, 72.26533, 72.26846, 72.26533,
72.26846, 72.26533, 72.26846, 72.26533, 72.26846, 72.27166, 72.26533,
72.26846, 72.26533, 72.26846, 72.26533, 72.26846, 72.26533, 72.26213,
72.26846, 72.26533, 72.26846, 72.26533, 72.26533, 72.26533, 72.26533,
72.26846, 72.26533, 72.26846, 72.26533, 72.26533, 72.26533, 72.26533,
72.26533, 72.26846)), class = "data.frame", row.names = c(36499L,
36501L, 36518L, 36527L, 37049L, 37812L, 37816L, 37818L, 37820L,
37826L, 37829L, 37943L, 37944L, 37945L, 37946L, 37947L, 37948L,
37950L, 37951L, 37953L, 37954L, 37955L, 37956L, 37957L, 37958L,
37959L, 37960L, 37961L, 37962L, 37963L, 37964L, 37966L, 37967L,
37968L, 37969L, 37971L, 37972L, 37973L, 37974L, 37975L, 37976L,
37977L, 37978L, 37979L, 37990L, 38007L, 38014L, 38016L, 38017L,
38023L, 38028L, 38031L, 38032L, 38036L, 38037L, 38041L, 38042L,
38045L, 38048L, 38049L, 38052L, 38053L, 38054L, 38055L, 38056L,
38057L, 38058L, 38059L, 38060L, 38061L, 38062L, 38063L, 38064L,
38065L, 38067L, 38068L, 38069L, 38072L, 38073L, 38074L, 38075L,
38076L, 38077L, 38079L, 38080L, 38081L, 38082L, 38083L, 38084L,
38086L, 38088L, 38090L, 38091L, 38094L, 38095L, 38096L, 38097L,
38098L, 38209L))

And here's my current code:

ggplot()+
  geom_count(data = DetsIND, aes( x = longitude, y = latitude), color = 'black', fill = NA)+
  xlim(-81.4, -80.55)+ ylim( 72.2, 72.7)

Body:
The default shape, 19, doesn't have a fill, so the parameter is ignored.

# Dummy data frame
df <- data.frame(x = rep(1, 10), y = rep(1, 10))

# Load library
library(ggplot2)

# Plot data
g <- ggplot(df) + geom_count(aes(x, y), colour = "black", fill = NA)
g

Whereas, shape = 1 does have a fill option.

# Plot data
g <- ggplot(df) + geom_count(aes(x, y), colour = "black", fill = NA, shape = 1)
g

Created on 2019-05-31 by the reprex package (v0.3.0)

A full list of shapes can be found at the bottom of the page here.


问:
How can I get the full string of PHP’s getTraceAsString()?
I'm using getTraceAsString() to get a stack trace but the string is being truncated for some reason.

Example, an exception is thrown and I log the string using:

```<code>catch (SoapFault $e) {
error_log( $e->getTraceAsString() )
}
</code>```

The string thats prints out is:

#0 C:\Somedirectory\Somedirectory\Somedirectory\Somedir\SomeScript.php(10): SoapClient->SoapClient('http://www.ex...')

How can I get the full string to print?

答:
You can print the backtrace with

```<code>debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
</code>```

It does not truncate.

Example print would be

```<code>#0  W3\\Sausage\\Mushroom->setCredentials() called at [/sausage/common/library/W3/Vzaar/Api.php:40]
#1  W3\\Sausage\\Mushroom->__construct() called at [/sausage/common/modules/video.mod.php:24]
#2  ModVideo->__construct() called at [/sausage/common/core/modules.core.php:133]
#3  Modules->__get() called at [/sausage/common/search/Classified/ESAdapter.php:399]
#4  Base\\Search\\Classified\\ESAdapter->getVideoInfo() called at [/sausage/common/search/Classified/ESAdapter.php:436]
#5  Base\\Search\\Classified\\ESAdapter->fillDataSet() called at [/sausage/common/search/Adapter.php:58]
</code>```

Body:
I'm using getTraceAsString() to get a stack trace but the string is being truncated for some reason.

Example, an exception is thrown and I log the string using:

catch (SoapFault $e) {
error_log( $e->getTraceAsString() )
}

The string thats prints out is:

#0 C:\Somedirectory\Somedirectory\Somedirectory\Somedir\SomeScript.php(10): SoapClient->SoapClient('http://www.ex...')

How can I get the full string to print?

Body:
You can print the backtrace with

debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);

It does not truncate.

Example print would be

#0  W3\\Sausage\\Mushroom->setCredentials() called at [/sausage/common/library/W3/Vzaar/Api.php:40]
#1  W3\\Sausage\\Mushroom->__construct() called at [/sausage/common/modules/video.mod.php:24]
#2  ModVideo->__construct() called at [/sausage/common/core/modules.core.php:133]
#3  Modules->__get() called at [/sausage/common/search/Classified/ESAdapter.php:399]
#4  Base\\Search\\Classified\\ESAdapter->getVideoInfo() called at [/sausage/common/search/Classified/ESAdapter.php:436]
#5  Base\\Search\\Classified\\ESAdapter->fillDataSet() called at [/sausage/common/search/Adapter.php:58]


问:
UIViewController rotate methods
What object is responsible for dipatching the UIViewController rotation method calls, i.e:

shouldAutorotateToInterfaceOrientation:

willRotateToInterfaceOrientation:duration:

willAnimateFirstHalfOfRotationToInterfaceOrientation:duration:

willAnimateSecondHalfOfRotationFromInterfaceOrientation:duration:

didRotateFromInterfaceOrientation:

I imagine it is UIApplication (but maybe the AppDelegate or UIWindow).

The next question, is how does the object know which UIViewController to talk to?

How does it know which UIViewController has its view as the subview of the window?

Is there a message you can send or a property you can set (of some object) that sets the "Active" UIViewController for the app?

答:
It seems that UIApplication is dispatching a message to the active view controller.

But how does your View Controller instance get these messages?

The message is forwarded to the first view controller whose view has been added to the UIWindow instance.

This boils down to 3 basic scenarios:

The ViewController whose view is
added directly to the UIWindow
instance (single view app)

The navigation Controller in a
    Navigation based app, then the
    navigation controller forwards the
    message to the active views view
    controller.

The tab bar Controller in a tab bar
        based app, then the tab bar
        controller forwards the message to
        the active views view controller (or
        the active navigation controller).

The problem you will have, is if you build an app with multiple views, but DO NOT use a Navigation controller or Tab Bar controller.  If you swap views in and out of the UIWindow instance manually, you will not receive these messages reliably.
This is similar to posts like this one:
iPhone viewWillAppear not firing

Just use Apple's conventions for multiple views and you be fine.  Hope this saves some one an hour or two

OwnerDisplayName: Corey

Title: UIViewController rotate methods


问:
Unable to read SMS from the Nokia phone using GSMComm
I'm implementing a project for reading and parsing SMS from Nokia Xpress Music 5800 using GSMComm library

I tried using GSMComm Demo: I'm able to get phone information, different status such as battery/storage and send SMS. But I'm not able to read SMS from the phone, it's giving following error:

```<code>Error: The phone reports an unspecified error.
</code>```

This typically happens when a command is not supported by the device,a command is not valid for the current state or if a parameter is incorrect.
    (GsmComm.GsmCommunication.CommException)

Since I use DLL's I don't see which commands are being sent to the phone. Also I doubt that all other commands work, except the ones reading the SMS.

Questions:

Main Question: what are possible causes of the problem?

I know it's difficult to answer above question. So is there any logs/dumps/events being logged in some place? I'm totally new in this area (hardware interfacing) and need starting point for troubleshooting

 Stretch: If I implement using above technology (USB to COMM emulator, GSMComm), what's the portability of my application? Definitely GSMComm dll needs to be shipped. But does this mean that the target PC needs to have Ovi Suite (containing USB to COMM emulator) installed? What about portablity on the phone: will it work only WITH Nokia Xpress Music 5800, or will it work with other Nokia phone as well. Or with  any other phone?"

More info: OS on my phone is in
  Cyriliic alphabet, if that matters.

Updated the question: since some of the questions were answered after a week of investigation.

Update 2: I've followed instructions in this link. My phone is responding to some of the commands, but giving "ERROR" for others. Any ideas?

答:
http://www.scampers.org/steve/sms/libraries.htm

I'm sure you've gone over this page, but at the bottom it tells you how to check the logs for GSMComm. Unfortunately, I have never worked directly with GSMComm and couldn't tell you what the root cause of the problem is, but try checking the logs. If you haven't read through the FAQ, I would do so, it may shed some light on the questions you are asking.

As far as portability, if you require a third-party emulator for you to run it, that would have to be a pre-requisite for others to use your application. Any GSMComm DLLs that contain code you use would also be required for distribution or else your program won't work.

Body:
I'm implementing a project for reading and parsing SMS from Nokia Xpress Music 5800 using GSMComm library

I tried using GSMComm Demo: I'm able to get phone information, different status such as battery/storage and send SMS. But I'm not able to read SMS from the phone, it's giving following error:

Error: The phone reports an unspecified error.

This typically happens when a command is not supported by the device,a command is not valid for the current state or if a parameter is incorrect.
    (GsmComm.GsmCommunication.CommException)

Since I use DLL's I don't see which commands are being sent to the phone. Also I doubt that all other commands work, except the ones reading the SMS.

Questions:

Main Question: what are possible causes of the problem?

I know it's difficult to answer above question. So is there any logs/dumps/events being logged in some place? I'm totally new in this area (hardware interfacing) and need starting point for troubleshooting

 Stretch: If I implement using above technology (USB to COMM emulator, GSMComm), what's the portability of my application? Definitely GSMComm dll needs to be shipped. But does this mean that the target PC needs to have Ovi Suite (containing USB to COMM emulator) installed? What about portablity on the phone: will it work only WITH Nokia Xpress Music 5800, or will it work with other Nokia phone as well. Or with  any other phone?"

More info: OS on my phone is in
  Cyriliic alphabet, if that matters.

Updated the question: since some of the questions were answered after a week of investigation.

Update 2: I've followed instructions in this link. My phone is responding to some of the commands, but giving "ERROR" for others. Any ideas?


问:
Django Query for Total Count of Records In ManyToMany Field
Given two models joined by a ManyToMany without a through table:

```<code>class Ingredient(models.Model):
    name = models.CharField(max_length=255)

class Recipe(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(Ingredient)
</code>```

How do I find the total count of instances of an ingredient being used in a recipe?

For example, if I had two ingredients (apples and sugar) and two recipes (apple pie and donuts) how would I know that there are 3 uses of recipes (two because apple pie uses apples and sugar, and one because donuts use sugar)?

I could do this with the following:

```<code>count = 0
for recipe in Recipe.objects.all():
  count += recipe.ingredients.count()
</code>```

but that generates too many queries.

Is there an easy way to get this number with annotation / aggregation?

答:
We can try like this (to avoid a lot of DB hits of course. Use database aggregations).

```<code>from django.db.models import Count

recipes = Recipe.objects.annotate(count_ingredients=Count('ingredients'))
for recipe in recipes:
    print(recipe.pk, recipe.count_ingredients)
</code>```

Body:
Given two models joined by a ManyToMany without a through table:

class Ingredient(models.Model):
    name = models.CharField(max_length=255)

class Recipe(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(Ingredient)

How do I find the total count of instances of an ingredient being used in a recipe?

For example, if I had two ingredients (apples and sugar) and two recipes (apple pie and donuts) how would I know that there are 3 uses of recipes (two because apple pie uses apples and sugar, and one because donuts use sugar)?

I could do this with the following:

count = 0
for recipe in Recipe.objects.all():
  count += recipe.ingredients.count()

but that generates too many queries.

Is there an easy way to get this number with annotation / aggregation?

Body:
We can try like this (to avoid a lot of DB hits of course. Use database aggregations).

from django.db.models import Count

recipes = Recipe.objects.annotate(count_ingredients=Count('ingredients'))
for recipe in recipes:
    print(recipe.pk, recipe.count_ingredients)


问:
error CS0430: The extern alias 'snh' was not specified in a /reference option [Up.UnitTests\obj\x64\Debug\Fakes\wsc\f.csproj]
Unit test project Up.UnitTests fails during build, with this build errors

error CS0430: The extern alias 'snh' was not specified in a /reference option
error CS0234: The type or namespace name 'System' does not exist in the namespace 'snh' (are you missing an assembly reference?)

The type or namespace name 'System' does not exist in the namespace 'snh'

I am guessing the above errors are due to System.Net.Http. Is it anything to do with different versions? How to fix this issue. Any help would be appreciated.

答:
I, also, ran into this CS0430 error. In my scenario, the issue came due to a dependency caused by updating NSubstitute. I updated my *.fakes file like below to add diagnostics and see that the issue was System.Net.Http like you observed.

```<code><Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
  <Assembly Name="ClassLibrary1"/>
</Fakes>
</code>```

After this, I tried to find the root cause of the issue by slowly removing the new dependencies and found that when System.Threading.Tasks.Extensions Nuget reference was there I would get the build error. During the upgrade NSubstitute added the  System.Threading.Tasks.Extensions. In your scenario, it may likely be a similar dependency issue that it is not directly related to System.Net.Http.

Update: I found this issue on the dotnet/sdk repo that fixes the issue. To your test project, add the following Directory.Build.targets.

```<code><Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <Target Name="PrivateFakesAfterFacadesSwitch"
          Condition="'$(ImplicitlyExpandNETStandardFacades)' == 'true' and $(AssemblyName.EndsWith('.Fakes'))"
          AfterTargets="ImplicitlyExpandNETStandardFacades" DependsOnTargets="ImplicitlyExpandNETStandardFacades">

    <ItemGroup Condition="'@(_NETStandardLibraryNETFrameworkLib)' != ''">
      <SnhReference Include = "@(_NETStandardLibraryNETFrameworkLib)" Condition="'%(_NETStandardLibraryNETFrameworkLib.FileName)' == 'System.Net.Http'" />

      <Reference Remove="%(SnhReference.FileName)" Condition="'@(SnhReference)' != ''"/>
      <Reference Include="%(SnhReference.FileName)" Condition="'@(SnhReference)' != ''">
        <HintPath>%(SnhReference.Identity)</HintPath>
        <Private>false</Private>
        <Aliases>snh</Aliases>
      </Reference>
    </ItemGroup>

  </Target>

</Project>
</code>```

Body:
I, also, ran into this CS0430 error. In my scenario, the issue came due to a dependency caused by updating NSubstitute. I updated my *.fakes file like below to add diagnostics and see that the issue was System.Net.Http like you observed.

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
  <Assembly Name="ClassLibrary1"/>
</Fakes>

After this, I tried to find the root cause of the issue by slowly removing the new dependencies and found that when System.Threading.Tasks.Extensions Nuget reference was there I would get the build error. During the upgrade NSubstitute added the  System.Threading.Tasks.Extensions. In your scenario, it may likely be a similar dependency issue that it is not directly related to System.Net.Http.

Update: I found this issue on the dotnet/sdk repo that fixes the issue. To your test project, add the following Directory.Build.targets.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <Target Name="PrivateFakesAfterFacadesSwitch"
          Condition="'$(ImplicitlyExpandNETStandardFacades)' == 'true' and $(AssemblyName.EndsWith('.Fakes'))"
          AfterTargets="ImplicitlyExpandNETStandardFacades" DependsOnTargets="ImplicitlyExpandNETStandardFacades">

    <ItemGroup Condition="'@(_NETStandardLibraryNETFrameworkLib)' != ''">
      <SnhReference Include = "@(_NETStandardLibraryNETFrameworkLib)" Condition="'%(_NETStandardLibraryNETFrameworkLib.FileName)' == 'System.Net.Http'" />

      <Reference Remove="%(SnhReference.FileName)" Condition="'@(SnhReference)' != ''"/>
      <Reference Include="%(SnhReference.FileName)" Condition="'@(SnhReference)' != ''">
        <HintPath>%(SnhReference.Identity)</HintPath>
        <Private>false</Private>
        <Aliases>snh</Aliases>
      </Reference>
    </ItemGroup>

  </Target>

</Project>


问:
Extract first few alphabets before numbers and skip the rest
I have a strange requirement where we want to extract first few alphabets in a string and skip the rest where there can be combination of alphabets and numbers.
e.g.

Text

```<code>1.  aaaa bbbb ccc 00110011 ddd eee ff 00 99
2.  bbbbbbbbbbbbbbbbbbbbbb 0123 azbe 999999999999999
3.  zfsfzzzzzzzzzz asasas 111 3333333 xxysys ddddd  9090909
4.  Returns the nth field within a delimited string 5555555555 99999999
</code>```

Output

```<code>1.  aaaa bbbb ccc
2.  bbbbbbbbbbbbbbbbbbbbbb
3.  zfsfzzzzzzzzzz asasas
4.  Returns the nth field within a delimited string
</code>```

We are using Hue/Impala and would like to extract all alphabets in first characters or all left characters before a number string starts.

Thank you

答:
I think regexp_extract() should work:

```<code>select regexp_extract(col, '^[a-zA-Z ]+', 0)
</code>```

Body:
I have a strange requirement where we want to extract first few alphabets in a string and skip the rest where there can be combination of alphabets and numbers.
e.g.

Text

1.  aaaa bbbb ccc 00110011 ddd eee ff 00 99
2.  bbbbbbbbbbbbbbbbbbbbbb 0123 azbe 999999999999999
3.  zfsfzzzzzzzzzz asasas 111 3333333 xxysys ddddd  9090909
4.  Returns the nth field within a delimited string 5555555555 99999999

Output

1.  aaaa bbbb ccc
2.  bbbbbbbbbbbbbbbbbbbbbb
3.  zfsfzzzzzzzzzz asasas
4.  Returns the nth field within a delimited string

We are using Hue/Impala and would like to extract all alphabets in first characters or all left characters before a number string starts.

Thank you

Body:
I think regexp_extract() should work:

select regexp_extract(col, '^[a-zA-Z ]+', 0)


问:
Remove multiple items from a list based on other list
I have two lists, which are both list of lists of the same lengths

list1 [[1 3 5 7] [2 5 1 6]]

list2 [[0.5 0.3 0.7 0.1] [0.1 0.4 0.6 0.2]]

My task is: if a number in list2 is <= e.g  0.2, remove items at corresponding position from list1. So based on the above example items in list2 which are <= 0.2 are [[3] [0 3]] and the final list1 should look like this [[1 3 5] [5 1]]. The same items should then be removed from list2 so its final version would look like [[0.5 0.3 0.7] [0.4 0.6]].
The below code works well but becomes very slow if the list is long (which is the case in my model)
Is the any efficient way of doing it without running loop of a loop?

```<code>let k 0

foreach list2
  [
    x ->
    let each_element_list2 x
    let each_element_list1 k list1
  (foreach each_element_list2
    [
      i ->
      if i <= 0.2
      [
        let rem_pos position i each_element_list2
        set each_element_list2 remove-item rem_pos each_element_list2
        set each_element_list1 remove-item rem_pos each_element_list1
      ]
    ]
    )

  set list2 replace-item k list2 each_element_list2
  set list1 replace-item k list1 each_element_list1
  set k k + 1
  ]
</code>```

Thanx in advance,

Magda

答:
This is not the most elegant code, and I don't have time to explain it step by step, but something like this should work:

```<code>to remove-items

  let list1 [[1   3   5   7  ] [2   5   1   6  ]]
  let list2 [[0.5 0.3 0.7 0.1] [0.1 0.4 0.6 0.2]]
  if length list1 != length list2 [ error "lists should be of equal length" ]

  foreach range length list1 [ i ->
    let sl1 item i list1 ; extract sublist 1
    let sl2 item i list2 ; extract sublist 2
    let indices-to-keep (
      map first                         ; extract the index from the pair
      filter [ p -> last p > 0.2 ]      ; keep the pairs where the item is <= 0.2
      (map list range (length sl2) sl2) ; build a list of index/item pairs
    )
    let replace-sublist [ [l sl] ->
      replace-item i l (map [ j -> item j sl ] indices-to-keep)
    ]
    set list1 (runresult replace-sublist list1 sl1)
    set list2 (runresult replace-sublist list2 sl2)
  ]

  print list1
  print list2

end
</code>```

Just one quick note: notice that I inverted the condition (i.e., > 0.2 instead of <= 0.2), as it's easier to use a list of the indices we want to keep instead of those we want to remove.

Body:
I have two lists, which are both list of lists of the same lengths

list1 [[1 3 5 7] [2 5 1 6]]

list2 [[0.5 0.3 0.7 0.1] [0.1 0.4 0.6 0.2]]

My task is: if a number in list2 is <= e.g  0.2, remove items at corresponding position from list1. So based on the above example items in list2 which are <= 0.2 are [[3] [0 3]] and the final list1 should look like this [[1 3 5] [5 1]]. The same items should then be removed from list2 so its final version would look like [[0.5 0.3 0.7] [0.4 0.6]].
The below code works well but becomes very slow if the list is long (which is the case in my model)
Is the any efficient way of doing it without running loop of a loop?

let k 0

foreach list2
  [
    x ->
    let each_element_list2 x
    let each_element_list1 k list1
  (foreach each_element_list2
    [
      i ->
      if i <= 0.2
      [
        let rem_pos position i each_element_list2
        set each_element_list2 remove-item rem_pos each_element_list2
        set each_element_list1 remove-item rem_pos each_element_list1
      ]
    ]
    )

  set list2 replace-item k list2 each_element_list2
  set list1 replace-item k list1 each_element_list1
  set k k + 1
  ]

Thanx in advance,

Magda

Body:
This is not the most elegant code, and I don't have time to explain it step by step, but something like this should work:

to remove-items

  let list1 [[1   3   5   7  ] [2   5   1   6  ]]
  let list2 [[0.5 0.3 0.7 0.1] [0.1 0.4 0.6 0.2]]
  if length list1 != length list2 [ error "lists should be of equal length" ]

  foreach range length list1 [ i ->
    let sl1 item i list1 ; extract sublist 1
    let sl2 item i list2 ; extract sublist 2
    let indices-to-keep (
      map first                         ; extract the index from the pair
      filter [ p -> last p > 0.2 ]      ; keep the pairs where the item is <= 0.2
      (map list range (length sl2) sl2) ; build a list of index/item pairs
    )
    let replace-sublist [ [l sl] ->
      replace-item i l (map [ j -> item j sl ] indices-to-keep)
    ]
    set list1 (runresult replace-sublist list1 sl1)
    set list2 (runresult replace-sublist list2 sl2)
  ]

  print list1
  print list2

end

Just one quick note: notice that I inverted the condition (i.e., > 0.2 instead of <= 0.2), as it's easier to use a list of the indices we want to keep instead of those we want to remove.


问:
Change Windows 10 Font and Zoom Settings
Our team is distributing Windows 10 that has some features locked down, but for which we provide some automation, one of which is changing screen resolutions. I have been asked to add the ability to change the Display settings, Make text bigger and Make everything bigger.

The only solution I have come across requires rewriting the registry key, and then logging off and then back on. Also, the only solution that I have seen is with PowerShell or CMD. I am currently working with .NET

My questions then are:

Is there a better way? The registry change is easy enough, but I would rather not force the users to log off.

Regardless, I'd rather do this in .NET, so wondering if could someone point me to an existing code sample, or provide one.

Example 1

```<code>@echo off
reg add "HKCU\Control Panel\Desktop" /v LogPixels /t reg_dword /d 144
exit /b
</code>```

Example 2

```<code>cd 'HKCU:\Control Panel\Desktop'
Set-ItemProperty -Path . -Name LogPixels -Value 144
Set-ItemProperty -Path . -Name Win8DpiScaling -Value 1
Set-ItemProperty -Path . -Name FocusBorderHeight -Value 2
Set-ItemProperty -Path . -Name FocusBorderWidth -Value 2
Write-Host 'Sign out and sign back in again to see changes.
</code>```

答:
Untested with your settings changes, but you could try the function below</p>

```<code>function Refresh-Explorer {
    [CmdletBinding()]
    Param()

    $code = @'
private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
private const int WM_SETTINGCHANGE = 0x1a;
private const int SMTO_ABORTIFHUNG = 0x0002;

[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam);

[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SendMessageTimeout ( IntPtr hWnd, int Msg, IntPtr wParam, string lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult );

[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);

public static void Refresh() {
    SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, null, SMTO_ABORTIFHUNG, 3000, IntPtr.Zero);
}
'@

    Add-Type -MemberDefinition $code -Namespace MyWinAPI -Name Explorer
    [MyWinAPI.Explorer]::Refresh()
}
</code>```

Body:
Our team is distributing Windows 10 that has some features locked down, but for which we provide some automation, one of which is changing screen resolutions. I have been asked to add the ability to change the Display settings, Make text bigger and Make everything bigger.

The only solution I have come across requires rewriting the registry key, and then logging off and then back on. Also, the only solution that I have seen is with PowerShell or CMD. I am currently working with .NET

My questions then are:

Is there a better way? The registry change is easy enough, but I would rather not force the users to log off.

Regardless, I'd rather do this in .NET, so wondering if could someone point me to an existing code sample, or provide one.

Example 1

@echo off
reg add "HKCU\Control Panel\Desktop" /v LogPixels /t reg_dword /d 144
exit /b

Example 2

cd 'HKCU:\Control Panel\Desktop'
Set-ItemProperty -Path . -Name LogPixels -Value 144
Set-ItemProperty -Path . -Name Win8DpiScaling -Value 1
Set-ItemProperty -Path . -Name FocusBorderHeight -Value 2
Set-ItemProperty -Path . -Name FocusBorderWidth -Value 2
Write-Host 'Sign out and sign back in again to see changes.

Body:
Untested with your settings changes, but you could try the function below

function Refresh-Explorer {
    [CmdletBinding()]
    Param()

    $code = @'
private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
private const int WM_SETTINGCHANGE = 0x1a;
private const int SMTO_ABORTIFHUNG = 0x0002;

[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam);

[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SendMessageTimeout ( IntPtr hWnd, int Msg, IntPtr wParam, string lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult );

[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);

public static void Refresh() {
    SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, null, SMTO_ABORTIFHUNG, 3000, IntPtr.Zero);
}
'@

    Add-Type -MemberDefinition $code -Namespace MyWinAPI -Name Explorer
    [MyWinAPI.Explorer]::Refresh()
}


问:
How to create dynamic images with text of MS Word Art
I am able to create simple image with text, but I want to apply MS Word Art font to my text.
Any Reference link or help appreciated.

here is my code to create image with Text.

```<code>Font MyFont = new Font(FontFamily, Font,FontStyle.Bold, GraphicsUnit.Point);
MyGraphics = Graphics.FromImage(bmpImage);
MyGraphics.Clear(Color.FromName(Convert.ToString(Request.QueryString["bgColor"])));
MyGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
MyGraphics.DrawString(sImageText, MyFont,
                    new SolidBrush(Color.FromName(Convert.ToString(Request.QueryString["TextColor"]))), 0, 0);
MyGraphics.Flush();
</code>```

Thanks

答: Applying MS Word Art to text in images isn't supported by the .NET Framework libraries but you can apply certain effects. For examples, see Bob Powell's article.</p>

Body:
I am able to create simple image with text, but I want to apply MS Word Art font to my text.
Any Reference link or help appreciated.

here is my code to create image with Text.

Font MyFont = new Font(FontFamily, Font,FontStyle.Bold, GraphicsUnit.Point);
MyGraphics = Graphics.FromImage(bmpImage);
MyGraphics.Clear(Color.FromName(Convert.ToString(Request.QueryString["bgColor"])));
MyGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
MyGraphics.DrawString(sImageText, MyFont,
                    new SolidBrush(Color.FromName(Convert.ToString(Request.QueryString["TextColor"]))), 0, 0);
MyGraphics.Flush();

Thanks


问:
How to embed an iframe in Confluence page?
I want to embed an iframe in a Confluence page, e.g. Google Calendar.

I insert the iframe code in Confluence page, it should show the calendar as follows:

But it just display the text of code as follows:

```<code><iframe src="https://calendar.google.com/calendar/embed?src=3g3ie767f4ji0e72icgtfjg%40group.calendar.google.com&c" style="border: 0" width="800" height="600" frameborder="0" scrolling="auto"></iframe>
</code>```

How to embed an iframe in Confluence page?

答:
When adding a macro I did the following:

"Other Macros"

Search for "iframe"

Select "Iframe" macro

Enter only the iframe url, and any other required settings.

Body:
I want to embed an iframe in a Confluence page, e.g. Google Calendar.

I insert the iframe code in Confluence page, it should show the calendar as follows:

But it just display the text of code as follows:

How to embed an iframe in Confluence page?


问:
Unable to run junit tests in intellij - play button greys out

Hello,

I am wondering if anyone has came across this issue before. I have a maven project where I can run maven commands like clean, verify, compile etc.

However when I try to run or debug anything debug related (like my Junit runner attached), nothing happens, the buttons just grey out. I don't see anything happening on the ide, just the buttons disabled and I am not sure why this is. I did not make any changes in the code so it was working before but I don't know why its not working now:

In the edit config for this junit runner the command is set as:

Here is the code for my runner:

```<code>@RunWith(SerenityRunner.class)
@CucumberOptions(features="src/test/java/resources/features/", glue = {"uk/co/xxx/cucumber/stepDefs"}, tags = {"@currentTest"} )
public class CurrentTestRunner {

    @BeforeClass
    public static void startAppium() {
        AppiumServerController.startAppiumServer();
    }

    @AfterClass
    public static void stopAppium() {
        AppiumServerController.stopAppiumServer();
    }
</code>```

I have tried the following:

Invalidate and restart

Remove idea and open project again

Pull project again from GIT and try again

Updated IntelliJ

答:
You can't run your unit tests because you don't have any tests to run.

You should have at least one method annotated with @Test.

Right now you have two methods in your class.
One is annotated with BeforeClass, the other is annotated with AfterClass.

Those are just methods that run once before the first test (@BeforeClass) and after the last test (@AfterClass).

Add a method like this:

```<code>@Test
public void testCondition(){
//Assertions
}
</code>```

Body:
Hello,

I am wondering if anyone has came across this issue before. I have a maven project where I can run maven commands like clean, verify, compile etc.

However when I try to run or debug anything debug related (like my Junit runner attached), nothing happens, the buttons just grey out. I don't see anything happening on the ide, just the buttons disabled and I am not sure why this is. I did not make any changes in the code so it was working before but I don't know why its not working now:

In the edit config for this junit runner the command is set as:

Here is the code for my runner:

@RunWith(SerenityRunner.class)
@CucumberOptions(features="src/test/java/resources/features/", glue = {"uk/co/xxx/cucumber/stepDefs"}, tags = {"@currentTest"} )
public class CurrentTestRunner {

    @BeforeClass
    public static void startAppium() {
        AppiumServerController.startAppiumServer();
    }

    @AfterClass
    public static void stopAppium() {
        AppiumServerController.stopAppiumServer();
    }

I have tried the following:

Invalidate and restart

Remove idea and open project again

Pull project again from GIT and try again

Updated IntelliJ

Body:
You can't run your unit tests because you don't have any tests to run.

You should have at least one method annotated with @Test.

Right now you have two methods in your class.
One is annotated with BeforeClass, the other is annotated with AfterClass.

Those are just methods that run once before the first test (@BeforeClass) and after the last test (@AfterClass).

Add a method like this:

@Test
public void testCondition(){
//Assertions
}


问:
Plugin to avoid share username in Wordpress
Is there a way to void sharing of username (based on ip address or login at same time in different location) for Wordpress? If there is a plugin just to track IP address and login time, it should be fine too. Thanks</p>

答:
you could add this to your functions.php or a plugin file.

```<code>    //set the most current user to have a cookie matching a unique value
add_action("set_logged_in_cookie", "one_cookie", 10, 5);
function one_cookie($logged_in_cookie, $expire, $expiration, $user_id, $logged_in) {
    $secure = apply_filters('secure_logged_in_cookie', false, $user_id, is_ssl());
    $cookie = uniqid();
    update_user_meta($user_id, "one_cookie", $cookie);
    setcookie("one_cookie", $cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure, true);
    return;
}
//check requests from users to ensure they have this cookie
add_action("init", "check_one_cookie", 1);
function check_one_cookie() {
    $user = wp_get_current_user();
    if ($user->ID == 0) { return; }
    $storedcookie = get_user_meta($user->ID, 'one_cookie');
    print_r(array('$storedcookie'=>$storedcookie));
  if (!empty($storedcookie) && $_COOKIE['one_cookie'] != $storedcookie) {
    /*if the user doesn't have the same cookie as we have stored, log them out.*/
        wp_logout();
        //auth_redirect() may have a more desired effect
    }
}
//unset a users cookie
add_action('wp-logout', 'one_cookie_logout');
function one_cookie_logout() {
    setcookie("one_cookie", "", 1);
}
</code>```

This will work in only one direction though. Any time a new login is processed it will lock out the old one. If you wish to reverse that you'll probably need to write a lot more code so that a user can break a lockout etc.

You could also accomplish this by replacing the appropriate functions in 'wp-includes/pluggable.php'

I've tested the above code to work with WordPress 3.1.

Body:
you could add this to your functions.php or a plugin file.

    //set the most current user to have a cookie matching a unique value
add_action("set_logged_in_cookie", "one_cookie", 10, 5);
function one_cookie($logged_in_cookie, $expire, $expiration, $user_id, $logged_in) {
    $secure = apply_filters('secure_logged_in_cookie', false, $user_id, is_ssl());
    $cookie = uniqid();
    update_user_meta($user_id, "one_cookie", $cookie);
    setcookie("one_cookie", $cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure, true);
    return;
}
//check requests from users to ensure they have this cookie
add_action("init", "check_one_cookie", 1);
function check_one_cookie() {
    $user = wp_get_current_user();
    if ($user->ID == 0) { return; }
    $storedcookie = get_user_meta($user->ID, 'one_cookie');
    print_r(array('$storedcookie'=>$storedcookie));
  if (!empty($storedcookie) && $_COOKIE['one_cookie'] != $storedcookie) {
    /*if the user doesn't have the same cookie as we have stored, log them out.*/
        wp_logout();
        //auth_redirect() may have a more desired effect
    }
}
//unset a users cookie
add_action('wp-logout', 'one_cookie_logout');
function one_cookie_logout() {
    setcookie("one_cookie", "", 1);
}

This will work in only one direction though. Any time a new login is processed it will lock out the old one. If you wish to reverse that you'll probably need to write a lot more code so that a user can break a lockout etc.

You could also accomplish this by replacing the appropriate functions in 'wp-includes/pluggable.php'

I've tested the above code to work with WordPress 3.1.