问:
Fetching all rows of dataframe using Python pandas
I ran a python code and got dataframe output like:

```<code>1    Department of Susta... (2)       Community Services (2)
2    Department of Commu... (2)       Community Services (2)
3    Sustainability Vict... (1)       Community Services (1)
4    Southern Grampians ... (1)       Community Services (1)
5    Productivity Commis... (1)       Community Services (1)
6         Parliament of NSW (1)       Community Services (1)
..                           ...                          ...
30      Noosa Shire Council (2)     Sport and Recreation (2)
31   State Library of Qu... (1)     Sport and Recreation (1)
32   Emergency Services ... (1)     Sport and Recreation (1)
33   Department of Susta... (1)     Sport and Recreation (1)
</code>```

now i don't have rows b/w 7 to 29. How to fetch all rows?

答:
You can create a function like this one</p>

```<code>def print_full(x):
    pd.set_option('display.max_rows', len(x))
    print(x)
    pd.reset_option('display.max_rows')
</code>```

Body:
I ran a python code and got dataframe output like:

1    Department of Susta... (2)       Community Services (2)
2    Department of Commu... (2)       Community Services (2)
3    Sustainability Vict... (1)       Community Services (1)
4    Southern Grampians ... (1)       Community Services (1)
5    Productivity Commis... (1)       Community Services (1)
6         Parliament of NSW (1)       Community Services (1)
..                           ...                          ...
30      Noosa Shire Council (2)     Sport and Recreation (2)
31   State Library of Qu... (1)     Sport and Recreation (1)
32   Emergency Services ... (1)     Sport and Recreation (1)
33   Department of Susta... (1)     Sport and Recreation (1)

now i don't have rows b/w 7 to 29. How to fetch all rows?

Body:
You can create a function like this one

def print_full(x):
    pd.set_option('display.max_rows', len(x))
    print(x)
    pd.reset_option('display.max_rows')


来源: stackexchange

问:
Make .toggleClass() to affect only one element with the same class on click in jQuery
I am trying to make dropdown menu with jQuery. Problem that my script effects all elements with the same class on click. Below is my problem in the snippet:

$(document).ready(function() {
  $('.parent').click(function() {
    $('.sub-nav').toggleClass('visible');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}</code>```

Home

One

Two

Three

About

Johnny

Julie

Jamie

Contact

```
</div>
</div>
</p>

<p>I was trying to play around with :</p>

```$(document)
    .ready(function () {
    $('.parent')
        .click(function () {
        $(this).children('.sub-nav').toggleClass('visible');
    });
});
```

but without any decent results. Could someone tell where I am missing the point? Many thanks for all possible help, looking forward.

答:
$(document).ready(function() {
  $('.parent').click(function() {
  $('.parent').not(this).find('.sub-nav.visible').removeClass('visible');
    $('.sub-nav',this).toggleClass('visible');//find .sub-nav of clicked .parent
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}</code>```

Home

One

Two

Three

About

Johnny

Julie

Jamie

Contact

```

Use this context

To get the clicked parent

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make dropdown menu with jQuery. Problem that my script effects all elements with the same class on click. Below is my problem in the snippet:

$(document).ready(function() {
  $('.parent').click(function() {
    $('.sub-nav').toggleClass('visible');
  });
});

#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}

Home

One

Two

Three

About

Johnny

Julie

Jamie

Contact

I was trying to play around with :

$(document)
    .ready(function () {
    $('.parent')
        .click(function () {
        $(this).children('.sub-nav').toggleClass('visible');
    });
});

but without any decent results. Could someone tell where I am missing the point? Many thanks for all possible help, looking forward.

Body:
$(document).ready(function() {
  $('.parent').click(function() {
  $('.parent').not(this).find('.sub-nav.visible').removeClass('visible');
    $('.sub-nav',this).toggleClass('visible');//find .sub-nav of clicked .parent
  });
});

#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="nav">
  <li class="parent">Home
    <ul class="sub-nav">
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
    </ul>
  </li>
  <li class="parent">About
    <ul class="sub-nav">
      <li>Johnny</li>
      <li>Julie</li>
      <li>Jamie</li>
    </ul>
  </li>
  <li>Contact</li>
</ul>

Use this context

To get the clicked parent


问:
php:How to fix ''Array ( )''? am trying to get contents from each individual file in a folder
```<code>    <?php

        function cmp($a, $b) {
            if (filemtime($a) == filemtime($b))
                return 0;

            return (filemtime($a) < filemtime($b)) ? -1 : 1;
        }

        $files = glob("/Users/xx/Desktop/2011/cdr/*.cdr");
        usort($files, "cmp");

        foreach($files as $file)

            //echo $file . "<br />";
            // echo "$file was last modified: " . date ("d-m-Y H:i:s.", filemtime($file))."\n";

    $file1 = file_get_contents($file, FILE_USE_INCLUDE_PATH);

    $arr1 = explode("\n", $file1);

    $data1 = array();

     foreach ($arr1 as $key => $value) {
 $split = explode(";", $value);

 $keys = md5(uniqid(rand(), true));
}
 print_r($data1);
?>
</code>```

I am trying to get contents from each file but it keep getting below

Array ( )

Question is how can i fix the error when am trying to get contents from each individual file in a folder? Should i make a loop to read from each file separately ?

答:
```<code>$files = glob("/Users/xx/Desktop/2011/cdr/*.cdr");
</code>```

This call to glob() will return an array of absolute paths like:

```<code>"/Users/xx/Desktop/2011/cdr/example.cdr"
</code>```

The path is part of the returned value! (This is unlike some other functions like readdir().) You don't need to append the path again when you call file_get_contents().

Body:
    <?php

        function cmp($a, $b) {
            if (filemtime($a) == filemtime($b))
                return 0;

            return (filemtime($a) < filemtime($b)) ? -1 : 1;
        }

        $files = glob("/Users/xx/Desktop/2011/cdr/*.cdr");
        usort($files, "cmp");

        foreach($files as $file)

            //echo $file . "
";
            // echo "$file was last modified: " . date ("d-m-Y H:i:s.", filemtime($file))."\n";

    $file1 = file_get_contents($file, FILE_USE_INCLUDE_PATH);

    $arr1 = explode("\n", $file1);

    $data1 = array();

     foreach ($arr1 as $key => $value) {
 $split = explode(";", $value);

 $keys = md5(uniqid(rand(), true));
}
 print_r($data1);
?>

I am trying to get contents from each file but it keep getting below

Array ( )

Question is how can i fix the error when am trying to get contents from each individual file in a folder? Should i make a loop to read from each file separately ?

Body:
$files = glob("/Users/xx/Desktop/2011/cdr/*.cdr");

This call to glob() will return an array of absolute paths like:

"/Users/xx/Desktop/2011/cdr/example.cdr"

The path is part of the returned value! (This is unlike some other functions like readdir().) You don't need to append the path again when you call file_get_contents().


问:
How to debug a Windows DLL used inside Python?
On Windows7 I have a python script that uses Windows DLLs, using the .NET Common Language Runtime (CLR). An error occurs inside one of the used DLL, but the standard Python debugger only debugs on the Python code level (and not the DLL).

How can I debug what is going on inside the DLL(s)?

答:
These 3 debugging scenarios with pythonnet are based on PTVS docs:

https://github.com/pythonnet/pythonnet/wiki/Various-debugging-scenarios-of-embedded-CPython


问:
How to declarate LARGE_INTEGER in C#
the code below(in C++) is what I am trying the convert into C#

```<code>DWORD Func_X_4(DWORD arg1, DWORD arg2, DWORD arg3)
{
LARGE_INTEGER result = {1, 0};
LARGE_INTEGER temp1 = {0};
LARGE_INTEGER temp2 = {0};
LARGE_INTEGER temp3 = {0};
LARGE_INTEGER temp4 = {0};
for(int x = 0; x < 32; ++x)
{
    if(arg2 & 1)
    {
        temp1.LowPart = arg3;
        temp1.HighPart = 0;
        temp2.QuadPart = temp1.QuadPart * result.QuadPart;
        temp3.LowPart = arg1;
        temp3.HighPart = 0;
        temp4.QuadPart = temp2.QuadPart % temp3.QuadPart;
        result.QuadPart = temp4.QuadPart;
    }
    arg2 >>= 1;
    temp1.LowPart = arg3;
    temp1.HighPart = 0;
    temp1.QuadPart *= temp1.QuadPart;
    temp2.LowPart = arg1;
    temp2.HighPart = 0;
    temp3.QuadPart = temp1.QuadPart % temp2.QuadPart;
    arg3 = temp3.LowPart;
    if(!arg2)
        break;
}
return result.LowPart;
}
</code>```

Here I tried to translate the code,but it's too messy and I never worked with Large integers before.

Structure:

```<code>public struct LARGE_INTEGER
{
    UInt32 LowPart;
    Int32 HighPart;
    Int32 QuadPart;
}
</code>```

Translated function:

```<code>    public Int32 Func_X_4(Int32 arg1, Int32 arg2, Int32 arg3)
    {
    LARGE_INTEGER result = {1, 0}; //this and the four below,are they correct?
    LARGE_INTEGER temp1 = {0, 0};
    LARGE_INTEGER temp2 = {0, 0};
    LARGE_INTEGER temp3 = {0, 0};
    LARGE_INTEGER temp4 = {0, 0};
    for(int x = 0; x < 32; ++x)
    {
        if(arg2 & 1==0) //correct?
        {
            temp1.LowPart = arg3;
            temp1.HighPart = 0;
            temp2.QuadPart = temp1.QuadPart * result.QuadPart;
            temp3.LowPart = arg1;
            temp3.HighPart = 0;
            temp4.QuadPart = temp2.QuadPart % temp3.QuadPart;
            result.QuadPart = temp4.QuadPart;
        }
        arg2 >>= 1;
        temp1.LowPart = arg3;
        temp1.HighPart = 0;
        temp1.QuadPart *= temp1.QuadPart;
        temp2.LowPart = arg1;
        temp2.HighPart = 0;
        temp3.QuadPart = temp1.QuadPart % temp2.QuadPart;
        arg3 = temp3.LowPart;
        if(arg2 != 0) //correct?
        break;
    }
    return result.LowPart;
}
</code>```

Problems:
The first problem is that I haven't found a LARGE_INTEGER type variable in C#,so I created a strucure,I'd like to know if there is actually.
As for the second problem,the function is not right,nothing worked.

Any help on that particular question will be greatfuly appreciated!
Thank you in advance.

答:
Building on a previous answer I found that it was useful to extend the definition of LARGE_INTEGER to include int and uint versions of the high and low parts:</p>

```<code>[StructLayout(LayoutKind.Explicit, Size=8)]
struct LARGE_INTEGER
    {
    [FieldOffset(0)]public long QuadPart;

    [FieldOffset(0)]public uint LowPart;
    [FieldOffset(4)]public int HighPart;

    [FieldOffset(0)]public int LowPartAsInt;
    [FieldOffset(0)]public uint LowPartAsUInt;

    [FieldOffset(4)]public int HighPartAsInt;
    [FieldOffset(4)]public uint HighPartAsUInt;
    }
</code>```

OwnerDisplayName: John

ContentLicense: CC BY-SA 2.5

Title: How to declarate LARGE_INTEGER in C#

Body:
the code below(in C++) is what I am trying the convert into C#

DWORD Func_X_4(DWORD arg1, DWORD arg2, DWORD arg3)
{
LARGE_INTEGER result = {1, 0};
LARGE_INTEGER temp1 = {0};
LARGE_INTEGER temp2 = {0};
LARGE_INTEGER temp3 = {0};
LARGE_INTEGER temp4 = {0};
for(int x = 0; x < 32; ++x)
{
    if(arg2 & 1)
    {
        temp1.LowPart = arg3;
        temp1.HighPart = 0;
        temp2.QuadPart = temp1.QuadPart * result.QuadPart;
        temp3.LowPart = arg1;
        temp3.HighPart = 0;
        temp4.QuadPart = temp2.QuadPart % temp3.QuadPart;
        result.QuadPart = temp4.QuadPart;
    }
    arg2 >>= 1;
    temp1.LowPart = arg3;
    temp1.HighPart = 0;
    temp1.QuadPart *= temp1.QuadPart;
    temp2.LowPart = arg1;
    temp2.HighPart = 0;
    temp3.QuadPart = temp1.QuadPart % temp2.QuadPart;
    arg3 = temp3.LowPart;
    if(!arg2)
        break;
}
return result.LowPart;
}

Here I tried to translate the code,but it's too messy and I never worked with Large integers before.

Structure:

public struct LARGE_INTEGER
{
    UInt32 LowPart;
    Int32 HighPart;
    Int32 QuadPart;
}

Translated function:

    public Int32 Func_X_4(Int32 arg1, Int32 arg2, Int32 arg3)
    {
    LARGE_INTEGER result = {1, 0}; //this and the four below,are they correct?
    LARGE_INTEGER temp1 = {0, 0};
    LARGE_INTEGER temp2 = {0, 0};
    LARGE_INTEGER temp3 = {0, 0};
    LARGE_INTEGER temp4 = {0, 0};
    for(int x = 0; x < 32; ++x)
    {
        if(arg2 & 1==0) //correct?
        {
            temp1.LowPart = arg3;
            temp1.HighPart = 0;
            temp2.QuadPart = temp1.QuadPart * result.QuadPart;
            temp3.LowPart = arg1;
            temp3.HighPart = 0;
            temp4.QuadPart = temp2.QuadPart % temp3.QuadPart;
            result.QuadPart = temp4.QuadPart;
        }
        arg2 >>= 1;
        temp1.LowPart = arg3;
        temp1.HighPart = 0;
        temp1.QuadPart *= temp1.QuadPart;
        temp2.LowPart = arg1;
        temp2.HighPart = 0;
        temp3.QuadPart = temp1.QuadPart % temp2.QuadPart;
        arg3 = temp3.LowPart;
        if(arg2 != 0) //correct?
        break;
    }
    return result.LowPart;
}

Problems:
The first problem is that I haven't found a LARGE_INTEGER type variable in C#,so I created a strucure,I'd like to know if there is actually.
As for the second problem,the function is not right,nothing worked.

Any help on that particular question will be greatfuly appreciated!
Thank you in advance.

Body:
Building on a previous answer I found that it was useful to extend the definition of LARGE_INTEGER to include int and uint versions of the high and low parts:

[StructLayout(LayoutKind.Explicit, Size=8)]
struct LARGE_INTEGER
    {
    [FieldOffset(0)]public long QuadPart;

    [FieldOffset(0)]public uint LowPart;
    [FieldOffset(4)]public int HighPart;

    [FieldOffset(0)]public int LowPartAsInt;
    [FieldOffset(0)]public uint LowPartAsUInt;

    [FieldOffset(4)]public int HighPartAsInt;
    [FieldOffset(4)]public uint HighPartAsUInt;
    }


问:
Copy text from label in xamarin.forms
I'm quite new to Xamarin.Forms. I have started to create an application which will display large amount of text retrieved from a book. At the moment I add the text into a Label, however the user can't copy the text he sees on the screen in any of the three platforms.

Is there a way to enable copying of text from a label in Xamarin.Forms? I have tried with Editor as well, it works to copy the data when pushed into Editor, however user can enter characters which is what I don't want them to do. I just want to show the text that I have read in from the stream and make it possible for the user to copy the amount of text he wishes. Any help will be appreciated!

答:
Can you try below

Page.Xaml

```<code><Entry TextChanged="Handle_TextChanged" Text="EnteyText" Unfocused="Handle_Unfocused" Focused="Handle_Focused" x:Name="entry" HeightRequest="50" WidthRequest="100" BackgroundColor="Aqua"/>
<Button Text="Bind Text From Book" Clicked="Handle_Clicked" HeightRequest="50" WidthRequest="100" />
</code>```

Page.Xaml.CS

```<code>    bool isFocused;
    string entryText="EnteyText";

    void Handle_Focused(object sender, Xamarin.Forms.FocusEventArgs e)
    {
        isFocused = e.IsFocused;
    }

        void Handle_Unfocused(object sender, Xamarin.Forms.FocusEventArgs e)
        {
            isFocused = e.IsFocused;
        }

        void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
        {
            if (!isFocused)
            {
                entryText = (sender as Entry).Text;
            }
            if (isFocused && entryText != e.NewTextValue)
            {
                (sender as Entry).Text = e.OldTextValue;
            }
        }

        void Handle_Clicked(object sender, System.EventArgs e)
        {
            entry.Unfocus();
            entry.Text = "Text from book";
        }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Copy text from label in xamarin.forms

Body:
Can you try below

Page.Xaml

<Entry TextChanged="Handle_TextChanged" Text="EnteyText" Unfocused="Handle_Unfocused" Focused="Handle_Focused" x:Name="entry" HeightRequest="50" WidthRequest="100" BackgroundColor="Aqua"/>
<Button Text="Bind Text From Book" Clicked="Handle_Clicked" HeightRequest="50" WidthRequest="100" />

Page.Xaml.CS

    bool isFocused;
    string entryText="EnteyText";

    void Handle_Focused(object sender, Xamarin.Forms.FocusEventArgs e)
    {
        isFocused = e.IsFocused;
    }

        void Handle_Unfocused(object sender, Xamarin.Forms.FocusEventArgs e)
        {
            isFocused = e.IsFocused;
        }

        void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
        {
            if (!isFocused)
            {
                entryText = (sender as Entry).Text;
            }
            if (isFocused && entryText != e.NewTextValue)
            {
                (sender as Entry).Text = e.OldTextValue;
            }
        }

        void Handle_Clicked(object sender, System.EventArgs e)
        {
            entry.Unfocus();
            entry.Text = "Text from book";
        }


问:
Using PHP to split a URL
I am creating a PHP proxy where it accepts a url and confirms it is on my list of servers.

When importing the url from the application i ran it to an issue where i needed 2 parser tags. i need it to split along a "\?" tag as well as a string, in my case, "export?"

i am using preg for the first tag. Does this accept the strings like my export tag or is there some other method for doing this?

please le me know how this is accomplished or if you have more questions.

答:
Regular expressions are strings matches that may also include variable matches. Because ? is included within ?, you have to do your split twice. Once on export? first, and a second pass on each of those with ? as your delimiter. As written below, you're just splitting on either of two different strings.

```<code>$first = preg_split('export\?', ...);
for ($first) {
        array_push ($second,preg_split('\?', ...)');
}
</code>```

That isn't perfectly valid PHP, but I hope it is close enough pseudocode.

Title: Using PHP to split a URL

Body:
Regular expressions are strings matches that may also include variable matches. Because ? is included within ?, you have to do your split twice. Once on export? first, and a second pass on each of those with ? as your delimiter. As written below, you're just splitting on either of two different strings.

$first = preg_split('export\?', ...);
for ($first) {
        array_push ($second,preg_split('\?', ...)');
}

That isn't perfectly valid PHP, but I hope it is close enough pseudocode.


问:
How to generate a custom color scale for plotly heatmap in R
I would like to get a custom color scale which looks like for plotly heatmap (plot_ly(z = data, colors = customcolors, type = "heatmap"))

```<code>palette <- colorRampPalette(c("darkblue", "blue", "lightblue1",
                          "green","yellow", "red", "darkred"))
plot(rep(1,50),col=palette(50), pch=19, cex=3, xlab = "", ylab ="", axes = F)
</code>```

and where the blue end represents 1 and red end represents 10^6 and plotted data would have varying values on this interval.

答:
The code you use to generate a color palette works just fine. You only need to provide data that match with a heatmap. The following code provides this:

```<code>library(RColorBrewer)
library(plotly)

# your palette definition
palette <- colorRampPalette(c("darkblue", "blue", "lightblue1",
                              "green","yellow", "red", "darkred"))

set.seed(9876)    # for reproducibility

## a complete random set
hmdata <- matrix(data = sample(x = 1:10^6, size = 100*100), nrow = 100, ncol = 100)
plot_ly(z = hmdata, colors = palette(50), type = "heatmap")
</code>```

This gives the following heatmap:

```<code>## a random set that has been sorted
hmdata_s <- matrix(data = sort(sample(x = 1:10^6, size = 100*100)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s, colors = palette(50), type = "heatmap")
</code>```

Yielding this plot:

Please let me know whether this is what you want.

UPDATE

you can set custom scale in plot_ly with zauto, zmax, and zmin. The following 2 pieces of code and graphs will illustrate this:

The scale is set from 1 to 100 and the data vary similarly:

```<code>hmdata_s3 <- matrix(data = sort(sample(x = 1:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s3, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)
</code>```

The scale is set from 1 to 100 and the data vary between 50 and 100 only

```<code>hmdata_s4 <- matrix(data = sort(sample(x = 50:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s4, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)
</code>```

Body:
I would like to get a custom color scale which looks like for plotly heatmap (plot_ly(z = data, colors = customcolors, type = "heatmap"))

palette <- colorRampPalette(c("darkblue", "blue", "lightblue1",
                          "green","yellow", "red", "darkred"))
plot(rep(1,50),col=palette(50), pch=19, cex=3, xlab = "", ylab ="", axes = F)

and where the blue end represents 1 and red end represents 10^6 and plotted data would have varying values on this interval.

Body:
The code you use to generate a color palette works just fine. You only need to provide data that match with a heatmap. The following code provides this:

library(RColorBrewer)
library(plotly)

# your palette definition
palette <- colorRampPalette(c("darkblue", "blue", "lightblue1",
                              "green","yellow", "red", "darkred"))

set.seed(9876)    # for reproducibility

## a complete random set
hmdata <- matrix(data = sample(x = 1:10^6, size = 100*100), nrow = 100, ncol = 100)
plot_ly(z = hmdata, colors = palette(50), type = "heatmap")

This gives the following heatmap:

## a random set that has been sorted
hmdata_s <- matrix(data = sort(sample(x = 1:10^6, size = 100*100)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s, colors = palette(50), type = "heatmap")

Yielding this plot:

Please let me know whether this is what you want.

UPDATE

you can set custom scale in plot_ly with zauto, zmax, and zmin. The following 2 pieces of code and graphs will illustrate this:

The scale is set from 1 to 100 and the data vary similarly:

hmdata_s3 <- matrix(data = sort(sample(x = 1:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s3, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)

The scale is set from 1 to 100 and the data vary between 50 and 100 only

hmdata_s4 <- matrix(data = sort(sample(x = 50:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s4, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)


问:
Separate numeric inside string variable using patindex
I have here a short problem.

i have a value like this

1/11
11/1
11/11
111/1
111/11

i'm trying to separate those value and put them into numeric variable.
let say for example i have numericvar1 and numericvar2

so in the 1st string numericvar1 will contain 1 and numericvar2 will contain 11

and so on.

i've tried it like this

```<code>SET @numericvar1= LEFT(@StrNumHolder, PATINDEX('%[0-9][^0-9]%', @StrNumHolder ))
SET @numericvar2= REPLACE(RIGHT(@StrNumHolder, PATINDEX('%[0-9][^0-9]%', @StrNumHolder )),'/','')
</code>```

in this code if the first number before / is in 2 digit i got the correct output. But if the first number is in 1 digit and the next number is in 2 digit like 1/11 i got the wrong output. something like this var1 = 1 and var2 = 1

did something wrong in my code? or it is not possible? please help me.

答:
You can use CHARINDEX to get the position of '/' then use SUBSTRING to separate the numbers. Here how you can query it:</p>

```<code>DECLARE @nIndex INT
SELECT @nIndex = CHARINDEX('/',@StrNumHolder)

SET @numericvar1 = SELECT SUBSTRING(@StrNumHolder,1,@nIndex-1)
SET @numericvar2 = SELECT SUBSTRING(@StrNumHolder,@nIndex+1,LEN(@StrNumHolder))
</code>```

Body:
I have here a short problem.

i have a value like this

1/11
11/1
11/11
111/1
111/11

i'm trying to separate those value and put them into numeric variable.
let say for example i have numericvar1 and numericvar2

so in the 1st string numericvar1 will contain 1 and numericvar2 will contain 11

and so on.

i've tried it like this

SET @numericvar1= LEFT(@StrNumHolder, PATINDEX('%[0-9][^0-9]%', @StrNumHolder ))
SET @numericvar2= REPLACE(RIGHT(@StrNumHolder, PATINDEX('%[0-9][^0-9]%', @StrNumHolder )),'/','')

in this code if the first number before / is in 2 digit i got the correct output. But if the first number is in 1 digit and the next number is in 2 digit like 1/11 i got the wrong output. something like this var1 = 1 and var2 = 1

did something wrong in my code? or it is not possible? please help me.

Body:
You can use CHARINDEX to get the position of '/' then use SUBSTRING to separate the numbers. Here how you can query it:

DECLARE @nIndex INT
SELECT @nIndex = CHARINDEX('/',@StrNumHolder)

SET @numericvar1 = SELECT SUBSTRING(@StrNumHolder,1,@nIndex-1)
SET @numericvar2 = SELECT SUBSTRING(@StrNumHolder,@nIndex+1,LEN(@StrNumHolder))


问:
javascript merge array of objects, resulting object values in array
Would like to merge an array of objects resulting in an object of unique keys and array of values (duplication of values is ok). Solutions in vanilla JS or lodash preferred.

eg - from this:

```<code>[{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}]
</code>```

to this:

```<code>{
  a: [1, 1],
  b: [2],
  c: [3]
}
</code>```

答:
A quick search here in stack reveals that @elclanrs already wrote code for that here However based on the comments, it needs a little tweaking to accept an array of objects, so I added a bit of change to the original code itself.

so basically it boils to the function call:

```<code>var merge = function() {
  return [].reduce.call(arguments, function(acc, x) {
  for(i=0;i<x.length;i++){
    Object.keys(x[i]).forEach(function(k) {
      acc[k] = (acc[k]||[]).concat([x[i][k]])
    });
    }
    return acc
  },{})
}
}
</code>```

Here's a snippet using the function call (with a bit of small change I put) in that post:

var x = [{a: 1, b: 2}, {a: 1,c: 3}]

var merge = function() {
  return [].reduce.call(arguments, function(acc, x) {
  for(i=0;i<x.length;i++){
    Object.keys(x[i]).forEach(function(k) {
      acc[k] = (acc[k]||[]).concat([x[i][k]])
    });
    }
    return acc
  },{})
}

y = merge(x);

alert(JSON.stringify(y));```

Body:
Would like to merge an array of objects resulting in an object of unique keys and array of values (duplication of values is ok). Solutions in vanilla JS or lodash preferred.

eg - from this:

[{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}]

to this:

{
  a: [1, 1],
  b: [2],
  c: [3]
}

Body:
A quick search here in stack reveals that @elclanrs already wrote code for that here However based on the comments, it needs a little tweaking to accept an array of objects, so I added a bit of change to the original code itself.

so basically it boils to the function call:

var merge = function() {
  return [].reduce.call(arguments, function(acc, x) {
  for(i=0;i<x.length;i++){
    Object.keys(x[i]).forEach(function(k) {
      acc[k] = (acc[k]||[]).concat([x[i][k]])
    });
    }
    return acc
  },{})
}
}

Here's a snippet using the function call (with a bit of small change I put) in that post:

var x = [{a: 1, b: 2}, {a: 1,c: 3}]

var merge = function() {
  return [].reduce.call(arguments, function(acc, x) {
  for(i=0;i<x.length;i++){
    Object.keys(x[i]).forEach(function(k) {
      acc[k] = (acc[k]||[]).concat([x[i][k]])
    });
    }
    return acc
  },{})
}

y = merge(x);

alert(JSON.stringify(y));


问:
angular 4, unable to hide element using ng-if
I'm using angular 4, I write below code

```<code><div ng-if="false">
     <a ng-if="false" routerLink="/login"routerLinkActive="active">Login</a>
</div>
</code>```

but unable to hide div, I even tried ng-show, still no help

答:
```<code><div *ngIf="false">
     <a *ngIf="false" routerLink="/login"routerLinkActive="active">Login</a>
</div>
</code>```

u can also use

```<code><div [hidden]="false">
     <a [hidden]="false" routerLink="/login"routerLinkActive="active">Login</a>
</div>
</code>```

Hidden will only apply display:none, ngIf removes the element

Body:
I'm using angular 4, I write below code

     Login

but unable to hide div, I even tried ng-show, still no help

Body:
<div *ngIf="false">
     <a *ngIf="false" routerLink="/login"routerLinkActive="active">Login</a>
</div>

u can also use

<div [hidden]="false">
     <a [hidden]="false" routerLink="/login"routerLinkActive="active">Login</a>
</div>

Hidden will only apply display:none, ngIf removes the element


问:
Can any one give me some advice to make my for loop more efficient?
So I have this for loop with 36 if-queries inside. Any advice on making it more efficient?
You can view the complete code  here

Here's a sample of what it looks like:

```<code>$numbers = range(1, 36);
shuffle($numbers);
for ($m =0; $m<37; $m++){
    if ($numbers[$m] == "1"){
        $mirza[$m] = "RUTHIE";
        $mage[$m] = "3";
        $mquote[$m] = "I get to learn a lot of new things here, like sign language!";
        $link[$m] = "http://www.google.com";
    }

    if ($numbers[$m] == "2"){
        $mirza[$m] = "AIDA";
        $mage[$m] = "82";
        $mquote[$m] = "This is like a club and I know and like all the members. It's good therapy.";
        $link[$m] = "/about/";
    }

    if ($numbers[$m] == "3"){
        $mirza[$m] = "AMIRE";
        $mage[$m] = "4";
        $mquote[$m] = "I am learning how to share and make friends.";
        $link[$m] = "/about/";
    }
}
</code>```

答:
My guess it's already as fast as you may ever need.

The only way to make it faster is to look at sites benchmarking PHP and to adjust this or that to easy the most efficent PHP internals.

Since PHP internals may change over time (with PHP updates), unless you regulary benchmark your code I'd say you have not that much to gain, especially with code that simple.

For example you may try to change

```<code>$numbers[$m] == "2"
</code>```

with

```<code>$numbers[$m] === 2
</code>```

or

```<code>$numbers[$m] === "2"
</code>```

But if you don't benchmark your code (ex. putting it in a function and measure the execution time over 10.000 iterations) you're gonna be blind about improvements. PHP internals speed don't always behave as you expect it.

(the same goes with the answer you got about the switch statement. Try it, but benchmark !)

Body:
So I have this for loop with 36 if-queries inside. Any advice on making it more efficient?
You can view the complete code  here

Here's a sample of what it looks like:

$numbers = range(1, 36);
shuffle($numbers);
for ($m =0; $m<37; $m++){
    if ($numbers[$m] == "1"){
        $mirza[$m] = "RUTHIE";
        $mage[$m] = "3";
        $mquote[$m] = "I get to learn a lot of new things here, like sign language!";
        $link[$m] = "http://www.google.com";
    }

    if ($numbers[$m] == "2"){
        $mirza[$m] = "AIDA";
        $mage[$m] = "82";
        $mquote[$m] = "This is like a club and I know and like all the members. It's good therapy.";
        $link[$m] = "/about/";
    }

    if ($numbers[$m] == "3"){
        $mirza[$m] = "AMIRE";
        $mage[$m] = "4";
        $mquote[$m] = "I am learning how to share and make friends.";
        $link[$m] = "/about/";
    }
}

Body:
My guess it's already as fast as you may ever need.

The only way to make it faster is to look at sites benchmarking PHP and to adjust this or that to easy the most efficent PHP internals.

Since PHP internals may change over time (with PHP updates), unless you regulary benchmark your code I'd say you have not that much to gain, especially with code that simple.

For example you may try to change

$numbers[$m] == "2"

with

$numbers[$m] === 2

or

$numbers[$m] === "2"

But if you don't benchmark your code (ex. putting it in a function and measure the execution time over 10.000 iterations) you're gonna be blind about improvements. PHP internals speed don't always behave as you expect it.

(the same goes with the answer you got about the switch statement. Try it, but benchmark !)


问:
how to achieve synchronization of threads using synchronized method in java?
i am unable to achieve synchronization of thread here .i used a synchronized method "meth" her . so according to definition only one thread should enter at a single time and print my desired output . but this is not happening . Need help. Thank you.

```<code>class ABC {

    synchronized public void meth(String msg) {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " Thread Interrupted");
        }
        System.out.println("]");
    }
}

class SyncMethod implements Runnable {

    ABC a = new ABC();
    Thread t;

    SyncMethod(String s) {
        t = new Thread(this, s);
        t.start();
    }

    public void run() {
        a.meth(t.getName());
    }

    public static void main(String args[]) {
        new SyncMethod("Hello");
        new SyncMethod("Synchronized");
        new SyncMethod("World");
    }
}
</code>```

Current Output :

```<code>        [Hello [Synchronized [World] ] ] ]
</code>```

Desired Output :

```<code>        [Hello]
        [Synchronized]
        [World]
</code>```

答:
Look here you are creating new instance of ABC each time you calling the constructor of SyncMethod so you have 3 copies of the class each called by different thread so they don't compete for the monitor so what you need is to use the same ABC object for all 3 calls here is the solution

```<code>class SyncMethod implements Runnable {
Thread t;
ABC a;

SyncMethod(String s, ABC a) {
    this.a = a;
    t = new Thread(this, s);
    t.start();

}

public void run() {
    a.meth(t.getName());
}

public static void main(String args[]) {
    ABC a = new ABC();
    new SyncMethod("Hello", a);
    new SyncMethod("Synchronized", a);
    new SyncMethod("World", a);
}
</code>```

}

Body:
i am unable to achieve synchronization of thread here .i used a synchronized method "meth" her . so according to definition only one thread should enter at a single time and print my desired output . but this is not happening . Need help. Thank you.

class ABC {

    synchronized public void meth(String msg) {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " Thread Interrupted");
        }
        System.out.println("]");
    }
}

class SyncMethod implements Runnable {

    ABC a = new ABC();
    Thread t;

    SyncMethod(String s) {
        t = new Thread(this, s);
        t.start();
    }

    public void run() {
        a.meth(t.getName());
    }

    public static void main(String args[]) {
        new SyncMethod("Hello");
        new SyncMethod("Synchronized");
        new SyncMethod("World");
    }
}

Current Output :

        [Hello [Synchronized [World] ] ] ]

Desired Output :

        [Hello]
        [Synchronized]
        [World]

Body:
Look here you are creating new instance of ABC each time you calling the constructor of SyncMethod so you have 3 copies of the class each called by different thread so they don't compete for the monitor so what you need is to use the same ABC object for all 3 calls here is the solution

class SyncMethod implements Runnable {
Thread t;
ABC a;

SyncMethod(String s, ABC a) {
    this.a = a;
    t = new Thread(this, s);
    t.start();

}

public void run() {
    a.meth(t.getName());
}

public static void main(String args[]) {
    ABC a = new ABC();
    new SyncMethod("Hello", a);
    new SyncMethod("Synchronized", a);
    new SyncMethod("World", a);
}

}


问:
ansible ini_file task fails and closes connection
I am trying to install telegraf and change configuration of its main config file /etc/telegraf/telegraf.conf.

The installation is succesful but the task fails on changing config file. Here is the tasks/main/yml file

```<code>---

- name: install telegraf
  apt: pkg=telegraf state=installed
  become: true

- name: changing conf file
  ini_file:
    path: /etc/telegraf/telegraf.conf
    section: outputs.influxdb
    option: database
    value: ['http://localhost:8086']
</code>```

But the task fails,

```<code>fatal: [192.168.122.62]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to 192.168.122.62 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_CQ_3uv/ansible_module_ini_file.py\", line 319, in <module>\r\n    main()\r\n  File \"/tmp/ansible_CQ_3uv/ansible_module_ini_file.py\", line 305, in main\r\n    (changed,backup_file,diff,msg) = do_ini(module, path, section, option, value, state, backup, no_extra_spaces, create)\r\n  File \"/tmp/ansible_CQ_3uv/ansible_module_ini_file.py\", line 268, in do_ini\r\n    ini_file = open(filename, 'w')\r\nIOError: [Errno 13] Permission denied: '/etc/telegraf/telegraf.conf'\r\n", "msg": "MODULE FAILURE", "rc": 0}
</code>```

It is a permission denied error, so I tried adding become: true in the task, but then it says that become is not a supported parameter in ini_file.

This is the section of the /etc/telegraf/telegraf.conf file which I want to change.

```<code>[[outputs.influxdb]]
  urls = ["http://192.168.1.9:8086"] # I want http://localhost:8086
  database = "server-telegraf"
</code>```

I am not getting how to solve this. Help needed !

答:
I bet you misplaced become as module's parameter, not task's.

It should be on the same indentation level as action name:

```<code>- name: changing conf file
  ini_file:
    path: /etc/telegraf/telegraf.conf
    section: outputs.influxdb
    option: database
    value: ['http://localhost:8086']
  become: yes
</code>```

Body:
I am trying to install telegraf and change configuration of its main config file /etc/telegraf/telegraf.conf.

The installation is succesful but the task fails on changing config file. Here is the tasks/main/yml file

---

- name: install telegraf
  apt: pkg=telegraf state=installed
  become: true

- name: changing conf file
  ini_file:
    path: /etc/telegraf/telegraf.conf
    section: outputs.influxdb
    option: database
    value: ['http://localhost:8086']

But the task fails,

fatal: [192.168.122.62]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to 192.168.122.62 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_CQ_3uv/ansible_module_ini_file.py\", line 319, in <module>\r\n    main()\r\n  File \"/tmp/ansible_CQ_3uv/ansible_module_ini_file.py\", line 305, in main\r\n    (changed,backup_file,diff,msg) = do_ini(module, path, section, option, value, state, backup, no_extra_spaces, create)\r\n  File \"/tmp/ansible_CQ_3uv/ansible_module_ini_file.py\", line 268, in do_ini\r\n    ini_file = open(filename, 'w')\r\nIOError: [Errno 13] Permission denied: '/etc/telegraf/telegraf.conf'\r\n", "msg": "MODULE FAILURE", "rc": 0}

It is a permission denied error, so I tried adding become: true in the task, but then it says that become is not a supported parameter in ini_file.

This is the section of the /etc/telegraf/telegraf.conf file which I want to change.

[[outputs.influxdb]]
  urls = ["http://192.168.1.9:8086"] # I want http://localhost:8086
  database = "server-telegraf"

I am not getting how to solve this. Help needed !

Body:
I bet you misplaced become as module's parameter, not task's.

It should be on the same indentation level as action name:

- name: changing conf file
  ini_file:
    path: /etc/telegraf/telegraf.conf
    section: outputs.influxdb
    option: database
    value: ['http://localhost:8086']
  become: yes


问:
Initializing strongly typed objects in LINQ to Entities
I have a plain old CLR object which is essentially a wrapper for two entity framework objects, I'm doing this so I can pass this wrapper object to a strongly typed view in the MVC framework. My foo wrapper class is very simple:

```<code>public class FooWrapper
{
    public FooWrapper(Foo f, Bar b)
    {
        this.FooObject = f;
        this.BarObject = b;
    }

    public Foo FooObject { get; private set; }
    public Bar BarObject { get; private set; }
}
</code>```

What I have so far for my ListFoosWithBars function is as follows:

```<code>public IEnumerable<FooWrapper> ListFoosWithBars(int userID)
{
    IEnumerable<Bar> tempBar = ListBarsByUserID(userID);
    IEnumerable<FooWrapper> results = (from f in _entities.FooSet
                                       join b in tempBar on f.ID equals b.foos.ID
                                       select new FooWrapper(f, b));
    return results;
}
</code>```

This doesn't work because evidently LINQ to Entities doesn't support parametrized initialization, an exception is thrown that says just that: "Only parameterless constructors and initializers are supported in LINQ to Entities." I was wondering if there is another way to achieve this same result?

答: I found this useful what possible workarounds are there for "only parameterless constructors are support in Linq to Entites"</p>

Body:
I have a plain old CLR object which is essentially a wrapper for two entity framework objects, I'm doing this so I can pass this wrapper object to a strongly typed view in the MVC framework. My foo wrapper class is very simple:

public class FooWrapper
{
    public FooWrapper(Foo f, Bar b)
    {
        this.FooObject = f;
        this.BarObject = b;
    }

    public Foo FooObject { get; private set; }
    public Bar BarObject { get; private set; }
}

What I have so far for my ListFoosWithBars function is as follows:

public IEnumerable<FooWrapper> ListFoosWithBars(int userID)
{
    IEnumerable<Bar> tempBar = ListBarsByUserID(userID);
    IEnumerable<FooWrapper> results = (from f in _entities.FooSet
                                       join b in tempBar on f.ID equals b.foos.ID
                                       select new FooWrapper(f, b));
    return results;
}

This doesn't work because evidently LINQ to Entities doesn't support parametrized initialization, an exception is thrown that says just that: "Only parameterless constructors and initializers are supported in LINQ to Entities." I was wondering if there is another way to achieve this same result?


问:
java.lang.ClassCastException while creating a dataframe with schema
I have some incoming data as rowValues, I will have to apply a particular schema and create a data frame , here is my code:

val rowValues = List("12","F","1980-10-11,1980-10-11T10:10:20")
val rdd = sqlContext.sparkContext.parallelize(Seq(rowValues))
val rowRdd = rdd.map(v => Row(v: _*))

var fieldSchema = ListBuffer[StructField]()

fieldSchema += StructField("C0", IntegerType, true, null)
fieldSchema += StructField("C1", StringType, true, null)
fieldSchema += StructField("C2", TimestampType, true, null)
val schema = StructType(fieldSchema.toList)

val newRow = sqlContext.createDataFrame(rowRdd, schema)
newRow.printSchema()   // new schema prints here
newRow.show()   // This fails with ClassCast exception
```

This fails with org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 16.0 failed 1 times, most recent failure: Lost task 0.0 in stage 16.0 (TID 16, localhost): java.lang.ClassCastException: java.lang.String cannot be cast to java.sql.Timestamp

How do I apply this schema?

答:
your input data are all strings but your schema for c0 is integer, c1 is string and c2 is timestamp, thus you are getting casting errors. Your string timestamp looks even more complicated.

If you are just looking for getting a dataframe you should change all columns datatypes to string and it will work

```<code>fieldSchema += StructField("C0", StringType, true, null)
fieldSchema += StructField("C1", StringType, true, null)
fieldSchema += StructField("C2", StringType, true, null)
</code>```

you should have

```<code>+---+---+------------------------------+
|C0 |C1 |C2                            |
+---+---+------------------------------+
|12 |F  |1980-10-11,1980-10-11T10:10:20|
+---+---+------------------------------+
</code>```

If you insist on staying with your schema, following code should give better ideas

```<code>val rowValues = List("12","F","1980-10-11,1980-10-11T10:10:20")
val rdd = sqlContext.sparkContext.parallelize(Seq(rowValues))

val rowRdd = rdd.map(v => Row(v(0).toInt, v(1), v(2).split(",")(1).replace("T", " ")))

var fieldSchema = ListBuffer[StructField]()

fieldSchema += StructField("C0", IntegerType, true)
fieldSchema += StructField("C1", StringType, true)
fieldSchema += StructField("C2", StringType, true)
val schema = StructType(fieldSchema.toList)

val newRow = sqlContext.createDataFrame(rowRdd, schema).withColumn("C2", unix_timestamp(col("C2")))
newRow.printSchema()   // new schema prints here
newRow.show(false)
</code>```

You can also do it with case class as

```<code>import sqlContext.implicits._

def convertToDate(dateTime: String): Timestamp = {
  val formatter = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss")
  val utilDate = formatter.parse(dateTime)
  new Timestamp(utilDate.getTime)
}
val rowValues = List("12","F","1980-10-11 10:10:20")
val rdd = sqlContext.sparkContext.parallelize(Seq(rowValues))

val rowRdd = rdd.map(v => Pratap(v(0).toInt, v(1), convertToDate(v(2))))

val newRow = rowRdd.toDF
newRow.printSchema()
newRow.show(false)
</code>```

And your case class should be outside the main class as

```<code>case class Pratap(C0: Int, C1: String, C2: java.sql.Timestamp)
</code>```

Body:
I have some incoming data as rowValues, I will have to apply a particular schema and create a data frame , here is my code:

val rowValues = List("12","F","1980-10-11,1980-10-11T10:10:20")
val rdd = sqlContext.sparkContext.parallelize(Seq(rowValues))
val rowRdd = rdd.map(v => Row(v: _*))

var fieldSchema = ListBuffer[StructField]()

fieldSchema += StructField("C0", IntegerType, true, null)
fieldSchema += StructField("C1", StringType, true, null)
fieldSchema += StructField("C2", TimestampType, true, null)
val schema = StructType(fieldSchema.toList)

val newRow = sqlContext.createDataFrame(rowRdd, schema)
newRow.printSchema()   // new schema prints here
newRow.show()   // This fails with ClassCast exception

This fails with org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 16.0 failed 1 times, most recent failure: Lost task 0.0 in stage 16.0 (TID 16, localhost): java.lang.ClassCastException: java.lang.String cannot be cast to java.sql.Timestamp

How do I apply this schema?

Body:
your input data are all strings but your schema for c0 is integer, c1 is string and c2 is timestamp, thus you are getting casting errors. Your string timestamp looks even more complicated.

If you are just looking for getting a dataframe you should change all columns datatypes to string and it will work

fieldSchema += StructField("C0", StringType, true, null)
fieldSchema += StructField("C1", StringType, true, null)
fieldSchema += StructField("C2", StringType, true, null)

you should have

+---+---+------------------------------+
|C0 |C1 |C2                            |
+---+---+------------------------------+
|12 |F  |1980-10-11,1980-10-11T10:10:20|
+---+---+------------------------------+

If you insist on staying with your schema, following code should give better ideas

val rowValues = List("12","F","1980-10-11,1980-10-11T10:10:20")
val rdd = sqlContext.sparkContext.parallelize(Seq(rowValues))

val rowRdd = rdd.map(v => Row(v(0).toInt, v(1), v(2).split(",")(1).replace("T", " ")))

var fieldSchema = ListBuffer[StructField]()

fieldSchema += StructField("C0", IntegerType, true)
fieldSchema += StructField("C1", StringType, true)
fieldSchema += StructField("C2", StringType, true)
val schema = StructType(fieldSchema.toList)

val newRow = sqlContext.createDataFrame(rowRdd, schema).withColumn("C2", unix_timestamp(col("C2")))
newRow.printSchema()   // new schema prints here
newRow.show(false)

You can also do it with case class as

import sqlContext.implicits._

def convertToDate(dateTime: String): Timestamp = {
  val formatter = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss")
  val utilDate = formatter.parse(dateTime)
  new Timestamp(utilDate.getTime)
}
val rowValues = List("12","F","1980-10-11 10:10:20")
val rdd = sqlContext.sparkContext.parallelize(Seq(rowValues))

val rowRdd = rdd.map(v => Pratap(v(0).toInt, v(1), convertToDate(v(2))))

val newRow = rowRdd.toDF
newRow.printSchema()
newRow.show(false)

And your case class should be outside the main class as

case class Pratap(C0: Int, C1: String, C2: java.sql.Timestamp)


问:
Can't display the proper value
I have these classes:

```<code>interface Shape
{
    public double getPerimeter();
    public double getArea();
    public void getDetails();
}
</code>```

and

```<code>class Circle implements Shape
{
    private double PI = 3.14;
    private int radius;
    double perimeter, area;

    //constructor
    public Circle(int radius)
    {
        perimeter = 2.0 * (PI * radius);
        area = PI * (radius * radius);
    }

    public int getRadius()
    {
        return radius;
    }

    public double getPerimeter()
    {
        return perimeter;
    }

    public double getArea()
    {
        return area;
    }

    public void getDetails()
    {
        System.out.println("Shape Type: Circle " + "\n"
                         + "Radius: " + getRadius() + "\n"
                         + "Perimeter: " + getPerimeter() + "\n"
                         + "Area: "  + getArea() + "\n"         );
    }
}
</code>```

and finally

```<code>public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.print("wrong");
            }

            catch(IllegalArgumentException iae)
            {
                System.err.print("wrong");
            }

            if(args.length==1)
            {
                i = Integer.parseInt(args[0]);
                Circle r1 = new Circle(i);
                r1.getDetails();
            }
        }

    }

}
</code>```

We were assigned to input 1,2 or 3 numbers on the command line of the terminal and the output would display what kind of shape it is depending on the array size. I managed to get the proper parameter and area when I input a number but the radius keeps displaying 0 instead of the actual number I inputted.

This is what the output looks like

So what do you guys think?

答:
Instance variable are assigned values by default if not initialized. In case of int it's 0 by default. So to assign the value to your instance variable radius you need to add this line in your constructor.

this.radius = radius

We are using this because your instance variable and local variable are having the same name.

Title: Can't display the proper value

Body:
I have these classes:

interface Shape
{
    public double getPerimeter();
    public double getArea();
    public void getDetails();
}

and

class Circle implements Shape
{
    private double PI = 3.14;
    private int radius;
    double perimeter, area;

    //constructor
    public Circle(int radius)
    {
        perimeter = 2.0 * (PI * radius);
        area = PI * (radius * radius);
    }

    public int getRadius()
    {
        return radius;
    }

    public double getPerimeter()
    {
        return perimeter;
    }

    public double getArea()
    {
        return area;
    }

    public void getDetails()
    {
        System.out.println("Shape Type: Circle " + "\n"
                         + "Radius: " + getRadius() + "\n"
                         + "Perimeter: " + getPerimeter() + "\n"
                         + "Area: "  + getArea() + "\n"         );
    }
}

and finally

public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.print("wrong");
            }

            catch(IllegalArgumentException iae)
            {
                System.err.print("wrong");
            }

            if(args.length==1)
            {
                i = Integer.parseInt(args[0]);
                Circle r1 = new Circle(i);
                r1.getDetails();
            }
        }

    }

}

We were assigned to input 1,2 or 3 numbers on the command line of the terminal and the output would display what kind of shape it is depending on the array size. I managed to get the proper parameter and area when I input a number but the radius keeps displaying 0 instead of the actual number I inputted.

This is what the output looks like

So what do you guys think?


问:
Password confirmation isn't working
For the life of me, I can't figure out what I've done wrong. I want a message to pop up when someone tries entering passwords that don't match below is the form code.

function passcheck() {
  var p1 = _("pass1").value;
  var p2 = _("pass2").value;
  if (p1 != p2) {
    status.innerHTML = "Your passwords don't match";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="signupform" id="signupform" onSubmit="return false;"><div id="password">Create Password:</div>
  <input id="pass1" type="password" maxlength="88" placeholder="●●●●●●●●●">
  <div id="confirm">Confirm Password:</div>
  <input id="pass2" type="password" onBlur="passcheck()" maxlength="88" placeholder="●●●●●●●●●"></code>```

What am I missing?

答:
$("#pass2").change(function() {

  var p1 = $("#pass1").val();
  var p2 = $("#pass2").val();

  if (p1 ===  p2) {

  }
  else{
    document.getElementById("passwordMatch").innerHTML = "Your passwords don't match";

}
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#passwordMatch{color:red;}</code>```

<input id="pass1" type="password"  maxlength="88" placeholder="●●●●●●●●●">

Confirm Password:

        <input id="pass2" type="password" maxlength="88" placeholder="●●●●●●●●●">

```

First of all , create a div separately to show the error msg.You have used "status" which is not used any where.

Title: Password confirmation isn't working

Body:
For the life of me, I can't figure out what I've done wrong. I want a message to pop up when someone tries entering passwords that don't match below is the form code.

function passcheck() {
  var p1 = _("pass1").value;
  var p2 = _("pass2").value;
  if (p1 != p2) {
    status.innerHTML = "Your passwords don't match";
  }
}

<form name="signupform" id="signupform" onSubmit="return false;">
Create Password:

  <input id="pass1" type="password" maxlength="88" placeholder="●●●●●●●●●">

Confirm Password:

  <input id="pass2" type="password" onBlur="passcheck()" maxlength="88" placeholder="●●●●●●●●●">

What am I missing?

Body:
$("#pass2").change(function() {

  var p1 = $("#pass1").val();
  var p2 = $("#pass2").val();

  if (p1 ===  p2) {

  }
  else{
    document.getElementById("passwordMatch").innerHTML = "Your passwords don't match";

}
});

#passwordMatch{color:red;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="pass1" type="password"  maxlength="88" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;">
        <div id="confirm">Confirm Password:</div>
        <input id="pass2" type="password" maxlength="88" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;">

        <div id="passwordMatch"></div>

First of all , create a div separately to show the error msg.You have used "status" which is not used any where.


问:
How to set back button text in iOS navigation controller?
How do you remove the back button text.

Current back button:

< Back

Desired back button:

< AnythingElse

None of these have worked:

```<code>self.navigationItem.backBarButtonItem?.title = "Back"
self.backItem?.title = ""
self.navigationController?.navigationBar.backItem?.title = ""
self.navigationItem.backBarButtonItem?.title = ""
self.navigationController?.navigationItem.backBarButtonItem?.title="Back"
self.navigationController?.navigationBar.backItem?.title = ""
self.navigationController?.navigationItem.backBarButtonItem?.title
</code>```

答:
If you are using xib file for view controller then do this in your view controller class.

```<code>class AboutUsViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    edgesForExtendedLayout = []
    setUpNavBar()
}

func setUpNavBar(){
    //For title in navigation bar
    self.navigationController?.view.backgroundColor = UIColor.white
    self.navigationController?.view.tintColor = UIColor.orange
    self.navigationItem.title = "About Us"

    //For back button in navigation bar
    let backButton = UIBarButtonItem()
    backButton.title = "Back"
    self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
}

}
</code>```

The result will be:

Body:
How do you remove the back button text.

Current back button:

< Back

Desired back button:

< AnythingElse

None of these have worked:

self.navigationItem.backBarButtonItem?.title = "Back"
self.backItem?.title = ""
self.navigationController?.navigationBar.backItem?.title = ""
self.navigationItem.backBarButtonItem?.title = ""
self.navigationController?.navigationItem.backBarButtonItem?.title="Back"
self.navigationController?.navigationBar.backItem?.title = ""
self.navigationController?.navigationItem.backBarButtonItem?.title

Body:
If you are using xib file for view controller then do this in your view controller class.

class AboutUsViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    edgesForExtendedLayout = []
    setUpNavBar()
}

func setUpNavBar(){
    //For title in navigation bar
    self.navigationController?.view.backgroundColor = UIColor.white
    self.navigationController?.view.tintColor = UIColor.orange
    self.navigationItem.title = "About Us"

    //For back button in navigation bar
    let backButton = UIBarButtonItem()
    backButton.title = "Back"
    self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
}

}

The result will be:


问:
Flashing nav when hitting the top
I was wondering how I can make the nav-bar flash while hitting the top.

I'm using bootstrap navbar and a jquery script to make it stick to the top while scrolling down but I can't make it flash without jquery looping their 'fadein/out' feature.

Any other options I can use?

```<code>$(function(){

    var advancedNav = $('#custom-bootstrap-menu').offset().top;

    $(window).scroll(function(){
        if( $(window).scrollTop() > advancedNav ) {
                $('#custom-bootstrap-menu').css({position: 'fixed', top: '0px'});
                $('#custom-bootstrap-menu').css('display', 'block');
                $('#custom-bootstrap-menu').css('width', "100%");
        } else {
                $('#custom-bootstrap-menu').css({position: 'static', top: '0px'});
                $('#custom-bootstrap-menu').css('display', 'block');
        }
    });
</code>```

答:
Try this one,</p>

```<code>$(function(){

$(window).scroll(function(){
    if( $(window).scrollTop() == 0) {
            $('#custom-bootstrap-menu').css({position: 'fixed', top: '0px'});
            $('#custom-bootstrap-menu').css('display', 'block');
            $('#custom-bootstrap-menu').css('width', "100%");
    } else {
            $('#custom-bootstrap-menu').css({position: 'static', top: '0px'});
            $('#custom-bootstrap-menu').css('display', 'block');
    }
});
</code>```

Title: Flashing nav when hitting the top

Body:
I was wondering how I can make the nav-bar flash while hitting the top.

I'm using bootstrap navbar and a jquery script to make it stick to the top while scrolling down but I can't make it flash without jquery looping their 'fadein/out' feature.

Any other options I can use?

$(function(){

    var advancedNav = $('#custom-bootstrap-menu').offset().top;

    $(window).scroll(function(){
        if( $(window).scrollTop() > advancedNav ) {
                $('#custom-bootstrap-menu').css({position: 'fixed', top: '0px'});
                $('#custom-bootstrap-menu').css('display', 'block');
                $('#custom-bootstrap-menu').css('width', "100%");
        } else {
                $('#custom-bootstrap-menu').css({position: 'static', top: '0px'});
                $('#custom-bootstrap-menu').css('display', 'block');
        }
    });

Body:
Try this one,

$(function(){

$(window).scroll(function(){
    if( $(window).scrollTop() == 0) {
            $('#custom-bootstrap-menu').css({position: 'fixed', top: '0px'});
            $('#custom-bootstrap-menu').css('display', 'block');
            $('#custom-bootstrap-menu').css('width', "100%");
    } else {
            $('#custom-bootstrap-menu').css({position: 'static', top: '0px'});
            $('#custom-bootstrap-menu').css('display', 'block');
    }
});


问:
Make .toggleClass() to affect only one element with the same class on click in jQuery
I am trying to make dropdown menu with jQuery. Problem that my script effects all elements with the same class on click. Below is my problem in the snippet:

$(document).ready(function() {
  $('.parent').click(function() {
    $('.sub-nav').toggleClass('visible');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}</code>```

Home

One

Two

Three

About

Johnny

Julie

Jamie

Contact

```
</div>
</div>
</p>

<p>I was trying to play around with :</p>

```$(document)
    .ready(function () {
    $('.parent')
        .click(function () {
        $(this).children('.sub-nav').toggleClass('visible');
    });
});
```

but without any decent results. Could someone tell where I am missing the point? Many thanks for all possible help, looking forward.

答:
Try this:

$(document).ready(function() {
  $('.parent').click(function() {
    $(this).children('.sub-nav').toggleClass('visible');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}</code>```

Home

One

Two

Three

About

Johnny

Julie

Jamie

Contact

```

Body:
I am trying to make dropdown menu with jQuery. Problem that my script effects all elements with the same class on click. Below is my problem in the snippet:

$(document).ready(function() {
  $('.parent').click(function() {
    $('.sub-nav').toggleClass('visible');
  });
});

#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}

Home

One

Two

Three

About

Johnny

Julie

Jamie

Contact

I was trying to play around with :

$(document)
    .ready(function () {
    $('.parent')
        .click(function () {
        $(this).children('.sub-nav').toggleClass('visible');
    });
});

but without any decent results. Could someone tell where I am missing the point? Many thanks for all possible help, looking forward.

Body:
Try this:

$(document).ready(function() {
  $('.parent').click(function() {
    $(this).children('.sub-nav').toggleClass('visible');
  });
});

#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="nav">
  <li class="parent">Home
    <ul class="sub-nav">
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
    </ul>
  </li>
  <li class="parent">About
    <ul class="sub-nav">
      <li>Johnny</li>
      <li>Julie</li>
      <li>Jamie</li>
    </ul>
  </li>
  <li>Contact</li>
</ul>


答: My advice is to try to work with data structures, and put all these values in an array of the same type as the data structure. That way, if you later need to access the values again with the same number-to-value relationship, you won't have to redefine everything like you have done here. All you would have to do then is to use array indices to access the values.</p>

Title: Can any one give me some advice to make my for loop more efficient?

Body:
So I have this for loop with 36 if-queries inside. Any advice on making it more efficient?
You can view the complete code  here

Here's a sample of what it looks like:

$numbers = range(1, 36);
shuffle($numbers);
for ($m =0; $m<37; $m++){
    if ($numbers[$m] == "1"){
        $mirza[$m] = "RUTHIE";
        $mage[$m] = "3";
        $mquote[$m] = "I get to learn a lot of new things here, like sign language!";
        $link[$m] = "http://www.google.com";
    }

    if ($numbers[$m] == "2"){
        $mirza[$m] = "AIDA";
        $mage[$m] = "82";
        $mquote[$m] = "This is like a club and I know and like all the members. It's good therapy.";
        $link[$m] = "/about/";
    }

    if ($numbers[$m] == "3"){
        $mirza[$m] = "AMIRE";
        $mage[$m] = "4";
        $mquote[$m] = "I am learning how to share and make friends.";
        $link[$m] = "/about/";
    }
}


问:
Unable to plot graph on matplotlib
I am new to Python and I am having some problems with plotting graphs on matplotlib which I hope you all can assist me.

So I have a DataFrame that shows the temperature in a given year.

```<code>    01-01    334
    01-02    320
    01-03    330
    01-04    331
    01-05    328
          .
          .
          .
    12-27    318
    12-28    320
    12-29    320
    12-30    325
    12-31    334
</code>```

and when I try to plot it by using the following codes:

```<code> dates = pd.date_range('1/1/2015','31/12/2015', freq = 'D')
 yvals = list(df.values)
 plt.figure()
 plt.plot(dates,'-', yvals, '-')
</code>```

It just returns a white figure with no points or lines on it.

How do I go about resolving this?? Thank you so much!

答:
The syntax is plt.plot(x, y, style)

Try

```<code>plt.plot(dates, yvals, '-')
</code>```

Title: Unable to plot graph on matplotlib

Body:
I am new to Python and I am having some problems with plotting graphs on matplotlib which I hope you all can assist me.

So I have a DataFrame that shows the temperature in a given year.

    01-01    334
    01-02    320
    01-03    330
    01-04    331
    01-05    328
          .
          .
          .
    12-27    318
    12-28    320
    12-29    320
    12-30    325
    12-31    334

and when I try to plot it by using the following codes:

 dates = pd.date_range('1/1/2015','31/12/2015', freq = 'D')
 yvals = list(df.values)
 plt.figure()
 plt.plot(dates,'-', yvals, '-')

It just returns a white figure with no points or lines on it.

How do I go about resolving this?? Thank you so much!

Body:
The syntax is plt.plot(x, y, style)

Try

plt.plot(dates, yvals, '-')


问:
Converting Electron app to UWP app
I need some tips on how to convert a Electron app to Universal Windows Platform. I have imported all the JavaScript files into Visual studio 2017 and chosen Universal Windows Platform platform. My main problem is that I have renderers (renderer.js) which does not want to run when I compile the solution in Visual studio. I can build the solution, but when I run it I only get a white window. Any tips on how to solve this?</p>

答: Are you just wanting to submit on the store or want a proper universal app? If it's just the former, take a look at https://github.com/felixrieseberg/electron-windows-store

Title: Converting Electron app to UWP app


问:
Formatting arrays specifically in PHP
I have the following PHP code on my website:

```<code><?php
    $FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
?>
</code>```

And I want it to be output like so:

```<code>("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06)
</code>```

for an SQL string, which will be:

```<code>INSERT INTO Users (FirstName, LastName, BirthDay) VALUES ("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06);
</code>```

I am quite new to PHP (only started yesterday) and was wondering how I would do this.

Thanks.

答:
below code is help you when birthday or lastname is not in array</p>

```<code>    $data = [];
    $total = count($FirstName);
    for($i = 0;$i < $total;$i++) {
        $tmp = [];
        $tmp[] = (isset($FirstName[$i]))? $FirstName[$i] : "";
        $tmp[] = (isset($LastName[$i]))? $LastName[$i] : "";
        $tmp[] = (isset($BirthDay[$i]))? $BirthDay[$i] : "";
        $data[] = $tmp;
    }

    // $data is array what you want i have just dump the $data

    echo "```";
    var_dump($data);
</code>```

Title: Formatting arrays specifically in PHP

Body:
I have the following PHP code on my website:

<?php
    $FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
?>

And I want it to be output like so:

("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06)

for an SQL string, which will be:

INSERT INTO Users (FirstName, LastName, BirthDay) VALUES ("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06);

I am quite new to PHP (only started yesterday) and was wondering how I would do this.

Thanks.

Body:
below code is help you when birthday or lastname is not in array

    $data = [];
    $total = count($FirstName);
    for($i = 0;$i < $total;$i++) {
        $tmp = [];
        $tmp[] = (isset($FirstName[$i]))? $FirstName[$i] : "";
        $tmp[] = (isset($LastName[$i]))? $LastName[$i] : "";
        $tmp[] = (isset($BirthDay[$i]))? $BirthDay[$i] : "";
        $data[] = $tmp;
    }

    // $data is array what you want i have just dump the $data

    echo "<pre>";
    var_dump($data);


问:
Import Rxjs in angular2?
How to import everything(like operators, observables,......,.....) on a single import from Rxjs in angular2(ts)?

How to use everything of RxJs  by using single import in angular2?

答:
Check the docs for Rxjs.

Just do:

```<code>import Rx from 'rxjs/Rx';
</code>```

You can access individual operators/observables etc using:

```<code> Rx.Observable.<operator>
</code>```

However importing all operators is generally unnecessary and I suggest you import only those operators which you use into a separate ts file and then import the particular file into your other files.

Title: Import Rxjs in angular2?

Body:
Check the docs for Rxjs.

Just do:

import Rx from 'rxjs/Rx';

You can access individual operators/observables etc using:

 Rx.Observable.<operator>

However importing all operators is generally unnecessary and I suggest you import only those operators which you use into a separate ts file and then import the particular file into your other files.


答:
You can use </p>

```<code>import * as Rx from 'rxjs';
</code>```

<p>And use it like </p>

```<code>let obs = Rx.Observable.of(true);
</code>```

Title: Import Rxjs in angular2?

Body:
How to import everything(like operators, observables,......,.....) on a single import from Rxjs in angular2(ts)?

How to use everything of RxJs  by using single import in angular2?

Body:
You can use

import * as Rx from 'rxjs';

And use it like

let obs = Rx.Observable.of(true);


问:
Swifty way to get value associated with another in struct
I have a CustomColors struct which contains static lets that define primary and secondary colors for my app.

```<code>struct CustomColors {

    static let orangePrimary = UIColor(r: 255, g: 110, b: 64, a: 1)
    static let orangeSecondary = UIColor(r: 230, g: 74, b: 25, a: 1)

    static let bluePrimary = UIColor(r: 24, g: 255, b: 255, a: 1)
    static let blueSecondary = UIColor(r: 18, g: 191, b: 191, a: 1)

    static let yellowPrimary = UIColor(r: 255, g: 255, b: 0, a: 1)
    static let yellowSecondary = UIColor(r: 255, g: 193, b: 7, a: 1)
}
</code>```

Because secondary colors are completely dependent from the primary ones, I am looking for a way to build a data structure (in the swiftiest way) that would allow me to call for example: CustomColors.bluePrimary.secondary to get the blueSecondary color.

I feel I am missing something pretty basic here as I cannot seem to see how I could do this in the most simple way.

Thanks in advance for your help !

答:
```<code>extension UIColor {
    open class var orangePrimary: UIColor {
        return UIColor.orange
    }
}
</code>```

you can used UIcolor.orangePrimary

Body:
I have a CustomColors struct which contains static lets that define primary and secondary colors for my app.

struct CustomColors {

    static let orangePrimary = UIColor(r: 255, g: 110, b: 64, a: 1)
    static let orangeSecondary = UIColor(r: 230, g: 74, b: 25, a: 1)

    static let bluePrimary = UIColor(r: 24, g: 255, b: 255, a: 1)
    static let blueSecondary = UIColor(r: 18, g: 191, b: 191, a: 1)

    static let yellowPrimary = UIColor(r: 255, g: 255, b: 0, a: 1)
    static let yellowSecondary = UIColor(r: 255, g: 193, b: 7, a: 1)
}

Because secondary colors are completely dependent from the primary ones, I am looking for a way to build a data structure (in the swiftiest way) that would allow me to call for example: CustomColors.bluePrimary.secondary to get the blueSecondary color.

I feel I am missing something pretty basic here as I cannot seem to see how I could do this in the most simple way.

Thanks in advance for your help !

Body:
extension UIColor {
    open class var orangePrimary: UIColor {
        return UIColor.orange
    }
}

you can used UIcolor.orangePrimary


问:
AVAudioPlayer is turning nil
Something is wrong with my code but I can't figure out what is wrong. If I compile the code everything is fine, but if I run the code I get this error:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) ```
</div>
</div>
</p>

<p>I've seen lots of the same questions but the answer to those questions is not useful in my case.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import UIKit
import AVFoundation
import AudioToolbox

class ViewController: UIViewController{

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath:  Bundle.main.path(forResource: "beep", ofType: "wav")!))
            audioPlayer.prepareToPlay()

        } catch{
            print(error)
        }

        //standaard klaarmaaklijst
        nummerLabel.text = "\(schijnNummer)"
        nummerCheck()
    }

@IBOutlet weak var nummerLabel: UILabel!
}</code>```

I hope someone knows what's wrong with my code.

答:
Swift :

```<code>    if let path = Bundle.main.path(forResource: "beep", ofType:"wav") {
        let url = URL(fileURLWithPath: path)

        do {

            let audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer.prepareToPlay()

        } catch{
            print(error)
        }
    }
</code>```

Note: Please check if the url is proper and not nil.

Title: AVAudioPlayer is turning nil

Body:
Something is wrong with my code but I can't figure out what is wrong. If I compile the code everything is fine, but if I run the code I get this error:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

I've seen lots of the same questions but the answer to those questions is not useful in my case.

import UIKit
import AVFoundation
import AudioToolbox

class ViewController: UIViewController{

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath:  Bundle.main.path(forResource: "beep", ofType: "wav")!))
            audioPlayer.prepareToPlay()

        } catch{
            print(error)
        }

        //standaard klaarmaaklijst
        nummerLabel.text = "\(schijnNummer)"
        nummerCheck()
    }

@IBOutlet weak var nummerLabel: UILabel!
}

I hope someone knows what's wrong with my code.

Body:
Swift :

    if let path = Bundle.main.path(forResource: "beep", ofType:"wav") {
        let url = URL(fileURLWithPath: path)

        do {

            let audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer.prepareToPlay()

        } catch{
            print(error)
        }
    }

Note: Please check if the url is proper and not nil.


问:
Add circle to map with carto.js and leaflet libraries
I have to show a circle on feature click on my layer.
When I try to create the circle I have this error: Error: Invalid LatLng object: (41.961124103390674, NaN).

If I print the object before this error I can read: Array [ 41.84664960937685, 12.008056640625 ].
I tried to write values separated but it doesn't work.

How is it possible?
Someone can help me? Thanks and sorry for my english

EDIT

I tried this solution:

```<code>layer.getSubLayer(1).on('featureClick', function (event, latlon, pos, data, index) {
var coord = {lat:data.lat, lng:data.lon};
console.log(coord)
L.circle(coord, {radius: data.distance}).addTo(map);
</code>```

Error and log are the same...

EDIT 2

With this code

```<code>var coord = L.latLng(42,21);
var cerchio = L.circle(coord,{radius: data.distance});
     console.log(cerchio);
     cerchio.addTo(map);
</code>```

I noticed that circle Object is correctly created, so the problem is on addTo(map) method.

Body:
I have to show a circle on feature click on my layer.
When I try to create the circle I have this error: Error: Invalid LatLng object: (41.961124103390674, NaN).

If I print the object before this error I can read: Array [ 41.84664960937685, 12.008056640625 ].
I tried to write values separated but it doesn't work.

How is it possible?
Someone can help me? Thanks and sorry for my english

EDIT

I tried this solution:

layer.getSubLayer(1).on('featureClick', function (event, latlon, pos, data, index) {
var coord = {lat:data.lat, lng:data.lon};
console.log(coord)
L.circle(coord, {radius: data.distance}).addTo(map);

Error and log are the same...

EDIT 2

With this code

var coord = L.latLng(42,21);
var cerchio = L.circle(coord,{radius: data.distance});
     console.log(cerchio);
     cerchio.addTo(map);

I noticed that circle Object is correctly created, so the problem is on addTo(map) method.

Body:
Add 1609*3

var coord = L.latLng(42,21,1609*3);


答:
I removed the onFocus() because you didn't provide the script for it, and I added document.getElementById() for both p1 and p2 so that you can get their value

function passcheck() {
  var p1 = document.getElementById("pass1").value;
  var p2 = document.getElementById("pass2").value;
  var result = document.getElementById("status");
  if (p1 != p2) {
    result.innerHTML = "Your passwords don't match";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="signupform" id="signupform" onSubmit="return false;">
  <div id="password">Create Password:</div>
  <input id="pass1" type="password" maxlength="88" placeholder="●●●●●●●●●">
  <div id="confirm">Confirm Password:</div>
  <input id="pass2" type="password" onBlur="passcheck()" maxlength="88" placeholder="●●●●●●●●●">
  <p id="status"></p>
</form></code>```

Title: Password confirmation isn't working

Body:
For the life of me, I can't figure out what I've done wrong. I want a message to pop up when someone tries entering passwords that don't match below is the form code.

function passcheck() {
  var p1 = _("pass1").value;
  var p2 = _("pass2").value;
  if (p1 != p2) {
    status.innerHTML = "Your passwords don't match";
  }
}

<form name="signupform" id="signupform" onSubmit="return false;">
Create Password:

  <input id="pass1" type="password" maxlength="88" placeholder="●●●●●●●●●">

Confirm Password:

  <input id="pass2" type="password" onBlur="passcheck()" maxlength="88" placeholder="●●●●●●●●●">

What am I missing?

Body:
I removed the onFocus() because you didn't provide the script for it, and I added document.getElementById() for both p1 and p2 so that you can get their value

function passcheck() {
  var p1 = document.getElementById("pass1").value;
  var p2 = document.getElementById("pass2").value;
  var result = document.getElementById("status");
  if (p1 != p2) {
    result.innerHTML = "Your passwords don't match";
  }
}

<form name="signupform" id="signupform" onSubmit="return false;">
  <div id="password">Create Password:</div>
  <input id="pass1" type="password" maxlength="88" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;">
  <div id="confirm">Confirm Password:</div>
  <input id="pass2" type="password" onBlur="passcheck()" maxlength="88" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;">
  <p id="status"></p>
</form>


问:
wordpress custom post type loop does not work with pagination
Working with a custom post type, which works perfect. All custom posts are showen, but I cant get the pagination to work correct.

Once I click on the next the page is redirected to /page/2/ which does not exict.

Untill now I could not find a working solution online so why is this not working?

Here's the code that I use:

```<code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$query = new WP_Query( array(
    'post_type'      => 'projects',
    'posts_per_page' => 5,
    'paged'          => $paged
) );

// the loop
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

    the_title();

endwhile;

    next_posts_link( '← '.__( 'next' , 'ff' ) ,  $query->max_num_pages );
    previous_posts_link( '← '.__( 'prev' , 'ff' ) , $query->max_num_pages );

    wp_reset_postdata();

endif;
</code>```

答:
You can write this code for pagination :

```<code>$total_pages = $query->max_num_pages;

    if ($total_pages > 1){

        $current_page = max(1, get_query_var('paged'));

        echo paginate_links(array(
            'base' => get_pagenum_link(1) . '%_%',
            'format' => '/page/%#%',
            'current' => $current_page,
            'total' => $total_pages,
            'prev_text'    => __('« prev'),
            'next_text'    => __('next »'),
        ));
    }
</code>```

Another option is You can add rewrite rule in your function.php

```<code>  function custom_rewrite_basic() {
  add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');
</code>```

Modify it as per your requirement and then flush it

```<code><?php flush_rewrite_rules( $hard ); ?>
</code>```

For More information, you can refer this link for WordPress documentation:
https://codex.wordpress.org/Rewrite_API/add_rewrite_rule

Hope this will gives you the solution.

Body:
Working with a custom post type, which works perfect. All custom posts are showen, but I cant get the pagination to work correct.

Once I click on the next the page is redirected to /page/2/ which does not exict.

Untill now I could not find a working solution online so why is this not working?

Here's the code that I use:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$query = new WP_Query( array(
    'post_type'      => 'projects',
    'posts_per_page' => 5,
    'paged'          => $paged
) );

// the loop
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

    the_title();

endwhile;

    next_posts_link( '← '.__( 'next' , 'ff' ) ,  $query->max_num_pages );
    previous_posts_link( '← '.__( 'prev' , 'ff' ) , $query->max_num_pages );

    wp_reset_postdata();

endif;

Body:
You can write this code for pagination :

$total_pages = $query->max_num_pages;

    if ($total_pages > 1){

        $current_page = max(1, get_query_var('paged'));

        echo paginate_links(array(
            'base' => get_pagenum_link(1) . '%_%',
            'format' => '/page/%#%',
            'current' => $current_page,
            'total' => $total_pages,
            'prev_text'    => __('« prev'),
            'next_text'    => __('next »'),
        ));
    }

Another option is You can add rewrite rule in your function.php

  function custom_rewrite_basic() {
  add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');

Modify it as per your requirement and then flush it

<?php flush_rewrite_rules( $hard ); ?>

For More information, you can refer this link for WordPress documentation:
https://codex.wordpress.org/Rewrite_API/add_rewrite_rule

Hope this will gives you the solution.


问:
Angular service is not returning error response
I am calling service saveRouteInfo(), but only success callback is getting invoked for both error and success in the controller.

Service

```<code>gisApp.factory('rpServc', function($http) {
      return {
          saveRouteInfo:function(routeInfo){
              return $http.post("/GISWebApp/gis/api/v1/route",routeInfo).then(
                  function(response)
                  {
                      return response.data;
                  }, function(response) {
                      return response.data;
                  });
            },
      };
});
</code>```

controller

```<code>rpServc.saveRouteInfo(routeInfo).then(function(data) {
    alert(JSON.stringify(data));

}, function(error) {
    alert(JSON.stringify(error));
});
</code>```

答:
you should read the  $q angular promises documentation

and return either resolved or rejected promise so you can catch the rejected ones in the .then() second function.

Body:
I am calling service saveRouteInfo(), but only success callback is getting invoked for both error and success in the controller.

Service

gisApp.factory('rpServc', function($http) {
      return {
          saveRouteInfo:function(routeInfo){
              return $http.post("/GISWebApp/gis/api/v1/route",routeInfo).then(
                  function(response)
                  {
                      return response.data;
                  }, function(response) {
                      return response.data;
                  });
            },
      };
});

controller

rpServc.saveRouteInfo(routeInfo).then(function(data) {
    alert(JSON.stringify(data));

}, function(error) {
    alert(JSON.stringify(error));
});


问:
EXTJS OnClick Tab Event
Is there a way to attach an OnClick event to a tab switch in EXTJS?

I make the grid like this:

```<code>var simple = new Ext.FormPanel({
    labelWidth: '100%',
    border:false,
    width: '100%',
            style:
            {
                height: '291px'
            },
    items: {
        xtype: 'tabpanel',
        activeTab: 0,
        //labelWidth: 75, // label settings here cascade unless overridden
        items:[{
        url:'save-form.php',
        title: 'Tab 1',
  ...
</code>```

Thanks!

答: There is a tabchange event that fires when the active tab changes: http://www.sencha.com/learn/Ext_FAQ_TabPanel

Title: EXTJS OnClick Tab Event

Body:
Is there a way to attach an OnClick event to a tab switch in EXTJS?

I make the grid like this:

var simple = new Ext.FormPanel({
    labelWidth: '100%',
    border:false,
    width: '100%',
            style:
            {
                height: '291px'
            },
    items: {
        xtype: 'tabpanel',
        activeTab: 0,
        //labelWidth: 75, // label settings here cascade unless overridden
        items:[{
        url:'save-form.php',
        title: 'Tab 1',
  ...

Thanks!


问:
Android app UI messed up when I change from appearance from settings
I have defined font size in android application, it works perfectly in all screen sizes, but when I change font size (appearance small, medium, large or x-large) from android phone settings, the UI is messed up with respect to font.</p>

答:
You have to use dp for setting the size of Text, it will sort your problem.

You should also refer this SO for when to using SP and DP.

Stackoverflow link


问:
Can't send custom events to Google Analytics/Firebase from my Objective-C code
I'm kind of new programming events for Google Analytics (nowadays Firebase?) under iOS.
Right now I'm coding some Objective C app and I need to track some custom events inside said app (The typical button press, etc...)

I've successfully installed all the needed pods, .plist files, etc, under my XCode 8.2.1, no problem.

My doubts come now:

I've added some random advice I found reading many pages, and applied them onto the desired places in my code, but apparently I can't create/send custom Events.

My current setup is this one:

-In my App Delegate I've added these lines of code:

```<code>// Google Analytics
// Configure tracker from GoogleService-Info.plist.
//
NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);

// Optional: configure GAI options.
GAI *gai = [GAI sharedInstance];
gai.trackUncaughtExceptions = YES;  // report uncaught exceptions
gai.logger.logLevel = kGAILogLevelVerbose;  // remove before app release

// THIS lines are just a test... They don't make a difference if I comment them.
id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
[tracker set:[GAIFields customDimensionForIndex:1] value:@"TEST_DIMENSION_VALUE" ];
</code>```

-In my ViewController I've added these other lines:

```<code>id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
[tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"ui_status"
                                                      action:@"init_scan_process"
                                                       label:@"hello"
                                                       value:@1] build]];
</code>```

Ok, what happens in runtime while I press the button firing that event? Apparently nothing.
If I'm inside Firebase/Analytics panel I don't get any custom event appearing. I get generic non explicitly sent ones ("entered into some screen", etc...).

I've added the debug verbose mode into XCode (for real time debugging inside Firebase/Analytics panel -> StreamView -> DebugView.
This way I get all kind of real time events (in 1 minute time slices)... But not my custom ones.

Apparently XCode sends and forwards my json data from my custom events to Google... But then I don't know where to find them onto the Firebase/Analytics panel.

I'm out of clues, any obvious hint I might have forgotten?
I'm open to questions from more advanced users having dealt with similar situations in the past.

Grettings and thanks.

答:
As usual self-answered question.

I finally found out why my custom events were not appearing where I looked for them.
I was looking for them in some Firebase console/panel. Why? No idea, as following Google tutorials (can't remember which one), I ended in some fancy Firebase panel (correctly associated with my google account).

The misleading part was that in that Firebase panel, there is a section named "Analytics" which showed some data about your iOS app, but not really what Google Analytics would show...

Whatever, reading more internets I finally found I should have gone to analytics.google.com to begin with.
Once I entered there, I finally found the Events section I was looking for, where I could see the custom hits I programmed inside my APP.
There is even a real time Events section, where I can see events grouped by the last 5 minutes of interaction.

Sucess!!

Thanks and greetings.

Body:
I'm kind of new programming events for Google Analytics (nowadays Firebase?) under iOS.
Right now I'm coding some Objective C app and I need to track some custom events inside said app (The typical button press, etc...)

I've successfully installed all the needed pods, .plist files, etc, under my XCode 8.2.1, no problem.

My doubts come now:

I've added some random advice I found reading many pages, and applied them onto the desired places in my code, but apparently I can't create/send custom Events.

My current setup is this one:

-In my App Delegate I've added these lines of code:

// Google Analytics
// Configure tracker from GoogleService-Info.plist.
//
NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);

// Optional: configure GAI options.
GAI *gai = [GAI sharedInstance];
gai.trackUncaughtExceptions = YES;  // report uncaught exceptions
gai.logger.logLevel = kGAILogLevelVerbose;  // remove before app release

// THIS lines are just a test... They don't make a difference if I comment them.
id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
[tracker set:[GAIFields customDimensionForIndex:1] value:@"TEST_DIMENSION_VALUE" ];

-In my ViewController I've added these other lines:

id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
[tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"ui_status"
                                                      action:@"init_scan_process"
                                                       label:@"hello"
                                                       value:@1] build]];

Ok, what happens in runtime while I press the button firing that event? Apparently nothing.
If I'm inside Firebase/Analytics panel I don't get any custom event appearing. I get generic non explicitly sent ones ("entered into some screen", etc...).

I've added the debug verbose mode into XCode (for real time debugging inside Firebase/Analytics panel -> StreamView -> DebugView.
This way I get all kind of real time events (in 1 minute time slices)... But not my custom ones.

Apparently XCode sends and forwards my json data from my custom events to Google... But then I don't know where to find them onto the Firebase/Analytics panel.

I'm out of clues, any obvious hint I might have forgotten?
I'm open to questions from more advanced users having dealt with similar situations in the past.

Grettings and thanks.