问:
java.lang.OutOfMemoryError: requested 1958536 bytes for Chunk::new. Out of swap space
We are facing the below problem at our production enviournment in unpredictable manner
sometimes the server is down in a day or sometimes in a week, below is the exact error
dump, below are the settings for the server.

```
JDK: jdk1.6.0_21
Server: Tomcat 7.0.2
OS: Red Hat Enterprise Linux Server release 5.5
```

In catalina.sh the following setting has been done:

```<code>JAVA_OPTS="-Xms1024M -Xmx1536M -XX:+HeapDumpOnOutOfMemoryError -XX:+AggressiveOpts
-XX:-DisableExplicitGC  -XX:AdaptiveSizeThroughPutPolicy=0
-XX:+UsePSAdaptiveSurvivorSizePolicy
-XX:+UseAdaptiveGenerationSizePolicyAtMinorCollection
-XX:+UseAdaptiveGenerationSizePolicyAtMajorCollection -XX:PermSize=768M
-XX:MaxPermSize=768M    -XX:+PrintGCDetails -Xloggc:/tmp/gcLogs.txt"

export CATALINA_OPTS="-Dcom.sun.management.jmxremote.port=22222
-Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.password.file=/jakarta-tomcat7/apache-tomcat-7.0.2/conf
/jmxremote.password -Dcom.sun.management.jmxremote.access.file=/jakarta-tomcat7/apache-
tomcat-7.0.2/conf/jmxremote.access"
</code>```

Error Trace:-

```
#
# A fatal error has been detected by the Java Runtime Environment:
#
# java.lang.OutOfMemoryError: requested 1958536 bytes for Chunk::new. Out of swap space?
#
#  Internal Error (allocation.cpp:215), pid=18658, tid=589781904
#  Error: Chunk::new
#
# JRE version: 6.0_21-b06
# Java VM: Java HotSpot(TM) Server VM (17.0-b16 mixed mode linux-x86 )
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
#

---------------  T H R E A D  ---------------

Current thread (0x23787400):  JavaThread "CompilerThread0" daemon [_thread_in_native, id=18668, stack(0x231f5000,0x23276000)]

Stack: [0x231f5000,0x23276000],  sp=0x23272e70,  free space=1f723276000k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [libjvm.so+0x6a9262]
V  [libjvm.so+0x2b277f]
V  [libjvm.so+0x12e03c]
V  [libjvm.so+0x12e536]
V  [libjvm.so+0x5d67d0]
V  [libjvm.so+0x2f809d]
V  [libjvm.so+0x4f65a9]
V  [libjvm.so+0x27b85f]
V  [libjvm.so+0x278043]
V  [libjvm.so+0x209767]
V  [libjvm.so+0x280f8c]
V  [libjvm.so+0x280839]
V  [libjvm.so+0x66feb6]
V  [libjvm.so+0x66959e]
V  [libjvm.so+0x57a89e]
C  [libpthread.so.0+0x5832]

Current CompileTask:
C2:3230  !   org.apache.jsp.com.common.press_jsp._jspService(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V (4433 bytes)

---------------  P R O C E S S  ---------------

Java Threads: ( => current thread )
  0x09a21400 JavaThread "http-8080-exec-904" daemon [_thread_in_native, id=17126, stack(SIGTERM: [libjvm.so+0x57aaf0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
SIGQUIT: [libjvm.so+0x57aaf0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004

---------------  S Y S T E M  ---------------

OS:Red Hat Enterprise Linux Server release 5.5 (Tikanga)

uname:Linux 2.6.18-194.17.1.el5PAE #1 SMP Mon Sep 20 07:34:07 EDT 2010 i686
libc:glibc 2.5 NPTL 2.5
rlimit: STACK 10240k, CORE 0k, NPROC 114688, NOFILE 1024, AS infinity
load average:0.39 0.54 0.38

CPU:total 2 (2 cores per cpu, 1 threads per core) family 6 model 15 stepping 11, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3

Memory: 4k page, physical 6228576k(225096k free), swap 6974456k(6974352k free)

vm_info: Java HotSpot(TM) Server VM (17.0-b16) for linux-x86 JRE (1.6.0_21-b06), built on Jun 22 2010 01:04:46 by "java_re" with gcc 3.2.1-7a (J2SE release)

time: Fri Dec 10 14:01:06 2010
elapsed time: 79552 seconds
```

Thanks in advance,
Amit

答:
As stated by the other answers / comments, you are running out of memory.  Given your JVM settings, I'd say that the root cause is 99% likely to be a memory leak.

If you have been doing a lot of hot loading in the Tomcat instance, this could just be caused by that.  Hot loading is notorious for leaking memory, and there is not much you can do about it in practice ... except exit and restart your Tomcat more often.

The other possibility is that your application is leaking memory.  If this is the case then you will need to use a memory profiler to track down the leak.

The fact that the OOME caused a JVM crash is interesting, but probably not significant.  (It looks like the JVM was trying to JIT compile a class generated from a JSP when it ran out of memory.  The chunk being requested is rather large, but that probably means you have a rather large / complicated JSP.)

Body:
We are facing the below problem at our production enviournment in unpredictable manner
sometimes the server is down in a day or sometimes in a week, below is the exact error
dump, below are the settings for the server.

JDK: jdk1.6.0_21
Server: Tomcat 7.0.2
OS: Red Hat Enterprise Linux Server release 5.5

In catalina.sh the following setting has been done:

JAVA_OPTS="-Xms1024M -Xmx1536M -XX:+HeapDumpOnOutOfMemoryError -XX:+AggressiveOpts
-XX:-DisableExplicitGC  -XX:AdaptiveSizeThroughPutPolicy=0
-XX:+UsePSAdaptiveSurvivorSizePolicy
-XX:+UseAdaptiveGenerationSizePolicyAtMinorCollection
-XX:+UseAdaptiveGenerationSizePolicyAtMajorCollection -XX:PermSize=768M
-XX:MaxPermSize=768M    -XX:+PrintGCDetails -Xloggc:/tmp/gcLogs.txt"

export CATALINA_OPTS="-Dcom.sun.management.jmxremote.port=22222
-Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.password.file=/jakarta-tomcat7/apache-tomcat-7.0.2/conf
/jmxremote.password -Dcom.sun.management.jmxremote.access.file=/jakarta-tomcat7/apache-
tomcat-7.0.2/conf/jmxremote.access"

Error Trace:-

#
# A fatal error has been detected by the Java Runtime Environment:
#
# java.lang.OutOfMemoryError: requested 1958536 bytes for Chunk::new. Out of swap space?
#
#  Internal Error (allocation.cpp:215), pid=18658, tid=589781904
#  Error: Chunk::new
#
# JRE version: 6.0_21-b06
# Java VM: Java HotSpot(TM) Server VM (17.0-b16 mixed mode linux-x86 )
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
#

---------------  T H R E A D  ---------------

Current thread (0x23787400):  JavaThread "CompilerThread0" daemon [_thread_in_native, id=18668, stack(0x231f5000,0x23276000)]

Stack: [0x231f5000,0x23276000],  sp=0x23272e70,  free space=1f723276000k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [libjvm.so+0x6a9262]
V  [libjvm.so+0x2b277f]
V  [libjvm.so+0x12e03c]
V  [libjvm.so+0x12e536]
V  [libjvm.so+0x5d67d0]
V  [libjvm.so+0x2f809d]
V  [libjvm.so+0x4f65a9]
V  [libjvm.so+0x27b85f]
V  [libjvm.so+0x278043]
V  [libjvm.so+0x209767]
V  [libjvm.so+0x280f8c]
V  [libjvm.so+0x280839]
V  [libjvm.so+0x66feb6]
V  [libjvm.so+0x66959e]
V  [libjvm.so+0x57a89e]
C  [libpthread.so.0+0x5832]

Current CompileTask:
C2:3230  !   org.apache.jsp.com.common.press_jsp._jspService(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V (4433 bytes)

---------------  P R O C E S S  ---------------

Java Threads: ( => current thread )
  0x09a21400 JavaThread "http-8080-exec-904" daemon [_thread_in_native, id=17126, stack(SIGTERM: [libjvm.so+0x57aaf0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004
SIGQUIT: [libjvm.so+0x57aaf0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004

---------------  S Y S T E M  ---------------

OS:Red Hat Enterprise Linux Server release 5.5 (Tikanga)

uname:Linux 2.6.18-194.17.1.el5PAE #1 SMP Mon Sep 20 07:34:07 EDT 2010 i686
libc:glibc 2.5 NPTL 2.5
rlimit: STACK 10240k, CORE 0k, NPROC 114688, NOFILE 1024, AS infinity
load average:0.39 0.54 0.38

CPU:total 2 (2 cores per cpu, 1 threads per core) family 6 model 15 stepping 11, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3

Memory: 4k page, physical 6228576k(225096k free), swap 6974456k(6974352k free)

vm_info: Java HotSpot(TM) Server VM (17.0-b16) for linux-x86 JRE (1.6.0_21-b06), built on Jun 22 2010 01:04:46 by "java_re" with gcc 3.2.1-7a (J2SE release)

time: Fri Dec 10 14:01:06 2010
elapsed time: 79552 seconds

Thanks in advance,
Amit


来源: stackexchange

问:
Creating a flat checkbox style
I'm trying to replicate the checkboxes seen in this image:

css-custom-checkboxes

I've been using the xaml from this example as a starting point:

web.archive.org - WPF CheckBox style (inspired by android)

My requirements:

Solid background.

No border.

Checkmark area and checkmark resizes with control.

Checkmark is centered in the checkbox area.

My Code:

```<code><Style TargetType="{x:Type local:DMStyle2CheckBox}">
    <Setter Property="SnapsToDevicePixels" Value="true" />
    <Setter Property="OverridesDefaultStyle" Value="true" />
    <Setter Property="Height" Value="32" />
    <Setter Property="Width" Value="138" />
    <Setter Property="FocusVisualStyle" Value="{DynamicResource MyFocusVisualStyte}" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type CheckBox}">
                <BulletDecorator>
                    <BulletDecorator.Bullet>
                        <Grid Background="{x:Null}" Height="{TemplateBinding Height}" Width="{Binding RelativeSource={RelativeSource Self}, Path=Height, UpdateSourceTrigger=PropertyChanged}"
                              MinHeight="30" MinWidth="30" ShowGridLines="False">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="4*" />
                                <ColumnDefinition Width="2*" />
                                <ColumnDefinition Width="1*" />
                                <ColumnDefinition Width="4*" />
                                <ColumnDefinition Width="1*" />
                                <ColumnDefinition Width="5*" />
                                <ColumnDefinition Width="2*" />
                                <ColumnDefinition Width="2*" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="3*" />
                                <RowDefinition Height="1*" />
                                <RowDefinition Height="1*" />
                                <RowDefinition Height="1*" />
                                <RowDefinition Height="4*" />
                                <RowDefinition Height="6*" />
                                <RowDefinition Height="1*" />
                                <RowDefinition Height="4*" />
                            </Grid.RowDefinitions>

                            <!-- Checkmark Box -->
                            <Border Name="InnerBorder" Grid.Column="1" Grid.ColumnSpan="5" Grid.Row="2" Grid.RowSpan="5" BorderThickness="1"
                                    BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"/>

                            <!-- Checkmark -->
                            <Path x:Name="CheckMark" Data="F1 M 9.97498,1.22334L 4.6983,9.09834L 4.52164,9.09834L 0,5.19331L 1.27664,3.52165L 4.255,6.08833L 8.33331,
                                  1.52588e-005L 9.97498,1.22334 Z" Fill="{Binding CheckMarkColor, RelativeSource={RelativeSource Mode=TemplatedParent}}" Opacity="0"
                                  Stretch="Uniform" Grid.Column="2" Grid.ColumnSpan="4" Grid.Row="3" Grid.RowSpan="3" />

                            <Path Name="InderminateMark"  Grid.Column="3" Grid.Row="4" Data="M0,4 L1,5 5,1 4,0" Opacity="0"
                                  Stretch="Fill" StrokeThickness="0" Fill="#808080" />
                        </Grid>
                    </BulletDecorator.Bullet>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CheckStates">
                            <VisualState x:Name="Checked">
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckMark" Duration="0:0:0.2" To="1" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Unchecked" >
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetProperty="Opacity" Storyboard.TargetName="CheckMark" Duration="0:0:0.2" To="0" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Indeterminate">
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetProperty="Opacity" Storyboard.TargetName="InderminateMark" Duration="0:0:0.2" To="1" />
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <ContentPresenter Margin="4,0,4,0" VerticalAlignment="Center" HorizontalAlignment="Left" RecognizesAccessKey="True" />
                </BulletDecorator>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter TargetName="InnerBorder" Property="BorderBrush" Value="{Binding BorderBrush, RelativeSource={RelativeSource Mode=TemplatedParent}}"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter TargetName="CheckMark" Property="Fill" Value="{StaticResource Color.Black}" />
                        <Setter TargetName="CheckMark" Property="Stroke" Value="{StaticResource Color.Black}" />
                        <Setter TargetName="InderminateMark" Property="Fill" Value="{StaticResource Color.Black}" />
                        <Setter TargetName="InnerBorder" Property="BorderBrush" Value="{StaticResource Color.Black}" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

For the most part this code does what I want. The checkmark is the biggest issues for me. It's not centered or resizable and it overflows the checkmark area.

I've tried playing with the grid columns and rows that hold the checkmark but its becoming increasingly frustrating. Ideally I would like to get rid of the grid columns and rows but haven't had much luck with that either.

I've looked at every SO question about wpf checkbox styles I could find and have searched for any other online resources but most of them don't come close to what I want. I even attempted to modify the default template with Expression Blend but that didn't work out either.

答:
you can set a style</p>

```<code><Style TargetType="CheckBox" x:Key="Flat_CheckBox">
    <Setter Property="HorizontalAlignment" Value="Stretch"/>
    <Setter Property="VerticalAlignment" Value="Top"/>
    <Setter Property="MinWidth" Value="60"/>
    <Setter Property="UIElement.SnapsToDevicePixels" Value="True"/>
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
    <Setter Property="ScrollViewer.CanContentScroll" Value="True"/>
    <Setter Property="TextElement.Foreground" Value="Black"/>
    <Setter Property="FrameworkElement.FocusVisualStyle" Value="{x:Null}"/>
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Background" Value="White" />

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="LightSkyBlue" />
        </Trigger>
    </Style.Triggers>

</Style>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Creating a flat checkbox style

Body:
I'm trying to replicate the checkboxes seen in this image:

css-custom-checkboxes

I've been using the xaml from this example as a starting point:

web.archive.org - WPF CheckBox style (inspired by android)

My requirements:

Solid background.

No border.

Checkmark area and checkmark resizes with control.

Checkmark is centered in the checkbox area.

My Code:

For the most part this code does what I want. The checkmark is the biggest issues for me. It's not centered or resizable and it overflows the checkmark area.

I've tried playing with the grid columns and rows that hold the checkmark but its becoming increasingly frustrating. Ideally I would like to get rid of the grid columns and rows but haven't had much luck with that either.

I've looked at every SO question about wpf checkbox styles I could find and have searched for any other online resources but most of them don't come close to what I want. I even attempted to modify the default template with Expression Blend but that didn't work out either.

Body:
you can set a style

<Style TargetType="CheckBox" x:Key="Flat_CheckBox">
    <Setter Property="HorizontalAlignment" Value="Stretch"/>
    <Setter Property="VerticalAlignment" Value="Top"/>
    <Setter Property="MinWidth" Value="60"/>
    <Setter Property="UIElement.SnapsToDevicePixels" Value="True"/>
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
    <Setter Property="ScrollViewer.CanContentScroll" Value="True"/>
    <Setter Property="TextElement.Foreground" Value="Black"/>
    <Setter Property="FrameworkElement.FocusVisualStyle" Value="{x:Null}"/>
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Background" Value="White" />

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="LightSkyBlue" />
        </Trigger>
    </Style.Triggers>

</Style>


问:
Cassandra CQL alternative to OR in WHERE clause
Here's the code I used to create the table:

```<code>CREATE TABLE test.packages (
     packageuuid timeuuid,
     ruserid text,
     suserid text,
     timestamp int,
     PRIMARY KEY (ruserid, suserid, packageuuid, timestamp)
);
</code>```

and then I create a materialized view:

```<code>CREATE MATERIALIZED VIEW test.packages_by_userid
    AS SELECT * FROM test.packages
    WHERE ruserid IS NOT NULL
       AND suserid IS NOT NULL
       AND TIMESTAMP IS NOT NULL
       AND packageuuid IS NOT NULL
    PRIMARY KEY (ruserid, suserid, timestamp, packageuuid)
    WITH CLUSTERING ORDER BY (packageuuid DESC);
</code>```

I want to be able to search for packages sent between two IDs

so I would need something like this:

```<code>SELECT * FROM test.packages_by_userid WHERE (ruserid = '1' AND suserid = '2' AND suserid = '1' AND ruserid = '2') AND timestamp > 1496601553;
</code>```

How would I accomplish something like this with CQL?

I've searched a bit but I can't figure it out.

I'm willing to change the structure of the table if it will make something like this possible.

If it's doable without a materialized view that would also be good.

答:
Since you always search for both sender and receiver, I'd model this with the following table layout:

```<code>CREATE TABLE test.packages (
     ruserid text,
     suserid text,
     timestamp int,
     packageuuid timeuuid,
     PRIMARY KEY ((ruserid, suserid), timestamp)
);
</code>```

In this way, for each pair of sender/receiver you need to run two queries, one for each partition:

```<code>SELECT * FROM packages WHERE ruserid=1 AND suserid=2 AND timestamp > 1496601553;
SELECT * FROM packages WHERE ruserid=2 AND suserid=1 AND timestamp > 1496601553;
</code>```

This is IMHO the best solution because, remember, in Cassandra you start from your queries and build your table models on that, never the reverse.

Body:
Here's the code I used to create the table:

CREATE TABLE test.packages (
     packageuuid timeuuid,
     ruserid text,
     suserid text,
     timestamp int,
     PRIMARY KEY (ruserid, suserid, packageuuid, timestamp)
);

and then I create a materialized view:

CREATE MATERIALIZED VIEW test.packages_by_userid
    AS SELECT * FROM test.packages
    WHERE ruserid IS NOT NULL
       AND suserid IS NOT NULL
       AND TIMESTAMP IS NOT NULL
       AND packageuuid IS NOT NULL
    PRIMARY KEY (ruserid, suserid, timestamp, packageuuid)
    WITH CLUSTERING ORDER BY (packageuuid DESC);

I want to be able to search for packages sent between two IDs

so I would need something like this:

SELECT * FROM test.packages_by_userid WHERE (ruserid = '1' AND suserid = '2' AND suserid = '1' AND ruserid = '2') AND timestamp > 1496601553;

How would I accomplish something like this with CQL?

I've searched a bit but I can't figure it out.

I'm willing to change the structure of the table if it will make something like this possible.

If it's doable without a materialized view that would also be good.

Body:
Since you always search for both sender and receiver, I'd model this with the following table layout:

CREATE TABLE test.packages (
     ruserid text,
     suserid text,
     timestamp int,
     packageuuid timeuuid,
     PRIMARY KEY ((ruserid, suserid), timestamp)
);

In this way, for each pair of sender/receiver you need to run two queries, one for each partition:

SELECT * FROM packages WHERE ruserid=1 AND suserid=2 AND timestamp > 1496601553;
SELECT * FROM packages WHERE ruserid=2 AND suserid=1 AND timestamp > 1496601553;

This is IMHO the best solution because, remember, in Cassandra you start from your queries and build your table models on that, never the reverse.


问:
Compiling Android from source, "no rule to make target" tbToolCM error
I'm trying to help out a friend of mine by compiling a ROM for the Samsung Galaxy Grand 2 (ms013g).

```<code>make: *** No rule to make target
'/home/quiche/cmsource/out/host/linux-x86/bin/dtbToolCM' needed by
'/home/quic/out/target/product/ms013g/dt.img '.
</code>```

I keep getting this error i cannot fix, i tried the fix described here: CM12 build failed for oneplus one
and i also made sure android_device_qcom_common is in my local_manifest.xml.
Somewere else, someone suggested changing dtbToolCM to dtbTool, which i tried to no avail.

答:
Please try this to add below to your Device.mk

BOARD_KERNEL_SEPARATED_DT :=true

Please see Android.mk for dtbtool.

Thank you.

Body:
I'm trying to help out a friend of mine by compiling a ROM for the Samsung Galaxy Grand 2 (ms013g).

make: *** No rule to make target
'/home/quiche/cmsource/out/host/linux-x86/bin/dtbToolCM' needed by
'/home/quic/out/target/product/ms013g/dt.img '.

I keep getting this error i cannot fix, i tried the fix described here: CM12 build failed for oneplus one
and i also made sure android_device_qcom_common is in my local_manifest.xml.
Somewere else, someone suggested changing dtbToolCM to dtbTool, which i tried to no avail.


问:
How to write ID in XML file for the first record by using LINQ to XML?
I am developing window phone 7 application. I am using XML as a database for my application. I am using a XML file instead of a database table for my application. I having the following structure for one of my xml file.

```<code><?xml version="1.0" encoding="utf-8" ?>
<Categories>
  <Category>
    <Category_ID></Category_ID>
    <Category_Name></Category_Name>
    <TransactionType_ID></TransactionType_ID>
  </Category>
  <Category>
    <Category_ID></Category_ID>
    <Category_Name></Category_Name>
    <TransactionType_ID></TransactionType_ID>
  </Category>
</Categories>
</code>```

In the above XML file I am inserting the values for Category_Name & TransactionType_ID through the user interface of my mobile application by using LINQ to XML. In the above XML file I am treating the Category_ID as a primary key & TransactionType_ID as a foreign key which belongs to other xml file. In the above XML file I want to generate the autoincrement id for the node Category_ID as we do in the database table. For this purpose I am using the following code

```<code>private int new_record_id()
        {
            IsolatedStorageFile isstore = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream bookfile = new IsolatedStorageFileStream("Categories.xml", System.IO.FileMode.Open, isstore);

            XDocument xmldetails = XDocument.Load(bookfile);

            var details = (from detail in xmldetails.Descendants("Category")
                           select (int.Parse(detail.Element("Category_ID").Value))).Max();

            bookfile.Close();

            return details + 1;
        }
</code>```

But when I insert first record in the XML file then it gives error in the following sentence because there is no record in my XML file at the beginning.

```<code> var details = (from detail in xmldetails.Descendants("Category")
                               select (int.Parse(detail.Element("Category_ID").Value))).Max();
</code>```

Can you please provide me any code or link or any solution through which I can insert the first record in the XML file ? If I am doing anything wrong then please guide me.

答:
Well, to start with your query can be written much more simply as:

```<code>var id = xmlDetails.Descendants("book")
                   .Max(x => (int) x.Element("id"));
</code>```

Now, if you want to be able to handle the case where there are no books in your XML, I'd test that explicitly first:

```<code>int id;
if (xmlDetails.Descendants("book").Any())
{
    id = xmlDetails.Descendants("book")
                   .Max(x => (int) x.Element("id"));
}
else
{
    id = -1; // Or whatever you want to do
}
</code>```

(You could use the conditional operator for this if you wanted, too.)

ContentLicense: CC BY-SA 2.5

Body:
I am developing window phone 7 application. I am using XML as a database for my application. I am using a XML file instead of a database table for my application. I having the following structure for one of my xml file.

<?xml version="1.0" encoding="utf-8" ?>
<Categories>
  <Category>
    <Category_ID></Category_ID>
    <Category_Name></Category_Name>
    <TransactionType_ID></TransactionType_ID>
  </Category>
  <Category>
    <Category_ID></Category_ID>
    <Category_Name></Category_Name>
    <TransactionType_ID></TransactionType_ID>
  </Category>
</Categories>

In the above XML file I am inserting the values for Category_Name & TransactionType_ID through the user interface of my mobile application by using LINQ to XML. In the above XML file I am treating the Category_ID as a primary key & TransactionType_ID as a foreign key which belongs to other xml file. In the above XML file I want to generate the autoincrement id for the node Category_ID as we do in the database table. For this purpose I am using the following code

private int new_record_id()
        {
            IsolatedStorageFile isstore = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream bookfile = new IsolatedStorageFileStream("Categories.xml", System.IO.FileMode.Open, isstore);

            XDocument xmldetails = XDocument.Load(bookfile);

            var details = (from detail in xmldetails.Descendants("Category")
                           select (int.Parse(detail.Element("Category_ID").Value))).Max();

            bookfile.Close();

            return details + 1;
        }

But when I insert first record in the XML file then it gives error in the following sentence because there is no record in my XML file at the beginning.

 var details = (from detail in xmldetails.Descendants("Category")
                               select (int.Parse(detail.Element("Category_ID").Value))).Max();

Can you please provide me any code or link or any solution through which I can insert the first record in the XML file ? If I am doing anything wrong then please guide me.

Body:
Well, to start with your query can be written much more simply as:

var id = xmlDetails.Descendants("book")
                   .Max(x => (int) x.Element("id"));

Now, if you want to be able to handle the case where there are no books in your XML, I'd test that explicitly first:

int id;
if (xmlDetails.Descendants("book").Any())
{
    id = xmlDetails.Descendants("book")
                   .Max(x => (int) x.Element("id"));
}
else
{
    id = -1; // Or whatever you want to do
}

(You could use the conditional operator for this if you wanted, too.)


问:
Gradle error: configuration declares dependency which is not declared
I'm making my first android wear app, but I can't get Android Studio working.
First I got the error

```<code> "Project with path ':wear' could not be found in project ':mobile'.
</code>```

This was resolved by adding "include ':wear" in settings.gradle.

But then a new error occurs:

```<code>"Error:Module version Test2:mobile:unspecified, configuration 'wearApp' declares a dependency on configuration 'default' which is not declared in the module descriptor for Test2:wear:unspecified" .
</code>```

What do I have to do to resolve that error?

Just in case it's needed: here's build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.verbraeken.joost.test2"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    wearApp project(':wear')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.google.android.gms:play-services:8.3.0'
    compile 'com.android.support:design:23.1.1'
}
</code>```

settings.gradle:

```<code>include ':mobile'
include ':wear'
</code>```

答:
In Android Studio 3.0 the documentation for Migrate to the New Plugin says:

```<code>dependencies {
    // This is the old method and no longer works for local
    // library modules:
    // debugCompile project(path: ':foo', configuration: 'debug')
    // releaseCompile project(path: ':foo', configuration: 'release')

    // Instead, simply use the following to take advantage of
    // variant-aware dependency resolution. You can learn more about
    // the 'implementation' configuration in the section about
    // new dependency configurations.
    implementation project(':foo')

    // You can, however, keep using variant-specific configurations when
    // targeting external dependencies. The following line adds 'app-magic'
    // as a dependency to only the 'debug' version of your module.

    debugImplementation 'com.example.android:app-magic:12.3'
}
</code>```

So change this

```<code>    debugCompile project(path: ':foo', configuration: 'debug')
    releaseCompile project(path: ':foo', configuration: 'release')
</code>```

to this

```<code>    implementation project(':foo')
</code>```

Body:
I'm making my first android wear app, but I can't get Android Studio working.
First I got the error

 "Project with path ':wear' could not be found in project ':mobile'.

This was resolved by adding "include ':wear" in settings.gradle.

But then a new error occurs:

"Error:Module version Test2:mobile:unspecified, configuration 'wearApp' declares a dependency on configuration 'default' which is not declared in the module descriptor for Test2:wear:unspecified" .

What do I have to do to resolve that error?

Just in case it's needed: here's build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.verbraeken.joost.test2"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    wearApp project(':wear')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.google.android.gms:play-services:8.3.0'
    compile 'com.android.support:design:23.1.1'
}

settings.gradle:

include ':mobile'
include ':wear'

Body:
In Android Studio 3.0 the documentation for Migrate to the New Plugin says:

dependencies {
    // This is the old method and no longer works for local
    // library modules:
    // debugCompile project(path: ':foo', configuration: 'debug')
    // releaseCompile project(path: ':foo', configuration: 'release')

    // Instead, simply use the following to take advantage of
    // variant-aware dependency resolution. You can learn more about
    // the 'implementation' configuration in the section about
    // new dependency configurations.
    implementation project(':foo')

    // You can, however, keep using variant-specific configurations when
    // targeting external dependencies. The following line adds 'app-magic'
    // as a dependency to only the 'debug' version of your module.

    debugImplementation 'com.example.android:app-magic:12.3'
}

So change this

    debugCompile project(path: ':foo', configuration: 'debug')
    releaseCompile project(path: ':foo', configuration: 'release')

to this

    implementation project(':foo')


问:
One Hot Encoding for States using sklearn
I am trying to perform hot encoding for states using sklearn hot encoder. Here's my pandas dataframe:

```<code>State
0   FL
1   CA
2   MD
3   NY
4   NY
5   NY
6   NY
</code>```

I wrote:

```<code>from sklearn.preprocessing import OneHotEncoder

enc=OneHotEncoder(sparse=False)
enc.fit(data)
</code>```

And here's the error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-78-a0b336acd757> in <module>()
----> 1 enc.fit(data)

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/preprocessing/data.py in fit(self, X, y)
   1842         self
   1843         """
-> 1844         self.fit_transform(X)
   1845         return self
   1846

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/preprocessing/data.py in fit_transform(self, X, y)
   1900         """
   1901         return _transform_selected(X, self._fit_transform,
-> 1902                                    self.categorical_features, copy=True)
   1903
   1904     def _transform(self, X):

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/preprocessing/data.py in _transform_selected(X, transform, selected, copy)
   1695     X : array or sparse matrix, shape=(n_samples, n_features_new)
   1696     """
-> 1697     X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)
   1698
   1699     if isinstance(selected, six.string_types) and selected == "all":

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    380                                       force_all_finite)
    381     else:
--> 382         array = np.array(array, dtype=dtype, order=order, copy=copy)
    383
    384         if ensure_2d:

ValueError: could not convert string to float: 'NY'
</code>```

I don't understand. I thought the whole point of doing a hot encoding is to convert from categorial, often string, information to numerics... Why is it saying I can't convert string to float, then?

答:
Pandas data frame have a build-in option to create one hot encoding, using get_dummies method.

in your example:

```<code>data = pd.DataFrame(['FL','CA','MD','NY','NY','NY','NY'], columns= ['State'])

pd.get_dummies(data.State)
</code>```

will result in:

CA    FL  MD  NY

0 0   1   0   0

1 1   0   0   0

2 0   0   1   0

3 0   0   0   1

4 0   0   0   1

5 0   0   0   1

6 0   0   0   1

Body:
I am trying to perform hot encoding for states using sklearn hot encoder. Here's my pandas dataframe:

State
0   FL
1   CA
2   MD
3   NY
4   NY
5   NY
6   NY

I wrote:

from sklearn.preprocessing import OneHotEncoder

enc=OneHotEncoder(sparse=False)
enc.fit(data)

And here's the error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-78-a0b336acd757> in <module>()
----> 1 enc.fit(data)

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/preprocessing/data.py in fit(self, X, y)
   1842         self
   1843         """
-> 1844         self.fit_transform(X)
   1845         return self
   1846

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/preprocessing/data.py in fit_transform(self, X, y)
   1900         """
   1901         return _transform_selected(X, self._fit_transform,
-> 1902                                    self.categorical_features, copy=True)
   1903
   1904     def _transform(self, X):

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/preprocessing/data.py in _transform_selected(X, transform, selected, copy)
   1695     X : array or sparse matrix, shape=(n_samples, n_features_new)
   1696     """
-> 1697     X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)
   1698
   1699     if isinstance(selected, six.string_types) and selected == "all":

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    380                                       force_all_finite)
    381     else:
--> 382         array = np.array(array, dtype=dtype, order=order, copy=copy)
    383
    384         if ensure_2d:

ValueError: could not convert string to float: 'NY'

I don't understand. I thought the whole point of doing a hot encoding is to convert from categorial, often string, information to numerics... Why is it saying I can't convert string to float, then?

Body:
Pandas data frame have a build-in option to create one hot encoding, using get_dummies method.

in your example:

data = pd.DataFrame(['FL','CA','MD','NY','NY','NY','NY'], columns= ['State'])

pd.get_dummies(data.State)

will result in:

CA    FL  MD  NY

0 0   1   0   0

1 1   0   0   0

2 0   0   1   0

3 0   0   0   1

4 0   0   0   1

5 0   0   0   1

6 0   0   0   1


问:
How to add a loader to a page till I get the data in the background from API in xamarin android MVVM/mono
I am able to get the data from the API which I am using it to bind the data in different ways but when getting the data is going slow, black screen is displayed for some time and then the data is getting loaded so I was trying to rectify that and make the data getting in background(async await) and then bind that to the view when the data is available locally.
How to do that?</p>

答: If you want to use ProgressDialog with MvvmCross (I see that tag under the topic) you may read an article by Stuart

ContentLicense: CC BY-SA 4.0


问:
 link puts page name at end of url
Sorry if the title is confusing, I wasn't exactly sure how to word this.

Basically what I want to do is make a link, simple enough. The page is tylerofcinema.github.io and if I make a link to say, google.com the url that I get is tylerofcinema.github.io/google.com.

Code is in a repo here, let me know if there is any clarification needed.

Thanks, Diego

答:
should be a simple syntax error.

My suggestion would be to change the url to the full address like http://www.google.com so that the browser understands you mean the actual google server and not something else. give it a try

Title: <a> link puts page name at end of url


问:
How to print a value with the same criteria - JavaScript
I am trying to print numbers that are divisible by 3 and 5.
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in
the console. Otherwise, just print out the number.

Tried these codes:

```<code>var i;

for(i = 1; i <= 20; i++){
  if(i % 3 === 0){
     console.log("Fizz");
  }else if(i % 5 === 0){
     console.log("Buzz");
 }else if(i % 3 === 0 && i % 5 === 0){
      console.log("FizzBuzz");
  }else {
   console.log(i);
}
}
</code>```

But it seems it passing out the 3rd else if...
Is there a better way to do this?

答:
A number divisible by two numbers must be divisible by their Least common multiple, which in this case is 15. You also have to move this check up, so that it's considered before the other statements.</p>

```<code>for (var i = 1; i <= 20; i++) {
    if (i % 15 == 0)
        console.log('FizzBuzz');
    else if (i % 3 === 0)
        console.log("Fizz");
    else if (i % 5 === 0)
        console.log("Buzz");
    else
        console.log(i);
}
</code>```

Body:
I am trying to print numbers that are divisible by 3 and 5.
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in
the console. Otherwise, just print out the number.

Tried these codes:

var i;

for(i = 1; i <= 20; i++){
  if(i % 3 === 0){
     console.log("Fizz");
  }else if(i % 5 === 0){
     console.log("Buzz");
 }else if(i % 3 === 0 && i % 5 === 0){
      console.log("FizzBuzz");
  }else {
   console.log(i);
}
}

But it seems it passing out the 3rd else if...
Is there a better way to do this?

Body:
A number divisible by two numbers must be divisible by their Least common multiple, which in this case is 15. You also have to move this check up, so that it's considered before the other statements.

for (var i = 1; i <= 20; i++) {
    if (i % 15 == 0)
        console.log('FizzBuzz');
    else if (i % 3 === 0)
        console.log("Fizz");
    else if (i % 5 === 0)
        console.log("Buzz");
    else
        console.log(i);
}


答: just add // before the start of the link, it should work

Title: <a> link puts page name at end of url

Body:
Sorry if the title is confusing, I wasn't exactly sure how to word this.

Basically what I want to do is make a link, simple enough. The page is tylerofcinema.github.io and if I make a link to say, google.com the url that I get is tylerofcinema.github.io/google.com.

Code is in a repo here, let me know if there is any clarification needed.

Thanks, Diego


问:
How to show Spark application's percentage of completion on AWS EMR (and Boto3)?
I am running a Spark step on AWS EMR, this step is added to EMR through Boto3, I will like to return to the user a percentage of completion of the task, is there anyway to do this?

I was thinking to calculate this percentage with the number of completed stages of Spark, I know this won't be too precise, as the stage 4 may take double time than stage 5 but I am fine with that.

Is it possible to access this information with boto3?

I checked the method list_steps (here are the docs) but in the response I am getting only if its running without other information.

答:
This is not supported at the moment and I don't think it will be anytime soon. </p>

<p>You'll just have to follow application logs the old fashioned way. So maybe consider formatting your logs in a way you know what has actually finished. </p>

Body:
This is not supported at the moment and I don't think it will be anytime soon.

You'll just have to follow application logs the old fashioned way. So maybe consider formatting your logs in a way you know what has actually finished.


问:
Protractor if ,else with (expect(condition))
in my script i need to include if and else statement,here is the code

```<code>if((element(by.model('trt_model')).all(by.tagName('option')).get(0).getText()).toEqual('Select Contract'))
{
    element(by.model('trt_model')).get(1).click();
}
else
{
    element(by.model('trt_model')).get(0).click();
}
</code>```

if the expect condition fails , i want the script to execute the else part, but this is not working.
when expect condition fails,the script is not executing the else part

kindly suggest how this can be resolved
Thank you

答:
I don't know how long is your list, but it seems that you can simplify your code. How about use:

```<code>element(by.model('trt_model')).get(last).click();
</code>```

instead of whole if statement?

Body:
in my script i need to include if and else statement,here is the code

if((element(by.model('trt_model')).all(by.tagName('option')).get(0).getText()).toEqual('Select Contract'))
{
    element(by.model('trt_model')).get(1).click();
}
else
{
    element(by.model('trt_model')).get(0).click();
}

if the expect condition fails , i want the script to execute the else part, but this is not working.
when expect condition fails,the script is not executing the else part

kindly suggest how this can be resolved
Thank you

Body:
I don't know how long is your list, but it seems that you can simplify your code. How about use:

element(by.model('trt_model')).get(last).click();

instead of whole if statement?


问:
Bootstrap: @media min-width AND max-width does not work on Ipad
I am trying to make the class "pad1" working on my Ipad (which has a width of 768px),

So I tried this code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>

<style>
@media (min-width: 767px) and (max-width:991px){
    .pad1 {
        margin-top: 150px;
    }
}

</style>

<div class="container">

  <div class="row pad1">

    <div class="col-sm-4" style="background-color: orange;">

    AAAAA

    </div>

  </div>

</div>

</body>

</html>
</code>```

But the padding does not work, whereas if I remove the and (max-width:991px) part it works..

I also tried some other solution from a different post, like:

```<code>@media only screen and (min-device-width: 767px) and (max-device-width: 991px) and (orientation:portrait) {

  .pad1 {
      margin-top: 150px;
  }
</code>```

But it still not working, I am stuck here, and I absolutly need to limit the max width for this class, do you have any solution ?

Thank you

答:
Change To :

```<code>@media all and (min-device-width:767px) and (max-device-width:991px){
    .pad1 {
        margin-top: 150px;
    }
}
</code>```

I hope ,help you.

Body:
I am trying to make the class "pad1" working on my Ipad (which has a width of 768px),

So I tried this code:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    AAAAA

But the padding does not work, whereas if I remove the and (max-width:991px) part it works..

I also tried some other solution from a different post, like:

@media only screen and (min-device-width: 767px) and (max-device-width: 991px) and (orientation:portrait) {

  .pad1 {
      margin-top: 150px;
  }

But it still not working, I am stuck here, and I absolutly need to limit the max width for this class, do you have any solution ?

Thank you

Body:
Change To :

@media all and (min-device-width:767px) and (max-device-width:991px){
    .pad1 {
        margin-top: 150px;
    }
}

I hope ,help you.


问:
masstransit with rabbitmq: Why message auto moved to _skipped queue when it published
MassTransit.3.1.2 MassTransit.Autofac.3.1.1  MassTransit.RabbitMQ.3.1.1 RabbitMQ.Client.3.6.0 Topshelf.3.3.1

One Topshelf Windows service, create a bus instance like this:

```<code>var builder = new ContainerBuilder();
builder.RegisterConsumers(Assembly.GetExecutingAssembly());
builder.Register<IBusControl>(context =>
        {
            return Bus.Factory.CreateUsingRabbitMq(rbmq =>
            {
                var host = rbmq.Host(new Uri("rabbitmq://" + BusConfig.Instance.Host + ":" + BusConfig.Instance.Port + "/" + BusConfig.Instance.VHost), h =>
                {
                    h.Username(BusConfig.Instance.UserName);
                    h.Password(BusConfig.Instance.Password);
                });
                rbmq.UseJsonSerializer();
                rbmq.UseNLog();

                rbmq.ReceiveEndpoint(BusConfig.Instance.Queue, edp =>
                {
                    edp.UseRetry(Retry.Incremental(5, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)));
                    edp.LoadFrom(context);
                });
            });
        }).SingleInstance().As<IBusControl>().As<IBus>();

        return builder.Build().Resolve<IBusControl>();
</code>```

One console application like this ：

```<code>var bus = Bus.Factory.CreateUsingRabbitMq(rbmq =>
           {
               var host = rbmq.Host(new Uri("rabbitmq://" + BusConfig.Instance.Host + ":" + BusConfig.Instance.Port + "/" + BusConfig.Instance.VHost), h =>
               {
                   h.Username(BusConfig.Instance.UserName);
                   h.Password(BusConfig.Instance.Password);
               });
           });
        bus.Start();
        var msg = new OrderCreatedMessage() { OrderId = 10102 };

        bus.Publish<OrderCreatedMessage>(msg);
</code>```

When mesasge published by console application ，Rabbitmq queue named by “BusConfig.Instance.Queue” received the OrderCreatedMessage：

Rabbitmq queue view when message published

Then i started the topshelf service ，The OrderCreatedMessage auto removed to _skipped queue ：

Rabbitmq queue view when topshelf service started

Masstransit log like this:

```<code>MOVE:rabbitmq:\/\/192.168.12.217:5672\/zst\/zst.order.queue?prefetch=8:rabbitmq:\/\/192.168.12.217:5672\/zst\/zst.order.queue_skipped?bind=true&queue=zst.order.queue_skipped:N\/A:Moved
</code>```

But,When i publish message and consume the message with the same bus (Topshelf service), it works!!!

Any help or additional insight on this architecture would be appreciated!

答: I'm just getting started with Masstransit and RabbitMQ. The answers above did send me in the right direction but for future reference. I was getting extra queues in RabbitMQ because the exhange had incorrect (duplicate bindings on) and I didn't notice this since the code seemed correct but the incorrect settings in RabbitMQ persisted. Deleting the queues and starting fresh solved it.</p>

Body:
MassTransit.3.1.2 MassTransit.Autofac.3.1.1  MassTransit.RabbitMQ.3.1.1 RabbitMQ.Client.3.6.0 Topshelf.3.3.1

One Topshelf Windows service, create a bus instance like this:

var builder = new ContainerBuilder();
builder.RegisterConsumers(Assembly.GetExecutingAssembly());
builder.Register<IBusControl>(context =>
        {
            return Bus.Factory.CreateUsingRabbitMq(rbmq =>
            {
                var host = rbmq.Host(new Uri("rabbitmq://" + BusConfig.Instance.Host + ":" + BusConfig.Instance.Port + "/" + BusConfig.Instance.VHost), h =>
                {
                    h.Username(BusConfig.Instance.UserName);
                    h.Password(BusConfig.Instance.Password);
                });
                rbmq.UseJsonSerializer();
                rbmq.UseNLog();

                rbmq.ReceiveEndpoint(BusConfig.Instance.Queue, edp =>
                {
                    edp.UseRetry(Retry.Incremental(5, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)));
                    edp.LoadFrom(context);
                });
            });
        }).SingleInstance().As<IBusControl>().As<IBus>();

        return builder.Build().Resolve<IBusControl>();

One console application like this ：

var bus = Bus.Factory.CreateUsingRabbitMq(rbmq =>
           {
               var host = rbmq.Host(new Uri("rabbitmq://" + BusConfig.Instance.Host + ":" + BusConfig.Instance.Port + "/" + BusConfig.Instance.VHost), h =>
               {
                   h.Username(BusConfig.Instance.UserName);
                   h.Password(BusConfig.Instance.Password);
               });
           });
        bus.Start();
        var msg = new OrderCreatedMessage() { OrderId = 10102 };

        bus.Publish<OrderCreatedMessage>(msg);

When mesasge published by console application ，Rabbitmq queue named by “BusConfig.Instance.Queue” received the OrderCreatedMessage：

Rabbitmq queue view when message published

Then i started the topshelf service ，The OrderCreatedMessage auto removed to _skipped queue ：

Rabbitmq queue view when topshelf service started

Masstransit log like this:

MOVE:rabbitmq:\/\/192.168.12.217:5672\/zst\/zst.order.queue?prefetch=8:rabbitmq:\/\/192.168.12.217:5672\/zst\/zst.order.queue_skipped?bind=true&queue=zst.order.queue_skipped:N\/A:Moved

But,When i publish message and consume the message with the same bus (Topshelf service), it works!!!

Any help or additional insight on this architecture would be appreciated!


问:
Is it reliable to use EventSource to get User's online status?
I have used an EventSource method to get online status of active users on my website.
In this following JavaScript code is inserted in every page

var source = new EventSource("set_online.php");

Thus this code is executing set_online.php file continuously.

On server side i.e. in set_online.php following code executed

```<code>$query = "UPDATE my_db SET last_active = '{$current_time}' WHERE id = {$_SESSION["id"]}";
                $result = mysqli_query($connection, $query);
</code>```

Now I have two concerns about this:

As Database is updating last_active continuously in realtime, will it affect server load?

As connection is open as long as user is on website, will it create vulnerabilities?

答:
SSE is not suitable for this purpose - or at least is not designed for it. SSE is a constant stream of events from server to browser.

Your script will work, though. The PHP script will do one thing (update the database) then exit. When it exits the connection is closed. The browser will see the connection has died, and after a few seconds will reconnect again. When the cycle repeats.

Regarding your two questions:
1. It is not really continuous, more a re-connect every 3 seconds. The server load might be significant.
2. The connection is not open continuously; but if it was it does not create any new vulnerabilities.

I would use an ajax call, on a JavaScript interval, instead of SSE. These advantages:

Older technology, so wider browser support

Explicit control over the timer interval, so you can control the balance between latency and server load.

Body:
I have used an EventSource method to get online status of active users on my website.
In this following JavaScript code is inserted in every page

var source = new EventSource("set_online.php");

Thus this code is executing set_online.php file continuously.

On server side i.e. in set_online.php following code executed

$query = "UPDATE my_db SET last_active = '{$current_time}' WHERE id = {$_SESSION["id"]}";
                $result = mysqli_query($connection, $query);

Now I have two concerns about this:

As Database is updating last_active continuously in realtime, will it affect server load?

As connection is open as long as user is on website, will it create vulnerabilities?


问:
VB not declaring variables
I have declared the variable "array" but then it says that the variable is undeclared. Its not auto filling "array" when i type so i think that my project file is stuffed? Im in visual studio 2015 if that helps Any help would be great Screen Shot of code</p>

答:
You can declare variables/procedures at class level, but you cannot modify or execute anything there.

This is invalid:

```<code>Public Module Stuff
    Public array(147) As String 'VALID. Declarations can be performed at class level.
    array(0) = "Hello" 'INVALID. Modifications can not be performed at class level.
End Module
</code>```

This is valid:

```<code>Public Module Stuff
    Public array(147) As String

    Public Sub FillArray()
        array(0) = "Hello"
    End Sub
End Module
</code>```

You can however initialize the array with a set of values if you'd like:

```<code>Public Module Stuff
    Public array() As String = New String(147) {"Hello", "Item 1", "Blabla", ...} 'VALID.
End Module
</code>```

And if you want to add loops and conditions to your initialization, and you're using Visual Basic 10.0 or above, you can use Lambda Expressions to create an inline function:

```<code>Public Module Stuff
    Public array(147) As String = _
        Function()
            Dim Result(147) As String
            For x = 0 To Result.Length - 1
                Result(x) = "Item " & x
            Next
            Return Result
        End Function.Invoke()

End Module
</code>```

Title: VB not declaring variables

Body:
You can declare variables/procedures at class level, but you cannot modify or execute anything there.

This is invalid:

Public Module Stuff
    Public array(147) As String 'VALID. Declarations can be performed at class level.
    array(0) = "Hello" 'INVALID. Modifications can not be performed at class level.
End Module

This is valid:

Public Module Stuff
    Public array(147) As String

    Public Sub FillArray()
        array(0) = "Hello"
    End Sub
End Module

You can however initialize the array with a set of values if you'd like:

Public Module Stuff
    Public array() As String = New String(147) {"Hello", "Item 1", "Blabla", ...} 'VALID.
End Module

And if you want to add loops and conditions to your initialization, and you're using Visual Basic 10.0 or above, you can use Lambda Expressions to create an inline function:

Public Module Stuff
    Public array(147) As String = _
        Function()
            Dim Result(147) As String
            For x = 0 To Result.Length - 1
                Result(x) = "Item " & x
            Next
            Return Result
        End Function.Invoke()

End Module


问:
Operating NI USRP-2920 by GNURadio
I try to operate NI USRP-2920 by GNUradio.
At the first, I typed "uhd_find_devices".
Result is below.

```<code>----------------------------------------------
-- UHD Devices 0
----------------------------------------------
Device Address:
   serial: 3077BE9
   adde: 192.168.10.4
   name:
   type: usrp2
</code>```

In the next, I typed "uhd_usrp_probe" in terminal.
Result is below.

Error: RuntimeError:  Please update the firmware and FPGA images for
  your device. See the application notes for USRP2/N-Series for
  instructions. Expected FPGA compatibility number 11, but got 10: The
  FPGA build is not compatible with the host code build. Please run:

"/usr/local/lib/uhd/utils/uhd_images_downloader.py"
  "/usr/local/bin/uhd_image_loader" \
      --args="type=usrp2,addr=192.168.10.4"

Therefore, I runned uhd_images_downloader. But, I typed
"uhd_usrp_probe" is the same result(RuntimError:update the firmware).

Could you tell me any advices?
Thank you.

答:
Thank you.
I typed "uhd_image_downloder" after renewing ubuntu.
As a result, I could connect USRP.
Thank you for advice.</p>

Title: Operating NI USRP-2920 by GNURadio

Body:
I try to operate NI USRP-2920 by GNUradio.
At the first, I typed "uhd_find_devices".
Result is below.

----------------------------------------------
-- UHD Devices 0
----------------------------------------------
Device Address:
   serial: 3077BE9
   adde: 192.168.10.4
   name:
   type: usrp2

In the next, I typed "uhd_usrp_probe" in terminal.
Result is below.

Error: RuntimeError:  Please update the firmware and FPGA images for
  your device. See the application notes for USRP2/N-Series for
  instructions. Expected FPGA compatibility number 11, but got 10: The
  FPGA build is not compatible with the host code build. Please run:

"/usr/local/lib/uhd/utils/uhd_images_downloader.py"
  "/usr/local/bin/uhd_image_loader" \
      --args="type=usrp2,addr=192.168.10.4"

Therefore, I runned uhd_images_downloader. But, I typed
"uhd_usrp_probe" is the same result(RuntimError:update the firmware).

Could you tell me any advices?
Thank you.


问:
Simple Authentication using Jwt in dot net core MVC
I'm trying to add JWT validation in my dot net core application. I've followed this link to understand JWT and able to generate a token by givings some values like this.

```<code>var token = new JwtSecurityToken(
  issuer: issuer,
  audience: aud,
  claims: claims,
  expires: expTime,
  signingCredentials: creds
);
</code>```

Edit: and to follow this answer, I've also added JwtBearerAuthentication middleware in my app by adding app.UseJwtBearerAuthentication(new JwtBearerOptions { /* options */ }) to Startup.Configure() method.

Now I'm stuck how could I pass this token inside HTTP header? I'm generating this token on Login but whats next? How could I get to know that JWT is added and working fine??

Any kind of help will be appreciated.

答:
This is a runnable sample for bearer token authentication in ASP.NET Core.

How to achieve a bearer token authentication and authorization in ASP.NET Core

At back end, you can generate the token following this code:

```<code>[Route("api/[controller]")]
public class TokenAuthController : Controller
{
    [HttpPost]
    public string GetAuthToken(User user)
    {
        var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password);

        if (existUser != null)
        {
            var requestAt = DateTime.Now;
            var expiresIn = requestAt + TokenAuthOption.ExpiresSpan;
            var token = GenerateToken(existUser, expiresIn);

            return JsonConvert.SerializeObject(new {
                stateCode = 1,
                requertAt = requestAt,
                expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds,
                accessToken = token
            });
        }
        else
        {
            return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" });
        }
    }

    private string GenerateToken(User user, DateTime expires)
    {
        var handler = new JwtSecurityTokenHandler();

        ClaimsIdentity identity = new ClaimsIdentity(
            new GenericIdentity(user.Username, "TokenAuth"),
            new[] {
                new Claim("ID", user.ID.ToString())
            }
        );

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = TokenAuthOption.Issuer,
            Audience = TokenAuthOption.Audience,
            SigningCredentials = TokenAuthOption.SigningCredentials,
            Subject = identity,
            Expires = expires
        });
        return handler.WriteToken(securityToken);
    }
}
</code>```

In Startup.cs/ConfigureServices method

```<code>services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser().Build());
});
</code>```

And add this code in Configure method

```<code>app.UseJwtBearerAuthentication(new JwtBearerOptions {
    TokenValidationParameters = new TokenValidationParameters {
        IssuerSigningKey = TokenAuthOption.Key,
        ValidAudience = TokenAuthOption.Audience,
        ValidIssuer = TokenAuthOption.Issuer,
        ValidateIssuerSigningKey = true,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromMinutes(0)
    }
});
</code>```

At front end, you just add the token to header like this:

```<code>$.ajaxSetup({
    headers: { "Authorization": "Bearer " + accessToken }
});
</code>```

or

```<code>$.ajax("http://somedomain/somepath/somepage",{
    headers:{ "Authorization": "Bearer " + accessToken },
    /*some else parameter for ajax, see more you can review the Jquery API*/
});
</code>```

Body:
I'm trying to add JWT validation in my dot net core application. I've followed this link to understand JWT and able to generate a token by givings some values like this.

var token = new JwtSecurityToken(
  issuer: issuer,
  audience: aud,
  claims: claims,
  expires: expTime,
  signingCredentials: creds
);

Edit: and to follow this answer, I've also added JwtBearerAuthentication middleware in my app by adding app.UseJwtBearerAuthentication(new JwtBearerOptions { /* options */ }) to Startup.Configure() method.

Now I'm stuck how could I pass this token inside HTTP header? I'm generating this token on Login but whats next? How could I get to know that JWT is added and working fine??

Any kind of help will be appreciated.

Body:
This is a runnable sample for bearer token authentication in ASP.NET Core.

How to achieve a bearer token authentication and authorization in ASP.NET Core

At back end, you can generate the token following this code:

[Route("api/[controller]")]
public class TokenAuthController : Controller
{
    [HttpPost]
    public string GetAuthToken(User user)
    {
        var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password);

        if (existUser != null)
        {
            var requestAt = DateTime.Now;
            var expiresIn = requestAt + TokenAuthOption.ExpiresSpan;
            var token = GenerateToken(existUser, expiresIn);

            return JsonConvert.SerializeObject(new {
                stateCode = 1,
                requertAt = requestAt,
                expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds,
                accessToken = token
            });
        }
        else
        {
            return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" });
        }
    }

    private string GenerateToken(User user, DateTime expires)
    {
        var handler = new JwtSecurityTokenHandler();

        ClaimsIdentity identity = new ClaimsIdentity(
            new GenericIdentity(user.Username, "TokenAuth"),
            new[] {
                new Claim("ID", user.ID.ToString())
            }
        );

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = TokenAuthOption.Issuer,
            Audience = TokenAuthOption.Audience,
            SigningCredentials = TokenAuthOption.SigningCredentials,
            Subject = identity,
            Expires = expires
        });
        return handler.WriteToken(securityToken);
    }
}

In Startup.cs/ConfigureServices method

services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser().Build());
});

And add this code in Configure method

app.UseJwtBearerAuthentication(new JwtBearerOptions {
    TokenValidationParameters = new TokenValidationParameters {
        IssuerSigningKey = TokenAuthOption.Key,
        ValidAudience = TokenAuthOption.Audience,
        ValidIssuer = TokenAuthOption.Issuer,
        ValidateIssuerSigningKey = true,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromMinutes(0)
    }
});

At front end, you just add the token to header like this:

$.ajaxSetup({
    headers: { "Authorization": "Bearer " + accessToken }
});

or

$.ajax("http://somedomain/somepath/somepage",{
    headers:{ "Authorization": "Bearer " + accessToken },
    /*some else parameter for ajax, see more you can review the Jquery API*/
});


问:
Nerd dinner error on Ajax call to Register action method
I'm new to MVC and I'm implementing the Nerd Dinner MVC sample app in MS MVC2. I'm on step 10, "Ajax enabling RSVPs accepts". I've added the new RSVP controller and added the Register action method like so:

```<code>public class RSVPController : Controller
{
    DinnerRepository dinnerRepository = new DinnerRepository();

    //
    // AJAX: /Dinners/RSVPForEvent/1

    [Authorize, AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Register(int id) {

        Dinner dinner = dinnerRepository.GetDinner(id);

        if (!dinner.IsUserRegistered(User.Identity.Name)) {

            RSVP rsvp = new RSVP();
            rsvp.AttendeeName = User.Identity.Name;

            dinner.RSVPs.Add(rsvp);
            dinnerRepository.Save();
        }

        return Content("Thanks - we'll see you there!");
    }
}
</code>```

I added the references to both Ajax script libraries and added the code below to the Details view as described in the article:

```<code><div id="rsvpmsg">

<% if(Request.IsAuthenticated) { %>

    <% if(Model.IsUserRegistered(Context.User.Identity.Name)) { %>

        <p>You are registred for this event!</p>

    <% } else { %>

        <%= Ajax.ActionLink( "RSVP for this event",
                             "Register", "RSVP",
                             new { id=Model.DinnerID },
                             new AjaxOptions { UpdateTargetId="rsvpmsg"}) %>
    <% } %>

<% } else { %>

    <a href="/Account/Logon">Logon</a> to RSVP for this event.

<% } %>

</div>
</code>```

When I click the "RSVP for this event" link I get a 404 eror saying the resource cannot be found:

```<code>The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /NerdDinner/RSVP/Register/24

Version Information: Microsoft .NET Framework Version:2.0.50727.4200; ASP.NET Version:2.0.50727.4205
</code>```

When I step into the code it is finding the Register action method correctly. After playing around with it I removed the "AcceptVerbs(HttpVerbs.Post)" from the constraint on the Register method, and it then worked. However it didn't reload the page it just displayed the "Thanks - we'll see you there" message on a new blank page. Looking at the html in the details page there is no Form submit taking place, so I'm wondering does the Ajax code need something more to make the call a Post? Is there a known issue with this part of the Nerd Dinner app? I think the app was written in MVC1 and I'm using MVC2 - does this make a diference?

TIA,

Ciaran

答:
if you include those two in your site.master, it should be fine

```<code><script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
</code>```

Body:
I'm new to MVC and I'm implementing the Nerd Dinner MVC sample app in MS MVC2. I'm on step 10, "Ajax enabling RSVPs accepts". I've added the new RSVP controller and added the Register action method like so:

public class RSVPController : Controller
{
    DinnerRepository dinnerRepository = new DinnerRepository();

    //
    // AJAX: /Dinners/RSVPForEvent/1

    [Authorize, AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Register(int id) {

        Dinner dinner = dinnerRepository.GetDinner(id);

        if (!dinner.IsUserRegistered(User.Identity.Name)) {

            RSVP rsvp = new RSVP();
            rsvp.AttendeeName = User.Identity.Name;

            dinner.RSVPs.Add(rsvp);
            dinnerRepository.Save();
        }

        return Content("Thanks - we'll see you there!");
    }
}

I added the references to both Ajax script libraries and added the code below to the Details view as described in the article:

<% if(Request.IsAuthenticated) { %>

    <% if(Model.IsUserRegistered(Context.User.Identity.Name)) { %>

You are registred for this event!

    <% } else { %>

        <%= Ajax.ActionLink( "RSVP for this event",
                             "Register", "RSVP",
                             new { id=Model.DinnerID },
                             new AjaxOptions { UpdateTargetId="rsvpmsg"}) %>
    <% } %>

<% } else { %>

    Logon to RSVP for this event.

<% } %>

When I click the "RSVP for this event" link I get a 404 eror saying the resource cannot be found:

The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /NerdDinner/RSVP/Register/24

Version Information: Microsoft .NET Framework Version:2.0.50727.4200; ASP.NET Version:2.0.50727.4205

When I step into the code it is finding the Register action method correctly. After playing around with it I removed the "AcceptVerbs(HttpVerbs.Post)" from the constraint on the Register method, and it then worked. However it didn't reload the page it just displayed the "Thanks - we'll see you there" message on a new blank page. Looking at the html in the details page there is no Form submit taking place, so I'm wondering does the Ajax code need something more to make the call a Post? Is there a known issue with this part of the Nerd Dinner app? I think the app was written in MVC1 and I'm using MVC2 - does this make a diference?

TIA,

Ciaran

Body:
if you include those two in your site.master, it should be fine

<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>


问:
Shapeless not working in generic context
I am still trying to get my head around Shapeless (and, to a lesser extent, Scala!) and I have been writing some simple code to generate random instance data for case classes - predominantly based on the guides here: http://enear.github.io/2016/09/27/bits-of-shapeless-2/ (the example covers a JSON Writer implementation)

I have created a Generator[A] trait and created implicit implementations for simple types, and as per the example in the above link, I have also created implicit implementations to handle HList, HNil, Coproduct and CNil:

```<code>  implicit def hnilGenerator = new Generator[HNil] {
    override def generate(a: HNil) = HNil
  }

  implicit def hconsGenerator[H, T <: HList](implicit headGen: Generator[H], tailGen: Generator[T]) =
    new Generator[H :: T] {
      override def generate(a: H :: T) = headGen.generate(a.head) :: tailGen.generate(a.tail)
    }

  implicit def cnilGenerator: Generator[CNil] =
    new Generator[CNil] {
      override def generate(a: CNil): CNil = throw new RuntimeException("Invalid candidate configuration")
    }

  implicit def cconsGenerator[H, T <: Coproduct] =
    new Generator[H :+: T] {
      override def generate(a: H :+: T) = throw new RuntimeException("Invalid candidate configuration")
    }
</code>```

I can now use this code to generate a random instance based on a case class or a sealed trait:

```<code>    it("should work with a case class to hlist") {
      case class Test(x: IntGene, y: DoubleGene, z: BooleanGene)
      val c = Generic[Test].to(Test(IntGene(), DoubleGene(), BooleanGene()))
      generate(c)
    }
    it("what happens with sealed traits") {
      sealed trait Shape
      case class Square(width: Int, height: Int) extends Shape
      case class Circle(radius: Int) extends Shape

      val c = Generic[Shape].to(Circle(1))
      generate(c)
    }
</code>```

Both of the above work no problem, however, if I try to make this a generic (as in parameter types) I get compilation errors not being able to find the necessary implicts:

```<code>it("should handle generics") {
  case class GenericTest[A: Generic](x: A) {
    def convert() = {
      val c = Generic[A].to(x)
      generate(c)
    }
  }
}
</code>```

So from my understanding, because I have used the Generic context bound A, the compiler knows that is going to be available, so c must be some possible return from the call to(x) - Am I missing something in the implementation to handle that return type from the Generic shapeless call? Or have I wildly misunderstood something?

I am hoping this is possible and I have just missed something - is it that the compiler doesn't know what will be passed in (Im assuming not), or is there another possible type that needs to be handled implicitly from that to(x) call?

EDIT

Compile error added below - I'm really just trying to understand: Is it that there is some return case from the to(x) shapeless call that I have not catered for, or is it because the compiler doesn't have any idea what will be passed in and there are some types not catered for (e.g. I haven't added a Date generator implicit - and a case class could potentially have any type included? I was hoping that was not the case, and as the compiler knows nothing is actually being passed to the class/method it knows there are no issues?)

```<code>GeneratorSpec.scala:44: could not find implicit value for parameter gen: io.github.robhinds.genotype.Generator[GenericTest.this.evidence$1.Repr]
          generate(c)
</code>```

And my generate method is just a simple helper method that gets given the implicit Generator :

```<code>def generate[A](a: A)(implicit gen: Generator[A]) = gen.generate(a)
</code>```

答:
Your problem comes from the fact that Generic only converts a case class to a HList and a sealed trait to a Coproduct (not recursively).

So if you have a generic Generic, you have no information on what HList or Coproduct you are given, so, you cannot use your product and coproduct rules to find the wanted implicit. In some explicit case, you might have the same problem, so I will give you this as an example:

Let's say you have a case class architecture

```<code>case class Bottom(value: String)
case class Top(bot: Bottom, count: Int)
</code>```

The implicit Generic[Top] will have type MyHList = Bottom :: Int :: HNil as output type, so you'll be asking for an implicit Generator[MyHList]. But since you don't have an implicit Generator[Bottom] in scope, you won't be able to use hconsgenerator.

In the generic case, it's even worse. The compiler can only infer HList for the output type of Generic[A] (and that's assuming you forget about Coproduct), so you need an implicit Generator[HList], which you cannot provide.

The solution is to give an implicit for constructs that have a generic that can itself be generated:

```<code>implicit def generic2generate[T, L <: HList](implicit generic: Generic.Aux[T, L], lGen: Generator[L]): Generator[T] = new Generator[T] {
  def generate(c: T) = generic.from(lGen.generate(generic.to(c)))
}
</code>```

EDIT

You can now follow the implicit resolution for our Top type:

We can have a Generator[Top] using last rule, if we have a Generic.Aux[Top, L] for some L, and a Generator[L].

The only Generic.Aux[Top, _] that exists implicitly is a Generic.Aux[Top, Bottom :: Int :: HNil], so we are reduced to finding a Generator[Top, Bottom :: Int :: HNil]

using the hcons rule three times, we are reduced to finding a Generator[Bottom], a Generator[Int] and a Generator[HNil].

Generator[Int] is given (I assume) and Generator[HNil] is the first rule, so we are reduced to finding a Generator[Bottom]

the only rule that can provide one, is once again the 3rd rule, so we must find a Generator[String :: HNil], since the only Generic available is a Generic.Aux[Bottom, String :: HNil].

using the hcons rule, we are down to finding a Generator[String], which can easily be provided.

This example shows different points:

first that it may take a long time when compiling to solve all these implicits (I only gave the main points of the proof, but the compiler has to try all possible branches)

second, that this resolution can only be done for a specific Generic, it cannot be inferred generically (although this might seem counter-intuitive); even if the human mind is able to tell that it will work for every Generic, the compiler cannot process it as such.

Body:
I am still trying to get my head around Shapeless (and, to a lesser extent, Scala!) and I have been writing some simple code to generate random instance data for case classes - predominantly based on the guides here: http://enear.github.io/2016/09/27/bits-of-shapeless-2/ (the example covers a JSON Writer implementation)

I have created a Generator[A] trait and created implicit implementations for simple types, and as per the example in the above link, I have also created implicit implementations to handle HList, HNil, Coproduct and CNil:

  implicit def hnilGenerator = new Generator[HNil] {
    override def generate(a: HNil) = HNil
  }

  implicit def hconsGenerator[H, T <: HList](implicit headGen: Generator[H], tailGen: Generator[T]) =
    new Generator[H :: T] {
      override def generate(a: H :: T) = headGen.generate(a.head) :: tailGen.generate(a.tail)
    }

  implicit def cnilGenerator: Generator[CNil] =
    new Generator[CNil] {
      override def generate(a: CNil): CNil = throw new RuntimeException("Invalid candidate configuration")
    }

  implicit def cconsGenerator[H, T <: Coproduct] =
    new Generator[H :+: T] {
      override def generate(a: H :+: T) = throw new RuntimeException("Invalid candidate configuration")
    }

I can now use this code to generate a random instance based on a case class or a sealed trait:

    it("should work with a case class to hlist") {
      case class Test(x: IntGene, y: DoubleGene, z: BooleanGene)
      val c = Generic[Test].to(Test(IntGene(), DoubleGene(), BooleanGene()))
      generate(c)
    }
    it("what happens with sealed traits") {
      sealed trait Shape
      case class Square(width: Int, height: Int) extends Shape
      case class Circle(radius: Int) extends Shape

      val c = Generic[Shape].to(Circle(1))
      generate(c)
    }

Both of the above work no problem, however, if I try to make this a generic (as in parameter types) I get compilation errors not being able to find the necessary implicts:

it("should handle generics") {
  case class GenericTest[A: Generic](x: A) {
    def convert() = {
      val c = Generic[A].to(x)
      generate(c)
    }
  }
}

So from my understanding, because I have used the Generic context bound A, the compiler knows that is going to be available, so c must be some possible return from the call to(x) - Am I missing something in the implementation to handle that return type from the Generic shapeless call? Or have I wildly misunderstood something?

I am hoping this is possible and I have just missed something - is it that the compiler doesn't know what will be passed in (Im assuming not), or is there another possible type that needs to be handled implicitly from that to(x) call?

EDIT

Compile error added below - I'm really just trying to understand: Is it that there is some return case from the to(x) shapeless call that I have not catered for, or is it because the compiler doesn't have any idea what will be passed in and there are some types not catered for (e.g. I haven't added a Date generator implicit - and a case class could potentially have any type included? I was hoping that was not the case, and as the compiler knows nothing is actually being passed to the class/method it knows there are no issues?)

GeneratorSpec.scala:44: could not find implicit value for parameter gen: io.github.robhinds.genotype.Generator[GenericTest.this.evidence$1.Repr]
          generate(c)

And my generate method is just a simple helper method that gets given the implicit Generator :

def generate[A](a: A)(implicit gen: Generator[A]) = gen.generate(a)

Body:
Your problem comes from the fact that Generic only converts a case class to a HList and a sealed trait to a Coproduct (not recursively).

So if you have a generic Generic, you have no information on what HList or Coproduct you are given, so, you cannot use your product and coproduct rules to find the wanted implicit. In some explicit case, you might have the same problem, so I will give you this as an example:

Let's say you have a case class architecture

case class Bottom(value: String)
case class Top(bot: Bottom, count: Int)

The implicit Generic[Top] will have type MyHList = Bottom :: Int :: HNil as output type, so you'll be asking for an implicit Generator[MyHList]. But since you don't have an implicit Generator[Bottom] in scope, you won't be able to use hconsgenerator.

In the generic case, it's even worse. The compiler can only infer HList for the output type of Generic[A] (and that's assuming you forget about Coproduct), so you need an implicit Generator[HList], which you cannot provide.

The solution is to give an implicit for constructs that have a generic that can itself be generated:

implicit def generic2generate[T, L <: HList](implicit generic: Generic.Aux[T, L], lGen: Generator[L]): Generator[T] = new Generator[T] {
  def generate(c: T) = generic.from(lGen.generate(generic.to(c)))
}

EDIT

You can now follow the implicit resolution for our Top type:

We can have a Generator[Top] using last rule, if we have a Generic.Aux[Top, L] for some L, and a Generator[L].

The only Generic.Aux[Top, _] that exists implicitly is a Generic.Aux[Top, Bottom :: Int :: HNil], so we are reduced to finding a Generator[Top, Bottom :: Int :: HNil]

using the hcons rule three times, we are reduced to finding a Generator[Bottom], a Generator[Int] and a Generator[HNil].

Generator[Int] is given (I assume) and Generator[HNil] is the first rule, so we are reduced to finding a Generator[Bottom]

the only rule that can provide one, is once again the 3rd rule, so we must find a Generator[String :: HNil], since the only Generic available is a Generic.Aux[Bottom, String :: HNil].

using the hcons rule, we are down to finding a Generator[String], which can easily be provided.

This example shows different points:

first that it may take a long time when compiling to solve all these implicits (I only gave the main points of the proof, but the compiler has to try all possible branches)

second, that this resolution can only be done for a specific Generic, it cannot be inferred generically (although this might seem counter-intuitive); even if the human mind is able to tell that it will work for every Generic, the compiler cannot process it as such.


问:
Spark context wholeTextFiles ,and JavaStreamingContext textFileStream not working in Apache spark cluster
I am beginner of Apache spark and Apache spark streaming programming,
        i configured to the Azure data-lake  to Apache spark using the Hadoop connector
link its connected properly and
 i can access the Adl data through terminal itself using

hadoop fs -ls adl://xxxxx.azuredatalakestore.net

its showing list of files name contains the directory,
but i need same list to get from program itself i tried like that

```<code>SparkConf conf = new SparkConf().setAppName("ADL Application");
JavaSparkContext jsc = new JavaSparkContext(conf);
@SuppressWarnings("resource")
JavaStreamingContext jcntxt=new JavaStreamingContext(jsc,Durations.seconds(1));
JavaDStream<String> javaDStream = jcntxt.textFileStream("adl://xxxxx.azuredatalakestore.net/directory");
JavaEsSparkStreaming.saveJsonToEs(javaDStream, "modwebservice/docs");
jcntxt.start();
jcntxt.awaitTermination();
</code>```

but its not showing any list i tried in the "wholeTextFiles"
instead of "textFileStream" also but its not working, and instead of directory if i use file name its working properly i can get the data also.

```<code>JavaSparkContext jsc = new JavaSparkContext(conf);
@SuppressWarnings("resource")
JavaStreamingContext jcntxt=new JavaStreamingContext(jsc,Durations.seconds(1));
JavaRDD<String> javaRDD6 = jsc.textFile(args[0],1);
Queue<JavaRDD<String>> microbatches = new LinkedList<JavaRDD<String>>();
microbatches.add(javaRDD6);
JavaDStream<String> javaDStream = jcntxt.queueStream(microbatches);
JavaEsSparkStreaming.saveJsonToEs(javaDStream, args[1]);
jcntxt.start();
jcntxt.awaitTermination();
</code>```

and as per my knowledge Apache spark only work on local
storage and hdfs file storage location only might be,
i don't know how to get azure data lake directory contains file list
i tried 2 way but its not working
if anyone knows please share the link ,Thank you..

答:
Try to use the code below in Java to list all files on HDFS with Data Lake Store via wholeTextFiles method of class JavaSparkContext (also use the same method of SparkContext).

```<code>JavaSparkContext jsc = new JavaSparkContext();
String path = "adl://xxxxx.azuredatalakestore.net";
JavaPairRDD<String, String> jprdd = jsc.wholeTextFiles(String path);
for(Tuple2<String, String> tuple: jprdd.collect()) {  // Tuple2: <FileName, Content>
    System.out.println(tuple._1());
}
</code>```

Hope it helps.

Body:
I am beginner of Apache spark and Apache spark streaming programming,
        i configured to the Azure data-lake  to Apache spark using the Hadoop connector
link its connected properly and
 i can access the Adl data through terminal itself using

hadoop fs -ls adl://xxxxx.azuredatalakestore.net

its showing list of files name contains the directory,
but i need same list to get from program itself i tried like that

SparkConf conf = new SparkConf().setAppName("ADL Application");
JavaSparkContext jsc = new JavaSparkContext(conf);
@SuppressWarnings("resource")
JavaStreamingContext jcntxt=new JavaStreamingContext(jsc,Durations.seconds(1));
JavaDStream<String> javaDStream = jcntxt.textFileStream("adl://xxxxx.azuredatalakestore.net/directory");
JavaEsSparkStreaming.saveJsonToEs(javaDStream, "modwebservice/docs");
jcntxt.start();
jcntxt.awaitTermination();

but its not showing any list i tried in the "wholeTextFiles"
instead of "textFileStream" also but its not working, and instead of directory if i use file name its working properly i can get the data also.

JavaSparkContext jsc = new JavaSparkContext(conf);
@SuppressWarnings("resource")
JavaStreamingContext jcntxt=new JavaStreamingContext(jsc,Durations.seconds(1));
JavaRDD<String> javaRDD6 = jsc.textFile(args[0],1);
Queue<JavaRDD<String>> microbatches = new LinkedList<JavaRDD<String>>();
microbatches.add(javaRDD6);
JavaDStream<String> javaDStream = jcntxt.queueStream(microbatches);
JavaEsSparkStreaming.saveJsonToEs(javaDStream, args[1]);
jcntxt.start();
jcntxt.awaitTermination();

and as per my knowledge Apache spark only work on local
storage and hdfs file storage location only might be,
i don't know how to get azure data lake directory contains file list
i tried 2 way but its not working
if anyone knows please share the link ,Thank you..

Body:
Try to use the code below in Java to list all files on HDFS with Data Lake Store via wholeTextFiles method of class JavaSparkContext (also use the same method of SparkContext).

JavaSparkContext jsc = new JavaSparkContext();
String path = "adl://xxxxx.azuredatalakestore.net";
JavaPairRDD<String, String> jprdd = jsc.wholeTextFiles(String path);
for(Tuple2<String, String> tuple: jprdd.collect()) {  // Tuple2: <FileName, Content>
    System.out.println(tuple._1());
}

Hope it helps.


问:
Smarter way to create this responsive css grid
I'm getting crazy with a grid. For my website I have a modular grid with a fixed size, 3 x 2. In this grid I can distribute, without space and with a 1 px margin between every element, some blocks.

I can have 5 types of block:

huge, a 3 x 2 block

big-square, a 2 x 2 block

horizontal, a 2 x 1 block

vertical, a 1 x 2 block

square, 1 x 1 block.

In this image I show some variants, and un the right the "tablet" version.

I have to generate the grid using code so I don't want to create X fixed templates to fill, I want a single template that adapt itself.
Now I'm using float and some class for every variant.

For Example for first cover variant

```<code><section class="cover variant-1">
  <div class="cover-block horizontal" id="block-1">
    <img alt="image" src="https://via.placeholder.com/900x350" />
  </div>
  <div class="cover-block small" id="block-2">
    <img alt="image" src="https://via.placeholder.com/450x350" />
  </div>
  <div class="cover-block square" id="block-3">
    <img alt="image" src="https://via.placeholder.com/450x350" />
  </div>
 <div class="cover-block horizontal" id="block-4">
    <img alt="image" src="https://via.placeholder.com/900x350" />
  </div>
</section>
</code>```

And for the second cover variant

```<code><section class="cover variant-2">
  <div class="cover-block big-square" id="block-1">
    <img alt="image" src="https://via.placeholder.com/900x700" />
  </div>
  <div class="cover-block vertical" id="block-2">
    <img alt="image" src="https://via.placeholder.com/450x700" />
  </div>
</section>
</code>```

The CSS is

```<code>.cover {
  float: none;
  max-width: 1350px;
  max-height: 700px;
  margin: 0;
}
.cover .cover-block {
  float: left;
  position: relative;
  border: 0px solid #fff;
}
.cover .cover-block img {
  width: 100%;
  height: 100%;
}
.cover .cover-block.huge {
  width: 1350px;
  height: 700px;
}
.cover .cover-block.vertical {
  width: 450px;
  height: 700px;
}
.cover .cover-block.horizontal {
  width: 900px;
  height: 350px;
}
.cover .cover-block.big-square {
  width: 900px;
  height: 700px;
}
.cover .cover-block.square {
  width: 450px;
  height: 350px;
}
.cover .variant-1 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-2 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-4 {
  border-width: 1px 1px 0 0;
}
.cover .variant-1 #block-5 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-2 #block-3 {
  border-width: 1px 1px 0 0;
}
.cover .variant-2 #block-4 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-5 {
  display: none;
}
</code>```

Whit the floats I have to define an ID for every block to handle the 1 pixel space just in one direction, and I have also a lot of media queries to have this grid responsive.

Is there a smarter way to design my grid, maybe using flexbox?

Here is the Codepen

答:
So Flexbox would indeed be the way forward for such grid systems. I've made a pen for you to see how it would work.

The first row shows equal columns, and the second and third rows are split into 3 columns. (See how the classes one and two are made and you should figure the rest out yourself)

https://codepen.io/Aotik/pen/BZyLBe

This is inspired by my framework, Blossom. You can see more about Blossom's grid system here http://getblossom.io/design/grid

Body:
I'm getting crazy with a grid. For my website I have a modular grid with a fixed size, 3 x 2. In this grid I can distribute, without space and with a 1 px margin between every element, some blocks.

I can have 5 types of block:

huge, a 3 x 2 block

big-square, a 2 x 2 block

horizontal, a 2 x 1 block

vertical, a 1 x 2 block

square, 1 x 1 block.

In this image I show some variants, and un the right the "tablet" version.

I have to generate the grid using code so I don't want to create X fixed templates to fill, I want a single template that adapt itself.
Now I'm using float and some class for every variant.

For Example for first cover variant

And for the second cover variant

The CSS is

.cover {
  float: none;
  max-width: 1350px;
  max-height: 700px;
  margin: 0;
}
.cover .cover-block {
  float: left;
  position: relative;
  border: 0px solid #fff;
}
.cover .cover-block img {
  width: 100%;
  height: 100%;
}
.cover .cover-block.huge {
  width: 1350px;
  height: 700px;
}
.cover .cover-block.vertical {
  width: 450px;
  height: 700px;
}
.cover .cover-block.horizontal {
  width: 900px;
  height: 350px;
}
.cover .cover-block.big-square {
  width: 900px;
  height: 700px;
}
.cover .cover-block.square {
  width: 450px;
  height: 350px;
}
.cover .variant-1 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-2 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-4 {
  border-width: 1px 1px 0 0;
}
.cover .variant-1 #block-5 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-2 #block-3 {
  border-width: 1px 1px 0 0;
}
.cover .variant-2 #block-4 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-5 {
  display: none;
}

Whit the floats I have to define an ID for every block to handle the 1 pixel space just in one direction, and I have also a lot of media queries to have this grid responsive.

Is there a smarter way to design my grid, maybe using flexbox?

Here is the Codepen


问:
How to terminate a background while loop in Linux?
I cannot find a way to terminate a background while loop.

I started a Perl script in an infinite while loop (i.e. while true; do perl abc.pl; done) and my terminal session got disconnected.

Now I am trying to terminate that loop.

If I do ps -aux | grep perl, I see that a Perl script is running.

If I do kill -9 <process id>, it keeps showing up with different process IDs.

How can I terminate it for good?

The only work around I have found is to rename my script, and then it stops.

答:
ps -ef tells you two numbers. The process id, and the parent process id.

Kill the latter, and you'll kill the thing spawning your perl processes.

alternatively - kill -1 -1  will kill all your processes (don't do this as root!).


问:
Connecting an .xib-File to a Custom Class
I have created a custom .xib-file and a custom subclass of UIView.
What is the procedure to connect the two?

Meaning that when I set MyCustomClass in the custom class attribute, it turns into my custom .xib-file and acts according to MyCustomClass.swift.

答:
Select Whatever.xib >> Click Show Identity Inspector >> Focus at Custom Class >> Edit Class as MyCustomClass
See this example for Test.xib and Test.swift :