问:
How can I properly use a Pandas Dataframe with a multiindex that includes Intervals?
I'm trying to slice into a DataFrame that has a MultiIndex composed of an IntervalIndex and a regular Index. Example code:

```<code>from pandas import Interval as ntv

df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id':2, 'var1': 0.5, 'ntv': ntv(0,12), 'E': 0}
], index=('ntv', 'id'))
</code>```

Looks like this:

```<code>            E  var1
ntv     id
(0, 10] 1   1   0.1
(0, 12] 2   0   0.5
</code>```

What I would like to do is to slice into the DataFrame at a specific value and return all rows that has an interval that contains the value. Ex:

```<code>df.loc[4]
</code>```

should return (trivially)

```<code>    E  var1
id
1   1   0.1
2   0   0.5
</code>```

The problem is I keep getting a TypeError about the index, and the docs show a similar operation (but on a single-level index) that does produce what I'm looking for.

```<code>TypeError: only integer scalar arrays can be converted to a scalar index
</code>```

I've tried many things, nothing seems to work normally. I could include the id column inside the dataframe, but I'd rather keep my index unique, and I would constantly be calling set_index('id').

I feel like either a) I'm missing something about MultiIndexes or b) there is a bug / ambiguity with using an IntervalIndex in a MultiIndex.

答:
Since we are speaking intervals there is a method called get_loc to find the rows that has the value in between the interval. To say what I mean :

```<code>from pandas import Interval as ntv

df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id':2, 'var1': 0.5, 'ntv': ntv(0,12), 'E': 0}
], index=('ntv', 'id'))

df.iloc[(df.index.get_level_values(0).get_loc(4))]
            E  var1
ntv     id
(0, 10] 1   1   0.1
(0, 12] 2   0   0.5

df.iloc[(df.index.get_level_values(0).get_loc(11))]
             E  var1
ntv     id
(0, 12] 2   0   0.5
</code>```

This also works if you have multiple rows of data for one inteval i.e

```<code>df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id': 3, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id':2, 'var1': 0.5, 'ntv': ntv(0,12), 'E': 0}
], index=('ntv', 'id'))

df.iloc[(df.index.get_level_values(0).get_loc(4))]

            E  var1
ntv     id
(0, 10] 1   1   0.1
        3   1   0.1
(0, 12] 2   0   0.5
</code>```

If you time this up with a list comprehension, this approach is way faster for large dataframes i.e

```<code>ndf = pd.concat([df]*10000)

%%timeit
ndf.iloc[ndf.index.get_level_values(0).get_loc(4)]
10 loops, best of 3: 32.8 ms per loop

%%timeit
intervals = ndf.index.get_level_values(0)
mask = [4 in i for i in intervals]
ndf.loc[mask]
1 loop, best of 3: 193 ms per loop
</code>```

Body:
I'm trying to slice into a DataFrame that has a MultiIndex composed of an IntervalIndex and a regular Index. Example code:

from pandas import Interval as ntv

df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id':2, 'var1': 0.5, 'ntv': ntv(0,12), 'E': 0}
], index=('ntv', 'id'))

Looks like this:

            E  var1
ntv     id
(0, 10] 1   1   0.1
(0, 12] 2   0   0.5

What I would like to do is to slice into the DataFrame at a specific value and return all rows that has an interval that contains the value. Ex:

df.loc[4]

should return (trivially)

    E  var1
id
1   1   0.1
2   0   0.5

The problem is I keep getting a TypeError about the index, and the docs show a similar operation (but on a single-level index) that does produce what I'm looking for.

TypeError: only integer scalar arrays can be converted to a scalar index

I've tried many things, nothing seems to work normally. I could include the id column inside the dataframe, but I'd rather keep my index unique, and I would constantly be calling set_index('id').

I feel like either a) I'm missing something about MultiIndexes or b) there is a bug / ambiguity with using an IntervalIndex in a MultiIndex.

Body:
Since we are speaking intervals there is a method called get_loc to find the rows that has the value in between the interval. To say what I mean :

from pandas import Interval as ntv

df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id':2, 'var1': 0.5, 'ntv': ntv(0,12), 'E': 0}
], index=('ntv', 'id'))

df.iloc[(df.index.get_level_values(0).get_loc(4))]
            E  var1
ntv     id
(0, 10] 1   1   0.1
(0, 12] 2   0   0.5

df.iloc[(df.index.get_level_values(0).get_loc(11))]
             E  var1
ntv     id
(0, 12] 2   0   0.5

This also works if you have multiple rows of data for one inteval i.e

df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id': 3, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id':2, 'var1': 0.5, 'ntv': ntv(0,12), 'E': 0}
], index=('ntv', 'id'))

df.iloc[(df.index.get_level_values(0).get_loc(4))]

            E  var1
ntv     id
(0, 10] 1   1   0.1
        3   1   0.1
(0, 12] 2   0   0.5

If you time this up with a list comprehension, this approach is way faster for large dataframes i.e

ndf = pd.concat([df]*10000)

%%timeit
ndf.iloc[ndf.index.get_level_values(0).get_loc(4)]
10 loops, best of 3: 32.8 ms per loop

%%timeit
intervals = ndf.index.get_level_values(0)
mask = [4 in i for i in intervals]
ndf.loc[mask]
1 loop, best of 3: 193 ms per loop


来源: stackexchange

问:
Saving Canvas to Image File saves Blank Black Image
For starters, I'm still new with UWP and XAML.
I've made a simple code on my uwp where I have a canvas (named it "ImageHolder") and there is an image and textblock inside it.
My main problem is that whenever I try to use RenderTargetBitmap inorder to save the canvas into an image file, it outputs a black blank image.
Here is my XAML code:

```<code><Page
x:Class="SaveAndRetreiveMap.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SaveAndRetreiveMap"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Line x:Name="dot" Stroke="Black" StrokeThickness="5" Fill="Black"></Line>

    <TextBox x:Name="xValue" HorizontalAlignment="Left" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Margin="89,415,0,0" Background="Azure"/>
    <TextBox x:Name="yValue" HorizontalAlignment="Left" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Margin="89,452,0,0" Background="Azure"/>
    <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="55,420,0,0" TextWrapping="Wrap" Text="X:" VerticalAlignment="Top" FontSize="20"/>
    <TextBlock x:Name="textBlock_Copy" HorizontalAlignment="Left" Margin="55,455,0,0" TextWrapping="Wrap" Text="Y:" VerticalAlignment="Top" FontSize="20"/>
    <Button x:Name="PlotButton" Content="Plot Points" HorizontalAlignment="Left" Margin="62,496,0,0" VerticalAlignment="Top" Click="PlotButton_Click"/>

    <Canvas Name="ImageHolder"  Height="206" Width="226" Margin="356,160,918,634">

        <Image x:Name="image" HorizontalAlignment="Left" Height="206" VerticalAlignment="Top" Width="226"/>
        <TextBlock Text="Johnny!" Margin="44,89,-44,-89"></TextBlock>
        <Button x:Name="button" Content="Save" HorizontalAlignment="Left" VerticalAlignment="Top" Click="button_Click" Canvas.Left="-133" Canvas.Top="335"/>
    </Canvas>
</Grid>
</code>```

My CS code:

```<code>        private async void button_Click(object sender, RoutedEventArgs e)
        {
        RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
        await renderTargetBitmap.RenderAsync(ImageHolder);

        var picker = new FileSavePicker();
        picker.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
        StorageFile file = await picker.PickSaveFileAsync();
        if (file != null)
        {
            var pixels = await renderTargetBitmap.GetPixelsAsync();

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await

                BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                byte[] bytes = pixels.ToArray();
                encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                     BitmapAlphaMode.Ignore,
                                     (uint)ImageHolder.Width, (uint)ImageHolder.Height,
                                     96, 96, bytes);

                await encoder.FlushAsync();
            }
        }
    }
</code>```

Output

I'm still really new at UWP, and a small help would really be appreciated. :)

答:
It is due to your foreground is black you this is rendering black background, this will work --

FOR JPEG

XAML

```<code><Canvas Name="ImageHolder" Height="260" Width="260">
        <Canvas.Background>
            <SolidColorBrush Color="White"/>
        </Canvas.Background>

        <Image x:Name="image" HorizontalAlignment="Left" Height="206" VerticalAlignment="Top" Width="226"/>
        <TextBlock Text="Johnny!" Margin="44,89,-44,-89"></TextBlock>

    </Canvas>
    <Button x:Name="button" Background="Gray" Content="Save" HorizontalAlignment="Left" VerticalAlignment="Top" Click="button_Click" />
</code>```

i removed the button from canvas because you are using  negative margin which is out of your canvas ant when you capture it or save it it renders dark black background so if you want button on it so place button inside the canvas

C#

```<code>private async void button_Click(object sender, RoutedEventArgs e)
{
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(ImageHolder);

    var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
    var pixels = pixelBuffer.ToArray();
    var displayInformation = DisplayInformation.GetForCurrentView();
    var picker = new FileSavePicker();
    picker.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
    StorageFile file = await picker.PickSaveFileAsync();
    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels);
        await encoder.FlushAsync();
    }
}
</code>```

FOR PNG (Bonus)

XAML --> Your regular above XAML

because you will always get transparent background irrespective of any margin

```<code>private async void button_Click(object sender, RoutedEventArgs e)
{
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
     await renderTargetBitmap.RenderAsync(ImageHolder);

     var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
     var pixels = pixelBuffer.ToArray();
     var displayInformation = DisplayInformation.GetForCurrentView();
     var picker = new FileSavePicker();
     picker.FileTypeChoices.Add("PNG Image", new string[] { ".png" });
     StorageFile file = await picker.PickSaveFileAsync();
     using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
     {
         var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
         encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels);
         await encoder.FlushAsync();
     }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For starters, I'm still new with UWP and XAML.
I've made a simple code on my uwp where I have a canvas (named it "ImageHolder") and there is an image and textblock inside it.
My main problem is that whenever I try to use RenderTargetBitmap inorder to save the canvas into an image file, it outputs a black blank image.
Here is my XAML code:

<Page
x:Class="SaveAndRetreiveMap.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SaveAndRetreiveMap"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Line x:Name="dot" Stroke="Black" StrokeThickness="5" Fill="Black"></Line>

    <TextBox x:Name="xValue" HorizontalAlignment="Left" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Margin="89,415,0,0" Background="Azure"/>
    <TextBox x:Name="yValue" HorizontalAlignment="Left" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Margin="89,452,0,0" Background="Azure"/>
    <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="55,420,0,0" TextWrapping="Wrap" Text="X:" VerticalAlignment="Top" FontSize="20"/>
    <TextBlock x:Name="textBlock_Copy" HorizontalAlignment="Left" Margin="55,455,0,0" TextWrapping="Wrap" Text="Y:" VerticalAlignment="Top" FontSize="20"/>
    <Button x:Name="PlotButton" Content="Plot Points" HorizontalAlignment="Left" Margin="62,496,0,0" VerticalAlignment="Top" Click="PlotButton_Click"/>

    <Canvas Name="ImageHolder"  Height="206" Width="226" Margin="356,160,918,634">

        <Image x:Name="image" HorizontalAlignment="Left" Height="206" VerticalAlignment="Top" Width="226"/>
        <TextBlock Text="Johnny!" Margin="44,89,-44,-89"></TextBlock>
        <Button x:Name="button" Content="Save" HorizontalAlignment="Left" VerticalAlignment="Top" Click="button_Click" Canvas.Left="-133" Canvas.Top="335"/>
    </Canvas>
</Grid>

My CS code:

        private async void button_Click(object sender, RoutedEventArgs e)
        {
        RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
        await renderTargetBitmap.RenderAsync(ImageHolder);

        var picker = new FileSavePicker();
        picker.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
        StorageFile file = await picker.PickSaveFileAsync();
        if (file != null)
        {
            var pixels = await renderTargetBitmap.GetPixelsAsync();

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await

                BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                byte[] bytes = pixels.ToArray();
                encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                     BitmapAlphaMode.Ignore,
                                     (uint)ImageHolder.Width, (uint)ImageHolder.Height,
                                     96, 96, bytes);

                await encoder.FlushAsync();
            }
        }
    }

Output

I'm still really new at UWP, and a small help would really be appreciated. :)

Body:
It is due to your foreground is black you this is rendering black background, this will work --

FOR JPEG

XAML

<Canvas Name="ImageHolder" Height="260" Width="260">
        <Canvas.Background>
            <SolidColorBrush Color="White"/>
        </Canvas.Background>

        <Image x:Name="image" HorizontalAlignment="Left" Height="206" VerticalAlignment="Top" Width="226"/>
        <TextBlock Text="Johnny!" Margin="44,89,-44,-89"></TextBlock>

    </Canvas>
    <Button x:Name="button" Background="Gray" Content="Save" HorizontalAlignment="Left" VerticalAlignment="Top" Click="button_Click" />

i removed the button from canvas because you are using  negative margin which is out of your canvas ant when you capture it or save it it renders dark black background so if you want button on it so place button inside the canvas

C#

private async void button_Click(object sender, RoutedEventArgs e)
{
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(ImageHolder);

    var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
    var pixels = pixelBuffer.ToArray();
    var displayInformation = DisplayInformation.GetForCurrentView();
    var picker = new FileSavePicker();
    picker.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
    StorageFile file = await picker.PickSaveFileAsync();
    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels);
        await encoder.FlushAsync();
    }
}

FOR PNG (Bonus)

XAML --> Your regular above XAML

because you will always get transparent background irrespective of any margin

private async void button_Click(object sender, RoutedEventArgs e)
{
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
     await renderTargetBitmap.RenderAsync(ImageHolder);

     var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
     var pixels = pixelBuffer.ToArray();
     var displayInformation = DisplayInformation.GetForCurrentView();
     var picker = new FileSavePicker();
     picker.FileTypeChoices.Add("PNG Image", new string[] { ".png" });
     StorageFile file = await picker.PickSaveFileAsync();
     using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
     {
         var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
         encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.RawDpiX, displayInformation.RawDpiY, pixels);
         await encoder.FlushAsync();
     }
}


问:
The multi-part identifier could not be bound sql where clause
I am trying to multiply two tables using the code below to get a new calculated column. I am using the SQL Server Express Edition and SQL Server Management Studio.

```<code>select
    [Yield_unpiv].[SubPrecinct],
    [Yield_unpiv].[LandUse],
    [Yield_unpiv].[Yield] * [LU_Rules_Final].[AM_GenRateFinal] * [LU_Rules_Final].[AM_In_factor] / [LU_Rules_Final].[UnitValue] as AM_In
from
    Yield_unpiv, LU_Rules_Final
where
    [Yield_unpiv].[LandUse]=[LU_Rules_Final].[LandUse]
</code>```

However, I get the following error

The multi-part identifier "Yield_unpiv.LandUse" could not be bound.

The Yield_unpiv is set up like this:

```<code>SubPrecinct | Yield     | LandUse
P1            Unique #s   LDResi
P1                        MDResi
.                           .
.                           .
.                           .
P2                       LDResi
P2                       MDResi
.                           .
.                           .
.                           .
</code>```

And the LU_Rules_Final is set up like this:

```<code>LandUse    | UnitValue | AM_GenRateFinal | AM_In_factor
LDResi       1             2.5                0.5
BulkyGoods   100           7                  0.7
MDREsi       1             0.52               0.1
.
.
.
</code>```

Not sure why I am getting this multi-part identifier "Yield_unpiv.LandUse" could not be bound error.

Please help!

答:
I don't know the exact cause of your error, but it likely has to do with that the column LandUse appears in both tables.  I speculate that refactoring it to use explicit joins would fix the problem:

```<code>SELECT
    t1.[SubPrecinct],
    t1.[LandUse],
    t1.[Yield] * t2.[AM_GenRateFinal] * t2.[AM_In_factor] / t2.[UnitValue] AS AM_In
FROM Yield_unpiv t1
INNER JOIN LU_Rules_Final t2
    OM t1.[LandUse] = t2.[LandUse];
</code>```

If this fixes your problem, then it means one more reason not to use the archaic pre ANSI-92 style of SQL joins.  Always use explicit joins whenever possible.

Body:
I am trying to multiply two tables using the code below to get a new calculated column. I am using the SQL Server Express Edition and SQL Server Management Studio.

select
    [Yield_unpiv].[SubPrecinct],
    [Yield_unpiv].[LandUse],
    [Yield_unpiv].[Yield] * [LU_Rules_Final].[AM_GenRateFinal] * [LU_Rules_Final].[AM_In_factor] / [LU_Rules_Final].[UnitValue] as AM_In
from
    Yield_unpiv, LU_Rules_Final
where
    [Yield_unpiv].[LandUse]=[LU_Rules_Final].[LandUse]

However, I get the following error

The multi-part identifier "Yield_unpiv.LandUse" could not be bound.

The Yield_unpiv is set up like this:

SubPrecinct | Yield     | LandUse
P1            Unique #s   LDResi
P1                        MDResi
.                           .
.                           .
.                           .
P2                       LDResi
P2                       MDResi
.                           .
.                           .
.                           .

And the LU_Rules_Final is set up like this:

LandUse    | UnitValue | AM_GenRateFinal | AM_In_factor
LDResi       1             2.5                0.5
BulkyGoods   100           7                  0.7
MDREsi       1             0.52               0.1
.
.
.

Not sure why I am getting this multi-part identifier "Yield_unpiv.LandUse" could not be bound error.

Please help!

Body:
I don't know the exact cause of your error, but it likely has to do with that the column LandUse appears in both tables.  I speculate that refactoring it to use explicit joins would fix the problem:

SELECT
    t1.[SubPrecinct],
    t1.[LandUse],
    t1.[Yield] * t2.[AM_GenRateFinal] * t2.[AM_In_factor] / t2.[UnitValue] AS AM_In
FROM Yield_unpiv t1
INNER JOIN LU_Rules_Final t2
    OM t1.[LandUse] = t2.[LandUse];

If this fixes your problem, then it means one more reason not to use the archaic pre ANSI-92 style of SQL joins.  Always use explicit joins whenever possible.


问:
Getting attributes from XML using c#
I have the following xml contents inside a string variable. i want to get the value of each attribute (JID) in the form of string.

Below is my xml

```<code>  <query xmlns="http://jabber.org/protocol/muc#admin">
  <item affiliation="member" jid="a@something.com" />
  <item affiliation="member" jid="b@something.com" />
  <item affiliation="member" jid="c@something.com" />
  <item affiliation="member" jid="d@something.com" />
  <item affiliation="member" jid="e@something.com" />
  <item affiliation="member" jid="f@something.com" />
  <item affiliation="member" jid="g@something.com" />
  <item affiliation="member" jid="h@something.com" />
  <item affiliation="member" jid="i@something.com" />
  <item affiliation="member" jid="j@something.com" />
  </query>
</code>```

Anyone please suggest some ideas to find this.
my expected output is like

```<code>   a@something.com
   b@something.com
   c@something.com
   d@something.com
   e@something.com
   f@something.com
</code>```

答:
Linq to XML is one way to tackle it.  Where the "" inside .Parse is - place the string variable with the xml.</p>

```<code>           List<XAttribute> jids = XDocument.Parse("").Root.Elements().Attributes().ToList();
            foreach (XAttribute a in jids)
            {
              if (a.Name =="jid")
              {
                string jid = a.Value;
              }
            }
</code>```

Title: Getting attributes from XML using c#

Body:
I have the following xml contents inside a string variable. i want to get the value of each attribute (JID) in the form of string.

Below is my xml

  <query xmlns="http://jabber.org/protocol/muc#admin">
  <item affiliation="member" jid="a@something.com" />
  <item affiliation="member" jid="b@something.com" />
  <item affiliation="member" jid="c@something.com" />
  <item affiliation="member" jid="d@something.com" />
  <item affiliation="member" jid="e@something.com" />
  <item affiliation="member" jid="f@something.com" />
  <item affiliation="member" jid="g@something.com" />
  <item affiliation="member" jid="h@something.com" />
  <item affiliation="member" jid="i@something.com" />
  <item affiliation="member" jid="j@something.com" />
  </query>

Anyone please suggest some ideas to find this.
my expected output is like

   a@something.com
   b@something.com
   c@something.com
   d@something.com
   e@something.com
   f@something.com

Body:
Linq to XML is one way to tackle it.  Where the "" inside .Parse is - place the string variable with the xml.

           List<XAttribute> jids = XDocument.Parse("").Root.Elements().Attributes().ToList();
            foreach (XAttribute a in jids)
            {
              if (a.Name =="jid")
              {
                string jid = a.Value;
              }
            }


问:
Moving committed git files to another directory
I've been doing development work in a 'dev-test' directory and committed files along the way.  I now need to commit those same files to a differently named directory and remove the committed files in the 'dev-test' directory.  I'm not sure how to retain my working files.

My 'dev-test' repo is local, but I have been doing pulls that are tracking as 'master', but I have not merged my code.

答:
To move a file from one directory to another you can use git mv command.
For example you have 2 directories
a.draft, b.pages on your git repository (gitrepo is the name in my case)  . You want to move a file abc.md from draft to pages make sure you're in yor gitrepo use cd to go to your gitrepo ( you can check status by $git status as well) and write  :

```<code>[zuha@localhost gitrepo] $ git mv draft/abc.md pages
</code>```

It will show something like

```<code>[zuha@localhost gitrepo] $ renamed: draft/abc.md -> pages/single-batch-ex.md~
</code>```

Now commit your file

```<code> [zuha@localhost gitrepo] $ git commit -m "first file"
</code>```

Enter your username and password, and push it .

```<code> [zuha@localhost gitrepo]  $ git push origin (your-branch)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
To move a file from one directory to another you can use git mv command.
For example you have 2 directories
a.draft, b.pages on your git repository (gitrepo is the name in my case)  . You want to move a file abc.md from draft to pages make sure you're in yor gitrepo use cd to go to your gitrepo ( you can check status by $git status as well) and write  :

[zuha@localhost gitrepo] $ git mv draft/abc.md pages

It will show something like

[zuha@localhost gitrepo] $ renamed: draft/abc.md -> pages/single-batch-ex.md~

Now commit your file

 [zuha@localhost gitrepo] $ git commit -m "first file"

Enter your username and password, and push it .

 [zuha@localhost gitrepo]  $ git push origin (your-branch)


问:
identify lines in a file in php
I have a file, which contains passwords/usernames:

thomas 123

john 321

What would be the best way to identify lines and add to them contact information? Right in password file I dont want store, because the size of the file matters.. I thought to add an identifier string before records, like this:

[1]

thomas 123

[2]

john 321

What do you think? It is a good way to identify lines? If yes, how I can read out line after identifier [number]?

If I can read out, then in a second file I can store contact information.

[1]

email, etc

[2]

email etc

this is a config file of an offline app, sadly I cant change the structure of that file (max. change: add an identifier before lines) or use database.

Thank you so much,

Adrian

答:
You can handle this as simple as a single call to file function.

```<code>$lines = file ('passwords.txt');
</code>```

After that you'll have all lines numbered from 0 to N-1.

ContentLicense: CC BY-SA 2.5

Title: identify lines in a file in php

Body:
You can handle this as simple as a single call to file function.

$lines = file ('passwords.txt');

After that you'll have all lines numbered from 0 to N-1.


问:
DatePicker not working on bootstrap 4
I want to used datepicker on my project.This is my first time using bootstrap.The problem is that datepicker not displayed when i click the date form.I already try replace CDN url position inside  and inside  tag and still not worked.I dont know what mistake that i make,hope you guys can help me with this problem thank you.</p>

```<code><!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <!-- datepicker -->
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
    $(function() {
      $("#datepicker").datepicker();
    });
  </script>
</head>

<body>
  <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
    <a class="navbar-brand" href="#">Menu</a>
    <div class="collapse navbar-collapse" id="navbarsExampleDefault">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Management</a>
          <div class="dropdown-menu" aria-labelledby="dropdown01">
            <a class="dropdown-item" href="dashboard.php?act=create_program">Create Program</a>
            <a class="dropdown-item" href="dashboard.php?act=view_program">View Program</a>
          </div>
        </li>
      </ul>
    </div>
  </nav>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4"></div>
      <div class="col-md-4">
        <!-- Datepicker -->
        Date: <input type="text" id="datepicker">
      </div>
      <div class="col-md-4"></div>
    </div>
  </div>
  <!-- jQuery first, then Tether, then Bootstrap JS. -->
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>

</html>
</code>```

答:
I have checked your above code their is two more Javascripts included in your project , Remove these redundent javascript from your code

Remove these javascript

```<code> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
</code>```

Use this code:

$(function() {
    $("#datepicker").datepicker();
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" >
<!-- jQuery first, then Tether, then Bootstrap JS. -->

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
    <!-- datepicker -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

  </head>
  <body>

          <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      Menu

      <div class="collapse navbar-collapse" id="navbarsExampleDefault">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item dropdown">
            Management
            <div class="dropdown-menu" aria-labelledby="dropdown01">
              Create Program
              View Program
            </div>
          </li>
        </ul>
      </div>
    </nav>

    <div class="container-fluid">
    <div class="row">

      <div class="col-md-4"></div>
      <div class="col-md-4">
            <!-- Datepicker -->
            Date: <input type="text" id="datepicker">
      </div>
      <div class="col-md-4"></div>

    </div>
    </div>

  </body></code>```

Title: DatePicker not working on bootstrap 4

Body:
I want to used datepicker on my project.This is my first time using bootstrap.The problem is that datepicker not displayed when i click the date form.I already try replace CDN url position inside  and inside  tag and still not worked.I dont know what mistake that i make,hope you guys can help me with this problem thank you.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

      </button>
    Menu

          Management

            Create Program
            View Program

        Date: <input type="text" id="datepicker">

Body:
I have checked your above code their is two more Javascripts included in your project , Remove these redundent javascript from your code

Remove these javascript

 <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>

Use this code:

$(function() {
    $("#datepicker").datepicker();
  });

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" >
<!-- jQuery first, then Tether, then Bootstrap JS. -->

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
    <!-- datepicker -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

  </head>
  <body>

          <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <a class="navbar-brand" href="#">Menu</a>

      <div class="collapse navbar-collapse" id="navbarsExampleDefault">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Management</a>
            <div class="dropdown-menu" aria-labelledby="dropdown01">
              <a class="dropdown-item" href="dashboard.php?act=create_program">Create Program</a>
              <a class="dropdown-item" href="dashboard.php?act=view_program">View Program</a>
            </div>
          </li>
        </ul>
      </div>
    </nav>

    <div class="container-fluid">
    <div class="row">

      <div class="col-md-4"></div>
      <div class="col-md-4">
            <!-- Datepicker -->
            Date: <input type="text" id="datepicker">
      </div>
      <div class="col-md-4"></div>

    </div>
    </div>

  </body>


问:
Ios crash when trying to do playerPhysicsBody.node?.addChild(emitter!)
for some reason, whenever i win the game, that is the player hits the target, the app crashes at line

 playerPhysicsBody.node?.addChild(emitter!)

with an error
fatal error: unexpectedly found nil while unwrapping an Optional value
any help here please?

答:
Before Execute Check Whether Is Null Or Not.</p>

```<code>    if(playerPhysicsBody != nil){
          playerPhysicsBody.node?.addChild(emitter!)
    }
</code>```

Body:
Before Execute Check Whether Is Null Or Not.

    if(playerPhysicsBody != nil){
          playerPhysicsBody.node?.addChild(emitter!)
    }


问:
How to restore own nuget package in another solution
I have C# solution called commons where I have my Model and some common stuff that will be used by other solutions.

As a Post Build Event I create a nuget package and copy it to my local Nuget folder ("C:\packages")

Post Build Event:

"$(ProjectDir)nuget.exe" pack "$(ProjectDir)Commons.csproj" -
IncludeReferencedProjects

xcopy Commons.1.0.0.nupkg c:\packages /Y

Note: Version never changes.

That creates successfully my new nuget package.

Then on the other solution I reference that package and I can see everything ok.
I can access all my models and everything.

The problem I have is

if I make any change to my Common projects (e.g add a new field to my model) this will not appear on my solution.

What am I missing??

答:
Create package with higher version than previous

Copy the new package to a Shared Folder

Make sure the folder has following structure

packageName/version/[packageName].[version].nupkg
v1: abc.common/1.0.0/abc.common.1.0.0.nupkg
v2: abc.common/2.0.0/abc.common.2.0.0.nupkg

Make sure the newer package has higher version, not just on the folder structure but also the nuspec file. You can rename .nupkg to zip file, and access the nuspec file. Or use package explorer https://github.com/NuGetPackageExplorer/NuGetPackageExplorer

Now add package to the shared folder eg: \\localhost\mypackages and use this shared url as a package source in visual studio

VS will automatically show upgrade button if there new version published.


问:
Command /bin/sh failed with exit code 1 Xcode 9.1
When i am run project in Xcode then showing some  error that means my add pod file is unknown error

and

error screen short

Screen Short Link

and showing error text is

"/Users/Appsfactor/Library/Developer/Xcode/DerivedData/You_Task-hfbipjtwskuqvfgdnnjienomkrbm/Build/Intermediates.noindex/ArchiveIntermediates/You Task/InstallationBuildProductsLocation/Applications//You Task.app/Frameworks/ALCameraViewController.framework: unknown error -1=ffffffffffffffff
Command /bin/sh failed with exit code 1"

答:
Clear Derived Data

Empty your Trash

Clean your Xcode Project and Run again.

Worked for me.


问:
Shell script: Ensure that script isn't executed if already running

Possible Duplicate:

  Quick-and-dirty way to ensure only one instance of a shell script is running at a time

I've set up a cronjob to backup my folders properly which I am quite proud of. However I've found out, by looking at the results from the backups, that my backup script has been called more than once by Crontab, resulting in multiple backups running at the same time.

Is there any way I can ensure that a certain shell script to not run if the very same script already is executing?

答:
You can use a tmp file.

Named it tmpCronBkp.a, tmpCronBkp.b, tmpCronBkp.c... etc. Releated of yout backup script.

Create it on script start and delete it at the end...

In a while, check if file exist or not and what file exist.

Have you tried this way?


问:
I want to enable textbox when checkbox is checked in jquery or javascript
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash" onclick="cash(this)">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div></code>```

答:
With pure javascript:</p>

```<code>function cash(cash){
  if(cash.checked ===true) document.getElementById('cashAmount').removeAttribute('disabled');
  else document.getElementById('cashAmount').setAttribute('disabled', 'disabled');
}
</code>```

Body:
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}

  Cash <input type="checkbox" name="cash" id="cash" onclick="cash(this)">

  Amount *
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>

Body:
With pure javascript:

function cash(cash){
  if(cash.checked ===true) document.getElementById('cashAmount').removeAttribute('disabled');
  else document.getElementById('cashAmount').setAttribute('disabled', 'disabled');
}


问:
how to set local time in project irrespective of server location
I have my project based in India and my hosting server located somewhere that is at a difference of -5:30 HRs from Indian time.

So my time being stored in database is coming as based on there timings. How can I rectify this in PHP so that the time actually gets stored on India.

I tried using date_default_timezone_set('Asia/Kolkata');

but still the time gets stored with a difference of -30mins to -45mins. What could be possible code fort his so that the time sets exactly according to Indian timings. Any advice will be very helpful.

答:
Step-1: Set timezone as asia/kolkata

Step-2: Now, first store the
date in local variable, example: $mydate = date('Y-m-d H:i:s'); and
just print the variable value to see, if it is the time as you want?

Step-3: If yes then store $mydate variable value in database.


问:
How to change CSS elements of an element when hovering on another
I'm experimenting with a design. I have a text element that changes colors and glows on hover. It's an a element wrapped in a p. I have the text in the middle of a circular image. I'd like for the image to change it's border color from transparent to white when a is hovered over. I've done some research but can't seem to get any of the solutions to work.

What I've tried,

a:hover > img { border-color: #fff; }

a:hover + img { border-color: #fff; }

a:hover img { border-color: #fff; }

a:hover ~ img { border-color: #fff; }

Same as above but p a:hover + img

Adding a class and id to img

Please help, here's the code:

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: rgb(24, 24, 24);
}

.Hero {
  position: fixed;
  z-index: -1000;
  width: 100%;
  height: 100%;
  overflow: hidden;
  top: 0;
  left: 0;
  object-fit: cover;
}

img {
  display: block;
  width: 940px;
  height: 940px;
  margin: 0 auto;
  position: absolute;
  top: 10px;
  right: 485px;
  z-index: -999;
  border: 5px solid transparent;
  border-radius: 50%;
}

p {
  text-align: center;
  font-size: 70px;
  margin-top: 415px;
  text-shadow: -.75px -.75px 0 #25343f, .75px -.75px 0 #25343f, -.75px .75px 0 #25343f, .75px .75px 0 #25343f;
}

a {
  text-decoration: none;
  -webkit-transition: all 0.7s;
  -moz-transition: all 0.7s;
  transition: all .7s;
}

p a {
  color: #405c71;
  font-family: Pacifico, cursive;
}

p a:hover {
  -webkit-animation: neon .9s ease-in-out infinite alternate;
  -moz-animation: neon .9s ease-in-out infinite alternate;
  animation: neon .65s ease-in-out infinite alternate;
  color: #fff;
}

@-webkit-keyframes neon {
  from {
    text-shadow: 0 0 5px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #405c71, 0 0 70px #405c71, 0 0 80px #405c71, 0 0 100px #405c71, 0 0 150px #405c71;
  }
  to {
    text-shadow: 0 0 5px #fff, 0 0 10px #fff, 0 0 15px #fff, 0 0 20px #405c71, 0 0 35px #405c71, 0 0 40px #405c71, 0 0 50px #405c71, 0 0 75px #405c71;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Container">

  <!-- <div class="Hero">
     <video src="dojo/frontend/photography/images/editor.mp4" preload="auto" autoplay="true" loop="loop"></video>
  </div> -->

  <p>Welcome</p>
  <img class="logo" src="https://placehold.it/940x940" alt="">

</div></code>```

答:
There is no CSS selector that does what you are trying to do.

For a:hover + img to work, the image has to be directly after the link. so remove the
 surrounding the

or wrap both the link and the image inside the paragraph tag like so:

a:hover + img {
  border-color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
Welcome<br/>
<img class="logo" src="dojo/frontend/photography/images/logo.png" alt="">
</p></code>```

Body:
I'm experimenting with a design. I have a text element that changes colors and glows on hover. It's an a element wrapped in a p. I have the text in the middle of a circular image. I'd like for the image to change it's border color from transparent to white when a is hovered over. I've done some research but can't seem to get any of the solutions to work.

What I've tried,

a:hover > img { border-color: #fff; }

a:hover + img { border-color: #fff; }

a:hover img { border-color: #fff; }

a:hover ~ img { border-color: #fff; }

Same as above but p a:hover + img

Adding a class and id to img

Please help, here's the code:

* {
  margin: 0;
  padding: 0;
}

body {
  background-color: rgb(24, 24, 24);
}

.Hero {
  position: fixed;
  z-index: -1000;
  width: 100%;
  height: 100%;
  overflow: hidden;
  top: 0;
  left: 0;
  object-fit: cover;
}

img {
  display: block;
  width: 940px;
  height: 940px;
  margin: 0 auto;
  position: absolute;
  top: 10px;
  right: 485px;
  z-index: -999;
  border: 5px solid transparent;
  border-radius: 50%;
}

p {
  text-align: center;
  font-size: 70px;
  margin-top: 415px;
  text-shadow: -.75px -.75px 0 #25343f, .75px -.75px 0 #25343f, -.75px .75px 0 #25343f, .75px .75px 0 #25343f;
}

a {
  text-decoration: none;
  -webkit-transition: all 0.7s;
  -moz-transition: all 0.7s;
  transition: all .7s;
}

p a {
  color: #405c71;
  font-family: Pacifico, cursive;
}

p a:hover {
  -webkit-animation: neon .9s ease-in-out infinite alternate;
  -moz-animation: neon .9s ease-in-out infinite alternate;
  animation: neon .65s ease-in-out infinite alternate;
  color: #fff;
}

@-webkit-keyframes neon {
  from {
    text-shadow: 0 0 5px #fff, 0 0 20px #fff, 0 0 30px #fff, 0 0 40px #405c71, 0 0 70px #405c71, 0 0 80px #405c71, 0 0 100px #405c71, 0 0 150px #405c71;
  }
  to {
    text-shadow: 0 0 5px #fff, 0 0 10px #fff, 0 0 15px #fff, 0 0 20px #405c71, 0 0 35px #405c71, 0 0 40px #405c71, 0 0 50px #405c71, 0 0 75px #405c71;
  }
}

Welcome

Body:
There is no CSS selector that does what you are trying to do.

For a:hover + img to work, the image has to be directly after the link. so remove the <p> surrounding the <a>

or wrap both the link and the image inside the paragraph tag like so:

a:hover + img {
  border-color: #fff;
}

<p>
<a href="dojo/frontend/photography/index.html">Welcome</a><br/>
<img class="logo" src="dojo/frontend/photography/images/logo.png" alt="">
</p>


问:
Type-signature vs. function equation in Haskell
I'm new to Haskell and to functional programming.  I'm reading through Real World Haskell, and I've realized I'm confused by a few examples.

Specifically this is in Chapter 9, in the section "A Domain specific language for predicates", the examples which have the w x y z parameters.

I've boiled it down to this:

Why does this code compile?

```<code>f :: Int -> (Int -> Int)
f x y = x+y

main = do
  let q = f 4 5
  putStr  (show (q))
</code>```

According to the type signature, f is clearly accepting 1 parameter and returning a function.
However, it seems I can write the function equation so it will accept two parameters and return an int.
Why is this possible?  Does this mean the type signature is ignored?

Is this currying?  Is this some kind of closure?
If I understand this http://www.haskell.org/haskellwiki/Currying correctly, then it seems to be somewhat in reverse to currying as defined there - my f function is taking multiple arguments instead of a single one!

Also, can anyone answering please provide a link to some sort of Haskell documentation where this ability is stated (if possible at all).

EDIT:

After thinking about this for some time, what you two seem to be implying is that:

1) This syntax is syntactic sugar, f will always have a single parameter, no matter how many parameters are written in the equation

2) Upon application of f, the function body will (always?) be transformed into a stub (in effect, the returned function), where x is fixed to the parameter given (4), and y is a parameter.

3) Then this new function is applied to 5 which replaces y, and then the + function is evaluated.

What I was really interested in was, where exactly does it say something like "in the function equation, if you write more than one parameter, it's really syntactic sugar, and the following actually happens..." as I wrote above.
Or is that so obvious to everyone except me?

Edit II:

The real eye-opener answer was in @luqui comment below, unfortunately I don't think I can mark a comment as an answer.

It is the fact that
f x y = ...
is actually syntactic sugar for:
f = \x -> \y -> ...

And for me, everything else everyone below said follows from this.

I found a sort of source for this in the Gentle Introduction to Haskell, here: http://haskell.cs.yale.edu/tutorial/functions.html in section 3.1, called Lambda Abstractions.

In fact, the equations:

inc x                  = x+1
    add x y                = x+y

are really shorthand for:

inc                    = \x   -> x+1
    add                    = \x y -> x+y

While it doesn't use the phrase "syntactic sugar", it uses the more, uh, mathematically oriented word "shorthand", but as a programmer I read this as "sugar" :-)

答:
The -> operator is right-associative, i.e. t -> t -> t is the same as t -> (t -> t).

If you re-write

```<code>f x y = x+y
</code>```

in the equivalent form

```<code>f x = \y -> x + y
</code>```

this conncetion should become obvious.

Body:
I'm new to Haskell and to functional programming.  I'm reading through Real World Haskell, and I've realized I'm confused by a few examples.

Specifically this is in Chapter 9, in the section "A Domain specific language for predicates", the examples which have the w x y z parameters.

I've boiled it down to this:

Why does this code compile?

f :: Int -> (Int -> Int)
f x y = x+y

main = do
  let q = f 4 5
  putStr  (show (q))

According to the type signature, f is clearly accepting 1 parameter and returning a function.
However, it seems I can write the function equation so it will accept two parameters and return an int.
Why is this possible?  Does this mean the type signature is ignored?

Is this currying?  Is this some kind of closure?
If I understand this http://www.haskell.org/haskellwiki/Currying correctly, then it seems to be somewhat in reverse to currying as defined there - my f function is taking multiple arguments instead of a single one!

Also, can anyone answering please provide a link to some sort of Haskell documentation where this ability is stated (if possible at all).

EDIT:

After thinking about this for some time, what you two seem to be implying is that:

1) This syntax is syntactic sugar, f will always have a single parameter, no matter how many parameters are written in the equation

2) Upon application of f, the function body will (always?) be transformed into a stub (in effect, the returned function), where x is fixed to the parameter given (4), and y is a parameter.

3) Then this new function is applied to 5 which replaces y, and then the + function is evaluated.

What I was really interested in was, where exactly does it say something like "in the function equation, if you write more than one parameter, it's really syntactic sugar, and the following actually happens..." as I wrote above.
Or is that so obvious to everyone except me?

Edit II:

The real eye-opener answer was in @luqui comment below, unfortunately I don't think I can mark a comment as an answer.

It is the fact that
f x y = ...
is actually syntactic sugar for:
f = \x -> \y -> ...

And for me, everything else everyone below said follows from this.

I found a sort of source for this in the Gentle Introduction to Haskell, here: http://haskell.cs.yale.edu/tutorial/functions.html in section 3.1, called Lambda Abstractions.

In fact, the equations:

inc x                  = x+1
    add x y                = x+y

are really shorthand for:

inc                    = \x   -> x+1
    add                    = \x y -> x+y

While it doesn't use the phrase "syntactic sugar", it uses the more, uh, mathematically oriented word "shorthand", but as a programmer I read this as "sugar" :-)

Body:
The -> operator is right-associative, i.e. t -> t -> t is the same as t -> (t -> t).

If you re-write

f x y = x+y

in the equivalent form

f x = \y -> x + y

this conncetion should become obvious.


问:
Cassandra 3.0 and later require Java 8u40 or later
I'm trying to run cassandra 3.0 in datastax. But i'm getting an error saying
Cassandra 3.0 and later require Java 8u40 or later.

I have installed java and moved the jdk1.8.0_65 to /usr/local/java and set JAVA_HOME to /usr/local/java/jdk1.8.0_65.

But I'm still facing the following error:

Cassandra 3.0 and later require Java 8u40 or later.

答:
Try to use alternatives command:

```<code>$ nodetool
Cassandra 3.0 and later require Java 8u40 or later.
$ java -version
java version "1.7.0_151"

$ sudo yum install java-1.8.0-openjdk
...
$ sudo alternatives --config java

There are 2 programs which provide 'java'.

Selection    Command
-----------------------------------------------
*+ 1           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
2           /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java

Enter to keep the current selection[+], or type selection number: 2

$ java -version
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
$ nodetool
usage: nodetool [(-p <port> | --port <port>)]
    [(-pwf <passwordFilePath> | --password-file <passwordFilePath>)]
    [(-h <host> | --host <host>)] [(-u <username> | --username <username>)]
    [(-pw <password> | --password <password>)] <command> [<args>]
</code>```

Body:
Try to use alternatives command:

$ nodetool
Cassandra 3.0 and later require Java 8u40 or later.
$ java -version
java version "1.7.0_151"

$ sudo yum install java-1.8.0-openjdk
...
$ sudo alternatives --config java

There are 2 programs which provide 'java'.

Selection    Command
-----------------------------------------------
*+ 1           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
2           /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java

Enter to keep the current selection[+], or type selection number: 2

$ java -version
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
$ nodetool
usage: nodetool [(-p <port> | --port <port>)]
    [(-pwf <passwordFilePath> | --password-file <passwordFilePath>)]
    [(-h <host> | --host <host>)] [(-u <username> | --username <username>)]
    [(-pw <password> | --password <password>)] <command> [<args>]


问:
SQL Query to get data from various databases
I wrote the below query to pull the data from different databases. I have created two temp tables to pull the data from two different databases and finally a select statement from the original database to join all the tables. My query is getting executed but not getting any data.(Report is blank). I tried executing the two temp tables separately. it is giving the correct data. But when I execute the whole query, the result is blank. Below is the query. Please help.</p>

```<code>"set fmtonly off

use GODSDB

IF object_id('tempdb..#CISIS_Call_Log') IS NOT NULL DROP TABLE #CISIS_Call_Log
select *
into #CISIS_Call_Log
from OPENQUERY (CSISDB,
'select
ccl.ContractOID,
ccl.db_insertdate,
ccl.ContractCallLogStatusIdentifier,
ccl.db_UpdateDate,
ccp.ContractCallLogPurposeOID,
ccp.ContractCallLogPurposeIdentifier,
ccp.Description
from csisdb.dbo.ContractCallLog CCL
inner join csisdb.dbo.ContractCallLogPurpose CCP on ccl.ContractCallLogPurposeIdentifier = ccp.ContractCallLogPurposeIdentifier
where JurisdictionShortIdentifier = ''ON''
AND  ContractCallLogStatusIdentifier IN (''DNR'', ''NR'')
')

IF object_id('tempdb..#CMS_Campaign') IS NOT NULL DROP TABLE #CMS_Campaign
select *
into #CMS_Campaign
from OPENQUERY (BA_GBASSTOCMS, '
Select
SystemSourceIdentifier,
ContractOID,
OfferSentDate,
CampaignOfferTypeIdentifier,
CampaignContractStatusIdentifier,
CampaignContractStatusUpdateDate,
DeclineDate,
CampaignOfferOID,
CampaignOID,
CampaignStartDate,
CampaignEndDate,
Jurisdiction,
CampaignDescription
from CMS.dbo.vw_CampaignInfo
where Jurisdiction = ''ON''
and CampaignOfferTypeIdentifier = ''REN''
')

select mp.CommodityTypeIdentifier as Commodity
,c.RtlrContractIdentifier as ContractID
,cs.ContractStatusIdentifier as ContractStatus
,c.SigningDate
,cf.StartDate as FlowStartDate
,cf.EndDate as FlowEndDate
,datediff(day, getdate(), c.RenewalDate) as RemainingDays
,c.RenewalDate
,l.ContractCallLogStatusIdentifier as CallLogType
,Substring (l.Description, 1, 20) as CallPurpose
,l.db_insertDate as CallLogDate
,cms.CampaignOfferOID as OfferID
,cms.CampaignContractStatusIdentifier as OfferStatus
,cms.CampaignContractStatusUpdateDate as StatusChangeDate
,cms.DeclineDate
from Contract c
inner join contractstate cs on cs.contractoid = c.ContractOID
and cs.ContractStatusIdentifier in ('ERA', 'FLW')
and datediff(day, getdate(), c.RenewalDate) > 60
inner join SiteIdentification si on si.SiteOID = c.SiteOID
inner join MarketParticipant mp on mp.MarketParticipantOID = si.MarketParticipantOID
inner join Market m on m.MarketOID = mp.MarketOID
inner join Jurisdiction j on j.JurisdictionOID = m.JurisdictionOID
and j.CountryCode = 'CA'
and j.ProvinceOrStateCode = 'ON'
inner join ContractFlow cf on cf.ContractOID = c.ContractOID
inner join #CISIS_Call_Log l on convert(varchar(15), l.ContractOID) = c.RtlrContractIdentifier
inner join #CMS_Campaign cms on convert(varchar(15), cms.ContractOID) = c.RtlrContractIdentifier

set fmtonly on"
</code>```

答:
IF the data in each temp table is verified, then:

Try a smaller, less complex, query to test your temp tables with. Also try them using a LEFT join as well e.g.:

```<code>select
      c.RtlrContractIdentifier as ContractID
    , c.SigningDate
    , datediff(day, getdate(), c.RenewalDate) as RemainingDays
    , c.RenewalDate
    , l.ContractCallLogStatusIdentifier as CallLogType
    , Substring (l.Description, 1, 20) as CallPurpose
    , l.db_insertDate as CallLogDate
    , cms.CampaignOfferOID as OfferID
    , cms.CampaignContractStatusIdentifier as OfferStatus
    , cms.CampaignContractStatusUpdateDate as StatusChangeDate
    , cms.DeclineDate
from Contract c
LEFT join #CISIS_Call_Log l on convert(varchar(15), l.ContractOID) = c.RtlrContractIdentifier
LEFT join #CMS_Campaign cms on convert(varchar(15), cms.ContractOID) = c.RtlrContractIdentifier
</code>```

Does this return data? Does it return data from both joined tables?

If neither temp table is returning data then those join conditions need to be changed.

If both temp tables do return data from that query, then try INNER joins. If that still works, then add back more joins (one at a time) until you identify the join that causes the overall fault.

Without data for every table it just isn't possible for us to pinpoint the exact reason for a NULL result. Only you can, so you need to trouble-shoot the problem one step at a time.

Body:
I wrote the below query to pull the data from different databases. I have created two temp tables to pull the data from two different databases and finally a select statement from the original database to join all the tables. My query is getting executed but not getting any data.(Report is blank). I tried executing the two temp tables separately. it is giving the correct data. But when I execute the whole query, the result is blank. Below is the query. Please help.

"set fmtonly off

use GODSDB

IF object_id('tempdb..#CISIS_Call_Log') IS NOT NULL DROP TABLE #CISIS_Call_Log
select *
into #CISIS_Call_Log
from OPENQUERY (CSISDB,
'select
ccl.ContractOID,
ccl.db_insertdate,
ccl.ContractCallLogStatusIdentifier,
ccl.db_UpdateDate,
ccp.ContractCallLogPurposeOID,
ccp.ContractCallLogPurposeIdentifier,
ccp.Description
from csisdb.dbo.ContractCallLog CCL
inner join csisdb.dbo.ContractCallLogPurpose CCP on ccl.ContractCallLogPurposeIdentifier = ccp.ContractCallLogPurposeIdentifier
where JurisdictionShortIdentifier = ''ON''
AND  ContractCallLogStatusIdentifier IN (''DNR'', ''NR'')
')

IF object_id('tempdb..#CMS_Campaign') IS NOT NULL DROP TABLE #CMS_Campaign
select *
into #CMS_Campaign
from OPENQUERY (BA_GBASSTOCMS, '
Select
SystemSourceIdentifier,
ContractOID,
OfferSentDate,
CampaignOfferTypeIdentifier,
CampaignContractStatusIdentifier,
CampaignContractStatusUpdateDate,
DeclineDate,
CampaignOfferOID,
CampaignOID,
CampaignStartDate,
CampaignEndDate,
Jurisdiction,
CampaignDescription
from CMS.dbo.vw_CampaignInfo
where Jurisdiction = ''ON''
and CampaignOfferTypeIdentifier = ''REN''
')

select mp.CommodityTypeIdentifier as Commodity
,c.RtlrContractIdentifier as ContractID
,cs.ContractStatusIdentifier as ContractStatus
,c.SigningDate
,cf.StartDate as FlowStartDate
,cf.EndDate as FlowEndDate
,datediff(day, getdate(), c.RenewalDate) as RemainingDays
,c.RenewalDate
,l.ContractCallLogStatusIdentifier as CallLogType
,Substring (l.Description, 1, 20) as CallPurpose
,l.db_insertDate as CallLogDate
,cms.CampaignOfferOID as OfferID
,cms.CampaignContractStatusIdentifier as OfferStatus
,cms.CampaignContractStatusUpdateDate as StatusChangeDate
,cms.DeclineDate
from Contract c
inner join contractstate cs on cs.contractoid = c.ContractOID
and cs.ContractStatusIdentifier in ('ERA', 'FLW')
and datediff(day, getdate(), c.RenewalDate) > 60
inner join SiteIdentification si on si.SiteOID = c.SiteOID
inner join MarketParticipant mp on mp.MarketParticipantOID = si.MarketParticipantOID
inner join Market m on m.MarketOID = mp.MarketOID
inner join Jurisdiction j on j.JurisdictionOID = m.JurisdictionOID
and j.CountryCode = 'CA'
and j.ProvinceOrStateCode = 'ON'
inner join ContractFlow cf on cf.ContractOID = c.ContractOID
inner join #CISIS_Call_Log l on convert(varchar(15), l.ContractOID) = c.RtlrContractIdentifier
inner join #CMS_Campaign cms on convert(varchar(15), cms.ContractOID) = c.RtlrContractIdentifier

set fmtonly on"

Body:
IF the data in each temp table is verified, then:

Try a smaller, less complex, query to test your temp tables with. Also try them using a LEFT join as well e.g.:

select
      c.RtlrContractIdentifier as ContractID
    , c.SigningDate
    , datediff(day, getdate(), c.RenewalDate) as RemainingDays
    , c.RenewalDate
    , l.ContractCallLogStatusIdentifier as CallLogType
    , Substring (l.Description, 1, 20) as CallPurpose
    , l.db_insertDate as CallLogDate
    , cms.CampaignOfferOID as OfferID
    , cms.CampaignContractStatusIdentifier as OfferStatus
    , cms.CampaignContractStatusUpdateDate as StatusChangeDate
    , cms.DeclineDate
from Contract c
LEFT join #CISIS_Call_Log l on convert(varchar(15), l.ContractOID) = c.RtlrContractIdentifier
LEFT join #CMS_Campaign cms on convert(varchar(15), cms.ContractOID) = c.RtlrContractIdentifier

Does this return data? Does it return data from both joined tables?

If neither temp table is returning data then those join conditions need to be changed.

If both temp tables do return data from that query, then try INNER joins. If that still works, then add back more joins (one at a time) until you identify the join that causes the overall fault.

Without data for every table it just isn't possible for us to pinpoint the exact reason for a NULL result. Only you can, so you need to trouble-shoot the problem one step at a time.


问:
React Native FAILURE: Build failed with an exception. Could not resolve ':classpath'. Could not find com.android.tools.build:gradle:3.0.1
When I make the command "react-native run-android" then it happened:

FAILURE: Build failed with an exception.

What went wrong:
A problem occurred configuring root project 'AsomeProject'.

Could not resolve all files for configuration ':classpath'.
  Could not find com.android.tools.build:gradle:3.0.1.
   Searched in the following locations:
       https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle                                                               -3.0.1.pom
       https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle                                                               -3.0.1.jar

screenshot:

答:
I added google() and mavenlocal() to the buildscript

```<code>buildscript {
    repositories {
        google()
        mavenLocal()
        jcenter()
    }
    ....
}
</code>```

Body:
I added google() and mavenlocal() to the buildscript

buildscript {
    repositories {
        google()
        mavenLocal()
        jcenter()
    }
    ....
}


问:
Android webview not work js function
I use android webview, it loads the page and after loading the javascript function calls, but it does not work. For the test I ran alert function, it works well.

Settings webview:

```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webView = (WebView) findViewById(R.id.webView);
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setJavaScriptEnabled(true);

    webView.addJavascriptInterface(new myJavaScriptInterface(), "CallToAnAndroidFunction");
    if (Build.VERSION.SDK_INT >= 19) {
        // chromium, enable hardware acceleration
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    } else {
        // older android version, disable hardware acceleration
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    webView.loadUrl("url");
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            // Make a note that the page has finished loading.
            authorization();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

        }
    });

private void authorization() {
      webView.loadUrl("javascript:appReg(" + deviceId + "," + "promoCode);");
    }
</code>```

Not work
    webView.loadUrl("javascript:appReg(" + deviceId + "," + "promoCode);");

If call webView.loadUrl("javascript:alert('asd')");, it work

答:
```<code>webView.loadUrl("javascript:appReg(" + deviceId + "," + "promoCode);");
</code>```

need add '' webView.loadUrl("javascript:appReg('" + deviceId + "," + "promoCode);'");

Title: Android webview not work js function

Body:
I use android webview, it loads the page and after loading the javascript function calls, but it does not work. For the test I ran alert function, it works well.

Settings webview:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webView = (WebView) findViewById(R.id.webView);
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setJavaScriptEnabled(true);

    webView.addJavascriptInterface(new myJavaScriptInterface(), "CallToAnAndroidFunction");
    if (Build.VERSION.SDK_INT >= 19) {
        // chromium, enable hardware acceleration
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    } else {
        // older android version, disable hardware acceleration
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    webView.loadUrl("url");
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            // Make a note that the page has finished loading.
            authorization();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

        }
    });

private void authorization() {
      webView.loadUrl("javascript:appReg(" + deviceId + "," + "promoCode);");
    }

Not work
    webView.loadUrl("javascript:appReg(" + deviceId + "," + "promoCode);");

If call webView.loadUrl("javascript:alert('asd')");, it work

Body:
webView.loadUrl("javascript:appReg(" + deviceId + "," + "promoCode);");

need add '' webView.loadUrl("javascript:appReg('" + deviceId + "," + "promoCode);'");


问:
How to make "Go back to initial StackNavigator Screen when TabNavigator's Tab is pressed"

Intro

Just like Facebook, Instagram, and any other mobile app, I want to implement 'go back to initial screen in Stacknavigator'

if user press the button,

it goes back to the very first page.

Simple Use Case

see TabNavigator

Goes to 'Feed' Tab

Goes to 'User' Screen

Goes to another 'User' Screen

PRESS the Main Tab Icon - 'Feed'}

Goes BACK to 'Feed' Tab // so you won't see the 'back' button

And please leave a comment if you don't understand this use case, I will draw its state flow for you

Code for the icon on my Main TabNavigator.

```<code>navigationOptions: ({ navigation }) => ({
      header: null,
      tabBarIcon: ({ focused }) => {
          const { routeName } = navigation.state;
          ....
          return (
              <TochableWithoutFeedback onPress={()=>{navigation.goback(iconName)}>
              // undefined is not a function when I press the Button
              // deeper screen. (not getting any error on Main)
                  <Ionicons
                      name={iconName}
                      size={30}
                      style={{ marginBottom: -3 }}
                      color={focused ? Colors.tabIconSelected : Colors.tabIconDefault}
                      />
             <TochableWithoutFeedback>
         );
  },
</code>```

答:
actually, it depends on how many deep is your routing like Instagram 2 to 3 deep routing else are tabs

so you can reset your router or go back to the main router by using

```<code>this.props.navigation.goBack(null)
</code>```

for eg.

Tab navigation child ahs Stack navigation so in Stack, you can do something like

```<code>// Anyone watching this, please check your react-navigation version
// I'm using ^1.0.0-beta.21.
// props for tabBarOnpress varies can be varied (Editor John Baek)
tabBarOnPress: ({scene, jumpToIndex}) => {
      jumpToIndex(scene.index)
      navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({ routeName: 'home' }) // go to first screen of the StackNavigator
        ]
      }))
    }
</code>```

so whenever someone press Home Tab then all route reset and you see Feed screen  just like Instagram

```<code>TabNavigation
  -Home
      |
      StakeNavigation
                    |
                    mainScreen //main of home
                    Subrouts
                    RouteToProfile //just like insta

  -Search
        |
         StakeNavigation
                       |
                       mainScreen //main of search
                       searchResult //if people serch some specific
</code>```

and go on...  so reset route at stakeNavigation level of Tab

```<code>const SubHome = StackNavigator({
  Home: { screen: Home },
  Home2: { screen: Home2 },
  Home3 : { screen: Home3 },
},{
  navigationOptions:({navigation,screenProps})=>({
    tabBarLabel: I18n.t('tab_car'),
    tabBarIcon: ({ tintColor }) => (
      <CustomIcon name={'Home'} width={28} height={30} fill={tintColor} />
    ),
    tabBarOnPress: (tab, jumpToIndex) => {
      jumpToIndex(tab.index)
      navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({ routeName: 'Home' }) // go to first screen of the StackNavigator
        ]
      }))
    }
  }),
  headerMode:'none'
});
</code>```

Body:
Intro

Just like Facebook, Instagram, and any other mobile app, I want to implement 'go back to initial screen in Stacknavigator'

if user press the button,

it goes back to the very first page.

Simple Use Case

see TabNavigator

Goes to 'Feed' Tab

Goes to 'User' Screen

Goes to another 'User' Screen

PRESS the Main Tab Icon - 'Feed'}

Goes BACK to 'Feed' Tab // so you won't see the 'back' button

And please leave a comment if you don't understand this use case, I will draw its state flow for you

Code for the icon on my Main TabNavigator.

navigationOptions: ({ navigation }) => ({
      header: null,
      tabBarIcon: ({ focused }) => {
          const { routeName } = navigation.state;
          ....
          return (
              <TochableWithoutFeedback onPress={()=>{navigation.goback(iconName)}>
              // undefined is not a function when I press the Button
              // deeper screen. (not getting any error on Main)
                  <Ionicons
                      name={iconName}
                      size={30}
                      style={{ marginBottom: -3 }}
                      color={focused ? Colors.tabIconSelected : Colors.tabIconDefault}
                      />
             <TochableWithoutFeedback>
         );
  },

Body:
actually, it depends on how many deep is your routing like Instagram 2 to 3 deep routing else are tabs

so you can reset your router or go back to the main router by using

this.props.navigation.goBack(null)

for eg.

Tab navigation child ahs Stack navigation so in Stack, you can do something like

// Anyone watching this, please check your react-navigation version
// I'm using ^1.0.0-beta.21.
// props for tabBarOnpress varies can be varied (Editor John Baek)
tabBarOnPress: ({scene, jumpToIndex}) => {
      jumpToIndex(scene.index)
      navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({ routeName: 'home' }) // go to first screen of the StackNavigator
        ]
      }))
    }

so whenever someone press Home Tab then all route reset and you see Feed screen  just like Instagram

TabNavigation
  -Home
      |
      StakeNavigation
                    |
                    mainScreen //main of home
                    Subrouts
                    RouteToProfile //just like insta

  -Search
        |
         StakeNavigation
                       |
                       mainScreen //main of search
                       searchResult //if people serch some specific

and go on...  so reset route at stakeNavigation level of Tab

const SubHome = StackNavigator({
  Home: { screen: Home },
  Home2: { screen: Home2 },
  Home3 : { screen: Home3 },
},{
  navigationOptions:({navigation,screenProps})=>({
    tabBarLabel: I18n.t('tab_car'),
    tabBarIcon: ({ tintColor }) => (
      <CustomIcon name={'Home'} width={28} height={30} fill={tintColor} />
    ),
    tabBarOnPress: (tab, jumpToIndex) => {
      jumpToIndex(tab.index)
      navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({ routeName: 'Home' }) // go to first screen of the StackNavigator
        ]
      }))
    }
  }),
  headerMode:'none'
});


答:
The usual and simple way to do this is to put something like:

```<code>if [[ -f /tmp/myscript.running ]] ; then
    exit
fi
touch /tmp/myscript.running
</code>```

at the top of you script and

```<code>rm -f /tmp/myscript.running
</code>```

at the end, and in trap functions in case it doesn't reach the end.

This still has a few potential problems (such as a race condition at the top) but will do for the vast majority of cases.

Title: Shell script: Ensure that script isn't executed if already running

Body:
Possible Duplicate:

  Quick-and-dirty way to ensure only one instance of a shell script is running at a time

I've set up a cronjob to backup my folders properly which I am quite proud of. However I've found out, by looking at the results from the backups, that my backup script has been called more than once by Crontab, resulting in multiple backups running at the same time.

Is there any way I can ensure that a certain shell script to not run if the very same script already is executing?

Body:
The usual and simple way to do this is to put something like:

if [[ -f /tmp/myscript.running ]] ; then
    exit
fi
touch /tmp/myscript.running

at the top of you script and

rm -f /tmp/myscript.running

at the end, and in trap functions in case it doesn't reach the end.

This still has a few potential problems (such as a race condition at the top) but will do for the vast majority of cases.


问:
Can't build iOS project with boost: error: linker command failed with exit code 1 (use -v to see invocation)
I append Boost to my iOS project via brew package manager:

```<code>brew install boost
</code>```

Then add header path to project settings:

```<code>/usr/local/**
</code>```

And now project doesn't builds with error:

```
ld: file not found: ~/Library/Developer/Xcode/DerivedData/ios-hgivqqzmkrkxlvdazbhavxnxtxod/Build/Intermediates/ios.build/Debug-iphonesimulator/ios.build/Objects-normal/x86_64/TLRPCmessages_searchGifs.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```

DerivedData/.../x86_64 folder doesn't contains any *.o files (only .d, .dia and .dat), why it talks only about one?

Also I tried change header path to non-recursive: /usr/local/Cellar/boost/1.60.0_1/include, and
build errors became as in this question

But I can't understand answers - #include <cstddef> already exists inside boost, compiler is Apple LLVM:

How can I fix this bugs?

答:
I solved my problem manually but did not remember how. Anyway my solution was bad because of application size enlarged over 100 Mbytes!

CocoaPods helped me, boost pod already exists .

Just add row to Podfile:

```<code>pod 'boost'
</code>```

and run pod install in project directory. With this pod project was built without errors and application size was not so huge.

Body:
I append Boost to my iOS project via brew package manager:

brew install boost

Then add header path to project settings:

/usr/local/**

And now project doesn't builds with error:

ld: file not found: ~/Library/Developer/Xcode/DerivedData/ios-hgivqqzmkrkxlvdazbhavxnxtxod/Build/Intermediates/ios.build/Debug-iphonesimulator/ios.build/Objects-normal/x86_64/TLRPCmessages_searchGifs.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)

DerivedData/.../x86_64 folder doesn't contains any *.o files (only .d, .dia and .dat), why it talks only about one?

Also I tried change header path to non-recursive: /usr/local/Cellar/boost/1.60.0_1/include, and
build errors became as in this question

But I can't understand answers - #include <cstddef> already exists inside boost, compiler is Apple LLVM:

How can I fix this bugs?

Body:
I solved my problem manually but did not remember how. Anyway my solution was bad because of application size enlarged over 100 Mbytes!

CocoaPods helped me, boost pod already exists .

Just add row to Podfile:

pod 'boost'

and run pod install in project directory. With this pod project was built without errors and application size was not so huge.


问:
Why getting this error in tensorflow?
```<code>m = tf.Variable(0.44)
b = tf.Variable(0.87)
error = 0
for x, y in zip(x_data, y_label):
    y_hat = m*x+b
    error +=(y-y_label)**2
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.001)
train = optimizer.minimize(error)
</code>```

AttributeError                            Traceback (most recent call
  last)  in ()
        1 optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.001)
  ----> 2 train = optimizer.minimize(error)

C:\Users\ASUS
  PC\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py
  in minimize(self, loss, global_step, var_list, gate_gradients,
  aggregation_method, colocate_gradients_with_ops, name, grad_loss)
      341         aggregation_method=aggregation_method,
      342         colocate_gradients_with_ops=colocate_gradients_with_ops,
  --> 343         grad_loss=grad_loss)
      344
      345     vars_with_grad = [v for g, v in grads_and_vars if g is not None]

C:\Users\ASUS
  PC\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py
  in compute_gradients(self, loss, var_list, gate_gradients,
  aggregation_method, colocate_gradients_with_ops, grad_loss)
      392                        "Optimizer.GATE_OP, Optimizer.GATE_GRAPH.  Not %s" %
      393                        gate_gradients)
  --> 394     self._assert_valid_dtypes([loss])
      395     if grad_loss is not None:
      396       self._assert_valid_dtypes([grad_loss])

C:\Users\ASUS
  PC\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py
  in _assert_valid_dtypes(self, tensors)
      541     valid_dtypes = self._valid_dtypes()
      542     for t in tensors:
  --> 543       dtype = t.dtype.base_dtype
      544       if dtype not in valid_dtypes:
      545         raise ValueError(

AttributeError: 'numpy.dtype' object has no attribute 'base_dtype'

答:
Because optimizer.minimize accepts only Tensor variables.

The rest of the code is not actually correct as well, it should look similar to:

```<code>x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
m = tf.Variable(0.44)
b = tf.Variable(0.87)

y_hat = m * x + b

error = tf.squared_difference(y, y_hat)
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.001)
train = optimizer.minimize(error)
number_of_iterations = 100000
with tf.Session() as sess:
    for _ in xrange(0, number_of_iterations):
        sess.run(train, {x:x_data, y: y_label}}
        #If you want to see the loss:
        #loss = sess.run(error,{x:x_data, y: y_label})
        #print("Current loss is:" + str(loss))
</code>```

Title: Why getting this error in tensorflow?

Body:
m = tf.Variable(0.44)
b = tf.Variable(0.87)
error = 0
for x, y in zip(x_data, y_label):
    y_hat = m*x+b
    error +=(y-y_label)**2
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.001)
train = optimizer.minimize(error)

AttributeError                            Traceback (most recent call
  last)  in ()
        1 optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.001)
  ----> 2 train = optimizer.minimize(error)

C:\Users\ASUS
  PC\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py
  in minimize(self, loss, global_step, var_list, gate_gradients,
  aggregation_method, colocate_gradients_with_ops, name, grad_loss)
      341         aggregation_method=aggregation_method,
      342         colocate_gradients_with_ops=colocate_gradients_with_ops,
  --> 343         grad_loss=grad_loss)
      344
      345     vars_with_grad = [v for g, v in grads_and_vars if g is not None]

C:\Users\ASUS
  PC\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py
  in compute_gradients(self, loss, var_list, gate_gradients,
  aggregation_method, colocate_gradients_with_ops, grad_loss)
      392                        "Optimizer.GATE_OP, Optimizer.GATE_GRAPH.  Not %s" %
      393                        gate_gradients)
  --> 394     self._assert_valid_dtypes([loss])
      395     if grad_loss is not None:
      396       self._assert_valid_dtypes([grad_loss])

C:\Users\ASUS
  PC\Anaconda3\lib\site-packages\tensorflow\python\training\optimizer.py
  in _assert_valid_dtypes(self, tensors)
      541     valid_dtypes = self._valid_dtypes()
      542     for t in tensors:
  --> 543       dtype = t.dtype.base_dtype
      544       if dtype not in valid_dtypes:
      545         raise ValueError(

AttributeError: 'numpy.dtype' object has no attribute 'base_dtype'

Body:
Because optimizer.minimize accepts only Tensor variables.

The rest of the code is not actually correct as well, it should look similar to:

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
m = tf.Variable(0.44)
b = tf.Variable(0.87)

y_hat = m * x + b

error = tf.squared_difference(y, y_hat)
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.001)
train = optimizer.minimize(error)
number_of_iterations = 100000
with tf.Session() as sess:
    for _ in xrange(0, number_of_iterations):
        sess.run(train, {x:x_data, y: y_label}}
        #If you want to see the loss:
        #loss = sess.run(error,{x:x_data, y: y_label})
        #print("Current loss is:" + str(loss))


问:
Sum up all matching elements in an array
How can I sum up all of the matching elements in an array? I currently trying to use a nested for loop, but if a number occurs more than 2 times it won't sum up the total correctly.I feel like am missing something small here.

```<code>public class Game {
ColoredDice dice[] = new ColoredDice[6];
private int diceValues[] = new int[6];

public Game() {
    rollSixDice();
    score();
}

public void rollSixDice(){
    for(int i = 0;i < 6;i++){
        dice[i] = new ColoredDice();
    }
    // getDiceValue returns the int value of the die
    for(int i =0;i<dice.length;i++){
        diceValues[i] = dice[i].getDiceValue();
    }
}

public void score(){
    for(int i=0;i<dice.length;i++){
        for(int j = i+1 ;j < 6;j++){
            if(dice[i].getDiceValue() == diceValues[j]){
                score += dice[i].getDiceValue();
            }
        }
    }
    System.out.println(score);
  }
}

public class DiceTester {
public static void main(String[] args) {
new Game();
  }
}
</code>```

To be clear more then what on what happens..
Both arrays here are identical and are of type int.
Example role values: 2,3,4,2,6,6.
Score:8

答:
Can you try this,</p>

```<code>for(int i=0;i < dice.length;i++){
        for(int j =i+1;j < dice.length;j++){
            if(dice[i].getDiceValue() == dice[j].getDiceValue()){
                score += dice[i].getDiceValue();
            }
        }
    }
</code>```

Body:
How can I sum up all of the matching elements in an array? I currently trying to use a nested for loop, but if a number occurs more than 2 times it won't sum up the total correctly.I feel like am missing something small here.

public class Game {
ColoredDice dice[] = new ColoredDice[6];
private int diceValues[] = new int[6];

public Game() {
    rollSixDice();
    score();
}

public void rollSixDice(){
    for(int i = 0;i < 6;i++){
        dice[i] = new ColoredDice();
    }
    // getDiceValue returns the int value of the die
    for(int i =0;i<dice.length;i++){
        diceValues[i] = dice[i].getDiceValue();
    }
}

public void score(){
    for(int i=0;i<dice.length;i++){
        for(int j = i+1 ;j < 6;j++){
            if(dice[i].getDiceValue() == diceValues[j]){
                score += dice[i].getDiceValue();
            }
        }
    }
    System.out.println(score);
  }
}

public class DiceTester {
public static void main(String[] args) {
new Game();
  }
}

To be clear more then what on what happens..
Both arrays here are identical and are of type int.
Example role values: 2,3,4,2,6,6.
Score:8

Body:
Can you try this,

for(int i=0;i < dice.length;i++){
        for(int j =i+1;j < dice.length;j++){
            if(dice[i].getDiceValue() == dice[j].getDiceValue()){
                score += dice[i].getDiceValue();
            }
        }
    }


问:
SpringBoot's @MultipartConfig maxFileSize not taking effect
I have a controller with a MultipartConfig annotation (a snippet of which is show below):

```<code>@RestController
@RequestMapping("packages")
@MultipartConfig(maxFileSize = 1024*1024*1024, maxRequestSize = 1024*1024*1024)
public class PackagesController
{
    @RequestMapping(method = RequestMethod.POST)
    public String create(@RequestParam("package") MultipartFile uploadedPackage)
    {
        // do stuff to the file
        return "create";
    }
}
</code>```

When I upload a file to this endpoint, though, it appears to be using the default multipart config values:

```<code>Caused by: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field package exceeds its maximum permitted size of 1048576 bytes.
    at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl$FileItemStreamImpl$1.raiseError(FileUploadBase.java:633) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit(LimitedInputStream.java:76) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:135) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at java.io.FilterInputStream.read(FilterInputStream.java:107) ~[na:1.8.0_45]
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:98) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:68) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:293) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.catalina.connector.Request.parseParts(Request.java:2776) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    ... 30 common frames omitted
</code>```

My application looks like this:

```<code>@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

}
</code>```

Is there something I'm missing that allows the @MultipartConfig annotation to take effect?

答:
For setting custom limits for multipart uploads, the below properties are to be used(for a sample size of 30MB):

```<code>spring.http.multipart.max-file-size=30MB
spring.http.multipart.max-request-size=30MB
</code>```

In our company's projects, I found that one of them was on Spring Boot version 1.3.5, so for versions < 1.4 you should use

```<code>multipart.max-file-size=30MB
multipart.max-request-size=30MB
</code>```

From the docs(v1.4.0):

Spring Boot embraces the Servlet 3 javax.servlet.http.Part API to
  support uploading files. By default Spring Boot configures Spring MVC
  with a maximum file of 1MB per file and a maximum of 10MB of file data
  in a single request. You may override these values, as well as the
  location to which intermediate data is stored (e.g., to the /tmp
  directory) and the threshold past which data is flushed to disk by
  using the properties exposed in the MultipartProperties class. If you
  want to specify that files be unlimited, for example, set the
  spring.http.multipart.max-file-size property to -1.

The multipart support is helpful when you want to receive multipart
  encoded file data as a @RequestParam-annotated parameter of type
  MultipartFile in a Spring MVC controller handler method.

Same docs for version 1.3.8:

If you want to specify that files be unlimited, for example, set the
  multipart.maxFileSize property to -1.

Body:
I have a controller with a MultipartConfig annotation (a snippet of which is show below):

@RestController
@RequestMapping("packages")
@MultipartConfig(maxFileSize = 1024*1024*1024, maxRequestSize = 1024*1024*1024)
public class PackagesController
{
    @RequestMapping(method = RequestMethod.POST)
    public String create(@RequestParam("package") MultipartFile uploadedPackage)
    {
        // do stuff to the file
        return "create";
    }
}

When I upload a file to this endpoint, though, it appears to be using the default multipart config values:

Caused by: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field package exceeds its maximum permitted size of 1048576 bytes.
    at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl$FileItemStreamImpl$1.raiseError(FileUploadBase.java:633) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit(LimitedInputStream.java:76) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:135) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at java.io.FilterInputStream.read(FilterInputStream.java:107) ~[na:1.8.0_45]
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:98) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:68) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:293) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    at org.apache.catalina.connector.Request.parseParts(Request.java:2776) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
    ... 30 common frames omitted

My application looks like this:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

}

Is there something I'm missing that allows the @MultipartConfig annotation to take effect?

Body:
For setting custom limits for multipart uploads, the below properties are to be used(for a sample size of 30MB):

spring.http.multipart.max-file-size=30MB
spring.http.multipart.max-request-size=30MB

In our company's projects, I found that one of them was on Spring Boot version 1.3.5, so for versions < 1.4 you should use

multipart.max-file-size=30MB
multipart.max-request-size=30MB

From the docs(v1.4.0):

Spring Boot embraces the Servlet 3 javax.servlet.http.Part API to
  support uploading files. By default Spring Boot configures Spring MVC
  with a maximum file of 1MB per file and a maximum of 10MB of file data
  in a single request. You may override these values, as well as the
  location to which intermediate data is stored (e.g., to the /tmp
  directory) and the threshold past which data is flushed to disk by
  using the properties exposed in the MultipartProperties class. If you
  want to specify that files be unlimited, for example, set the
  spring.http.multipart.max-file-size property to -1.

The multipart support is helpful when you want to receive multipart
  encoded file data as a @RequestParam-annotated parameter of type
  MultipartFile in a Spring MVC controller handler method.

Same docs for version 1.3.8:

If you want to specify that files be unlimited, for example, set the
  multipart.maxFileSize property to -1.