问:
Add number of characters and extend time of Rfc6238AuthenticationService
I am using Rfc6238AuthenticationService at https://github.com/aspnet/Identity/blob/85012bd0ac83548f7eab31f0585dae3836935d9d/src/Microsoft.AspNet.Identity/Rfc6238AuthenticationService.cs

which uses rfc6238 https://www.rfc-editor.org/rfc/rfc6238

```<code>internal static class Rfc6238AuthenticationService
{
    private static readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    private static readonly TimeSpan _timestep = TimeSpan.FromMinutes(3);
    private static readonly Encoding _encoding = new UTF8Encoding(false, true);

    private static int ComputeTotp(HashAlgorithm hashAlgorithm, ulong timestepNumber, string modifier)
    {
        // # of 0's = length of pin
        const int Mod = 1000000;

        // See https://www.rfc-editor.org/rfc/rfc4226
        // We can add an optional modifier
        var timestepAsBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((long)timestepNumber));
        var hash = hashAlgorithm.ComputeHash(ApplyModifier(timestepAsBytes, modifier));

        // Generate DT string
        var offset = hash[hash.Length - 1] & 0xf;
        Debug.Assert(offset + 4 < hash.Length);
        var binaryCode = (hash[offset] & 0x7f) << 24
                         | (hash[offset + 1] & 0xff) << 16
                         | (hash[offset + 2] & 0xff) << 8
                         | (hash[offset + 3] & 0xff);

        return binaryCode % Mod;
    }

    private static byte[] ApplyModifier(byte[] input, string modifier)
    {
        if (String.IsNullOrEmpty(modifier))
        {
            return input;
        }

        var modifierBytes = _encoding.GetBytes(modifier);
        var combined = new byte[checked(input.Length + modifierBytes.Length)];
        Buffer.BlockCopy(input, 0, combined, 0, input.Length);
        Buffer.BlockCopy(modifierBytes, 0, combined, input.Length, modifierBytes.Length);
        return combined;
    }

    // More info: https://www.rfc-editor.org/rfc/rfc6238#section-4
    private static ulong GetCurrentTimeStepNumber()
    {
        var delta = DateTime.UtcNow - _unixEpoch;
        return (ulong)(delta.Ticks / _timestep.Ticks);
    }

    public static int GenerateCode(byte[] securityToken, string modifier = null)
    {
        if (securityToken == null)
        {
            throw new ArgumentNullException(nameof(securityToken));
        }

        // Allow a variance of no greater than 90 seconds in either direction
        var currentTimeStep = GetCurrentTimeStepNumber();
        using (var hashAlgorithm = new HMACSHA1(securityToken))
        {
            return ComputeTotp(hashAlgorithm, currentTimeStep, modifier);
        }
    }

    public static bool ValidateCode(byte[] securityToken, int code, string modifier = null)
    {
        if (securityToken == null)
        {
            throw new ArgumentNullException(nameof(securityToken));
        }

        // Allow a variance of no greater than 90 seconds in either direction
        var currentTimeStep = GetCurrentTimeStepNumber();
        using (var hashAlgorithm = new HMACSHA1(securityToken))
        {
            for (var i = -2; i <= 2; i++)
            {
                var computedTotp = ComputeTotp(hashAlgorithm, (ulong)((long)currentTimeStep + i), modifier);
                if (computedTotp == code)
                {
                    return true;
                }
            }
        }

        // No match
        return false;
    }
}
</code>```

Is it possible to add character limit in this class and make it configurable(like 6 chars)? Also, is it possible to extend the time of token and make it configurable(like 120 seconds)?

答:
Here is the place, where OTP is truncated to the defined length:

```<code>return binaryCode % Mod;
</code>```

So, you just need to change the value of the Mod to 1000000 to get 6-digits code.

A variable, responsible for time of token is timestepNumber. So change the logic in its calculation if needed.

Body:
I am using Rfc6238AuthenticationService at https://github.com/aspnet/Identity/blob/85012bd0ac83548f7eab31f0585dae3836935d9d/src/Microsoft.AspNet.Identity/Rfc6238AuthenticationService.cs

which uses rfc6238 https://www.rfc-editor.org/rfc/rfc6238

internal static class Rfc6238AuthenticationService
{
    private static readonly DateTime _unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    private static readonly TimeSpan _timestep = TimeSpan.FromMinutes(3);
    private static readonly Encoding _encoding = new UTF8Encoding(false, true);

    private static int ComputeTotp(HashAlgorithm hashAlgorithm, ulong timestepNumber, string modifier)
    {
        // # of 0's = length of pin
        const int Mod = 1000000;

        // See https://www.rfc-editor.org/rfc/rfc4226
        // We can add an optional modifier
        var timestepAsBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((long)timestepNumber));
        var hash = hashAlgorithm.ComputeHash(ApplyModifier(timestepAsBytes, modifier));

        // Generate DT string
        var offset = hash[hash.Length - 1] & 0xf;
        Debug.Assert(offset + 4 < hash.Length);
        var binaryCode = (hash[offset] & 0x7f) << 24
                         | (hash[offset + 1] & 0xff) << 16
                         | (hash[offset + 2] & 0xff) << 8
                         | (hash[offset + 3] & 0xff);

        return binaryCode % Mod;
    }

    private static byte[] ApplyModifier(byte[] input, string modifier)
    {
        if (String.IsNullOrEmpty(modifier))
        {
            return input;
        }

        var modifierBytes = _encoding.GetBytes(modifier);
        var combined = new byte[checked(input.Length + modifierBytes.Length)];
        Buffer.BlockCopy(input, 0, combined, 0, input.Length);
        Buffer.BlockCopy(modifierBytes, 0, combined, input.Length, modifierBytes.Length);
        return combined;
    }

    // More info: https://www.rfc-editor.org/rfc/rfc6238#section-4
    private static ulong GetCurrentTimeStepNumber()
    {
        var delta = DateTime.UtcNow - _unixEpoch;
        return (ulong)(delta.Ticks / _timestep.Ticks);
    }

    public static int GenerateCode(byte[] securityToken, string modifier = null)
    {
        if (securityToken == null)
        {
            throw new ArgumentNullException(nameof(securityToken));
        }

        // Allow a variance of no greater than 90 seconds in either direction
        var currentTimeStep = GetCurrentTimeStepNumber();
        using (var hashAlgorithm = new HMACSHA1(securityToken))
        {
            return ComputeTotp(hashAlgorithm, currentTimeStep, modifier);
        }
    }

    public static bool ValidateCode(byte[] securityToken, int code, string modifier = null)
    {
        if (securityToken == null)
        {
            throw new ArgumentNullException(nameof(securityToken));
        }

        // Allow a variance of no greater than 90 seconds in either direction
        var currentTimeStep = GetCurrentTimeStepNumber();
        using (var hashAlgorithm = new HMACSHA1(securityToken))
        {
            for (var i = -2; i <= 2; i++)
            {
                var computedTotp = ComputeTotp(hashAlgorithm, (ulong)((long)currentTimeStep + i), modifier);
                if (computedTotp == code)
                {
                    return true;
                }
            }
        }

        // No match
        return false;
    }
}

Is it possible to add character limit in this class and make it configurable(like 6 chars)? Also, is it possible to extend the time of token and make it configurable(like 120 seconds)?

Body:
Here is the place, where OTP is truncated to the defined length:

return binaryCode % Mod;

So, you just need to change the value of the Mod to 1000000 to get 6-digits code.

A variable, responsible for time of token is timestepNumber. So change the logic in its calculation if needed.


来源: stackexchange

问:
how to replace two same keys array and make none set keys empty
Let say we have 2 flowing arrays

```<code>$arr1= array('a' => "XL");
$arr2= array('a' => "XLd",'b'=>"CDW");
</code>```

i need to assign $arr1 to $arr2  and make other keys empty whith a builtin function not foreach.

It should looks as bellow:

```<code>array(2) { ['a']=> string(2) "XL" ['b']=> string(0) ""}
</code>```

thanks

答:
Another oneliner solution:

```<code>$arr2 = array_replace(array_map(function($n){return "";}, $arr2), $arr1);
</code>```

https://3v4l.org/cgBB1

ContentLicense: CC BY-SA 3.0

Body:
Let say we have 2 flowing arrays

$arr1= array('a' => "XL");
$arr2= array('a' => "XLd",'b'=>"CDW");

i need to assign $arr1 to $arr2  and make other keys empty whith a builtin function not foreach.

It should looks as bellow:

array(2) { ['a']=> string(2) "XL" ['b']=> string(0) ""}

thanks

Body:
Another oneliner solution:

$arr2 = array_replace(array_map(function($n){return "";}, $arr2), $arr1);

https://3v4l.org/cgBB1


问:
Component @Input inheritance
I have issues with inheritance in components, I am trying to implement a hierarchy of classes for in-house components and services.
I have several classes that provide common functionality for the actual components, the aim would be to have easier to manage code.

For example, I have an (in essence abstract) base class:

```<code>@Component({
  selector: 'ic-base-alpha-locale-sensitive-input',
  template: '<div></div>'
})
export class BaseAlphaLocaleSensitiveInput extends BaseAlphaInput implements OnInit {

  @Input()
  charCase: TextCaseType;
  ....
}
</code>```

Which i try to use in a descendant:

```<code>export class AlphabeticInputComponent extends BaseAlphaLocaleSensitiveInput
implements OnInit {
  ...
}
</code>```

with a template

```<code><input ... [charCase]="caseConvert" #input="ngModel" ...>
</code>```

And i'm getting an error:

Can't bind to 'charCase' since it isn't a known property of 'input'. ...  [ERROR ->][charCase]="caseConvert"

What is the proper way to inherit @Input bindings in descendant
  classes?

or

In general what is the best practice for implementing abstract classes
  from which several component implementations can inherit common
  methods, properties and bindings?

答:
You should not use the input tag, but the selector you defined in your @Component:

```<code><ic-alphabetic-input [charCase]="caseConvert" #input="ngModel"></ic-alphabetic-input>
</code>```

Title: Component @Input inheritance

Body:
I have issues with inheritance in components, I am trying to implement a hierarchy of classes for in-house components and services.
I have several classes that provide common functionality for the actual components, the aim would be to have easier to manage code.

For example, I have an (in essence abstract) base class:

@Component({
  selector: 'ic-base-alpha-locale-sensitive-input',
  template: '

'
})
export class BaseAlphaLocaleSensitiveInput extends BaseAlphaInput implements OnInit {

  @Input()
  charCase: TextCaseType;
  ....
}

Which i try to use in a descendant:

export class AlphabeticInputComponent extends BaseAlphaLocaleSensitiveInput
implements OnInit {
  ...
}

with a template

<input ... [charCase]="caseConvert" #input="ngModel" ...>

And i'm getting an error:

Can't bind to 'charCase' since it isn't a known property of 'input'. ...  [ERROR ->][charCase]="caseConvert"

What is the proper way to inherit @Input bindings in descendant
  classes?

or

In general what is the best practice for implementing abstract classes
  from which several component implementations can inherit common
  methods, properties and bindings?

Body:
You should not use the input tag, but the selector you defined in your @Component:

<ic-alphabetic-input [charCase]="caseConvert" #input="ngModel"></ic-alphabetic-input>


问:
C# Monogame Performance when Drawing Thousands of SpriteBatch.DrawString()
I'm currently creating a large map, that consists of a lot of rectangles (33,844), that all have a unique name (label), which I'm drawing on top of them using a SpriteFont.

Drawing all of the rectangles takes no performance hit at all. But, as soon as I try to write all of their labels with DrawString(), my performance goes into the dumps.

In my head, I would like to draw all my rectangles and text to one texture all at once, and only have to keep redrawing that entire finished texture. My issue is, this is an enormous map, and some of the coordinates for the rectangles are very high (example: one slot's x is 14869 and y is 23622), and they're far bigger than a Texture2D allows.

Since this is a map, I really only need to draw the entire thing once, and then allow the user to scroll/move around it. There's no need for me to continually redraw all of the individual rectangles and their labels.

Does anyone have experience with this type of situation?

答:
Try to only render the labels that you can see on the screen and if you can zoom back far enough, just don't render them.

Textrendering is expensive, since it is basically creating a rectangle to draw on for every character in the font and then applying the same RGBA texture to it. So depending on the number of characters you write, the number of rectangles increases. This means four new vertices per character.

Depending on what you write you could simply create a texture with the text already on it and render that, but it won't be very dynamic.

EDIT: I need to clarify something.

There's no need for me to continually redraw all of the individual rectangles and their labels.

This is wrong. You have to draw the whole thing every frame. Sure, it doesn't increase memorywise, but it still is a lot to render and you will need to render it every frame.

But as I said: Try to only render the labels and the rectangles that collide with the screenboundaries, then you should be fine.


问:
Doctrine queryBuilder: return object not array
I have this query created with doctrine querybuilder, the return i get is an array of arrays.
I would like to get a return that is an array of objects, is this possible?

I know that normally Doctrine returns objects of an entity, bit since i have an inner join to get the name from another table it returns arrays.

Thanks in advance.

```<code>   $qb->select('u', 'h.name')
        ->from('AppBundle:UserHose', 'u')
        ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
        ->where('u.userId = :userId')
        ->orderBy('u.id', 'DESC')
            ->setParameter('userId', $userId);

    return $qb->getQuery()->getResult();
</code>```

答:
you can use this:

```<code>return $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);
</code>```

Or this:

```<code>return $qb->getQuery()->getArrayResult();
</code>```

Body:
I have this query created with doctrine querybuilder, the return i get is an array of arrays.
I would like to get a return that is an array of objects, is this possible?

I know that normally Doctrine returns objects of an entity, bit since i have an inner join to get the name from another table it returns arrays.

Thanks in advance.

   $qb->select('u', 'h.name')
        ->from('AppBundle:UserHose', 'u')
        ->innerJoin('AppBundle:Hose', 'h', 'WITH', 'u.hoseId = h.id')
        ->where('u.userId = :userId')
        ->orderBy('u.id', 'DESC')
            ->setParameter('userId', $userId);

    return $qb->getQuery()->getResult();

Body:
you can use this:

return $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);

Or this:

return $qb->getQuery()->getArrayResult();


问:
How to show a message on the last page of pagination
I'm trying to show a message according the page where user is. This is what I got so far but something is wrong and I don't know why...</p>

```<code>    global $wp_query;
        $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
        $posts_per_page = get_option( 'posts_per_page' );
        $count_post = wp_count_posts('post');
        $total = (int) $count_post->publish ;
        $total_pages = ceil( $total / $posts_per_page );

if ( $paged == 1){
             echo 'this is page number 1'; // work's fine!
       }
        elseif ( $paged > 1 ) {
            echo 'these are pages bigger than one'; // work's fine!
       }
        elseif ( $paged == $total_pages ) {
            echo 'this is the last page of pagination'; // FAIL!
           }}}
</code>```

答:
Hope this can save time to someone...

Changing the order (and doing minor tweaks) of the statements solved the issue like mentioned by @alexwc_ on the comment above. Thanks, @alexwc_!

```<code>if ( $paged >= $total_pages){
    echo 'this is the last page of pagination'; // work's fine!
} elseif ($paged === 1 ) {
    echo 'this is page number 1'; // work's fine!
} elseif ($paged > 1 ) {
    echo 'these are pages bigger than one'; // work's fine!
                            }
</code>```

Body:
I'm trying to show a message according the page where user is. This is what I got so far but something is wrong and I don't know why...

    global $wp_query;
        $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
        $posts_per_page = get_option( 'posts_per_page' );
        $count_post = wp_count_posts('post');
        $total = (int) $count_post->publish ;
        $total_pages = ceil( $total / $posts_per_page );

if ( $paged == 1){
             echo 'this is page number 1'; // work's fine!
       }
        elseif ( $paged > 1 ) {
            echo 'these are pages bigger than one'; // work's fine!
       }
        elseif ( $paged == $total_pages ) {
            echo 'this is the last page of pagination'; // FAIL!
           }}}

Body:
Hope this can save time to someone...

Changing the order (and doing minor tweaks) of the statements solved the issue like mentioned by @alexwc_ on the comment above. Thanks, @alexwc_!

if ( $paged >= $total_pages){
    echo 'this is the last page of pagination'; // work's fine!
} elseif ($paged === 1 ) {
    echo 'this is page number 1'; // work's fine!
} elseif ($paged > 1 ) {
    echo 'these are pages bigger than one'; // work's fine!
                            }


问:
Vertical align input and button without bootstrap
I wonder what's the best way to vertically align an input field and a button without Bootstrap.

Here's how it looks right know:

Some code:

```<code><!doctype html>
        <title>Postnummer</title>
      <div class="container-fluid">
          <div class="divider"></div>
          <div class="row">
              <div class="col-md-12">
                  <form class="navbar-form">
                    <div class="input-group">
                      <input style="height:50px; color: black; border-radius: 0px;" type="number"  id="searchZipCode"class="form-control" placeholder="Sök postnummer">
                      <div class="input-group-btn">
                      <a id="submitBtn">
                        <button style="height:50px; border-radius: 0px" type="button" click="submitZipCode()" class="btn btn-default"><i class="fa fa-search fa-2x"></i></button>
                      </a>
                      </div>
                    </div>
                  </form>
              </div>
          </div>
    </div>
</code>```

Fiddle: https://jsfiddle.net/5mxzu4m5/

I want the the icon on the right side of the input field. Really grateful for all the answers! :)

答:
Use the below code (just added display:inline-block & vertical-align:top on textbox and .input-group-btn, increased button height)</p>

```<code><div class="container-fluid">
      <div class="divider"></div>
      <div class="row">
          <div class="col-md-12">
              <form class="navbar-form">
                <div class="input-group" style="text-align: center">
                  <input style="height:50px; color: black; border-radius: 0px; display: inline-block; vertical-align:top; margin-right:-4px; " type="number"  id="searchZipCode"class="form-control" placeholder="Sök postnummer">
                  <div class="input-group-btn" style="display: inline-block; vertical-align:top">
                  <a id="submitBtn">
                    <button style="height:56px; border-radius: 0px;" type="button" click="submitZipCode()" class="btn btn-default"><i class="fa fa-search fa-2x"></i></button>
                  </a>
                  </div>
                </div>
              </form>
          </div>
      </div>
</div>
</code>```

Body:
I wonder what's the best way to vertically align an input field and a button without Bootstrap.

Here's how it looks right know:

Some code:

<!doctype html>
        <title>Postnummer</title>

                  <form class="navbar-form">

                      <input style="height:50px; color: black; border-radius: 0px;" type="number"  id="searchZipCode"class="form-control" placeholder="Sök postnummer">

                        <button style="height:50px; border-radius: 0px" type="button" click="submitZipCode()" class="btn btn-default"></button>

                  </form>

Fiddle: https://jsfiddle.net/5mxzu4m5/

I want the the icon on the right side of the input field. Really grateful for all the answers! :)

Body:
Use the below code (just added display:inline-block & vertical-align:top on textbox and .input-group-btn, increased button height)

<div class="container-fluid">
      <div class="divider"></div>
      <div class="row">
          <div class="col-md-12">
              <form class="navbar-form">
                <div class="input-group" style="text-align: center">
                  <input style="height:50px; color: black; border-radius: 0px; display: inline-block; vertical-align:top; margin-right:-4px; " type="number"  id="searchZipCode"class="form-control" placeholder="Sök postnummer">
                  <div class="input-group-btn" style="display: inline-block; vertical-align:top">
                  <a id="submitBtn">
                    <button style="height:56px; border-radius: 0px;" type="button" click="submitZipCode()" class="btn btn-default"><i class="fa fa-search fa-2x"></i></button>
                  </a>
                  </div>
                </div>
              </form>
          </div>
      </div>
</div>


问:
Watir-ruby how to click on text by color property
I'm trying to click on an element in a table. There are a few elements with the same class , and I need to click on one with a specific color property: color:#555.
I tried a couple of approaches that didn't work:

```<code>1- browser.span(:class => 'price', visible: true ).click  -- not work
2- browser.span(:class => 'price', ).style(color: '#555').click  -- undefined method click for string
</code>```

The link depends on product availability so some times is grey and I can't click on it.  Is there any way apart from this one to achieve this click?

答:
You can do it this way:

```<code>browser.span(:css, 'span[style="color: #555;"].price').click
</code>```

You'll have to use the css selector, as the style method can only be used to return values in the style attribute. Example of that:

```<code>browser.spans(:class, 'price').each {|e| puts e.style('color')}
</code>```

As a side note, if you have any control over the source I would consider making product availability more explicit in the CSS.

Body:
I'm trying to click on an element in a table. There are a few elements with the same class , and I need to click on one with a specific color property: color:#555.
I tried a couple of approaches that didn't work:

1- browser.span(:class => 'price', visible: true ).click  -- not work
2- browser.span(:class => 'price', ).style(color: '#555').click  -- undefined method click for string

The link depends on product availability so some times is grey and I can't click on it.  Is there any way apart from this one to achieve this click?

Body:
You can do it this way:

browser.span(:css, 'span[style="color: #555;"].price').click

You'll have to use the css selector, as the style method can only be used to return values in the style attribute. Example of that:

browser.spans(:class, 'price').each {|e| puts e.style('color')}

As a side note, if you have any control over the source I would consider making product availability more explicit in the CSS.


问:
Using value of ng-model in ng-if
I have a text box where I enter an idNumber. I want to check if that id number appears in my table. If it does, I want to add a glyphicon to that row.

Now, my problem is that I don't know how to access ng-model="idNumber" from ng-if.

I try using ng-if="data.id== {{idNumber}}" but that does not work.

```<code>        <div class="container" id="inputDiv">
            <div>
                <input type="text" class="form-control" ng-model="idNumber">
            </div>
        </div>

        <div class="container col-md-12">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th>Id number</th>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Status</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="data in idData">
                    <td>{{data.id}}</td>
                    <td>{{data.name}}</td>
                    <td>{{data.dokumenttype}}</td>
                    <td>
                      <span ng-if="data.id== {{idNumber}}">
                        <span class="glyphicon glyphicon-asterisk"></span>
                      </span>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
</code>```

答:
Use like this:</p>

```<code><span ng-if="data.id === idNumber">
</code>```

Title: Using value of ng-model in ng-if

Body:
I have a text box where I enter an idNumber. I want to check if that id number appears in my table. If it does, I want to add a glyphicon to that row.

Now, my problem is that I don't know how to access ng-model="idNumber" from ng-if.

I try using ng-if="data.id== {{idNumber}}" but that does not work.

                <input type="text" class="form-control" ng-model="idNumber">

                    Id number
                    Name
                    Type
                    Status

                    {{data.id}}
                    {{data.name}}
                    {{data.dokumenttype}}

Body:
Use like this:

<span ng-if="data.id === idNumber">


问:
Cannot sort purchasers by content in BigQuery/Firebase
I'm using Firebase to analyze a mobile app. Data from Firebase is exported to BigQuery.

I'm trying to use the following query, written in standard SQL, to count purchasers relevant to a specific content:

```<code>SELECT COUNT(user_dim.app_info.app_instance_id) AS purchasers
    ,eventParams.value.string_value AS eventName
    ,event.DATE AS eventDate
FROM `id.TABLE.app_events_ * `
    ,UNNEST(event_dim) AS event
    ,UNNEST(event.params) AS eventParams
WHERE (
        event.NAME = 'select_content'
        AND eventParams.KEY = 'item_id'
        )
    AND user_dim.app_info.app_instance_id IN (
        SELECT [user_dim.app_info.app_instance_id]
        FROM `id.TABLE.app_events_ * `
            ,UNNEST(event_dim) AS event
            ,UNNEST(event.params) AS eventParams
        WHERE event.NAME = 'in_app_purchase'
            AND eventParams.KEY = 'quantity'
        )
GROUP BY eventDate
    ,eventName
ORDER BY eventDate DESC
</code>```

But I get the error message: 'Cannot execute IN subquery with uncomparable types STRING and ARRAY'

I have tried to use 'UNNEST' function after the 'IN' operator.
But then I got the error: 'Scalar subquery produced more than one element'

Please, help me to find out where my mistake is.

答:
I've created the query which helped me to sort purchasers by content. It's in Legacy SQL:

`

```<code>SELECT
  user_dim.app_info.app_platform as appPlatform,
  event_dim.date as eventDate,
  COUNT(event_dim.name) as purchasers,
  user_dim.app_info.app_instance_id as appInstanceID,
  event_dim.params.value.string_value as contentID,
  event_dim.value_in_usd as revenue,
  CASE
    WHEN event_dim.params.value.string_value = 'content id1'  THEN 'content name1'
    WHEN event_dim.params.value.string_value = 'content id2'  THEN 'content name2'
    ELSE 'Undefined'
  END as contentName
FROM
  TABLE_QUERY([table_IOS], 'table_id CONTAINS "app_events_"'),
  TABLE_QUERY([table_ANDROID], 'table_id CONTAINS "app_events_"')
WHERE`enter code here`
  (event_dim.name = 'in_app_purchase' AND event_dim.params.key = 'product_id' OR event_dim.params.key = 'price')
  AND event_dim.params.value.string_value != 'null'
GROUP BY
  appPlatform, eventDate, appInstanceID, contentID, revenue, contentName
ORDER BY
  appPlatform, eventDate DESC
</code>```

`

Body:
I'm using Firebase to analyze a mobile app. Data from Firebase is exported to BigQuery.

I'm trying to use the following query, written in standard SQL, to count purchasers relevant to a specific content:

SELECT COUNT(user_dim.app_info.app_instance_id) AS purchasers
    ,eventParams.value.string_value AS eventName
    ,event.DATE AS eventDate
FROM `id.TABLE.app_events_ * `
    ,UNNEST(event_dim) AS event
    ,UNNEST(event.params) AS eventParams
WHERE (
        event.NAME = 'select_content'
        AND eventParams.KEY = 'item_id'
        )
    AND user_dim.app_info.app_instance_id IN (
        SELECT [user_dim.app_info.app_instance_id]
        FROM `id.TABLE.app_events_ * `
            ,UNNEST(event_dim) AS event
            ,UNNEST(event.params) AS eventParams
        WHERE event.NAME = 'in_app_purchase'
            AND eventParams.KEY = 'quantity'
        )
GROUP BY eventDate
    ,eventName
ORDER BY eventDate DESC

But I get the error message: 'Cannot execute IN subquery with uncomparable types STRING and ARRAY'

I have tried to use 'UNNEST' function after the 'IN' operator.
But then I got the error: 'Scalar subquery produced more than one element'

Please, help me to find out where my mistake is.

Body:
I've created the query which helped me to sort purchasers by content. It's in Legacy SQL:

`

SELECT
  user_dim.app_info.app_platform as appPlatform,
  event_dim.date as eventDate,
  COUNT(event_dim.name) as purchasers,
  user_dim.app_info.app_instance_id as appInstanceID,
  event_dim.params.value.string_value as contentID,
  event_dim.value_in_usd as revenue,
  CASE
    WHEN event_dim.params.value.string_value = 'content id1'  THEN 'content name1'
    WHEN event_dim.params.value.string_value = 'content id2'  THEN 'content name2'
    ELSE 'Undefined'
  END as contentName
FROM
  TABLE_QUERY([table_IOS], 'table_id CONTAINS "app_events_"'),
  TABLE_QUERY([table_ANDROID], 'table_id CONTAINS "app_events_"')
WHERE`enter code here`
  (event_dim.name = 'in_app_purchase' AND event_dim.params.key = 'product_id' OR event_dim.params.key = 'price')
  AND event_dim.params.value.string_value != 'null'
GROUP BY
  appPlatform, eventDate, appInstanceID, contentID, revenue, contentName
ORDER BY
  appPlatform, eventDate DESC

`


答:
Try this CSS

```<code>.input-group{
  display:table;
}
.form-control,.input-group-btn
{
  display:table-cell;
  vertical-align:middle;
}
</code>```

Link For Reference

style your button accordingly

hope this helps..

Title: Vertical align input and button without bootstrap

Body:
Try this CSS

.input-group{
  display:table;
}
.form-control,.input-group-btn
{
  display:table-cell;
  vertical-align:middle;
}

Link For Reference

style your button accordingly

hope this helps..


问:
Google Chrome viewport-anchored expand direction with flexbox
There is an issue in Google Chrome where elements expand/collapse in different directions relative to the viewport when placed inside a flexbox container with an adjacent flex item having space-between or center justified content.

This is not a problem in Firefox, IE11, Edge, or Safari as the elements always expand downward.

I'm curious:

Does Chrome's behavior here follow some spec? If so, which one?

If not, then why was this done in Chrome? (IMHO, it is horrible UX for the click trigger to disappear offscreen randomly.)

Can Chrome's behavior be modified or disabled in someway? Eg. through CSS or meta-tag?

Update 1: I've filed issue #739860 on chromium bug tracker seeking insight/explanation from Chromium devs, if possible.

Here are two examples inserted below. The full test suite describing the problem can be found in this pen: https://codepen.io/jameswilson/full/xrpRPg/  I've chosen to use slideToggle in this example so that the expand/collapse motion is animated and visible to the eye. The same behavior happens with the details tag, but cross-browser support is not there yet, and the expand/collapse is too janky.

Ex 1: Chrome's expand/collapse behavior for space-between justified flexbox

$('button').click(function() {
  $(this).next().slideToggle();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 30px;
  font-family: sans-serif;
}
aside,
aside div,
summary,
main,
button,
details p,
button + p {
  background: rgba(0,0,0,.09);
  border: none;
  padding: 20px;
  margin: 0;
}

.flexcontainer {
  display: flex;
}
aside {
  flex: 1;
  position: relative;
  max-width: 25%;
  background: mintcream;

  display: flex;
  flex-direction: column;
  position: relative;
}
aside.space-between {
  justify-content: space-between;
}
aside.center {
  justify-content: center;
}

main {
  flex: 3;
  position: relative;
  max-width: 75%;
  background: aliceblue;
  vertical-align: top;
  height: 100%;
}
main > * + * {
  margin-top: 20px;
}

button + p {
  display: none;
}</code>```

Top Sidebar

Bottom Sidebar

      <button>slideToggle</button>

Other browsers: always expands downward.

        Chrome: Should always expand downward because Top Sidebar is always visible.

      <button>slideToggle (usually expands down)</button>

Other browsers: always expands downward.

        Chrome: Should expand downward while Bottom Sidebar and Top Sidebar are both visible. But will expand upward if you scroll down far enough so that Top Sidebar is off-screen.

      <button>slideToggle (usually expands down)</button>

Other browsers: always expands downward.

        Chrome: Should expand downward while Bottom Sidebar and Top Sidebar are both visible. But will expand upward if you scroll down far enough so that Top Sidebar is off-screen.

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

<p><strong>Ex 2: Chrome's expand/collapse behavior for center justified flexbox</strong></p>

<p><img src="https://i.stack.imgur.com/N51nt.gif" alt="Chrome's expand/collapse behavior for center justified flexbox"></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('button').click(function() {
  $(this).next().slideToggle();
})</code>```

body {
  margin: 30px;
  font-family: sans-serif;
}
aside,
aside div,
summary,
main,
button,
details p,
button + p {
  background: rgba(0,0,0,.09);
  border: none;
  padding: 20px;
  margin: 0;
}

.flexcontainer {
  display: flex;
}
aside {
  flex: 1;
  position: relative;
  max-width: 25%;
  background: mintcream;

  display: flex;
  flex-direction: column;
  position: relative;
}
aside.space-between {
  justify-content: space-between;
}
aside.center {
  justify-content: center;
}

main {
  flex: 3;
  position: relative;
  max-width: 75%;
  background: aliceblue;
  vertical-align: top;
  height: 100%;
}
main > * + * {
  margin-top: 20px;
}

button + p {
  display: none;
}```
<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>
<section class="flexcontainer">
  <aside class="center">
    <div>Center Sidebar</div>
  </aside>
  <main>

    <div>
      <button>slideToggle (usually expands downwards)</button>
      <p>Other browsers: always expands downward.<br>
        Chrome: Usually expands downwards. Expands in both directions when the top-edge of the container scrolls out of the viewport.</p>
    </div>

    <div>
      <button>slideToggle</button>
      <p>Other browsers: always expands downward.<br>
        Chrome: Usually expands downwards. Expands in both directions when the top-edge of the container scrolls out of the viewport.</p>
    </div>

    <div>
      <button>slideToggle (usually expands downwards)</button>
      <p>Other browsers: always expands downward.<br>
        Chrome: Usually expands downwards. Expands in both directions when the top-edge of the container scrolls out of the viewport, but then resumes expanding downwards again when Center Sidebar scrolls out of view.</p>
    </div>
  </main>
</section></code>```

答:
Add this code to your flex container:

overflow-anchor: none

This will disable a feature in Chrome known as "scroll anchoring", which is causing the upward expansion of boxes (revised codepen).

In Chrome, the upward / downward direction of expanding boxes is governed by the scroll position in the viewport, not the layout itself.

Chrome takes a unique approach to this behavior for the purpose of improving the user experience.

Basically, they bind a DOM element to the current scroll position. The movement of this particular ("anchor") element on the screen will determine an adjustment, if any, to the scroll position.

They call this approach "Scroll Anchoring". The algorithm is explained on this page:
https://github.com/WICG/ScrollAnchoring/blob/master/explainer.md

This behavior is currently unique to Chrome, but Google is pushing for standardization.

In accordance with the Scroll Anchoring documentation, applying overflow-anchor: none to the appropriate element(s) will disable scroll anchoring adjustments.

More information:

https://github.com/WICG/ScrollAnchoring/blob/master/explainer.md

https://bugs.chromium.org/p/chromium/issues/detail?id=739860

https://hacks.mozilla.org/2019/03/scroll-anchoring-in-firefox-66/

Changing CSS flex order causes scrolling

Body:
There is an issue in Google Chrome where elements expand/collapse in different directions relative to the viewport when placed inside a flexbox container with an adjacent flex item having space-between or center justified content.

This is not a problem in Firefox, IE11, Edge, or Safari as the elements always expand downward.

I'm curious:

Does Chrome's behavior here follow some spec? If so, which one?

If not, then why was this done in Chrome? (IMHO, it is horrible UX for the click trigger to disappear offscreen randomly.)

Can Chrome's behavior be modified or disabled in someway? Eg. through CSS or meta-tag?

Update 1: I've filed issue #739860 on chromium bug tracker seeking insight/explanation from Chromium devs, if possible.

Here are two examples inserted below. The full test suite describing the problem can be found in this pen: https://codepen.io/jameswilson/full/xrpRPg/  I've chosen to use slideToggle in this example so that the expand/collapse motion is animated and visible to the eye. The same behavior happens with the details tag, but cross-browser support is not there yet, and the expand/collapse is too janky.

Ex 1: Chrome's expand/collapse behavior for space-between justified flexbox

$('button').click(function() {
  $(this).next().slideToggle();
})

body {
  margin: 30px;
  font-family: sans-serif;
}
aside,
aside div,
summary,
main,
button,
details p,
button + p {
  background: rgba(0,0,0,.09);
  border: none;
  padding: 20px;
  margin: 0;
}

.flexcontainer {
  display: flex;
}
aside {
  flex: 1;
  position: relative;
  max-width: 25%;
  background: mintcream;

  display: flex;
  flex-direction: column;
  position: relative;
}
aside.space-between {
  justify-content: space-between;
}
aside.center {
  justify-content: center;
}

main {
  flex: 3;
  position: relative;
  max-width: 75%;
  background: aliceblue;
  vertical-align: top;
  height: 100%;
}
main > * + * {
  margin-top: 20px;
}

button + p {
  display: none;
}

Top Sidebar

Bottom Sidebar

      <button>slideToggle</button>

Other browsers: always expands downward.

        Chrome: Should always expand downward because Top Sidebar is always visible.

      <button>slideToggle (usually expands down)</button>

Other browsers: always expands downward.

        Chrome: Should expand downward while Bottom Sidebar and Top Sidebar are both visible. But will expand upward if you scroll down far enough so that Top Sidebar is off-screen.

      <button>slideToggle (usually expands down)</button>

Other browsers: always expands downward.

        Chrome: Should expand downward while Bottom Sidebar and Top Sidebar are both visible. But will expand upward if you scroll down far enough so that Top Sidebar is off-screen.

Ex 2: Chrome's expand/collapse behavior for center justified flexbox

$('button').click(function() {
  $(this).next().slideToggle();
})

body {
  margin: 30px;
  font-family: sans-serif;
}
aside,
aside div,
summary,
main,
button,
details p,
button + p {
  background: rgba(0,0,0,.09);
  border: none;
  padding: 20px;
  margin: 0;
}

.flexcontainer {
  display: flex;
}
aside {
  flex: 1;
  position: relative;
  max-width: 25%;
  background: mintcream;

  display: flex;
  flex-direction: column;
  position: relative;
}
aside.space-between {
  justify-content: space-between;
}
aside.center {
  justify-content: center;
}

main {
  flex: 3;
  position: relative;
  max-width: 75%;
  background: aliceblue;
  vertical-align: top;
  height: 100%;
}
main > * + * {
  margin-top: 20px;
}

button + p {
  display: none;
}

Center Sidebar

      <button>slideToggle (usually expands downwards)</button>

Other browsers: always expands downward.

        Chrome: Usually expands downwards. Expands in both directions when the top-edge of the container scrolls out of the viewport.

      <button>slideToggle</button>

Other browsers: always expands downward.

        Chrome: Usually expands downwards. Expands in both directions when the top-edge of the container scrolls out of the viewport.

      <button>slideToggle (usually expands downwards)</button>

Other browsers: always expands downward.

        Chrome: Usually expands downwards. Expands in both directions when the top-edge of the container scrolls out of the viewport, but then resumes expanding downwards again when Center Sidebar scrolls out of view.

ContentLicense: CC BY-SA 4.0


问:
Java regex for replaceAll
What is the regex expression for replace all the A char with A1, B->B1, C->C1, D->D1 and E->E1 string?

```<code>//AND(A<>B,C>D)?GREEN(E-E)

String expr ="AND(A<>B,C>D)?GREEN(E-E)";
String regex="";
expr.replaceAll(regex, "N1");
System.out.println(expr);
</code>```

The result may be:

```<code>AND(A1<>B1,C1>D1)?GREEN(E1-E1)
</code>```

Thank you

答:
You can use a regex like this:

```<code>\b([A-E])\b
</code>```

With the replacement string $11

Bear in mind that in java you have to escape backslasher, so you have to use:

```<code>String expr = "AND(A<>B,C>D)?GREEN(E-E)";
expr = expr.replaceAll("\\b([A-E])\\b", "$11");
System.out.println(expr);
</code>```

Java demo

Regex demo

Update: following your comment, if you want to extend the regex to all letters, then replace [A-E] to [A-Z].

Title: Java regex for replaceAll

Body:
What is the regex expression for replace all the A char with A1, B->B1, C->C1, D->D1 and E->E1 string?

//AND(A<>B,C>D)?GREEN(E-E)

String expr ="AND(A<>B,C>D)?GREEN(E-E)";
String regex="";
expr.replaceAll(regex, "N1");
System.out.println(expr);

The result may be:

AND(A1<>B1,C1>D1)?GREEN(E1-E1)

Thank you

Body:
You can use a regex like this:

\b([A-E])\b

With the replacement string $11

Bear in mind that in java you have to escape backslasher, so you have to use:

String expr = "AND(A<>B,C>D)?GREEN(E-E)";
expr = expr.replaceAll("\\b([A-E])\\b", "$11");
System.out.println(expr);

Java demo

Regex demo

Update: following your comment, if you want to extend the regex to all letters, then replace [A-E] to [A-Z].


问:
Forcing a SimpleXML Object to a string, regardless of context
Let's say I have some XML like this

```<code><channel>
  <item>
    <title>This is title 1</title>
  </item>
</channel>
</code>```

The code below does what I want in that it outputs the title as a string

```<code>$xml = simplexml_load_string($xmlstring);
echo $xml->channel->item->title;
</code>```

Here's my problem.  The code below doesn't treat the title as a string in that context so I end up with a SimpleXML object in the array instead of a string.

```<code>$foo = array( $xml->channel->item->title );
</code>```

I've been working around it like this

```<code>$foo = array( sprintf("%s",$xml->channel->item->title) );
</code>```

but that seems ugly.

What's the best way to force a SimpleXML object to a string, regardless of context?

OwnerDisplayName: Mark Biek

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have some XML like this

<channel>
  <item>
    <title>This is title 1</title>
  </item>
</channel>

The code below does what I want in that it outputs the title as a string

$xml = simplexml_load_string($xmlstring);
echo $xml->channel->item->title;

Here's my problem.  The code below doesn't treat the title as a string in that context so I end up with a SimpleXML object in the array instead of a string.

$foo = array( $xml->channel->item->title );

I've been working around it like this

$foo = array( sprintf("%s",$xml->channel->item->title) );

but that seems ugly.

What's the best way to force a SimpleXML object to a string, regardless of context?

LastEditorDisplayName: Vincent

Body: Try strval($xml->channel->item->title)


问:
Zend Framework: Is there a way to get the path to the view template directory?
I'm just trying to find a way to get the path to the directory of my view templates using the Zend Framework. Is there a way to do that?</p>

答:
You can use getScriptPaths() function so from a view you could write:</p>

```<code>print_r($this->getScriptPaths());
</code>```

OwnerDisplayName: Andrew

Body:
You can use getScriptPaths() function so from a view you could write:

print_r($this->getScriptPaths());

OwnerDisplayName: Brian Fisher


问:
How to show result page when integrating Struts 2 with Apache Shiro
Using:

struts2 2.5.10, spring 4.x, struts2-spring-plugin 2.5.10, shiro 1.4.0,
shiro-spring 1.4.0.

web.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
  </context-param>

  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
  </filter>

  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

  <!-- shiro filter mapping has to be first -->
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
  </filter-mapping>

  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>
</code>```

beanx.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        ">

    <bean name="loginAction" class="example.shiro.action.LoginAction" >

    </bean>

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="loginUrl" value="/login.jsp" />

        <property name="filterChainDefinitions">
            <value>
                /login.jsp = authc
                /logout = logout
                /* = authc
            </value>
        </property>
    </bean>

    <bean id="iniRealm" class="org.apache.shiro.realm.text.IniRealm">
        <property name="resourcePath" value="classpath:shiro.ini" />
    </bean>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">

        <property name="realm" ref="iniRealm" />
    </bean>

    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

</beans>
</code>```

struts.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.devMode" value="true" />

    <package name="default" extends="struts-default">

        <action name="list" class="loginAction" method="list">
            <result name="success">/success.jsp</result>
            <result name="error">error.jsp</result>
        </action>

    </package>

</struts>
</code>```

index.jsp :

```<code><body>
    <s:action name="list" />
</body>
</code>```

login.jsp looks like:

```<code><form name="loginform" action="" method="post">
        <table align="left" border="0" cellspacing="0" cellpadding="3">
            <tr>
                <td>Username:</td>
                <td><input type="text" name="username" maxlength="30"></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" name="password" maxlength="30"></td>
            </tr>
            <tr>
                <td colspan="2" align="left"><input type="checkbox"
                    name="rememberMe"><font size="2">Remember Me</font></td>
            </tr>
            <tr>
                <td colspan="2" align="right"><input type="submit"
                    name="submit" value="Login"></td>
            </tr>
        </table>
    </form>
</code>```

LoginAction.list() :

```<code>public String list() {

        Subject currentUser = SecurityUtils.getSubject();

        if(currentUser.isAuthenticated()) {System.out.println("user : "+currentUser.getPrincipal());
            System.out.println("You are authenticated!");
        } else {
            System.out.println("Hey hacker, hands up!");
        }

        return "success";
    }
</code>```

shiro.ini :

```<code>[users]
root=123,admin
guest=456,guest
frank=789,roleA,roleB

# role name=permission1,permission2,..,permissionN
[roles]
admin=*
roleA=lightsaber:*
roleB=winnebago:drive:eagle5
</code>```

index.jsp, login.jsp, and success.jsp are placed under webapp.

What I want is : enter into LoginAction.list() need to be authenticated, if login success, then run LoginAction.list() and return "success" then show success.jsp which defined as Struts action result.

Now LoginAction.list() can be executed after login successful, but success.jsp is not displayed, browser is a blank page.

Why?

答:
I found the reason : I used <s:action name="list" /> in index.jsp, however, the struts doc said if we want to see the result page with <s:action>, then we have to set its property executeResult to true, that is like <s:action name="list" executeResult="true"/>.

In my opinion, this is a little wired, this attribute should be true by default.

Body:
Using:

struts2 2.5.10, spring 4.x, struts2-spring-plugin 2.5.10, shiro 1.4.0,
shiro-spring 1.4.0.

web.xml :

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
  </context-param>

  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
  </filter>

  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
  </filter-mapping>

  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>

beanx.xml :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        ">

    <bean name="loginAction" class="example.shiro.action.LoginAction" >

    </bean>

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="loginUrl" value="/login.jsp" />

        <property name="filterChainDefinitions">
            <value>
                /login.jsp = authc
                /logout = logout
                /* = authc
            </value>
        </property>
    </bean>

    <bean id="iniRealm" class="org.apache.shiro.realm.text.IniRealm">
        <property name="resourcePath" value="classpath:shiro.ini" />
    </bean>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">

        <property name="realm" ref="iniRealm" />
    </bean>

    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

</beans>

struts.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.devMode" value="true" />

    <package name="default" extends="struts-default">

        <action name="list" class="loginAction" method="list">
            <result name="success">/success.jsp</result>
            <result name="error">error.jsp</result>
        </action>

    </package>

</struts>

index.jsp :

    <s:action name="list" />

login.jsp looks like:

<form name="loginform" action="" method="post">

                Username:
                <input type="text" name="username" maxlength="30">

                Password:
                <input type="password" name="password" maxlength="30">

                <input type="checkbox"
                    name="rememberMe">Remember Me

                <input type="submit"
                    name="submit" value="Login">

    </form>

LoginAction.list() :

public String list() {

        Subject currentUser = SecurityUtils.getSubject();

        if(currentUser.isAuthenticated()) {System.out.println("user : "+currentUser.getPrincipal());
            System.out.println("You are authenticated!");
        } else {
            System.out.println("Hey hacker, hands up!");
        }

        return "success";
    }

shiro.ini :

[users]
root=123,admin
guest=456,guest
frank=789,roleA,roleB

# role name=permission1,permission2,..,permissionN
[roles]
admin=*
roleA=lightsaber:*
roleB=winnebago:drive:eagle5

index.jsp, login.jsp, and success.jsp are placed under webapp.

What I want is : enter into LoginAction.list() need to be authenticated, if login success, then run LoginAction.list() and return "success" then show success.jsp which defined as Struts action result.

Now LoginAction.list() can be executed after login successful, but success.jsp is not displayed, browser is a blank page.

Why?


问:
If...Else Statement always diverts to "else".
I am trying to run a "presence check" on a radio group, to determine what happens if 1 of 2 radiobuttons are selected in the group (if statement), if the other of the 2 radiobuttons is selected instead (else if statement) or if neither are selected (else statement). The code for this is as follows:

```<code>if (rdbAM.isSelected()) {
        strTime = rdbAM.getText().toString();
    } else if(rdbPM.isSelected()){
        strTime = rdbPM.getText().toString();
    } else {
        AlertDialog.Builder WrongDateFormat = new AlertDialog.Builder(this);
        WrongDateFormat.setMessage("Please Select AM or PM");
        WrongDateFormat.setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alertWrongDateFormat = WrongDateFormat.create();
        alertWrongDateFormat.show();
        return;
    }
</code>```

So basically, what this should do is either, set the variable called "strTime" to whatever the text of the selected radiobutton in the radiogroup is, or display an error message if neither are selected. It is instead always displaying this error message, regardless of whether either radiobutton is selected or not:

(As you can see above, the "AM" radiobutton is selected, but error is still being displayed).

Any suggestions as to why this may be would be appreciated. Please note that I am relatively new to Android development, so if it is clearly something obvious then I apologise, but I have been trying to get my head round this for several days now! If you would like to see any further code, please let me know and I'll be happy to provide it, but am trying to keep it as private as possible, so didn't want to post everything in the initial post if not necessary. Thanks in advance.

答:
According the documentation the RadioButton extends the CompoundButton that offers the method isChecked(). However there is poorly described the difference from the method isSelected() from the extended class View that might be confusing.

Do the following and it should work:

```<code>rdbAM.isChecked();
</code>```

Body:
I am trying to run a "presence check" on a radio group, to determine what happens if 1 of 2 radiobuttons are selected in the group (if statement), if the other of the 2 radiobuttons is selected instead (else if statement) or if neither are selected (else statement). The code for this is as follows:

if (rdbAM.isSelected()) {
        strTime = rdbAM.getText().toString();
    } else if(rdbPM.isSelected()){
        strTime = rdbPM.getText().toString();
    } else {
        AlertDialog.Builder WrongDateFormat = new AlertDialog.Builder(this);
        WrongDateFormat.setMessage("Please Select AM or PM");
        WrongDateFormat.setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alertWrongDateFormat = WrongDateFormat.create();
        alertWrongDateFormat.show();
        return;
    }

So basically, what this should do is either, set the variable called "strTime" to whatever the text of the selected radiobutton in the radiogroup is, or display an error message if neither are selected. It is instead always displaying this error message, regardless of whether either radiobutton is selected or not:

(As you can see above, the "AM" radiobutton is selected, but error is still being displayed).

Any suggestions as to why this may be would be appreciated. Please note that I am relatively new to Android development, so if it is clearly something obvious then I apologise, but I have been trying to get my head round this for several days now! If you would like to see any further code, please let me know and I'll be happy to provide it, but am trying to keep it as private as possible, so didn't want to post everything in the initial post if not necessary. Thanks in advance.

Body:
According the documentation the RadioButton extends the CompoundButton that offers the method isChecked(). However there is poorly described the difference from the method isSelected() from the extended class View that might be confusing.

Do the following and it should work:

rdbAM.isChecked();


问:
Spring MqttPahoMessageDrivenChannelAdapter Lost connection:Connection lost; retrying
We are using Spring message-driven-channel-adapter to subscribe MQTT topic. But we are getting below error very frequently. I have tested connection using JavaScript client(mqttws31.js), which is working fine. Means there is no issue with connection.

Error :-

```<code>org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter connectionLost
SEVERE: Lost connection:Connection lost; retrying...
</code>```

MQTT message :-

```<code>[payload=6483D03E4C75BA943148F18D73,1.00,1E, headers={mqtt_retained=false, mqtt_qos=0,
id=5fa41168-34c6-1e3d-a775-e3146842990a, mqtt_topic=TEST/GATEWAY2, mqtt_duplicate=false, timestamp=1499067757559}]
</code>```

Configuration :-

```<code><bean id="clientFactory"
    class="org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory">
    <property name="userName" value="${mqtt.username}" />
    <property name="password" value="${mqtt.password}" />
</bean>

<int-mqtt:message-driven-channel-adapter
    id="mqttInbound" client-id="${mqtt.default.client.id}" url="${mqtt.url}"
    topics="${topics}" client-factory="clientFactory" auto-startup="true"
    channel="output" error-channel="errorChannel" />

<int:channel id="output" />
<int:channel id="errorChannel" />

<int:service-activator input-channel="errorChannel"
    ref="errorMessageLogger" method="logError" />
<bean id="errorMessageLogger" class="com.mqtt.ErrorMessageLogger" />

<int:service-activator input-channel="output"
    method="handleMessage" ref="mqttLogger" />
<bean id="mqttLogger" class="com.mqtt.MqttReciever" />
</code>```

pom.xml :

```<code><dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-mqtt</artifactId>
    <version>4.2.2.RELEASE</version>
</dependency>
</code>```

While debugging org.eclipse.paho.client.mqttv3-1.1.1-sources.jar:-

CommsReceiver.Java

```<code>public void run() {
        final String methodName = "run";
        MqttToken token = null;

        while (running && (in != null)) {
            try {
                //@TRACE 852=network read message
                log.fine(CLASS_NAME,methodName,"852");
                receiving = in.available() > 0;
                MqttWireMessage message = in.readMqttWireMessage();
                receiving = false;

                // instanceof checks if message is null
                if (message instanceof MqttAck) {
                    token = tokenStore.getToken(message);
                    if (token!=null) {
                        synchronized (token) {
                            // Ensure the notify processing is done under a lock on the token
                            // This ensures that the send processing can complete  before the
                            // receive processing starts! ( request and ack and ack processing
                            // can occur before request processing is complete if not!
                            clientState.notifyReceivedAck((MqttAck)message);
                        }
                    } else if(message instanceof MqttPubRec || message instanceof MqttPubComp || message instanceof MqttPubAck) {
                        //This is an ack for a message we no longer have a ticket for.
                        //This probably means we already received this message and it's being send again
                        //because of timeouts, crashes, disconnects, restarts etc.
                        //It should be safe to ignore these unexpected messages.
                        log.fine(CLASS_NAME, methodName, "857");
                    } else {
                        // It its an ack and there is no token then something is not right.
                        // An ack should always have a token assoicated with it.
                        throw new MqttException(MqttException.REASON_CODE_UNEXPECTED_ERROR);
                    }
                } else {
                    if (message != null) {
                        // A new message has arrived
                        clientState.notifyReceivedMsg(message);
                    }
                }
            }
            catch (MqttException ex) {
                //@TRACE 856=Stopping, MQttException
                log.fine(CLASS_NAME,methodName,"856",null,ex);
                running = false;
                // Token maybe null but that is handled in shutdown
                clientComms.shutdownConnection(token, ex);
            }
            catch (IOException ioe) {
                //@TRACE 853=Stopping due to IOException
                log.fine(CLASS_NAME,methodName,"853");

                running = false;
                // An EOFException could be raised if the broker processes the
                // DISCONNECT and ends the socket before we complete. As such,
                // only shutdown the connection if we're not already shutting down.
                if (!clientComms.isDisconnecting()) {
                    clientComms.shutdownConnection(token, new MqttException(MqttException.REASON_CODE_CONNECTION_LOST, ioe));
                }
            }
            finally {
                receiving = false;
            }
        }

        //@TRACE 854=<
        log.fine(CLASS_NAME,methodName,"854");
    }
</code>```

In above method, sometime in.readMqttWireMessage() throw IOException. So based on catch block it reconnect using clientComms.shutdownConnection(token, ...

答:
But you are still not really describing a problem. You show a message above so it must be working for you. Paho is detecting a connection problem; it informs Spring Integration which will reconnect.

You can get complete information about the exception by adding an ApplicationListener to your application.

```<code>@Bean
public ApplicationListener<?> eventListener() {
    return new ApplicationListener<MqttConnectionFailedEvent>() {

        @Override
        public void onApplicationEvent(MqttConnectionFailedEvent event) {
            event.getCause().printStackTrace();
        }

    };
}
</code>```

Result:

```<code>Connection lost (32109) - java.io.EOFException
    at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:164)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.EOFException
    at java.io.DataInputStream.readByte(DataInputStream.java:267)
    at org.eclipse.paho.client.mqttv3.internal.wire.MqttInputStream.readMqttWireMessage(MqttInputStream.java:92)
    at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:116)
    ... 1 more
</code>```

(when I shut down the broker).

If you think there's a problem with the paho client, you should raise an issue for that project.

Body:
We are using Spring message-driven-channel-adapter to subscribe MQTT topic. But we are getting below error very frequently. I have tested connection using JavaScript client(mqttws31.js), which is working fine. Means there is no issue with connection.

Error :-

org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter connectionLost
SEVERE: Lost connection:Connection lost; retrying...

MQTT message :-

[payload=6483D03E4C75BA943148F18D73,1.00,1E, headers={mqtt_retained=false, mqtt_qos=0,
id=5fa41168-34c6-1e3d-a775-e3146842990a, mqtt_topic=TEST/GATEWAY2, mqtt_duplicate=false, timestamp=1499067757559}]

Configuration :-

<bean id="clientFactory"
    class="org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory">
    <property name="userName" value="${mqtt.username}" />
    <property name="password" value="${mqtt.password}" />
</bean>

<int-mqtt:message-driven-channel-adapter
    id="mqttInbound" client-id="${mqtt.default.client.id}" url="${mqtt.url}"
    topics="${topics}" client-factory="clientFactory" auto-startup="true"
    channel="output" error-channel="errorChannel" />

<int:channel id="output" />
<int:channel id="errorChannel" />

<int:service-activator input-channel="errorChannel"
    ref="errorMessageLogger" method="logError" />
<bean id="errorMessageLogger" class="com.mqtt.ErrorMessageLogger" />

<int:service-activator input-channel="output"
    method="handleMessage" ref="mqttLogger" />
<bean id="mqttLogger" class="com.mqtt.MqttReciever" />

pom.xml :

<dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-mqtt</artifactId>
    <version>4.2.2.RELEASE</version>
</dependency>

While debugging org.eclipse.paho.client.mqttv3-1.1.1-sources.jar:-

CommsReceiver.Java

public void run() {
        final String methodName = "run";
        MqttToken token = null;

        while (running && (in != null)) {
            try {
                //@TRACE 852=network read message
                log.fine(CLASS_NAME,methodName,"852");
                receiving = in.available() > 0;
                MqttWireMessage message = in.readMqttWireMessage();
                receiving = false;

                // instanceof checks if message is null
                if (message instanceof MqttAck) {
                    token = tokenStore.getToken(message);
                    if (token!=null) {
                        synchronized (token) {
                            // Ensure the notify processing is done under a lock on the token
                            // This ensures that the send processing can complete  before the
                            // receive processing starts! ( request and ack and ack processing
                            // can occur before request processing is complete if not!
                            clientState.notifyReceivedAck((MqttAck)message);
                        }
                    } else if(message instanceof MqttPubRec || message instanceof MqttPubComp || message instanceof MqttPubAck) {
                        //This is an ack for a message we no longer have a ticket for.
                        //This probably means we already received this message and it's being send again
                        //because of timeouts, crashes, disconnects, restarts etc.
                        //It should be safe to ignore these unexpected messages.
                        log.fine(CLASS_NAME, methodName, "857");
                    } else {
                        // It its an ack and there is no token then something is not right.
                        // An ack should always have a token assoicated with it.
                        throw new MqttException(MqttException.REASON_CODE_UNEXPECTED_ERROR);
                    }
                } else {
                    if (message != null) {
                        // A new message has arrived
                        clientState.notifyReceivedMsg(message);
                    }
                }
            }
            catch (MqttException ex) {
                //@TRACE 856=Stopping, MQttException
                log.fine(CLASS_NAME,methodName,"856",null,ex);
                running = false;
                // Token maybe null but that is handled in shutdown
                clientComms.shutdownConnection(token, ex);
            }
            catch (IOException ioe) {
                //@TRACE 853=Stopping due to IOException
                log.fine(CLASS_NAME,methodName,"853");

                running = false;
                // An EOFException could be raised if the broker processes the
                // DISCONNECT and ends the socket before we complete. As such,
                // only shutdown the connection if we're not already shutting down.
                if (!clientComms.isDisconnecting()) {
                    clientComms.shutdownConnection(token, new MqttException(MqttException.REASON_CODE_CONNECTION_LOST, ioe));
                }
            }
            finally {
                receiving = false;
            }
        }

        //@TRACE 854=<
        log.fine(CLASS_NAME,methodName,"854");
    }

In above method, sometime in.readMqttWireMessage() throw IOException. So based on catch block it reconnect using clientComms.shutdownConnection(token, ...

Body:
But you are still not really describing a problem. You show a message above so it must be working for you. Paho is detecting a connection problem; it informs Spring Integration which will reconnect.

You can get complete information about the exception by adding an ApplicationListener to your application.

@Bean
public ApplicationListener<?> eventListener() {
    return new ApplicationListener<MqttConnectionFailedEvent>() {

        @Override
        public void onApplicationEvent(MqttConnectionFailedEvent event) {
            event.getCause().printStackTrace();
        }

    };
}

Result:

Connection lost (32109) - java.io.EOFException
    at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:164)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.EOFException
    at java.io.DataInputStream.readByte(DataInputStream.java:267)
    at org.eclipse.paho.client.mqttv3.internal.wire.MqttInputStream.readMqttWireMessage(MqttInputStream.java:92)
    at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:116)
    ... 1 more

(when I shut down the broker).

If you think there's a problem with the paho client, you should raise an issue for that project.


问:
How to use HTML formatting with telegra.ph API
I am using the telegra.ph api to edit the page I have made. I want to format the text that I have on the page to align to the right of the page. Right now the content that I am sending through a Python request is:

```<code>from telegraph import Telegraph
tel = Telegraph(my_access_token)

content = [{"tag": "h4",
            "children": ["Hello, World!"]},
            "attrs": {"dir": "rtl"}
            }]

page = tel.edit_page(path='/url',
                     title='testing',
                     content=content,
                     )
</code>```

However the request completely ignores the "dir": "rtl" attribute, since "dir" is not one of the attributes that Telegraph accepts. How can one align the text to the right through telegra.ph?

答: In case anyone is looking for an answer still, I could shift the text right to left by changing the title to Arabic/Farsi letters. In case your Arabic/Farsi text is formatted left to right, you can use Arabic/Farsi letters in the page title to fix it.</p>

Body:
I am using the telegra.ph api to edit the page I have made. I want to format the text that I have on the page to align to the right of the page. Right now the content that I am sending through a Python request is:

from telegraph import Telegraph
tel = Telegraph(my_access_token)

content = [{"tag": "h4",
            "children": ["Hello, World!"]},
            "attrs": {"dir": "rtl"}
            }]

page = tel.edit_page(path='/url',
                     title='testing',
                     content=content,
                     )

However the request completely ignores the "dir": "rtl" attribute, since "dir" is not one of the attributes that Telegraph accepts. How can one align the text to the right through telegra.ph?


问:
When to use each type of loop?
I'm learning the basics of programming here (C#) but I think this question is generic in its nature.

What are some simple practical situations that lend themselves closer to a particular type of loop?

The while and for loops seem pretty similar and there are several SO questions addressing the differences between the two. How about foreach? From my basic understanding, its seems I ought to be able to do everything a foreach loop does within a for loop.

答:
As others have said, 'it depends'.

I find I use simple 'for' loops very rarely nowadays.  If you start to use Linq you'll find you either don't need loops at all and when you do it's the 'foreach' loop that's called for.

Ultimately I agree with Colin Mackay - code for readability!

Title: When to use each type of loop?


问:
Round corners of table
I try to make round corners of my table

Here is  my code

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

08.00

09.00

10.00

11.00

12.00

13.00

14.00

15.00

16.00

17.00

18.00

19.00

```

But it not works.

Where is trouble?

How I can make it rounded?

EDIT

I added whole code oа View for full understanding of problem. I see border, but not with rounded corners

答:
 was missing

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

```

Title: Round corners of table

Body:
I try to make round corners of my table

Here is  my code

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

08.00

09.00

10.00

11.00

12.00

13.00

14.00

15.00

16.00

17.00

18.00

19.00

But it not works.

Where is trouble?

How I can make it rounded?

EDIT

I added whole code oа View for full understanding of problem. I see border, but not with rounded corners

Body:
</table> was missing

<table class="table" style="width: 100%;border-style: solid; border-color: #1d69b4;border-radius: 10px;">
  <tr style="background: white">

    <th style="font-size: 18px; text-align: center;color:#1d69b4;border-style: solid; border-color: #1d69b4;border-radius: 10px;">
      <b>Hours</b><b style="margin-left: 30px;"> Monday</b>
    </th>
    <th style="font-size: 20px; text-align: center;color:#1d69b4;border-style: solid; border-color: #1d69b4;border-radius: 10px;">
      <b>Hours</b><b style="margin-left: 30px;"> Tuesday</b>
    </th>
    <th style="font-size: 20px; text-align: center;color:#1d69b4;border-style: solid; border-color: #1d69b4;border-radius: 10px;">
      <b>Hours</b><b style="margin-left: 30px;"> Wednesday</b>
    </th>
    <th style="font-size: 20px; text-align: center;color:#1d69b4;border-style: solid; border-color: #1d69b4;border-radius: 10px;">
      <b>Hours</b><b style="margin-left: 30px;">  Thursday</b>
    </th>
    <th style="font-size: 20px; text-align: center;color:#1d69b4;border-style: solid; border-color: #1d69b4;border-radius: 10px;">
      <b>Hours</b><b style="margin-left: 30px;">  Friday</b>
    </th>
    <th style="font-size: 20px; text-align: center;color:#1d69b4;border-style: solid; border-color: #1d69b4;border-radius: 10px;">
      <b>Hours</b><b style="margin-left: 30px;"> Saturday</b>
    </th>
    <th style="font-size: 20px; text-align: center;color:#1d69b4;border-style: solid; border-color: #1d69b4;border-radius: 10px;">
      <b>Hours</b><b style="margin-left: 30px;"> Sunday</b>
    </th>

  </tr>
</table>


问:
CurieBLE: /ble_service/ble_protocol.h: no such file or directory
I rewrote a program from here and combined it with the Adafruit BNO055 program so to read the calibration data on an Android app I made on MITs App Inventor.

I'm getting the following error:

```<code>C:\Program Files
(x86)\Arduino\libraries\CurieBLE\src/BLECommon.h:26:54: fatal error:
../src/services/ble_service/ble_protocol.h: No such file or directory
</code>```

Looking through the folders (both on my PC and github) I can find the BLECommon, but there is no 'ble_service'...though there is a 'BLEService'. I also can't find a 'ble_protocol.h' anywhere.

Can anyone help me understand what I may be doing wrong, and how I can remedy this error?

答:
I'm trying to do something similar - use a PlatformIO compiler as part of my CI process in Gitlab. I received a similar error when compiling so I went looking for the missing files and found them here (note, I'm using linux so adjust accordingly for Windows):

```<code>/.arduino15/packages/Intel/hardware/arc32/2.0.2/system/libarc32_arduino101/framework/src/services/ble_service
</code>```

I moved the ble_service folder to the CurieBLE library folder (within the project folder) so now my project folder structure is:

```<code>|--lib
|  |--CurieBLE
|  |  |--src
|  |  |  |--bluetooth
|  |  |  |  |[contents of the bluetooth folder from .arduino15/packages/Intel/hardware/arc32/2.0.2/system/libarc32_arduino101/drivers]
|  |  |  |--services
|  |  |  |  |--ble_service
|  |  |  |  |  |[contents of the ble_service folder from above path]
|  |  |  |[rest of the CurieBLE folder contents]
|--src
|  |- main.cpp
|- platformio.ini
</code>```

I'm still working through other errors to get PlatformIO to work but this at least fixed the missing libraries/files.

Body:
I rewrote a program from here and combined it with the Adafruit BNO055 program so to read the calibration data on an Android app I made on MITs App Inventor.

I'm getting the following error:

C:\Program Files
(x86)\Arduino\libraries\CurieBLE\src/BLECommon.h:26:54: fatal error:
../src/services/ble_service/ble_protocol.h: No such file or directory

Looking through the folders (both on my PC and github) I can find the BLECommon, but there is no 'ble_service'...though there is a 'BLEService'. I also can't find a 'ble_protocol.h' anywhere.

Can anyone help me understand what I may be doing wrong, and how I can remedy this error?

Body:
I'm trying to do something similar - use a PlatformIO compiler as part of my CI process in Gitlab. I received a similar error when compiling so I went looking for the missing files and found them here (note, I'm using linux so adjust accordingly for Windows):

/.arduino15/packages/Intel/hardware/arc32/2.0.2/system/libarc32_arduino101/framework/src/services/ble_service

I moved the ble_service folder to the CurieBLE library folder (within the project folder) so now my project folder structure is:

|--lib
|  |--CurieBLE
|  |  |--src
|  |  |  |--bluetooth
|  |  |  |  |[contents of the bluetooth folder from .arduino15/packages/Intel/hardware/arc32/2.0.2/system/libarc32_arduino101/drivers]
|  |  |  |--services
|  |  |  |  |--ble_service
|  |  |  |  |  |[contents of the ble_service folder from above path]
|  |  |  |[rest of the CurieBLE folder contents]
|--src
|  |- main.cpp
|- platformio.ini

I'm still working through other errors to get PlatformIO to work but this at least fixed the missing libraries/files.


问:
Determine Windows as 32- or 64bit
This is the code I have so far:

```<code>#include <MsgBoxConstants.au3>
If FileExists(@HomeDrive & "Program Files (x86)") Then
   $arc = 64
Else
   $arc = 32
EndIf
MsgBox("Hello", "Bit", "The computer that the program is been run on is a " & $arc & "bit one.")
</code>```

It will say my computer is 32bit when it is 64. So I had a look at the path and made new code:

```<code>#include <MsgBoxConstants.au3>
If FileExists(@HomeDrive & "Program Files (x86)") Then
   $arc = 64
Else
   $arc = 32
EndIf
$path = @HomeDrive & "\Program Files (x86)"
MsgBox("Hello", $path, "The computer that the program is been run on is a " & $arc & "bit one.")
</code>```

This shows the path and seems to be OK. Where am I going wrong?

答:
Does any one know where I am going wrong.

As per Documentation - Macros:

@OSArch Returns one of the following: "X86", "IA64", "X64" - this is the architecture type of the currently running operating system.

@CPUArch Returns "X86" when the CPU is a 32-bit CPU and "X64" when the CPU is 64-bit.

Example:

```<code>Global Const $g_sTpl = 'OS  : %s\nCPU : %s\n'
Global Const $g_sMsg = StringFormat($g_sTpl, @OSArch, @CPUArch)

ConsoleWrite($g_sMsg)
</code>```

Title: Determine Windows as 32- or 64bit

Body:
This is the code I have so far:

#include <MsgBoxConstants.au3>
If FileExists(@HomeDrive & "Program Files (x86)") Then
   $arc = 64
Else
   $arc = 32
EndIf
MsgBox("Hello", "Bit", "The computer that the program is been run on is a " & $arc & "bit one.")

It will say my computer is 32bit when it is 64. So I had a look at the path and made new code:

#include <MsgBoxConstants.au3>
If FileExists(@HomeDrive & "Program Files (x86)") Then
   $arc = 64
Else
   $arc = 32
EndIf
$path = @HomeDrive & "\Program Files (x86)"
MsgBox("Hello", $path, "The computer that the program is been run on is a " & $arc & "bit one.")

This shows the path and seems to be OK. Where am I going wrong?

Body:
Does any one know where I am going wrong.

As per Documentation - Macros:

@OSArch Returns one of the following: "X86", "IA64", "X64" - this is the architecture type of the currently running operating system.

@CPUArch Returns "X86" when the CPU is a 32-bit CPU and "X64" when the CPU is 64-bit.

Example:

Global Const $g_sTpl = 'OS  : %s\nCPU : %s\n'
Global Const $g_sMsg = StringFormat($g_sTpl, @OSArch, @CPUArch)

ConsoleWrite($g_sMsg)


问:
c program to find average
i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.

```<code>#include <math.h>
#include <stdio.h>

int main()
{
    int n;
    float per1, per2, per3;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    for (int i = 0; i <= n - 1; i++)
    {
        if (arr[i] < 0)
        {
            int sum1 = sum1 + 1;
        }
        if (arr[i] > 0)
        {
            sum2 = sum2 + 1;
        }
        else
        {
            sum3 = sum3 + 1;
        }
    }

    per1 = sum1 / n;
    per2 = sum2 / n;
    per3 = sum3 / n;
    printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);

    return 0;
}
</code>```

output

```<code>3
1
-2
0
0.000000
0.000000
0.000000
</code>```

the last three numbers should be .3,.3,.3 but it is giving zeros.

答:
I think this code is a little bit better. I've used the function malloc() instead of the "scattered" declaration int arr[n] (in this case I prefer the old C style).

People already said you the problem relevant to the variable types and some ways to solve the problem. Here there's another way similar to the others you just saw between the answers.

```<code>#include <math.h>
#include <stdio.h>
#include <malloc.h>

#define STR_ORD_SUFFIX(i) (i>3)?"th":(i==0)?"--":(i==1)?"st":(i==2)?"nd":"rd"

int main()
{
    int n, *arr=NULL;
    float per1,per2,per3;

    int sum1=0;
    int sum2=0;
    int sum3=0;

    printf("How many number you have to insert? ");
    scanf("%d",&n);
    if (n<=0)
        return 1;

    arr=malloc(n*sizeof(*arr));
    if (arr==NULL)
        return 2;

    printf("Insert %d number%c\n",n,(n!=1)?'s':'\x0');
    for(int i = 0; i < n; i++){
        printf("%4d%s: ",i+1,STR_ORD_SUFFIX(i+1));
        scanf("%d",&arr[i]);
    }

    for(int i=0;i<=n-1;i++)
    {
        if(arr[i]<0){
            sum1=sum1+1;
        } else if(arr[i]>0){
            sum2=sum2+1;
        } else {
            sum3=sum3+1;
        }
    }

    per1=sum1; per1/=n; per1*=100.0;
    per2=sum2; per2/=n; per2*=100.0;
    per3=sum3; per3/=n; per3*=100.0;

    printf("\n<0 %.6f%%\n>0 %.6f%%\n=0 %.6f%%\n",per1,per2,per3);

    if (arr!=NULL)
        free(arr);

    return 0;

}
</code>```

Title: c program to find average

Body:
i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.

#include <math.h>
#include <stdio.h>

int main()
{
    int n;
    float per1, per2, per3;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    for (int i = 0; i <= n - 1; i++)
    {
        if (arr[i] < 0)
        {
            int sum1 = sum1 + 1;
        }
        if (arr[i] > 0)
        {
            sum2 = sum2 + 1;
        }
        else
        {
            sum3 = sum3 + 1;
        }
    }

    per1 = sum1 / n;
    per2 = sum2 / n;
    per3 = sum3 / n;
    printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);

    return 0;
}

output

3
1
-2
0
0.000000
0.000000
0.000000

the last three numbers should be .3,.3,.3 but it is giving zeros.

Body:
I think this code is a little bit better. I've used the function malloc() instead of the "scattered" declaration int arr[n] (in this case I prefer the old C style).

People already said you the problem relevant to the variable types and some ways to solve the problem. Here there's another way similar to the others you just saw between the answers.

#include <math.h>
#include <stdio.h>
#include <malloc.h>

#define STR_ORD_SUFFIX(i) (i>3)?"th":(i==0)?"--":(i==1)?"st":(i==2)?"nd":"rd"

int main()
{
    int n, *arr=NULL;
    float per1,per2,per3;

    int sum1=0;
    int sum2=0;
    int sum3=0;

    printf("How many number you have to insert? ");
    scanf("%d",&n);
    if (n<=0)
        return 1;

    arr=malloc(n*sizeof(*arr));
    if (arr==NULL)
        return 2;

    printf("Insert %d number%c\n",n,(n!=1)?'s':'\x0');
    for(int i = 0; i < n; i++){
        printf("%4d%s: ",i+1,STR_ORD_SUFFIX(i+1));
        scanf("%d",&arr[i]);
    }

    for(int i=0;i<=n-1;i++)
    {
        if(arr[i]<0){
            sum1=sum1+1;
        } else if(arr[i]>0){
            sum2=sum2+1;
        } else {
            sum3=sum3+1;
        }
    }

    per1=sum1; per1/=n; per1*=100.0;
    per2=sum2; per2/=n; per2*=100.0;
    per3=sum3; per3/=n; per3*=100.0;

    printf("\n<0 %.6f%%\n>0 %.6f%%\n=0 %.6f%%\n",per1,per2,per3);

    if (arr!=NULL)
        free(arr);

    return 0;

}


问:
How to avoid overfitting on a simple feed forward network
Using the pima indians diabetes dataset I'm trying to build an accurate model using Keras. I've written the following code:

```<code># Visualize training history
from keras import callbacks
from keras.layers import Dropout

tb = callbacks.TensorBoard(log_dir='/.logs', histogram_freq=10, batch_size=32,
                           write_graph=True, write_grads=True, write_images=False,
                           embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
# Visualize training history
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu', name='first_input'))
model.add(Dense(500, activation='tanh', name='first_hidden'))
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(8, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))

# Compile model
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# Fit the model
history = model.fit(X, Y, validation_split=0.33, epochs=1000, batch_size=10, verbose=0, callbacks=[tb])
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
</code>```

After several tries, I've added dropout layers in order to avoid overfitting, but with no luck. The following graph shows that the validation loss and training loss gets separate at one point.

What else could I do to optimize this network?

UPDATE:
based on the comments I got I've tweaked the code like so:

```<code>model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', kernel_regularizer=regularizers.l2(0.01),
                activity_regularizer=regularizers.l1(0.01), activation='relu',
                name='first_input'))  # added regularizers
model.add(Dense(8, activation='relu', name='first_hidden'))  # reduced to 8 neurons
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(5, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))
</code>```

Here are the graphs for 500 epochs

答:
For a dataset like the Diabetes one you can use a much simpler network. Try to reduce the neurons in your second layer. (Is there a specific reason why you chose tanh as the activation there?).

In addition you simply can add an EarlyStopping callback to your training: https://keras.io/callbacks/

Body:
Using the pima indians diabetes dataset I'm trying to build an accurate model using Keras. I've written the following code:

# Visualize training history
from keras import callbacks
from keras.layers import Dropout

tb = callbacks.TensorBoard(log_dir='/.logs', histogram_freq=10, batch_size=32,
                           write_graph=True, write_grads=True, write_images=False,
                           embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
# Visualize training history
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu', name='first_input'))
model.add(Dense(500, activation='tanh', name='first_hidden'))
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(8, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))

# Compile model
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# Fit the model
history = model.fit(X, Y, validation_split=0.33, epochs=1000, batch_size=10, verbose=0, callbacks=[tb])
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

After several tries, I've added dropout layers in order to avoid overfitting, but with no luck. The following graph shows that the validation loss and training loss gets separate at one point.

What else could I do to optimize this network?

UPDATE:
based on the comments I got I've tweaked the code like so:

model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', kernel_regularizer=regularizers.l2(0.01),
                activity_regularizer=regularizers.l1(0.01), activation='relu',
                name='first_input'))  # added regularizers
model.add(Dense(8, activation='relu', name='first_hidden'))  # reduced to 8 neurons
model.add(Dropout(0.5, name='dropout_1'))
model.add(Dense(5, activation='relu', name='second_hidden'))
model.add(Dense(1, activation='sigmoid', name='output_layer'))

Here are the graphs for 500 epochs