Spring Boot Microsoft AD Authentication

Question: I know little about Spring Boot and even less about Active Directory.
I need to Authenticate against Microsoft Active Directory using Spring Boot and JWT. I have working JWT with user from memory but i am having trouble authenticating against user from Microsoft AD.
Microsoft AD setup:

Active Directory is running on Windows Server 2012r2 (192.168.1.166).
AD users.
AD user property.

Spring Boot app is running on: 192.168.1.31:8082
Spring Boot config:
import com.mts.oh.config.cors.SimpleCORSFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SimpleCORSFilter myCorsFilter;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(myCorsFilter, ChannelProcessingFilter.class).
                csrf().disable().
                exceptionHandling().authenticationEntryPoint(unauthorizedHandler).
                and().
                authorizeRequests().
                antMatchers(HttpMethod.POST, "/api/login").permitAll().
                anyRequest().authenticated().
                and().
                addFilterBefore(new LoginInterceptor("/api/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class).
                addFilterBefore(new JwtInterceptor(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.authenticationProvider(activeDirectoryLdapAuthenticationProvider()).userDetailsService(userDetailsService());
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
    }

    @Bean
    public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider("bmad.com",
            "ldap://192.168.1.166:389/DC=bmad,DC=com");
    provider.setSearchFilter("OU=devs,OU=employees");
    provider.setConvertSubErrorCodesToExceptions(true);
    provider.setUseAuthenticationRequestCredentials(true);

        return provider;
    }
}

Login endpoint is: /api/login.
Postman request:

Login Request Body
Login Request Headers

Stack Trace:
> rg.springframework.security.authentication.BadCredentialsException:
> Bad credentials
>       at org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.badCredentials(ActiveDirectoryLdapAuthenticationProvider.java:295)
>       at org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.badCredentials(ActiveDirectoryLdapAuthenticationProvider.java:300)
>       at org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.raiseExceptionForErrorCode(ActiveDirectoryLdapAuthenticationProvider.java:267)
>       at org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.handleBindException(ActiveDirectoryLdapAuthenticationProvider.java:233)
>       at org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.bindAsUser(ActiveDirectoryLdapAuthenticationProvider.java:208)
>       at org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.doAuthentication(ActiveDirectoryLdapAuthenticationProvider.java:144)
>       at org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider.authenticate(AbstractLdapAuthenticationProvider.java:85)
>       at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
>       at com.mts.oh.config.security.LoginInterceptor.attemptAuthentication(LoginInterceptor.java:28)
>       at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
>       at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
>       at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
>       at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
>       at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
>       at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
>       at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
>       at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
>       at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
>       at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
>       at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
>       at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
>       at com.mts.oh.config.cors.SimpleCORSFilter.doFilter(SimpleCORSFilter.java:32)
>       at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
>       at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
>       at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
>       at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
>       at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
>       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
>       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
>       at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
>       at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
>       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
>       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
>       at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
>       at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
>       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
>       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
>       at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
>       at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
>       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
>       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
>       at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
>       at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
>       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
>       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
>       at com.mts.oh.config.cors.SimpleCORSFilter.doFilter(SimpleCORSFilter.java:32)
>       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
>       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
>       at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
>       at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
>       at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
>       at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
>       at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
>       at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
>       at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
>       at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
>       at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
>       at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
>       at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457)
>       at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
>       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
>       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
>       at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
>       at java.lang.Thread.run(Thread.java:748)
>     Caused by: org.springframework.security.ldap.authentication.ad.ActiveDirectoryAuthenticationException:
> [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903C5, comment:
> AcceptSecurityContext error, data 773, v2580 ]
>       at org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.raiseExceptionForErrorCode(ActiveDirectoryLdapAuthenticationProvider.java:250)
>       ... 61 common frames omitted
>     Caused by: javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903C5, comment: AcceptSecurityContext
> error, data 773, v2580 ]
>       at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3154)
>       at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:3100)
>       at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2886)
>       at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2800)
>       at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:319)
>       at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:192)
>       at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:210)
>       at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:153)
>       at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:83)
>       at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
>       at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
>       at javax.naming.InitialContext.init(InitialContext.java:244)
>       at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:154)
>       at org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider$ContextFactory.createContext(ActiveDirectoryLdapAuthenticationProvider.java:402)
>       at org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.bindAsUser(ActiveDirectoryLdapAuthenticationProvider.java:203)
>       ... 59 common frames omitted

I have tried different combinations of username and password but none of them work:

John Doe / ****
johnupn / ****
firstname.lastname@example.com / ****
bmad\johnupn / ****

I have picked up Spring Boot configuration from:
https://medium.com/@dmarko484/spring-boot-active-directory-authentication-5ea04969f220
and
https://www.ziaconsulting.com/developer-help/spring-security-active-directory/
but these do not work for me.
Answer: From a computer logged into the domain, a user can find the values for their account using whoami. Below shows the commands to get a user's sAMAccountName, userPrincipalName, and fully qualified distinguished name respectively. Active Directory uses all three of these as the username when authenticating via LDAP.
c:>whoami
mydomain\lisa

c:>whoami /upn
email@example.com

c:>whoami /fqdn
CN=Smith\, Lisa,OU=GPOTest,OU=IT,OU=Company,DC=mydomain,DC=ccTLD

Comment: My answer helps because multiple iterations of the user id were being attempted. Two of the four iterations are not valid, and the other two may or may not be valid depending on the actual values used within AD. I've seen domains where example.com still has OldComp as their sAMAccountName prefix and sometimes an internal DNS like Company.Local in their userPrincipalName. There is nothing to be gained by continuing to test and troubleshoot using invalid user IDs. Knowing exactly what needs to be used as the user ID eliminates a cause of failure that absolutely will yield LDAP err 49.
Comment: How does your answer help?

Spring Boot Microsoft AD Authentication


Unix(Mac OS) terminal does not honor Ctrl+D as EOF

Question: Problem I have:
When I was playing getchar() behavior, I found my terminal (macOS Mohave Version 10.14.6 18G87) does not honor Ctrl+D as EOF.
How I got the problem:
The code with getchar() is attached below, basically this code is echo getchar() if the input char is not blank, otherwise, for multiple continously blank char it only output one single blank char.
The code itself works, but when running it in terminal, the terminal does not honor Ctrl+D as EOF, thus the code never terminates.
I am sure this is due to I mistakenly use system ("/bin/stty raw"); and system ("/bin/stty cooked"); , however, I dont' know how to fix it.
 /* K&R C Exercise 1-9. Write a program to copy its input to its output,
 * replacing each string of one or more blanks by a single blank.*/

#include <stdio.h>
#include <stdlib.h>

int main(void){

    int ch;
    int prev = -1;

    /* if you are in a UNIX like environment
     * the ICANON flag is enabled by default, so input is buffered until the next '\n' or EOF
     * https://stackoverflow.com/a/1799024/5450745
     * */
    system ("/bin/stty raw");

    while ((ch=getchar())!= EOF){
       if (ch != ' ' ){
           if (prev == ' '){
               putchar(prev);
               putchar(ch);
           }
           else{
               putchar(ch);
           }
           prev = ch;
       }
       else{

           prev = ch;
           continue;
       }

    }
    /* use system call to set terminal behaviour to more normal behaviour */
    system ("/bin/stty cooked");

    return 0;
}

I checked stty, however, it does configure EOF as Ctrl +D. However, right now, if I press Ctrl + D, it only splits the terminal from one window to two.

What can I do to allow EOF re-enable again?
Thanks!
Comment: Your problem has nothing to do with MacOS, and everything to do with, yes, your `stty` call.  If you want to do the exercise as the authors intended, get rid of the `stty` calls.  If you want to see characters immediately as they're typed -- as I remember *I* did, the first time I did a similar exercise in K&R -- then yes, you're going to have to tinker with the tty modes, but you're also going to have to check for control-D yourself.  Easiest way would be to change the loop to `while ((ch=getchar()) != EOF && ch != 4)`.
Comment: Are you actually pressing `ctrl+d` and not `command+d`? Because `command+d` is the default shortcut to split the window in the MacOS Terminal.
Comment: Raw mode input doesn't honour any special characters — no EOF, no erase, no interrupt, no quit, no kill, etc.  Maybe `stty cbreak` — I've not experimented, and I'm not sure.  Note that you can't erase characters either at the moment.  (And one key `stty` flag is `icanon`/`-icanon`.)
Comment: You could use `while ((ch=getchar())!= EOF && ch != '\004'){` though since EOF will not be detected if the `stty` command works, you could simplify that to `while ((ch=getchar()) != `\004'){`.  The value `'\004'` (equivalent to `'\4'` and `'\x04'` and `4`) is also the notation for control-D.
Comment: Voted to migrate to https://superuser.com/ As this is not a programming question but terminal configuration.
Comment: The reason I put it here is because I think this problem is raised due to I wrongly use `system ("/bin/stty raw")` and `system ("/bin/stty cooked");`, I think I sort of mixed the C library, and UNIX terminal configurations in one question.
Comment: @SteveSummit Hi! Thanks for reply! May I know what does it mean for `ch!=4` ? what does `4` represent for , an integer 4 ?
Comment: @JacquelineP. That's the value you'll get if you type control-D.  (`A` is 65, `D` is 68, `a` is 97, `d` is 100, control-A is 1, control-D is 4, ...)
Comment: I tried Ctrl +d and Command⌘ + d , neither works as EOF. And pressing " Command⌘ + d" splits from one window to two...
Comment: Sorry, I really thought Control-D would map to 4.  You may just have to get rid of the `stty` calls.
Answer: This code works for me on my Mac running macOS Catalina 10.15. I'd expect it to work essentially the same on just about any Unix-like system you can lay hands on, including older versions of macOS.  It spots control-D by comparing ch with '\004' (octal 4 — writable numerous other ways in standard C, including just 4) is detected when typed and terminates the loop.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int ch;
    int prev = -1;

    /* if you are in a UNIX like environment
     * the ICANON flag is enabled by default, so input is buffered until the next '\n' or EOF
     * https://stackoverflow.com/a/1799024/5450745
     * */
    system("/bin/stty raw");

    while ((ch = getchar()) != EOF && ch != '\004')
    {
        if (ch != ' ')
        {
            if (prev == ' ')
            {
                putchar(prev);
                putchar(ch);
            }
            else
            {
                putchar(ch);
            }
            prev = ch;
        }
        else
        {
            prev = ch;
            continue;
        }
    }
    /* use system call to set terminal behaviour to more normal behaviour */
    system("/bin/stty cooked");

    return 0;
}

Of course, the output display is a bit weird — typing return does not move the cursor to the next line, for example.  But the test for ch == '\004' does detect when control-D is typed.  (The space elimination code does work too.)
Using stty cbreak instead of stty raw leaves the interrupt enabled, but EOF via control-D is still disabled.
Comment: It works! Thank you!


PHP 7.4 number_format still renders as string

Question: This is my array $grand_total_payouts,
<code> array(5) {
            [0]=> string(6) "120.00"
            [1]=> string(8) "1,200.00"
            [2]=> string(8) "1,347.50"
            [3]=> string(5) "40.00"
            [4]=> string(6) "200.00"
           }
</code>
When I do this
<code>   $value = '';
    foreach ($grand_total_provider_payouts as $payout) {
        $value = number_format($payout, 2, '.', ',' );
        var_dump($value);
    }
</code>
I get this.
<code> string(6) "120.00"
 string(4) "1.00"
 string(4) "1.00"
 string(5) "40.00"
 string(6) "200.00"
</code>
Why do [1] and [2] render as 1.0? And why do the numbers render as strings and not int?
According to https://www.php.net/manual/en/function.number-format
It should render as a number.
My ultimate goal is to sum these numbers.
What is the right way to convert the string to int?
Answer: When you call number_format it return a string, because this is the expected behaviour, present number in currency format is a commom case.
1.0 to "US$ 1.00"
If you need perform math operations, don't use number_format before. Perform
all operations, so use number_format if you wish present formatted to view
Comment: The key was to not let the numbers in the array become strings, to begin with. Where the numbers were generated, I changed the code to create numbers instead of strings.
Comment: a simple cast is what are you looking  for? e.g:
$value = "1.01";
$numberValue = (float) $value;
var_dump($numberValue); // prints: float(1.01)
Comment: The problem is the array. From an array, I was unable to change the string value. Like this string [0] => "1,307.50" can't be set to an int


Starts with not working in while check in Xsl

Question: I have tried different ways but not able to figure out the mistake.I have to do 2 checks to set the value of an attribute.The below example is a simple version of it.
Input XML
`
<Detail Type="3242432" LastDate="2016-04-22T11:02:43+01:00"
    NodName="10001"
    UpdateValueReason="Apple: 123 56"
    Date="2016-04-22T11:02:43+01:00">

</Detail>

`
XSL
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

   <xsl:template match="/Detail/Sub">
      <Status>
      <xsl:attribute name="StatusType">
      <xsl:choose>
      <xsl:when test="../starts-with(@UpdateValueReason, 'Apple') and @EventID='2'">
                  <xsl:value-of select="'23'" />
               </xsl:when>

               <xsl:otherwise>
                  <xsl:value-of select="'1234'" />
               </xsl:otherwise>
               </xsl:choose>
       </xsl:attribute>
      </Status>
   </xsl:template>
</xsl:stylesheet>

Here I am checking if an attribute starts with certain set of char I am stamping another attribute, but its throwing error
Error while running on cooktop
Error:
ERROR: Description: NodeTest expected here.
../-->starts-with<--(@UpdateValueReason, 'Apple') and @EventID='2'
Comment: You should edit your question to say what the error is, as often error messages give useful information. Thank you.
Answer: Your current syntax would work with XSLT 2.0, but not XSLT 1.0.
Try this instead for XSLT 1.0:
 <xsl:when test="starts-with(../@UpdateValueReason, 'Apple') and @EventID='2'">


jquery mobile collapse if mobile device

Question: I have a web application built on JQuery Mobile.
I've been looking for a way to have certain divs (which have data-role="collapsible") be collapsed when viewed on a mobile device, but expanded if viewed on a desktop browser.
I know there are a lot of similar questions, but I haven't been able to get any of those solutions to work. Here's what I've tried.
The divs have a class of mobileHide

I didn't have all of those running at once, but each piece that I commented on was the only part that was active at the time.
Any insight into why the last one detects mobile device and displays the alert (when it's not commented out) but won't trigger the collapse when it detects mobile device would be much appreciated!
Comment: Which version of jQM?
Comment: try --  $( ".mobileHide" ).children().trigger( "collapse" );    --- and to expand --- and use the javascript way to detect as you getting alerts --- if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
Comment: For 1.4.x: http://jsfiddle.net/ezanker/suPc7/, for 1.3: http://jsfiddle.net/ezanker/suPc7/1/. Working demos using window width
Comment: Hey sorry for delay, I didn't refresh the page so I didn't see the reply (doh!).
It's version 1.0... I started to update it in the past, but I have so much built on it already and too many things stopped working correctly I just decided to stick with 1.0 until I'm ready to do a complete rebuild (after this version is out there doing its job).
Comment: Thanks all.
@ezanker, I used the code from your 1.3 jsfiddle and it works! Thanks!
I don't see an option to mark it as the correct answer, does it need to be listed as an answer instead of a comment?
Comment: I have added it as an answer so you can accept it, thanks.
Answer:
Here is a working DEMO

The function CollapsiblesOnSize() checks the window width and then either collapses or expands all elements with class of mobileHide. You can then call this on window resize, orientation change and jQM's pageshow:
$(document).on("pageinit", "#page1", function () {
    CollapsiblesOnSize();
    $(window).on("resize orientationchange", function(){
        CollapsiblesOnSize();
    });
});

function CollapsiblesOnSize(){
    var w = $(window).width();
    if(w >= 540 ) {
        $( ".mobileHide" ).trigger( "expand" );
    }else{
        $( ".mobileHide" ).trigger( "collapse" );
    }
}

jquery mobile collapse if mobile device


Making coefficient for centered binary variable meaningful?

Question: I'm having a hard time making a centered binary variable in a multilevel model interpretable. Here is what I'm working with: at Level 1, I have a binary variable indicating whether a participant gets free/reduced lunch (0= No; 1= Yes). Participants are nested within schools (Level 2), so to disentangle person and school effects, I centered the free/reduced lunch variable within school (as recommended in various multilevel modeling texts).
The issue that I'm running into now is difficulty interpreting the coefficient for this variable. Each participant's score is now a 0 or 1 deviation from a school-level percentage of respondents that receive free/reduced lunch. For example, the range for my participant-centered lunch variable ranges from approximately .75 (a participant receiving free/reduced lunch in a school where 25% of participants get free/reduced lunch: 1.0 - 0.25 = 0.75) to -.34 (a participant that does not get free/reduced lunch in a school where 34% do: 0.0 - 0.34 = -0.34).
Now I'm not really sure what my fixed effect coefficients mean under this coding scheme. I initially thought that the raw coefficient from my multilevel model for the participant-centered binary variable (b = -1.6) indicates that the predicted change in the dependent variable decreases (on average) by 1.6 between participants that do not receive free/reduced lunch and those that do. That can't be right though because the centering.
Can anybody help me out?
Answer: Your coefficient is just the change from going from 0 to 1. In this case, no free lunch to free lunch. Don't think you need to mention the centering as this only changes the intercept, not the value of the coefficient.
Comment: I don't think that can be true. I think that the interpretation of this variable must be tied to the school mean that it's centered around.


Finding number of summands by using generating function

Question: I did something wrong in the calculations, but I can't find the error. I've recalculated it many times and checked it in many different ways. Here're the calculations: http://pastebin.com/yUvnmKTm
But, in the nutshell, the task:
$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 29$
But, there must be exactly 3 odd $x_i$, every $x_i$ must be greater then 1.
If I solve this using generating function, as in:
$(k^2 + k^4 + \dots + k^{18})^3(k^3 + k^5 + \dots + k^{17})^3$
The coefficient in front of $k^{29}$ is 792. But this number doesn't correspond to anything. Neither the number of sequences of summands, nor the number of sets of summands. In particular, if solutions such as $(2, 3, 4, 6, 7, 7)$ and $(2, 3, 4, 7, 6, 7)$ are considered distinct, then there are 15840 such sequences. 74 otherwise.
What did I miss?
PS. I'm sorry for the probably vague formulation of the task, ironically, neither the language of the task, nor English are my native tongue. And I really don't know whether it is asking to find all possible summands, or all permutations of all possible summands.
Comment: The coefficient of $k^{29}$ in your generating function counts the number of sequences where the first three terms are even, the second three terms are odd, all terms are greater than $1$, and the sum is $29$.  According to WolframAlpha, the coefficient of $k^{29}$ in your generating function is $792$.  To remove the (undesired) restriction that the even terms come first, you must multiply the count by ${{6}\choose{3}}=20$, giving $15840$.
Comment: @mjqxxxx, may I encourage you to elevate your comment to an answer?
Comment: Yes, please, @mjqxxxx that answers it. Sorry, that was a silly typo, I got the same result as you get from WolframAlpha (you can see that in the print in the pastebin code), just typed it here incorrectly.
Answer: The coefficient of $k^{29}$ in your generating function counts the number of sequences where the first three terms are even, the second three terms are odd, all terms are greater than $1$, and the sum is $29$.  According to WolframAlpha, the coefficient of $k^{29}$ in your generating function is $792$.  To remove the (undesired) restriction that the even terms come first, you must multiply the count by ${{6}\choose{3}}=20$, giving $15840$.


dynamic strings in struct

Question: I am having a problem with understanding the concept of dynamic memory allocation, I have some code that is encountering a segfault perhaps some one may have some insight?
 #include <stdio.h>
 #include <stdlib.h>

typedef struct tName
{
   char **stringA;
   int capacity;
} tName;

tName *createTName(int length);
tName *destroyTName(tName *l);

int main(void) {
    tName *ll = createTName(10);
}

tName *createTName(int length) {
    tName *temp;
    int i;
    temp->capacity = length;

    temp->stringA= (char**) malloc(sizeof(char*) * length);
    for(i=0;i<length;i++)
       temp->stringA[i] = (char*) malloc(sizeof(char)*50);

    return temp;
}

When I call run this program I get a segfault, can anyone assist me please?
Comment: FYI: Don't cast the result of `malloc`.
Comment: @Barmar: Why not? In c++, you are even forced to cast the return-value. I think there is no problem with casting.
Comment: maja: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc
Comment: @Barmar: Thanks, I never tought about it in this way :)
Answer: Your problem is here:
temp->capacity = length;

You are asigning a value to a variable, which doesn't have memory yet. You have to allocate memory for the struct to.
Use this:
tName *temp = malloc( sizeof(tName) );

If you only write tName *temp, the compiler will only allocate 4 Bytes (or 8 in 64bit Systems) for the pointer. But it wont't allocate the momory, where the pointer is pointing to.
Another problem is at the malloc, which allocates memory for the string - it should be this:
temp->stringA = malloc(length+1);

Fist of all, you don't have to multiply it with sizeof(char*) (which will again be 4 or 8 Bytes), but with sizeof(char). The Variabletype char always needs 1 Byte, so you don't have to mulitply it at all.
But you must not forget to allocate one extra-byte for the string, if you want to use string-operations. This byte is needed to stroe the Ascii-0, which specifies the end of the string.
If you forget about this byte, the Program can result in strange output, and even in sefgaults.
And about this loop:
for(i=0;i<length;i++)
       temp->stringA[i] = (char*) malloc(sizeof(char)*50);

I don't really know what you want to achieve with it, can you add some more information?

dynamic strings in struct


Multi-peak Gaussian fit in R with small number of sample

Question: I have only five data set to predict two bimodal Gaussian fit like this one.
x = c(51,92,220, 280, 333)
y = c(40,80,20,60,40)

Here's an example of the plot and loess line using ggplot.

I want to get an equation through Gaussian curve fitting.
So, I use nls() function like this.
fit <- nls(y ~ (C1 * exp(-(x-mean1)**2/(2 * sigma1**2)) +
                    C2 * exp(-(x-mean2)**2/(2 * sigma2**2))),
           start=list(C1=20, mean1=100, sigma1=0.1,
                      C2=20, mean2=270, sigma2=0.1), algorithm="port")

however, it didn't work, show 'singular gradient matrix at initial parameter estimates' error.
I know it was caused by a wrong initial values, but I can't find a solution. Is there any good way? or can't I fit the curve fitting because I only have a small sample?
Answer: You have 6 unknown parameters but only 5 data points. Somewhat like fitting a straight line to a single data point, there are an infinite no. of parameter choices that will fit your data.


Can we access Data from ADLA tables creating ODATA source using REST API?

Question: Is there a way if ODATA can be established on top of azure data lake analytics table via REST API's?
It seems there are REST API's to get ADLA job informations, account information etc.,
Is there any such existing API's to get data or is it possible to create API to access data via ODATA concept?
Answer: If you want to access data in ADLS files, there are REST APIs to get data from the lake. ADLS supports WebHDFS APIs with OAuth.
If you want to send queries and see their results or get U-SQL table data, you would have to write your own shim that translates the query you submit via your API into a U-SQL Script that outputs a file and then transparently download the file and returns it as the result.
Note that so-called interactive support is on the roadmap and being worked on. Once that is available, you can access the data using standard query APIs (such as ODBC, JDBC etc).


Restrict POST Request The Server

Question: I want to restrict all POST request that comes from other server via .htacces
if they try to post any from other server thing they will get redirected to home page or 404 etc.
I tried this
<Limit POST>
order deny,allow
deny from all
allow from 127.0.0.1
</Limit>

Note:- GET request are allowed from all servers. Only to block POST requests.
Comment: Your code seems to work fine for me. Maybe you only had to correct the name of .htaccess file. (double "s")
Answer: That block will only prevent POST requests from hosts other than 127.0.0.1, and you will get a 403 Forbidden response. You could try using mod_rewrite and replace the <LIMIT> with:
RewriteCond %{REQUEST_METHOD} POST

# allow the server to POST to itself
RewriteCond %{REMOTE_ADDR} !127.0.0.1

# allow POST from trusted users
RewriteCond %{REMOTE_ADDR} !123.456.789.123

# send all other post requests to 403 forbidden
RewriteRule ^ / [F]

If you would prefer to send post request to the home page of your site instead replace [F] in the last line with [R,L]
You'd replace the / with where your "home page" is if it isn't just /.
Comment: that's great stuff. Thanks. Quick question.
if i want to allow some more server to allow.
i need to include `RewriteCond %{REMOTE_ADDR} !SOME IP ADDRES` am i right.
Comment: What about allowing a domain and its subdomains?

Restrict POST Request The Server


Show $w,L(w),L^2(w),\dots,L^{n-1}$ are linearly independent

Question: Let $W$ be an finite dimensional vector space.
The dimension of $W$ is $n$. Let $L:W\rightarrow W$ be linear.
Define $L^0=I_W$ and $L^k=L\circ L\circ \cdots \circ L$ for $k$ times.
If there exists $w\in W$ such that $L^{n-1}(w)\ne 0$ and $L^n(w)=0$.
Show $w,L(w),L^2(w),\dots,L^{n-1}$ are linearly independent.
It is easy to show that a few vectors are linearly independent, but how can I show that $n$ vectors are?
Answer: Suppose
$$\sum_{k=0}^{n-1}a_kL^kw=0$$
Apply now $\;L^{n-1}\;$ to both sides of the last equality:
$$a_0L^{n-1}w+a_1\overbrace{L^nw}^{=0}+\ldots+a_{n-1}\overbrace{L^{2(n-1)}w}^{=0}=0\implies a_0L^{n-1}w=0\implies a_0=0$$
Now take off $\;a_0\;$ from the first equality and repeat the above with applying $\;L^{n-2}\;$ in both sides, and then induction...


How to find a useful variable change for this integral

Question: I would like to find the area of the following region
$$
D=\left \{(x,y): -\sqrt{1+y^2}\leq x\leq \sqrt{1+y^2}; -1\leq y\leq (x+1)/2\right \}.
$$
I try to calculate the double integral brute force, but following this path
I came across some very unpleasant integrals. So I think that maybe a variable
change may be an appropriate approach here.
Can someone suggest me a useful variable change to calculate the area of this region?
Comment: polar integration is probably your best chance, split the integral to 4 separate ones
Comment: How does that set have a nonzero area? It lies on a hyperbola and is therefore one-dimensional. Did you mean $x^2-y^2\le1$?
Comment: what is the bound for $x$?
Comment: @Théophile In fact there was a mistake in the descricption.  But It is already fixed
Comment: @person At a first look I think in polar coordinates but I was not able to discribe the region properly
Comment: With the latest edit to the problem, the area is clearly infinite.
Comment: Did you mean $x^2$ instead of $x$ in the first inequality?
Comment: @Théophile yes you are right, i have edited again
Comment: It is a hyperbolic region so the integral is not going to be as simple.
Answer:
See the diagram. You need to find the area of the region ABCO. If you integrate along $y$ axis taking strips of thickness $dy$ parallel to $x$ axis, you can see that from $y = -1$  to $y = 0$, both the left and right ends are bound by the hyperbola but for strips at $0 \leq y  \leq \frac{4}{3}$, the left is bound by the line $2y = x+1$ and the right is bound by the hyperbola. So we divide our integral in two parts.
Now to find the intersection of the line $2y = x+1$ and the hyperbola $x^2 - y^2 = 1$,
$x^2 - y^2 = 1$
At intersection, $x^2 - \frac{(x + 1)^2}{4} = 1$. That gives us $x = \frac{5}{3}, y = \frac{4}{3}$
So, $A = \displaystyle \int_{-1}^0 ({x_r - x_l}) \, dy \, \, + \int_{0}^{4/3} ({x_r - x_l}) \, dy$
$A = \displaystyle \int_{-1}^0 (\sqrt{1+y^2} - (-\sqrt{1+y^2}) \, dy \, \, + \int_{0}^{4/3} (\sqrt{1+y^2} - (2y-1)) \, dy$
$A = \displaystyle 2\int_{-1}^0 \sqrt{1+y^2} \, dy \, \, + \int_{0}^{4/3} (\sqrt{1+y^2} - 2y + 1) \, dy$
To integrate $\sqrt{1+y^2}$, one of the ways is to substitute $y = \tan \theta$.
Integral of $\sqrt{1+y^2}$ is given by  $\frac{y}{2} \sqrt{1+y^2} + \frac{1}{2} \ln ({y + \sqrt{1+y^2}})$.
You can check WolframAlpha for the same.
Answer: split the area into 5 separate areas:
$$\int_{\pi}^{\pi+\tan^{-1}(1/\sqrt{2})}\frac{1}{2}r^2d\theta+
\int_{\pi+\tan^{-1}(1/\sqrt{2}))}^{-\tan^{-1}(1/\sqrt{2}))}\frac{1}{2}r^2d\theta+
\int_{-\tan^{-1}(1/\sqrt{2}))}^{0}\frac{1}{2}r^2d\theta+
\int_{0}^{\tan^{-1}(4/5)}\frac{1}{2}r^2d\theta+
\int_{\tan^{-1}(4/5)}^{\pi}\frac{1}{2}r^2d\theta
$$
the second and the last integral are triangles, and the first and the third are equal:
$$
\sqrt{2}+
2\int_{-\tan^{-1}(1/\sqrt{2}))}^{0}\frac{1}{2}r^2d\theta+
\int_{0}^{\tan^{-1}(4/5)}\frac{1}{2}r^2d\theta+
\frac{2}{3}
$$
the polar function that defines the hyperbola is:
$$r=\left(\frac{1}{\cos2\theta}\right)^{\frac{1}{2}}$$
so putting it into the integral then evaluating:
$$
\sqrt{2}+
2\int_{-\tan^{-1}(1/\sqrt{2}))}^{0}\frac{1}{2}\left(\frac{1}{\cos2\theta}\right)d\theta+
\int_{0}^{\tan^{-1}(4/5)}\frac{1}{2}\left(\frac{1}{\cos2\theta}\right)d\theta+
\frac{2}{3}
$$
$$
=\sqrt{2}+
\frac{1}{2}\ln \left(3\right)-\frac{1}{2}\ln \left(3-2\sqrt{2}\right)+
\frac{2}{3}
$$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\on}[1]{\operatorname{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&D \equiv
\braces{\!\!\pars{x, y} \mid -\root{1 + y^{2}} \!\leq\! x\! \leq\! \root{1 + y^{2}};\ -1\! \leq\! y\! \leq\! {x + 1 \over 2}}.
\\[2mm] &\ \bbox[#ffd,10px,border:1px groove navy]
{{\cal A}_{D} \equiv D\ area}:\ {\Large ?}.
\\ &
\end{align}

\begin{align}
{\cal A}_{D} & \equiv
\bbox[5px,#ffd]{\iint_{\mathbb{R}^{2}}
\bracks{\verts{x} \leq \root{1 + y^{2}}}
\bracks{-1 \leq y \leq {x + 1 \over 2}}\dd x\,\dd y}
\\[5mm] & =
\int_{-1}^{\infty}
\int_{-\root{\vphantom{A^{A}}1\ +\ y^{2}\,}}
^{\root{\vphantom{A^{A}}1\ +\ y^{2}\,}}
\bracks{x \geq 2y - 1}\dd x\,\dd y
\\[5mm] & =
\int_{-1}^{\infty}\ \overbrace{\bracks{2y - 1 <
-\root{\vphantom{A^{A}}1\ +\ y^{2}\,}}}
^{\ds{= \bracks{y < 0}}}\
\int_{-\root{\vphantom{A^{A}}1\ +\ y^{2}\,}}
^{\root{\vphantom{A^{A}}1\ +\ y^{2}\,}}
\dd x\,\dd y
\\[2mm] & +
\int_{-1}^{\infty}\
\overbrace{\bracks{-\root{\vphantom{A^{A}}1\ +\ y^{2}\,} < 2y - 1 <
\root{\vphantom{A^{A}}1\ +\ y^{2}\,}}}
^{\ds{= \bracks{0 < y < {4 \over 3}}}}\ \times
\\ & \phantom{\int_{-1}^{\infty}\ }
\int_{2y - 1}
^{\root{\vphantom{A^{A}}1\ +\ y^{2}\,}}\dd x\,\dd y
\\[5mm] & =
\underbrace{\int_{-1}^{0}2\root{1 + y^{2}}\dd y}
_{\ds{\root{2} + \on{arcsinh}\pars{1}}}\ +\
\underbrace{\int_{0}^{4/3}\bracks{\root{1 + y^{2}} - 2y + 1}\dd y}
_{\ds{{2 \over 3} + {\ln\pars{3} \over 2}}}
\\[5mm] & =
\bbx{{2 \over 3} + \root{2} + {1 \over 2}\ln\pars{3} +
\on{arcsinh}\pars{1}} \approx 3.5116 \\ &\
\end{align}

Note that
\begin{align}
\on{arcsinh}\pars{1} & = \ln\pars{1 + \root{2}} =
{1 \over 2}\ln\pars{3 + 2\root{2}}
\\[2mm] & =
-{1 \over 2}\ln\pars{3 - 2\root{2}}
\end{align}


Check for status updates using APEX.SERVER.PROCESS

Question: Env: Oracle APEX v5.1.2 with Oracle 12c R2 DB
I have a report that is based off the following table columns in a table called MY_TASK:
TASK_ID (PK),
TASK,
TASK_STATUS (from TASK_CHECKER.task_status)

I also have another table that I use as a running table to check the status of a job that relates to the TASK_ID number from table MY_TASK called TASK_CHECKER which has the columns:
TASK_ID (PK),
TASK_STATUS

Based on the above, I have a scheduled job that regularly checks the status of another table for a specific TASK_ID, which updates the TASK_STATUS value within the TASK_CHECKER table.
Using the above, when the user runs the Oracle APEX app and goes to the MY_TASK report page, I would like through the use of apex.server.process, at startup, join the two tables together via TASK_ID and display the TASK_STATUS at the time within the MY_TASK report.
Please note that the TASK_STATUS values are: WAITING / IN-PROGRESS / SUCCESS or FAILED
So if I had 5 TASK_IDs running, I might see at page load:
1    TASK_A   SUCCESS
2    TASK_B   ERROR
3    TASK_C   IN-PROGRESS
4    TASK_D   WAITING
5    TASK_E   WAITING

and perhaps 10 seconds later change to:
1    TASK_A   SUCCESS
2    TASK_B   ERROR
3    TASK_C   SUCCESS
4    TASK_D   SUCCESS
5    TASK_E   IN-PROGRESS

Would like to see TASK_STATUS updates appear in real time.
Comment: The easiest thing to do is to just refresh the region every N seconds. Would that work?
Comment: @DanMcGhan - Hi Dan, that would work but just wondering whether I could use apex.server.process and refreshing an Interactive Grid does seem to work using apex.region("region_static_id").refresh() . I'm just after a means of refreshing the IG every N seconds without locking the screen, while the user is on the page.
Answer: I just checked and it seems that refresh is async (it doesn't lock the screen). You should be able to do something like this...
setInterval(function() {
  apex.region("region_static_id").refresh();
}, 5000);

Just make sure the number of milliseconds is higher than the amount of time the region takes the query to run and the region to render.
Comment: Does this also work for Interactive Grids and I thought this is done differently for IG's?


Why am I getting empty input value on expose filter $form_state variables for taxonomy?

Question: I have created a panel. Inside the panel there is one content pane and one view expose filter present.
Normal exposed filter works properly but Simple hierarchical select does not works as expected: I am getting empty value after submit.
I have checked using views_exposed_form_alter hook.
$form_state['view']->exposed_input['shs_term_node_tid_depth']

Is there any alternative way to set or get the expose filter input?
Answer: Apply little trick and my issue solved.
Used default taxonomy search and hide it.
(function($) {

Drupal.behaviors.tushar_1 = {
  attach: function (context, settings) {
    $('#edit-shs-term-node-tid-depth').change(function(){
      var eid = $('#edit-shs-term-node-tid-depth').val();
      $('#edit-tid ').val(eid);
    });
  }
};

})(jQuery);

Solved my issue.


Flutter collapse and expand widget with elastic animation

Question: in this simple below ui i have Container right of screen and i want to collapse and expand it with elastic animation, for example on expand elasticIn animation and for collapse elasticOut.
Answer: Is this what you need?

import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
import 'dart:math';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Spring Box",
      theme: ThemeData(),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  Animation animationIn, animationOut;

  AnimationController _animationController;

  @override
  void initState() {
    _animationController = AnimationController(
      vsync: this,
      value: 1.0,
      duration: Duration(milliseconds: 500),
    );
    animationIn = CurvedAnimation(parent: _animationController, curve: Curves.elasticIn);
    animationOut = CurvedAnimation(parent: _animationController, curve: Curves.elasticIn);
  }

  _toggleExpanded() {
    if (_animationController.status == AnimationStatus.completed) {
      _animationController.reverse();
    } else {
      _animationController.forward();
    }
  }

  @override
  Widget build(BuildContext context) {
    var isExpanded = _animationController.status != AnimationStatus.completed;
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: _toggleExpanded,
        child: Icon(Icons.add),
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          CollapsAnimation(
            animation: isExpanded ? animationOut : animationIn,
            child: Container(
              color: Color(0xFF404bc4),
            ),
          ),
        ],
      ),
      backgroundColor: Color(0xFFe8e8e8),
    );
  }
}

class CollapsAnimation extends AnimatedWidget {
  CollapsAnimation({key, animation, this.child})
      : super(
          key: key,
          listenable: animation,
        );

  final Widget child;
  final Tween tween = Tween<double>(begin: 0, end: 80);

  @override
  Widget build(BuildContext context) {
    Animation<double> animation = listenable;

    var animationValue = tween.evaluate(animation);
    double width = animationValue >= 0.0 ? animationValue : 0.0;
    return Container(
      width: width,
      child: child,
    );
  }
}

Comment: Thanks, this is the first version: https://gist.github.com/kherel/1048888bf4da291b4d79596c2828d131
Comment: there is a bit different what i want to have, that's `elasticOut` when container collapsed, it means three animation, third animation is when `container` collapsed
Comment: hm.. like that?
Comment: @Kherek thanks a lot, i accepted your answer. all of your answers are correct, but there is a bit something different, if you got free time, there are three animation, - :starting to expand(without any animation), first: when container expanded, second when container want to collapse and third animation is when container collapsed, how can i get your previous post which you had answered?


Fetch Outlook contacts from php or using LAMP architecture

Question: I have LAMP architecture at my server and i want to import contacts from outlook into my web app. Also I want generic solution that will run on any browser not just IE.
Is this possible or not? if yes then please let me know.
Thanks in advance.
Comment: im not 100% sure if u can get this info directly from PHP because PHP is a server side language and outlook is client side (unless you are hosting your PHP app and outlook on the same machine). You could export your contacts manually from outlook and create an import script for your PHP app.
Answer: The Outlook desktop client will allow you to export your contacts as a .csv file. You can write a script to import that file and import it using PHP.
If you use the PHP function fgetcsv you can read in the CSV file and parse it as rows of arrays, then push that into what ever storage mechanism you are using on your webapp.
It's also possible to interact with windows.live.com to get contacts from the Outlook live service, using this Outlook.com API. I've had success interfacing with that using the PHP Exchange Web Services library
Comment: Thanks Dorian. The export mechanism works for outlook. Now I have another requirement where I want to fetch contacts from office 365. I tried there APIs in PHP but no luck.


Regions. how can I disable a region? (not disabling blocks)

Question: I want to disable a region, to not show blocks in this region to an specific page. I want this because, I have several blocks (more than 20) so in this case is necessary enter to each block, and configure in what page or pages must not be showed. Well I can do that, I just want to know if exist some way to make this task in a more practical way, or in a programmatically way.
I am using Drupal 6.
Answer: The context module is a very handy way to control blocks on a site which uses them extensively. It allows you to define contexts which show and hide blocks. It will stop the blocks from even being loaded so will help performance.
It makes it much easier to define where and when the blocks appear. Rather than defining things per block you define what blocks appear per context.
This video seems to explain things well.
Answer: You may want to try the Region Visibility module.
They say:

This module allows privileged users to set role or page specific visibility settings for regions, similar to the block visibility settings in Drupal core.

I didn't try it out myself, but it seems useful.
Answer: The quickest way is to unset the region you want hidden in your theme's template.php. For example:
<code>function YOUR_THEME_preprocess_page(&$vars) {
  if (drupal_is_front_page())
    unset($vars['left']);
}
</code>
Comment: thank you! I will change the content of IF to something to get path alias (drupal_get_path_alias) to hide block in specific places. Also I must say that is necessary clean chache to view results (at least to me). very thanks.
Comment: this code actually loads the blocks, but then unsets them.
Comment: True. Another solution I came across was style="display: none"... Unfortunately D6's modular system is lacking when it comes to blocks. To programmatically disable blocks that are configured to show up in a specific region, think [hook_boot()](http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_boot/6), [register_shutdown_function()](http://php.net/manual/en/function.register-shutdown-function.php) and a bit of SQL over {blocks}.


UITableViewController not Calling the UISearchBarDelegate methods

Question: Given the following UITableViewController, why can't I get any of the UISearchBarDelegate methods to be called? I'm omitting the UITableViewDelegate and UITableViewDataSource methods.
#import <UIKit/UIKit.h>

@interface OpportunitySearchViewController : UITableViewController <UISearchBarDelegate>
@end

#import "OpportunitySearchViewController.h"

@interface OpportunitySearchViewController ()
@end

@implementation OpportunitySearchViewController
- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];

    if (self) {
        NSLog(@"initWithCoder:");
    };

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"self=%@ self.view=%@ ", self, [self view]);
}

- (void)viewDidUnload {
    [super viewDidUnload];

    NSLog(@"viewDidUnload");
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    NSLog(@"shouldAutorotateToInterfaceOrientation:");

    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSLog(@"searchBar:textDidChange:");
}
@end

I've confirmed that my Storyboard scene is configured to use the OpportunitySearchViewContoller class and I've confirmed that the UISearchBar on the scene has the First Responder set as it's delegate. Although that might be wrong, but I couldn't find a File's Owner in the Storyboard interface.
Help would be appreciated.
Comment: Is the search bar in your cell? plz show us code in "tableView: cellForRowAtIndexPath:" method.
Comment: Try to create an outlet for you search bar and wire it to the search bar in storyboard and set the delegate in program.
Answer: Don't connect the first responder to your class as the delegate. Drag from the search bar to the controller object itself and make that the connection to the delegate.


Inserting "sponsored content" into a fixed position in a view

Question: So this is an interesting scenario I'm faced with.  Lets say I have a content type called Article.  Within that content type there is a term that is tagged as "sponsored."  The content type also holds other tags like Chicago, Seattle, San Fran, Etc.
The View I have built is simply time based and shows a feed based on time published of all articles.  However I want some special functionality for any article that is tagged as "sponsored."  At the moment the feed looks like this...
1) tag
2) tag
3) tag
4) tag
5) tag
6) tag
This means that if an article is tagged as sponsored is simply falls down the list as new articles are added.  What I'd like to have happen instead is always FIX the 2 latest sponsored articles (maybe in a node queue) in the second and fifth position.  All other articles without the sponsored tag would fall off as normal based on time while the sponsored articles would stay.  So you'd get
1) tag
Sponsored
3) tag
4) tag
Sponsored
6)
Can this even be done in views?  Should I just think about adding it to the view template file in a custom manor?  Thanks
Comment: This isn't something you can do in the views UI. You're going to need to do some custom code. Sorry I don't have the time to show an example. Probably using https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7 you can loop over the results, find the first two which are sponsored, then insert them into the result array at the positions you desire.
Answer: I found a pretty great solution that i hope others can use.  I simply made a new view with my list of sponsored content in a node queue.  I then used the function views_embed_view inside my view template of content and displayed each block at a certain row ID whick looked a bit like this:
<code><?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php print $row; ?>
 </div>
 <?php if ($id == 3): ?>
<?php print views_embed_view('sponsored_content','block_1'); ?>
 <?php endif; ?>
 <?php if ($id == 8): ?>
<?php print views_embed_view('sponsored_content','block_2'); ?>
 <?php endif; ?>
</code>
Answer: You can produce a block in a custom module, using hook_block_info() and hook_block_view() and a content callback for the block, like so:
<code>/**
 * Implements hook_block_info().
 */
function YOUR_MODULE_block_info(){
  $blocks = array();
  $blocks['YOUR_BLOCK_DELTA'] = array(
    'info' => t('NICE NAME FOR YOUR BLOCK');
    'cache' => DRUPAL_CACHE_PER_PAGE,
  )
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function YOUR_MODULE_block_view($delta = '') {
  $block = array();
  switch($delta){
    case 'YOUR_BLOCK_DELTA':
      $block['subject'] = 'YOUR BLOCK TITLE';
      $block['content']['markup'] = your_block_callback();
      break;
  }
  return $block;
}
function your_block_callback() {
      $position = 3;
      $sponsored = YOUR_SPONSORED_CONTENT;
      $query = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('n.status', 1)
        ->condition('n.type', 'YOUR_CONTENT_TYPE');
      $result = $query->execute();
      $return = '';
      $i = 1;
      foreach ($result as $r) {
         $node = node_load($r->nid);
          $teaser = node_view($node, 'teaser');
          if ($i == $position) {
            $return .= $sponsored;
          }
        $i++;
        $return .= render($teaser);
      }
      return $return;
    }
</code>
Replace all dummy text like YOUR_BLOCK_MACHINE_NAME with your own names, and place this in your custom module's .module file. You'll have to add some code to fill in YOUR_SPONSORED_CONTENT. This will produce a list of teasers. You'll have to add conditions and other logic to the $query, of course.can
Comment: So does this block get added inside the view?  I'm assuming i'd place this function within template.php but im unclear as to how this would run for a particular view
Comment: No you'd place this in a custom module, more specifically in the YOUR_MODULE.module file. You also need a YOUR_MODULE.info file. I've edited my answer to make it more complete. On module creation, see https://drupal.org/developing/modules/7
Answer: I think that you can solve this using the Views UI.
I would probably create a view for your content, containing one page display and two attachments like this:

The main view display can hold the 2 sponsored items (appropriate filters needed)
The first attachment display would filter out sponsored items and can hold the first 4 normal items.
The second attachment display would also filter out sponsored items and can display the next number of normal items. For this you can use the offset setting in the pager options, see the screenshot

The first attachment display would be configured to appear before the main content (which are the sponsored items) and the second attachment display would be configured to appear after the main content.
Comment: The only issue I see with that is being able to page through the view to all the other stories within the view.
Comment: @user1792023 Right, that will probably not work and I don't see an obvious code-less solution to that. But then again, you could add a more link that displays another views page display that is just a listing of the normal items. If you want the sponsored ones in each page, then you will probably have to code something.
Comment: That sounds like a decent compromise i suppose.  Time to fight with drupal again


DKIM and how it relates to DMARC reports

Question: I've been tasked with setting up DKIM, SPF and DMARC for a business. I come from more of a development background, so as a result, I've been a bit confused on how to interpret the DMARC reports I'm seeing.
I'm using a DMARC report analyzer (DMARCreport), and it's showing some spam-y emails as DKIM aligned and DKIM verdict "pass". I don't understand how these emails are passing DKIM, since the only service that is set up to sign with DKIM is Google Workspace, and again these emails don't appear to be legitimate emails, and are also failing SPF.
Does "DKIM aligned" in the report mean simply that the From header matched the "d" domain value in the DKIM signature, or does it actually verify the keys using cryptography?
If it does actually cryptographically verify, any idea why I'm seeing spam-y emails showing as DKIM aligned?
Comment: There are a few possible explanations, and I believe each is answered already - please at the very least [edit] your question to include some unambiguous details about the situation you are facing, e.g. report excerpt. I *think* you are looking at messages where the signature was verified & aligned (DMARC is always about the combination of passing the check *and* the relationship to the claimed sender) meaning the message did originate from your authorized systems, but due to **forwarding** outside of your control you no longer recognize the reported sending network address.
Comment: Does this answer your question? [I don't understand DMARC reports regarding my policy](https://serverfault.com/questions/1114105/i-dont-understand-dmarc-reports-regarding-my-policy)
Answer: Since you have mentioned that Google workspace is your only authorized sender, this could be a case of email forwarding. When an email is forwarded, the original message is received by one email server and then re-sent to another email address. In this case, the forwarding server is sending the email on behalf of the original sender (Google workspace in your case), but using its own email server.
If the original sender has set up SPF and DKIM for their domain, it's possible that the forwarded email may fail SPF but pass DKIM.
SPF checks whether the IP address of the sending email server is authorized to send emails for the domain in the From header. In the case of forwarded emails, the email is being sent from the forwarding server, which is not authorized to send emails for the original sender's domain. Therefore, the SPF check may fail.
To confirm if these are forwarded emails you could check whether the selector of these emails are same as that of your authorised sender (google workspace)


How to Sent Auth0 Access Token from Flutter to Node Js Through Headers

Question: class ApiProvider extends ChangeNotifier {
  Future sentToken(Map<String, String> body) async {
    final Uri restApiUrl = Uri.parse("https://localhost:3000/dummy/");

    http.Response response = await http.post(
      restApiUrl,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': "Bearer: ${AuthService.instance.auth0AccessToken}"
      },
      body: jsonEncode(body),
    );
    return response.body;
  }
}

This Function Should to Called While logging to the Auth0 Account are Where to Call this Function to sent Header from flutter to node js
Answer: Just to clarify, I believe what you want to do is

log in with Auth0 and get accessToken
Have a backed with NodJS where it validates Auth0AccessToken and authenticated and authorized user
You need to call the NodeJS backend by passing the headers.

Therefore, once you parsed the Auth0 result after login
   auth0AccessToken = result.accessToken;

then you can call your NodeJS API by passing the Authorization header as you did in the example above however, you have a mistake
class ApiProvider extends ChangeNotifier {
  Future sentToken(Map<String, String> body) async {
    final Uri restApiUrl = Uri.parse("https://localhost:3000/dummy/");

    http.Response response = await http.post(
      restApiUrl,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': "Bearer ${AuthService.instance.auth0AccessToken}"
      },
      body: jsonEncode(body),
    );
    return response.body;
  }
}

It does not need to be a post method if you have a GET method, it should also be fine to send tokens. So your nodeJS can parse it properly.
If you just need to call your API right after login, you can actually do that exactly when you get the result from the auth0 when you want to store your tokens securely in flutter for example:
// /lib/services/auth_service.dart

  login() async {
      final authorizationTokenRequest = AuthorizationTokenRequest(
        AUTH0_CLIENT_ID, AUTH0_REDIRECT_URI,
        issuer: AUTH0_ISSUER,
        scopes: ['openid', 'profile', 'offline_access', 'email'],
      );
      final AuthorizationTokenResponse? result =
          await appAuth.authorizeAndExchangeCode(
        authorizationTokenRequest,
      );
      print(result);
     // you can call it here
  Future sentToken(Map<String, String> body) async {
    final Uri restApiUrl = Uri.parse("https://localhost:3000/dummy/");

    http.Response response = await http.post(
      restApiUrl,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': "Bearer: ${AuthService.instance.auth0AccessToken}"
      },
      body: jsonEncode(body),
    );
    return response.body;
  }

  }

I have written an extensive article about Auth0 and Flutter and you can find it here

Part 1:
https://auth0.com/blog/flutter-authentication-authorization-with-auth0-part-1-adding-authentication-to-an-app/

Part 2:
https://auth0.com/blog/flutter-authentication-authorization-with-auth0-part-2-refresh-tokens-social-logins-more/

Part 3:
https://auth0.com/blog/flutter-authentication-authorization-with-auth0-part-3-adding-real-time-chat-to-the-app/

Part 4:
https://auth0.com/blog/flutter-authentication-authorization-with-auth0-part-4-roles-permissions/
Comment: I read this Article and Implemented the Authentication but i am facing a Issue on ReLogin Once I hit logout the application logged out and i comes to login screen but when i hit again login its throw a error kindly call a method but in Ontap i have called the method what kind of issue is this ?
Comment: mm that's strange, it's hard to debug if you don't show me what you have done, but I can imagine that probably you have some values in your OnTap where after logout it will become NULL and therefore, you cannot call or get that value. is that the case? can you possibly send your error? maybe in another issue.
Comment: Yes its Showing like that after I logged out and try to login again its show try to call a Method Call() like this
Comment: do you have stack trace?
Comment: https://pastebin.com/tgfkiPDj   This is AuthServer Class File
Comment: https://pastebin.com/yRtNy6Tt This is AppState to Navigate to Next Screen after Login
Comment: but where does the error happen? which line? do you have stacktrace?
Comment: No I have to Check that its on Office System Let me Initimate Once i Reach and I think there is one more the loginAction() is Called inside onPress but it show error like this on Top of Stful Widget I have Declared                                                                                The method 'loginAction' isn't defined for the type '_LoginScreenState'.
Try correcting the name to the name of an existing method, or defining a method named 'loginAction'.
Comment: when i called the loginAction like this its Working  widget.loginAction(); what kind of issue is this
Comment: I guess, it's because you are passing LoginActionto a stateful widget `LoginScreen(loginAction, errorMessage),` and therefore in the `state` class of the widget, you must call `widget.loginAction` which is a parameter to the constructor. that's why.
Comment: Uh Okie let me see that and also I will update the issue regarding relogin as soon as possible
Comment: I think you should post another question if you cannot figure it out.


Can you find the value of this limit in a better way?

Question: We have the sequence of real numbers $(x_{n})_{n\geq1}$ defined by $x_{1}>0$ and $$x_{n+1}=\frac{1}{n}\sum_{k=1}^n\sqrt{x_{k}^2+x_{k}}$$ for every $n\geq1$. Show that:
\begin{align}
\text{a)}\quad&\lim_{n\to\infty}\frac{x_{n}}{\ln n}=\frac{1}{2}\\
\text{b)}\quad&\lim_{n\to\infty}\left(\frac{x_{n}}{\ln n}-\frac{1}{2}\right)\frac{\ln n}{\ln\ln n}=-\frac{1}{4}
\end{align}
Ok, so I showed first by induction that $x_{n}>0$ for every $n\geq1$. I rewrote the recursion formula of the sequence: $x_{n+1} = \frac{n-1}{n}x_{n}+\frac{1}{n}\sqrt{x_{n}^2+x_{n}}$ . I showed then the sequence is inscreasing. I supposed that the sequence is upper bounded so it will converge. If the sequence converge then it is a fundamental sequence. So it exists an N natural number such that for every $n>N$ and every $\epsilon>0$ we have $\mid l - x_{n}\mid<\epsilon$, where $l$ is the limit (real number) of the sequence. By giving the value $\frac{l}{8l+2}$ for $\epsilon$ the inequality fails so the sequence is not a fundamental one, so it will not convegre wich is a contradiciton. So the sequence is not upper bounded, so the limit of $x_{n}=\infty$. For a) we can use the Stolz-Cesaro theorem and rewrite $x_{n+1}$ in terms of $x_{n}$ by the "new" recursion formula. If we use conjugation on the square root, then factor $x_{n}$, simplify the argument of the limit by $x_{n}$ and use the fact that the limit of $x_{n}=\infty$, we will get the answer $\frac{1}{2}$. b) is the main problem. Why? Because I could not find a "friendly" solution. I used twice Stolz-Cesaro Theorem and I got pages of ugly calculations and then I used some Taylor series to calculate hard limits. Yes, I got $-\frac{1}{4}$, but with an ugly method. I wonder if someone can find for b) a better solution. I will leave some photos with my ugly solution on b).
Comment: I wonder why the downvotes. Yes, handwritten math is hard on the eyes, but...
Answer: The initial steps are done in the right direction: we rewrite the recurrence as $$n(x_{n+1}-x_n)=\sqrt{x_n^2+x_n}-x_n,$$ observe that $x_n>0$ for each $n>0$, hence $x_{n+1}>x_n$, thus $x_n\to\infty$ as $n\to\infty$ (otherwise $x_n\to x$ for some $x>0$, which would imply $n(x_{n+1}-x_n)\to\sqrt{x^2+x}-x>0$, hence $x_{n+1}-x_n>c/n$ for some $c>0$ and sufficiently large $n$, contradiction). This way we get $$\lim_{n\to\infty}\frac{x_{n+1}-x_n}{\ln(n+1)-\ln n}=\lim_{n\to\infty}n(x_{n+1}-x_n)=\lim_{n\to\infty}\big(\sqrt{x_n^2+x_n}-x_n\big)=\frac12,$$ i.e. $x_n/\ln n\to1/2$ by Stolz–Cesàro. Put $x_n=(\ln n)/2+y_n$ with $y_n=o(\ln n)$; then
\begin{gather}
\frac{n}{2}\ln\left(1+\frac1n\right)+n(y_{n+1}-y_n)=x_n\left(\sqrt{1+\frac1{x_n}}-1\right);\\
n(y_{n+1}-y_n)+\frac12+O\left(\frac1n\right)=\frac12-\frac1{8x_n}+O\left(\frac1{x_n^2}\right);\\
y_{n+1}-y_n=-\frac{1+o(1)}{4n\ln n},
\end{gather}
and we get $y_n/\ln\ln n\to-1/4$ as $n\to\infty$, again by Stolz–Cesàro, since $$\lim_{n\to\infty}(\ln\ln(n+1)-\ln\ln n)n\ln n=1.$$
Comment: what is that o(ln n) ?
Comment: @StefanSolomon: Widely used [notation](https://en.wikipedia.org/wiki/Big_O_notation).


Properly listing notes on a scale by following the 3 guidelines: Alphabetical, No Repeats/Omissions, Don't Mix Sharps or Flats

Question: My question specifically addresses the G Harmonic Minor scale, which I always see listed as: G, A, Bb, C, D, Eb, F#, (G). The scale is listed alphabetically but it contains a mixture of 2 flats and 1 sharp. In order to fix that the only way to rewrite it to fulfill the 3 guidelines is F##, G##, A#, B#, C##, D#, E##, (F##). Is that correct? It just looks so strange and I'm wondering if using the notes listed at the top is an 'acceptable' exception.
Comment: *" [...] contains a mixture of 2 flats and 1 sharp. In order to fix that, the only way to rewrite it [...]"* Well, technically there are more ways to rewrite it with either all sharps or all flats. You'll need double accidentals and beyond, though. Here's my shortcut thought process: G minor has 2 flats. To respell it enharmonically, add/subtract 12 accidentals and respell the tonic like usual - let's try going from 2 flats to 14 flats! That's Abb minor. Now we can change that to harmonic minor, and we end up with an enharmonic respelling that uses only flats: Abb Bbb Cbb Dbb Ebb Fbb Gb!
Comment: And this process can be repeated ad infinitum in either direction for more enharmonic madness... This is all completely tangential to the question, and of course as the answers below mention, there's no reason to actually avoid having sharps and flats together in a scale, but I thought it was interesting enough to comment.
Comment: Related question: [Do scales need to be in alphabetical order?](https://music.stackexchange.com/q/82327/70803).
Answer: Yes, the mixture of sharps and flats is acceptable and standard. Scales like harmonic minor, which are an alteration of the "normal" (i.e., natural minor) scale, will sometimes have both sharps and flats. In the harmonic minor case, the sharp signals that a note has been altered from its expected (key signature) position.
Comment: The mixture of sharps and flats being an acceptable standard (under certain situations anyway) is a relief.  Thank you, I appreciate your input.
Answer: There is no 'don't mix sharps and flats' rule for scales.  As you note, this would make G and D harmonic minor scales very difficult to spell!
There IS a 'don't mix sharps and flats' rule for key signatures though. The F♯ in G harmonic minor scale will always be written as an accidental, not in the key signature.
Answer: Musical notation is based on keys rather than scales. Scales are derived by ordering notes within a key. In major keys, it's simple but in minor keys, two of the scale steps are mutable; they exist with both a lower and upper tone. For simplicity, the key signatures of pieces in minor are usually indicated with the same signature as the relative major. During the Baroque (and perhaps extending a bit in the "Classical" era, minor keys were indicated with fewer sharps or flats than that of the relative major; this practice doesn't make reading easier.
Once I did an experiment of notating minor keys this way. G minor would have a single flat and D minor had no sharps or flats in the signature. Then I notated minor key pieces with the key signature of the relative major, with the seventh degree in its upper form, and with the Baroque style. Then I counted the number of actual accidentals needed in the piece (skipping those unchanged by the different key signatures.) Naturally, I used a computer to perform the transpositions. I found the conventional idea of matching the relative major slightly better. The main point is that the VII chord is common in minor key music; it's often used in descending passages (especially in the bass) and is the root note of the dominant of the relative major. These uses seemed to outweigh the use of a raised seventh step at (some) cadences and in some ascending patterns.
Comment: I took some short Bach pieces (especially the "Dorian Fugue" and a couple of others. I also used some pop music and something Romantic. It wasn't deep enough for a true study, just an hour  About all I could conclude is that rotating G-minor with a key signature of Bb and F# didn't save much (and sometimes lost) over Bb and Eb.
Comment: It shouldn't need too much. Check out the Brown Corpus from Francis and Kucera. They did the best statistical work on English (at the time and it's still good) by choosing small samples. There may be a nice master's project here somewhere. (I'm too old and someone else probably needs a project.)   I wanted to see if there would be any gain by using arbitrary key signatures. My answer was "no," as the current rule has a single generating formula and works well in most cases. It's easier to read a bunch of accidentals that remember arbitrary and pages-old signatures that may change.
Comment: Interesting experiment! What types of pieces and songs did you run the experiment on? Hypothetically, it would be neat to see if the accidental ratios changed across styles and genres or across time...
Comment: I imagine a prohibitively extensive study would be needed for the greatest insight. Thanks for sharing, that was interesting!
Answer: Minor scales are, like most, alphabetically ordered. How otherwise, would those notes appear on the stave? They also bear reference to their relative major partner. Thus the exact same key signature. The fact that with harmonic minors, the leading note is always raised, means that that note (same letter name, remember) will be the altered one. Naturals will go to sharps, flats to naturals.
So, let sleeping dogs lie - if your idea had been considered a better option, wouldn't we all be using it in preferred.
Unfortunately, that leading note isn't reflected in the key sig., although in minor pieces, it isn't always sharpened, and there's also the sometimes sharpened 6th to consider - again not reflected in the key sig.
Check out Bela Bartok, who did some experimentation with differing key signatures.
Comment: Yes, the leading note not being indicated is problematic, which is the main reason for asking the question.  So, your explanation makes sense, especially the 'let sleeping dogs lie' comment.  Thank you, this is very helpful, and I appreciate your input.


Using a generator comprehension to create data frames

Question: Correct me if I'm wrong but a generator comprehension produces a generator object.  If this is the case, then why are the contents of df1, df2, df3 & df4 actual data frames and not generator objects?
In  [1]: import pandas as pd
nrows, ncols = 10, 10
rng = np.random.RandomState(42)
df1, df2, df3, df4 = (pd.DataFrame(rng.rand(nrows, ncols)) for i in range(4))

In  [2]: df1
Out [2]:
          0         1         2  ...         7         8         9
0  0.103124  0.902553  0.505252  ...  0.010838  0.905382  0.091287
1  0.319314  0.950062  0.950607  ...  0.328665  0.672518  0.752375
2  0.791579  0.789618  0.091206  ...  0.887704  0.350915  0.117067
3  0.142992  0.761511  0.618218  ...  0.821860  0.706242  0.081349
4  0.084838  0.986640  0.374271  ...  0.753378  0.376260  0.083501
5  0.777147  0.558404  0.424222  ...  0.468661  0.056303  0.118818
6  0.117526  0.649210  0.746045  ...  0.868599  0.223596  0.963223
7  0.012154  0.969879  0.043160  ...  0.553854  0.969303  0.523098
8  0.629399  0.695749  0.454541  ...  0.280963  0.950411  0.890264
9  0.455657  0.620133  0.277381  ...  0.077735  0.974395  0.986211

Comment: For the same reason that `x,y = [1, 2]` makes `x` and `y` ints instead of lists... because you are *unpacking the contents of the iterable*
Answer: Unpacking a generator object (by doing a, b, c, etc. = (genexp)) causes it to generate all of it's items then gives one item to each of the variables it unpacks to. In your case, each variable (df1, df2, df3, and df4) gets one DataFrame from the generator object because you unpacked the generator to those those variables.


Search Files and Helper Apps

Question: I am new to Drupal.
How do I use the helper apps with the search files module.
were to i put them or how do i apply them?
serach files: http://drupal.org/project/search_files
Answer: I have this installed and am using the search directories part successfully. the attachment submod doesn't seem to work right. but I do have the directory part installed.
Directory Path sites/all/files/pdfs/criminal
The directory path to be searched for files. Relative pathes are kept and currently based on /var/www/html.
URI Path http://docresource.org/sites/all/files/pdfs/criminal
The URI path to retrieve files from the directory above. Usually some http:// download URL. Warning : no test access done.
my PDFs are in the folder shown above. you have to have the relative path and the urL.
you also have to have a helper app installed. I installed xpdf via YUM in Centos.
then, you can adjust the indexing to suit the capacity of your server. I have thousands of PDFs to scan so i have to tweak it.
let me know if you have additional questions.
Comment: oh, there is also a patch that I had to install. i think you had better just read thru this whole post to get an idea of what needs to be done.    https://drupal.org/node/1093268

Search Files and Helper Apps


Closing StreamReader

Question: After getting a response from a server (by sending http request), I try to fetch a content as follows:
HttpEntity entity = response.getEntity();

    if (entity == null) {
        ...
    }

    String content;
    try {
        Reader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        content = IOUtils.toString(reader);
        reader.close();
        EntityUtils.consume(entity);
    } catch (IOException e) {
        ...
    }

Is it necessary to close the reader (reader.close())? Or EntityUtils.consume(entity) is enough?
Answer: You can use the try-with-resources-statement:
try(Reader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"))) {
    content = IOUtils.toString(reader);
    EntityUtils.consume(entity);
} catch (IOException e) {
    ...
}

Which already closes the reader for you.
For Java 6 you should use the following:
Reader reader = null;
try {
    reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
    content = IOUtils.toString(reader);
    EntityUtils.consume(entity);
} catch (IOException e) {
    ...
} finally {
    if(reader != null){
        try {
            reader.close();
        } catch(IOException e){
            // can not be closed
        }
    }
}

Comment: so if I use Java 6, I should close reader in finally section?
Comment: should I consume entity also in finally section?
Comment: @ru51an depends on what that consume does. Is it in any case related to reading the content? Does it access any resources, like files, databases and so on?
Comment: entity is used only in that part of code that I published above
Comment: You might want to call that `EntityUtils.consume()` outside of the try catch. As it doesn't really belong there. You should put the least amount of code into a try-catch block, to minimize the possible errors and failures
Comment: Since the OP is already using `IOUtils` the `finally` block can just be `IOUtils.closeQuietly(reader);` which takes care of the null check and catching a secondary exception.
Answer: It is good practice. When using resources that allow for "cleanup" just go for it.
And the simple way is to use try-with-resources:
try (InputStreamReader isr = new InputStreamReader(entity.getContent(), "UTF-8");
     Reader reader = new BufferedReader()) {
    content = IOUtils.toString(reader);
    EntityUtils.consume(entity);
} catch (IOException e) {
    ...
}

Meaning: the Java language already gives you the means to have that happen automatically.
Comment: Yes. And try to move forward. Java 6 is like: bad idea :-)
Comment: so if I use Java 6, I should close reader in finally section?
Comment: should I consume entity also in finally section?

Closing StreamReader


Add class to field parent with a preprocess hook in a custom module?

Question: Background:
I would like to alter the classes that are added to a rendered field in Drupal 9 in a custom module. I'm trying to use hook_preprocess_field and I'm not sure if this will work or if there is a better alternative.
based on:
https://www.drupal.org/forum/support/module-development-and-code-questions/2017-03-31/add-class-to-field-in-drupal-8
I have the following:
function my_module_preprocess_field__field_pricing_grid_items(&$vars)
{

  foreach(array_keys($vars['items']) as $delta)
  {
    $vars['items'][$delta]['attributes']->setAttribute('class', 'my-class');
  }
}

This works for adding a class but I can't figure out how to add a class to the parent div.
Result

Desired result:

Questions:

How can I add a class to the parent div? Is that possible with this hook?
Would an alternative approach of maybe overriding the field with a template in my module work? The theme template would be field--field-pricing-grid-items.html.twig Is there a way to override the theme with a module?
If neither of these approaches make sense what would be a possible way of achieving this.
Answer: I was going with the wrong approach.
What worked:
I needed to use hook_theme in my /my_module/my_module.module file
function MY_MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field__field_pricing_grid_items' => [
      'base hook' => 'field',
      'path' => $path . '/templates/field',
    ],
  ];
}

then it was easy to override field.html.twig with /my_module/templates/field/field--field-pricing-grid-items.html.twig


SVG animation (blinking) inside of animation (blinking)

Question: So i have page 1 and page 2 which are animated, inside of page 2 there is also animation but problem is that this object shows when page 2 is "hidden". How to prevent that ??
Black square should only be visible when page 2 is visible, but it ignores parent style.

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 612 792" style="enable-background:new 0 0 612 792;" xml:space="preserve">

    <rect x="0.5" y="0.167" fill="#ccc" stroke="#000" width="100" height="100"/>

    <g>

        <g id="page_one" style="z-index:1">
            <rect x="25" y="5" width="50" height="50" fill="red" style=""></rect>
        </g>

        <g id="page_two" style="z-index:-1">
            <rect x="25" y="5" width="50" height="50" fill="white" style=""></rect>
            <g transform="scale(2.9) translate(6,0)">
                <g transform="scale(0.205)translate(1,1)">

                    <g style="z-index:-1">
                        <animate attributeName="visibility" dur="2" repeatCount="indefinite" keyTimes="0;0.5;1" values="visible;hidden;visible"></animate>
                        <rect x="25" y="15" width="50" height="50" fill="black" style=""></rect>
                    </g>
                </g>
            </g>
        </g>

        <animate xlink:href="#page_one" attributeName="visibility" values="visible;hidden" dur="4s" begin="0s" repeatCount="indefinite"></animate>
        <animate xlink:href="#page_two" attributeName="visibility" values="hidden;visible" dur="4s" begin="0s" repeatCount="indefinite"></animate>
    </g>
</svg>

Tried some css styling, z-index but nothing solved issue.
Answer: animate the display property instead.

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 612 792" style="enable-background:new 0 0 612 792;" xml:space="preserve">

    <rect x="0.5" y="0.167" fill="#ccc" stroke="#000" width="100" height="100"/>

    <g>

        <g id="page_one" style="z-index:1">
            <rect x="25" y="5" width="50" height="50" fill="red" style=""></rect>
        </g>

        <g id="page_two" style="z-index:-1">
            <rect x="25" y="5" width="50" height="50" fill="white" style=""></rect>
            <g transform="scale(2.9) translate(6,0)">
                <g transform="scale(0.205)translate(1,1)">

                    <g style="z-index:-1">
                        <animate attributeName="display" dur="2" repeatCount="indefinite" keyTimes="0;0.5;1" values="block;none;block"></animate>
                        <rect x="25" y="15" width="50" height="50" fill="black" style=""></rect>
                    </g>
                </g>
            </g>
        </g>

        <animate xlink:href="#page_one" attributeName="display" values="block;none" dur="4s" begin="0s" repeatCount="indefinite"></animate>
        <animate xlink:href="#page_two" attributeName="display" values="none;block" dur="4s" begin="0s" repeatCount="indefinite"></animate>
    </g>
</svg>


Maintain in-house repository of custom modules?

Question: Whenever a contributed module has a new version, Drupal's update manager will show a notification and allow automatic downloading of the updates. After that, the user is guided through "update.php". Is it possible to get the same automatic treatment for custom modules?
If I develop a few custom modules for a specific site, it would be interesting to get Drupal to look for updates of said custom modules, on a server specified by me, where I'm hosting the modules myself, and treat them like any contributed module. But maybe this goes against good practices?
Answer:
maybe this goes against good practices?

Wouldn't have thought so, providing a central repo for your modules can only be a good thing in my opinion. It's the best way to keep multiple sites up-to-date with changes to custom modules.
What you need is a combination of the Feature Server module:

This module allows you to share features and custom modules on your own website. It lets you create projects and releases, and it produces an update XML feed compatible with the update module in core. In a way it's a highly simplified version of the project module.

And the project status url module .info file setting, for your custom modules:

Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.
Comment: `Feature Server` has exactly the functionality I had in mind. Hopefully it will have a 7.x release eventually... Thank you.
Comment: It doesn't @CamilB, but you can use the D6 version to serve D7 modules - bit confusing but it does work :)
Comment: Yes, I had to read that part three times. But indeed... the D6 site should only care about the `*.info` file of a custom module (or not even care at all...), and won't actually enable the D7 modules it is serving to D7 sites. I'll look into it.


Ratio of sides of triangle $ABC$

Question: If in a triangle $\Delta ABC$ with $a$, $b$ and $c$ as sides
$$\begin{align}\left(Cot\frac{A}{2}\right)^2 +\left(2Cot\frac{B}{2}\right)^2+\left(3Cot\frac{C}{2}\right)^2=\left(\frac{6s}{7r}\right)^2\end{align} \tag{1}$$ where $r$ is inradius and $s$ is SemiPerimeter, then find the ratio $a:b:c$
My try: If $\Delta$ is the area of the triangle we have
$$Cot\frac{A}{2}=\frac{s(s-a)}{\Delta}$$ and $$sr=\Delta$$
Using these in $(1)$ we get
$$ \frac{s^2(s-a)^2}{\Delta^2}+\frac{4s^2(s-b)^2}{\Delta^2}+\frac{9s^2(s-c)^2}{\Delta^2}=\frac{36s^4}{49\Delta^2}$$
$\implies$
$$49\left((s-a)^2+4(s-b)^2+9(s-c)^2\right)=36s^2$$
$\implies$
$$650s^2-98s(a+4b+9c)+49(a^2+4b^2+9c^2)=0$$
since for a triangle $s$ need to be unique, the above equation must have Discriminant Zero $\implies$
$$49(a+4b+9c)^2-650(a^2+4b^2+9c^2)=0$$
$\implies$
$$601a^2+1816b^2+1881c^2=392ab+3528bc+882ac$$
I am stuck up here, please help me.
Answer: You have proved that the proposed condition is equivalent to
$$
(s-a)^2+4(s-b)^2+9(s-c)^2=\frac{36}{49}s^2\tag 1
$$
Note that, by the Cauchy-Schwarz inequality, we have
$$\eqalign{
s&=(s-a)+\frac{1}{2}(2(s-b))+\frac{1}{3}(3(s-c))\cr
&\leq\sqrt{(s-a)^2+4(s-b)^2+9(s-c)^2}\sqrt{1+\frac{1}{4}+\frac{1}{9}}\cr
&\leq\frac{7}{6}\sqrt{(s-a)^2+4(s-b)^2+9(s-c)^2}\cr
}$$
So $(1)$ corresponds to the case of equality in the Cauchy-Schwarz inequality, hence
$$
\frac{s-a}{1}=\frac{2(s-b)}{\frac{1}{2}}=\frac{3(s-c)}{\frac{1}{3}}
$$
that is
$$
s-a=\lambda,\quad s-b=\frac{\lambda}{4},\quad s-c=\frac{\lambda}{9}
$$
for some $\lambda>0$. Adding these equalities we get: $s=\frac{49}{36}\lambda$,
that is
$$
a=\frac{13}{36}\lambda,\quad b=\frac{40}{36}\lambda,\quad c=\frac{45}{36}\lambda
$$
Finally $a:b:c=13:40:45$.$\qquad\square$

Ratio of sides of triangle $ABC$


Get random array from multidimensional array

Question: I have an array like this :
Array
(
 [Test1] => Array
    (
       [id] => 5
     )
 [Test2] => Array
    (
       [id] => 5
    )
 )

I make the : aRandomGames = array_rand ($aGameList, 1 ); but I get only the key like Test1, it's possible to get :
[Test1] => Array
    (
      [id] => 5
    )
Can you help me please ? Thx in advance and sorry for my english
Comment: You *did* read [the fine manual for `array_rand`](http://php.net/array_rand), did you?
Answer: $randomKey = array_rand ($aGameList, 1 );
$aRandomGames = $aGameList[$randomKey];


UIImagePicker freezes

Question: I'm able to call the modal view controller for the image picker, pick the image, and crop it, but when I tap 'done' it doesn't do anything, it just hangs with the done button grayed out.
There are no errors, but the function is called.
<code>- (void)viewDidLoad
{
self.imgPicker = [[UIImagePickerController alloc] init];
self.imgPicker.allowsImageEditing = YES;
self.imgPicker.delegate = self;
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
userImage.image = img;
uploadButton.hidden = NO;
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
NSLog(@"called");
}

- (IBAction)getImage:(id)sender {
[self presentModalViewController:self.imgPicker animated:YES];
}
</code>
Comment: @golergka It's not a bug, by calling `[picker parentViewController]` you would expect `self`, as seen in @Rayfleck's answer. This is because the parent view controller of `picker` is the same controller that presented it in `getImage:`
Comment: Does this bug happen every time?
Answer: Replace
<code> [[picker parentViewController] dismissModalViewControllerAnimated:YES];
</code>
with:
<code> [self dismissModalViewControllerAnimated:YES];
</code>

UIImagePicker freezes


Negative exponents on a quantity in scientific notation considering significant figures

Question: Are there rules that apply to negative exponents with regard to scientific notation?  The specific problem is:
$$\left(6.3\times10^{2}\right)^{-6}$$
I believe the following is correct:
$$\frac{1}{\left(6.3\times10^2\right)^6}$$
However is there a rule that we can apply to the exponent (similar to the rule of multiplying means adding exponents and division means subtracting exponents)? Forgive me as this is a very simple problem, I am back teaching Chem after many years and for some reason this is escaping me.
Comment: not sure what your problem is? Yes, $(6.3\times 10^2)^{-6}=\frac{1}{(6.3\times 10^2)^6}$...
Answer: If I understand the question, then what you wrote is correct.
You can verify properties of exponentiation on corresponding Wikipedia page, for example.
In particular,
\begin{align} \big(\,b^m\,\big)^n &= b^{m\cdot n}&
\text{ and }& & b^{-n} &= \dfrac{1}{b^n} \end{align}
Comment: This is incorrect: $\left(b^m \right)^n = b^{mn}\neq b^{m+n}$.
Comment: @mzp My bad, thank you for correcting my typo
Answer: I think the rule you are looking for is that
$$ \left(x^a\right)^b = x^{ab}.$$
Applying it to your case:
$$\left(6.3\times10^{2}\right)^{-6}=\left(6.3^{-6}\times10^{-12}\right)\approx 1.599398 \times 10^{-17}.$$


What does "judicious extrapolation" mean?

Question: In the article There's more to mathematics than rigour and proofs, there is a term "judicious extrapolation":

It is of course vitally important that you know how to think rigorously, as this gives you the discipline to avoid many common errors and purge many misconceptions. Unfortunately, this has the unintended consequence that "fuzzier" or "intuitive" thinking (such as heuristic reasoning, judicious extrapolation from examples, or analogies with other contexts such as physics) gets deprecated as "non-rigorous".

A Google search for <code>"judicious extrapolation"</code> yields several results, suggesting that "judicious extrapolation" is a term. Some examples are:

"The procedure is based on available data combined with judicious extrapolation of design information on plant structures and equipment."
"Full configuration interaction calculations carried out in conjunction with careful optimization of basis sets and judicious extrapolation schemes"

Wikipedia doesn't mention anything about this.
Is this a term? If yes, what does it mean?
Comment: This is an informal usage... much like "careful extrapolation."  Don't read anything deeper into it.
Comment: I don't think it's a technical term, just an English phrase.
Comment: By interesting terminological coincidence, one of my favorite teaching modes is to present examples of an apparent pattern, and suggest they might be telling us something: "*If there's any justice*, we should have [such-and-such]." I recall once when a student immediately asked, "But *is there any justice*?", to which I responded, "In this case, no." and went on to explain how the pattern failed. ... Anyway, I think the author and I are getting at the same notion: extrapolation isn't a guarantee, but it can drive discussion and exploration, so developing an intuition for it isn't a bad thing.
Answer: The term judicious simply means "with good judgement/sense", so judicious extrapolation is extrapolation that's performed in a scientifically or mathematically reasonable manner. It's not really a set phrase, as the term judicious can be applied to any activity to indicate that it is a reasonable thing to do. It's just an adjective + noun pair, and the meaning of either word individually is unchanged when putting them together.
Answer: It's not a technical term.
Extrapolate (Merriam-Webster meaning #1(b)): to project, extend, or expand (known data or experience) into an area not known or experienced so as to arrive at a usually conjectural knowledge of the unknown area.
Judicious:  having, exercising, or characterized by sound judgment.
Comment: would it be any different if I use "sound extrapolation"?


Erro em sqlite3 foreign ou foreigin

Question: Eu criei um banco de dados em sqlite3 na versão 3.9.2 e tive problemas com a foreign key.
alter table table_01 add column tab_2 integer foreign key references table_02(id);
    // Esse deu erro de sintaxe no foreign key
    alter table table_01 add column tab_2 integer foreigin key references table_02(id);
    // Já esse, adicionou o campo com sucesso.

como está no código, o gdb aceitou foreigin ao invés de foreign, alguém poderia saberia me dizer algo sobre isso?
Comment: De uma olhada nesta documentação: [http://www.sqlite.org/syntaxdiagrams.html#foreign-key-clause](http://www.sqlite.org/syntaxdiagrams.html#foreign-key-clause) me ajudou bastante a entender a syntax e aos limites do sqlite com ForeignKeys.
Answer: Na verdade, ao passar foreigin key, se estiver usando Sqlitestudio, ele entende que você está passando o tipo, junto com o integer. Veja o print da mesma query que rodei aqui:
Query de inserção(idêntica a que você fez):

Como ficou a coluna após inserção:

Pode-se perceber que a coluna foi adicionada como foreign key, mas a sintaxe usada foi ignorada para este fim.
Como pode ser visto nesta resposta do SOEN, a sintaxe correta para essa alteração é:
ALTER TABLE tabela ADD COLUMN coluna TIPO REFERENCES tabela_parente(coluna_parente);

Veja abaixo no print, a coluna adicionada em testes que fiz, executando o comando acima:

Referencias para leitura:
https://www.sqlite.org/lang_altertable.html
https://www.sqlite.org/lang_altertable.html#otheralter (importante a leitura)

Erro em sqlite3 foreign ou foreigin