问:
Sql: Query returns column name instead of Value
I have structure like this to use a Dynamic column name in After Update trigger

this two query returns ColumnName instead of Value by this statement,

```<code>(select @Name from deleted)
(select @Name from inserted)
</code>```

How can i get the value from this and then store into variable?

```<code>ALTER TRIGGER [dbo].[afterUpdate_Project] ON [dbo].[Projects]
FOR UPDATE
as
begin

SET NOCOUNT ON;

DECLARE @ModifiedBy int = (select IsNULL(LastModifiedBy,0) from inserted)

 DECLARE @Name varchar(MAX)
 DECLARE my_Cursor CURSOR FOR
 (
    select C.name from sys.tables T
    inner join sys.columns C on
    T.object_id = C.object_id
    where T.name = 'Projects'
 )

 OPEN my_Cursor;

 FETCH NEXT FROM my_Cursor into @Name;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @OldValue nvarchar(MAX) = (select @Name from deleted)
        DECLARE @NewValue nvarchar(MAX) = (select @Name from inserted)
        print  @OldValue
        print  @NewValue

            If (@OldValue <> @NewValue)
                BEGIN
                    insert into EntityHistory
                    values(1, @Name, @OldValue, @NewValue, @ModifiedBy, GETDATE())
                END

    FETCH NEXT FROM my_Cursor into @Name;
    END

 CLOSE my_Cursor; DEALLOCATE my_Cursor;
 END
</code>```

答:
Finally I as able to find a solution for your problem. It involves temp tables. Using temp tables excessively is not recommended but I could not figure out better solution than that.

Following is the ALTER TRIGGER script I created and it worked perfectly for my table.

```<code>ALTER TRIGGER [dbo].[afterUpdate_Project] ON [dbo].[Projects]
FOR UPDATE
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @ModifiedBy NVARCHAR(255) = (SELECT IsNULL(UserId,0) FROM inserted)

    DECLARE @queryForInserted NVARCHAR(255)
    DECLARE @queryForDeleted NVARCHAR(255)

    DECLARE @Name varchar(MAX)
    DECLARE my_Cursor CURSOR FOR
    (
        SELECT C.name FROM sys.objects T
        INNER JOIN sys.columns C ON
        T.object_id = C.object_id
        WHERE T.name = 'Projects'
    )

    --Creating Temp table for storing single value for each of the column during iteration.
    IF OBJECT_ID('tempdb..#tmpInsertedSingleValue') IS NULL CREATE TABLE #tmpInsertedSingleValue(InsertedValue NVARCHAR(MAX))

    IF OBJECT_ID('tempdb..#tmpDeletedSingleValue') IS NULL CREATE TABLE #tmpDeletedSingleValue(DeletedValue NVARCHAR(MAX))

    --Creating temp tables and populating them with data from 'inserted' and 'deleted'
    SELECT TOP 1 * INTO #tmpInserted FROM inserted

    SELECT TOP 1 * INTO #tmpDeleted FROM deleted

    OPEN my_Cursor;

    FETCH NEXT FROM my_Cursor into @Name;

        WHILE @@FETCH_STATUS = 0
        BEGIN

            PRINT @Name

            -- Creating dynamic sql to select single column value from temp table.
            SET @queryForDeleted = 'SELECT ' + @Name + ' FROM #tmpDeleted'
            SET @queryForInserted = 'SELECT ' + @Name + ' FROM #tmpInserted'

            -- Executing dynamic sql to populabe single column value to other temp table.
            INSERT INTO #tmpDeletedSingleValue EXECUTE (@queryForDeleted)
            INSERT INTO #tmpInsertedSingleValue EXECUTE (@queryForInserted)

            -- Selecting single value in to variables.
            DECLARE @OldValue NVARCHAR(MAX) = (SELECT TOP 1 * FROM #tmpDeletedSingleValue)
            DECLARE @NewValue NVARCHAR(MAX) = (SELECT TOP 1 * FROM #tmpInsertedSingleValue)
            PRINT  @OldValue
            PRINT  @NewValue

            IF (@OldValue <> @NewValue)
            BEGIN
                INSERT INTO EntityHistory
            VALUES (1, @Name, @OldValue, @NewValue, @ModifiedBy, GETDATE())
            END

            --Clearing SingleValue temp tables after every iteration
            DELETE FROM #tmpDeletedSingleValue
            DELETE FROM #tmpInsertedSingleValue

        FETCH NEXT FROM my_Cursor into @Name;
        END

    CLOSE my_Cursor; DEALLOCATE my_Cursor;
    -- Clearing temp tables after looping thru all the columns
    DELETE FROM #tmpDeleted
    DELETE FROM #tmpInserted
END
</code>```

This should resolve your issue.

Body:
I have structure like this to use a Dynamic column name in After Update trigger

this two query returns ColumnName instead of Value by this statement,

(select @Name from deleted)
(select @Name from inserted)

How can i get the value from this and then store into variable?

ALTER TRIGGER [dbo].[afterUpdate_Project] ON [dbo].[Projects]
FOR UPDATE
as
begin

SET NOCOUNT ON;

DECLARE @ModifiedBy int = (select IsNULL(LastModifiedBy,0) from inserted)

 DECLARE @Name varchar(MAX)
 DECLARE my_Cursor CURSOR FOR
 (
    select C.name from sys.tables T
    inner join sys.columns C on
    T.object_id = C.object_id
    where T.name = 'Projects'
 )

 OPEN my_Cursor;

 FETCH NEXT FROM my_Cursor into @Name;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @OldValue nvarchar(MAX) = (select @Name from deleted)
        DECLARE @NewValue nvarchar(MAX) = (select @Name from inserted)
        print  @OldValue
        print  @NewValue

            If (@OldValue <> @NewValue)
                BEGIN
                    insert into EntityHistory
                    values(1, @Name, @OldValue, @NewValue, @ModifiedBy, GETDATE())
                END

    FETCH NEXT FROM my_Cursor into @Name;
    END

 CLOSE my_Cursor; DEALLOCATE my_Cursor;
 END

Body:
Finally I as able to find a solution for your problem. It involves temp tables. Using temp tables excessively is not recommended but I could not figure out better solution than that.

Following is the ALTER TRIGGER script I created and it worked perfectly for my table.

ALTER TRIGGER [dbo].[afterUpdate_Project] ON [dbo].[Projects]
FOR UPDATE
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @ModifiedBy NVARCHAR(255) = (SELECT IsNULL(UserId,0) FROM inserted)

    DECLARE @queryForInserted NVARCHAR(255)
    DECLARE @queryForDeleted NVARCHAR(255)

    DECLARE @Name varchar(MAX)
    DECLARE my_Cursor CURSOR FOR
    (
        SELECT C.name FROM sys.objects T
        INNER JOIN sys.columns C ON
        T.object_id = C.object_id
        WHERE T.name = 'Projects'
    )

    --Creating Temp table for storing single value for each of the column during iteration.
    IF OBJECT_ID('tempdb..#tmpInsertedSingleValue') IS NULL CREATE TABLE #tmpInsertedSingleValue(InsertedValue NVARCHAR(MAX))

    IF OBJECT_ID('tempdb..#tmpDeletedSingleValue') IS NULL CREATE TABLE #tmpDeletedSingleValue(DeletedValue NVARCHAR(MAX))

    --Creating temp tables and populating them with data from 'inserted' and 'deleted'
    SELECT TOP 1 * INTO #tmpInserted FROM inserted

    SELECT TOP 1 * INTO #tmpDeleted FROM deleted

    OPEN my_Cursor;

    FETCH NEXT FROM my_Cursor into @Name;

        WHILE @@FETCH_STATUS = 0
        BEGIN

            PRINT @Name

            -- Creating dynamic sql to select single column value from temp table.
            SET @queryForDeleted = 'SELECT ' + @Name + ' FROM #tmpDeleted'
            SET @queryForInserted = 'SELECT ' + @Name + ' FROM #tmpInserted'

            -- Executing dynamic sql to populabe single column value to other temp table.
            INSERT INTO #tmpDeletedSingleValue EXECUTE (@queryForDeleted)
            INSERT INTO #tmpInsertedSingleValue EXECUTE (@queryForInserted)

            -- Selecting single value in to variables.
            DECLARE @OldValue NVARCHAR(MAX) = (SELECT TOP 1 * FROM #tmpDeletedSingleValue)
            DECLARE @NewValue NVARCHAR(MAX) = (SELECT TOP 1 * FROM #tmpInsertedSingleValue)
            PRINT  @OldValue
            PRINT  @NewValue

            IF (@OldValue <> @NewValue)
            BEGIN
                INSERT INTO EntityHistory
            VALUES (1, @Name, @OldValue, @NewValue, @ModifiedBy, GETDATE())
            END

            --Clearing SingleValue temp tables after every iteration
            DELETE FROM #tmpDeletedSingleValue
            DELETE FROM #tmpInsertedSingleValue

        FETCH NEXT FROM my_Cursor into @Name;
        END

    CLOSE my_Cursor; DEALLOCATE my_Cursor;
    -- Clearing temp tables after looping thru all the columns
    DELETE FROM #tmpDeleted
    DELETE FROM #tmpInserted
END

This should resolve your issue.


来源: stackexchange

问:
What is the replacement of the Bash "source" command in the sh shell?
What is replacement of the source command of bash shell in sh shell?

I was getting an error while executing source in #!/bin/sh.

In #!/bin/bash, it is working well.

答: source is a synonym for the POSIX . (dot) command. Note that source/. behaves slightly differently in bash than in the POSIX standard, but that difference comes from whether or not bash is run in POSIX mode, not in which name you use.

ContentLicense: CC BY-SA 3.0


问:
Showing images on same axes
I have a basic question about MATLAB. How I can show two images on same axes? I don't want it to be in same figure (as the following code shows) but the same axes.</p>

```<code>subplot(1,2,1), subimage(X)
subplot(1,2,2), subimage(X2)
</code>```

答:
You need hold on to plot two graphs on the same axes:

```<code>figure
subimage(X)
hold on
subimage(X2)
</code>```

Title: Showing images on same axes

Body:
I have a basic question about MATLAB. How I can show two images on same axes? I don't want it to be in same figure (as the following code shows) but the same axes.

subplot(1,2,1), subimage(X)
subplot(1,2,2), subimage(X2)

Body:
You need hold on to plot two graphs on the same axes:

figure
subimage(X)
hold on
subimage(X2)


问:
How to use GIMP to change the icon's color?

I want to change the red color #c0283d to #34a2fb while keep the shadow using GIMP.

答: for this icon, pdb.gimp_colorize(drawable, hue, saturation, lightness) should work. you can look it up in gimp's procedure browser.


问:
How to add slide show animation to my sider code
I am currently working on a project for my school, I have a image slideshow.

When I click on an arrow the next image appears.

But I want it to slide and show the next picture.

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("MySlides");
  if (n > x.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = x.length
  }
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex - 1].style.display = "block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="MySlides" src="http://lorempixel.com/400/400/sports/" width="380px;" height="380px;">
<img class="MySlides" src="http://lorempixel.com/400/400/food/" width="380px;" height="380px;" style="display:none;">
<img class="MySlides" src="http://lorempixel.com/400/400/cats/" width="380px;" height="380px;" style="display:none;">
<span>‹</span>
<span>›</span></code>```

答:
$("#slideshow > div:gt(0)").hide();

var index = 1;
var maxindex = $('#slideshow > div').length;

setInterval(function () {
    $('#slideshow > div:first')
        .fadeOut(1000)
        .next()
        .fadeIn(1000)
        .end()
        .appendTo('#slideshow');
    $('ul li').removeClass('active');
    $('ul li:eq(' + index + ')').addClass('active');
    index = index < maxindex - 1 ? index + 1 : 0;
}, 3000);

for (var i = 0; i < maxindex; i++) {
    $('ul').append('

');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#slideshow {
    margin: 50px auto;
    position: relative;
    width: 240px;
    height: 240px;
    padding: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
}
#slideshow > div {
    position: absolute;
    top: 10px;
    left: 10px;
    right: 10px;
    bottom: 10px;
}

#slideshow img {
    max-width:240px;
    max-height:240px;
}

ul {
    list-style:none;
    margin:0px;
    padding:0px;
}
ul li {
    float:left;
    border-radius:10px;
    width:10px;
    height:10px;
    border:1px solid white;
    background:grey;
}
ul li.active {
    background:black;
}</code>```

```

Body:
I am currently working on a project for my school, I have a image slideshow.

When I click on an arrow the next image appears.

But I want it to slide and show the next picture.

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("MySlides");
  if (n > x.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = x.length
  }
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex - 1].style.display = "block";
}

‹
›

Body:
$("#slideshow > div:gt(0)").hide();

var index = 1;
var maxindex = $('#slideshow > div').length;

setInterval(function () {
    $('#slideshow > div:first')
        .fadeOut(1000)
        .next()
        .fadeIn(1000)
        .end()
        .appendTo('#slideshow');
    $('ul li').removeClass('active');
    $('ul li:eq(' + index + ')').addClass('active');
    index = index < maxindex - 1 ? index + 1 : 0;
}, 3000);

for (var i = 0; i < maxindex; i++) {
    $('ul').append('<li class="' + (i == 0 ? 'active' : '') + '"></li>');
}

#slideshow {
    margin: 50px auto;
    position: relative;
    width: 240px;
    height: 240px;
    padding: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
}
#slideshow > div {
    position: absolute;
    top: 10px;
    left: 10px;
    right: 10px;
    bottom: 10px;
}

#slideshow img {
    max-width:240px;
    max-height:240px;
}

ul {
    list-style:none;
    margin:0px;
    padding:0px;
}
ul li {
    float:left;
    border-radius:10px;
    width:10px;
    height:10px;
    border:1px solid white;
    background:grey;
}
ul li.active {
    background:black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<body>
<div id="slideshow">
<div>
<img class="MySlides" src="http://lorempixel.com/400/400/food/" width="380px;" height="380px;">
</div>
<div>
<img class="MySlides" src="https://www.w3schools.com/css/img_fjords.jpg" width="380px;" height="380px; ">
 </div>
 <ul></ul>

</div>
</body>


问:
How to import a list of contacts to telegram from desktop application?
Is there a way to easily import a list of contacts to telegram from desktop application?

I found contacts.importContacts method in Telegram API, but don't understand how to use it.

答:
If you use TLSharp library in your desktop application, easily you can call contacts.importContacts method in this way:

```<code>client = new TelegramClient(apiId, apiHash);
await client.ConnectAsync();
var result = await client.GetContactsAsync();
</code>```

and for example use the result variable in this way:

```<code>var user = result.users.lists
  .Where(x => x.GetType() == typeof(TLUser))
  .Cast<TLUser>()
  .Where(x => x.first_name == textBox1.Text);
if (user.ToList().Count != 0)
{
    foreach (var u in user)
    await client.SendMessageAsync(new TLInputPeerUser() { user_id = u.id }, textBox1.Text);
}
</code>```

Body:
If you use TLSharp library in your desktop application, easily you can call contacts.importContacts method in this way:

client = new TelegramClient(apiId, apiHash);
await client.ConnectAsync();
var result = await client.GetContactsAsync();

and for example use the result variable in this way:

var user = result.users.lists
  .Where(x => x.GetType() == typeof(TLUser))
  .Cast<TLUser>()
  .Where(x => x.first_name == textBox1.Text);
if (user.ToList().Count != 0)
{
    foreach (var u in user)
    await client.SendMessageAsync(new TLInputPeerUser() { user_id = u.id }, textBox1.Text);
}


问:
How can I remove an override check button in TYPO3 TCA
Servus,
I am searching for the solution how can I remove an override check button in TYPO3 TCA.

My TCA configuration:

```<code>'myfield' => array(
    'l10n_mode' => 'mergeIfNotBlank',
    'exclude'   => 1,
    'label'     => 'my field',
    'config'    => array(
        'type'        => 'input',
        'size'        => '20',
        'eval'        => 'trim',
        'placeholder' => 'my placeholder',
    )
),
</code>```

答:
It is a problem with your placeholder. If you dont need your placeholder, you can remove it.

So your code can look like this:

```<code>'myfield' => array(
    'l10n_mode' => 'mergeIfNotBlank',
    'exclude'   => 1,
    'label'     => 'my field',
    'config'    => array(
        'type'        => 'input',
        'size'        => '20',
        'eval'        => 'trim',
    )
),
</code>```

so after that this should looks like this:

Body:
Servus,
I am searching for the solution how can I remove an override check button in TYPO3 TCA.

My TCA configuration:

'myfield' => array(
    'l10n_mode' => 'mergeIfNotBlank',
    'exclude'   => 1,
    'label'     => 'my field',
    'config'    => array(
        'type'        => 'input',
        'size'        => '20',
        'eval'        => 'trim',
        'placeholder' => 'my placeholder',
    )
),

Body:
It is a problem with your placeholder. If you dont need your placeholder, you can remove it.

So your code can look like this:

'myfield' => array(
    'l10n_mode' => 'mergeIfNotBlank',
    'exclude'   => 1,
    'label'     => 'my field',
    'config'    => array(
        'type'        => 'input',
        'size'        => '20',
        'eval'        => 'trim',
    )
),

so after that this should looks like this:


问:
pow for SSE types
I do some explicitly vectorised computations using SSE types, such as __m128 (defined in xmmintrin.h etc), but now I need to raise all elements of the vector to some (same) power, i.e. ideally I would want something like __m128 _mm_pow_ps(__m128, float), which unfortunately doesn't exist.

What is the best way around this? I could store the vector, call std::pow on each element, and then reload it. Is this the best I can do? How do compilers implement a call to std::pow when auto-vectorising code that otherwise is well vectorisable? Are there any libraries that provide something useful?

(note that this question is related by not a duplicate and certainly doesn't have a useful answer.)

答:
An AVX version of the ssemath library is now available: http://software-lisc.fbk.eu/avx_mathfun/

with the library you can use:

```<code>exp256_ps(y*log256_ps(x)); // for pow(x, y)
</code>```

Title: pow for SSE types

Body:
An AVX version of the ssemath library is now available: http://software-lisc.fbk.eu/avx_mathfun/

with the library you can use:

exp256_ps(y*log256_ps(x)); // for pow(x, y)


问:
Toggle visibility of sibling element of $(this) element | No unique ID [jQuery]
I need div.edit-button to toggle its sibling div.additionalFieldForm.

Note that there's more than one div.edit-button and div.additionalFieldForm on the page, but I would like to target the div.additionalFieldForm that is in the same "family" as the div.edit-button that was clicked.

$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).closest("div").prev().toggle();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm">Content</div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm">Content</div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
</ul></code>```

I've tried other selectors but I couldn't specifically target just the div.additionalFieldForm sibling of the edit button being clicked.

EDIT: I realize that there must be an underlying problem because the selector works on jsFiddle (http://jsfiddle.net/wf7jjoq7/), but not on my site, without any console errors.

答:
li is the common parent. So,

```<code>$(".edit-button").click(function () {
 $(this).closest("li").find(".additionalFieldForm").toggle();
});
</code>```

Body:
I need div.edit-button to toggle its sibling div.additionalFieldForm.

Note that there's more than one div.edit-button and div.additionalFieldForm on the page, but I would like to target the div.additionalFieldForm that is in the same "family" as the div.edit-button that was clicked.

$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).closest("div").prev().toggle();

});

    Additional Field

Content

Edit

Remove

    Additional Field

Content

Edit

Remove

I've tried other selectors but I couldn't specifically target just the div.additionalFieldForm sibling of the edit button being clicked.

EDIT: I realize that there must be an underlying problem because the selector works on jsFiddle (http://jsfiddle.net/wf7jjoq7/), but not on my site, without any console errors.

Body:
li is the common parent. So,

$(".edit-button").click(function () {
 $(this).closest("li").find(".additionalFieldForm").toggle();
});


问:
Extra tab in the scrollable tablayout
I have problem in tablayout section. i created a scrollable tablayout with view pager like in
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
and the i have seen an empty tab in the last. i can click that tab but nothing shows. But when i swipe the view pager it never enters in that tab.

if this question already solved please give me a link in the comment...
Thanks in ADVANCE...

Here is my code

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.event_home);
    final Loading loading = new Loading(this);
    loading.show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            loading.cancel();
        }
    }, Constants.WAIT_TIME);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPager.setOffscreenPageLimit(7);
    Interpolator sInterpolator = new AccelerateInterpolator();
    try {
        Field mScroller;
        mScroller = ViewPager.class.getDeclaredField("mScroller");
        mScroller.setAccessible(true);
        DecelerateInterpolator decelerateInterpolator = new DecelerateInterpolator();
        FixedSpeedScroller scroller = new FixedSpeedScroller(viewPager.getContext(), decelerateInterpolator);
        scroller.SetDuration(500);
        mScroller.set(viewPager, scroller);
    } catch (NoSuchFieldException e) {
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    }
    setupViewPager(viewPager);
    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

  private void setupTabIcons() {
    tabLayout.addTab(tabLayout.newTab());
    tabLayout.getTabAt(0).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(1).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(2).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(3).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(4).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(5).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(6).setCustomView(R.layout.event_tablayout);
    View tab1_view = tabLayout.getTabAt(0).getCustomView();
    View tab2_view = tabLayout.getTabAt(1).getCustomView();
    View tab3_view = tabLayout.getTabAt(2).getCustomView();
    View tab4_view = tabLayout.getTabAt(3).getCustomView();
    View tab5_view = tabLayout.getTabAt(4).getCustomView();
    View tab6_view = tabLayout.getTabAt(5).getCustomView();
    View tab7_view = tabLayout.getTabAt(6).getCustomView();
    TextView tab1_title = (TextView) tab1_view.findViewById(R.id.tabtitle);
    ImageView img1 = (ImageView) tab1_view.findViewById(R.id.tabicon);
    TextView tab2_title = (TextView) tab2_view.findViewById(R.id.tabtitle);
    ImageView img2 = (ImageView) tab2_view.findViewById(R.id.tabicon);
    TextView tab3_title = (TextView) tab3_view.findViewById(R.id.tabtitle);
    ImageView img3 = (ImageView) tab3_view.findViewById(R.id.tabicon);
    TextView tab4_title = (TextView) tab4_view.findViewById(R.id.tabtitle);
    ImageView img4 = (ImageView) tab4_view.findViewById(R.id.tabicon);
    TextView tab5_title = (TextView) tab5_view.findViewById(R.id.tabtitle);
    ImageView img5 = (ImageView) tab5_view.findViewById(R.id.tabicon);
    TextView tab6_title = (TextView) tab6_view.findViewById(R.id.tabtitle);
    ImageView img6 = (ImageView) tab6_view.findViewById(R.id.tabicon);
    TextView tab7_title = (TextView) tab7_view.findViewById(R.id.tabtitle);
    ImageView img7 = (ImageView) tab7_view.findViewById(R.id.tabicon);
    tab1_title.setText("DASHBOARD");
    img1.setImageResource(R.drawable.ic_home);
    tab2_title.setText("ABOUT");
    img2.setImageResource(R.drawable.ic_information);
    tab3_title.setText("QR CODE");
    img3.setImageResource(R.drawable.ic_qrcode);
    tab4_title.setText("UPDATES");
    img4.setImageResource(R.drawable.ic_announcement);
    tab5_title.setText("TEAM");
    img5.setImageResource(R.drawable.ic_team);
    tab6_title.setText(" CONTACT US");
    img6.setImageResource(R.drawable.ic_mobile_phone);
    tab7_title.setText("REGISTER");
    img7.setImageResource(R.drawable.ic_register);
}

public void setupViewPager(ViewPager viewPager) {
    Adapter_pager adapter = new Adapter_pager(getSupportFragmentManager());
    adapter.addFrag(new Dashboard(), "Dashboard");
    adapter.addFrag(new Details(), "Details");
    adapter.addFrag(new Qrcodedisplay(), "Qr codes");
    adapter.addFrag(new Update(), "Update");
    adapter.addFrag(new Teams(), "Team");
    adapter.addFrag(new Contact_Us(), "Contact");
    adapter.addFrag(new Event_register(), "Register");
    viewPager.setAdapter(adapter);
}
</code>```

答:
You can try to add this to your tabLayout

```<code>tabLayout.setTabMode(TabLayout.MODE_FIXED);
</code>```

And if this dont work please post ur xml of that activity and be sure u have set the width to tabLayout to match_parent.

And i am not sure but give this a try in your code

```<code> private void setupTabIcons() {
    tabLayout.addTab(tabLayout.newTab());
.....
}
</code>```

Delete that line, because its looks like u are adding a empty tab

Title: Extra tab in the scrollable tablayout

Body:
I have problem in tablayout section. i created a scrollable tablayout with view pager like in
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
and the i have seen an empty tab in the last. i can click that tab but nothing shows. But when i swipe the view pager it never enters in that tab.

if this question already solved please give me a link in the comment...
Thanks in ADVANCE...

Here is my code

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.event_home);
    final Loading loading = new Loading(this);
    loading.show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            loading.cancel();
        }
    }, Constants.WAIT_TIME);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPager.setOffscreenPageLimit(7);
    Interpolator sInterpolator = new AccelerateInterpolator();
    try {
        Field mScroller;
        mScroller = ViewPager.class.getDeclaredField("mScroller");
        mScroller.setAccessible(true);
        DecelerateInterpolator decelerateInterpolator = new DecelerateInterpolator();
        FixedSpeedScroller scroller = new FixedSpeedScroller(viewPager.getContext(), decelerateInterpolator);
        scroller.SetDuration(500);
        mScroller.set(viewPager, scroller);
    } catch (NoSuchFieldException e) {
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    }
    setupViewPager(viewPager);
    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

  private void setupTabIcons() {
    tabLayout.addTab(tabLayout.newTab());
    tabLayout.getTabAt(0).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(1).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(2).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(3).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(4).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(5).setCustomView(R.layout.event_tablayout);
    tabLayout.getTabAt(6).setCustomView(R.layout.event_tablayout);
    View tab1_view = tabLayout.getTabAt(0).getCustomView();
    View tab2_view = tabLayout.getTabAt(1).getCustomView();
    View tab3_view = tabLayout.getTabAt(2).getCustomView();
    View tab4_view = tabLayout.getTabAt(3).getCustomView();
    View tab5_view = tabLayout.getTabAt(4).getCustomView();
    View tab6_view = tabLayout.getTabAt(5).getCustomView();
    View tab7_view = tabLayout.getTabAt(6).getCustomView();
    TextView tab1_title = (TextView) tab1_view.findViewById(R.id.tabtitle);
    ImageView img1 = (ImageView) tab1_view.findViewById(R.id.tabicon);
    TextView tab2_title = (TextView) tab2_view.findViewById(R.id.tabtitle);
    ImageView img2 = (ImageView) tab2_view.findViewById(R.id.tabicon);
    TextView tab3_title = (TextView) tab3_view.findViewById(R.id.tabtitle);
    ImageView img3 = (ImageView) tab3_view.findViewById(R.id.tabicon);
    TextView tab4_title = (TextView) tab4_view.findViewById(R.id.tabtitle);
    ImageView img4 = (ImageView) tab4_view.findViewById(R.id.tabicon);
    TextView tab5_title = (TextView) tab5_view.findViewById(R.id.tabtitle);
    ImageView img5 = (ImageView) tab5_view.findViewById(R.id.tabicon);
    TextView tab6_title = (TextView) tab6_view.findViewById(R.id.tabtitle);
    ImageView img6 = (ImageView) tab6_view.findViewById(R.id.tabicon);
    TextView tab7_title = (TextView) tab7_view.findViewById(R.id.tabtitle);
    ImageView img7 = (ImageView) tab7_view.findViewById(R.id.tabicon);
    tab1_title.setText("DASHBOARD");
    img1.setImageResource(R.drawable.ic_home);
    tab2_title.setText("ABOUT");
    img2.setImageResource(R.drawable.ic_information);
    tab3_title.setText("QR CODE");
    img3.setImageResource(R.drawable.ic_qrcode);
    tab4_title.setText("UPDATES");
    img4.setImageResource(R.drawable.ic_announcement);
    tab5_title.setText("TEAM");
    img5.setImageResource(R.drawable.ic_team);
    tab6_title.setText(" CONTACT US");
    img6.setImageResource(R.drawable.ic_mobile_phone);
    tab7_title.setText("REGISTER");
    img7.setImageResource(R.drawable.ic_register);
}

public void setupViewPager(ViewPager viewPager) {
    Adapter_pager adapter = new Adapter_pager(getSupportFragmentManager());
    adapter.addFrag(new Dashboard(), "Dashboard");
    adapter.addFrag(new Details(), "Details");
    adapter.addFrag(new Qrcodedisplay(), "Qr codes");
    adapter.addFrag(new Update(), "Update");
    adapter.addFrag(new Teams(), "Team");
    adapter.addFrag(new Contact_Us(), "Contact");
    adapter.addFrag(new Event_register(), "Register");
    viewPager.setAdapter(adapter);
}

Body:
You can try to add this to your tabLayout

tabLayout.setTabMode(TabLayout.MODE_FIXED);

And if this dont work please post ur xml of that activity and be sure u have set the width to tabLayout to match_parent.

And i am not sure but give this a try in your code

 private void setupTabIcons() {
    tabLayout.addTab(tabLayout.newTab());
.....
}

Delete that line, because its looks like u are adding a empty tab


问:
Azure Service Fabric Multi-Tenancy with microservice
I  want  to  develop   the  Micro-service   apps    using   Azure Service Fabric Multi-Tenant ,   for   this   i   already   Configured   Active   Directive   with   Multi   Domain   dev,Prod   etc.

I  did   not  get  any   sample   reference    which   will  help   me   to   get  start   this   topic

I   already   followed   this   link

Azure Service Fabric Multi-Tenancy

But   not   find   any   sample   reference

答:
I am not sure if this is going to help you. But I believe you should follow this process

Create Service Fabric package for your application (using msbuild or VS).

Upload package into Service Fabric Image Store through api (example). This will create a base ApplicationType for you which you will use later.

Now from that ApplicationType create a new application Instance using New-ServiceFabricApplication command. Just specify different ApplicationName and use same ApplicationTypeName. If you need to override some parameters, specify ApplicationParameter.

You can create as many Instances as you need from original ApplicationType.


问:
Why is C# Linq Count() method missing IReadOnlyCollection?
This is an extension of Why doesn't generic ICollection implement IReadOnlyCollection in .NET 4.5?

Design and compatibility are the main reasons.

When a method needs to get both ICollection and IReadCollection as parameter, the easiest solution is then to use IEnumerable instead since  both extend it.

Then, one could use the Linq Count() method instead of using directly the Count property.

This is an extract of System.Linq.Enumerable.cs from https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,41ef9e39e54d0d0b

```<code>public static int Count<TSource>(this IEnumerable<TSource> source) {
        if (source == null) throw Error.ArgumentNull("source");
        ICollection<TSource> collectionoft = source as ICollection<TSource>;
        if (collectionoft != null) return collectionoft.Count;
        ICollection collection = source as ICollection;
        if (collection != null) return collection.Count;
        int count = 0;
        using (IEnumerator<TSource> e = source.GetEnumerator()) {
            checked {
                while (e.MoveNext()) count++;
            }
        }
        return count;
    }
</code>```

It first checks if it is a collection and in that case directly return Count so the performance cost will be minimal.
However, why does this this implementation of Count() is does not have a similar check with IReadOnlyCollection?

I don't see compatibility to be an issue here: older code written with .NET<4  that get compiled with .NET 4.5+ can check the IReadOnlyCollection even if nothing use it...

答:
If you have deal with IReadOnlyCollection you can get count directly from Count property of IReadOnlyCollection.
https://msdn.microsoft.com/en-us/library/hh881542(v=vs.110).aspx

It would be wrong to add dependency from general Linq Count() to more specific IReadOnlyCollection.

UPD

Linq Count() it's a core function that works with IEnumerable, so any cast inside it just some performance hack's. Count() extension can't have specific code for each IEnumerable that have count somewhere. If you want you can make extension self. But, probably, naming can be better

Body:
This is an extension of Why doesn't generic ICollection implement IReadOnlyCollection in .NET 4.5?

Design and compatibility are the main reasons.

When a method needs to get both ICollection and IReadCollection as parameter, the easiest solution is then to use IEnumerable instead since  both extend it.

Then, one could use the Linq Count() method instead of using directly the Count property.

This is an extract of System.Linq.Enumerable.cs from https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,41ef9e39e54d0d0b

public static int Count<TSource>(this IEnumerable<TSource> source) {
        if (source == null) throw Error.ArgumentNull("source");
        ICollection<TSource> collectionoft = source as ICollection<TSource>;
        if (collectionoft != null) return collectionoft.Count;
        ICollection collection = source as ICollection;
        if (collection != null) return collection.Count;
        int count = 0;
        using (IEnumerator<TSource> e = source.GetEnumerator()) {
            checked {
                while (e.MoveNext()) count++;
            }
        }
        return count;
    }

It first checks if it is a collection and in that case directly return Count so the performance cost will be minimal.
However, why does this this implementation of Count() is does not have a similar check with IReadOnlyCollection?

I don't see compatibility to be an issue here: older code written with .NET<4  that get compiled with .NET 4.5+ can check the IReadOnlyCollection even if nothing use it...


问:
What's the difference between faking, mocking, and stubbing?
I know how I use these terms, but I'm wondering if there are accepted definitions for faking, mocking, and stubbing for unit tests?  How do you define these for your tests?  Describe situations where you might use each.

Here is how I use them:

Fake: a class that implements an interface but contains fixed data and no logic.  Simply returns "good" or "bad" data depending on the implementation.

Mock: a class that implements an interface and allows the ability to dynamically set the values to return/exceptions to throw from particular methods and provides the ability to check if particular methods have been called/not called.

Stub: Like a mock class, except that it doesn't provide the ability to verify that methods have been called/not called.

Mocks and stubs can be hand generated or generated by a mocking framework.  Fake classes are generated by hand.  I use mocks primarily to verify interactions between my class and dependent classes.  I use stubs once I have verified the interactions and am testing alternate paths through my code.  I use fake classes primarily to abstract out data dependencies or when mocks/stubs are too tedious to set up each time.

答:
If you are familiar with Arrange-Act-Assert, then one way of explaining the difference between stub and mock that might be useful for you, is that stubs belong to the arrange section as they are for arranging input state, and mocks belong to the assert section as they are for asserting results against.

Dummies don't do anything. They are just for filling up parameter lists, so that you don't get undefined or null errors. They also exist to satisfy the type checker in statically typed languages, so that you can be allowed to compile and run.

OwnerDisplayName: tvanfosson

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: tvanfosson

ContentLicense: CC BY-SA 4.0


问:
isConsecutiveStraightFlush consecutive array check
The assignment I have is to return true if a deck of cards is a consecutive straight flush, which means an entire deck that consists of a sequence of  cards of the same suit with consecutive ranks. Since these are cards, this would mean that a card with rank 14 (A) would go BEFORE a card with rank 2.

How would I go about establishing that the order of cards goes 12,13,14,2,3 for example?

This is the Card class

```<code>public class Card {
    private String suit;
    private int rank;

    public Card(String suit, int rank) {
        super();
        this.suit = suit;
        this.rank = rank;
    }

    @Override
    public String toString() {
        return "[" + rank  + "," + suit + "]";
    }

    @Override
    public boolean equals(Object c2) {
        if (!(c2 instanceof Card)) {
            throw new RuntimeException("Illegal argument to Card.equals()");
        }
        Card card2 = (Card) c2;
        return ((this.getSuit().equals(card2.getSuit())) &&
                (this.getRank() == card2.getRank()));
    }

    public String getSuit() {
        return suit;
    }

    public int getRank() {
        return rank;
    }

    public boolean sameSuitAs(Card card2) {
        return (this.getSuit().equals(card2.getSuit()));
    }

    public boolean sameRankAs(Card card2) {
        return (this.getRank() == card2.getRank());
    }

    public boolean isAnA() {
        if (getRank() != 14) {
            return false;
        }
        return true;
    }

    public boolean isPair(Card c) {
        int rank = getRank();
        if (rank == c.getRank()) {
            return true;
        }
        return false;
    }

    public boolean isTrio(Card c1, Card c2) {
        if (c1.isPair(c2) == true ) {
            if (isPair(c1) == true) {
                return true;
            }
        }
        return false;
    }

    public boolean isFourTuple(Card c1, Card c2, Card c3) {
        if (c1.isPair(c2) == true ) {
            if (c2.isPair(c3) == true) {
                if (isPair(c1) == true) {
                    return true;
                }
            }
        }
        return false;
    }

    public static long countCardsBySuit(Card[] deck, Card target) {
        long result = 0;
        String suit = target.getSuit();
        for (int i = 0; i < deck.length; i++) {
            if (suit == deck[i].getSuit()) {
                result ++;
            }
        }
        return result;
    }

     public static boolean cardExists(Card[] deck, Card target) {
         String targetsuit = target.getSuit();
         int targetrank = target.getRank();
         for (int i = 0; i < deck.length; i++) {
             if (targetsuit == deck[i].getSuit() && targetrank == deck[i].getRank()) {
                 return true;
             }
         }
         return false;
     }

     public static boolean consecutivePairExists(Card[] deck) {
         int pairs = 0;
         for (int i = 0; i < deck.length; i++) {
             int targetrank = deck[i].getRank();
             for (int j = 0 + i + 1; i < deck.length - 3; j ++) {
                 if (targetrank == deck[j].getRank()) {
                     pairs++;
                     if (pairs > 1) {
                         return true;
                     }
                 }
             }
         }
         return false;
     }

     public static boolean pairExists(Card[] deck) {
         for (int i = 0; i < deck.length; i++) {
             int targetrank = deck[i].getRank();
             if (i == 0) {
                 for (int k = 1 ; k <deck.length; k++) {
                     if (targetrank == deck[k].getRank()) {
                         return true;
                     }
                 }
             }
             else {
                 for (int j = i + 1 ; j <deck.length; j++) {
                     if (targetrank == deck[j].getRank()) {
                         return true;
                     }
                 }
             }
         }
         return false;
     }

     public static boolean isConsecutiveStraightFlush(Card[] deck) {
         if (deck.length > 1) {
             long result = 0;
             String suit = deck[0].getSuit();
                for (int i = 1; i < deck.length; i++) {
                    if (suit == deck[i].getSuit()) {
                        result ++;
                    }
                }
                if (result == deck.length - 1) {
                    int count = 0;
                    int rank = deck[0].getRank();
                    for (int j = 1; j < deck.length; j++) {
                        if (rank - deck[j].getRank() == -1) {
                            count++;
                            rank = deck[j].getRank();
                            if (count == deck.length - 1) {
                                return true;
                            }
                        }
                    }
                }
         }
         return false;
     }
}
</code>```

and this is the JUnit Test Case CardTest

```<code>import static org.junit.Assert.*;
import org.junit.Test;

public class CardTest {

    Card diamond1 = new Card("Diamond", 1);
    Card diamond2 = new Card("Diamond", 2);
    Card spade1 = new Card("Spade", 1);
    Card spade2 = new Card("Spade", 2);
    Card spadeA = new Card("Spade", 14);

        Card card2C = new Card("Club", 2);
        Card card2S = new Card("Spade", 2);
        Card card2D = new Card("Diamond", 2);
        Card card2H = new Card("Heart", 2);

        Card card3C = new Card("Club", 3);
        Card card4C = new Card("Club", 4);
        Card card5C = new Card("Club", 5);
        Card card6C = new Card("Club", 6);
        Card card7C = new Card("Club", 7);
        Card card8C = new Card("Club", 8);
        Card card9C = new Card("Club", 9);
        Card card10C = new Card("Club", 10);
        Card cardJC = new Card("Club", 11);
        Card cardQC = new Card("Club", 12);
        Card cardKC = new Card("Club", 13);
        Card cardAC = new Card("Club", 14);

        Card[] deck1 = { card2C, card2S, card2D, card3C };

        Card[] deck2 = { card2C, card3C, card2D};

        Card[] deck3 = { card2C, card3C, spadeA};

        Card[] straightFlush1 = { card2C, card3C, card4C, card5C, card6C};
        Card[] straightFlush2 = { cardQC, cardKC, cardAC, card2C, card3C};

        Card[] emptyDeck = {};

    @Test
    public void testToString() {
        assertTrue("Card.toString: generates incorrect String", diamond1.toString().equals("[1,Diamond]"));
        assertTrue("Card.toString: generates incorrect String", spade2.toString().equals("[2,Spade]"));
    }

    @Test
    public void testEquals() {
        assertTrue("Card.equals: Yields false incorrectly", diamond1.equals(diamond1));
        assertFalse("Card.equals: Yields true incorrectly", diamond1.equals(diamond2));
    }

    @Test
    public void testSameSuitRank() {
        assertTrue("Card.sameRankAs: Yields false incorrectly", diamond1.sameRankAs(spade1));
        assertTrue("Card.sameSuitAs: Yields false incorrectly", diamond1.sameSuitAs(diamond2));
        assertFalse("Card.sameRankAs: Yields true incorrectly", spade1.sameRankAs(spade2));
        assertFalse("Card.sameSuitAs: Yields true incorrectly", spade2.sameSuitAs(diamond1));
    }

    @Test
    public void testIsConsecutiveStraightFlush() {
        assertFalse("isConsecutiveStraightFlush: returns true incorrectly", Card.isConsecutiveStraightFlush(emptyDeck));
        assertFalse("isConsecutiveStraightFlush: returns true incorrectly", Card.isConsecutiveStraightFlush(deck1));
        assertTrue("isConsecutiveStraightFlush: returns false incorrectly", Card.isConsecutiveStraightFlush(straightFlush1));
        assertTrue("isConsecutiveStraightFlush: returns false incorrectly", Card.isConsecutiveStraightFlush(straightFlush2));
    }
}
</code>```

Any help would be appreciated

答:
You need to add this special condition to your if (rank - deck[j].getRank() == -1).

```<code>if (rank - deck[j].getRank() == -1 || (rank == 14 && deck[j].getRank() == 2))
</code>```

Body:
The assignment I have is to return true if a deck of cards is a consecutive straight flush, which means an entire deck that consists of a sequence of  cards of the same suit with consecutive ranks. Since these are cards, this would mean that a card with rank 14 (A) would go BEFORE a card with rank 2.

How would I go about establishing that the order of cards goes 12,13,14,2,3 for example?

This is the Card class

public class Card {
    private String suit;
    private int rank;

    public Card(String suit, int rank) {
        super();
        this.suit = suit;
        this.rank = rank;
    }

    @Override
    public String toString() {
        return "[" + rank  + "," + suit + "]";
    }

    @Override
    public boolean equals(Object c2) {
        if (!(c2 instanceof Card)) {
            throw new RuntimeException("Illegal argument to Card.equals()");
        }
        Card card2 = (Card) c2;
        return ((this.getSuit().equals(card2.getSuit())) &&
                (this.getRank() == card2.getRank()));
    }

    public String getSuit() {
        return suit;
    }

    public int getRank() {
        return rank;
    }

    public boolean sameSuitAs(Card card2) {
        return (this.getSuit().equals(card2.getSuit()));
    }

    public boolean sameRankAs(Card card2) {
        return (this.getRank() == card2.getRank());
    }

    public boolean isAnA() {
        if (getRank() != 14) {
            return false;
        }
        return true;
    }

    public boolean isPair(Card c) {
        int rank = getRank();
        if (rank == c.getRank()) {
            return true;
        }
        return false;
    }

    public boolean isTrio(Card c1, Card c2) {
        if (c1.isPair(c2) == true ) {
            if (isPair(c1) == true) {
                return true;
            }
        }
        return false;
    }

    public boolean isFourTuple(Card c1, Card c2, Card c3) {
        if (c1.isPair(c2) == true ) {
            if (c2.isPair(c3) == true) {
                if (isPair(c1) == true) {
                    return true;
                }
            }
        }
        return false;
    }

    public static long countCardsBySuit(Card[] deck, Card target) {
        long result = 0;
        String suit = target.getSuit();
        for (int i = 0; i < deck.length; i++) {
            if (suit == deck[i].getSuit()) {
                result ++;
            }
        }
        return result;
    }

     public static boolean cardExists(Card[] deck, Card target) {
         String targetsuit = target.getSuit();
         int targetrank = target.getRank();
         for (int i = 0; i < deck.length; i++) {
             if (targetsuit == deck[i].getSuit() && targetrank == deck[i].getRank()) {
                 return true;
             }
         }
         return false;
     }

     public static boolean consecutivePairExists(Card[] deck) {
         int pairs = 0;
         for (int i = 0; i < deck.length; i++) {
             int targetrank = deck[i].getRank();
             for (int j = 0 + i + 1; i < deck.length - 3; j ++) {
                 if (targetrank == deck[j].getRank()) {
                     pairs++;
                     if (pairs > 1) {
                         return true;
                     }
                 }
             }
         }
         return false;
     }

     public static boolean pairExists(Card[] deck) {
         for (int i = 0; i < deck.length; i++) {
             int targetrank = deck[i].getRank();
             if (i == 0) {
                 for (int k = 1 ; k <deck.length; k++) {
                     if (targetrank == deck[k].getRank()) {
                         return true;
                     }
                 }
             }
             else {
                 for (int j = i + 1 ; j <deck.length; j++) {
                     if (targetrank == deck[j].getRank()) {
                         return true;
                     }
                 }
             }
         }
         return false;
     }

     public static boolean isConsecutiveStraightFlush(Card[] deck) {
         if (deck.length > 1) {
             long result = 0;
             String suit = deck[0].getSuit();
                for (int i = 1; i < deck.length; i++) {
                    if (suit == deck[i].getSuit()) {
                        result ++;
                    }
                }
                if (result == deck.length - 1) {
                    int count = 0;
                    int rank = deck[0].getRank();
                    for (int j = 1; j < deck.length; j++) {
                        if (rank - deck[j].getRank() == -1) {
                            count++;
                            rank = deck[j].getRank();
                            if (count == deck.length - 1) {
                                return true;
                            }
                        }
                    }
                }
         }
         return false;
     }
}

and this is the JUnit Test Case CardTest

import static org.junit.Assert.*;
import org.junit.Test;

public class CardTest {

    Card diamond1 = new Card("Diamond", 1);
    Card diamond2 = new Card("Diamond", 2);
    Card spade1 = new Card("Spade", 1);
    Card spade2 = new Card("Spade", 2);
    Card spadeA = new Card("Spade", 14);

        Card card2C = new Card("Club", 2);
        Card card2S = new Card("Spade", 2);
        Card card2D = new Card("Diamond", 2);
        Card card2H = new Card("Heart", 2);

        Card card3C = new Card("Club", 3);
        Card card4C = new Card("Club", 4);
        Card card5C = new Card("Club", 5);
        Card card6C = new Card("Club", 6);
        Card card7C = new Card("Club", 7);
        Card card8C = new Card("Club", 8);
        Card card9C = new Card("Club", 9);
        Card card10C = new Card("Club", 10);
        Card cardJC = new Card("Club", 11);
        Card cardQC = new Card("Club", 12);
        Card cardKC = new Card("Club", 13);
        Card cardAC = new Card("Club", 14);

        Card[] deck1 = { card2C, card2S, card2D, card3C };

        Card[] deck2 = { card2C, card3C, card2D};

        Card[] deck3 = { card2C, card3C, spadeA};

        Card[] straightFlush1 = { card2C, card3C, card4C, card5C, card6C};
        Card[] straightFlush2 = { cardQC, cardKC, cardAC, card2C, card3C};

        Card[] emptyDeck = {};

    @Test
    public void testToString() {
        assertTrue("Card.toString: generates incorrect String", diamond1.toString().equals("[1,Diamond]"));
        assertTrue("Card.toString: generates incorrect String", spade2.toString().equals("[2,Spade]"));
    }

    @Test
    public void testEquals() {
        assertTrue("Card.equals: Yields false incorrectly", diamond1.equals(diamond1));
        assertFalse("Card.equals: Yields true incorrectly", diamond1.equals(diamond2));
    }

    @Test
    public void testSameSuitRank() {
        assertTrue("Card.sameRankAs: Yields false incorrectly", diamond1.sameRankAs(spade1));
        assertTrue("Card.sameSuitAs: Yields false incorrectly", diamond1.sameSuitAs(diamond2));
        assertFalse("Card.sameRankAs: Yields true incorrectly", spade1.sameRankAs(spade2));
        assertFalse("Card.sameSuitAs: Yields true incorrectly", spade2.sameSuitAs(diamond1));
    }

    @Test
    public void testIsConsecutiveStraightFlush() {
        assertFalse("isConsecutiveStraightFlush: returns true incorrectly", Card.isConsecutiveStraightFlush(emptyDeck));
        assertFalse("isConsecutiveStraightFlush: returns true incorrectly", Card.isConsecutiveStraightFlush(deck1));
        assertTrue("isConsecutiveStraightFlush: returns false incorrectly", Card.isConsecutiveStraightFlush(straightFlush1));
        assertTrue("isConsecutiveStraightFlush: returns false incorrectly", Card.isConsecutiveStraightFlush(straightFlush2));
    }
}

Any help would be appreciated

Body:
You need to add this special condition to your if (rank - deck[j].getRank() == -1).

if (rank - deck[j].getRank() == -1 || (rank == 14 && deck[j].getRank() == 2))


问:
Android Form as an Activity
I have an application with multiple activities. In the main class I open a database and create a list of the content like so:

```<code>public class MyApplication extends Activity
{
    private List<PhoneNumber> numberList;

    public void onCreate(Bundle savedInstanceState)
    {
        ...
        numberList = new ArrayList<PhoneNumber>();
        ...
        loadDatabase()
        ...
    }

    private void loadDatabase()
    {
        // File IO and parsing stuff
        addNumber(thisNumber);   // executes for each entry
    }

    public void addNumber(PhoneNumber thisNumber)
    {
        numberList.add(thisNumber);
    }
}
</code>```

This works fine and I have a ListView in the main activity that is populated with this data. Now, moving on to the next step. I am trying to launch a form as a new activity that will add an entry to this list. The activity launches fine, and I was able to build a form easily. The problem is accessing the list to add to it.

```<code>public class AddNumber extends Activity
{
    ...
    // This function is called from the done button
    // <Button android:text="Done" android:onClick="formDone"/>
    public void formDone(View v)
    {
        // findViewByIds here to get data from form.
        // This is done correctly and I can see my data in memory

        MyApplication access = new MyApplication();
        PhoneNumber newNumber = new PhoneNumber();

        // Fill newNumber object with data from form. Done correctly. Verified

        access.addNumber(newNumber);
    }
</code>```

The last line of formDone() executes correctly. Through debugging I can step through to the Application class and it executes addNumber(). Before executing numberList.add(thisNumber); I can look at the contents of memory for the thisNumber object it is trying to add to the list and that data is correct. Attempting to execute that line though crashes the application in standard Android format. (Loads View.class with 'Source not found' followed by ZygoteInit$MethodBlahBlah).

So I'm a little confused because it looks like the data being fed to addNumber() is correct, and the function works perfectly fine when the application first launches by building the list from the data in the database. Fundamentally, am I thinking about this correct? Should a form like this be it's own activity or is there a better way to do it? If it can be it's own activity, what am I doing wrong?

Thanks,

Nate

答:
Why work this way? I think it's better to use startActivityForResult instead of just startActivity from your MyApplication class.

https://developer.android.com/reference/android/app/Activity.html

It's better to use it this way, because who knows, for memory reasons, your starting activity might get destroyed to be rebuilt afterwards and what happens to your callback then? Do not underestimate the power of intents.

Title: Android Form as an Activity

Body:
I have an application with multiple activities. In the main class I open a database and create a list of the content like so:

public class MyApplication extends Activity
{
    private List<PhoneNumber> numberList;

    public void onCreate(Bundle savedInstanceState)
    {
        ...
        numberList = new ArrayList<PhoneNumber>();
        ...
        loadDatabase()
        ...
    }

    private void loadDatabase()
    {
        // File IO and parsing stuff
        addNumber(thisNumber);   // executes for each entry
    }

    public void addNumber(PhoneNumber thisNumber)
    {
        numberList.add(thisNumber);
    }
}

This works fine and I have a ListView in the main activity that is populated with this data. Now, moving on to the next step. I am trying to launch a form as a new activity that will add an entry to this list. The activity launches fine, and I was able to build a form easily. The problem is accessing the list to add to it.

public class AddNumber extends Activity
{
    ...
    // This function is called from the done button
    // <Button android:text="Done" android:onClick="formDone"/>
    public void formDone(View v)
    {
        // findViewByIds here to get data from form.
        // This is done correctly and I can see my data in memory

        MyApplication access = new MyApplication();
        PhoneNumber newNumber = new PhoneNumber();

        // Fill newNumber object with data from form. Done correctly. Verified

        access.addNumber(newNumber);
    }

The last line of formDone() executes correctly. Through debugging I can step through to the Application class and it executes addNumber(). Before executing numberList.add(thisNumber); I can look at the contents of memory for the thisNumber object it is trying to add to the list and that data is correct. Attempting to execute that line though crashes the application in standard Android format. (Loads View.class with 'Source not found' followed by ZygoteInit$MethodBlahBlah).

So I'm a little confused because it looks like the data being fed to addNumber() is correct, and the function works perfectly fine when the application first launches by building the list from the data in the database. Fundamentally, am I thinking about this correct? Should a form like this be it's own activity or is there a better way to do it? If it can be it's own activity, what am I doing wrong?

Thanks,

Nate


问:
Regexp to select images with whitespaces
Im tried several combinations but it seams to end up by inserting every possible sign.

I have a regexp that looks like

```<code><img[^>]*?src=["']([\w:\\\/\s\S]*[.a-zA-Z]{3,})[^>]*?>
</code>```

I want to select the src part from an image.

Sample URL looks like

```<code>Sample <img alt="foo" src="c:\my-folder\contains.dot\and space\in myImagePath.png" title="bar" >
</code>```

but this selects title as well, I want to stop at the src's end " .

I also tried some more constelations but with same or no result....

Is there a was to stop at " when first " was mached ?

ORIGINAL DATA

Original HTMLCode copied from VS2017 console:

```<code><style>*{font-family: Arial, Helvetica, sans-serif;}</style><p><img src=\"C:\\Users\\JustMe\\Desktop\\de mo1.png\" width=\"1635\" height=\"989\" /></p>\n<p> </p>
</code>```

Code I used originaly:

```<code>using System.Text.RegularExpressions;

...

public List<string[]> FetchLinksFromSource(string htmlSource)
    {
        List<string[]> links = new List<string[]>();

        int i = 1;
        string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
        MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        foreach (Match m in matchesImgSrc)
        {
            string[] matches = new string[3];
            string href = m.Groups[1].Value;
            matches[0] = href;
            matches[1] = new Uri(href).ToString();
            matches[2] = "imageID_" + i++.ToString();
            links.Add(matches);
        }
        return links;
    }
</code>```

This code crashes if image or path has white spaces!

Body:
Im tried several combinations but it seams to end up by inserting every possible sign.

I have a regexp that looks like

]*?src=["']([\w:\\\/\s\S]*[.a-zA-Z]{3,})[^>]*?>

I want to select the src part from an image.

Sample URL looks like

Sample

but this selects title as well, I want to stop at the src's end " .

I also tried some more constelations but with same or no result....

Is there a was to stop at " when first " was mached ?

ORIGINAL DATA

Original HTMLCode copied from VS2017 console:

\n

Code I used originaly:

using System.Text.RegularExpressions;

...

public List<string[]> FetchLinksFromSource(string htmlSource)
    {
        List<string[]> links = new List<string[]>();

        int i = 1;
        string regexImgSrc = @"]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
        MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        foreach (Match m in matchesImgSrc)
        {
            string[] matches = new string[3];
            string href = m.Groups[1].Value;
            matches[0] = href;
            matches[1] = new Uri(href).ToString();
            matches[2] = "imageID_" + i++.ToString();
            links.Add(matches);
        }
        return links;
    }

This code crashes if image or path has white spaces!

Body:
Change to:

<img[^>]*?src=["']([^"']*[.a-zA-Z]{3,})[^>]*?>
                   ^^^^^

See it live


问:
how to fix mismatched arity deprecation in RSpec 2.99.2
I am migrating from RSpec 2 to RSpec 3. While trying to remove all deprecations with Rspec 2.99.2, I have resolved all other deprecations. Except,

```<code>stubbing implementations with mismatched arity is deprecated. Called from /path/to/file.rb:60:in `block in deliver_grouped_system_event_notification'.
stubbing implementations with mismatched arity is deprecated. Called from /path/to/file.rb:26:in `send_notification'.
</code>```

This is the file:60

```<code> supports.each{ |support, system_events| Mailer.grouped_system_event_email(support, system_events).deliver_now }
</code>```

This is the original method

```<code>def grouped_system_event_email(support, system_events)
  @recipients   = support.email
  @subject      = "[ #{ENVIRONMENT_NAME} Grouped System Event List] #{system_events.first.customer.symbol}"
  @system_events = system_events

  mail(to: @recipients, subject: @subject)
</code>```

end

This is where it is stubbed

```<code>      Mailer.stub :grouped_system_event_email, &@email_spy
</code>```

The lambda &@email_spy

```<code> @email_spy = lambda do
  @email_sent = true
  stub = OpenStruct.new
  stub.stub :deliver_now
  stub
end
</code>```

答:
I just ran 'transpec' which converts RSpec 2 syntaxes to RSpec 3.

```<code>gem install transpec
myproject$ transpec
</code>```

this actually gave more insights about the error.

```<code> from: Klass.any_instance.stub(:message)
 to: allow_any_instance_of(Klass).to receive(:message)
</code>```

After running transpec, the following was the transition

From

```<code>Mailer.stub :system_event_email, &@email_spy
</code>```

To

```<code>allow(Mailer).to receive :system_event_email, &@email_spy
</code>```

Body:
I am migrating from RSpec 2 to RSpec 3. While trying to remove all deprecations with Rspec 2.99.2, I have resolved all other deprecations. Except,

stubbing implementations with mismatched arity is deprecated. Called from /path/to/file.rb:60:in `block in deliver_grouped_system_event_notification'.
stubbing implementations with mismatched arity is deprecated. Called from /path/to/file.rb:26:in `send_notification'.

This is the file:60

 supports.each{ |support, system_events| Mailer.grouped_system_event_email(support, system_events).deliver_now }

This is the original method

def grouped_system_event_email(support, system_events)
  @recipients   = support.email
  @subject      = "[ #{ENVIRONMENT_NAME} Grouped System Event List] #{system_events.first.customer.symbol}"
  @system_events = system_events

  mail(to: @recipients, subject: @subject)

end

This is where it is stubbed

      Mailer.stub :grouped_system_event_email, &@email_spy

The lambda &@email_spy

 @email_spy = lambda do
  @email_sent = true
  stub = OpenStruct.new
  stub.stub :deliver_now
  stub
end

Body:
I just ran 'transpec' which converts RSpec 2 syntaxes to RSpec 3.

gem install transpec
myproject$ transpec

this actually gave more insights about the error.

 from: Klass.any_instance.stub(:message)
 to: allow_any_instance_of(Klass).to receive(:message)

After running transpec, the following was the transition

From

Mailer.stub :system_event_email, &@email_spy

To

allow(Mailer).to receive :system_event_email, &@email_spy


问:
How to summarize a long text using Thymeleaf?
I have an object with two attributes, one is the id and the other is an attribute of the type strring called TEXT (postgres database) that is used to store the text of a post from a client.

When the application loads these posts on the page, for it does not be a text  too long,I would like to summarize this text.

I was able to do this using JSP, in an easy way, using forTokens.

How to do the same as the below code using thymeleaf?

```<code><p class="post-text">
    <c:forTokens var="summary" items="${p.text}" delims=" " begin="0" end="60">
            ${summary}
    </c:forTokens><a href="<c:url value="/${p.link}" />">[Keep reading...]</a>
</p>
</code>```

答:
Thymeleaf has the abbreviate function

see the documentation in this url: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html

/*  * Abbreviate text making it have a maximum size of n. If text is
  bigger, it  * will be clipped and finished in "..."  * Also works with
  arrays, lists or sets  / ${#strings.abbreviate(str,10)}

  // also array, list* and set*

thus, you can have something like that

${#strings.abbreviate(summary,60)}

Body:
I have an object with two attributes, one is the id and the other is an attribute of the type strring called TEXT (postgres database) that is used to store the text of a post from a client.

When the application loads these posts on the page, for it does not be a text  too long,I would like to summarize this text.

I was able to do this using JSP, in an easy way, using forTokens.

How to do the same as the below code using thymeleaf?

    <c:forTokens var="summary" items="${p.text}" delims=" " begin="0" end="60">
            ${summary}
    </c:forTokens><a href="<c:url value="/${p.link}" />">[Keep reading...]


问:
Possible to autocomplete a EditTextPreference?
Is it possible to have an EditTextPreference with AutoComplete attached to it?

I know ho to attach one to an element with an id, but am having trouble figure out how to attach the ArrayAdapter to the preference field.

This is wrong, but it's as close as I can get.

```<code>final String[] TEAMS = getResources().getStringArray(R.array.teams);
AutoCompleteTextView EditTextPreference = (AutoCompleteTextView) findViewById(R.id.editTextPrefTeam);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, TEAMS);
EditTextPreference.setAdapter(adapter);
</code>```

答:
Here's a workaround I implemented by studying the EditTextPreference.java  source code.

Essentially you need to subclass EditTextPreference and override when it binds to the dialog. At this point you can retrieve the EditText, copy it's values, and remove it from its parent view group. Then you inject your Autocompletetextview and hook up it's Arrayadapter.

```<code>public class AutoCompleteEditTextPreference extends EditTextPreference
{
    public AutoCompleteEditTextPreference(Context context)
    {
        super(context);
    }

    public AutoCompleteEditTextPreference(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public AutoCompleteEditTextPreference(Context context, AttributeSet attrs,
        int defStyle)
    {
        super(context, attrs, defStyle);
    }

    /**
     * the default EditTextPreference does not make it easy to
     * use an AutoCompleteEditTextPreference field. By overriding this method
     * we perform surgery on it to use the type of edit field that
     * we want.
     */
    protected void onBindDialogView(View view)
    {
        super.onBindDialogView(view);

        // find the current EditText object
        final EditText editText = (EditText)view.findViewById(android.R.id.edit);
        // copy its layout params
        LayoutParams params = editText.getLayoutParams();
        ViewGroup vg = (ViewGroup)editText.getParent();
        String curVal = editText.getText().toString();
        // remove it from the existing layout hierarchy
        vg.removeView(editText);
        // construct a new editable autocomplete object with the appropriate params
        // and id that the TextEditPreference is expecting
        mACTV = new AutoCompleteTextView(getContext());
        mACTV.setLayoutParams(params);
        mACTV.setId(android.R.id.edit);
        mACTV.setText(curVal);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
             android.R.layout.simple_dropdown_item_1line, [LIST OF DATA HERE]);
        mACTV.setAdapter(adapter);

        // add the new view to the layout
        vg.addView(mACTV);
    }

    /**
     * Because the baseclass does not handle this correctly
     * we need to query our injected AutoCompleteTextView for
     * the value to save
     */
    protected void onDialogClosed(boolean positiveResult)
    {
        super.onDialogClosed(positiveResult);

        if (positiveResult && mACTV != null)
        {
            String value = mACTV.getText().toString();
            if (callChangeListener(value)) {
                setText(value);
            }
        }
    }

    /**
     * again we need to override methods from the base class
     */
    public EditText getEditText()
    {
        return mACTV;
    }

    private AutoCompleteTextView mACTV = null;
    private final String TAG = "AutoCompleteEditTextPreference";
}
</code>```

Body:
Is it possible to have an EditTextPreference with AutoComplete attached to it?

I know ho to attach one to an element with an id, but am having trouble figure out how to attach the ArrayAdapter to the preference field.

This is wrong, but it's as close as I can get.

final String[] TEAMS = getResources().getStringArray(R.array.teams);
AutoCompleteTextView EditTextPreference = (AutoCompleteTextView) findViewById(R.id.editTextPrefTeam);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, TEAMS);
EditTextPreference.setAdapter(adapter);

Body:
Here's a workaround I implemented by studying the EditTextPreference.java  source code.

Essentially you need to subclass EditTextPreference and override when it binds to the dialog. At this point you can retrieve the EditText, copy it's values, and remove it from its parent view group. Then you inject your Autocompletetextview and hook up it's Arrayadapter.

public class AutoCompleteEditTextPreference extends EditTextPreference
{
    public AutoCompleteEditTextPreference(Context context)
    {
        super(context);
    }

    public AutoCompleteEditTextPreference(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public AutoCompleteEditTextPreference(Context context, AttributeSet attrs,
        int defStyle)
    {
        super(context, attrs, defStyle);
    }

    /**
     * the default EditTextPreference does not make it easy to
     * use an AutoCompleteEditTextPreference field. By overriding this method
     * we perform surgery on it to use the type of edit field that
     * we want.
     */
    protected void onBindDialogView(View view)
    {
        super.onBindDialogView(view);

        // find the current EditText object
        final EditText editText = (EditText)view.findViewById(android.R.id.edit);
        // copy its layout params
        LayoutParams params = editText.getLayoutParams();
        ViewGroup vg = (ViewGroup)editText.getParent();
        String curVal = editText.getText().toString();
        // remove it from the existing layout hierarchy
        vg.removeView(editText);
        // construct a new editable autocomplete object with the appropriate params
        // and id that the TextEditPreference is expecting
        mACTV = new AutoCompleteTextView(getContext());
        mACTV.setLayoutParams(params);
        mACTV.setId(android.R.id.edit);
        mACTV.setText(curVal);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
             android.R.layout.simple_dropdown_item_1line, [LIST OF DATA HERE]);
        mACTV.setAdapter(adapter);

        // add the new view to the layout
        vg.addView(mACTV);
    }

    /**
     * Because the baseclass does not handle this correctly
     * we need to query our injected AutoCompleteTextView for
     * the value to save
     */
    protected void onDialogClosed(boolean positiveResult)
    {
        super.onDialogClosed(positiveResult);

        if (positiveResult && mACTV != null)
        {
            String value = mACTV.getText().toString();
            if (callChangeListener(value)) {
                setText(value);
            }
        }
    }

    /**
     * again we need to override methods from the base class
     */
    public EditText getEditText()
    {
        return mACTV;
    }

    private AutoCompleteTextView mACTV = null;
    private final String TAG = "AutoCompleteEditTextPreference";
}


问:
Seaborn – how to interpret the values of the x-axis in a distplot?
I have a dataframe in which each row represents a date where a number of events were logged in a database.

Every event has a date it concerns, so for example an event that was logged on 2017-02-03 might belong to 2017-02-02 (meaning it was logged the day after it happened).

I'm trying to visualize the distribution of each column in a distplot, to get an idea of the distance between when an event was logged, and the date it concerns ("Do people log events on the same day, the day after, or even later?").

So far I've made a function that iterates over each column and plots it into a seaborn distplot.

```<code>def plot(dates):
    plt.figure(figsize=(45,25))
    for date in dates:
        sns.distplot(df[date], kde=False, bins=len(dates))
    return
</code>```

The plot then looks like this:

However, I can't understand how to interpret the values on the x-axis.

It shows a range from 0 - 3500, what does that mean?

Are there any other better ways to visualize this?

答:
In your current skript you loop over the data and plot all the output in the same figure. In the example plot that you provide, the x-axis shows the occurence of events in on the 2017-02-28, which I assume is the last date in your dataset. However,  the different colors present the data from the other dates, which are plotted in the same figure inside your loop. About the interpretations of the plot:  the x-axis shows the number of events per day: towards the right side of the figure you can see that there is usually only one day when a large number (> 1000 or so) of events is recorder. From the left side of the figure you can tell that there is around 50 days when only one event is recorded.  A simple bar chart might be easier to interpret: it will show you on the x-axis the date and on the y-axis the number of events recorded.
You could plot and save a separate barchart figure for each date by modifying your function as follows: </p>

```<code>def plot(dates):
  for date in dates:
    plt.figure()
    plt.bar(np.arange(0,len(dates)),df[date], width=1.0)
    ax=plt.gca()
    ax.set_xticks(np.arange(0,len(dates)),)+0.5)
    ax.set_xticklabels(dates)
    plt.savefig('barchart_'+date+'.png')
    return
</code>```

<p>There are probably more elegant ways than this to study your data, but I hope this helps you in getting forward. </p>

Body:
I have a dataframe in which each row represents a date where a number of events were logged in a database.

Every event has a date it concerns, so for example an event that was logged on 2017-02-03 might belong to 2017-02-02 (meaning it was logged the day after it happened).

I'm trying to visualize the distribution of each column in a distplot, to get an idea of the distance between when an event was logged, and the date it concerns ("Do people log events on the same day, the day after, or even later?").

So far I've made a function that iterates over each column and plots it into a seaborn distplot.

def plot(dates):
    plt.figure(figsize=(45,25))
    for date in dates:
        sns.distplot(df[date], kde=False, bins=len(dates))
    return

The plot then looks like this:

However, I can't understand how to interpret the values on the x-axis.

It shows a range from 0 - 3500, what does that mean?

Are there any other better ways to visualize this?

Body:
In your current skript you loop over the data and plot all the output in the same figure. In the example plot that you provide, the x-axis shows the occurence of events in on the 2017-02-28, which I assume is the last date in your dataset. However,  the different colors present the data from the other dates, which are plotted in the same figure inside your loop. About the interpretations of the plot:  the x-axis shows the number of events per day: towards the right side of the figure you can see that there is usually only one day when a large number (> 1000 or so) of events is recorder. From the left side of the figure you can tell that there is around 50 days when only one event is recorded.  A simple bar chart might be easier to interpret: it will show you on the x-axis the date and on the y-axis the number of events recorded.
You could plot and save a separate barchart figure for each date by modifying your function as follows:

def plot(dates):
  for date in dates:
    plt.figure()
    plt.bar(np.arange(0,len(dates)),df[date], width=1.0)
    ax=plt.gca()
    ax.set_xticks(np.arange(0,len(dates)),)+0.5)
    ax.set_xticklabels(dates)
    plt.savefig('barchart_'+date+'.png')
    return

There are probably more elegant ways than this to study your data, but I hope this helps you in getting forward.


问:
How to convert '.opus' file to flac file format
I have an audio file with '.opus' format.
http://img.wbcsrv.com/2017/03/14/4915792368684-41222-919020044692-1489468385000.opus
I need to use it with google cloud speech API. But the google speech API only support some file encodings, specified in https://cloud.google.com/speech/docs/basics#audio-encodings . How can i use 'opus' file format with google cloud speech API?
Is there any way to convert '.opus' file into the specified(googles audio encoding documentation) format or any npm available for do this?</p>

答:
In Node you can use ffmpgeg in several ways, using:

https://www.npmjs.com/package/ffmpeg

https://www.npmjs.com/package/ffmpeg-node

https://www.npmjs.com/package/ffmpeg-static

https://www.npmjs.com/package/ffmpeg-wrap

few more at https://www.npmjs.com/search?q=ffmpeg

The ffmpeg supports Opus according to the docs:

https://www.ffmpeg.org/ffmpeg-codecs.html#opus

https://www.ffmpeg.org/ffmpeg-codecs.html#libopus

https://www.ffmpeg.org/ffmpeg-codecs.html#libopus-1

You may need to use libopus for that:

http://opus-codec.org/downloads/

The ffmpeg also supports encoding FLAC so it can also be used for that part:

https://www.ffmpeg.org/ffmpeg-codecs.html#flac-2

There is not a straightforward way to convert Opus to Flac using Node without any external dependencies but it should be possible using the modules and libraries above.


问:
How can I make my two R leaflet maps synchronise with each other?
I have had some nice success implementing Leaflet package in R for some data.

I have also managed to put two maps side by side as a lattice, and as a sync.

I have two issues:

1) Sync...does not sync the maps at all

I am using Mapview and Raster to attempt sync but the two maps side by side do not zoom in/out together.

See the code below:

```<code>library(leaflet)
library(ggmap)
library(mapview)
library(raster)
library(magrittr)
UK <- ggmap::geocode("United Kingdom")

#FILE1 <- read.csv("DATASET1.csv")
#FILE2 <- read.csv("DATASET2.csv")
FILE1 <- data.frame('lat' = c(51.31, 51.52, 51.53), 'lon' = c(0.06, 0.11, 0.09))
FILE2 <- data.frame('lat' = c(52.20, 52.25, 52.21), 'lon' = c(0.12, 0.12, 0.12))

map1 <- leaflet(FILE1)%>%
  addTiles()%>%
  addMarkers(clusterOptions = markerClusterOptions())

map2 <- leaflet(FILE2)%>%
  addTiles()%>%
  addMarkers(clusterOptions = markerClusterOptions())

sync(map1,map2)
</code>```

I am sure I am missing something simple here but hopefully someone can help me in seeing that :)

2) Ideally I want one leaflet map to overlap the other one

I want to differentiate them by using different markets for each map. I have attempted to research this on the internet and through reading the manuals for leaflet but to no success

any guidance greatly appreciated!

答:
1) Syncing two maps

Installing the development version solved this for me

```<code># Dependencies
# If your devtools is not the latest version
# then you might have to install "units" manually
install.packages('units')
install.packages('devtools')
library(devtools)

devtools::install_github("environmentalinformatics-marburg/mapview", ref = "develop")
</code>```

The code I used:

```<code>library(leaflet)
library(ggmap)
library(mapview)
library(raster)
library(magrittr)
UK <- ggmap::geocode("United Kingdom")

#FILE1 <- read.csv("DATASET1.csv")
#FILE2 <- read.csv("DATASET2.csv")
FILE1 <- data.frame('lat' = c(51.31, 51.52, 51.53), 'lon' = c(0.06, 0.11, 0.09))
FILE2 <- data.frame('lat' = c(52.20, 52.25, 52.21), 'lon' = c(0.12, 0.12, 0.12))

map1 <- leaflet(FILE1)%>%
  addTiles()%>%
  addMarkers(clusterOptions = markerClusterOptions())

map2 <- leaflet(FILE2)%>%
  addTiles()%>%
  addMarkers(clusterOptions = markerClusterOptions())

mapview::latticeView(map1, map2, ncol = 2, sync = list(c(1, 2)), sync.cursor = FALSE, no.initial.sync = FALSE)
# Or:
sync(map1, map2)
</code>```

2) Overlaying two maps

You can use two separate data frames as data sources and add them to the same map separately. Change the symbol style to be able to differentiate between them.

```<code>map3 <- leaflet(FILE2)%>%
  addTiles() %>%
  addCircleMarkers(data = FILE1) %>%
  addCircleMarkers(data = FILE2,
                   color = '#0FF')
map3
</code>```

If you want to do something similar for the cluster markers, there is some good documentation on that here and here. Based on some of the code from those posts I created a suggestion below where I use the pre-existing styles to differentiate between clusters of different types:

```<code>FILE1 <- data.frame('lat' = rnorm(n = 1000, mean = 51.4, sd = 0.5),
                    'lon' = rnorm(n = 1000, mean = 0.8, sd = 0.5))
FILE2 <- data.frame('lat' = rnorm(n = 1000, mean = 53, sd = 0.5),
                    'lon' = rnorm(n = 1000, mean = -0.5, sd = 0.5))

map3 <- leaflet(rbind(FILE1, FILE2)) %>%
  addTiles() %>%
  addCircleMarkers(data = FILE1,
    color = '#FA5',
    opacity = 1,
    clusterOptions = markerClusterOptions(iconCreateFunction = JS("function (cluster) {
      var childCount = cluster.getChildCount();
      var c = ' marker-cluster-';
      if (childCount < 3) {
        c += 'large';
      } else if (childCount < 5) {
        c += 'large';
      } else {
        c += 'large';
      }
      return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>',
      className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });

    }"))) %>%
  addCircleMarkers(data = FILE2,
    color = '#9D7',
    opacity = 1,
    clusterOptions = markerClusterOptions(iconCreateFunction = JS("function (cluster) {
      var childCount = cluster.getChildCount();
      var c = ' marker-cluster-';
      if (childCount < 3) {
        c += 'small';
      } else if (childCount < 5) {
        c += 'small';
      } else {
        c += 'small';
      }
      return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>',
      className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });

    }")))
</code>```

Body:
I have had some nice success implementing Leaflet package in R for some data.

I have also managed to put two maps side by side as a lattice, and as a sync.

I have two issues:

1) Sync...does not sync the maps at all

I am using Mapview and Raster to attempt sync but the two maps side by side do not zoom in/out together.

See the code below:

library(leaflet)
library(ggmap)
library(mapview)
library(raster)
library(magrittr)
UK <- ggmap::geocode("United Kingdom")

#FILE1 <- read.csv("DATASET1.csv")
#FILE2 <- read.csv("DATASET2.csv")
FILE1 <- data.frame('lat' = c(51.31, 51.52, 51.53), 'lon' = c(0.06, 0.11, 0.09))
FILE2 <- data.frame('lat' = c(52.20, 52.25, 52.21), 'lon' = c(0.12, 0.12, 0.12))

map1 <- leaflet(FILE1)%>%
  addTiles()%>%
  addMarkers(clusterOptions = markerClusterOptions())

map2 <- leaflet(FILE2)%>%
  addTiles()%>%
  addMarkers(clusterOptions = markerClusterOptions())

sync(map1,map2)

I am sure I am missing something simple here but hopefully someone can help me in seeing that :)

2) Ideally I want one leaflet map to overlap the other one

I want to differentiate them by using different markets for each map. I have attempted to research this on the internet and through reading the manuals for leaflet but to no success

any guidance greatly appreciated!

Body:
1) Syncing two maps

Installing the development version solved this for me

# Dependencies
# If your devtools is not the latest version
# then you might have to install "units" manually
install.packages('units')
install.packages('devtools')
library(devtools)

devtools::install_github("environmentalinformatics-marburg/mapview", ref = "develop")

The code I used:

library(leaflet)
library(ggmap)
library(mapview)
library(raster)
library(magrittr)
UK <- ggmap::geocode("United Kingdom")

#FILE1 <- read.csv("DATASET1.csv")
#FILE2 <- read.csv("DATASET2.csv")
FILE1 <- data.frame('lat' = c(51.31, 51.52, 51.53), 'lon' = c(0.06, 0.11, 0.09))
FILE2 <- data.frame('lat' = c(52.20, 52.25, 52.21), 'lon' = c(0.12, 0.12, 0.12))

map1 <- leaflet(FILE1)%>%
  addTiles()%>%
  addMarkers(clusterOptions = markerClusterOptions())

map2 <- leaflet(FILE2)%>%
  addTiles()%>%
  addMarkers(clusterOptions = markerClusterOptions())

mapview::latticeView(map1, map2, ncol = 2, sync = list(c(1, 2)), sync.cursor = FALSE, no.initial.sync = FALSE)
# Or:
sync(map1, map2)

2) Overlaying two maps

You can use two separate data frames as data sources and add them to the same map separately. Change the symbol style to be able to differentiate between them.

map3 <- leaflet(FILE2)%>%
  addTiles() %>%
  addCircleMarkers(data = FILE1) %>%
  addCircleMarkers(data = FILE2,
                   color = '#0FF')
map3

If you want to do something similar for the cluster markers, there is some good documentation on that here and here. Based on some of the code from those posts I created a suggestion below where I use the pre-existing styles to differentiate between clusters of different types:

FILE1 <- data.frame('lat' = rnorm(n = 1000, mean = 51.4, sd = 0.5),
                    'lon' = rnorm(n = 1000, mean = 0.8, sd = 0.5))
FILE2 <- data.frame('lat' = rnorm(n = 1000, mean = 53, sd = 0.5),
                    'lon' = rnorm(n = 1000, mean = -0.5, sd = 0.5))

map3 <- leaflet(rbind(FILE1, FILE2)) %>%
  addTiles() %>%
  addCircleMarkers(data = FILE1,
    color = '#FA5',
    opacity = 1,
    clusterOptions = markerClusterOptions(iconCreateFunction = JS("function (cluster) {
      var childCount = cluster.getChildCount();
      var c = ' marker-cluster-';
      if (childCount < 3) {
        c += 'large';
      } else if (childCount < 5) {
        c += 'large';
      } else {
        c += 'large';
      }
      return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>',
      className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });

    }"))) %>%
  addCircleMarkers(data = FILE2,
    color = '#9D7',
    opacity = 1,
    clusterOptions = markerClusterOptions(iconCreateFunction = JS("function (cluster) {
      var childCount = cluster.getChildCount();
      var c = ' marker-cluster-';
      if (childCount < 3) {
        c += 'small';
      } else if (childCount < 5) {
        c += 'small';
      } else {
        c += 'small';
      }
      return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>',
      className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });

    }")))