问:
Split string into two longest palindrome
So I have this string "nmmaddammhelloollehdertr", if we split the string into x = "nmmaddamm" and y = "helloollehdertr" we could find the LPS to be x = "mmaddamm" and y = "helloolleh". We know that this is the biggest palindrome as x has a length of 8, and y has a length of 10. 10 * 8 = 80

I attempted this problem by using dynamic programming with Longest Palindromic Subsequence, noting that I need to split the string at a pivot point creating two strings with the longest size.

A brute-force approach was to try every single palindrome for each subsequence, and that was my attempt:

```<code>using System;

namespace Palindrome
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetLongestPalindrome("nmmaddammhelloollehdertr"));
        }

        static int GetLongestPalindrome(string s)
        {
            int longest = 1;
            for (int i = 0; i < s.Length; ++i)
                longest = Math.Max(longest, GetLongestPalindromeHelper(s.Substring(0, i)) * GetLongestPalindromeHelper(s.Substring(i)));
            return longest;
        }

        static int GetLongestPalindromeHelper(string str)
        {
            if (str.Length == 0)
                return 1;

            /*
             * For a str = "madeam"
             *       || 0 | 1 | 2 | 3 | 4 | 5 ||
             *  _____|| m | a | d | e | a | m ||
             * | 0 m || 1 | 1 | 1 | 1 | 1 |_5_||
             * | 1 a || 0 | 1 | 1 | 1 |_3_| 3 ||
             * | 2 d || 0 | 0 |_1_| 1 | 1 | 1 ||
             * | 3 e || 0 | 0 | 0 | 1 | 1 | 1 ||
             * | 4 a || 0 | 0 | 0 | 0 | 1 | 1 ||
             * | 5 m || 0 | 0 | 0 | 0 | 0 | 1 ||
             *
             */
            int[,] matrix = new int[str.Length, str.Length];

            // i -> row
            // j -> column
            // windowSize -> the numbers of chars in the window

            // each character is a palindrome with a length 1
            for (int i = 0; i < str.Length; ++i)
                matrix[i, i] = 1;

            // we handled windowSize 1, so we start at 2
            for (int windowSize = 2; windowSize <= str.Length; ++windowSize)
            {
                for (int i = 0, j = windowSize - 1; i < str.Length - windowSize + 1; ++i, j = i + windowSize - 1)
                {
                    if (str[i] == str[j])
                        matrix[i, j] = matrix[i + 1, j - 1] + 2;
                    else
                        matrix[i, j] = Math.Max(matrix[i, j - 1], matrix[i + 1, j]);
                }
            }

            return matrix[0, str.Length - 1];
        }
    }
}
</code>```

However, I am sure there is a better way to do this, but I do not know how. Any advice? Also, anyone could point out what the complexity of my code is?

Thanks!

答:
You can do Manacher's Algorithm in Linear time and get the length of all the palindromes. After that, you can process the length to get the maximum length from left and from right, and then with one final loop, you can get your answer.

The total complexity will be O(n).

There are many helpful resources for Manacher's Algorithm including these links:
good explanation, Animation

```<code>static void Main(String[] args) {
    string s = "nmmaddammhelloollehdertr";
    long ans = Manacher(s, s.Length);
    Console.WriteLine(ans);
}
static long Manacher(string s, int N) {
    int i, j, k, rp;
    int[,] R = new int[2, N + 1];
    // rp is the palindrome radius
    // R is a table for storing results (2 rows for even and odd length palindromes)

    // store the maximum length of the palindromes from left and from right here
    int[] MaxFromLeft = new int[N];
    int[] MaxFromRight = new int[N];
    for (i = 0; i < N; i++) {
        MaxFromLeft[i] = 1;
        MaxFromRight[i] = 1;
    }

    // insert guards to iterate easily
    // without having to check going out of index range
    s = "@" + s + "#";

    for (j = 0; j <= 1; j++) {
        R[j, 0] = rp = 0; i = 1;
        while (i <= N) {
            while (s[i - rp - 1] == s[i + j + rp]) rp++;
            R[j, i] = rp;
            k = 1;
            while ((R[j, i - k] != rp - k) && (k < rp)) {
                R[j, i + k] = Math.Min(R[j, i - k], rp - k);
                k++;
            }
            rp = Math.Max(rp - k, 0);
            i += k;
        }
    }

    s = s.Substring(1, N);

    int len     // length of the palindrome
        , st    // start index
        , end;  // end index;
    for (i = 1; i <= N; i++) {
        for (j = 0; j <= 1; j++)
            for (rp = R[j, i]; rp > 0; rp--) {
                len = 2 * rp + j;
                st = i - rp - 1;
                end = st + len - 1;
                // update the maximum length
                MaxFromRight[st] = Math.Max(MaxFromRight[st], len);
                MaxFromLeft[end] = Math.Max(MaxFromLeft[end], len);
            }
    }

    // get the accumulative maximums
    // to avoid doing a second loop inside
    for (i = N - 2, j = 1; i > 1; i--, j++) {
        MaxFromRight[i] = Math.Max(MaxFromRight[i], MaxFromRight[i + 1]);
        MaxFromLeft[j] = Math.Max(MaxFromLeft[j], MaxFromLeft[j - 1]);
    }

    long ans = 0;
    for (i = 0; i < N - 1; i++) {
        ans = Math.Max(ans, MaxFromLeft[i] * MaxFromRight[i + 1]);
    }
    return ans;
}
</code>```

Body:
So I have this string "nmmaddammhelloollehdertr", if we split the string into x = "nmmaddamm" and y = "helloollehdertr" we could find the LPS to be x = "mmaddamm" and y = "helloolleh". We know that this is the biggest palindrome as x has a length of 8, and y has a length of 10. 10 * 8 = 80

I attempted this problem by using dynamic programming with Longest Palindromic Subsequence, noting that I need to split the string at a pivot point creating two strings with the longest size.

A brute-force approach was to try every single palindrome for each subsequence, and that was my attempt:

using System;

namespace Palindrome
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetLongestPalindrome("nmmaddammhelloollehdertr"));
        }

        static int GetLongestPalindrome(string s)
        {
            int longest = 1;
            for (int i = 0; i < s.Length; ++i)
                longest = Math.Max(longest, GetLongestPalindromeHelper(s.Substring(0, i)) * GetLongestPalindromeHelper(s.Substring(i)));
            return longest;
        }

        static int GetLongestPalindromeHelper(string str)
        {
            if (str.Length == 0)
                return 1;

            /*
             * For a str = "madeam"
             *       || 0 | 1 | 2 | 3 | 4 | 5 ||
             *  _____|| m | a | d | e | a | m ||
             * | 0 m || 1 | 1 | 1 | 1 | 1 |_5_||
             * | 1 a || 0 | 1 | 1 | 1 |_3_| 3 ||
             * | 2 d || 0 | 0 |_1_| 1 | 1 | 1 ||
             * | 3 e || 0 | 0 | 0 | 1 | 1 | 1 ||
             * | 4 a || 0 | 0 | 0 | 0 | 1 | 1 ||
             * | 5 m || 0 | 0 | 0 | 0 | 0 | 1 ||
             *
             */
            int[,] matrix = new int[str.Length, str.Length];

            // i -> row
            // j -> column
            // windowSize -> the numbers of chars in the window

            // each character is a palindrome with a length 1
            for (int i = 0; i < str.Length; ++i)
                matrix[i, i] = 1;

            // we handled windowSize 1, so we start at 2
            for (int windowSize = 2; windowSize <= str.Length; ++windowSize)
            {
                for (int i = 0, j = windowSize - 1; i < str.Length - windowSize + 1; ++i, j = i + windowSize - 1)
                {
                    if (str[i] == str[j])
                        matrix[i, j] = matrix[i + 1, j - 1] + 2;
                    else
                        matrix[i, j] = Math.Max(matrix[i, j - 1], matrix[i + 1, j]);
                }
            }

            return matrix[0, str.Length - 1];
        }
    }
}

However, I am sure there is a better way to do this, but I do not know how. Any advice? Also, anyone could point out what the complexity of my code is?

Thanks!

Body:
You can do Manacher's Algorithm in Linear time and get the length of all the palindromes. After that, you can process the length to get the maximum length from left and from right, and then with one final loop, you can get your answer.

The total complexity will be O(n).

There are many helpful resources for Manacher's Algorithm including these links:
good explanation, Animation

static void Main(String[] args) {
    string s = "nmmaddammhelloollehdertr";
    long ans = Manacher(s, s.Length);
    Console.WriteLine(ans);
}
static long Manacher(string s, int N) {
    int i, j, k, rp;
    int[,] R = new int[2, N + 1];
    // rp is the palindrome radius
    // R is a table for storing results (2 rows for even and odd length palindromes)

    // store the maximum length of the palindromes from left and from right here
    int[] MaxFromLeft = new int[N];
    int[] MaxFromRight = new int[N];
    for (i = 0; i < N; i++) {
        MaxFromLeft[i] = 1;
        MaxFromRight[i] = 1;
    }

    // insert guards to iterate easily
    // without having to check going out of index range
    s = "@" + s + "#";

    for (j = 0; j <= 1; j++) {
        R[j, 0] = rp = 0; i = 1;
        while (i <= N) {
            while (s[i - rp - 1] == s[i + j + rp]) rp++;
            R[j, i] = rp;
            k = 1;
            while ((R[j, i - k] != rp - k) && (k < rp)) {
                R[j, i + k] = Math.Min(R[j, i - k], rp - k);
                k++;
            }
            rp = Math.Max(rp - k, 0);
            i += k;
        }
    }

    s = s.Substring(1, N);

    int len     // length of the palindrome
        , st    // start index
        , end;  // end index;
    for (i = 1; i <= N; i++) {
        for (j = 0; j <= 1; j++)
            for (rp = R[j, i]; rp > 0; rp--) {
                len = 2 * rp + j;
                st = i - rp - 1;
                end = st + len - 1;
                // update the maximum length
                MaxFromRight[st] = Math.Max(MaxFromRight[st], len);
                MaxFromLeft[end] = Math.Max(MaxFromLeft[end], len);
            }
    }

    // get the accumulative maximums
    // to avoid doing a second loop inside
    for (i = N - 2, j = 1; i > 1; i--, j++) {
        MaxFromRight[i] = Math.Max(MaxFromRight[i], MaxFromRight[i + 1]);
        MaxFromLeft[j] = Math.Max(MaxFromLeft[j], MaxFromLeft[j - 1]);
    }

    long ans = 0;
    for (i = 0; i < N - 1; i++) {
        ans = Math.Max(ans, MaxFromLeft[i] * MaxFromRight[i + 1]);
    }
    return ans;
}


来源: stackexchange

问:
best way for sorting some arrays
I have some array:

```<code>trade_prices[n]
trade_volumes[n]
trade_dates[n]
trade_tickers[n]
</code>```

and I want to sort them by tickers and then by dates.

how can I sort them?

答: Make a class with constructors and methods in it and declare your arrays as global. You can write a function to sort your arrays.</p>

ContentLicense: CC BY-SA 3.0

Title: best way for sorting some arrays

Body:
I have some array:

trade_prices[n]
trade_volumes[n]
trade_dates[n]
trade_tickers[n]

and I want to sort them by tickers and then by dates.

how can I sort them?


问:
how to make POST action from another server - Laravel
How can i make post request from another server to my laravel server?

I have a website from another provider (lets say domainA.com) , they have CMS system, so I can make my custom pages - the question is, I want to make a form in domainA.com, and post it to domainB.com (my original Server), how can I make it in laravel? As far as I understand I should use api route file for this, is it secure to make such a POST request? because as far as I understand there is no token protection on api requests right?

sorry for my english - i am most interested in security side of such a action - if you show me an example, it would be appreciated.

答:
You are right is not sure about this communication.

What you can do is a chain token code

Start with a code and every time you contact the server b it will give you a new code that you will need to use for the next message.

I know it's not as beautiful as a solution but I do not think of anything else.

You could implement your api framework but you would spend a lot of time


问:
Updating state from child component reactjs
I am trying to refactor component elegantly so we can easily use the component for same usecase.

I have two component,

NewPurchaseOrder (parent comp.)

SelectWarehouse (child comp.)

SelectWarehouse component would render the dropdown list of available warehouses in NewPurchaseOrder component.

The parent component has one state warehouseId to track selected warehouse, to update the parent components state (warehouseId) from the child component i am doing this,

Parent Component

```<code><SelectWarehouse
  updateTarget={ ( ghostValue ) => {
    this.setState( {
      warehouseId: ghostValue // updating the state from child comp. value
    }, () => {
      console.log( 'yokygoky', this.state.warehouseId )
    } )
  } }
/>
</code>```

Child Component

```<code>handleChangeWarehouse( e ) {
  this.setState( {
    selectedWarehouse: e.target.value
  }, () => {
    this.props.updateTarget( e.target.value ) // Updating the parent props
  } )
}
</code>```

Now what i am trying to do, is to send only the state name from the parent instead of sending a function and then update that state of parent component from the child component.
It would look something like this,

```<code><SelectWarehouse
  updateTarget={ warehouseId }
/>
</code>```

And then update the warehouseId from the child component.

Is it possible?

I have tested it by only sending the state with no luck, also its not possible to bind this context with only a simple state.

答:
I think it is not possible to set reset props from the component itself, for more please refer to link.

You should call a method to parent and then set State and pass it to child.

Parent

```<code>updateTarget = (value) => {

   this.setState( {
     warehouseId: value
   })
}
<SelectWarehouse
 updateTarget= {this.updateTarget }
/>
</code>```

Child

```<code>handleChangeWarehouse( e ) {
  this.setState( {
    selectedWarehouse: e.target.value
  }, () => {
    this.props.updateTarget( e.target.value )
  })
}
</code>```

Body:
I am trying to refactor component elegantly so we can easily use the component for same usecase.

I have two component,

NewPurchaseOrder (parent comp.)

SelectWarehouse (child comp.)

SelectWarehouse component would render the dropdown list of available warehouses in NewPurchaseOrder component.

The parent component has one state warehouseId to track selected warehouse, to update the parent components state (warehouseId) from the child component i am doing this,

Parent Component

<SelectWarehouse
  updateTarget={ ( ghostValue ) => {
    this.setState( {
      warehouseId: ghostValue // updating the state from child comp. value
    }, () => {
      console.log( 'yokygoky', this.state.warehouseId )
    } )
  } }
/>

Child Component

handleChangeWarehouse( e ) {
  this.setState( {
    selectedWarehouse: e.target.value
  }, () => {
    this.props.updateTarget( e.target.value ) // Updating the parent props
  } )
}

Now what i am trying to do, is to send only the state name from the parent instead of sending a function and then update that state of parent component from the child component.
It would look something like this,

<SelectWarehouse
  updateTarget={ warehouseId }
/>

And then update the warehouseId from the child component.

Is it possible?

I have tested it by only sending the state with no luck, also its not possible to bind this context with only a simple state.

Body:
I think it is not possible to set reset props from the component itself, for more please refer to link.

You should call a method to parent and then set State and pass it to child.

Parent

updateTarget = (value) => {

   this.setState( {
     warehouseId: value
   })
}
<SelectWarehouse
 updateTarget= {this.updateTarget }
/>

Child

handleChangeWarehouse( e ) {
  this.setState( {
    selectedWarehouse: e.target.value
  }, () => {
    this.props.updateTarget( e.target.value )
  })
}


问:
How to target div#specificDiv in jquery?
I want to ask that how can i target a specific division in Jquery code. In the code below we are targeting "everything", Even if we change this to "div", it will target all the divisions in the file.But my question is that how can we target a specific division, As i want to target at the div with class "particles particles2"

$(document).ready(function() {

  $(document).on('click', function() {
    $('body').jGravity({
      target: 'eveything',
      ignoreClass: 'ignoreMe',
      weight: 25,
      depth: 5,
      drag: true
    });
    // Misc code for demo purposes
    $(this).removeClass('#fountains');

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="template-page"> </div>
<div class="particles particles2 ignoreMe jGravity" id="fountains"></div></code>```

答:
If you want to target a specific class, put the selector in target:

```<code>$(document).ready(function() {

    $(document).on('click', function() {
        $('body').jGravity({
            target: '.particles.particles2',
            ignoreClass: 'ignoreMe',
            weight: 25,
            depth: 5,
            drag: true
        });
        // Misc code for demo purposes
        $(this).removeClass('#fountains');

    });
});
</code>```

Body:
If you want to target a specific class, put the selector in target:

$(document).ready(function() {

    $(document).on('click', function() {
        $('body').jGravity({
            target: '.particles.particles2',
            ignoreClass: 'ignoreMe',
            weight: 25,
            depth: 5,
            drag: true
        });
        // Misc code for demo purposes
        $(this).removeClass('#fountains');

    });
});


问:
Spring Batch Hello World
I'm trying to do this Spring batch tutorial

But I'm getting the following error relating to the jobRepository.

I've read that the jobRepository is mandatory when creating a job but I don't know why it's not being created. I've loaded all my dependencies as per the tutorial.

Could somebody help point me in the right direction? Thanks in advance.

```<code>Jun 03, 2017 8:13:18 PM
    org.springframework.context.support.AbstractApplicationContext
    prepareRefresh
    INFO: Refreshing
    org.springframework.context.support.ClassPathXmlApplicationContext@579bb367:
    startup date [Sat Jun 03 20:13:18 AEST 2017]; root of context hierarchy
    Jun 03, 2017 8:13:18 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/batch/jobs/job-hello-world.xml]
Jun 03, 2017 8:13:18 PM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'helloWorldJob': replacing [Generic bean: class [org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.springframework.batch.core.configuration.xml.JobParserJobFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
Jun 03, 2017 8:13:18 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3532ec19: defining beans [report,itemProcessor,org.springframework.batch.core.scope.internalStepScope,org.springframework.beans.factory.config.CustomEditorConfigurer,org.springframework.batch.core.configuration.xml.CoreNamespacePostProcessor,step1,helloWorldJob,cvsFileItemReader,xmlItemWriter,reportMarshaller]; root of factory hierarchy
Jun 03, 2017 8:13:18 PM org.springframework.oxm.jaxb.Jaxb2Marshaller createJaxbContextFromClasses
INFO: Creating JAXBContext with classes to be bound [class com.mkyong.model.Report]
Jun 03, 2017 8:13:18 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3532ec19: defining beans [report,itemProcessor,org.springframework.batch.core.scope.internalStepScope,org.springframework.beans.factory.config.CustomEditorConfigurer,org.springframework.batch.core.configuration.xml.CoreNamespacePostProcessor,step1,helloWorldJob,cvsFileItemReader,xmlItemWriter,reportMarshaller]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'jobRepository' while setting bean property 'jobRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'jobRepository' is defined
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1134)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
    at com.mkyong.App.main(App.java:18)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'jobRepository' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
    ... 15 more

Process finished with exit code 1
</code>```

答:
First of all, that seems a too complicated tutorial for category - "Hello World".

Secondly, if you are starting now, you shouldn't use XML based configurations - Use annotations based configuration unless you have very compelling reasons to do so - find a Java Configuration based tutorial.

Regarding your error, if you go down that tutorial , in context.xml, he is defining repositories ,

```<code><!-- stored job-meta in memory -->
    <!--
    <bean id="jobRepository"
        class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
        <property name="transactionManager" ref="transactionManager" />
    </bean>
     -->

     <!-- stored job-meta in database -->
    <bean id="jobRepository"
        class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="transactionManager" ref="transactionManager" />
        <property name="databaseType" value="mysql" />
    </bean>
</code>```

You have not shown any code, so I can't be sure as what you are missing.

If you are not using any DB , use commented out bean - MapJobRepositoryFactoryBean but you will have to make sure that some in - memory DB like HSQL , H2 are on your class path. These dependencies are not there.

If you have a mysql database, use existing beans as shown in context.xml and mysql dependency is included.

Title: Spring Batch Hello World

Body:
I'm trying to do this Spring batch tutorial

But I'm getting the following error relating to the jobRepository.

I've read that the jobRepository is mandatory when creating a job but I don't know why it's not being created. I've loaded all my dependencies as per the tutorial.

Could somebody help point me in the right direction? Thanks in advance.

Jun 03, 2017 8:13:18 PM
    org.springframework.context.support.AbstractApplicationContext
    prepareRefresh
    INFO: Refreshing
    org.springframework.context.support.ClassPathXmlApplicationContext@579bb367:
    startup date [Sat Jun 03 20:13:18 AEST 2017]; root of context hierarchy
    Jun 03, 2017 8:13:18 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/batch/jobs/job-hello-world.xml]
Jun 03, 2017 8:13:18 PM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'helloWorldJob': replacing [Generic bean: class [org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.springframework.batch.core.configuration.xml.JobParserJobFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
Jun 03, 2017 8:13:18 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3532ec19: defining beans [report,itemProcessor,org.springframework.batch.core.scope.internalStepScope,org.springframework.beans.factory.config.CustomEditorConfigurer,org.springframework.batch.core.configuration.xml.CoreNamespacePostProcessor,step1,helloWorldJob,cvsFileItemReader,xmlItemWriter,reportMarshaller]; root of factory hierarchy
Jun 03, 2017 8:13:18 PM org.springframework.oxm.jaxb.Jaxb2Marshaller createJaxbContextFromClasses
INFO: Creating JAXBContext with classes to be bound [class com.mkyong.model.Report]
Jun 03, 2017 8:13:18 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3532ec19: defining beans [report,itemProcessor,org.springframework.batch.core.scope.internalStepScope,org.springframework.beans.factory.config.CustomEditorConfigurer,org.springframework.batch.core.configuration.xml.CoreNamespacePostProcessor,step1,helloWorldJob,cvsFileItemReader,xmlItemWriter,reportMarshaller]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'jobRepository' while setting bean property 'jobRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'jobRepository' is defined
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1134)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
    at com.mkyong.App.main(App.java:18)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'jobRepository' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
    ... 15 more

Process finished with exit code 1

Body:
First of all, that seems a too complicated tutorial for category - "Hello World".

Secondly, if you are starting now, you shouldn't use XML based configurations - Use annotations based configuration unless you have very compelling reasons to do so - find a Java Configuration based tutorial.

Regarding your error, if you go down that tutorial , in context.xml, he is defining repositories ,

<!-- stored job-meta in memory -->
    <!--
    <bean id="jobRepository"
        class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
        <property name="transactionManager" ref="transactionManager" />
    </bean>
     -->

     <!-- stored job-meta in database -->
    <bean id="jobRepository"
        class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="transactionManager" ref="transactionManager" />
        <property name="databaseType" value="mysql" />
    </bean>

You have not shown any code, so I can't be sure as what you are missing.

If you are not using any DB , use commented out bean - MapJobRepositoryFactoryBean but you will have to make sure that some in - memory DB like HSQL , H2 are on your class path. These dependencies are not there.

If you have a mysql database, use existing beans as shown in context.xml and mysql dependency is included.


问:
Pass form data to the called activity
How do i get all the user input fields from signupActivity which is currently taking email, passwords and rest of the fields as input from the user and use it in finalactivity.

I already have made the xml layout and wonder how can i display all these fields to a newer activity which is called when signup button is pressed.

My SignupActivity.java:-

```<code>public class SignupActivity extends AppCompatActivity {
    @Bind(R.id.input_name) EditText _nameText;
    @Bind(R.id.input_email) EditText _emailText;
    @Bind(R.id.input_password) EditText _passwordText;
    @Bind(R.id.btn_signup) Button _signupButton;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signing);
        ButterKnife.bind(this);
        _signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  signup();
            }
        });
    }
    public void signup(){
        //call the finalactivity and do the
    }
}
</code>```

And now finally the signup() function should call the activity finalActivity and print the info. Maybe like this-
For eg in the finalactivity i want to display-

Your name is :"name here"

  And your email is :"email here"

My question is different from How do I pass data between Activities in Android application? as i want to pass multiple variables (~50) and obviously dont want to create 50 Intents.

答:
```<code>ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)object);
intent.putExtra("BUNDLE",args);
startActivity(intent);
</code>```

```<code>Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>) args.getSerializable("ARRAYLIST");
</code>```

This would do probably.
How to pass ArrayList of Objects from one to another activity using Intent in android? --source

Title: Pass form data to the called activity

Body:
How do i get all the user input fields from signupActivity which is currently taking email, passwords and rest of the fields as input from the user and use it in finalactivity.

I already have made the xml layout and wonder how can i display all these fields to a newer activity which is called when signup button is pressed.

My SignupActivity.java:-

public class SignupActivity extends AppCompatActivity {
    @Bind(R.id.input_name) EditText _nameText;
    @Bind(R.id.input_email) EditText _emailText;
    @Bind(R.id.input_password) EditText _passwordText;
    @Bind(R.id.btn_signup) Button _signupButton;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signing);
        ButterKnife.bind(this);
        _signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  signup();
            }
        });
    }
    public void signup(){
        //call the finalactivity and do the
    }
}

And now finally the signup() function should call the activity finalActivity and print the info. Maybe like this-
For eg in the finalactivity i want to display-

Your name is :"name here"

  And your email is :"email here"

My question is different from How do I pass data between Activities in Android application? as i want to pass multiple variables (~50) and obviously dont want to create 50 Intents.

Body:
ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)object);
intent.putExtra("BUNDLE",args);
startActivity(intent);

Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>) args.getSerializable("ARRAYLIST");

This would do probably.
How to pass ArrayList of Objects from one to another activity using Intent in android? --source


问:
How to access profile picture with Facebook API in Swift 3?
Earlier I tried to access like this:

```<code>let gr2 : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id,picture.width(198).height(198)"])
gr2.start(completionHandler: { (connection, result2, error) -> Void in
let data = result2 as! [String : AnyObject]
let _loggedInUserSettingRecordName = data["id"] as? String // (forKey: "id") as? String
let profilePictureURLStr = data["picture.data.url"] as? String
</code>```

But profilePictureURLStr is nil now. What is different with Swift 3?

I can see url info is part of it:

```<code>(lldb) po result2
▿ Optional<Any>
  ▿ some : 2 elements
    ▿ 0 : 2 elements
      - .0 : id
      - .1 : 10208273026137463
    ▿ 1 : 2 elements
      - .0 : picture
      ▿ .1 : 1 element
        ▿ 0 : 2 elements
          - .0 : data
          ▿ .1 : 4 elements
            ▿ 0 : 2 elements
              - .0 : is_silhouette
              - .1 : 0
            ▿ 1 : 2 elements
              - .0 : height
              - .1 : 200
            ▿ 2 : 2 elements
              - .0 : url
              - .1 : https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/13418946_10208553701714177_3969269576626117653_n.jpg?oh=add39246ec9693ecead0529ecbbbfc53&oe=5862D7ED
            ▿ 3 : 2 elements
              - .0 : width
              - .1 : 200
</code>```

答:
Also this way works in Swift 3:</p>

```<code>if let picture = data["picture"] as? Dictionary<String,Any> {
                        if let data = picture["data"] as? Dictionary<String,Any> {
                            if let pictureUrl = data["url"] as? String {
                                dict["remote_main_image_url"] = pictureUrl
                            }
                        }
                    }
</code>```

Body:
Earlier I tried to access like this:

let gr2 : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id,picture.width(198).height(198)"])
gr2.start(completionHandler: { (connection, result2, error) -> Void in
let data = result2 as! [String : AnyObject]
let _loggedInUserSettingRecordName = data["id"] as? String // (forKey: "id") as? String
let profilePictureURLStr = data["picture.data.url"] as? String

But profilePictureURLStr is nil now. What is different with Swift 3?

I can see url info is part of it:

(lldb) po result2
▿ Optional<Any>
  ▿ some : 2 elements
    ▿ 0 : 2 elements
      - .0 : id
      - .1 : 10208273026137463
    ▿ 1 : 2 elements
      - .0 : picture
      ▿ .1 : 1 element
        ▿ 0 : 2 elements
          - .0 : data
          ▿ .1 : 4 elements
            ▿ 0 : 2 elements
              - .0 : is_silhouette
              - .1 : 0
            ▿ 1 : 2 elements
              - .0 : height
              - .1 : 200
            ▿ 2 : 2 elements
              - .0 : url
              - .1 : https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/13418946_10208553701714177_3969269576626117653_n.jpg?oh=add39246ec9693ecead0529ecbbbfc53&oe=5862D7ED
            ▿ 3 : 2 elements
              - .0 : width
              - .1 : 200

Body:
Also this way works in Swift 3:

if let picture = data["picture"] as? Dictionary<String,Any> {
                        if let data = picture["data"] as? Dictionary<String,Any> {
                            if let pictureUrl = data["url"] as? String {
                                dict["remote_main_image_url"] = pictureUrl
                            }
                        }
                    }


问:
Grouped alternating row colors with a variation
This is a simple logical problem but I am having a mental block. I have groups of rows as follows:

Observe the following:

Group #1 has 2 records

Group #2 has 2 records

Group #3 has 1 record

Group #4 has 2 records

Group #5 has 1 record

Group #6 has 2 records

I want each record in each group to have the same background color as the other records in the group, yet a different background color from the next grouping after it. So, what I am trying to achieve is:

Both records in group 1 should have a white background color.

Both records in group 2 should have a gray background color.

The sole record in group 3 should have a white background color.

Both records in group 4 should have a gray background color.

...and so forth. So instead of the typical alternating row colors in which each record's bgcolor alternates, I want each group's bgcolor to alternate, while the colors within each group stays consistent with each other.

My current logic does this:

```<code>if($gameID != $previousGameID)
    $rowColor = "#ffffff";
else
    $rowColor = "#F0F0F0";
</code>```

Although that code is PHP, this question is not unique to PHP, it's just a logic problem, which is why I tagged this question with PHP, C#, and JS (3 languages I know). My code above is wrong because it causes the background color to change for each record, rather than for each group of records. The records in each group have the same gameID, and that gameID will be different from all other groups. So the gameID is part of the key to solving this little puzzle, but I can't get my head around the solution.

Note: You cannot assume that each grouping will have either 1 or 2 records. Although my example doesn't show it, on rare occasions there will be 3 records in a group (and all 3 in that case would have the same gameID as each other).

Any ideas?

答:
set a global variable to store the first color, say $rowColor= "#ffffff".
Then in loops

```<code>if($gameId != $previousGameId)
{
    alternateColor();
}
</code>```

then define,

```<code>function alternate()
{
    if($rowColor== "#ffffff")
    {
         $rowColor= "#FOFOFO";
    }
    else
    {
         $rowColor= "$ffffff";
    }
}
</code>```

This should work!!

Body:
This is a simple logical problem but I am having a mental block. I have groups of rows as follows:

Observe the following:

Group #1 has 2 records

Group #2 has 2 records

Group #3 has 1 record

Group #4 has 2 records

Group #5 has 1 record

Group #6 has 2 records

I want each record in each group to have the same background color as the other records in the group, yet a different background color from the next grouping after it. So, what I am trying to achieve is:

Both records in group 1 should have a white background color.

Both records in group 2 should have a gray background color.

The sole record in group 3 should have a white background color.

Both records in group 4 should have a gray background color.

...and so forth. So instead of the typical alternating row colors in which each record's bgcolor alternates, I want each group's bgcolor to alternate, while the colors within each group stays consistent with each other.

My current logic does this:

if($gameID != $previousGameID)
    $rowColor = "#ffffff";
else
    $rowColor = "#F0F0F0";

Although that code is PHP, this question is not unique to PHP, it's just a logic problem, which is why I tagged this question with PHP, C#, and JS (3 languages I know). My code above is wrong because it causes the background color to change for each record, rather than for each group of records. The records in each group have the same gameID, and that gameID will be different from all other groups. So the gameID is part of the key to solving this little puzzle, but I can't get my head around the solution.

Note: You cannot assume that each grouping will have either 1 or 2 records. Although my example doesn't show it, on rare occasions there will be 3 records in a group (and all 3 in that case would have the same gameID as each other).

Any ideas?

Body:
set a global variable to store the first color, say $rowColor= "#ffffff".
Then in loops

if($gameId != $previousGameId)
{
    alternateColor();
}

then define,

function alternate()
{
    if($rowColor== "#ffffff")
    {
         $rowColor= "#FOFOFO";
    }
    else
    {
         $rowColor= "$ffffff";
    }
}

This should work!!


问:
How can I extract a short part of characters from the string with Regular Expression in Python?
Here is my code:

```<code>s = '''I wish I may, I wish I might
Have a dish of fish tonight.'''

import re
m = re.search('w.*m', s)
print(m.group())
</code>```

and I got the result:

```<code>wish I may, I wish I m
</code>```

If I want to get the result only the first half wish I m, how can I revise my code?

Thanks a lot!

答:
Use .*? to match non-greedily.

```<code>>>> s = '''I wish I may, I wish I might
... Have a dish of fish tonight.'''
>>>
>>> import re
>>> m = re.search('w.*?m', s)
>>> m.group()
'wish I m'
</code>```

Body:
Here is my code:

s = '''I wish I may, I wish I might
Have a dish of fish tonight.'''

import re
m = re.search('w.*m', s)
print(m.group())

and I got the result:

wish I may, I wish I m

If I want to get the result only the first half wish I m, how can I revise my code?

Thanks a lot!

Body:
Use .*? to match non-greedily.

>>> s = '''I wish I may, I wish I might
... Have a dish of fish tonight.'''
>>>
>>> import re
>>> m = re.search('w.*?m', s)
>>> m.group()
'wish I m'


答:
In your case :

```<code>$("div.particles.particles2")
</code>```

...will access the specific div tag you want.

Title: How to target div#specificDiv in jquery?

Body:
I want to ask that how can i target a specific division in Jquery code. In the code below we are targeting "everything", Even if we change this to "div", it will target all the divisions in the file.But my question is that how can we target a specific division, As i want to target at the div with class "particles particles2"

$(document).ready(function() {

  $(document).on('click', function() {
    $('body').jGravity({
      target: 'eveything',
      ignoreClass: 'ignoreMe',
      weight: 25,
      depth: 5,
      drag: true
    });
    // Misc code for demo purposes
    $(this).removeClass('#fountains');

  });
});

Body:
In your case :

$("div.particles.particles2")

...will access the specific div tag you want.


问:
nodemcu custom firmware build problems
hello everybody:) I built a firmware with cloud build service. The firmware is master and includes "adc, file, gpio, http, mqtt, net, node, ow, spi, tmr, uart, wifi" and also supports SSL.
Using ESP 07 and the previous version of firmware was nodeMCU 0.9.6 and that was correctly worked but didn't support some modules that i need.
To flash the firmware, i use NodeMCU flasher with these setting:
flasher setting

I upload the binary firmware file to address 0x00000 and esp_init_data_default.bin which is from ESP8266_NONOS_SDK_V1.5.4.1 (downloaded from nodemcu website) to address 0x7c000.
After finishing the upload, module very actively prints garbage on the console.
I uploaded nodeMCU 0.9.6 again to check if the problem  is because of the way i flashed firmware, but it wasn't. The module worked with uploaded nodeMCU 0.9.6 well.

Thank you very much:)

答: You mentioned that garbage was printed to console. This can be an indication of mismatched serial port parameters. It's probably worth spending a couple of minutes playing around working through the speed/parity settings of the tool you are using to display the serial output. Try using Putty or Coolterm for "raw" output as these apps do not try and interpret the response. </p>

Title: nodemcu custom firmware build problems


问:
How to use $http.then response in another method which is called from view in angularjs?
I have view which has a function inside a table td to check whether the td has data stored in database. If td has data, it will red colored:

```<code><tr ng-repeat="row in rows">
            <td ng-repeat="column in columns" style="width: 100px; cursor: pointer"
                ng-style="{background: getWeight(row, column) ? 'red' :  '' }"
                ng-click="onCellselect(row, column)">
                @{{row}}@{{column}}
            </td>
        </tr>
</code>```

JS:

```<code>  $http.get("api/getYardGraphDetails")

    .then(function (r) {
        console.log(r.data)

        $scope.weights =r.data

    })

$scope.getWeight = function (row, column) {
    console.log($scope.weights)

        // See if there's a record with the row and column.
        var record = _.find($scope.weights, {
            row: row,
            column: column
        });

        // Was a record found with the row and column?
        if (record) {
            // If so return its weight.
            return record.weight;
        }

};
</code>```

in $scope.getWeight() function $scope.weights comes from an $http.get response. But console.log($scope.weights) inside $scope.getWeight()  returns undefined

How can i get $scope.weights from $http.get for $scope.getWeight() ?

I think i should call $scope.getWeight() after $http.getreturns data from database. As $http.get is async it doesn't wait for response and that's my $scope.weights doesn't has value in $scope.getWeight().

答:
Assuming that $http.get is invoked on init of the controller, a simple solution would be to guard this with an ng-if. Something like:

```<code><tr ng-if="weights" ng-repeat="row in rows">
    <td ng-repeat="column in columns" style="width: 100px; cursor: pointer"
       ng-style="{background: getWeight(row, column) ? 'red' :  '' }"
       ng-click="onCellselect(row, column)">
       @{{row}}@{{column}}
    </td>
</code>```

That way, the function getWeight() will be invoked only after $scope.weights gets populated. If you need to invoke the http more than once, you should invoke getWeights() from the promise resolve instead.

Will this work or am I missing something?

Body:
I have view which has a function inside a table td to check whether the td has data stored in database. If td has data, it will red colored:

                @{{row}}@{{column}}

JS:

  $http.get("api/getYardGraphDetails")

    .then(function (r) {
        console.log(r.data)

        $scope.weights =r.data

    })

$scope.getWeight = function (row, column) {
    console.log($scope.weights)

        // See if there's a record with the row and column.
        var record = _.find($scope.weights, {
            row: row,
            column: column
        });

        // Was a record found with the row and column?
        if (record) {
            // If so return its weight.
            return record.weight;
        }

};

in $scope.getWeight() function $scope.weights comes from an $http.get response. But console.log($scope.weights) inside $scope.getWeight()  returns undefined

How can i get $scope.weights from $http.get for $scope.getWeight() ?

I think i should call $scope.getWeight() after $http.getreturns data from database. As $http.get is async it doesn't wait for response and that's my $scope.weights doesn't has value in $scope.getWeight().

Body:
Assuming that $http.get is invoked on init of the controller, a simple solution would be to guard this with an ng-if. Something like:

<tr ng-if="weights" ng-repeat="row in rows">
    <td ng-repeat="column in columns" style="width: 100px; cursor: pointer"
       ng-style="{background: getWeight(row, column) ? 'red' :  '' }"
       ng-click="onCellselect(row, column)">
       @{{row}}@{{column}}
    </td>

That way, the function getWeight() will be invoked only after $scope.weights gets populated. If you need to invoke the http more than once, you should invoke getWeights() from the promise resolve instead.

Will this work or am I missing something?


问:
Deploying a newly developed Eclipse Plugin
I have written an Eclpise plugin (an Error Parser for the CDT), and it works just fine in the debugger version of eclipse.  However I cannot for the life of me figure out how to install the plugin into eclipse.  I can export the plugin as a jar file, and it seems to export without errors.  I put the plugin jar file into eclipse\dropins and it is not loaded by eclipse.  If I add it to the plugins directory, no luck.  The features directory also seems to ignore my plugin.

So I thought, OK, I'll try installing it through the GUI.  So I browse to where the plugin archive is and add it as a local update site, but eclipse complains there is no plugin there.

I'm frustrated.  Please help.

答:
Putting the plugin into the eclipse/plugins folder should work. If it doesn't, that usually means Eclipse has cached the plugins configuration for performance reasons. You can force Eclipse to rescan the plugins directory for changes by starting it with the -clean command-line argument.

The typical deployment mechanism for Eclipse is to use features. A feature includes plugins (in your case, probably just one), and can be installed through the Eclipse update manager. To deploy your plugin using a feature, you would do the following:

Create a feature project, and add your plugin to the feature using the feature editor.

Create an update site project, and add your feature to the update site, using the update site editor.

Build the update site. This creates a site.xml file, a features folder, and a plugins folder.

You should then be able to point the Eclipse update manager at the folder or URL containing the site.xml, and install your plugin that way. The advantage of this approach is you can upload the files to a website and deploy remotely.

OwnerDisplayName: David Martin

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jordan


问:
How to transfer data between view controller using segues
I'm trying to pass data using a prepare(for segue:) function but it's showing nil in the second VC. Am I doing anything wrong?

```<code>class ViewController: UIViewController {

    var first : [String] = []

    @IBOutlet weak var passField: UITextField!
    @IBOutlet weak var userID: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func login(_ sender: Any) {
        let user : String = self.userID.text!
        let password : String = self.passField.text!

        if user != "" && password != "" {
            let postString = ["username":user, “password”: password]
            var request = URLRequest(url:URL(string:"http://mydomainhere.com/api/login")!)
            request.httpMethod = "POST"
            request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)
            let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
                if error != nil {
                    print("error=\(error)")
                    return
                }

                do {
                    if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
                        let firstName = json["first_name"] as? String
                        let lastName = json["last_name"] as? String
                        self.first.append(firstName!) //putting into Array
                        self.performSegue(withIdentifier: "loginSegue", sender: self)
                    }
                } catch {
                    print(error)
                }
            }
        }
    }

    // data transfer to another controller
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "loginSegue" {
            let secondController = segue.destination as? SecondVC
            secondController?.name = first //passing to next VC   //* here having the issue its not passing the data to next VC
            print(first)    // here first is printing perfectly
        }
    }
}

// second View Controller
class SecondVC: UIViewController {

    var menu_vc : MenuViewController!
    var name : [String]?    // passing to this Array

    override func viewDidLoad() {
        super.viewDidLoad()
        print(name)    // here printing nil
    }
}
</code>```

答:
Everything seems perfect with the below snippet</p>

```<code>var first : [String] = []

@IBAction func btnTapped(_ sender: Any) {
    let firstName = "iOS Geek"
    self.first.append(firstName)

    self.performSegue(withIdentifier: "MovetoSecVC", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "MovetoSecVC"{

        let secVC = segue.destination as! SecondVC
        secVC.name = first
        print(first) // it'll print here ["iOS Geek"]
    }
}

// Your Second View Controller

class SecondVC: UIViewController {

var menu_vc : MenuViewController!
var name : [String]?    // passing to this Array

override func viewDidLoad() {
    super.viewDidLoad()

    print(name!)    // it'll print here ["iOS Geek"]
    }
}
</code>```

Body:
I'm trying to pass data using a prepare(for segue:) function but it's showing nil in the second VC. Am I doing anything wrong?

class ViewController: UIViewController {

    var first : [String] = []

    @IBOutlet weak var passField: UITextField!
    @IBOutlet weak var userID: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func login(_ sender: Any) {
        let user : String = self.userID.text!
        let password : String = self.passField.text!

        if user != "" && password != "" {
            let postString = ["username":user, “password”: password]
            var request = URLRequest(url:URL(string:"http://mydomainhere.com/api/login")!)
            request.httpMethod = "POST"
            request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)
            let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
                if error != nil {
                    print("error=\(error)")
                    return
                }

                do {
                    if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
                        let firstName = json["first_name"] as? String
                        let lastName = json["last_name"] as? String
                        self.first.append(firstName!) //putting into Array
                        self.performSegue(withIdentifier: "loginSegue", sender: self)
                    }
                } catch {
                    print(error)
                }
            }
        }
    }

    // data transfer to another controller
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "loginSegue" {
            let secondController = segue.destination as? SecondVC
            secondController?.name = first //passing to next VC   //* here having the issue its not passing the data to next VC
            print(first)    // here first is printing perfectly
        }
    }
}

// second View Controller
class SecondVC: UIViewController {

    var menu_vc : MenuViewController!
    var name : [String]?    // passing to this Array

    override func viewDidLoad() {
        super.viewDidLoad()
        print(name)    // here printing nil
    }
}

Body:
Everything seems perfect with the below snippet

var first : [String] = []

@IBAction func btnTapped(_ sender: Any) {
    let firstName = "iOS Geek"
    self.first.append(firstName)

    self.performSegue(withIdentifier: "MovetoSecVC", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "MovetoSecVC"{

        let secVC = segue.destination as! SecondVC
        secVC.name = first
        print(first) // it'll print here ["iOS Geek"]
    }
}

// Your Second View Controller

class SecondVC: UIViewController {

var menu_vc : MenuViewController!
var name : [String]?    // passing to this Array

override func viewDidLoad() {
    super.viewDidLoad()

    print(name!)    // it'll print here ["iOS Geek"]
    }
}


问:
Web Api Controller not hitting during post request
Here is my code
I am giving the data from one page to another
using Jquery Ajax. It is not hitting while giving the data.

```<code>$("#button").click(function () {
            var test = $("#name").val();
            var test1 = $("#username").val();
            var test2 = $("#email").val();
            var test3 = $("#pwd").val();
            var data1 = {
                name: test,
                username: test1,
                email: test2,
                password:test3
            }
            alert("the value is" + test + "" + test1 + "" + test2 + "" + test3);
            $.ajax({
                type: 'POST',
                url: 'http://localhost:54150/api/Login',
                data:data1,
                contentType: 'application/json;charset=utf-8',
                success: function (result) {
                    alert('Data Saved Successfully');
                },
                error: function () {
                    alert("Bad...Really bad");
                }
            });
        });
</code>```

and my controller

```<code>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using AbiApp.Models;

namespace AbiApp.Controllers
{
    public class LoginController : ApiController
    {
        String connStr = System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpPost]

        public void Post([FromBody]login loginmodel)
        {
            try
            {
                using (SqlConnection df = new SqlConnection(connStr))
                {
                    using (SqlCommand de = new SqlCommand())
                    {
                        de.CommandType = System.Data.CommandType.StoredProcedure;
                        de.CommandText = "StoreImageDetails";
                        de.Connection = df;
                        de.Parameters.Add(new SqlParameter("@name", loginmodel.name));
                        de.Parameters.Add(new SqlParameter("@username", loginmodel.username));
                        de.Parameters.Add(new SqlParameter("@email", loginmodel.email));
                        de.Parameters.Add(new SqlParameter("@password", loginmodel.password));
                        df.Open();
                        var dt = de.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ed)
            {
                //ed+Message;
            }
        }
    }
}
</code>```

It is not hitting when called from the Jquery Ajax
Please review the code and
please find the bug

答:
Seems problem with your routing. You can remove

[System.Web.Http.AcceptVerbs("GET", "POST")]

and use attribute routing as below

```<code>[Route("api/Login")]
public void Post([FromBody]login loginmodel)
        {
            try
            {
                using (SqlConnection df = new SqlConnection(connStr))
                {
                    using (SqlCommand de = new SqlCommand())
                    {
                        de.CommandType = System.Data.CommandType.StoredProcedure;
                        de.CommandText = "StoreImageDetails";
                        de.Connection = df;
                        de.Parameters.Add(new SqlParameter("@name", loginmodel.name));
                        de.Parameters.Add(new SqlParameter("@username", loginmodel.username));
                        de.Parameters.Add(new SqlParameter("@email", loginmodel.email));
                        de.Parameters.Add(new SqlParameter("@password", loginmodel.password));
                        df.Open();
                        var dt = de.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ed)
            {
                //ed+Message;
            }
        }
</code>```

Body:
Here is my code
I am giving the data from one page to another
using Jquery Ajax. It is not hitting while giving the data.

$("#button").click(function () {
            var test = $("#name").val();
            var test1 = $("#username").val();
            var test2 = $("#email").val();
            var test3 = $("#pwd").val();
            var data1 = {
                name: test,
                username: test1,
                email: test2,
                password:test3
            }
            alert("the value is" + test + "" + test1 + "" + test2 + "" + test3);
            $.ajax({
                type: 'POST',
                url: 'http://localhost:54150/api/Login',
                data:data1,
                contentType: 'application/json;charset=utf-8',
                success: function (result) {
                    alert('Data Saved Successfully');
                },
                error: function () {
                    alert("Bad...Really bad");
                }
            });
        });

and my controller

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using AbiApp.Models;

namespace AbiApp.Controllers
{
    public class LoginController : ApiController
    {
        String connStr = System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpPost]

        public void Post([FromBody]login loginmodel)
        {
            try
            {
                using (SqlConnection df = new SqlConnection(connStr))
                {
                    using (SqlCommand de = new SqlCommand())
                    {
                        de.CommandType = System.Data.CommandType.StoredProcedure;
                        de.CommandText = "StoreImageDetails";
                        de.Connection = df;
                        de.Parameters.Add(new SqlParameter("@name", loginmodel.name));
                        de.Parameters.Add(new SqlParameter("@username", loginmodel.username));
                        de.Parameters.Add(new SqlParameter("@email", loginmodel.email));
                        de.Parameters.Add(new SqlParameter("@password", loginmodel.password));
                        df.Open();
                        var dt = de.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ed)
            {
                //ed+Message;
            }
        }
    }
}

It is not hitting when called from the Jquery Ajax
Please review the code and
please find the bug

Body:
Seems problem with your routing. You can remove

[System.Web.Http.AcceptVerbs("GET", "POST")]

and use attribute routing as below

[Route("api/Login")]
public void Post([FromBody]login loginmodel)
        {
            try
            {
                using (SqlConnection df = new SqlConnection(connStr))
                {
                    using (SqlCommand de = new SqlCommand())
                    {
                        de.CommandType = System.Data.CommandType.StoredProcedure;
                        de.CommandText = "StoreImageDetails";
                        de.Connection = df;
                        de.Parameters.Add(new SqlParameter("@name", loginmodel.name));
                        de.Parameters.Add(new SqlParameter("@username", loginmodel.username));
                        de.Parameters.Add(new SqlParameter("@email", loginmodel.email));
                        de.Parameters.Add(new SqlParameter("@password", loginmodel.password));
                        df.Open();
                        var dt = de.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ed)
            {
                //ed+Message;
            }
        }


问:
Difference between paging and segmentation
I am trying to understand both paradigms of memory management;however, I fail to see the big picture and the difference between both. Paging consists of taking fixed size pages from a secondary to a primary storage in order to do some task requested by a process. Segmentation consists of assigning to each unit in a process an address space, so they are allowed to grow. I don't quiet see how they are related and that's because there are still a lot of holes in my understanding. Can someone fill them up?</p>

答: You got your answer right there, paging relates with fixed size pages in a storage while segmentation deals with units in a page. 'Segments' are objects in the class 'Page'</p>


问:
How do I update the text inside a textblock everytime I enter something in a textbox?
I now have a WPF app which gives me the result I wanted. It reads the texts inside the three textboxes "aValue", "bValue" and "cValue" and use those to print a quadratic equation inside the TextBlock "quadEqn". The problem is that I need the textblock to display or update the equation the moment a number is entered inside any of the textboxes.

Here's my xaml

```<code><Grid>
    <TextBox x:Name="aValue" KeyDown="TextBox_KeyDown" Text="" .../>
    <TextBox x:Name="bValue" KeyDown="TextBox_KeyDown" Text="" .../>
    <TextBox x:Name="cValue" KeyDown="TextBox_KeyDown" Text="" .../>

        <TextBlock x:Name="quadEqn" Text="" .../>
</Grid>
</code>```

and the code behind

```<code>    private void TextBox_KeyDown(object sender, RoutedEventArgs e)
    {
        sendValuesToEqn();
    }

    public void sendValuesToEqn()
    {
        double a, b, c;
        if(aValue.Text=="") a = 0;
        else a = double.Parse(aValue.Text);

        if (bValue.Text == "") b = 0;
        else b = double.Parse(bValue.Text);

        if (cValue.Text == "") c = 0;
        else c = double.Parse(cValue.Text);

        writeEquation(a, b, c);
    }

    public void writeEquation(double a, double b, double c)
    {
        if(a==0)
        {
            if(b==0)
            {
                if(c==0)
                {
                    quadEqn.Text = "";
                }
                else
                {
                    quadEqn.Text = c.ToString();
                }
            }
            else
            {
                if(c==0)
                {
                    quadEqn.Text = b + "x";
                }
                else
                {
                    quadEqn.Text = b + "x + " + c;
                }
            }
        }
        else
        {
            if(b==0)
            {
                if(c==0)
                {
                    quadEqn.Text = a + "x\xB2";
                }
                else
                {
                    quadEqn.Text = a + "x\xB2 + " + c;
                }
            }
            else
            {
                if(c==0)
                {
                    quadEqn.Text = a + "x\xB2 + " + b + "x";
                }
                else
                {
                    quadEqn.Text = a + "x\xB2 + " + b + "x + " + c;
                }
            }
        }
    }
</code>```

答:
I believe the best solution is to imlement described logic via MVVM rather than via code behind.

In your view model you should create three string properties for each TextBox:

```<code>public string A { get { ... } set { ... } }
public string B { get { ... } set { ... } }
public string C { get { ... } set { ... } }
</code>```

Then bind Text property of TextBox'es to these properties. Don't forget to implement INotifyPropertyChanged in view-model class and to fire PropertyChanged in setters of the view-model properties.

Then create a property for the equation TextBlock:

```<code>public string Equation { get { ... } set { ... } }
</code>```

Also fire PropertyChanged in setter of this property. Bind Text property of the equation TextBlock to it.

In setters of A, B, C call a method which will take these three values and will construct an equation. When the equation constructed set it to the Equation property of the view-model.

To change equation immidiately as you typing at TextBox'es in their bindings set UpdateSourceTrigger=PropertyChanged.

Body:
I now have a WPF app which gives me the result I wanted. It reads the texts inside the three textboxes "aValue", "bValue" and "cValue" and use those to print a quadratic equation inside the TextBlock "quadEqn". The problem is that I need the textblock to display or update the equation the moment a number is entered inside any of the textboxes.

Here's my xaml

<Grid>
    <TextBox x:Name="aValue" KeyDown="TextBox_KeyDown" Text="" .../>
    <TextBox x:Name="bValue" KeyDown="TextBox_KeyDown" Text="" .../>
    <TextBox x:Name="cValue" KeyDown="TextBox_KeyDown" Text="" .../>

        <TextBlock x:Name="quadEqn" Text="" .../>
</Grid>

and the code behind

    private void TextBox_KeyDown(object sender, RoutedEventArgs e)
    {
        sendValuesToEqn();
    }

    public void sendValuesToEqn()
    {
        double a, b, c;
        if(aValue.Text=="") a = 0;
        else a = double.Parse(aValue.Text);

        if (bValue.Text == "") b = 0;
        else b = double.Parse(bValue.Text);

        if (cValue.Text == "") c = 0;
        else c = double.Parse(cValue.Text);

        writeEquation(a, b, c);
    }

    public void writeEquation(double a, double b, double c)
    {
        if(a==0)
        {
            if(b==0)
            {
                if(c==0)
                {
                    quadEqn.Text = "";
                }
                else
                {
                    quadEqn.Text = c.ToString();
                }
            }
            else
            {
                if(c==0)
                {
                    quadEqn.Text = b + "x";
                }
                else
                {
                    quadEqn.Text = b + "x + " + c;
                }
            }
        }
        else
        {
            if(b==0)
            {
                if(c==0)
                {
                    quadEqn.Text = a + "x\xB2";
                }
                else
                {
                    quadEqn.Text = a + "x\xB2 + " + c;
                }
            }
            else
            {
                if(c==0)
                {
                    quadEqn.Text = a + "x\xB2 + " + b + "x";
                }
                else
                {
                    quadEqn.Text = a + "x\xB2 + " + b + "x + " + c;
                }
            }
        }
    }

Body:
I believe the best solution is to imlement described logic via MVVM rather than via code behind.

In your view model you should create three string properties for each TextBox:

public string A { get { ... } set { ... } }
public string B { get { ... } set { ... } }
public string C { get { ... } set { ... } }

Then bind Text property of TextBox'es to these properties. Don't forget to implement INotifyPropertyChanged in view-model class and to fire PropertyChanged in setters of the view-model properties.

Then create a property for the equation TextBlock:

public string Equation { get { ... } set { ... } }

Also fire PropertyChanged in setter of this property. Bind Text property of the equation TextBlock to it.

In setters of A, B, C call a method which will take these three values and will construct an equation. When the equation constructed set it to the Equation property of the view-model.

To change equation immidiately as you typing at TextBox'es in their bindings set UpdateSourceTrigger=PropertyChanged.


问:
How to convert Pytorch autograd.Variable to Numpy?
The title says it all. I want to convert a PyTorch autograd.Variable to its equivalent numpy array. In their official documentation they advocated using a.numpy() to get the equivalent numpy array (for PyTorch tensor). But this gives me the following error:

Traceback (most recent call last): File "stdin", line 1, in module
  File
  "/home/bishwajit/anaconda3/lib/python3.6/site-packages/torch/autograd/variable.py",
  line 63, in getattr    raise AttributeError(name) AttributeError:
  numpy

Is there any way I can circumvent this?

答:
Two possible case

Using GPU: If you  try to convert a cuda float-tensor directly to numpy like shown below,it will throw an error.

x.data.numpy()

RuntimeError: numpy conversion for FloatTensor is not supported

So, you cant covert a cuda float-tensor directly to numpy, instead you have to convert it into a cpu float-tensor first, and try converting into numpy, like shown below.

x.data.cpu().numpy()

Using CPU: Converting a CPU tensor is straight forward.

x.data.numpy()


问:
Java: how to modify instance variable of a child class
The story goes like this:

I have an abstract class called Algorithms and a lot of classes that extend it. Some of them have parameters to tune. Some have none, and some have up to 5.

I would like to have a method in Algorithms that can tune an arbitrary parameter. e.g.:

```<code>public static void tune (String paramName, double minValue, double MaxValue)
{ ... }
</code>```

So that I can call it like this on 'class SoftRankBoots extends Algorithm':

```<code>Algorithm srb = new SoftRankBoost();
srb.tune("delta", 0, 1);
</code>```

Note that SoftRankBoost has an instance variable 'double delta';

How can I achieve this?

Thank you.

答:
Take a look at the Reflections API:

http://download.oracle.com/javase/tutorial/reflect/member/index.html

http://download.oracle.com/javase/tutorial/reflect/member/fieldValues.html

Last link contains example source code.

Note: If you need reflection in Java, then your design may be not as clean, as it could be.

Body:
The story goes like this:

I have an abstract class called Algorithms and a lot of classes that extend it. Some of them have parameters to tune. Some have none, and some have up to 5.

I would like to have a method in Algorithms that can tune an arbitrary parameter. e.g.:

public static void tune (String paramName, double minValue, double MaxValue)
{ ... }

So that I can call it like this on 'class SoftRankBoots extends Algorithm':

Algorithm srb = new SoftRankBoost();
srb.tune("delta", 0, 1);

Note that SoftRankBoost has an instance variable 'double delta';

How can I achieve this?

Thank you.


问:
Get Unique records in Spark
I have a dataframe df as mentioned below:

```<code>**customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
     1               A            1           ABC            123         1
     3               Z            r           ERF            789         2
     2               B            X           ABC            123         2
     2               B            X           DEF            456         3
     1               A            1           DEF            456         2
</code>```

I want to create a new dataframe df2, which will have only unique customer ids, but as rule_name and rule_id columns are different for same customer in data, so I want to pick those records which has highest priority for the same customer, so my final outcome should be:

```<code> **customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
         1               A            1           ABC            123         1
         3               Z            r           ERF            789         2
         2               B            X           ABC            123         2
</code>```

Can anyone please help me to achieve it using Spark scala. Any help will be appericiated.

答:
You basically want to select rows with extreme values in a column. This is a really common issue, so there's even a whole tag greatest-n-per-group. Also see this question SQL Select only rows with Max Value on a Column which has a nice answer.

Here's an example for your specific case.

Note that this could select multiple rows for a customer, if there are multiple rows for that customer with the same (minimum) priority value.

This example is in pyspark, but it should be straightforward to translate to Scala

```<code># find best priority for each customer. this DF has only two columns.
cusPriDF = df.groupBy("customers").agg( F.min(df["priority"]).alias("priority") )
# now join back to choose only those rows and get all columns back
bestRowsDF = df.join(cusPriDF, on=["customers","priority"], how="inner")
</code>```

Title: Get Unique records in Spark

Body:
I have a dataframe df as mentioned below:

**customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
     1               A            1           ABC            123         1
     3               Z            r           ERF            789         2
     2               B            X           ABC            123         2
     2               B            X           DEF            456         3
     1               A            1           DEF            456         2

I want to create a new dataframe df2, which will have only unique customer ids, but as rule_name and rule_id columns are different for same customer in data, so I want to pick those records which has highest priority for the same customer, so my final outcome should be:

 **customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
         1               A            1           ABC            123         1
         3               Z            r           ERF            789         2
         2               B            X           ABC            123         2

Can anyone please help me to achieve it using Spark scala. Any help will be appericiated.

Body:
You basically want to select rows with extreme values in a column. This is a really common issue, so there's even a whole tag greatest-n-per-group. Also see this question SQL Select only rows with Max Value on a Column which has a nice answer.

Here's an example for your specific case.

Note that this could select multiple rows for a customer, if there are multiple rows for that customer with the same (minimum) priority value.

This example is in pyspark, but it should be straightforward to translate to Scala

# find best priority for each customer. this DF has only two columns.
cusPriDF = df.groupBy("customers").agg( F.min(df["priority"]).alias("priority") )
# now join back to choose only those rows and get all columns back
bestRowsDF = df.join(cusPriDF, on=["customers","priority"], how="inner")


问:
List comprehension for Pythagorean Triples
I am new to Python and would like to learn how to use list comprehension.

I have this code that prints a list of Pythagorean Triples less than the user-input value n:

```<code>n = int(input("Enter the value of n:"))

a = 0
b = 0
c = 0
m = 2
triples = []

while c < n:
    for i in range(1, m, 1):
        a = m*m - i*i
        b = 2*m*i
        c = m*m + i*i
        if c > n:
            break
        triples.append((a, b, c))
    m += 1

print(triples)
</code>```

It kinda works but I want to do the same using list comprehension in Python how can we do that?

For example if I input 17 the output should be [(3,4,5), (8,6,10),(5,12,13), (15,8,17), (9,12,15)] however I am not getting (9,12,15).

答:
You can use itertools. Try this -

```<code>import itertools

n = int(input("Enter the value of n:"))

print([(a,b,c) for a, b, c in itertools.product(range(1,n+1), repeat=3) if a**2 + b**2 == c**2])
</code>```

To know more about itertools and product follow this link -
https://docs.python.org/3/library/itertools.html#itertools.product

Using product we get a tuple of 3 elements which we unpack to three variables a, b, c and used comprehension to include only those tuple which satisfies the if condition.

This code however generates duplicates like (3,4,5) and (4,3,5)

To remove the duplicates you can easily modify the if statement like this -

```<code>print([(a,b,c) for a, b, c in itertools.product(range(1,n+1), repeat=3) if a < b < c and a**2 + b**2 == c**2])
</code>```

This modified code will get you following output for n=17 -

```<code>[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15)]
</code>```

Body:
I am new to Python and would like to learn how to use list comprehension.

I have this code that prints a list of Pythagorean Triples less than the user-input value n:

n = int(input("Enter the value of n:"))

a = 0
b = 0
c = 0
m = 2
triples = []

while c < n:
    for i in range(1, m, 1):
        a = m*m - i*i
        b = 2*m*i
        c = m*m + i*i
        if c > n:
            break
        triples.append((a, b, c))
    m += 1

print(triples)

It kinda works but I want to do the same using list comprehension in Python how can we do that?

For example if I input 17 the output should be [(3,4,5), (8,6,10),(5,12,13), (15,8,17), (9,12,15)] however I am not getting (9,12,15).

Body:
You can use itertools. Try this -

import itertools

n = int(input("Enter the value of n:"))

print([(a,b,c) for a, b, c in itertools.product(range(1,n+1), repeat=3) if a**2 + b**2 == c**2])

To know more about itertools and product follow this link -
https://docs.python.org/3/library/itertools.html#itertools.product

Using product we get a tuple of 3 elements which we unpack to three variables a, b, c and used comprehension to include only those tuple which satisfies the if condition.

This code however generates duplicates like (3,4,5) and (4,3,5)

To remove the duplicates you can easily modify the if statement like this -

print([(a,b,c) for a, b, c in itertools.product(range(1,n+1), repeat=3) if a < b < c and a**2 + b**2 == c**2])

This modified code will get you following output for n=17 -

[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15)]


问:
How to configure my app with capability "PrivateNetworkClientServer" and keep possibility to pass "WACK" test
I am working on  Apache Cordova Win 10 Windows-x86 Store app for the data exchanging with the  microcomputers collecting measurements, connected entirely to a local network.

I tested this app  with capability "PrivateNetworkClientServer"  and
deployed it in a form of "*.appx" package.  It is working.

But  "PrivateNetworkClientServer" capability is forbidden for Windows Store
with the setting in "package.windows10.appxmanifest" as this:

"uap:Rule Match="ms-appx-web:///" Type="include" WindowsRuntimeAccess="all" "

I have tried to change this setting or remove it (by default WindowsRuntimeAccess="none"),
but after running "build" this part of manifest was returned to its initial state.

How to configure my app with capability "PrivateNetworkClientServer" and keep
possibility to pass "WACK" test.

I  appreciate any suggestions.
Thank you.

答: To have access from my Win Store App to web API in the local network I am using the "Fiddler4" exemption for now, but still hope to find more simple solution. The same Cordova app, but built with Visual Studio for Android, works in the same local network without any quirks.</p>


问:
One Script Run Properly,Both Script Not Run
if i run one of these below scripts then run properly, but if i run both

    of the

    scripts then run only last script.but i want to run both of this scripts, then how to solve , My scripts codes are below

```<code><!-- JS -->
<link rel="stylesheet" href="date style/date.css">
<script src="date style/1.js"></script>
<script src="date style/2.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
<script>
$( function() {
$( "#datepicker1" ).datepicker();
} );
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name,
course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</code>```

答:
Here is how you can add JQuery and run both the scripts:

```

Body:
if i run one of these below scripts then run properly, but if i run both

    of the

    scripts then run only last script.but i want to run both of this scripts, then how to solve , My scripts codes are below

<link rel="stylesheet" href="date style/date.css">

Body:
Here is how you can add JQuery and run both the scripts:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="date style/1.js"></script>
<script src="date style/2.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $("#datepicker, #datepicker1").datepicker();
  });

  function my_validate_func() {
    var name = $('#name').val();
    var year = $('#year').val();
    var course = $('#course').val();
    var branch_name = $('#branch_name').val();
    if ($('#name').val() != "" && $('#year').val() != "" &&
      $('#course').val() != "" && $('#branch_name').val() != "") {
      $.ajax({
        type: "POST",
        url: 'roll.php',
        data: {
          name: name,
          year: year,
          branch_name: branch_name,
          course: course
        },
        success: function(response) {
          $('#roll').val(response);
        }
      });
    }
  }
</script>


问:
Javascript: Nav bar disappears when scrolling up and reaches the top
I have created a navigation bar on my website (still in development). This navigation bar appears when a visitor is scrolling up. However, the nav bar remains all the way to the top. At the top I have the original menu, so need to have the nav bar as well.

What I would like to achieve is that the menu bar disappears as soon as the visitor hits a certain point, like hitting a div and it disappears. So far no luck with it. I use -70px (position:fixed) to place the nav bar outside the viewport and make it via Javascript appear when a visitor is scrolling up.

This is the Javascript for the nav bar:

```<code>var lastScrollTop = pageYOffset || document.documentElement.scrollTop;

window.addEventListener("scroll", function() {
   var st = window.pageYOffset || document.documentElement.scrollTop;
   if (st > lastScrollTop) {
// Scroll Down

$('.navbar').css({
   "transform": "translate3d(0,-70px,0)"
});

} else {
 // Scroll Up

$('.navbar').css({
   "transform": "translate3d(0,70px,0)"
});
}
   lastScrollTop = st;
}, false);
</code>```

Any help to make the nav bar disappear when hitting a certain div scrolling up will be much appreciated. Thanks in advance!

This is the closest I got, see below. Basically it does what I need (disable the nav bar in a certain area, in this case 350px from the bottom). I just need it to be the top, not the bottom.

```<code>$(window).scroll(function() {
var pxFromBottom = 350;
if ($(window).scrollTop() + $(window).height() > $(document).height() - pxFromBottom) {
$('.navbar').css({
  "transform": "translate3d(0,-70px,0)"
});
}
});
</code>```

答:
Update: with some trial and error I managed to get it to work. I've added a second condition which hides the menu bar when scrolling up. I added this part:
if ((st > lastScrollTop) || ($(this).scrollTop() < 500)) {
This is the condition by which the nav bar hides when it comes at 500 px from the top.

```<code>var lastScrollTop = pageYOffset || document.documentElement.scrollTop;

window.addEventListener("scroll", function() {
  var st = window.pageYOffset || document.documentElement.scrollTop;
  if ((st > lastScrollTop) || ($(this).scrollTop() < 500)) {
    // Scroll Down
    $('.navbar').css({
      "transform": "translate3d(0,-70px,0)"
    });
  } else {
    // Scroll Up
    $('.navbar').css({
      "transform": "translate3d(0,70px,0)"
    });
  }
  lastScrollTop = st;
   }, false);
</code>```

Body:
I have created a navigation bar on my website (still in development). This navigation bar appears when a visitor is scrolling up. However, the nav bar remains all the way to the top. At the top I have the original menu, so need to have the nav bar as well.

What I would like to achieve is that the menu bar disappears as soon as the visitor hits a certain point, like hitting a div and it disappears. So far no luck with it. I use -70px (position:fixed) to place the nav bar outside the viewport and make it via Javascript appear when a visitor is scrolling up.

This is the Javascript for the nav bar:

var lastScrollTop = pageYOffset || document.documentElement.scrollTop;

window.addEventListener("scroll", function() {
   var st = window.pageYOffset || document.documentElement.scrollTop;
   if (st > lastScrollTop) {
// Scroll Down

$('.navbar').css({
   "transform": "translate3d(0,-70px,0)"
});

} else {
 // Scroll Up

$('.navbar').css({
   "transform": "translate3d(0,70px,0)"
});
}
   lastScrollTop = st;
}, false);

Any help to make the nav bar disappear when hitting a certain div scrolling up will be much appreciated. Thanks in advance!

This is the closest I got, see below. Basically it does what I need (disable the nav bar in a certain area, in this case 350px from the bottom). I just need it to be the top, not the bottom.

$(window).scroll(function() {
var pxFromBottom = 350;
if ($(window).scrollTop() + $(window).height() > $(document).height() - pxFromBottom) {
$('.navbar').css({
  "transform": "translate3d(0,-70px,0)"
});
}
});

Body:
Update: with some trial and error I managed to get it to work. I've added a second condition which hides the menu bar when scrolling up. I added this part:
if ((st > lastScrollTop) || ($(this).scrollTop() < 500)) {
This is the condition by which the nav bar hides when it comes at 500 px from the top.

var lastScrollTop = pageYOffset || document.documentElement.scrollTop;

window.addEventListener("scroll", function() {
  var st = window.pageYOffset || document.documentElement.scrollTop;
  if ((st > lastScrollTop) || ($(this).scrollTop() < 500)) {
    // Scroll Down
    $('.navbar').css({
      "transform": "translate3d(0,-70px,0)"
    });
  } else {
    // Scroll Up
    $('.navbar').css({
      "transform": "translate3d(0,70px,0)"
    });
  }
  lastScrollTop = st;
   }, false);