text:
Q: Maintain whitespace in JAXB with xs:any and mixed content I have a schema with an xs:any element. This element may contain other elements that have mixed content. I'm trying to use JAXB to unmarshall it into Java objects (with the 'any' as an Element).
From the schema:
<xs:element name="a">
    <xs:complexType>
        <xs:sequence>
            <xs:any processContents="lax"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

In general, this works. But when handling elements with mixed content, whitespace between nested nodes is lost.
test.xml:
<foo>Hello World</foo>

Unmarshalling like this:
JAXBContext jc = JAXBContext.newInstance(A.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
InputStream inputStream = this.getClass().getResourceAsStream("/data/test.xml");
A a = (A) unmarshaller.unmarshal(inputStream);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(a, System.out);

Results in this:
<foo>HelloWorld</foo>

I lose the space between the child tags of the <foo> element. I'm certain that it's the unmarshal step that takes the whitespace out here, but I do need it to survive the round trip.
Note that it's only whitespace-only text content that's removed. This works as desired:
<foo>Hello to you World</foo>

I tried adding xml:space="preserve" (see, for example, JAXB: How to keep consecutive spaces as they are in source XML during unmarshalling), but that has no effect on whitespace between elements. I've tried with processContents set to each of strict, lax, and skip, none of which helped.

A: After facing a similar issue I could come up with the following solution (to this specific scenario, as for some other complex XML structures it doesn't work perfectly).
package com.stackoverflow.answers;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.transform.stream.StreamSource;

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.w3c.dom.Element;

public class XmlAnyElementWithWhiteSpacesTest {

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name = "a")
    private static class A {

        @XmlAnyElement
        @XmlMixed
        private List<Element> elements;
    }

    private static final String SAMPLE = "<foo>Hello World</foo>";

    @Test
    public void shouldParseAndSerializeKeepingWhiteSpaceElements() throws JAXBException {
        // given
        JAXBContext jc = JAXBContext.newInstance(A.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        InputStream inputStream = new ByteArrayInputStream(SAMPLE.getBytes(StandardCharsets.UTF_8));
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        // when
        JAXBElement a = unmarshaller.unmarshal(new StreamSource(inputStream), A.class);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        marshaller.marshal(a.getValue(), outputStream);
        String actual = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
        // then
        assertEquals(SAMPLE, actual);
    }

}

The key points here are:

*

*Usage of @XmlMixed annotation

*Usage of StreamSource
You can use either List<Object> or List<Element> for your "XML any content" property.


text:
Q: "#include errors detected" and "cannot open source file" #include <cmath>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
#include <iostream>

line2: "#include errors detected based on information provided by the configurationProvider setting."
line2&3: "cannot open source file"
My CMakeLists.txt is
cmake_minimum_required (VERSION 3.22.1)
project (Transformation)

find_package(Eigen3 REQUIRED)
include_directories(EIGEN3_INCLUDE_DIR)
message("${EIGEN3_INCLUDE_DIR}")

add_executable (Transformation main.cpp)

and its output is
...
[cmake] /usr/local/include/eigen3
[cmake] Not searching for unused variables given on the command line.
[cmake] -- Configuring done
[cmake] -- Generating done
[cmake] -- Build files have been written to:
...

It seems cmake has found eigen3 with path "/usr/local/include/eigen3" but #include still reports errors.
I have also added eigen3 alias path into the includePath. My c_cpp_properties.json is
{
    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/local/include"
            ],
            "defines": [],
            "macFrameworkPath": [],
            "compilerPath": "/usr/local/bin/gcc-11",
            "cStandard": "gnu17",
            "cppStandard": "gnu++17",
            "intelliSenseMode": "macos-gcc-x64",
            "configurationProvider": "ms-vscode.cmake-tools"
        }
    ],
    "version": 4
}

I checked some relative problems but haven't found a solution. I don't know why the files cannot be opened as they exactly exist and I have edited the includePath. Are my configurations wrong?
Many thanks!!!

Update: My solution is to replace include_directories(EIGEN3_INCLUDE_DIR) in CMakeLists.txt with include_directories("/usr/local/include")
Nonetheless, I don't understand why it doesn't work if I remain include_directories(EIGEN3_INCLUDE_DIR) but remove the eigen3/ prefix in the includes. Besides, it seems what I wrote in c_cpp_properties.json doesn't affect anything.

Update: I try to replace include_directories(EIGEN3_INCLUDE_DIR) in CMakeLists.txt with include_directories(${EIGEN3_INCLUDE_DIR}) as suggested and remove the eigen3/ prefix in the includes. And now only line2 reports error "'Eigen/Core' file not found". It is strange since line2 & line3 should be in similar cases.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is testng.xml file updated automatically When running testng with mvn, I configured my workspace as required:
My pom.xml file is configured with all the required dependencies and testng.xml contains all the required classes.
Yet, when I add a new test class, the testng.xml isn't updated automatically-
Shouldn't it scan from the root for the corresponding tests? Or will I have to update the testng.xml file manually?
 (BTW, my workspace is configured according to the following post: How to call testng.xml file from pom.xml in Maven)

A: The xml method gives you more granular control of your test sets. It will not be altered automatically, although eclipse will generate xml configs on the fly if you select say a folder and right click run as testng. If you would just like to run all testng annotated test and you have maven configured properly with surefire or failsafe, you don't even need an xml file. Just run "mvn verify" and all test should be run based on annotation. If this doesn't work, please post your surefire/failsafe pom sections.
If you want to configure a particular xml in maven, use something like (surefire or failsafe work the same.):
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${failsafe.version}</version>
                <configuration>
                    <argLine>-Xmx1024m</argLine>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                        <configuration>
                            <suiteXmlFiles>
                                <suiteXmlFile>testng.xml</suiteXmlFile>
                                <!-- <groups>functest,perftest</groups> -->
                            </suiteXmlFiles>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

If you do need more granular control, and would like to use an xml file specified by maven, you launch it via "verify -P MyProfile"
<profiles>
        <profile>
            <id>MyProfile</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <configuration>
                            <suiteXmlFiles>
                                <suiteXmlFile>MyProfile.xml</suiteXmlFile>
                                <!-- <groups>functest,perftest</groups> -->
                            </suiteXmlFiles>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>MyOtherProfile</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <configuration>
                            <suiteXmlFiles>
                                <suiteXmlFile>MyOtherProfile.xml</suiteXmlFile>
                                <!-- <groups>functest,perftest</groups> -->
                            </suiteXmlFiles>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
<profiles>


text:
Q: While downloading an HTML file show a static text and running points (Loading. .. ...) In my app I download an HTML file from a server and check if an image is currently on the website and set a status to a label when the image was found. All works great but I like to
show the user a Loading status label while the app is downloading the file. It works with static text but how can I show running points after the Loading text? I like to see: Loading > Loading. > Loading.. > Loading... > Loading > and so on (I don't need an exact progress bar)
Code:
- (void)viewDidLoad
{
    [super viewDidLoad];
    platzStatusLabel.text = @"Loading";
    if (myConnection == nil) {
        myData = [NSMutableData new];
        NSString *urlString = [NSString stringWithFormat:@"http://www.myURL.com"];
        myConnection =[NSURLConnection connectionWithRequest:
                       [NSURLRequest requestWithURL:
                        [NSURL URLWithString:urlString]]
                                                    delegate:self];
    }

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSString *stringToLookup = [[NSString alloc]initWithData:myData encoding:NSASCIIStringEncoding];

    if ([stringToLookup rangeOfString:@"image_green"].location != NSNotFound){
        platzStatusLabel.text = @"Course is open.";
    } else {
        platzStatusLabel.text = @"Course is closed.";
    }

    [self initializeVariablesAgain];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [myData appendData:data];
}

- (void) initializeVariablesAgain {
    myData = nil;
    myConnection = nil;
}

A: Why not start a UIActivityIndicator (this circly thing that highlights) upon creation of the request and stop it in didFinishLoading?
Or start and stop an NSTimer that iterates through your several strings in the same fashion.
Lastly, you could iterate through your different strings in didReceiveData.
Cheers

A: Update your counter (file size downloaded updates) in
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

eg.
[myData appendData:data];
self.myCountInBytesOfDownloadProgress = [myData length];


text:
Q: same mysql query taking too long in mysql than mariadb I migrated from MariaDB to Mysql. My query below is taking more than three minutes in Mysql, but less than one minute in MariaDB. Mysql version is 5.7.
Please suggest how can I deal with this problem, thanks a lot!!!
SELECT
COUNT(*)
FROM
(SELECT i.*, f.*, c.*, ft.*, -- summarized for readability
        (SELECT f1.id
         FROM sys_exten_flow_task f1
         WHERE f1.instance_id = f.INSTANCE_ID AND state = '1'
         ORDER BY f1.update_date DESC
         LIMIT 0 , 1) AS pretaskid,
        CASE
            WHEN i.FLOW_DEFINE IS NULL THEN 'free'
            ELSE i.FLOW_DEFINE
        END AS fd,
        CASE
            WHEN f.TASK_DEFINE_ID IS NULL THEN 'free'
            ELSE f.TASK_DEFINE_ID
        END AS tdi
FROM
    sys_exten_flow_task f, sys_exten_flow_instance i,
    sys_exten_flow_define_task dt, sys_user c, sys_dict ft
WHERE
    i.ID = f.INSTANCE_ID
        AND i.CREATE_BY = c.ID
        AND i.FLOW_TYPE = ft.ID
        AND dt.id = f.task_define_id) a;

+----------+
| count(*) |
+----------+
|  3841309 |
+----------+
1 row in set (3 min 21.97 sec)

with the explain plan
+----+--------------------+------------+------------+--------+--------------------------------------------------+------------------------+---------+----------------------------+---------+----------+---------------------------------------+
| id | select_type        | table      | partitions | type   | possible_keys                                    | key                    | key_len | ref                        | rows    | filtered | Extra                                 |
+----+--------------------+------------+------------+--------+--------------------------------------------------+------------------------+---------+----------------------------+---------+----------+---------------------------------------+
|  1 | PRIMARY            | <derived2> | NULL       | ALL    | NULL                                             | NULL                   | NULL    | NULL                       | 3640604 |   100.00 | NULL                                  |
|  2 | DERIVED            | i          | NULL       | ALL    | PRIMARY,CREATE_BY                                | NULL                   | NULL    | NULL                       |  788059 |   100.00 | Using where                           |
|  2 | DERIVED            | ft         | NULL       | eq_ref | PRIMARY,ID                                       | PRIMARY                | 258     | scdxoa.i.FLOW_TYPE         |       1 |   100.00 | Using where                           |
|  2 | DERIVED            | c          | NULL       | eq_ref | PRIMARY,ID                                       | PRIMARY                | 258     | scdxoa.i.CREATE_BY         |       1 |   100.00 | NULL                                  |
|  2 | DERIVED            | f          | NULL       | ref    | INDEX_TASK_INSTANCE_ID,INDEX_TASK_TASK_DEFINE_ID | INDEX_TASK_INSTANCE_ID | 402     | scdxoa.i.ID                |       4 |   100.00 | Using index condition; Using where    |
|  2 | DERIVED            | dt         | NULL       | eq_ref | PRIMARY                                          | PRIMARY                | 258     | scdxoa.f.TASK_DEFINE_ID    |       1 |   100.00 | Using where                           |
|  3 | DEPENDENT SUBQUERY | f1         | NULL       | ref    | INDEX_TASK_STATUS,INDEX_TASK_INSTANCE_ID,INDEX   | INDEX                  | 408     | const,scdxoa.f.INSTANCE_ID |       3 |   100.00 | Using index condition; Using filesort |
+----+--------------------+------------+------------+--------+--------------------------------------------------+------------------------+---------+----------------------------+---------+----------+---------------------------------------+

7 rows in set, 2 warnings (0.01 sec)

Executing the same query in MariaDB, I get
+----------+
| count(*) |
+----------+
|  3912445 |
+----------+
1 row in set (56.54 sec)

with the explain plan
+------+--------------------+-------+--------+--------------------------------------------------+------------------------+---------+-------------------------+-------+----------+------------------------------------+

| id   | select_type        | table | type   | possible_keys                                    | key                    | key_len | ref                     | rows  | filtered | Extra                              |
+------+--------------------+-------+--------+--------------------------------------------------+------------------------+---------+-------------------------+-------+----------+------------------------------------+
|    1 | PRIMARY            | c     | index  | PRIMARY,ID                                       | group_login_name       | 205     | NULL                    | 23047 |   100.00 | Using index                        |
|    1 | PRIMARY            | i     | ref    | PRIMARY,CREATE_BY                                | CREATE_BY              | 259     | scdxoa.c.ID             |    15 |   100.00 |                                    |
|    1 | PRIMARY            | ft    | eq_ref | PRIMARY,ID                                       | PRIMARY                | 258     | scdxoa.i.FLOW_TYPE      |     1 |   100.00 | Using where; Using index           |
|    1 | PRIMARY            | f     | ref    | INDEX_TASK_INSTANCE_ID,INDEX_TASK_TASK_DEFINE_ID | INDEX_TASK_INSTANCE_ID | 402     | scdxoa.i.ID             |     2 |   100.00 | Using index condition; Using where |
|    1 | PRIMARY            | dt    | eq_ref | PRIMARY                                          | PRIMARY                | 258     | scdxoa.f.TASK_DEFINE_ID |     1 |   100.00 | Using where; Using index           |
|    3 | DEPENDENT SUBQUERY | f1    | ref    | INDEX_TASK_STATUS,INDEX_TASK_INSTANCE_ID,INDEX   | INDEX_TASK_INSTANCE_ID | 402     | scdxoa.f.INSTANCE_ID    |     2 |   100.00 | Using where; Using filesort        |
+------+--------------------+-------+--------+--------------------------------------------------+------------------------+---------+-------------------------+-------+----------+------------------------------------+

6 rows in set, 2 warnings (0.00 sec)

I also try to let Mysql to execute the result sql from mariadb optimized.
select count(0) AS "count(*)"
from "scdxoa"."sys_exten_flow_task" "f"
join "scdxoa"."sys_exten_flow_instance" "i"
join "scdxoa"."sys_exten_flow_define_task" "dt"
join "scdxoa"."sys_user" "c"
join "scdxoa"."sys_dict" "ft"
where (("scdxoa"."i"."CREATE_BY" = "scdxoa"."c"."ID")
     and ("scdxoa"."i"."ID" = "scdxoa"."f"."INSTANCE_ID")
     and ("scdxoa"."i"."FLOW_TYPE" = "scdxoa"."ft"."ID")
     and ("scdxoa"."dt"."ID" = "scdxoa"."f"."TASK_DEFINE_ID"));
+----------+
| count(*) |
+----------+
|  3841309 |
+----------+
1 row in set (21.83 sec)

A: Some amount of time is wasted by this construct:
SELECT COUNT(*)
    FROM ( SELECT lots-of-columns
               FROM, etc )

Instead of simply
           SELECT COUNT(*)
               FROM, etc

This is because the derived table is built and put into a temp table, probably on disk in your case, then counted.
Since I don't see a "2" in MariaDB's EXPLAIN, I guess that they did that Optimization for you.
At 5.6 and 10.0, they made some noticeable divergences in their Optimizers. You hit a case where MariaDB shines.
Simplify the first CASE..END to IFNULL(i.FLOW_DEFINE, 'free'); etc.
Please use JOIN..ON instead of comma+WHERE -- This won't help speed, but may help readability.
Even within the subquery there are other simplifications; for example, the CASEs provide nothing toward the COUNT. Whether or not you care, you might more help from us if you provide a minimal test case that demonstrates the problem.


text:
Q: performance between jquery bind click and  tag onclick I am developing a web application and using quite a lot of JavaScript doing tasks. I have quite some  tags that are bound with Jquery click to do some jobs, so I have code like this:
html code:
 some content here
 some content here
 ....

Jquery code:
 $('#id1').click(function(){
     //do something here..
     return false;
 });

 $('#id2').click(function(){
     //do something else here..
     return false;
 });

with this approach, when the script runs, jquery must look up the selectors (id1,id2, ect).
but there is another approach which avoid looking up selectors , this is as follow:
some content here
some content here

and js code:
 function f1(){
     //do something here..
 });

 function f2(){
     //do something else here..
 });

which approach is better, considering performance?  thanks for help.

A: Forget performance - any difference between the two will be inconsequential.
The first approach is MUCH better as it maintains a strict separation between behaviour and content.
Incidentally, the performance difference is only incurred on assigning the event-handler.
In this case the inline-call does not have to "find" the dom element, however, since your jquery selector is selecting by id (which is very efficient), the "overhead" incurred by the extra step will be tiny.

A: The real performance gain is by using only one event handler attached to the parent element, and catch the children element generated event with event.target, since events bubble up by default in JavaScript to the outermost parent.
Wrap your link in a div

 some content here
 some content here

Attach only one event listener to it
$('#parent').click(function(event){
    // event.target is now the element who originated the event
    $(event.target).doSomething();
});

This is a big increase in speed, expecially in older browsers such as IE, and when you start to have really many events.
View example here

A: Performance wise inline call is fast because it is triggered right away whereas if you use jquery it listens to this event and finds all the attached handlers and executes them in sequence. But using jquery you can manage to attach as many handlers you want in a systematic way.

A: One possibility would be to use .delegate() where you can set context specific bindings.  This should be faster than both .live() and several .click() bindings due to how delegate works.  There is an excellent write up on this here, an EXCELLENT MUST READ in SO here.  Good Luck!
HTML

   some content here
   some content here

Jquery/Javascript
$("#wrapper").delegate("#id1", "click", function(e){
   e.preventDefault();
   //do something here..
});

Jquery Delegate API

A: According to Jose Faeti's answer, here are two questions:

*

*How can I directly answer to his answer? ;)

*I have the following scenario: http://jsfiddle.net/syY4D/
The problem is, that an anchor-tag which contains other elements - such as divs, or spans - is not seen as clicked. It's child-element is tho.

hello

i don't need to be listened to

there

neither me, only a-tags should be concerned

    only i am "really" listened to

more content

This might be ugly, but in our existing application, that's the current state. So I reformed the according JavaScript as following:
$('#foo').click( function ( event ) {
    event.preventDefault();

    if( $(event.target).hasClass('clickable') ) {
        alert('clicked: ' + event.target.name );
    } else {
        if( $(event.target).closest('a.clickable').length )
            alert('has parent: ' + $(event.target).closest('a.clickable').attr('name') );
    }
});

My question: Is there any better solution to this? More performant? Is it ugly or would you do different?
Cheers


text:
Q: Max Value always setting to 8 I was writing a program that takes the input, and then prints the maximum value of the frequency of each letter in it. For this program, I have decided to take the input only as these 5 letters: a,b,c,d and e. The program goes like this.
#include <stdio.h>

int main(){
    int i, c , nchar[5];
    int maxvalue;

   for(i=0;i<5;i++){
    nchar[i]=0;
   }

    /*COLLECTING AND SETTING THE DATA*/
    while((c=getchar())!=EOF){
        if (c=='a')
            nchar[0]++;

        else if (c=='b')
            nchar[1]++;

        else if (c=='c')
            nchar[2]++;

        else if (c=='d')
            nchar[3]++;

        else if (c=='e')
            nchar[4]++;

    }
    printf("%d",setMax(nchar,maxvalue));

}
int setMax(int a[5], int maxv){
    if ( a[0]> a[1] &&  a[0]> a[2] &&  a[0]>a[3] &&  a[0]> a[4])
        a[0]=maxv;

    else if ( a[1]> a[0] && a[1]> a[2] && a[1]> a[3] && a[1]> a[4])
        a[1]=maxv;

    else if ( a[2]> a[0] && a[2]> a[1] && a[2]> a[3] && a[2]> a[4])
        a[2]=maxv;

    else if ( a[3]> a[0] && a[3]> a[2] && a[3]> a[1] && a[3]> a[4])
        a[3]=maxv;

    else if ( a[4]> a[0] && a[4]> a[2] && a[4]> a[3] && a[4]> a[1])
        a[4]=maxv;

        return maxv;

}

Now, for example I write the input as 'aaabc', it should print the value 3 because the maximum frequency is of letter 'a' which is 3. But, it is printing the value 8. Not only this input, but anything I write as input, it always prints 8. Can someone tell me what mistake have I done?

A: You have your logic backward.
Instead of
if ( a[0]> a[1] &&  a[0]> a[2] &&  a[0]>a[3] &&  a[0]> a[4])
    a[0]=maxv;

you need
if ( a[0]> a[1] &&  a[0]> a[2] &&  a[0]>a[3] &&  a[0]> a[4])
    maxv = a[0];

General Improvement
Change the name of the function setMax() to getMax() and change its signature to:
int getMax(int a[5]);

Change the usage to:
printf("%d", getMax(nchar);

And change the implementation to:
int getMax(int a[5]){

   int maxv = 0;
    if ( a[0]> a[1] && a[0]> a[2] &&  a[0]>a[3] &&  a[0]> a[4])
        maxv = a[0];

    else if ( a[1]> a[0] && a[1]> a[2] && a[1]> a[3] && a[1]> a[4])
        maxv = a[1];

    else if ( a[2]> a[0] && a[2]> a[1] && a[2]> a[3] && a[2]> a[4])
        maxv = a[2];

    else if ( a[3]> a[0] && a[3]> a[2] && a[3]> a[1] && a[3]> a[4])
        maxv = a[3];

    else if ( a[4]> a[0] && a[4]> a[2] && a[4]> a[3] && a[4]> a[1])
        maxv = a[4];

    return maxv;
}

Update
An updated version of getMax() that fixes the problem when two values are equal.
int getMax(int a[5])
{
   if ( a[0] >= a[1] && a[0] >= a[2] &&  a[0] >= a[3] &&  a[0] >= a[4] )
      return a[0];

   // a[0] is not the max. it has has be a[1], a[2], a[3], or a[4]
   if ( a[1] >= a[2] && a[1] >= a[3] && a[1] >= a[4] )
      return a[1];

   // Similarly, the max has to be a[2], a[3], or a[4]
   if ( a[2] >= a[3] && a[2] >= a[4] )
      return a[2];

   // Similarly, the max has to be a[3] or a[4]
   if ( a[3] >= a[4] )
      return a[3];

   // At this point, a[4] has to be the max value.
   return a[4];
}

A: do maxval = 0 and just return a[0] a[1] etc which ever condition is satisfied. Dont assign the value to maxval.
Or if you want to do like this, Here is the code for setMax() func:
int setMax(int a[5], int maxv){

int i=0;
maxval = a[0];
for (i=1;i<5;i++)
 if (maxval < a[i])
  maxval = a[i];
return maxval;
}

A: The variable maxvalue has an undefined value when you call setMax().
This gives undefined behavior.
Also I don't think setMax() makes sense. I think it should do return a[0] in the first if, and so on.

A: The variable maxvalue is uninitialized, and it's value will be indeterminate. Using it in calculations will lead to undefined behavior.
Besides, you always return it (or rather maxv) from the setMax function without modifications, so you will always print the same value.

A: As already pointed my Mr. Unwind and Mr. JP, the usage of maxvalue in current code invokes undefined behaviour, as you're using an uninitialized automatic variable value.
Based on the usage of setMax() function in your code, I think, what you want to do is (are)

*

*Point 1 You don't need to define maxvalue in main() and pass that as a parameter to setMax().

*Point 2 Inside setMax() function, define a local maxvalue and change a[0]=maxv; and series to maxv = a[0]; and likewise.


text:
Q: A server-side library to extract the content of web-pages I'm looking for a server-side library (preferably in PHP) to parse and extract the content of web-pages that is free for commercial use. It should be able to extract the headline and html (including images) of the content part of a page, but filter out ads and irrelevant content.
The Readability Parser API is a non-free software that does that, but I'm looking for free alternatives.
Any thoughts?

A: I'm using Boilerpipe. It's for Java unfortunately, but if you won't find anything in PHP, it may be useful to you. It's not perfect, obviously, but it's worth a try. It's also open source, thus it's possible to make necessary changes.
It has several so-called 'extractors', so you can choose the one which suits your need the most.
Usage is also pretty straightforward, on example:
URL url = new URL("http://example.com/article");
String articleText = ArticleExtractor.INSTANCE.getText(url);

A: Try using Simple HTML DOM
I used it to build a scraper for a rather complex website. Works very well.

A: The best way to get any data from page, like the geographic position of the Eiffel Tower from Wikipedia, is jQuery DOM.

    48°51′29″
    2°17′40″

Test in FireBug console jQuery('.geo-lat').text(). jQuery is a JavaScript library and the best result you get with server-side JavaScript web-server Node.js. There is a lot of good Node.js solutions for web crawling with DOM traversing.


text:
Q: How can you open a video on your desktop at a specific time using terminal? I wanted to know if it was possible to open a mp4 file located on my desktop right at a specific time of the video (e.g. 1 hour 10 minutes 30 seconds) using the terminal?
$ open /Volumes/USERNAME/Desktop/lecture.mp4
This works for starting at the beginning of the video.
But how could I include a specific time (hours, minutes, seconds) at where the video opens/starts at?

A: If you have the VLC media player installed, you can run the following example  compound command in Terminal to start playing the video file at the 1 hour 10 minutes 30 seconds mark:
open -a /Applications/VLC.app/Contents/MacOS/VLC '/path/to/name.mp4' --args --start-time 4230

Showing on two lines to see the whole compound command:
open -a /Applications/VLC.app/Contents/MacOS/VLC \
    '/path/to/name.mp4' --args --start-time 4230

Using the default macOS open command to open VLC and pass it the --start-time option, the value of which is expressed in seconds.
open options:

*

*-a application -- Specifies the application to use for opening the file.

*--args -- All remaining arguments are passed to the opened application in the argv parameter to main(). These arguments are not opened or interpreted by the open tool.

VLC option:

*

*--start-time  -- Starts the video here; the integer is the number of seconds from the beginning (e.g. 1:30 is written as 90).

See also: Documentation:Command line


text:
Q: Java SimpleDateFormat Pattern for JavaScript Date I need to convert a Java Date object to a string that is the same format as JavaScript Dates when they are converted to a string. On our server we have JavaScript dates that are .toString()'d and have a format like:
Wed Mar 30 2016 00:00:00 GMT-0400 (EDT)
And I have a Java Date object that I am trying to convert to a string of the same format. So far my SimpleDateFormat pattern is
EEE MMM dd yyyy '00:00:00' (The hours, minutes and secs will always be 0) but I can't figure out the proper pattern for the time zone (GMT-0400 (EDT))
Thanks for the help! Here is the Java code I'm using so far in case it helps:
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy '00:00:00'");
Date date = arrayOfDates[i];
String dateStr = format.format(date);
// Current dateStr = "Wed Mar 30 2016 00:00:00"

EDIT
Vaibhav Jain's answer put me on the right track (Java SimpleDateFormat Pattern for JavaScript Date)
The final format I ended up using is:
EEE MMM dd yyyy '00:00:00' 'GMT'Z '('z')'
Thanks again, all!

A: SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy '00:00:00'  zZ");
Date date = arrayOfDates[i];
String dateStr = format.format(date);

A: tl;dr
Parsing string.
ZonedDateTime.parse (
    "Wed Mar 30 2016 00:00:00 GMT-0400 (EDT)" ,
    DateTimeFormatter.ofPattern ( "EEE MMM dd uuuu HH:mm:ss 'GMT'Z (z)" ).withLocale ( Locale.US )
)

Generating string.
myJavaUtilDate.toInstant()
              .atZone( ZoneId.of( "America/New_York" ) )
              .format(
                  DateTimeFormatter.ofPattern ( "EEE MMM dd uuuu HH:mm:ss 'GMT'Z (z)" )
                                   .withLocale ( Locale.US )
              )

java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Parsing strings
Define a formatting pattern with DateTimeFormatter class.
The modern pattern codes are similar to the legacy SimpleDateFormat codes, but not exactly identical. Study the documentation. The subtleties of the zone/offset pattern codes eludes me, but some trial-and-error found a combination that seems to work. Test thoroughly, as I have not; use at your own risk.
String input = "Wed Mar 30 2016 00:00:00 GMT-0400 (EDT)"; // EDT
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EEE MMM dd uuuu HH:mm:ss 'GMT'x (z)" ).withLocale ( Locale.US );

ZonedDateTime zdt = ZonedDateTime.parse ( input , f );

Generate a String in standard ISO 8601 format.
System.out.println ( "zdt.toString(): " + zdt );

zdt.toString(): 2016-03-30T00:00-04:00[America/New_York]

By the way, if at all possible I suggest you use the standard ISO 8601 formats rather than the format shown in your Question. Much easier to parse and easier to read by humans across cultures.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or EDT or IST as they are not true time zones, not standardized, and not even unique(!).
Generating strings
Convert any java.util.Date to its modern equivalent, Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
To convert, look to new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;

Adjust into the desired time zone.
ZoneId z = ZoneId.of( "America/New_York" );
ZonedDateTime zdt = instant.atZone( z );

Generate a string using the same DateTimeFormatter object seen above.
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EEE MMM dd uuuu HH:mm:ss 'GMT'x (z)" ).withLocale ( Locale.US );
String output = zdt.format( f );

Live code
See this example code live in IdeOne.com.
String input = "Wed Mar 30 2016 00:00:00 GMT-0400 (EDT)"; // EDT
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EEE MMM dd uuuu HH:mm:ss 'GMT'Z (z)" ).withLocale ( Locale.US );

ZonedDateTime zdt = ZonedDateTime.parse ( input , f );

String output = zdt.format ( f );

System.out.println ( "input: " + input );
System.out.println ( "zdt.toString(): " + zdt );
System.out.println ( "output: " + output );
System.out.println ( "input equals output: " + input.equals ( output ) );

input: Wed Mar 30 2016 00:00:00 GMT-0400 (EDT)
zdt.toString(): 2016-03-30T00:00-04:00[America/New_York]
output: Wed Mar 30 2016 00:00:00 GMT-0400 (EDT)
input equals output: true

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?

*

*Java SE 8 and SE 9 and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

*See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

A: To format the date exactly like that, we may need to format date and timezone separately, e,g,:
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy hh:mm:ss");
Date date = new Date();
String dateStr = format.format(date);
TimeZone tz = TimeZone.getDefault();
int offset = tz.getRawOffset();

String text = String.format("%s%02d%02d", offset >= 0 ? "+" : "-", offset / 3600000, (offset / 60000) % 60);

String timeZoneText = "GMT" + text + " (" + tz.getDisplayName(true, tz.SHORT, Locale.getDefault())+")";

System.out.println(dateStr + " " + timeZoneText);

A: Typically if a given date is valid then the date object created should return back the same date, month and year value. Below logic worked for most of the cases that I coded.
Example: 29-Feb-2018 does not exist, but when javascript accepts this input as Date("2018-02-29") it creates a date value of 1-Mar-2018.
Javascript Function:

    function dateCheck(dd,mm,yyyy)
    {
      var tempDt = new Date(parseInt(yyyy), parseInt(mm)-1, parseInt(dd), 0, 0, 0, 0);

      if(tempDt.getDate()!=parseInt(dd) ||
        tempDt.getFullYear()!=parseInt(yyyy) ||
        tempDt.getMonth() + 1 !=parseInt(mm))
        return false;
      else
        return true;
    }


text:
Q: Displaying own map in android I want to display the map of college. I already have blueprint of college and also know the lat and longitude. Is there any way to achieve this, if so then please help me. I want to display map like this..enter image description here
  Thanks in advance

A: you can use GoogleAPI for it, using lattitude and longitude you can plot your college location.


text:
Q: Quaternionic projective space and homotopy groups of spheres Let $\mathbb{H}$ be the $\mathbb{C}$ with formal basis {1,j} and define multiplication by distributively extending $j^2 =-1$ and $ji =-ij$:
$$(a+bj)(u+vj):= au-b\overline{v} +(av+b \overline{u})j.$$ It is easy to see that $(\mathbb{H},+,.)$ is a skew field with $$||a+bj||= \sqrt{(a\overline{a}+b\overline{b})}, ||pq||= ||p||||q||.$$
I have the following three questions:

*

*How can I define a free action of $\mathbb{S}^3$ on $\mathbb{S}^{4n+3}$ and obtain a fibration $$q:\mathbb{S}^{4n+3} \rightarrow \mathbb{S}^{4n+3}/\mathbb{S}^3 =:  \mathbb{H}P^n.$$ The base space is quaternion projective $n$-space.

*How is $\mathbb{H}P^1$  homeomorphic to $\mathbb{S}^4$. This looks obvious from the quotient defined above but I cant seem to provide an argument/proof.

*Lastly, from the Long exact sequence, how can one show that for $k \ge1$, $$\pi_k\mathbb{S}^4 \cong \pi_k\mathbb{S}^7 \oplus \pi_{k-1}\mathbb{S}^3.$$
Thanks for you kind help and explanations.

A: Suppose $\mathbb{K}$ is one of $\mathbb{R},\mathbb{C},\mathbb{H}$ and $d=\dim_{\mathbb{R}}(\mathbb{K})$ (so one of $1,2,4$).
The elements of $\mathbb{K}^n$ with unit norm form the sphere $S^{dn-1}$.
$\mathbb{K}^n$ is a right vector space over $\mathbb{K}$ of dimension $n$, and a real inner product space of dimension $dn$ with inner product $\langle x,y\rangle=\overline{x_1}y_1+\cdots+\overline{x_n}y_n$ (using the physicist convention of linearity in the second argument, so they can write things like $x^{\dagger}y$ or $\langle x\mid y\rangle$). I have scalars multiplied from the right so that matrices may be applied from the left and yield $\mathbb{K}$-linear transformations.
To form the projective space $\mathbb{KP}^{n-1}$, we put an equivalence relation $\sim$ on nonzero elements of $\mathbb{K}^n$ in which $x\sim x\lambda$ for all nonzero vectors $x\in\mathbb{K}^n\setminus0$ and nonzero scalars $\lambda\in\mathbb{K}^\times$, then create the quotient space $(\mathbb{K}^n\setminus0)/\!\sim$. The equivalence class of $(x_1,\cdots,x_n)$ is denoted $[x_1:\cdots:x_n]$.
Every unit vector of $\mathbb{K}^n$ defines a $\mathbb{K}$-line, i.e. a $1$-dimensional subspace as a right vector space over the (possibly skew) field $\mathbb{K}$. In other words, we have a map $S^{dn-1}\to\mathbb{KP}^{n-1}$. As every $\mathbb{K}$-line contains a unit vector, this map is surjective.
A fiber of this map will be all unit vectors in a given $\mathbb{K}$-line. Since every $\mathbb{K}$-line looks like $\mathbb{K}^1$, all of the fibers will be $S^{d-1}$. Thus, we have a fiber bundle $S^{d-1}\to S^{dn-1}\to\mathbb{KP}^{n-1}$.
Moreover, the group $S^{d-1}\subset\mathbb{K}^\times$ acts regularly on each fiber (the $\mathbb{K}$-lines are equivalence classes under scalar multiplication, and the intersection of a $\mathbb{K}$-line with the sphere of unit vectors must be a copy of $S^{d-1}\subseteq\mathbb{K}^1$), making $S^{dn-1}\to\mathbb{KP}^{n-1}$ a principal $S^{d-1}$-bundle.
The projective line $\mathbb{KP}^1$ can be identified with $S^d$. One way is as follows. Every vector $(x,y)$ can normalized to have the form $(xy^{-1},1)$, unless $y=0$ in which case it may be normalized  to have the form $(1,0)$. Thus, $\mathbb{KP}^1$ minus a point may be identified with $\mathbb{K}$ (in the first coordinate). If we extend $\mathbb{K}$ by adjoining the symbol $\infty$ to it, call the result $\widehat{\mathbb{K}}=\mathbb{K}\cup\{\infty\}$, topologize it as the one-point compactification of $\mathbb{K}$, then we can extend this to a homeomorphism $\mathbb{KP}^1\to\widehat{\mathbb{K}}$. In the case of $\mathbb{K}=\mathbb{C}$, this is called the Riemann sphere.
This is also the origin of Mobius transformations (aka linear fractional transformations). $\mathrm{GL}(2,\mathbb{K})$ acts on $\mathbb{K}^n$ and commutes with the right action by scalars in $\mathbb{K}^\times$, hence descends to an action on $\mathbb{KP}^1\simeq\widehat{\mathbb{K}}$. Since $[\begin{smallmatrix}a & b \\ c & d \end{smallmatrix}][\begin{smallmatrix} x \\ y \end{smallmatrix}]=[\begin{smallmatrix} ax+by \\ cx+dy\end{smallmatrix}]\mapsto (ax+by)(cx+dy)^{-1}=(axy^{-1}+b)(cxy^{-1}+d)^{-1}$, the transported action of $\mathrm{GL}(2,\mathbb{K})$ on $\widehat{\mathbb{K}}$ is $[\begin{smallmatrix}a & b \\ c & d \end{smallmatrix}]z=(az+b)(cz+d)^{-1}$.
To see $\widehat{\mathbb{K}}$ is a sphere, we may use stereographic projection. Given any real inner product space (which $\mathbb{K}$ is an example of), invoke coordinates so it looks like $\mathbb{R}^d$. Any line through the "north pole" $(0,\cdots,0,1)\in S^d\subset \mathbb{R}^{d+1}$ and a point $x\in\mathbb{R}^d$ (viewed as a subspace of $\mathbb{R}^{d+1}$ in the obvious way) intersects the sphere $S^d$ in a unique point, and conversely, which sets up a bijection between $\mathbb{R}^d$ and ($S^d$ minus the north pole), in which case $S^d$ is the one-point compactification of $\mathbb{R}^d$.
Here's another trick, which IIRC Baez attributes to Penrose. Given any $\mathbb{K}$-line $L$ in $\mathbb{K}^n$ (equivalently, point in $\mathbb{KP}^{n-1}$) there is an orthogonal projection onto $L$. This has the property that it acts as the identity on $L$ and as the zero map on $L^\perp$ (the orthogonal complement with respect to the real inner product). Concretely, if we represent $L=x\mathbb{K}$ with $x$ a unit vector, then $\langle x,-\rangle$ siphons out the "$x$-component" of vectors, so the projection is $x\langle x,-\rangle$, which may be represented as left-multiplication by the matrix $xx^{\dagger}$ (where $x$ is treated as a column vector and $x^{\dagger}$ denotes conjugate transpose). This is an element of $\mathfrak{h}_n(\mathbb{K})$ ($n\times n$ hermitian matrices over $\mathbb{K}$, i.e. matrices $A$ for which $A^{\dagger}=A$) with trace $\mathrm{tr}(xx^{\dagger})=|x|^2=1$.
In the case of $n=2$, you can subtract $\frac{1}{2}I_2$ from $xx^{\dagger}$ and you get an element of a sphere centered at the origin in the space of traceless $n\times n$ hermitian matrices (equipped with the Frobenius norm), and thus establish a bijection $\mathbb{KP}^1\to S^d$. I give more detail here, and relate it to stereographic projection and exceptional isomorphisms.
Given a fiber bundle $F\to E\to B$, there is a long homotopy exact sequence
$$ \cdots\to\pi_{k+1}(B)\to ~~~ \pi_k(F)\to \pi_k(E)\to \pi_k(B) ~~~ \to \pi_{k-1}(F)\to\cdots $$
If all inclusions $F\to E$ are null-homotopic, then $\pi_k(F)\to\pi_k(E)$ is the zero map, in which case the long homotopy exact sequence becomes a collection of short exact sequences
$$ 0\to \pi_k(E)\to \pi_k(B)\to\pi_{k-1}(F)\to0. $$
Moreover, we have projections $\pi_k(B)\to \pi_k(E)$, so a split exact sequence
$$ 0\to \pi_k(E)\rightleftarrows \pi_k(B)\to \pi_{k-1}(F)\to0 $$
which implies $\pi_k(B)\cong\pi_k(E)\oplus\pi_{k-1}(F)$.
In the case of $S^{d-1}\to S^{2d-1}\to S^d$ (with $n=2$ of our discussion above) this gives the desired result that $\pi_k(S^{2d-1})=\pi_k(S^{d-1})\oplus \pi_{k-1}(S^d)$. To see that $S^{d-1}\to S^{2d-1}$ is null-homotopic, notice it is certainly not surjective, so there is a point outside the image (of a fixed choice of inclusion) we can use for stereographic projection, getting an embedding $S^{d-1}\to \mathbb{R}^{2d-1}$ which can be contracted to the trivial based map by rescaling embeddings by $t$ with $0\le t\le 1$.
Note that by sufficiently changing the definition of projective space (using equivalent algebraic characterizations), we can define a projective line $\mathbb{OP}^1$ (and even projective plane $\mathbb{OP}^2$) over the octonions $\mathbb{O}$, in which case the above results still hold true.


text:
Q: LinkedIn Marketing developer plattform APIs, how to use access token? After receiving the access token trough the 3-legged OAuth (https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin%2Fmarketing%2Fcontext&tabs=HTTPS), how can I use this access token for API requests?
For example if I want to get the follower statistics of my company, where would i put the access token in this API request?
GET https://api.linkedin.com/v2/organizationalEntityFollowerStatistics?q=organizationalEntity&organizationalEntity={organization URN}

I could not find it in the documentation:
https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/organizations/follower-statistics?tabs=http

A: I had to press on the "curl" tab under "Sample request" in the documentation: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/organizations/follower-statistics?tabs=http


text:
Q: KeyCloak as IDP to Salesforce SP - SP initiated SSO not working I am new to KeyCloak, and am trying to configure it as a SAML IDP to a SalesForce client.
IDP initiated SSO flow works fine. I am directed to the Salesforce home page correctly post-authentication. However, SP initiated SSO gives me a JSON output instead of the Keycloak login page.
This is the URL that SalesForce is redirecting to (masked IP):
http://10.99.xxx.xxx:8080/auth/realms/test?SAMLRequest=...
SAML tracer indicates a valid SAML authentication request.
<?xml version="1.0" encoding="UTF-8"?>
<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
                    AssertionConsumerServiceURL="https://f-corpcont--dev.my.salesforce.com?so=00D3K000000lOS"
                    Destination="http://10.99.xxx.xxx:8080/auth/realms/test"
                    ID="_2CAAAAXJxZQlkME8wswMDAwMDAwMDA2AAAA3kJle3T1o4lEOE9QztKYIVXwLjlHOcfEaw-7mLWvYqmEiPv5SS32lT0WcQIbjXTP-qO779xPjACwqlhiGs9ZM8ZmltHZd6stzimY1Br3b1_5PqBgWxExV7R1FAAxZ914_3s8rViWWGxmKKGFN94OG2WBh3SMPF3WwGagDIZLRKtSpcGIDCGkuYERb_DR0LgOflx-C0kF7XqKdtU8OTTbk0HpoCKQ8oRh58Mai1eFlqgKf50rdGsFQmCQa-Sg0-JyZg"
                    IssueInstant="2020-05-04T19:39:22.807Z"
                    ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
                    Version="2.0">
  <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">https://f-corpcont--dev.my.salesforce.com</saml:Issuer>
</samlp:AuthnRequest>

The JSON output I see in my browser is:
{
    "realm": "test",
    "public_key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqHobhU5mQ2itvVfkDWm64sLgT9dfoCNm137ul+A7YRNSXk5g0JEGxoZLVdicRQUx0mr4z6BEM+LN/mztSsigG0aQIqUY8y1un33kBk5gE6W3jaFDX6Rsap/lcXIoO7Jl/pzjAxf3R8RyMMhFQ4Hi1rHl2wSXMWfeNLaoLrzy+LEG1KNZpfhbfG1HUa5fEYpI0sSWEEgcP3faEy2JWOJrfJrcS1tezDD+7x4u+fTUJt0M8vsIjMDAX9UUu+JXnG901a15drj9UjYJyiMJTFQt3Rdrxv96XZa93fKyB36an5GDZWPiwEehtjAJ4mQ0oo0v/TmevoJwZd7YTvClQIDAQAB",
    "token-service": "http://10.99.xxx.xxx:8080/auth/realms/test/protocol/openid-connect",
    "account-service": "http://10.99.xxx.xxx:8080/auth/realms/test/account",
    "tokens-not-before": 0
}

Any pointers would be appreciated

A: You have used wrong URL for SAML request. Wrong:
http://10.99.xxx.xxx:8080/auth/realms/test?SAMLRequest=

Correct:
http://10.99.xxx.xxx:8080/auth/realms/test/protocol/saml?SAMLRequest=


text:
Q: How to get values from Entry on tkinter? if I run this program I can't seem to get any values on my user entries. Also, I am not sure why my Tkinter is producing 2 windows. Can anyone help?
Here is the sample code.
Background: I am making an interactive app for the Lorenz Equations to show the chaotic butterfly trajectory in phase space. In my Tkinter window, I have added 3 Entry for the user to choose for a certain parameter and I want to retrieve these values but for some reason, under function click1, it is not printing the values obtained.
import sys
import traceback
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from random import randint
import math
from tkinter import *
import tkinter as tk
import matplotlib

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from matplotlib import style

matplotlib.use("TkAgg")

class LorenzAttractorRungeKutta(tk.Frame):
    DT            = 1e-3     # Differential interval
    STEP          = 100000   # Time step count

    def __init__(self):
        global user_r_entry
        global user_sigma_entry
        global user_b_entry

        super(LorenzAttractorRungeKutta, self).__init__()

        self.X_0, self.Y_0, self.Z_0 = 0,0,0

        self.root = Tk()
        self.root.grid()
        self.root.title("Lorenz Simulation")
        self.root.geometry = ("500x500")
        self.root.resizable = (False, False)

        self.res = [[], [], []]

        self.root.graphframe = LabelFrame(master = self.root, text = "Phase Space")
        self.root.label1 = Label(self.root.graphframe, text="Graph", height = 3, width = 15).grid(row=5, column=0, columnspan=10)

        #self.root.graphframe = LabelFrame(master = self.root, text = "Phase Space")
        #self.root.label1 = Label(self.root.graphframe, text="Graph", height = 3, width = 15).grid(row=5, column=0, columnspan=10)
        user_r_entry = IntVar()
        r_entry = Entry(self.root, textvariable = user_r_entry).grid(row = 1, column = 0)
        self.root.r_label = Label(self.root, text="r value", height = 1, width = 12).grid(row=2, column=0, columnspan=1)

        user_sigma_entry = IntVar()
        sigma_entry = Entry(self.root, textvariable = user_sigma_entry).grid(row = 1, column = 1)
        self.root.sigma_label = Label(self.root, text="sigma value", height = 1, width = 12).grid(row=2, column=1, columnspan=1)

        user_b_entry = IntVar()
        b_entry = Entry(self.root, textvariable = user_b_entry).grid(row = 1, column = 2)
        self.root.b_label = Label(self.root, text="b value", height = 1, width = 12).grid(row=2, column=2, columnspan=1)

        self.plot_button = Button (self.root, command = self.click1, height = 2, width = 4).grid(row = 3, column = 1)

        self.mainloop()

    def click1(self):
        global r_info
        global sigma_info
        global b_info

        r_info = user_r_entry.get()
        sigma_info = user_sigma_entry.get()
        b_info = user_b_entry.get()

        print (r_info, sigma_info, b_info)

    def plot(self):
        global user_r_entry
        global user_sigma_entry
        global user_b_entry
        global r_info
        global sigma_info
        global b_info

        print (r_info,sigma_info,b_info)

        tk.Frame.__init__(self, self.root)

        try:
            xyz = [self.X_0, self.Y_0, self.Z_0]
            for _ in range(self.STEP):
                k_0 = self.__lorenz(xyz)
                k_1 = self.__lorenz([x + k * self.DT / 2 for x, k in zip(xyz, k_0)])
                k_2 = self.__lorenz([x + k * self.DT / 2 for x, k in zip(xyz, k_1)])
                k_3 = self.__lorenz([x + k * self.DT for x, k in zip(xyz, k_2)])
                for i in range(3):
                    xyz[i] += (k_0[i] + 2 * k_1[i] + 2 * k_2[i] + k_3[i]) \
                            * self.DT / 6.0
                    self.res[i].append(xyz[i])

            #print (self.res[1])

            f = Figure(figsize=(10,10), dpi=100)
            a = f.add_subplot(111)
            a.plot(self.res[0], self.res[1])

            canvas = FigureCanvasTkAgg(f, self)
            canvas.draw()
            canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        except Exception as e:
            raise

    def __lorenz(self, xyz):
        global r_info
        global sigma_info
        global b_info

        p = sigma_info
        r = r_info
        b = b_info

        try:
            return [
                -p * xyz[0] + p * xyz[1],
                -xyz[0] * xyz[2] + r * xyz[0] - xyz[1],
                xyz[0] * xyz[1] - b * xyz[2]
            ]
        except Exception as e:
            raise

if __name__ == '__main__':
    try:
        LorenzAttractorRungeKutta()

    except Exception as e:
        traceback.print_exc()
        sys.exit(1)


text:
Q: About Sorting String In C++ How can I do a stable sort of words in a string based only on the length of each word, so the longest words come first, and the shortest words at the end (but words of the same length retain their original order relative to each other)?
For example:
Input:
sj a sa df r e w f d s a v c x z sd fd

Resulting output:
sj sa df sd fd a r e w f d s a v c x z

A: The simplest solution is to split the string into a collection of string then sort that collection and concatenate the result into a string again: you can use a custom comparator using the size of the string and feed it to std::stable_sort with the collection of strings to sort:
// Your original string
std::string your_string = "sj a sa df r e w f d s a v c x z sd fd";

// Split the string
std::istringstream iss(your_string);
std::vector<std::string> words{
    std::istream_iterator<std::string>(iss),
    std::istream_iterator<std::string>()
};

// Stable sort by size
std::stable_sort(std::begin(words), std::end(words), [](const std::string& lhs, const std::string& rhs) {
    return lhs.size() > rhs.size();
});

// Merge the results back with spaces
std::ostringstream oss;
std::copy(
    std::begin(words), std::end(words),
    std::ostream_iterator<std::string>(oss, " ")
);
your_string = oss.str();

Of course, this algorithm is not optimal. To avoid much of the computation, you could store directly a vector of strings and work with that instead of storing your words in a space-separated string. Among the suboptimals things: we copy many things from the original string while some things could probably be moved to and from the words vector (not sure). The mere fact that we strip the spaces to add them back is a clear hint that we're doing more than we could.
Also, note that the final string will have an additional trailing space that you can choose to remove with pop_back.


text:
Q: Nature of $\sum 1/f(n)$ with $f(n) := n\ln(n)\ln(\ln(n))...*\ln^{(k_n)}(n)$ ; $k_n$ being the largest natural integer $k$ such that $\ln^{(k)}(n)≥1$
For all $n$ in $\mathbb N^*$, let $f(n) :=
n*\ln(n)*\ln(\ln(n))*...*\ln^{(k_n)}(n)$, with $\ln^{(k)}$ being the
  logarithm iterated $k$ times, and $k_n$ being the largest natural
  integer $k$ such that $\ln^{(k)}(n)≥1$.
Study the nature of the series $\sum 1/f(n)$.

One can show that when $k_n$ is a constant, the series diverges (by comparison with integral) but here  it is not the case. I think the series also diverges. How to prove it ?

A: For any $k\geq 0$, we have $k_n=k$ for
$$
a_k:=\begin{matrix}
    &\underbrace{e^{e^{{}^{.\,^{.\,^{.\,^e}}}}}} &
\\
    &  k\mbox{ copies of }e
  \end{matrix} \leq n < a_{k+1}:=\begin{matrix}
    &\underbrace{e^{e^{{}^{.\,^{.\,^{.\,^e}}}}}} &
\\
    &  k+1\mbox{ copies of }e
  \end{matrix}
$$
The sum of $1/f(n)$ on this range of $n$, is at least
$$
\int_{a_k}^{a_{k+1}} \frac1{x \ln(x) \ln(\ln(x))\cdots \ln^{(k)}(x) } dx=\ln^{(k+1)}(x) \Bigg\vert_{a_k}^{a_{k+1}} = 1.
$$
Therefore, the sum of $1/f(n)$ over all $n$ diverges.


text:
Q: How to run a loop from a program in background while the code proceeds to do other things so, i was trying to make a personal assistant and i wanted to make a reminder type of commnd.
here is the code of the reminder(notification).
and the speak and takecommand fuctions are custom.
elif "remind" in query:
        speak("what should i remind you")
        messageT = takeCommand()
        speak("ok, so when should i remind you.")
        timeOfReminder = takeCommand()
        while True:
            current_time = tm.strftime("%H:%M:%S")
            if current_time == timeOfReminder:
                print(current_time)
                break;

        toaster = ToastNotifier()
        toaster.show_toast(messageT,
                        duration=10)

so the problem is not with this code, but the code contains a while loop which prohibits me to proceed with my code(this whole code is also a part of a while loop which contains all the command).
i wanna know how to like run this loop in parellel of the other main while loop(this while loop checks the time while the main while loop checks what command the user is giving.)
is there any way to do this (if you want i can post my full code if it helps).

A: Use the threading library in Python 3.
import threading
Create a function:
def my_long_function():
    while 1:
        print("runs in background")
        time.sleep(1)

long_thread = threading.Thread(target=my_long_function)
long_thread.start()

while 1:
    print("Running in foreground")
    time.sleep(3)

Hope this works for you!


text:
Q: Python Arima X13 model gets AttributeError: 'NoneType' object has no attribute 'startswith' I am trying to run the following code and at the end of the code, I get this error:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
import statsmodels as sm
from statsmodels.tsa.x13 import x13_arima_select_order, _find_x12
import os

df_railroad=pd.read_csv('Input_Data1.csv')

XPATH = os.chdir('C:/Users/walkea24/Downloads/winx13_V2.5/WinX13/x13as')

df_railroad.rename(columns={'US Railroad Traffic Originated: Intermodal +
Carloads (Units)':'Railroad'}, inplace=True)

df_railroad.set_index('Date', inplace=True)
temp_series =
pd.DataFrame(df_railroad["Railroad"].values,index=df_railroad.index)
x13results = sm.tsa.x13.x13_arima_analysis(endog =
temp_series,x12path=XPATH, freq='M',outlier=True,print_stdout=True)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\PythonPlus\64bit\envs\Python36\lib\site-packages\statsmodels\tsa\x13.py
in pandas_to_series_spec(x)
    291     try:
--> 292         period = _freq_to_period[x.index.freqstr]
    293     except (AttributeError, ValueError):

AttributeError: 'Index' object has no attribute 'freqstr'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
<ipython-input-7-0721f586e7a5> in <module>()
      1 temp_series =
pd.DataFrame(df_railroad["Railroad"].values,index=df_railroad.index)
----> 2 x13results = sm.tsa.x13.x13_arima_analysis(endog =
temp_series,x12path=XPATH, freq='M',outlier=True,print_stdout=True)

C:\PythonPlus\64bit\envs\Python36\lib\site-packages\statsmodels\tsa\x13.py
in x13_arima_analysis(endog, maxorder, maxdiff, diff, exog, log, outlier,
trading, forecast_years, retspec, speconly, start, freq, print_stdout,
x12path, prefer_x13)
    412
periods=len(endog),
    413                                                         freq=freq))
--> 414     spec_obj = pandas_to_series_spec(endog)
    415     spec = spec_obj.create_spec()
    416     spec += "transform{{function={0}}}\n".format(_log_to_x12[log])

C:\PythonPlus\64bit\envs\Python36\lib\site-packages\statsmodels\tsa\x13.py
in pandas_to_series_spec(x)
    293     except (AttributeError, ValueError):
    294         from pandas.tseries.api import infer_freq
--> 295         period = _freq_to_period[infer_freq(x.index)]
    296     start_date = x.index[0]
    297     if period == 12:

C:\PythonPlus\64bit\envs\Python36\lib\site-packages\statsmodels\tsa\x13.py
in __getitem__(self, key)
     29 class _freq_to_period:
     30     def __getitem__(self, key):
---> 31         if key.startswith('M'):
     32             return 12
     33         elif key.startswith('Q'):

AttributeError: 'NoneType' object has no attribute 'startswith'

I am not sure why it is saying NoneType has no attribute 'startswith' because I have the proper data setup with my left column as a date index and the right as values. Statsmodels should be able to infer that I have a date variable on the right. Below is the beginning of my data:
Date        US Railroad Traffic Originated: Intermodal + Carloads (Units)
1/31/1990   1593540
2/28/1990   1667441
3/31/1990   2124852
4/30/1990   1685441
5/31/1990   1710519
6/30/1990   2111856


text:
Q: Can I parameterize generic Type We are having several reports in fixed length record format. We are using FileHelpers for transforming them to delimited record format.
As there are serveral reports we thought of describing the fixed and delimited models and pass to
FileTransformEngine<TSource, TDestination>();

As to make it DRY can we do something like
Transform<TInput, TOutput>()
{
var engine = new FileTransformEngine<TInput, TOutput>();
engine.TransformFileFast(...);
}

I'm new to C# and generics and I'm not sure where to start.
Can anyone can give me some guidance, whether this is possible, as all models are already created they are available at compile time I think.

A: The documentation for filehelpers shows how to read a fixed file and write a delimited file - so it should be pretty easy to wrap calls to both in your own FileTransformEngine
public class FileTransformEngine<T>
{
    public void TransformFileFast(string inputFile, string outputFile)
    {
       var readEngine = new FixedFileEngine<T>();
       T[] records = readEngine.ReadFile(inputFile);
       var writeEngine = new FileHelperEngine<T>();
       writeEngine.WriteFile(outputFile,records);

    }
}

For this to work, your class will need the attributes for both reading and writing. eg
[FixedLengthRecord()]
[DelimitedRecord("|")]
public class MyRecord
{
     [FieldFixedLength(5)] // for reading
     [FieldConverter(ConverterKind.Decimal, ".")] // for writing
     public decimal Foo{get; set; }
}

Then you would use
var engine = new FileTransformEngine<MyRecord>();
engine.TransformFileFast("from/input.txt","to/output.csv");

If you want different types for input and output you could have the class take two types (an input and an output) along with a predicate for transforming one to the other.
public class FileTransformEngine<TInput, TOutput>
{
    public void TransformFileFast(string inputFile, string outputFile,
                                      Func<TInput,TOutput> transformer)
    {
       var readEngine = new FixedFileEngine<TInput>();
       TInput[] records = readEngine.ReadFile(inputFile);
       IEnumerable<TOutput> outputRecords = records.Select(transformer);
       var writeEngine = new FileHelperEngine<TOutput>();
       writeEngine.WriteFile(outputFile,outputRecords );

    }
}

This would then be called with your two types
var engine = new FileTransformEngine<MyInputRecord, MyOutputRecord>();
engine.TransformFileFast("from/input.txt","to/output.csv", input => {
    //transform input to output.
    return new MyOutputRecord();
});


text:
Q: If $f_{n+1}(t)\le c\int_0^tf_n(s)\:{\rm d}s$, then $f_n(t)\le\frac{(ct)^n}{n!}\sup_{s\in[0,\:T]}f_0(s)$ Really simple question, but I don't see how to solve it at the moment: Say we know that $$f_{n+1}(t)\le c\int_0^tf_n(s)\:{\rm d}s\tag1$$ for all $t\in[0,T]$. Why can we conclude $$f_n(t)\le\frac{(ct)^n}{n!}\sup_{s\in[0,\:T]}f_0(s)\tag2$$ for all $t\in[0,T]$? I don't get where the factorial comes from.

A: By induction on $n$.
For $n=0$, the inequality is $f_0(t) \leq \sup_{s \in [0,T]} f_0(s)$ which is true.
Suppose it is true for an integer $n$. Then
$$f_{n+1}(t) \leq c \int_0^t f_n(s) \mathrm{ds} \leq c \int_0^t \frac{(cs)^n}{n!} \sup_{s' \in [0,T]} f_0(s') \mathrm{ds} = \frac{c^{n+1}\sup_{s \in [0,T]} f_0(s)}{n!} \int_0^t s^n \mathrm{ds}$$
$$ = \frac{c^{n+1}\sup_{s \in [0,T]} f_0(s)}{n!} \times \frac{t^{n+1}}{n+1} = \frac{(ct)^{n+1}}{(n+1)!}\sup_{s \in [0,T]} f_0(s)$$
and you are done.


text:
Q: Can't get query to work I have a database containing 3 tables (member, boat, boatType) and in the method below two of them is affected. What I want is to list all boats that's registered on a member, but there's a problem with the code (at least with the SQL, but I suspect that's not all).
Thanks in advance.
boatHandler.php:
public function GetMembersBoats($memberId) {

    $query = "SELECT b.boatId, b.length, bt.type
                  FROM boat AS b
                      INNER JOIN member AS m
                          ON b.memberId = m.memberId
                              WHERE m.memberId = ?
                      INNER JOIN boatType AS bt
                          ON b.boatTypeId = bt.boatTypeId
                      GROUP BY b.boatId";

    $stmt = $this->m_db->Prepare($query);
    $stmt->bind_param('i', $memberId);

    $boats = $this->m_db->GetBoats($stmt);
}

database.php:
public function GetBoats($stmt) {
    $boats = array(
            0 => array(),
            1 => array(),
            2 => array()
        );

    $stmt->execute();

    $stmt->bind_result($boatId, $length, $type);

    while ($stmt->fetch()) {
        array_push($boats[0], $boatId);
        array_push($boats[1], $length);
        array_push($boats[2], $type);
    }

    $stmt->Close();

    return $boats;
}

Affected tables:

*

*boat: boatId, boatTypeId, length, memberId

*boatType: boatTypeId, type

A: The WHERE clause has to be listed after the table references. You have to move the WHERE m.memberId = ? to the end of the table references after the FROM and JOINs like so:
SELECT b.boatId, b.length, bt.type
FROM boat AS b
      INNER JOIN member AS m
          ON b.memberId = m.memberId

      INNER JOIN boatType AS bt
          ON b.boatTypeId = bt.boatTypeId
WHERE m.memberId = ?
GROUP BY b.boatId

A: as you in on clause, simply replace 'where' by 'and':
SELECT b.boatId, b.length, bt.type
              FROM boat AS b
                  INNER JOIN member AS m
                      ON b.memberId = m.memberId
                          AND m.memberId = ?
                  INNER JOIN boatType AS bt
                      ON b.boatTypeId = bt.boatTypeId
                  GROUP BY b.boatId


text:
Q: Examining $\mathbb{Z}[\sqrt{-3}]_{\mathfrak{p}}\subset \mathbb{Z}[\frac{1+\sqrt{-3}}{2}]_{\mathfrak{p}}$ The problem is to show that if $\mathfrak{p}\ne 0$ is  a prime ideal of
$\mathbb{Z}[\sqrt{-3}]=R$, and we denote $S=\mathbb{Z}[\frac{1+\sqrt{-3}}{2}]$ then we have $R\subset S$ and for the localizations $R_{\mathfrak{p}}\subset S_{\mathfrak{p}}$, and $R_{\mathfrak{p}}=S_{\mathfrak{p}}$  if $\mathfrak{p}$ does not contain $2$.
The inclusion is certainly still true since injectivity is a local property. For equality, I believe the intuition is clear but I am having trouble with the details. If $2\not \in \mathfrak{p}$, then it gets inverted, and there is no difference between $R$ and $S$ and whatever else gets inverted at this point. I imagine there is probably more to say. How do I fill in the details?
For added context on the problem: the first part was to show that
$S$ is finitely generated as an $R$ module, which is clear as $S$ is finitely generated as $\mathbb{Z}$ module, $\frac{1+\sqrt{-3}}{2}$ being integral over $\mathbb{Z}$. The final part is to show that $S$ is not a flat $R$ module, which I have not yet tackled.
Thanks in advance for any help.

A: As you said, if $2\not \in \mathfrak{p}$, then $1/2\in R_{\mathfrak{p}}$, hence also $\frac{1+\sqrt{-3}}{2}\in R_{\mathfrak{p}}$, so $R_{\mathfrak{p}}=S_{\mathfrak{p}}$.


text:
Q: Create New Categorical Variable (high, mid, low) I have this dataframe, and I would like to create a new categorical variable 'life.cat' that denotes for each country in each year, whether it is 'High' (> = 1 SD above the mean); 'Low' ( < = 1 SD below the mean); or else 'Mid', based on its lifeExp compared to that of other countries in its continent in each year.
structure(list(country = c("Afghanistan", "Afghanistan", "Afghanistan",
"Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan",
"Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Albania",
"Albania", "Albania", "Albania", "Albania", "Albania", "Albania",
"Albania", "Albania", "Albania", "Albania", "Albania", "Algeria",
"Algeria", "Algeria", "Algeria", "Algeria", "Algeria"), continent = c("Asia",
"Asia", "Asia", "Asia", "Asia", "Asia", "Asia", "Asia", "Asia",
"Asia", "Asia", "Asia", "Europe", "Europe", "Europe", "Europe",
"Europe", "Europe", "Europe", "Europe", "Europe", "Europe", "Europe",
"Europe", "Africa", "Africa", "Africa", "Africa", "Africa", "Africa"
), year = c(1952L, 1957L, 1962L, 1967L, 1972L, 1977L, 1982L,
1987L, 1992L, 1997L, 2002L, 2007L, 1952L, 1957L, 1962L, 1967L,
1972L, 1977L, 1982L, 1987L, 1992L, 1997L, 2002L, 2007L, 1952L,
1957L, 1962L, 1967L, 1972L, 1977L), lifeExp = c(28.801, 30.332,
31.997, 34.02, 36.088, 38.438, 39.854, 40.822, 41.674, 41.763,
42.129, 43.828, 55.23, 59.28, 64.82, 66.22, 67.69, 68.93, 70.42,
72, 71.581, 72.95, 75.651, 76.423, 43.077, 45.685, 48.303, 51.407,
54.518, 58.014), pop = c(8425333L, 9240934L, 10267083L, 11537966L,
13079460L, 14880372L, 12881816L, 13867957L, 16317921L, 22227415L,
25268405L, 31889923L, 1282697L, 1476505L, 1728137L, 1984060L,
2263554L, 2509048L, 2780097L, 3075321L, 3326498L, 3428038L, 3508512L,
3600523L, 9279525L, 10270856L, 11000948L, 12760499L, 14760787L,
17152804L), gdpPercap = c(779.4453145, 820.8530296, 853.10071,
836.1971382, 739.9811058, 786.11336, 978.0114388, 852.3959448,
649.3413952, 635.341351, 726.7340548, 974.5803384, 1601.056136,
1942.284244, 2312.888958, 2760.196931, 3313.422188, 3533.00391,
3630.880722, 3738.932735, 2497.437901, 3193.054604, 4604.211737,
5937.029526, 2449.008185, 3013.976023, 2550.81688, 3246.991771,
4182.663766, 4910.416756)), row.names = c(NA, 30L), class = "data.frame")

So far, I have tried this code:
library(dplyr)
df1 %>%
    group_by(continent, year) %>%
    mutate(Mean = mean(lifeExp),
           SD = sd(lifeExp),
           life.cat = case_when(Mean > (Mean + SD) ~ 'High',
                                Mean < (Mean - SD) ~ 'Low',
          TRUE ~ 'Mid'  ), Mean = NULL, SD = NULL) %>%
    ungroup

But the output in the new column is all "mid", which is not possible. Could any one tell me what went wrong?

A: Each continent-year only has one value in the subset of data you shared here, since Afghanistan, Albania, and Algeria are on different continents. SD produces an NA running on that example data since each group only has one element. It should work ok if there are multiple elements in each group. The NA in SD means that the case_when's first two terms will be false (in R, no number is bigger or smaller than NA), hence all "mid".
If you can't know there will be multiple elements in each group ahead of time, you might change sd(lifeExp) to coalesce(sd(lifeExp, 0) so that any NA's for SD turn into zeroes.
You also probably want to change the code here so that the current row's lifeExp is compared to the Mean+SD for its group. Comparing Mean > Mean + SD is always false, and Mean < Mean - SD is also always false.

A: You could use within and ave and do a straightforward case handling using bracketing. (Your data is not suitable for demonstration, I have created them new.)
e <- within(e, {
    le.mn <- ave(lifeExp, continent, year, FUN=mean)
    le.sd <- ave(lifeExp, continent, FUN=sd)
    life.cat <- NA
    life.cat[lifeExp < le.mn - le.sd] <- "lo"
    life.cat[lifeExp >= le.mn - le.sd] <- "mid"
    life.cat[lifeExp > le.mn + le.sd] <- "hi"
    rm(le.mn, le.sd)
})
e
#    country year continent  lifeExp life.cat
# 1        a 2015         A 29.14806      mid
# 2        a 2016         A 29.37075       hi
# 3        a 2017         A 22.86140      mid
# 4        a 2018         A 28.30448      mid
# 5        a 2019         A 26.41746      mid
# 6        a 2020         A 25.19096      mid
# 7        b 2015         A 27.36588      mid
# 8        b 2016         A 21.34667       lo
# 9        b 2017         A 26.56992      mid
# 10       b 2018         A 27.05065      mid
# 11       b 2019         A 24.57742      mid
# 12       b 2020         A 27.19112      mid
# 13       c 2015         B 29.34672      mid
# 14       c 2016         B 22.55429      mid
# 15       c 2017         B 24.62293      mid
# 16       c 2018         B 29.40015       hi
# 17       c 2019         B 29.78226      mid
# 18       c 2020         B 21.17487       lo
# 19       d 2015         B 24.74997      mid
# 20       d 2016         B 25.60333      mid
# 21       d 2017         B 29.04031      mid
# 22       d 2018         B 21.38710       lo
# 23       d 2019         B 29.88892      mid
# 24       d 2020         B 29.46668       hi

Data:
e <- structure(list(country = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L,
4L, 4L), .Label = c("a", "b", "c", "d"), class = "factor"), year = c(2015L,
2016L, 2017L, 2018L, 2019L, 2020L, 2015L, 2016L, 2017L, 2018L,
2019L, 2020L, 2015L, 2016L, 2017L, 2018L, 2019L, 2020L, 2015L,
2016L, 2017L, 2018L, 2019L, 2020L), continent = c("A", "A", "A",
"A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B",
"B", "B", "B", "B", "B", "B", "B", "B"), lifeExp = c(29.1480604349636,
29.3707541329786, 22.8613953478634, 28.3044762606733, 26.41745518893,
25.1909594913013, 27.3658831464127, 21.3466659723781, 26.5699229040183,
27.0506478403695, 24.5774177624844, 27.191122516524, 29.3467224715278,
22.5542882434092, 24.6229282254353, 29.4001452275552, 29.7822642838582,
21.1748736165464, 24.7499708156101, 25.6033274624497, 29.0403138729744,
21.3871016772464, 29.8889172892086, 29.466682325583)), out.attrs = list(
    dim = c(country = 4L, year = 6L), dimnames = list(country = c("country=a",
    "country=b", "country=c", "country=d"), year = c("year=2015",
    "year=2016", "year=2017", "year=2018", "year=2019", "year=2020"
    ))), row.names = c(NA, -24L), class = "data.frame")


text:
Q: JavaScript Array to String I'm using the jQuery plugin jQuery-Tokenizing-Autocomplete in a rails application with a has_many association.
I need to save the values to the database, but to do that I need it to be a string, not an array. So the result should equal "1","2","3". Hope this clarifies.
The javascript used to generate this array:
$.TokenList.ParseValue = function (value, settings) {
  var result = [];
  $.each(value, function(i, node) {
    if (node) {
      result.push(node.id);
    }
  });
  return result;
};

A: for array to string in javascript you can do it like this.
var str = (['1', '2', '3']).join(","); // will result to 1,2,3

similar syntax works for ruby code
['1', '2', '3']).join(",") # will return 1,2,3

A: The default separator for join is the comma, so remove the '","' argument.  You are specifying a separator of "," so the double quotes must be escaped in the result string, hence the backslashes.

A: var string = '"' + array.join('","') + '"'; // "1","2","3"


text:
Q: Parskip seems to reset after tabular environment I am working on a document in which I include some tables. However, when I include the tables, the \parskip length seems to reset to 0 afterwards. Why is that and how can I circumvent that?
The code I use with a small example is given in the following. Please note that I included every package I use for the sake of completeness. I do not know where the issue stems from exactly, so better include everything. So some packages are not required to display the following code per se.
The parskip option works fine before the table and is reset after it.
\documentclass[a4paper, bibtotocnumbered,liststotoc,12pt]{scrartcl}
\makeatletter
\usepackage{apacite}
\usepackage{hyperref}
\renewcommand\paragraph{\@startsection{paragraph}{4}{\z@}%
            {-2.5ex\@plus -1ex \@minus -.25ex}%
            {1.25ex \@plus .25ex}%
            {\normalfont\normalsize\bfseries}}
\makeatother
\setcounter{secnumdepth}{4}
\setcounter{tocdepth}{4}
\usepackage{xfakebold}

\usepackage{natbib}

\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
\usepackage[english]{babel}

\usepackage{setspace}
\linespread{1.25}
\setlength{\parindent}{0pt}
\setlength{\parskip}{8pt}

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{xfrac}
\usepackage{calrsfs}
\DeclareMathAlphabet{\pazocal}{OMS}{zplm}{m}{n}

\usepackage[paper=a4paper,left=40mm,right=20mm,top=20mm,bottom=20mm]{geometry}
\geometry{a4paper}
\usepackage{lmodern}
\usepackage{verbatim}
\setkomafont{sectioning}{\rmfamily\bfseries\boldmath}
\usepackage[usenames,dvipsnames]{color}

\usepackage{caption}
\captionsetup{labelfont=bf}
\captionsetup[figure]{aboveskip=10pt}
\captionsetup{justification=justified,singlelinecheck=false,font=small}

\usepackage{booktabs}
\usepackage{tabularx}
\usepackage{array}
\usepackage{graphicx}
\usepackage{rotating}
\usepackage{xtab}
\usepackage{float}
\usepackage{tikz}
\usetikzlibrary{positioning, shapes, arrows.meta}
\usetikzlibrary{decorations.pathreplacing, calc}
\tikzset{
    answer/.style={rectangle, draw, text width=15em, text badly centered, inner sep=0pt, minimum height=4em},
    inout/.style={rectangle, draw, text width=#1, text centered, rounded corners, minimum height=4em},
    line/.style={-{Stealth}}
}

\usepackage{booktabs}

\begin{document}

On insensible possession oh particular attachment at excellence in. The books arose but miles happy she. It building contempt or interest children mistress of unlocked no. Offending she contained mrs led listening resembled. Delicate marianne absolute men dashwood landlord and offended. Suppose cottage between and way. Minuter him own clothes but observe country. Agreement far boy otherwise rapturous incommode favourite.

Cause dried no solid no an small so still widen. Ten weather evident smiling bed against she examine its. Rendered far opinions two yet moderate sex striking. Sufficient motionless compliment by stimulated assistance at. Convinced resolving extensive agreeable in it on as remainder. Cordially say affection met who propriety him. Are man she towards private weather pleased. In more part he lose need so want rank no. At bringing or he sensible pleasure. Prevent he parlors do waiting be females an message society.

\smallskip
\captionof{table}{Hypothesis 3}
\begin{scriptsize}
\begin{tabular*}{\columnwidth}{@{\extracolsep{\stretch{1}}}*{5}{r}@{}}
  \toprule
  & $Estimation$ & $Standard \ Error$ & $t\text{-}Value$ & $Pr > |t|$  \\
  \midrule
  x. I & 0 & 80 & 80   \\
  x. II & 0 & 1 & 80   \\
  x.  & 0 & 0.39 & 0.02   \\
  x. I & 0 & 0.00 & 0.00 \\
  x. II & 0 & 0.00 & 0.13   \\
  x I & (-)** & 0.39 & 0.02   \\
  x II & 0 & 0.08 & 0.00   \\
  x I & 0 & 0.39 & 0.02   \\
  x II & 0 & 0.08 & 0.00   \\
  x & 0 & 0.00 & 0.13  \\
  x & 0 & 0.39 & 0.02   \\
  x & 0 & 0.39 & 0.02  \\
  x & 0 & 0.39 & 0.02  \\
  \bottomrule
\end{tabular*}
\caption*{\textit{Notes}: TBD}
\end{scriptsize}
\bigskip

On insensible possession oh particular attachment at excellence in. The books arose but miles happy she. It building contempt or interest children mistress of unlocked no. Offending she contained mrs led listening resembled. Delicate marianne absolute men dashwood landlord and offended. Suppose cottage between and way. Minuter him own clothes but observe country. Agreement far boy otherwise rapturous incommode favourite.

Cause dried no solid no an small so still widen. Ten weather evident smiling bed against she examine its. Rendered far opinions two yet moderate sex striking. Sufficient motionless compliment by stimulated assistance at. Convinced resolving extensive agreeable in it on as remainder. Cordially say affection met who propriety him. Are man she towards private weather pleased. In more part he lose need so want rank no. At bringing or he sensible pleasure. Prevent he parlors do waiting be females an message society.

\end{document}

A: You could simplify your example to
\documentclass[a4paper, bibtotocnumbered,liststotoc,12pt]{scrartcl}

\usepackage{caption}

\begin{document}

[\the\parskip]

\captionof{table}{Hypothesis 3}
\begin{scriptsize}
\caption*{\textit{Notes}: TBD}
\end{scriptsize}
\bigskip

[\the\parskip]

\end{document}

showing the changed value of \parskip. Note that you are using caption package that documents that \caption should not be used at teh top level and the terminal and log file warn:
Package caption Warning: \captionsetup{type*=...} or \captionof
(caption)                outside box or environment on input line 10.
See the caption package documentation for explanation.

Placing the code inside any environment or even a simple {...} group will restore all the local settings after the group.


text:
Q: IDL RDFLOAT Undefined I am a beginner in IDL.
I am trying to use RDFLOAT in the following format in a terminal:
rdfloat,'filename.dat',d,sf,wts
this is the error I get,

% Attempt to call undefined procedure/function: 'RDFLOAT'.
% Execution halted at: $MAIN$

Kindly help me resolve this.
Thank you in advance!

A: RDFLOAT is a third party routine I am not familiar with. Is it a function? Is it in your IDL !path?


text:
Q: Simple replace across an array fails - unexpected output suppose I have an array and I want to bracket each of its elements.  I would expect the following would do it:
"a b c d".split() -replace ".*", "<$&>"

however the output I get is:
<>
<>
<c><>
<d><>

instead of:

<c>
<d>

and I can't figure out why.  what's going on with this?

A: I'm not sure, but I think it happens because you used .* as a pattern - the parser also treats null string as matches and that's why you get the extra matches. You can fix it by using the pattern:
^.*

which will force the matches to start from the beginning of the line.


text:
Q: Safe timeout value for codeigniter session class? I am using codeigniter's session class to handle my PHP sessions. One of the session variables automatically created on every visit to the site is session_id:

The user's unique Session ID (this is a statistically random string with very strong entropy, hashed with MD5 for portability, and regenerated (by default) every five minutes)

On my site I need to have functionality to track unregistered user's and I currently have this implemented by comparing the visitor's session_id with a stored id value in a VISITOR table in the database.  This works perfectly except for the fact that the session id times out every five minutes.  I would like my application to remember visitors for longer than 5 minutes (kind of like what SO does when you post a question or answer without registering).
My question is this: can you see any security issues with simply extending the regeneration time of the session class (to something like 12 hours)?
Update: based on the answers I've seen so far, it seems like its more of a performance concern rather than a safety issue.  Its kinda weird how the codeigniter session class works because when creating a new session, it also creates a new cookie which seems to persist as long as the session.  I guess I could create another cookie with the session ID that lasts as long as I need it to.  But how much of a performance concern would it be if I were to save the sessions for something like 12 hours?  Would it slow things down unless I have millions of unique visitors within a 12 hour period (in which case I'd have bigger problems to worry about...)?

A: Two things with that idea :

*

*If users go away from their computer (without locking it / closing their browser), someone else might use it to go to your site with their account

*

*well, that's probably not your problem

*if you have some login/password fields, your users probably already have their login+password memorized by the browser anyway (well, for the registedred ones, anyway -- and those probably have more "power" than not registered ones)

*If you have lots of users on your site, you will have more session files

*

*as sessions are stored in files

*(same if they are stored in DB / memcached -- in which case you must ensure you have configured memcached so there is enough RAM to store more sessions)

So, yes, there is a small security risk ; but I don't think it is really relevant.

Another idea would be to keep a short session lifetime, but to store some informations in cookies, with a lifetime more important than that ?
Enough information, actually, to allow re-creation of a new session, without the user noticing anything ?
But, yes, that would require a bit more work on your side...

To add a bit more precisions after your edit :

Its kinda weird how the codeigniter
  session class works because when
  creating a new session, it also
  creates a new cookie which seems to
  persist as long as the session.

This is the "standard" way of dealing with sessions -- at least, in PHP :

*

*The session's data is stored in a file, on disk, on the server

*and a cookie is used to keep a "link" between a user, and the file containing his session's information. Without that cookie, there would be no way of knowing which one of those files contains the session of a specific user.

But how much of a performance concern
  would it be if I were to save the
  sessions for something like 12 hours?

If you're having millions of users on your site, this will means having millions of files, each one containing the session's data of one user -- and it's not good to have too many files.
But is you are having a few hundreds user, that should be allright, I guess.

A: Depending on the amount of visitors to your site, saving sessions for 12 hours may not be a good idea. Why not use cookies? This is dependent on whether or not the user has it enabled in his browser though: http://www.php.net/setcookie.

A: One Security Tip:
Leave True on sess_match_useragent(application/config/config.php)


text:
Q: Jquery - Show / Hide Textarea when a href is clicked I have an a href and a textarea, I used link because the button is not fit in my design. The problem is I want to Show the textarea when the tag  is clicked and change the text from "Reply (show)" to "Reply (hide)" my code isn't working.
$(document).ready(function(){
    $("#replyshow").click(function(){
    var rep = $("#replyshow").text();
    event.preventDefault();
    if (rep == "Reply (show)") {
        $("#reply").show(500);
        rep = $("#replyshow").text("Reply (hide)");
    } else {
        $("#reply").hide(500);
        rep = $("#replyshow").text("Reply (show)");
    }
    });
});

A: You are missing event in click function call as @Jagadeesh commented. Your code should look like this:

$(document).ready(function(){
  $("#replyshow").click(function(event){ // event is added here!
    var rep = $("#replyshow").text();
    event.preventDefault();
    if (rep == "Reply (show)") {
     $("#reply").show(500);
     rep = $("#replyshow").text("Reply (hide)");
    } else {
     $("#reply").hide(500);
     rep = $("#replyshow").text("Reply (show)");
    }
  });
 });

Reply (hide)

<textarea id="reply"></textarea>


text:
Q: inner join with group by expression in oracle sql I am new to sql, any help is appreciated.
I have two tables, employees and jobs. employees contain a variable job_id (multiple employees can have the same job_ID). jobs contain variables job_id and job_title (one job_ID correspond to one job_title, this is the hr schema in oracle if you are interested).
I want the query to return: the job_title, job_ID and the number of people who have the same job_Id.
I tried the following code:
select j.job_title, e.job_ID, count(e.job_ID)
from employees e, jobs j
where e.job_id=j.job_id
group by e.job_Id

the error message is:

ORA-00979: not a GROUP BY expression
  00979. 00000 -  "not a GROUP BY expression"
  *Cause:
  *Action:
  Error at Line: 83 Column: 8

Can you help me fix this?

A: The error message is a bit misleading.  When you select a bunch of fields and an aggregate, you have to group by every field you select and only the fields you select. So your query has to be:
select j.job_title, e.job_ID, count(e.job_ID)
from employees e, jobs j
where e.job_id=j.job_id
group by e.job_Id, j.job_title


text:
Q: Detecting and dynamicly loading the installed Microsoft Word Object Library A little back story: I have small application that will use Word to generate a Outlook signature based on a Word template and data from the company active directory. It works wonderful on computers with Office 2007, since I used "Microsoft Word 12.0 Object Library" when I coded it on my own computer.
There are quite a few computers on the network with Office 2003 though, and on those computers "Microsoft Word 12.0 Object Library" is missing, resulting in exceptions left and right.
My question is: How do I detect which version of Office is installed and thus which version of the "Microsoft Word Object Library" is available, and subsequently load it. I am quite sure that the functionality I am using are in both the "Microsoft Word 12.0 Object Library" and the "Microsoft Word 11.0 Object Library".
In case anybody is interested, here is my current code used to generate the signature:
class Signature
{
    public Dictionary<string, string> TemplateMappings { get; set;}
    public string SignatureTemplateFileName { get; set; }
    public string SignatureName { get; set;}
    public bool UseSignatureWithNewMessages { get; set; }
    public bool UseSignatureInReplyMessages { get; set; }

    public Signature()
    {
        UseSignatureWithNewMessages = true;
        UseSignatureInReplyMessages = true;
        TemplateMappings = new Dictionary<string, string>();
    }

    public void Create()
    {
        if(string.IsNullOrEmpty(SignatureTemplateFileName) || !File.Exists(SignatureTemplateFileName))
        {
            throw new InvalidOperationException("SignatureTemplateFileName is null or the file do not exists");
        }

        if(string.IsNullOrEmpty(SignatureName))
        {
            throw new InvalidOperationException("No SignatureName specified");
        }

        object nullObject = System.Reflection.Missing.Value;
        object signatureTemplate = SignatureTemplateFileName;

        // open word doc
        var word = new ApplicationClass();
        var doc = word.Documents.Add(ref signatureTemplate, ref nullObject, ref nullObject, ref nullObject);

        // search/replace user info
        object wdReplaceAll = WdReplace.wdReplaceAll;
        var find = word.Selection.Find;
        foreach (var pair in TemplateMappings)
        {
            find.Text = pair.Key;
            find.Forward = true;
            find.MatchCase = true;
            find.MatchWholeWord = true;
            find.Replacement.Text = pair.Value;
            find.Execute(ref nullObject /* FindText */,
                         ref nullObject /* MatchCase*/,
                         ref nullObject /* MatchWholeWord*/,
                         ref nullObject /* MatchWildcards*/,
                         ref nullObject /* MatchSoundsLike*/,
                         ref nullObject /* MatchAllWordForms*/,
                         ref nullObject /* Forward*/,
                         ref nullObject /* Wrap*/,
                         ref nullObject /* Format*/,
                         ref nullObject /* ReplaceWith*/,
                         ref wdReplaceAll /* Replace*/,
                         ref nullObject /* MatchKashida*/,
                         ref nullObject /* MatchDiacritics*/,
                         ref nullObject /* MatchAlefHamza*/,
                         ref nullObject /* MatchControl */);
        }

        // Add signature to outlook
        var signatureRange = doc.Range(ref nullObject, ref nullObject);
        word.EmailOptions.EmailSignature.EmailSignatureEntries.Add(SignatureName, signatureRange);

        // set new signature as default for news messages and replies
        if (UseSignatureWithNewMessages)
            word.EmailOptions.EmailSignature.NewMessageSignature = SignatureName;
        if (UseSignatureInReplyMessages)
            word.EmailOptions.EmailSignature.ReplyMessageSignature = SignatureName;

        // close and clean up
        doc.Saved = true;
        doc.Close(ref nullObject, ref nullObject, ref nullObject);
        word.Quit(ref nullObject, ref nullObject, ref nullObject);
    }
}

Any help will be much appreciated. Input on the code above is also welcome; I do not have any experience coding against Office Interop library, so I am sure there are things I can do differently.
Best regards, Egil.

A: OK found what I was looking for.
MS Office For Net abstracts away the headaches of the underlying Office interop assembly versions.  Perhaps you can use it directly in your project, else study it's implementation to understand how to address this issue.  The folks working on that project are probably a great resource to ask interop questions as well..


text:
Q: not able to set the other variables inside dirReader.readEntries() html5 I am working on folder uploads in HTML5. I am using the DirectoryReader.readEntries function() to read the entries inside the directory. I am successfully able to iterate over the entries but I need to return the list of names of all the names of the entries inside the directory. I tried creating an array outside and setting it inside the readEntries function, but it array is set inside the function properly and is unchanged outside the readEntries function. I also tried using a global variable and set the values there, but that too doesn't seem to work. Also, in some cases I have seen on the web that we can do
var entries  = dirReader.readEntries(); and it does return the entries and then we can iterate over it. But in my case it throws an exception and is not able to read the directory.
https://developer.mozilla.org/en-US/docs/Web/API/DirectoryReaderSync
My code :
var subResourceNames = [];
 var dirReader = e.createReader();
 dirReader.readEntries(function(entries) {
     for(var i = 0; i < entries.length; i++) {
        subResourceNames.push(new String(entry.name));
        }
 });

console.log("outside readEntries (subresourcenames ):"+subResourceNames);
return subResourceNames;

subResourceNames is still empty when it comes outside the readEntries, but if I print it after the for loop is complete it is giving a populated array.What should I do to the the values outside. Even returning the value from the readEntries function and assigning it to some variable doesn't work.


text:
Q: get all content between a custom tag with regular expression I need to extract all the contents of a custom tag that I created, but I try to make some form and it is not working, let's practice then:
context
{{#teste}}
                texto1
                {{#teste2}}
                    texto2
                {{/teste2}}
            {{/teste}}

I need extract all content from {{#teste}} ... {{/teste}}.
So far, I have arrived at the following code:
{{#teste}}(.|\n\s)*?{{\/teste}}

However, I need everything that was gitiated between and not containing itself.
Example: https://regex101.com/r/cyu3sL/1

A: (?<={{#teste}})(?>.|\s)*?(?={{\/teste}})

captures everything between but excluding {{#teste}} and {{/teste}}
Test regex


text:
Q: how to make polymer iron-list keep expanding, instead of scolling I am following the example of collapsible items of iron-list. However, I have more content under the iron-list, say an iron-menu.
The issue is that the height of the iron-list does not dynamically increase as the user expand the iron-list contents. Instead the iron-list becomes scollable, making it hard to see all the contents.
I would like the iron-list to expand in height, and push down the content (iron-menu) below. Is there a way to do this? Many thanks.
I also tried to set the scroll-target, but it doesn't push the content below down. It overlaps the iron-list content onto the content below, which is not what I want.
<iron-list scroll-target="document" ... >

A: The size of the iron-list must be set explicitly, as described on the iron-list project ReadMe under "Sizing iron-list".
So you could use javascript to change the height, based on other conditions.
The other way of putting something 'below' an iron-list is to compute whether you are on the last list item, and add in a custom row (i.e. pagination) as shown here
But if you don't have a huge dataset, you could use dom-repeat, which will add nodes to the DOM, and therefore you could have your list expand.

A: I finally find a solution. As you can see from the example, the function getClassForItem() changes the div class to control show/hide. Thus we can trigger the resize event together with it.
    getClassForItem: function(item, selected) {
      this.querySelector('iron-list').fire('iron-resize'); // added line
      return selected ? 'item expanded' : 'item';
    }


text:
Q: DotNetNuke 5 - How do I dynamically create a Page, select a Skin, and assign Modules to it? In DNN 5, I need to:

*

*Dynamically create a page (programmatically)

*select a skin

*assign modules to the page

How do I do this?
Thanks

A: The Mass Tabs project on codeplex is doing the page creation portion of what you are looking for.
There is also an article here.