问:
Firemonkey app: monospace font in TMemo?
Is it possible to set/use a Monospace font in TMemo in a Firemonkey (developed with Delphi 10.2 Tokyo) application.

We tried:

```<code>TextSettings.Font.Family := 'Courier New';
TextSettings.Font.Family := 'Courier';
TextSettings.Font.Family := 'Monospace';
</code>```

But when we run the app in Android the text font is not monospace.

答:
First, don't do any application for android using Delphi Tokyo, it's not work yet and you app will be very very slow! you must wait an update.

This is all the font available on android :

```<code>// +---------------------------------------------------------------+
// ¦    ¦ FONT FAMILY                ¦ TTF FILE                    ¦
// ¦----+----------------------------+-----------------------------¦
// ¦  1 ¦ casual                     ¦ ComingSoon.ttf              ¦
// ¦  2 ¦ cursive                    ¦ DancingScript-Regular.ttf   ¦
// ¦  3 ¦ monospace                  ¦ DroidSansMono.ttf           ¦
// ¦  4 ¦ sans-serif                 ¦ Roboto-Regular.ttf          ¦ Roboto-Regular.ttf / Roboto-Bold.ttf / Roboto-BoldItalic.ttf / Roboto-Italic.ttf
// ¦  5 ¦ sans-serif-black           ¦ Roboto-Black.ttf            ¦ Roboto-Black.ttf / Roboto-BlackItalic.ttf
// ¦  6 ¦ sans-serif-condensed       ¦ RobotoCondensed-Regular.ttf ¦ RobotoCondensed-Regular.ttf / RobotoCondensed-Bold.ttf / RobotoCondensed-BoldItalic.ttf / RobotoCondensed-Italic.ttf
// ¦  7 ¦ sans-serif-condensed-light ¦ RobotoCondensed-Light.ttf   ¦ RobotoCondensed-Light.ttf /  RobotoCondensed-LightItalic.ttf
// ¦  8 ¦ sans-serif-light           ¦ Roboto-Light.ttf            ¦ Roboto-Light.ttf / Roboto-LightItalic.ttf
// ¦  9 ¦ sans-serif-medium          ¦ Roboto-Medium.ttf           ¦ Roboto-Medium.ttf / Roboto-MediumItalic.ttf
// ¦ 10 ¦ sans-serif-smallcaps       ¦ CarroisGothicSC-Regular.ttf ¦
// ¦ 11 ¦ sans-serif-thin            ¦ Roboto-Thin.ttf             ¦ Roboto-Thin.ttf / Roboto-ThinItalic.ttf
// ¦ 12 ¦ serif                      ¦ NotoSerif-Regular.ttf       ¦
// ¦ 13 ¦ serif-monospace            ¦ CutiveMono.ttf              ¦
// +---------------------------------------------------------------+
</code>```

so try instead serif-monospace

Body:
Is it possible to set/use a Monospace font in TMemo in a Firemonkey (developed with Delphi 10.2 Tokyo) application.

We tried:

TextSettings.Font.Family := 'Courier New';
TextSettings.Font.Family := 'Courier';
TextSettings.Font.Family := 'Monospace';

But when we run the app in Android the text font is not monospace.

Body:
First, don't do any application for android using Delphi Tokyo, it's not work yet and you app will be very very slow! you must wait an update.

This is all the font available on android :

// +---------------------------------------------------------------+
// ¦    ¦ FONT FAMILY                ¦ TTF FILE                    ¦
// ¦----+----------------------------+-----------------------------¦
// ¦  1 ¦ casual                     ¦ ComingSoon.ttf              ¦
// ¦  2 ¦ cursive                    ¦ DancingScript-Regular.ttf   ¦
// ¦  3 ¦ monospace                  ¦ DroidSansMono.ttf           ¦
// ¦  4 ¦ sans-serif                 ¦ Roboto-Regular.ttf          ¦ Roboto-Regular.ttf / Roboto-Bold.ttf / Roboto-BoldItalic.ttf / Roboto-Italic.ttf
// ¦  5 ¦ sans-serif-black           ¦ Roboto-Black.ttf            ¦ Roboto-Black.ttf / Roboto-BlackItalic.ttf
// ¦  6 ¦ sans-serif-condensed       ¦ RobotoCondensed-Regular.ttf ¦ RobotoCondensed-Regular.ttf / RobotoCondensed-Bold.ttf / RobotoCondensed-BoldItalic.ttf / RobotoCondensed-Italic.ttf
// ¦  7 ¦ sans-serif-condensed-light ¦ RobotoCondensed-Light.ttf   ¦ RobotoCondensed-Light.ttf /  RobotoCondensed-LightItalic.ttf
// ¦  8 ¦ sans-serif-light           ¦ Roboto-Light.ttf            ¦ Roboto-Light.ttf / Roboto-LightItalic.ttf
// ¦  9 ¦ sans-serif-medium          ¦ Roboto-Medium.ttf           ¦ Roboto-Medium.ttf / Roboto-MediumItalic.ttf
// ¦ 10 ¦ sans-serif-smallcaps       ¦ CarroisGothicSC-Regular.ttf ¦
// ¦ 11 ¦ sans-serif-thin            ¦ Roboto-Thin.ttf             ¦ Roboto-Thin.ttf / Roboto-ThinItalic.ttf
// ¦ 12 ¦ serif                      ¦ NotoSerif-Regular.ttf       ¦
// ¦ 13 ¦ serif-monospace            ¦ CutiveMono.ttf              ¦
// +---------------------------------------------------------------+

so try instead serif-monospace


来源: stackexchange

问:
Handle spring security authentication exceptions with @ExceptionHandler
I'm using Spring MVC's @ControllerAdvice and @ExceptionHandler to handle all the exception of a REST Api. It works fine for exceptions thrown by web mvc controllers but it does not work for exceptions thrown by spring security custom filters because they run before the controller methods are invoked.

I have a custom spring security filter that does a token based auth:

```<code>public class AegisAuthenticationFilter extends GenericFilterBean {

...

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        try {

            ...
        } catch(AuthenticationException authenticationException) {

            SecurityContextHolder.clearContext();
            authenticationEntryPoint.commence(request, response, authenticationException);

        }

    }

}
</code>```

With this custom entry point:

```<code>@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
    }

}
</code>```

And with this class to handle exceptions globally:

```<code>@ControllerAdvice
public class RestEntityResponseExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler({ InvalidTokenException.class, AuthenticationException.class })
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public RestError handleAuthenticationException(Exception ex) {

        int errorCode = AegisErrorCode.GenericAuthenticationError;
        if(ex instanceof AegisException) {
            errorCode = ((AegisException)ex).getCode();
        }

        RestError re = new RestError(
            HttpStatus.UNAUTHORIZED,
            errorCode,
            "...",
            ex.getMessage());

        return re;
    }
}
</code>```

What I need to do is to return a detailed JSON body even for spring security  AuthenticationException. Is there a way make spring security AuthenticationEntryPoint and spring mvc @ExceptionHandler work together?

I'm using spring security 3.1.4 and spring mvc 3.2.4.

答:
In case of Spring Boot and @EnableResourceServer, it is relatively easy and convenient to extend ResourceServerConfigurerAdapter instead of WebSecurityConfigurerAdapter in the Java configuration and register a custom AuthenticationEntryPoint by overriding configure(ResourceServerSecurityConfigurer resources) and using resources.authenticationEntryPoint(customAuthEntryPoint()) inside the method.

Something like this:

```<code>@Configuration
@EnableResourceServer
public class CommonSecurityConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(customAuthEntryPoint());
    }

    @Bean
    public AuthenticationEntryPoint customAuthEntryPoint(){
        return new AuthFailureHandler();
    }
}
</code>```

There's also a nice OAuth2AuthenticationEntryPoint that can be extended (since it's not final) and partially re-used while implementing a custom AuthenticationEntryPoint. In particular, it adds "WWW-Authenticate" headers with error-related details.

Hope this will help someone.

ContentLicense: CC BY-SA 3.0

Body:
I'm using Spring MVC's @ControllerAdvice and @ExceptionHandler to handle all the exception of a REST Api. It works fine for exceptions thrown by web mvc controllers but it does not work for exceptions thrown by spring security custom filters because they run before the controller methods are invoked.

I have a custom spring security filter that does a token based auth:

public class AegisAuthenticationFilter extends GenericFilterBean {

...

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        try {

            ...
        } catch(AuthenticationException authenticationException) {

            SecurityContextHolder.clearContext();
            authenticationEntryPoint.commence(request, response, authenticationException);

        }

    }

}

With this custom entry point:

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
    }

}

And with this class to handle exceptions globally:

@ControllerAdvice
public class RestEntityResponseExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler({ InvalidTokenException.class, AuthenticationException.class })
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public RestError handleAuthenticationException(Exception ex) {

        int errorCode = AegisErrorCode.GenericAuthenticationError;
        if(ex instanceof AegisException) {
            errorCode = ((AegisException)ex).getCode();
        }

        RestError re = new RestError(
            HttpStatus.UNAUTHORIZED,
            errorCode,
            "...",
            ex.getMessage());

        return re;
    }
}

What I need to do is to return a detailed JSON body even for spring security  AuthenticationException. Is there a way make spring security AuthenticationEntryPoint and spring mvc @ExceptionHandler work together?

I'm using spring security 3.1.4 and spring mvc 3.2.4.

Body:
In case of Spring Boot and @EnableResourceServer, it is relatively easy and convenient to extend ResourceServerConfigurerAdapter instead of WebSecurityConfigurerAdapter in the Java configuration and register a custom AuthenticationEntryPoint by overriding configure(ResourceServerSecurityConfigurer resources) and using resources.authenticationEntryPoint(customAuthEntryPoint()) inside the method.

Something like this:

@Configuration
@EnableResourceServer
public class CommonSecurityConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(customAuthEntryPoint());
    }

    @Bean
    public AuthenticationEntryPoint customAuthEntryPoint(){
        return new AuthFailureHandler();
    }
}

There's also a nice OAuth2AuthenticationEntryPoint that can be extended (since it's not final) and partially re-used while implementing a custom AuthenticationEntryPoint. In particular, it adds "WWW-Authenticate" headers with error-related details.

Hope this will help someone.


问:
Get the id from a Img without the ID
i'm creating  a simple bootstrap gallery thumbnail with images that are being called from database. I succeed in calling all the info, but now i'm struggling with getting the id of each image. This is my code:

```<code> <div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">
  <div class="caption">
    <h3><?php echo $row['ID_Category']?></h3>
    <p><?php echo $row['Categories'] ?></p>
    <p><a href="#" onclick="return getID(this);" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
  </div>
</div>
</code>```

And this is my function in javascript:

```<code>function getID(e)
{
    var x = e.src;
    alert(x);
}
</code>```

But it is not working, how do I get the id of each image if is being called from a database?

答:
you can use Attribute tag in a tag and add onclick function to get your id value . i set category-id Attribute and in javascript code use this tag to get value

```<code><div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">
  <div class="caption">
    <h3><?php echo $row['ID_Category']?></h3>
    <p><?php echo $row['Categories'] ?></p>
   <p><a href="#" onclick="return getID(this);" category-id="<?php echo $row['ID_Category']?>" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
  </div>
</div>
</code>```

then this is script function

```<code><script>
function getID(obj)
{
    alert(obj.getAttribute("category-id"));
}
</script>
</code>```

or add onclick function and send id in this function

```<code><div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">
  <div class="caption">
    <h3><?php echo $row['ID_Category']?></h3>
    <p><?php echo $row['Categories'] ?></p>
   <p><a href="#" onclick="return getID('<?php echo $row['ID_Category']?>');"  class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
  </div>
</div>
</code>```

this is script

```<code><script>
function getID(id)
{
    alert(id);
}
</script>
</code>```

both will work.

Title: Get the id from a Img without the ID

Body:
i'm creating  a simple bootstrap gallery thumbnail with images that are being called from database. I succeed in calling all the info, but now i'm struggling with getting the id of each image. This is my code:

  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">

<?php echo $row['ID_Category']?>

<?php echo $row['Categories'] ?>

Button Button

And this is my function in javascript:

function getID(e)
{
    var x = e.src;
    alert(x);
}

But it is not working, how do I get the id of each image if is being called from a database?

Body:
you can use Attribute tag in a tag and add onclick function to get your id value . i set category-id Attribute and in javascript code use this tag to get value

<div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">
  <div class="caption">
    <h3><?php echo $row['ID_Category']?></h3>
    <p><?php echo $row['Categories'] ?></p>
   <p><a href="#" onclick="return getID(this);" category-id="<?php echo $row['ID_Category']?>" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
  </div>
</div>

then this is script function

<script>
function getID(obj)
{
    alert(obj.getAttribute("category-id"));
}
</script>

or add onclick function and send id in this function

<div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">
  <div class="caption">
    <h3><?php echo $row['ID_Category']?></h3>
    <p><?php echo $row['Categories'] ?></p>
   <p><a href="#" onclick="return getID('<?php echo $row['ID_Category']?>');"  class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
  </div>
</div>

this is script

<script>
function getID(id)
{
    alert(id);
}
</script>

both will work.


问:
How to make sure client doesn't sync when switching from dev to live server
When I change the url in the client from localhost to myLiveServer.com, how do I make sure that the localStorage doesn't get synced with the live data?
Do I need to configure that somewhere and extend the url like...
localhost:8080/gun/dev and myLiveServer.com/gun/live</p>

答:
Yes, it is probably wise to do something like this:

```<code>var gun = Gun('http://localhost:8080/gun').get('development');
</code>```

And then in production, do something like:

```<code>var gun = Gun('http://myserver.com/gun').get('uniqueAppName');
</code>```

Great question though, maybe this is something we can improve/make easier in the future.

Let me know if this works.

Body:
Yes, it is probably wise to do something like this:

var gun = Gun('http://localhost:8080/gun').get('development');

And then in production, do something like:

var gun = Gun('http://myserver.com/gun').get('uniqueAppName');

Great question though, maybe this is something we can improve/make easier in the future.

Let me know if this works.


问:
using onclick to display a confirmation message within php/html
So I have this line of code:

```<code>echo '<a href="scripts/Logout.php"><span>Logout</span></a></li>';
</code>```

This appears when a user is logged in, instead of displaying "Login", it says "logout".
It works fine, however, what I am trying to do is use onClick to display a popup message box asking the user "are you sure you wish to logout?"

Something like this:

```<code>echo '<a href="scripts/Logout.php" onClick="return confirm('are you sure?')"><span>Logout</span></a></li>';
</code>```

If for example i copy that second line of code on the home page within a content div, it works fine (minus the fact im no longer clicking on the "Logout" button).

**FYI - I have taken this out of the php script (deleted the echo infront of the line, still the same result).

Anyone able to point me in the right direction?

Many thanks.

答:
An alternative to @JamesHunt's comment.

Assuming you're using sessions, you could verify if the user is logged in with the session itself.

Inside php file:

```<code><?php
    if($_SESSION['userAuthed']):
?>
    <a href="scripts/Logout.php"><span>Logout</span></a></li>
<?php
    else:
?>
    <a href="scripts/Logout.php" onClick="return confirm('are you sure?')"><span>Logout</span></a></li>
<?php
    endif;
?>
</code>```

Body:
So I have this line of code:

echo 'Logout
';

This appears when a user is logged in, instead of displaying "Login", it says "logout".
It works fine, however, what I am trying to do is use onClick to display a popup message box asking the user "are you sure you wish to logout?"

Something like this:

echo 'Logout
';

If for example i copy that second line of code on the home page within a content div, it works fine (minus the fact im no longer clicking on the "Logout" button).

**FYI - I have taken this out of the php script (deleted the echo infront of the line, still the same result).

Anyone able to point me in the right direction?

Many thanks.

Body:
An alternative to @JamesHunt's comment.

Assuming you're using sessions, you could verify if the user is logged in with the session itself.

Inside php file:

<?php
    if($_SESSION['userAuthed']):
?>
    <a href="scripts/Logout.php"><span>Logout</span></a></li>
<?php
    else:
?>
    <a href="scripts/Logout.php" onClick="return confirm('are you sure?')"><span>Logout</span></a></li>
<?php
    endif;
?>


问:
oracle sql query error while comparing date columns
I have a following oracle sql query in which START_DATE is a number column and a_date is DATE type and the input value is also of type DATE. kindly let me know how to compare the date columns with the input date.</p>

```<code>select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE = to_date('11-DEC-10','YYYYMMDD')
 and a.START_DATE = b.a_date and b.code = 'JFK'
</code>```

答: select * from tbltlcrconfighistory where STARTDATE = TO_DATE('14-dec-2010','dd-mon-yyyy');</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a following oracle sql query in which START_DATE is a number column and a_date is DATE type and the input value is also of type DATE. kindly let me know how to compare the date columns with the input date.

select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE = to_date('11-DEC-10','YYYYMMDD')
 and a.START_DATE = b.a_date and b.code = 'JFK'


问:
Highcharts Zones not working with valid JSON
Trying to replicate this: http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/series/color-zones-dashstyle-dot

It works fine when I directly copy and paste, but when I'm using the getJSON function, the line will populate, but its not recognizing the dashed line for the zone.

```<code>[{"name":"Test","data":[29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],"zoneAxis":"x","zones":"[{value: 8}, {dashStyle: 'dot'}]"}]
</code>```

Seems to be in valid JSON format - so not sure what the issue is and I'm not getting any sort of errors.

答: "zones":"[{value: 8}, {dashStyle: 'dot'}]" - remove the quotes from the value. So try [{value: 8}, {dashStyle: 'dot'}]</p>

Body:
Trying to replicate this: http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/series/color-zones-dashstyle-dot

It works fine when I directly copy and paste, but when I'm using the getJSON function, the line will populate, but its not recognizing the dashed line for the zone.

[{"name":"Test","data":[29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],"zoneAxis":"x","zones":"[{value: 8}, {dashStyle: 'dot'}]"}]

Seems to be in valid JSON format - so not sure what the issue is and I'm not getting any sort of errors.


问:
Bash Regex Accepts [Number], but i want only Number accepted
I have some Problems and i dont know what causes them. In my Script (bash) i want to ask with "if" if my $1 is a number. Only 0-9 Digits and optinal "-".
When i make

```<code>`if [[ "$1" -eq "$1" ]]`
</code>```

or

```<code> if `([[ $1 =~ ^-?[0-9]+$ ]]`
</code>```

Both times i can make

```<code>`./myscript [number]`
</code>```

or

./myscript number*

and the number got accepted. But of course i dont want [number] to be a number as parameter. Only Numbers without any other symbols, brackets or other stuff

Can Someone tell me where is my Problem? I only want to understand why the bash acts like this. I dont want some complete code snipped that solve my Problems. Only some ideas was causes the Problem
Greetings

答:
I guess in current directory you have a file named number. Please see log below:

```<code>[arturcz@home xxx]$ ls -la
total 4
drwxr-xr-x  2 arturcz arturcz  60 Jun  5 16:27 .
drwxrwxrwt 16 root    root     580 Jun  5 16:27 ..
-rwxr-xr-x  1 arturcz arturcz  88 Jun  5 16:24 number.sh
[arturcz@home xxx]$ cat number.sh
#!/bin/bash
if [[ $1 =~ ^-?[0-9]+$ ]]; then
    echo Number
else
    echo Not number
fi
[arturcz@home xxx]$ ./number.sh 1
Number
[arturcz@home xxx]$ ./number.sh [1]
Not number
[arturcz@home xxx]$ ./number.sh 1*
Not number
[arturcz@home xxx]$ touch 1
[arturcz@home xxx]$ ./number.sh [1]
Number
[arturcz@home xxx]$ ./number.sh 1*
Number
[arturcz@home xxx]$
</code>```

If you want to avoid parameter to be interpreted and expanded by bash, put in in single or double quotation marks:

```<code>[arturcz@home xxx]$ ./number.sh '1*'
Not number
[arturcz@home xxx]$ ./number.sh '[1]'
Not number
</code>```

Body:
I have some Problems and i dont know what causes them. In my Script (bash) i want to ask with "if" if my $1 is a number. Only 0-9 Digits and optinal "-".
When i make

`if [[ "$1" -eq "$1" ]]`

or

 if `([[ $1 =~ ^-?[0-9]+$ ]]`

Both times i can make

`./myscript [number]`

or

./myscript number*

and the number got accepted. But of course i dont want [number] to be a number as parameter. Only Numbers without any other symbols, brackets or other stuff

Can Someone tell me where is my Problem? I only want to understand why the bash acts like this. I dont want some complete code snipped that solve my Problems. Only some ideas was causes the Problem
Greetings

Body:
I guess in current directory you have a file named number. Please see log below:

[arturcz@home xxx]$ ls -la
total 4
drwxr-xr-x  2 arturcz arturcz  60 Jun  5 16:27 .
drwxrwxrwt 16 root    root     580 Jun  5 16:27 ..
-rwxr-xr-x  1 arturcz arturcz  88 Jun  5 16:24 number.sh
[arturcz@home xxx]$ cat number.sh
#!/bin/bash
if [[ $1 =~ ^-?[0-9]+$ ]]; then
    echo Number
else
    echo Not number
fi
[arturcz@home xxx]$ ./number.sh 1
Number
[arturcz@home xxx]$ ./number.sh [1]
Not number
[arturcz@home xxx]$ ./number.sh 1*
Not number
[arturcz@home xxx]$ touch 1
[arturcz@home xxx]$ ./number.sh [1]
Number
[arturcz@home xxx]$ ./number.sh 1*
Number
[arturcz@home xxx]$

If you want to avoid parameter to be interpreted and expanded by bash, put in in single or double quotation marks:

[arturcz@home xxx]$ ./number.sh '1*'
Not number
[arturcz@home xxx]$ ./number.sh '[1]'
Not number


问:
EchoDot is unable to request my skill tough it works in web interface
I just tried to develop a skill for Alexa in C#. It just consits out of a simple intent with a slot for a name and says something like "Hi {name}" as response.

I created an AWS Lambda project in visual studio, referenced alexa skills for .Net core by Tim Heuer and implemented the intent:

```<code>var name = intentRequest.Intent.Slots["name"].Value;
var speech = new Alexa.NET.Response.SsmlOutputSpeech {Ssml = $"Hallo {name}. Schön dich zu sehen."};

response = ResponseBuilder.Tell(speech);
response.Response.ShouldEndSession = true;
</code>```

I published it into my AWS Lambdas via Visual Studio AWS Toolkit, added Alexa as a trigger and created the Alexa skill and referenced it to the lambdas arn.

I enabled the skill for my own echo dot device, I also can see it exists in my app. If I now ask the echo dot to launch the skill I just get an error saying "An error occurred during the response of the requested skill" (translated from German). But if I test the skill in the Alexa developer website on Amazon it all works fine. Same if I test it in visual studio itself.

Skills in general work on my echo dot (also the node js trivia game example). What might cause this problem? Is this an error in my lambda function?

答: I finally found out that the SsmlOutputSpeech was the problem. Seems like you have to fill in the string in Ssml syntax, even it wasn´t done like this in the related GitHub repository. I just moved to PlainTextOutputSpeech as this is enough for my cases.</p>

Body:
I just tried to develop a skill for Alexa in C#. It just consits out of a simple intent with a slot for a name and says something like "Hi {name}" as response.

I created an AWS Lambda project in visual studio, referenced alexa skills for .Net core by Tim Heuer and implemented the intent:

var name = intentRequest.Intent.Slots["name"].Value;
var speech = new Alexa.NET.Response.SsmlOutputSpeech {Ssml = $"Hallo {name}. Schön dich zu sehen."};

response = ResponseBuilder.Tell(speech);
response.Response.ShouldEndSession = true;

I published it into my AWS Lambdas via Visual Studio AWS Toolkit, added Alexa as a trigger and created the Alexa skill and referenced it to the lambdas arn.

I enabled the skill for my own echo dot device, I also can see it exists in my app. If I now ask the echo dot to launch the skill I just get an error saying "An error occurred during the response of the requested skill" (translated from German). But if I test the skill in the Alexa developer website on Amazon it all works fine. Same if I test it in visual studio itself.

Skills in general work on my echo dot (also the node js trivia game example). What might cause this problem? Is this an error in my lambda function?


问:
Can you change the order events fire in Javascript for external libraries?
I am using a jquery plugin called: jQueryFontIconPicker. I am modifying this icon picker to also select image icons that the user can upload.

When the icon is chosen I use the .on('change') attached to the function that creates the jqfonticonpicker... the problem is that I am trying to manipulate the dom but cannot force my changes to take effect AFTER the plugins changes take effect.

Is there an elegant way to set sequencing?

```<code>var iconcats = { // these are just arrays listing the icons to use. they all work fine.
            'Library Icons': libicons,
            'My Icons': usericons
        };

        $('.iconpicker-input').fontIconPicker({
            source:    iconcats,
            emptyIcon: false,
            hasSearch: true,
            theme: 'fip-darkgrey'
        }).on('change', function(){
  // Do DOM changes here, replace icons with images.

            var target = event.target;
            var iconname;

            if($(target).hasClass('custom-icon-image'))
            {
                iconname = $(target).attr('title');
                alert('check sequence');
                $(target).closest('.icons-selector .selected-icon i').html('<img class="selected-icon-image" src="/site_repo/' + siteID +'/icons/' + iconname + '.png" title="' + iconname + '" />');
                $(target).closest('.icons-selector .selector').html('<p>test</p>');
            }
        });

});
</code>```

Thank you in advance

答: I discovered that there is no control over the sequence of execution of events, it seems to be browser controlled, so I ended up just modifying the plugin code myself. Not ideal, but solves the problem.  </p>

Body:
I am using a jquery plugin called: jQueryFontIconPicker. I am modifying this icon picker to also select image icons that the user can upload.

When the icon is chosen I use the .on('change') attached to the function that creates the jqfonticonpicker... the problem is that I am trying to manipulate the dom but cannot force my changes to take effect AFTER the plugins changes take effect.

Is there an elegant way to set sequencing?

var iconcats = { // these are just arrays listing the icons to use. they all work fine.
            'Library Icons': libicons,
            'My Icons': usericons
        };

        $('.iconpicker-input').fontIconPicker({
            source:    iconcats,
            emptyIcon: false,
            hasSearch: true,
            theme: 'fip-darkgrey'
        }).on('change', function(){
  // Do DOM changes here, replace icons with images.

            var target = event.target;
            var iconname;

            if($(target).hasClass('custom-icon-image'))
            {
                iconname = $(target).attr('title');
                alert('check sequence');
                $(target).closest('.icons-selector .selected-icon i').html('');
                $(target).closest('.icons-selector .selector').html('
test
');
            }
        });

});

Thank you in advance


问:
Checkbox create multiple AJAX request
On my way to solve an issue about an xhr 200 status (So the request is "ok") who's in fact isn't so ok (nothing land in the db), I've found out something weird.

On chrome, I hit F12, then go to network to see all the activities and complete the form randomly. In this form there's some checkboxes, so I've checked them all to see if the values are correctly transfered.. And surprise !

The network activities showed up 6 times the same php files who's used for the request. In the 1st activity of this php file, I've been able to see this (1 for checked, 0 for unchecked) :

```<code>windows:1
shutter:0
garage:0
portal:0
door:0
blind:0
</code>```

In the 2nd call :

```<code>windows:1
shutter:1
garage:0
portal:0
door:0
blind:0
</code>```

Ect... To get this final data when the file is called for the 6th time, with only one click :

```<code>windows:1
shutter:1
garage:1
portal:1
door:1
blind:1
</code>```

This last transfert is the one who should be done in the first place, without going through a loop.

I wonder what's going on here. If you want some code, feel free to ask. To be honest I've never seen this before.

EDIT :
Here's the full script, maybe the $(':checkbox:checked').each(function(i) should be closed before the AJAX request ?

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

    // Only if the form is submitted
    $('#estimate').on('click', function(e) {
      // To prevent the page to be reloaded on submit
      e.preventDefault();

      // Declare all variable
      var civil = $('input[name="gender"]:checked').val();
      var lastname = $('input[name="lastname"]').val();
      var firstname = $('input[name="firstname"]').val();
      var address = $('input[name="address"]').val();
      var zipcode = $('input[name="zipcode"]').val();
      var city = $('input[name="city"]').val();
      var tel = $('input[name="tel"]').val();
      var email = $('input[name="email"]').val();
      var situation = $('input[name="situation"]:checked').val();
      var place = $('input[name="place"]:checked').val();
      var message = $('#message').val();
      var selectedProject = [];

      // Set 0 to get a false boolean
      var windows = 0;
      var shutter = 0;
      var garage = 0;
      var portal = 0;
      var door = 0;
      var blind = 0;

      // At least one checkbox need to be checked
      if ( $('div.checkbox-group :checkbox:checked').length > 0 ) {
        // If the last message was displayed for an error
        $('.select').fadeOut('slow')

        // Get the value of the checked box
        $(':checkbox:checked').each(function(i) {
          selectedProject[i] = $(this).val();

          // Set 1 to get a true boolean for the checked box
          if ( selectedProject[i] == 'windows') {
            windows = 1
          }
          if ( selectedProject[i] == 'shutter') {
            shutter = 1
          }
          if ( selectedProject[i] == 'garage') {
            garage = 1
          }
          if ( selectedProject[i] == 'portal') {
            portal = 1
          }
          if ( selectedProject[i] == 'door') {
            door = 1
          }
          if ( selectedProject[i] == 'blind') {
            blind = 1
          }

          // Declare the data for the AJAX request
          data = {
            civil : civil,
            lastname : lastname,
            firstname : firstname,
            address : address,
            zipcode : zipcode,
            city : city,
            tel : tel,
            email : email,
            situation : situation,
            place : place,
            windows : windows,
            shutter : shutter,
            garage : garage,
            portal : portal,
            door : door,
            blind : blind,
            message : message,
          }

          // Beginning of the AJAX request
          $.ajax({
            url : "transfert/db_transfert.php",
            method :"POST",
            data : data,
            success : function(res){
              if ( res == "done" ) {
                $("#res").hide().html("<p style=\"color:green;\">Votre demande à était envoyée</p>").fadeIn('slow');
              } else if ( res == "missing" ) {
                $("#res").hide().html("<p style=\"color:red;\">Il manque des renseignements</p>").fadeIn('slow');
              } else {
                $("#res").hide().html("<p style=\"color:red;\">Une erreur s'est produite, recommencez ultérieurement</p>").fadeIn('slow');
              }
            }
          })
        });

      } else {
        $('.select').hide().html('<p style="color:red;">Veuillez choisir votre projet avant de continuer.</p>').fadeIn('slow');
      }

    })

  })
</code>```

答:
maybe the $(':checkbox:checked').each(function(i) should be closed before the AJAX request ?

That is definitely the problem. It starts a separate AJAX request for every checkbox. Just close the .each() before the AJAX and you should be good.

Title: Checkbox create multiple AJAX request

Body:
On my way to solve an issue about an xhr 200 status (So the request is "ok") who's in fact isn't so ok (nothing land in the db), I've found out something weird.

On chrome, I hit F12, then go to network to see all the activities and complete the form randomly. In this form there's some checkboxes, so I've checked them all to see if the values are correctly transfered.. And surprise !

The network activities showed up 6 times the same php files who's used for the request. In the 1st activity of this php file, I've been able to see this (1 for checked, 0 for unchecked) :

windows:1
shutter:0
garage:0
portal:0
door:0
blind:0

In the 2nd call :

windows:1
shutter:1
garage:0
portal:0
door:0
blind:0

Ect... To get this final data when the file is called for the 6th time, with only one click :

windows:1
shutter:1
garage:1
portal:1
door:1
blind:1

This last transfert is the one who should be done in the first place, without going through a loop.

I wonder what's going on here. If you want some code, feel free to ask. To be honest I've never seen this before.

EDIT :
Here's the full script, maybe the $(':checkbox:checked').each(function(i) should be closed before the AJAX request ?

  $(function() {

    // Only if the form is submitted
    $('#estimate').on('click', function(e) {
      // To prevent the page to be reloaded on submit
      e.preventDefault();

      // Declare all variable
      var civil = $('input[name="gender"]:checked').val();
      var lastname = $('input[name="lastname"]').val();
      var firstname = $('input[name="firstname"]').val();
      var address = $('input[name="address"]').val();
      var zipcode = $('input[name="zipcode"]').val();
      var city = $('input[name="city"]').val();
      var tel = $('input[name="tel"]').val();
      var email = $('input[name="email"]').val();
      var situation = $('input[name="situation"]:checked').val();
      var place = $('input[name="place"]:checked').val();
      var message = $('#message').val();
      var selectedProject = [];

      // Set 0 to get a false boolean
      var windows = 0;
      var shutter = 0;
      var garage = 0;
      var portal = 0;
      var door = 0;
      var blind = 0;

      // At least one checkbox need to be checked
      if ( $('div.checkbox-group :checkbox:checked').length > 0 ) {
        // If the last message was displayed for an error
        $('.select').fadeOut('slow')

        // Get the value of the checked box
        $(':checkbox:checked').each(function(i) {
          selectedProject[i] = $(this).val();

          // Set 1 to get a true boolean for the checked box
          if ( selectedProject[i] == 'windows') {
            windows = 1
          }
          if ( selectedProject[i] == 'shutter') {
            shutter = 1
          }
          if ( selectedProject[i] == 'garage') {
            garage = 1
          }
          if ( selectedProject[i] == 'portal') {
            portal = 1
          }
          if ( selectedProject[i] == 'door') {
            door = 1
          }
          if ( selectedProject[i] == 'blind') {
            blind = 1
          }

          // Declare the data for the AJAX request
          data = {
            civil : civil,
            lastname : lastname,
            firstname : firstname,
            address : address,
            zipcode : zipcode,
            city : city,
            tel : tel,
            email : email,
            situation : situation,
            place : place,
            windows : windows,
            shutter : shutter,
            garage : garage,
            portal : portal,
            door : door,
            blind : blind,
            message : message,
          }

          // Beginning of the AJAX request
          $.ajax({
            url : "transfert/db_transfert.php",
            method :"POST",
            data : data,
            success : function(res){
              if ( res == "done" ) {
                $("#res").hide().html("
Votre demande à était envoyée
").fadeIn('slow');
              } else if ( res == "missing" ) {
                $("#res").hide().html("
Il manque des renseignements
").fadeIn('slow');
              } else {
                $("#res").hide().html("
Une erreur s'est produite, recommencez ultérieurement
").fadeIn('slow');
              }
            }
          })
        });

      } else {
        $('.select').hide().html('
Veuillez choisir votre projet avant de continuer.
').fadeIn('slow');
      }

    })

  })


问:
WorkFront / AtTask API $$TODAYe+6m flaw?
The workfront API isn't returning the same results as our web report:

On our web front-end on workfront one of the reports has a date range from $$TODAYbw to $$TODAYe+6m and it returned about ~500 rows.

I tried the same query on the API like so (formatted for easier reading)

```<code>/v7.0/RSALLO/search
?fields=DE:project:Probability,allocationDate,scheduledHours,project:name,project:status,roleID,project:status,role:name
&allocationDate_Mod=between
&allocationDate=$$TODAYbw
&allocationDate_Range=$$TODAYe+6m
&AND:0:project:status_Mod=notin
&AND:0:project:status=CPL
&AND:0:project:status=DED
&AND:0:project:status=REJ
&AND:0:project:status=UZF
&AND:0:project:status=IDA
&AND:0:roleID_Mod=in
&AND:0:roleID=55cb58b8001cc9bc1bd9767e080f6c10
&AND:0:roleID=55cb58b8001cc9bd9fc0f8b03a581493
&AND:0:roleID=55cb58b8001cc9bfaa01243cd6024b6d
&AND:0:roleID=55cb58b8001cc9c0afa399dece405efd
&$$LIMIT=1000
</code>```

which returned barely any results. Notice the &allocationDate_Range=$$TODAYe+6m line. If I change it to read =$$TODAY+6m without the end of day modifier the API returns ~500 rows.

I went through every filter criteria and it's only the allocationDate range that is going wrong. I found this resource for the date modifiers and in it there is no e+6m example, yet it works on our web front-end report.

Is the API flawed or is the web report doing something extra in the background?

答:
I don't have an exact solution for your problem, but I can confirm that the API does have some difficulty parsing wildcards like you're trying to use and they don't always come up the way we expect. Furthermore, the API doesn't parse things the same way as text mode reporting, so a query that looks great in the latter might return something different in the former.

If I may propose a different solution, since you're already coding this up outside of Workfront then I suggest you simply perform the date calculations on your own and pass explicit datetime objects to Workfront instead of allowing it to use its own logic. I know this doesn't answer the question of "what is a query that will return exactly what I want" but it should give you the correct end result.

For what it's worth, I spent about 15 minutes trying to get an example working on my end and I gave up after it kept returning values which should have been outside of my own date range.

Body:
The workfront API isn't returning the same results as our web report:

On our web front-end on workfront one of the reports has a date range from $$TODAYbw to $$TODAYe+6m and it returned about ~500 rows.

I tried the same query on the API like so (formatted for easier reading)

/v7.0/RSALLO/search
?fields=DE:project:Probability,allocationDate,scheduledHours,project:name,project:status,roleID,project:status,role:name
&allocationDate_Mod=between
&allocationDate=$$TODAYbw
&allocationDate_Range=$$TODAYe+6m
&AND:0:project:status_Mod=notin
&AND:0:project:status=CPL
&AND:0:project:status=DED
&AND:0:project:status=REJ
&AND:0:project:status=UZF
&AND:0:project:status=IDA
&AND:0:roleID_Mod=in
&AND:0:roleID=55cb58b8001cc9bc1bd9767e080f6c10
&AND:0:roleID=55cb58b8001cc9bd9fc0f8b03a581493
&AND:0:roleID=55cb58b8001cc9bfaa01243cd6024b6d
&AND:0:roleID=55cb58b8001cc9c0afa399dece405efd
&$$LIMIT=1000

which returned barely any results. Notice the &allocationDate_Range=$$TODAYe+6m line. If I change it to read =$$TODAY+6m without the end of day modifier the API returns ~500 rows.

I went through every filter criteria and it's only the allocationDate range that is going wrong. I found this resource for the date modifiers and in it there is no e+6m example, yet it works on our web front-end report.

Is the API flawed or is the web report doing something extra in the background?


问:
Remove padding in google chart?
I'm wondering why google charts add a blank padding when not specifying the top/right/left axises.

Select the image and you'll find a huge padding except the bottom which is already filled & that's why, how to remove that?

Specifically, Talking about the right and left paddings.

Thank you.

答:
When using the Google Chart API you can eliminate the padding. I made an example Here.

The relevant parameter is chma.

According to the documentation:

You can specify the size of the chart's margins, in pixels. Margins are calculated inward from the specified chart size (chs); increasing the margin size does not increase the total chart size, but rather shrinks the chart area, if necessary.

You can try these parameters online in the Chart Playground HERE.

HTH!

Edit: Warning from Google

Important: The Image Charts portion of Google Chart Tools has been officially deprecated as of April 20, 2012. It will continue to work as per our deprecation policy.

Title: Remove padding in google chart?


问:
Redirect_URI error when using GoogleAuth.grantOfflineAccess to authenticate on server
I'm trying to use the authorization flow outlined at https://developers.google.com/identity/sign-in/web/server-side-flow.
I've created the credentials as indicated... with no Authorized redirect URIs specified as the doc indicates: "The Authorized redirect URI field does not require a value. Redirect URIs are not used with JavaScript APIs."

The code initiating the authorization is:
Client button and callback:

```<code><script>
$('#signinButton').click(function() {

    var auth2 = gapi.auth2.getAuthInstance();
    auth2.grantOfflineAccess().then(signInCallback);

});
function signInCallback(authResult) {

    console.log('sending to server');

    if (authResult['code']) {

        // Send the code to the server
        $.ajax({
          type: 'POST',
          url: 'CheckAuth',

          headers: {
            'X-Requested-With': 'XMLHttpRequest'
          },
          contentType: 'application/octet-stream; charset=utf-8',
          success: function(result) {
            // Handle or verify the server response.
          },
          processData: false,
          data: authResult['code']
        });
      } else {
        // There was an error.
      }
}
</script>
</code>```

Server side (CheckAuth method to create credentials from auth code, which it receives correctly via the javascript callback):

```<code>private Credential authorize() throws Exception {
    // load client secrets
    InputStream is = new FileInputStream(clientSecretsPath_);
    InputStreamReader isr = new InputStreamReader(is);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, isr);

    String redirect_URI = "";
    GoogleTokenResponse tokenResponse =
                  new GoogleAuthorizationCodeTokenRequest(
                          httpTransport, JSON_FACTORY,
                      "https://www.googleapis.com/oauth2/v4/token",
                      clientSecrets.getDetails().getClientId(),
                      clientSecrets.getDetails().getClientSecret(),
                      token_,
                      redirect_URI)
                      .execute();

        String accessToken = tokenResponse.getAccessToken();

        // Use access token to call API
        GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
        return credential;

    }
</code>```

The flow works correctly, up until the point my server attempts to exchange the authorization code for the token response (GoogleAuthorizationCodeTokenRequest.execute() )... the auth server returns:

```<code>400 Bad Request
{
  "error" : "invalid_request",
  "error_description" : "Missing parameter: redirect_uri"
}
</code>```

Given the error, I looked in debug at the auth instance in javascript and noted what it indicated was the redirect_uri. I then updated my google credentials and specified that URI in the Authorized redirect URIs (it's the URL that accessed the javascript, as the auth server correctly returns to the specified javascript callback). With the updated credentials and the URI specified in the instantiation of GoogleAuthorizationCodeTokenRequest (String redirect_URI = "http://example.com:8080/JavascriptLocation";), the error then becomes:

```<code>400 Bad Request
{
  "error" : "redirect_uri_mismatch",
  "error_description" : "Bad Request"
}
</code>```

I've tracked all the way through to the actual HttpRequest to the auth server (www.googleapis.com/oauth2/v4/token) and cannot tell what redirect_uri it is looking for.

Does anyone know what the value of redirect_uri should be in this case (when using grantOfflineAccess())? I'm happy to post more of the code, if that is at all helpful... just didn't want to flood the page. Thanks.

答:
Found a reference to "postmessage" right after posting the question... using it as the redirect_URI on the server side seems to generate a successful response from the auth server. So... setting redirect_URI="postmessage" in the code below appears to work in this situation.</p>

```<code>GoogleTokenResponse tokenResponse =
                  new GoogleAuthorizationCodeTokenRequest(
                          httpTransport, JSON_FACTORY,
                      "https://www.googleapis.com/oauth2/v4/token",
                      clientSecrets.getDetails().getClientId(),
                      clientSecrets.getDetails().getClientSecret(),
                      token_,
                      redirect_URI)
                      .execute();
</code>```

Body:
I'm trying to use the authorization flow outlined at https://developers.google.com/identity/sign-in/web/server-side-flow.
I've created the credentials as indicated... with no Authorized redirect URIs specified as the doc indicates: "The Authorized redirect URI field does not require a value. Redirect URIs are not used with JavaScript APIs."

The code initiating the authorization is:
Client button and callback:

Server side (CheckAuth method to create credentials from auth code, which it receives correctly via the javascript callback):

private Credential authorize() throws Exception {
    // load client secrets
    InputStream is = new FileInputStream(clientSecretsPath_);
    InputStreamReader isr = new InputStreamReader(is);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, isr);

    String redirect_URI = "";
    GoogleTokenResponse tokenResponse =
                  new GoogleAuthorizationCodeTokenRequest(
                          httpTransport, JSON_FACTORY,
                      "https://www.googleapis.com/oauth2/v4/token",
                      clientSecrets.getDetails().getClientId(),
                      clientSecrets.getDetails().getClientSecret(),
                      token_,
                      redirect_URI)
                      .execute();

        String accessToken = tokenResponse.getAccessToken();

        // Use access token to call API
        GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
        return credential;

    }

The flow works correctly, up until the point my server attempts to exchange the authorization code for the token response (GoogleAuthorizationCodeTokenRequest.execute() )... the auth server returns:

400 Bad Request
{
  "error" : "invalid_request",
  "error_description" : "Missing parameter: redirect_uri"
}

Given the error, I looked in debug at the auth instance in javascript and noted what it indicated was the redirect_uri. I then updated my google credentials and specified that URI in the Authorized redirect URIs (it's the URL that accessed the javascript, as the auth server correctly returns to the specified javascript callback). With the updated credentials and the URI specified in the instantiation of GoogleAuthorizationCodeTokenRequest (String redirect_URI = "http://example.com:8080/JavascriptLocation";), the error then becomes:

400 Bad Request
{
  "error" : "redirect_uri_mismatch",
  "error_description" : "Bad Request"
}

I've tracked all the way through to the actual HttpRequest to the auth server (www.googleapis.com/oauth2/v4/token) and cannot tell what redirect_uri it is looking for.

Does anyone know what the value of redirect_uri should be in this case (when using grantOfflineAccess())? I'm happy to post more of the code, if that is at all helpful... just didn't want to flood the page. Thanks.

Body:
Found a reference to "postmessage" right after posting the question... using it as the redirect_URI on the server side seems to generate a successful response from the auth server. So... setting redirect_URI="postmessage" in the code below appears to work in this situation.

GoogleTokenResponse tokenResponse =
                  new GoogleAuthorizationCodeTokenRequest(
                          httpTransport, JSON_FACTORY,
                      "https://www.googleapis.com/oauth2/v4/token",
                      clientSecrets.getDetails().getClientId(),
                      clientSecrets.getDetails().getClientSecret(),
                      token_,
                      redirect_URI)
                      .execute();


问:
ImportError: No module named 'ldap' Python 3.5
I'm running Python 3.5 (on Windows) and I have installed python-ldap from https://pypi.python.org/pypi/python-ldap/

I also tried using ldap3 but I keep getting an error saying

"ImportError: No module named 'ldap'

I looked around and saw some people saying there's no python-ldap for 3.5 so I installed 2.6 still getting the same error.

Is there a way to import ldap and make it work for Python 3.5?

答: It's extremely complicated to make things from 2.X to work in 3.X. Have you tried using it in a separate, 2.X only script and using it from there? It's not so unusual to combine python 2.X with 3.X in that manner or so I've heard.</p>


问:
Elastic Search : Does it maintain inverted and non inverted indexes both internally?
I was reading about elastic search. It looks like it maintain inverted index on all terms in all the documents. But does it also maintain normal indexing, i.e. from document id to document? Also, as it maintains lot of indexing on all fields and for all terms, so does it take too much memory?
Eg. when compared to DynamoDb, where say, I made indexes on only 2 fields and here it form indexes on each and every term, which would be more memory efficient?</p>

答:
"too much" is a very opinionated question and will totally depend on your use-case. To make an informed decision, you'll need to dive into a few topics (Elasticsearch is really powerful, but you need to know what you are doing):

Text vs keyword

Meta-fields especially _all and _source

Every  _uid field, which contains the _id, is indexed.

So it will really depend on your data, your mapping, and what you want to achieve with your data. I'm afraid you will need to build a quick prototype with exactly your data and use-case to find out.


问:
Empty array in multi class project returning null after receiving data when called upon
I'm having an issue that has been giving me a an error saying java.lang.StackOverflowError: null. My program is sort of like a lottery, a random number is chosen, and based off the number, your item is chosen from a array. Now this works all handy and dandy, but when i try to insert the item received into an inventory. I get that error. Im pretty sure i set up my class wrong but i don't know how to construct an array in a separate class that receives data from another class, and returns the data back to the same class. Enough chit chatting, heres what my code looks like so far. (please dont mind the extra variables as this is a cropped portion of my code)

```<code>public class inventory {
   private int inventorymain;
   public String[] inventorymain()  {
      String[] inventorymain;
      return inventorymain();
   }
}

    import java.util.Scanner;
    import java.util.Random;

    public class glue {

       public static void main(String [] args) {
          inventory inv = new inventory();
          allskins a = new allskins();
          Scanner s = new Scanner(System.in);
          int selection = 0;
          int invcount = -1;
          Random rand = new Random();
          do {
             System.out.println(d.menue());
             selection = s.nextInt();
             if (selection == 1) {
                invcount++;
                int random = rand.nextInt(208);
                System.out.println("You opend a: ");
                System.out.println(a.allskins()[random]);
                System.out.println("Your item has been put in your inventory, select inventroy from the menue to view all items.");
                System.out.println("");
                inv.inventorymain()[invcount] = (a.allskins()[random]);
              }
          }while (selection != 6);
      }
}
</code>```

Thank you

答:
You're entering infinite recursive loop calling inventorymain()

```<code>public class inventory {

    private int inventorymain;

    public String[] inventorymain()  {
        String[] inventorymain;
        return inventorymain(); // recursive call here without escape condition
    }

}
</code>```

It's better to keep the method name and variable name different to avoid such cases.

Body:
I'm having an issue that has been giving me a an error saying java.lang.StackOverflowError: null. My program is sort of like a lottery, a random number is chosen, and based off the number, your item is chosen from a array. Now this works all handy and dandy, but when i try to insert the item received into an inventory. I get that error. Im pretty sure i set up my class wrong but i don't know how to construct an array in a separate class that receives data from another class, and returns the data back to the same class. Enough chit chatting, heres what my code looks like so far. (please dont mind the extra variables as this is a cropped portion of my code)

public class inventory {
   private int inventorymain;
   public String[] inventorymain()  {
      String[] inventorymain;
      return inventorymain();
   }
}

    import java.util.Scanner;
    import java.util.Random;

    public class glue {

       public static void main(String [] args) {
          inventory inv = new inventory();
          allskins a = new allskins();
          Scanner s = new Scanner(System.in);
          int selection = 0;
          int invcount = -1;
          Random rand = new Random();
          do {
             System.out.println(d.menue());
             selection = s.nextInt();
             if (selection == 1) {
                invcount++;
                int random = rand.nextInt(208);
                System.out.println("You opend a: ");
                System.out.println(a.allskins()[random]);
                System.out.println("Your item has been put in your inventory, select inventroy from the menue to view all items.");
                System.out.println("");
                inv.inventorymain()[invcount] = (a.allskins()[random]);
              }
          }while (selection != 6);
      }
}

Thank you

Body:
You're entering infinite recursive loop calling inventorymain()

public class inventory {

    private int inventorymain;

    public String[] inventorymain()  {
        String[] inventorymain;
        return inventorymain(); // recursive call here without escape condition
    }

}

It's better to keep the method name and variable name different to avoid such cases.


问:
Ionic framework PdfViewer
I want to develop pdf ebook application for mobile. Is there pdf viewer component for ionic framework. I fond mozilla pdf.js . I need ionic project example. </p>

答:
You could use Cordova - InAppBrowser since it will be able to display pdf just open specify the static or dynamic path . you do need to add other modules as this an be also used to open web pages also you could use

https://github.com/initialxy/cordova-plugin-themeablebrowser

to theme the pdf openings for  custom loading to hide url etc fields

these two approaches can be used to open a simple pdf  document for reading purposes.

but for more specific options you should go with

https://github.com/akrennmair/ng-pdfviewer

which requires pdf.js and pdf.compat.js.

add it as a dependency in your app.

```<code>var app = angular.module('testApp', [ 'ngPDFViewer' ]);
</code>```

basic controller syntax useage :

```<code>app.controller('TestCtrl', [ '$scope', 'PDFViewerService', function($scope,
pdf) {
    $scope.viewer = pdf.Instance("viewer");

    $scope.nextPage = function() {
        $scope.viewer.nextPage();
    };

    $scope.prevPage = function() {
        $scope.viewer.prevPage();
    };

    $scope.pageLoaded = function(curPage, totalPages) {
        $scope.currentPage = curPage;
        $scope.totalPages = totalPages;
    };
}]);
</code>```

Title: Ionic framework PdfViewer

Body:
You could use Cordova - InAppBrowser since it will be able to display pdf just open specify the static or dynamic path . you do need to add other modules as this an be also used to open web pages also you could use

https://github.com/initialxy/cordova-plugin-themeablebrowser

to theme the pdf openings for  custom loading to hide url etc fields

these two approaches can be used to open a simple pdf  document for reading purposes.

but for more specific options you should go with

https://github.com/akrennmair/ng-pdfviewer

which requires pdf.js and pdf.compat.js.

add it as a dependency in your app.

var app = angular.module('testApp', [ 'ngPDFViewer' ]);

basic controller syntax useage :

app.controller('TestCtrl', [ '$scope', 'PDFViewerService', function($scope,
pdf) {
    $scope.viewer = pdf.Instance("viewer");

    $scope.nextPage = function() {
        $scope.viewer.nextPage();
    };

    $scope.prevPage = function() {
        $scope.viewer.prevPage();
    };

    $scope.pageLoaded = function(curPage, totalPages) {
        $scope.currentPage = curPage;
        $scope.totalPages = totalPages;
    };
}]);


问:
css class not working properly
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>
  <h1>Audio Projects</h1>
    <blockquote>
     <h3>

              Class D Amplifier

      </h3>
      <div class="wrapper">
          <div class="left">
              <img src="Damp/Damp_front.JPG"/>
          </div>
          <div class="right">
              Some text that should be next to image
          </div>
      </div>
  </blockquote>
</article></code>```

答:
I changed those:

```<code>.h1 {
text-align: left;
}

.h3 {
text-align: left;
}

div.left{
float: left;
}

div.right {
width: 500px;
float: left;
margin-left: 20px;}
</code>```

results

https://i.stack.imgur.com/7rswY.png

Title: css class not working properly

Body:
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}

Audio Projects

              Class D Amplifier

              Some text that should be next to image

Body:
I changed those:

.h1 {
text-align: left;
}

.h3 {
text-align: left;
}

div.left{
float: left;
}

div.right {
width: 500px;
float: left;
margin-left: 20px;}

results

https://i.stack.imgur.com/7rswY.png


问:
Kivy: How to check for the existence of a child widget
In my .py file I have a screen that looks something like:

```<code>class ExampleScreen(Screen):
    def create_layout(self):
        box = BoxLayout(orientation='vertical')
        # other layout stuff in here
        self.add_widget(box)
</code>```

In my .kv file, I have a button which, when pressed, calls this function and displays this layout on <ExampleScreen>. However, I would like to be able to press this button and first check if this layout already exists, and if so, remove it before adding a new one. I anticipate modifying create_layout() to something like:

```<code>def create_layout(self):
    if (box layout child has already been added):
        self.remove_widget(box layout child)
    box = BoxLayout(orientation='vertical')
    # other layout stuff in here
    self.add_widget(box)
</code>```

Does anyone know how to do this? Using id somehow?

答: Well, you can do it with an id or some other child checks, but the easiest and most straight-forward way would be to have a boolean flag in your class that would change to True when you added the widget and False when you removed it. Otherwise, you can also create a kivy box_obj = ObjectProperty(None) and do self.box_obj = box and then check if the self.box_obj is not None.

Body:
In my .py file I have a screen that looks something like:

class ExampleScreen(Screen):
    def create_layout(self):
        box = BoxLayout(orientation='vertical')
        # other layout stuff in here
        self.add_widget(box)

In my .kv file, I have a button which, when pressed, calls this function and displays this layout on <ExampleScreen>. However, I would like to be able to press this button and first check if this layout already exists, and if so, remove it before adding a new one. I anticipate modifying create_layout() to something like:

def create_layout(self):
    if (box layout child has already been added):
        self.remove_widget(box layout child)
    box = BoxLayout(orientation='vertical')
    # other layout stuff in here
    self.add_widget(box)

Does anyone know how to do this? Using id somehow?


问:
React Native - Vertical align image with resizeMode "contain"
When an image has a resize mode "contain" it seems to align/justify the actual image in the center, the image content however is aligned/justified at flex start.

```<code><Image resizeMode="contain" ...>
<Text>Title</Text>
</Image>
</code>```

With the following I'm seeing the text appearing above the image.

Is there any way to vertically align the contained image to top ?

答:
I needed to do the same thing. The best way I found to accomplish this was to explicitly give the height or width of the image. Then, by wrapping your image in an other component, you can use justifyContent to have full control on the position of the image.

It's true that you might not always have the width or height of the image. However, quite often (especially is using resizeMode: 'contain') you want to set the height or width relative to something. I wanted the height to be equal to the width of the viewport. Here is the solution that I used:

```<code><View style={{ flex: 1, justifyContent: 'flex-start' }}>
    <Image
      source={{ uri: imagePath }}
      resizeMode="contain"
      style={{ height: vw(100) }}
    />
 </View>
</code>```

The vw is a helper function that comes from this answer.

Body:
When an image has a resize mode "contain" it seems to align/justify the actual image in the center, the image content however is aligned/justified at flex start.

<Image resizeMode="contain" ...>
<Text>Title</Text>
</Image>

With the following I'm seeing the text appearing above the image.

Is there any way to vertically align the contained image to top ?

Body:
I needed to do the same thing. The best way I found to accomplish this was to explicitly give the height or width of the image. Then, by wrapping your image in an other component, you can use justifyContent to have full control on the position of the image.

It's true that you might not always have the width or height of the image. However, quite often (especially is using resizeMode: 'contain') you want to set the height or width relative to something. I wanted the height to be equal to the width of the viewport. Here is the solution that I used:

<View style={{ flex: 1, justifyContent: 'flex-start' }}>
    <Image
      source={{ uri: imagePath }}
      resizeMode="contain"
      style={{ height: vw(100) }}
    />
 </View>

The vw is a helper function that comes from this answer.


问:
Multiple columns processing and dynamically naming new columns
Variables are mistakenly being entered into multiple columns eg: "aaa_1", "aaa_2" and "aaa_3", or "ccc_1, "ccc_2", and "ccc_3"). Need to create single new columns (eg "aaa", or "ccc"). Some variables are currently in a single column though ("hhh_1"), but more columns may be added (hhh_2 etc).

This is what I got:

```<code>aaa_1 <- c(43, 23, 65, NA, 45)
aaa_2 <- c(NA, NA, NA, NA, NA)
aaa_3 <- c(NA, NA, 92, NA, 82)
ccc_1 <- c("fra", NA, "spa", NA, NA)
ccc_2 <- c(NA, NA, NA, "wez", NA)
ccc_3 <- c(NA, "ija", NA, "fda", NA)
ccc_4 <- c(NA, NA, NA, NA, NA)
hhh_1 <- c(183, NA, 198, NA, 182)
dataf1 <- data.frame(aaa_1,aaa_2,aaa_3,ccc_1,ccc_2, ccc_3,ccc_4,hhh_1)
</code>```

This is what I want:

```<code>aaa <- c(43, 23, NA, NA, NA)
ccc <- c("fra", "ija", "spa", NA, NA)
hhh <- c(183, NA, 198, NA, 182)
dataf2 <- data.frame(aaa,ccc,hhh)
</code>```

General solution needed as there are ~100 variables (eg "aaa", "hhh", "ccc", "ttt", "eee", "hhh"etc).

Thanks!

答:
We may try with splitstackshape

```<code>library(splitstackshape)
nm1 <- sub("_\\d+", "", names(dataf1))
tbl <- table(nm1) > 1
merged.stack(dataf1, var.stubs = names(tbl)[tbl], sep="_")
</code>```

Body:
Variables are mistakenly being entered into multiple columns eg: "aaa_1", "aaa_2" and "aaa_3", or "ccc_1, "ccc_2", and "ccc_3"). Need to create single new columns (eg "aaa", or "ccc"). Some variables are currently in a single column though ("hhh_1"), but more columns may be added (hhh_2 etc).

This is what I got:

aaa_1 <- c(43, 23, 65, NA, 45)
aaa_2 <- c(NA, NA, NA, NA, NA)
aaa_3 <- c(NA, NA, 92, NA, 82)
ccc_1 <- c("fra", NA, "spa", NA, NA)
ccc_2 <- c(NA, NA, NA, "wez", NA)
ccc_3 <- c(NA, "ija", NA, "fda", NA)
ccc_4 <- c(NA, NA, NA, NA, NA)
hhh_1 <- c(183, NA, 198, NA, 182)
dataf1 <- data.frame(aaa_1,aaa_2,aaa_3,ccc_1,ccc_2, ccc_3,ccc_4,hhh_1)

This is what I want:

aaa <- c(43, 23, NA, NA, NA)
ccc <- c("fra", "ija", "spa", NA, NA)
hhh <- c(183, NA, 198, NA, 182)
dataf2 <- data.frame(aaa,ccc,hhh)

General solution needed as there are ~100 variables (eg "aaa", "hhh", "ccc", "ttt", "eee", "hhh"etc).

Thanks!

Body:
We may try with splitstackshape

library(splitstackshape)
nm1 <- sub("_\\d+", "", names(dataf1))
tbl <- table(nm1) > 1
merged.stack(dataf1, var.stubs = names(tbl)[tbl], sep="_")


问:
looking for way to know through the code which USB device is connected to the machine?

Possible Duplicate:

  Path of the USB devices which are connected to the machine?

I'm working on a tool which perform different kind of copying - from and to different kind of USB devices, is there any way to know which kind of USB device is connected to my machine through the code?    I need it for the copying path

答:
you need to listen for removable device events and write your code there. i have a post about this here:
Listen for removable device events</p>


问:
Custom theme for AlertDialog not working
I am trying to customize the accent color for AlertDialog buttons. But it is not taking any affect it seems it is inheriting the color from system. Here is my style/theme.

```<code>   <color name="actionable_items">#0574ac</color>  <!-- it is blue color -->
   <style name="LLDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
      <!--buttons color-->
      <item name="colorAccent">@color/actionable_items</item>
      <!--item RadioButton or CheckBox color-->
      <item name="colorControlActivated">@color/actionable_items</item>
      <item name="colorPrimary">@color/actionable_items</item>
      <item name="colorPrimaryDark">@color/actionable_items</item>
      <item name="android:listChoiceIndicatorMultiple">@color/actionable_items</item>
      <item name="android:listChoiceIndicatorSingle">@color/actionable_items</item>
   </style>
</code>```

Here is my code which is trying to build the Alertdialog.

```<code>final CustomPopupBuilder removePlaceDialog =  new CustomPopupBuilder(new ContextThemeWrapper(context,
                                                            R.style.LLDialog));
            removePlaceDialog.setTitle(getString(R.string.delete_place, placeName));
            removePlaceDialog.setMessage(getString(R.string.delete_place_message));
            removePlaceDialog.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() {

               public void onClick(DialogInterface dialog, int which) {
                  ....
                  ....
               }
            });
            removePlaceDialog.setNegativeButton(R.string.cancel, null);
            removePlaceDialog.create().show();
</code>```

The final AlertDialog doesn't have buttons with the same text color. The text color is similar to green. It seems like it is inheriting the color from the system instead of the customized theme.
Here is the image :

EDIT1:

I tried the use the AlertDialog.Builder but it gives me the same result.

```<code>final AlertDialog.Builder removePlaceDialog =  AlertDialog.Builder(new ContextThemeWrapper(context,
                                                             R.style.LLDialog));
                removePlaceDialog.setTitle(getString(R.string.delete_place, placeName));
                removePlaceDialog.setMessage(getString(R.string.delete_place_message));
                removePlaceDialog.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() {

                   public void onClick(DialogInterface dialog, int which) {
                      ....
                      ....
                   }
                });
                removePlaceDialog.setNegativeButton(R.string.cancel, null);
                removePlaceDialog.create().show();
</code>```

Edit2:

I also tried to change the accent color for the dialog box but I don't see that color:

```<code><style name="LLDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
      <!--buttons color-->
      <item name="colorAccent">#990000</item>
      ...
      ...
</style>
</code>```

Even this doesn't change the button text color :(.

答:
Please check your AlertDialog import. It should be imported from v7 support lib for styles to be applied on older Android versions. I had the same problem and changing import line from

```<code>import android.app.AlertDialog
</code>```

to

```<code>import android.support.v7.app.AlertDialog
</code>```

helped me.

2019 Update:

Cause of google released AndroidX libraries, the new answer would be

```<code>import androidx.appcompat.app.AlertDialog;
</code>```

Thx to @ChristosThemelis

Body:
I am trying to customize the accent color for AlertDialog buttons. But it is not taking any affect it seems it is inheriting the color from system. Here is my style/theme.

   <color name="actionable_items">#0574ac</color>

Here is my code which is trying to build the Alertdialog.

final CustomPopupBuilder removePlaceDialog =  new CustomPopupBuilder(new ContextThemeWrapper(context,
                                                            R.style.LLDialog));
            removePlaceDialog.setTitle(getString(R.string.delete_place, placeName));
            removePlaceDialog.setMessage(getString(R.string.delete_place_message));
            removePlaceDialog.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() {

               public void onClick(DialogInterface dialog, int which) {
                  ....
                  ....
               }
            });
            removePlaceDialog.setNegativeButton(R.string.cancel, null);
            removePlaceDialog.create().show();

The final AlertDialog doesn't have buttons with the same text color. The text color is similar to green. It seems like it is inheriting the color from the system instead of the customized theme.
Here is the image :

EDIT1:

I tried the use the AlertDialog.Builder but it gives me the same result.

final AlertDialog.Builder removePlaceDialog =  AlertDialog.Builder(new ContextThemeWrapper(context,
                                                             R.style.LLDialog));
                removePlaceDialog.setTitle(getString(R.string.delete_place, placeName));
                removePlaceDialog.setMessage(getString(R.string.delete_place_message));
                removePlaceDialog.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() {

                   public void onClick(DialogInterface dialog, int which) {
                      ....
                      ....
                   }
                });
                removePlaceDialog.setNegativeButton(R.string.cancel, null);
                removePlaceDialog.create().show();

Edit2:

I also tried to change the accent color for the dialog box but I don't see that color:

Even this doesn't change the button text color :(.

Body:
Please check your AlertDialog import. It should be imported from v7 support lib for styles to be applied on older Android versions. I had the same problem and changing import line from

import android.app.AlertDialog

to

import android.support.v7.app.AlertDialog

helped me.

2019 Update:

Cause of google released AndroidX libraries, the new answer would be

import androidx.appcompat.app.AlertDialog;

Thx to @ChristosThemelis

ContentLicense: CC BY-SA 4.0


问:
Netbeans won't install on Windows 10
I'm trying to install Netbeans 8.2 Java EE, but whenever I start the installer it quits after configuring it. I am trying to install it on Windows 10 64-bit.</p>

答:
This is an Java issue, which was came up due to recent windows 10 update, that started treated differently for GodMode folder/shortcut.
This has been already fixed - https://bugs.openjdk.java.net/browse/JDK-8179014
You can verify the fix in early access build of JDK8 update 152, which is available here

We have verified the issue only with GodMode, do let us k now if there are any other scenarios that can cause such similar issues.

Title: Netbeans won't install on Windows 10


问:
using onclick to display a confirmation message within php/html
So I have this line of code:

```<code>echo '<a href="scripts/Logout.php"><span>Logout</span></a></li>';
</code>```

This appears when a user is logged in, instead of displaying "Login", it says "logout".
It works fine, however, what I am trying to do is use onClick to display a popup message box asking the user "are you sure you wish to logout?"

Something like this:

```<code>echo '<a href="scripts/Logout.php" onClick="return confirm('are you sure?')"><span>Logout</span></a></li>';
</code>```

If for example i copy that second line of code on the home page within a content div, it works fine (minus the fact im no longer clicking on the "Logout" button).

**FYI - I have taken this out of the php script (deleted the echo infront of the line, still the same result).

Anyone able to point me in the right direction?

Many thanks.

答:
The code highlighting in your code snippet already shows you what's wrong: The single quote actually breaks your echo statement. Escape them:

```<code>echo '<a href="scripts/Logout.php" onClick="return confirm(\'are you sure?\')"><span>Logout</span></a></li>';
</code>```

I would generally avoid echoing a lot of html code to prevent these kind of errors in the first place.

Also UX-wise it is questionable if you want to prompt a warning. Except in the case where the user might lose some data, it is usually preferred to let them log out laconically.

Body:
So I have this line of code:

echo 'Logout
';

This appears when a user is logged in, instead of displaying "Login", it says "logout".
It works fine, however, what I am trying to do is use onClick to display a popup message box asking the user "are you sure you wish to logout?"

Something like this:

echo 'Logout
';

If for example i copy that second line of code on the home page within a content div, it works fine (minus the fact im no longer clicking on the "Logout" button).

**FYI - I have taken this out of the php script (deleted the echo infront of the line, still the same result).

Anyone able to point me in the right direction?

Many thanks.

Body:
The code highlighting in your code snippet already shows you what's wrong: The single quote actually breaks your echo statement. Escape them:

echo '<a href="scripts/Logout.php" onClick="return confirm(\'are you sure?\')"><span>Logout</span></a></li>';

I would generally avoid echoing a lot of html code to prevent these kind of errors in the first place.

Also UX-wise it is questionable if you want to prompt a warning. Except in the case where the user might lose some data, it is usually preferred to let them log out laconically.