问:
C struct pointers return
```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_BUFFER_SIZE 100

typedef struct config_struct config_t ;

struct config_struct{
    char name[20];
        char ip[20];
        int port;
        char log[100];
};

int main(int argc, char *argv[]) {
        config_t config;
        read_config_file(argv[1], &config);
        return 0;
}

int read_int_from_config_line(char* config_line) {
        int val = atoi(config_line);
        return val;
}

void read_str_from_config_line(char* config_line, char* val) {
        strncpy(val,config_line, MAX_BUFFER_SIZE);
}

void read_config_file(char* config_filename, config_t *config) {
        FILE *fp;
        char *value, buffer[MAX_BUFFER_SIZE];
        fp = fopen("./settings.conf", "r");
        while (fgets(buffer, MAX_BUFFER_SIZE, fp) != NULL) {
            if(!strcmp(buffer,"NAME")) {
                    read_str_from_config_line(value, &(config->name));
        }
            if(!strcmp(buffer,"PORT")) {
                &(config->port) = read_int_from_config_line(value);
                }

        }
}
</code>```

I try to compile this code and it gives me a incompatible pointer type at read_str_from_config_line(value , &(config->name)); and lvalue required as left operand of assignment  &(config->port) = read_int_from_config_line(value);

I am trying to return the stuct back to the main program but I'm having problem with the struct pointers.

Any solution for it to be solve?
PS: The code is a mess as I trying to shorten it. Any help will be good as I am still a beginner to C programming.

Thanks

答:
```<code>                read_str_from_config_line(value, &(config->name));
</code>```

confg->name is declared as a char array, which naturally decays to a pointer to the first element (of type "pointer-to-char") if you omit the &:

```<code>                read_str_from_config_line(value, config->name);
</code>```

Taking its address explicitly instead results in a pointer of type pointer-to-array-of-20-chars, which is not the same type as pointer-to-char - which is why you are getting an error. This is a common source of confusion in C; in general, you should not take the address of an array (although it does have legitimate use cases).

In this line:

```<code>            &(config->port) = read_int_from_config_line(value);
</code>```

You are taking the address of the port member of the structure pointed at by config, which is a non-lvalue pointer. It looks like you are actually trying to assign to the member, so the line should read:

```<code>            config->port = read_int_from_config_line(value);
</code>```

Title: C struct pointers return

Body:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_BUFFER_SIZE 100

typedef struct config_struct config_t ;

struct config_struct{
    char name[20];
        char ip[20];
        int port;
        char log[100];
};

int main(int argc, char *argv[]) {
        config_t config;
        read_config_file(argv[1], &config);
        return 0;
}

int read_int_from_config_line(char* config_line) {
        int val = atoi(config_line);
        return val;
}

void read_str_from_config_line(char* config_line, char* val) {
        strncpy(val,config_line, MAX_BUFFER_SIZE);
}

void read_config_file(char* config_filename, config_t *config) {
        FILE *fp;
        char *value, buffer[MAX_BUFFER_SIZE];
        fp = fopen("./settings.conf", "r");
        while (fgets(buffer, MAX_BUFFER_SIZE, fp) != NULL) {
            if(!strcmp(buffer,"NAME")) {
                    read_str_from_config_line(value, &(config->name));
        }
            if(!strcmp(buffer,"PORT")) {
                &(config->port) = read_int_from_config_line(value);
                }

        }
}

I try to compile this code and it gives me a incompatible pointer type at read_str_from_config_line(value , &(config->name)); and lvalue required as left operand of assignment  &(config->port) = read_int_from_config_line(value);

I am trying to return the stuct back to the main program but I'm having problem with the struct pointers.

Any solution for it to be solve?
PS: The code is a mess as I trying to shorten it. Any help will be good as I am still a beginner to C programming.

Thanks

Body:
                read_str_from_config_line(value, &(config->name));

confg->name is declared as a char array, which naturally decays to a pointer to the first element (of type "pointer-to-char") if you omit the &:

                read_str_from_config_line(value, config->name);

Taking its address explicitly instead results in a pointer of type pointer-to-array-of-20-chars, which is not the same type as pointer-to-char - which is why you are getting an error. This is a common source of confusion in C; in general, you should not take the address of an array (although it does have legitimate use cases).

In this line:

            &(config->port) = read_int_from_config_line(value);

You are taking the address of the port member of the structure pointed at by config, which is a non-lvalue pointer. It looks like you are actually trying to assign to the member, so the line should read:

            config->port = read_int_from_config_line(value);


来源: stackexchange

答:
The & operator means "take the address of the object to the right".

This:

```<code>&(config->port)
</code>```

means "take the address of the port member of the structure pointed to by config.

You don't want to take the address, you just want to assign to the member. That's just:

```<code>config->port = ...
</code>```

This is the same as (*config).port, but nobody writes it like that since the arrow operator is so convenient.

ContentLicense: CC BY-SA 3.0

Title: C struct pointers return

Body:
The & operator means "take the address of the object to the right".

This:

&(config->port)

means "take the address of the port member of the structure pointed to by config.

You don't want to take the address, you just want to assign to the member. That's just:

config->port = ...

This is the same as (*config).port, but nobody writes it like that since the arrow operator is so convenient.


问:
AutoMapper: ignore property on update existing, but allow when create
Is it possible to configure/use AutoMapper in such a way where when i create an object from a mapping i allow all properties and child collections, however, when it comes to performing an update to existing object, the mapping will ignore child collection properties as they will be empty but i dont want them removed.

This is because i am working with a WCF service that sends delta changes to objects and most of my model works in a tree hierarchy:

```<code>Parent
  List<Child> Children

ParentDto
  List<ChildDto> Children

config.CreateMap<ParentDto, Parent>();
config.CreateMap<ChildDto, ChildDto>();
</code>```

This works well and the child collection is populated first time round. However, there are scenarios where i will send the ParentDto across with just the parent POCO property changes (such as a datetime change), but the child list will be empty as none of them have changed. Normally i would do:

```<code>_Mapper.Map<ParentDto,Parent>(dto, local)
</code>```

but obviously that will change the entire tree and populate the local object with an empty child list. Massively simplifying but would something like

```<code>_Mapper.Map<ParentDto, Parent>(dto, local).Ignore(p => p.Children)
</code>```

be possible?

I should also add I am using SimpleInjector DI framework. So perhaps there is a way to register 2 configurations, one with ignore and one without?

答:
For those who still struggle to find this. You can use Autommapper Conditional Mapping.

You can do it like this, in the Initialize

```<code>config.CreateMap<ChildDto, ChildDto>().ForMember(dest => dest.Children, opt => opt.Condition(source => source.TriggerChildMap));
</code>```

This will ignore mapping based on the property in source object. To map against existing destination you need to use
Mapper.Map(source, destination) method and not the var result = Mapper.Map<ChildDto>(source) property.

Body:
Is it possible to configure/use AutoMapper in such a way where when i create an object from a mapping i allow all properties and child collections, however, when it comes to performing an update to existing object, the mapping will ignore child collection properties as they will be empty but i dont want them removed.

This is because i am working with a WCF service that sends delta changes to objects and most of my model works in a tree hierarchy:

Parent
  List<Child> Children

ParentDto
  List<ChildDto> Children

config.CreateMap<ParentDto, Parent>();
config.CreateMap<ChildDto, ChildDto>();

This works well and the child collection is populated first time round. However, there are scenarios where i will send the ParentDto across with just the parent POCO property changes (such as a datetime change), but the child list will be empty as none of them have changed. Normally i would do:

_Mapper.Map<ParentDto,Parent>(dto, local)

but obviously that will change the entire tree and populate the local object with an empty child list. Massively simplifying but would something like

_Mapper.Map<ParentDto, Parent>(dto, local).Ignore(p => p.Children)

be possible?

I should also add I am using SimpleInjector DI framework. So perhaps there is a way to register 2 configurations, one with ignore and one without?

Body:
For those who still struggle to find this. You can use Autommapper Conditional Mapping.

You can do it like this, in the Initialize

config.CreateMap<ChildDto, ChildDto>().ForMember(dest => dest.Children, opt => opt.Condition(source => source.TriggerChildMap));

This will ignore mapping based on the property in source object. To map against existing destination you need to use
Mapper.Map(source, destination) method and not the var result = Mapper.Map<ChildDto>(source) property.


答:
```<code> while(!(output.charAt(end-1)==','))
{
end--;
}
</code>```

change it to

```<code> while(!(output.charAt(end-1)==','))
    {

  if(end>=1)
    end--;
  else
    break;

    }
</code>```

You will not get error but you may want to change else part.
Also, you didn't ask specifically but check this link out.

How to split a string in Java

Title: How to substring a given string with specific rules in java

Body:
This is my code and it is showing error at while.Index out of bound exception is coming.The substrings should be such that

Max 50 characters per string

No number should be broken - for example " 4318, 4466, 486," is acceptable but  " 4318, 4466, 48" is not

Substring should always start with one space and end with comma ","

can someone help me out with this please

 public class MyString {

/**
 * @param args

 */
static String input = " 4318, 4466, 486, 1698, 478, 590, 582, 1594, 486, 1690, 702, 378, 486, 586, 486, 1694, 486, 598, 538, 526, 486, 1694, 486, 622, 434, 630, 462, 1730, 422, 1754, 450, 586, 486, 1690, 498, 1682, 486, 586, 502, 606, 454, 1698, 478, 1694, 486, 1718, 458, 1686, 726, 1458, 646, 426, 486, 1694, 482, 1694, 486, 590, 482, 622, 490, 550, 490, 602, 450, 634, 466, 586, 486, 1730, 426, 1714, 494, 622, 446, 590, 494, 618, 450, 586, 490, 586, 486, 1730, 450, 586, 486, 590, 502, 1674, 530, 1650, 482, 1690, 558, 1622, 486, 1690, 486, 5298, 4306, 4466, 530, 1646, 486, 594, 650, 1502, 546, 1650, 490, 586, 486, 622, 522, 1622, 486, 602, 454, 634, 462, 1694, 482, 590, 486, 590, 486, 1694, 482, 1730, 450, 590, 498, 1638, 526, 1690, 498, 606, 458, 586, 486, 1698, 482, 1694, 482, 1690, 486, 1694, 486, 1698, 574, 494, 486, 1714, 462, 1690, 486, 626, 430, 610, 486, 590, 490, 622, 426, 610, 498, 618, 446, 1690, 486, 1734, 446, 590, 482, 590, 502, 606, 454, 590, 502, 582, 478, 1690, 486, 586, 506, 578, 482, 1686, 558, 1622, 674, 1506, 482, 1698, 590, 1606, 462, 1000";
char space=' ';
 static char comma=',';
public static void main(String[] args) {
    // TODO Auto-generated method stub
    int start=0, end=0;
    while (end-1 < input.length()){

    start=end;
    end= start+ 50;

    String output= input.substring(start,end);
    if(output.charAt(start)==' ' && output.charAt(end-1)==',')
    {
    System.out.println(output);
    }
    else
    {

    while(!(output.charAt(end-1)==','))
    {

    end--;

    }
    output= input.substring(start,end);
    System.out.println(output);

    }
    }
    }

}

Body:
 while(!(output.charAt(end-1)==','))
{
end--;
}

change it to

 while(!(output.charAt(end-1)==','))
    {

  if(end>=1)
    end--;
  else
    break;

    }

You will not get error but you may want to change else part.
Also, you didn't ask specifically but check this link out.

How to split a string in Java


问:
Spring AOP pointcut definition for string setter
I'm developing an aspect that checks string arguments of setter methods of my entity package for empty strings and replace them with null values. But unfortunately my aspect doesn't works well :(. I guess it is because of my pointcut definition, but I'm not sure.

My aspect looks like:

```<code>import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class EmptyStringToNullSetter {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(EmptyStringToNullSetter.class);

    public void check(final JoinPoint jp) {
        LOGGER.debug(jp.getSignature().toLongString());
    }
}
</code>```

My spring config looks like:

```<code><bean id="emptyStringToNullSetter" class="de.foo.util.aop.parameter.EmptyStringToNullSetter" />
<aop:config>
    <aop:pointcut id="entityStringSetter" expression="execution(* de.foo.entity.*.set*(..)) and args(java.lang.String)" />
    <aop:aspect id="checkEmptyStringsAspect" ref="emptyStringToNullSetter">
        <aop:before method="check" pointcut-ref="entityStringSetter" />
    </aop:aspect>
</aop:config>
</code>```

My test class looks like:

```<code>import de.foo.entity.Period;

@ContextConfiguration(locations = { "/spring/test-util-context.xml" })
public class EmptyStringToNullSetterTest extends
    AbstractJUnit4SpringContextTests {
    @Test
    public void testCheck() {
        Period period = new Period();
        period.setName("");
        Assert.assertNull(period.getName());
    }
}
</code>```

When I execute my test the aspect doesn't intercept my setter. Do anyone has any idea why?!

Cheers,

Kevin

答: Since you are using proxy-based AOP, the advice will apply only to Spring beans and the "period" object isn't a bean. You need to either have "period" as a bean or use AspectJ's weaving based AOP. In either case, you will also need to use an around advice instead of before.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm developing an aspect that checks string arguments of setter methods of my entity package for empty strings and replace them with null values. But unfortunately my aspect doesn't works well :(. I guess it is because of my pointcut definition, but I'm not sure.

My aspect looks like:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class EmptyStringToNullSetter {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(EmptyStringToNullSetter.class);

    public void check(final JoinPoint jp) {
        LOGGER.debug(jp.getSignature().toLongString());
    }
}

My spring config looks like:

<bean id="emptyStringToNullSetter" class="de.foo.util.aop.parameter.EmptyStringToNullSetter" />
<aop:config>
    <aop:pointcut id="entityStringSetter" expression="execution(* de.foo.entity.*.set*(..)) and args(java.lang.String)" />
    <aop:aspect id="checkEmptyStringsAspect" ref="emptyStringToNullSetter">
        <aop:before method="check" pointcut-ref="entityStringSetter" />
    </aop:aspect>
</aop:config>

My test class looks like:

import de.foo.entity.Period;

@ContextConfiguration(locations = { "/spring/test-util-context.xml" })
public class EmptyStringToNullSetterTest extends
    AbstractJUnit4SpringContextTests {
    @Test
    public void testCheck() {
        Period period = new Period();
        period.setName("");
        Assert.assertNull(period.getName());
    }
}

When I execute my test the aspect doesn't intercept my setter. Do anyone has any idea why?!

Cheers,

Kevin


问:
How to remove folder symbol which comes in front of each node from JTree in java
I am trying to remove the folder symbol from node of JTree which comes by default.
How can I accomplish this?</p>

答:
```<code>DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) jTree.getCellRenderer();
    renderer.setLeafIcon(null);
    renderer.setClosedIcon(null);
    renderer.setOpenIcon(null);
</code>```

<p>The jtree uses CellRender, for example DefaultTreeCellRenderer, and you can dasable or change default nodes icon. Also, you can create custom cellRender and defined more dificult logic for you icon scheme. </p>

```<code>tree.setCellRenderer(new DefaultTreeCellRenderer() {
                @Override
                public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                    JLabel component = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
                    ImageIcon iconPath = ((WizardNode) value).getIcon();
                    component.setIcon(iconPath);
                    return this;
                }
            });
</code>```

Body:
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) jTree.getCellRenderer();
    renderer.setLeafIcon(null);
    renderer.setClosedIcon(null);
    renderer.setOpenIcon(null);

The jtree uses CellRender, for example DefaultTreeCellRenderer, and you can dasable or change default nodes icon. Also, you can create custom cellRender and defined more dificult logic for you icon scheme.

tree.setCellRenderer(new DefaultTreeCellRenderer() {
                @Override
                public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                    JLabel component = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
                    ImageIcon iconPath = ((WizardNode) value).getIcon();
                    component.setIcon(iconPath);
                    return this;
                }
            });


问:
Differences in these subclass definitions?
Could someone explain what is the difference between the following class definitions derived from BaseClass and in what cases it would matter how they are defined:

```<code>class BaseClass(object):
    def __init__(self):
        # ...

    def as_dict(self):
        # ...

class SomeClass(BaseClass):

    def as_dict(self):
        # Does this somehow change the method compared to 'AnotherClass.as_dict()' below
        return super(SomeClass, self).as_dict()

class AnotherClass(BaseClass): pass

SomeOtherClass = BaseClass
</code>```

答:
Since you add an as_dict method to SomeClass that contains a single super call,  there's no difference in the end behavior for that class. There's a difference in the fact that, overall, you've added a couple more function calls that are not necessary.

AnotherClass behaves just like SomeClass since SomeClass doesn't do anything different in as_dict. It inherits the methods of BaseClass as usual.

SomeOtherClass is simply another name for BaseClass, you aren't creating a subclassing relationship there, just attaching another name by which you can refer to that class.

Body:
Could someone explain what is the difference between the following class definitions derived from BaseClass and in what cases it would matter how they are defined:

class BaseClass(object):
    def __init__(self):
        # ...

    def as_dict(self):
        # ...

class SomeClass(BaseClass):

    def as_dict(self):
        # Does this somehow change the method compared to 'AnotherClass.as_dict()' below
        return super(SomeClass, self).as_dict()

class AnotherClass(BaseClass): pass

SomeOtherClass = BaseClass


问:
sqlite3 python inner join syntax
I have created a customer and orders table for a demo project using SQLITE3 and Python 3.  I am trying to select data from both the CUSTOMER and ORDERS table.

CUSTOMERID is a foreign key on the ORDERS table.

```<code>import sqlite3
conn = sqlite3.connect('promhire.db')
print("Opened database successfully")

cursor = conn.execute ('''\
            SELECT ORDERS.ORDERID, ORDERS.CUSTOMERID ORDERS.ORDERDATE CUSTOMERS.CUSTOMERID, CUSTOMERS.FIRSTNAME
            FROM ORDERS
            INNER JOIN CUSTOMERS
            ON ORDERS.CUSTOMERID = CUSTOMERS.CUSTOMERID
            WHERE CUSTOMERS.CUSTOMERID = 1''')
for row in cursor:
    print(row)
conn.close()
</code>```

screenshot of code

The error I am getting is

```<code>"OperationalError: near ".": syntax error"
Highlighting the last line of SQL.
</code>```

screenshot of error

Any ideas how to code this correctly for Python?

Thanks

答:
check comma (",") in query

```<code>select orders.orderid, orders.customerid,orders.orderdate,customers.customerid,customers.firstname from orders ..
</code>```

Edit :

```<code>cursor = conn.execute ('''\
            SELECT ORDERS.ORDERID, ORDERS.CUSTOMERID, ORDERS.ORDERDATE, CUSTOMERS.CUSTOMERID, CUSTOMERS.FIRSTNAME
            FROM ORDERS
            INNER JOIN CUSTOMERS
            ON ORDERS.CUSTOMERID = CUSTOMERS.CUSTOMERID
            WHERE CUSTOMERS.CUSTOMERID = 1''')
</code>```

Title: sqlite3 python inner join syntax

Body:
I have created a customer and orders table for a demo project using SQLITE3 and Python 3.  I am trying to select data from both the CUSTOMER and ORDERS table.

CUSTOMERID is a foreign key on the ORDERS table.

import sqlite3
conn = sqlite3.connect('promhire.db')
print("Opened database successfully")

cursor = conn.execute ('''\
            SELECT ORDERS.ORDERID, ORDERS.CUSTOMERID ORDERS.ORDERDATE CUSTOMERS.CUSTOMERID, CUSTOMERS.FIRSTNAME
            FROM ORDERS
            INNER JOIN CUSTOMERS
            ON ORDERS.CUSTOMERID = CUSTOMERS.CUSTOMERID
            WHERE CUSTOMERS.CUSTOMERID = 1''')
for row in cursor:
    print(row)
conn.close()

screenshot of code

The error I am getting is

"OperationalError: near ".": syntax error"
Highlighting the last line of SQL.

screenshot of error

Any ideas how to code this correctly for Python?

Thanks

Body:
check comma (",") in query

select orders.orderid, orders.customerid,orders.orderdate,customers.customerid,customers.firstname from orders ..

Edit :

cursor = conn.execute ('''\
            SELECT ORDERS.ORDERID, ORDERS.CUSTOMERID, ORDERS.ORDERDATE, CUSTOMERS.CUSTOMERID, CUSTOMERS.FIRSTNAME
            FROM ORDERS
            INNER JOIN CUSTOMERS
            ON ORDERS.CUSTOMERID = CUSTOMERS.CUSTOMERID
            WHERE CUSTOMERS.CUSTOMERID = 1''')


问:
Validation (vs) Sanitization in Symfony2+Twig?
I need my users to enter the URI of their personal website in their profile so that other users can see and click on it. I am worried that this could lead to XSS attacks if the output is not sanitized properly.

Like in this very simplistic schema below:

I am using the full stack symfony2 framework, Doctrine as ORM and Twig as a template engine. I know that Symfony provides some amazing Validation tools, and that TWIG provides automatic output escaping (which is not necessary in this particular case) as well as some filters for output sanitizing.

I've read the following about how symfony2 and twig handle sanitization:

Doctrine comes with sanitization for database
  (SQL) injections. Apart from this, there is no recommended / provided
  input sanitization at controller level in Symfony2. However, using Twig in the
  view, output sanitization is available.

As an example, in CakePHP however:

Data sanitization is implemented as a Utility which can be
  accessed from anywhere (controller, component, model .. even view). It
  follows a sanitize-all-input approach with a fixed set of predefined
  sanitization filters. Sanitizing specific inputs with dedicated rules
  is possible, but seems not to be encouraged.The existing rules
  concentrate on SQL and HTML injections and filtering out general
  suspicious unicode characters.

1 How do symfony2 + twig users handle input sanitization? Do they discard input sanitization totally and for example rely on validation only? Or do they write their own utility function to filter user inputs? or maybe use a library like owasp-esapi-php?

2 How do symfony2 + twig users handle output sanitization? Do they rely on the filters provided by the twig engine only? For example, are there already any tools that one can use to sanitize a user-entered URI, something similar to this?

3 In this situarion, how would you handle database storage and display of a user-entered URI like in the example above, would you care about input sanitization at all? or would you use output sanitization only and store the URI as is?

答:
Using the form validators provided by Symfony verifies the integrity of the data supplied to your application's database.

You should consider adding a test for a url-pattern, there are various

Other users already pointed out you are safe against various attax using components (csrf, type/property validation (symfony-form), sql-injection(Doctrine) and xss (twig) and of course various access authentification)

So for the specific attack you ask about it is necessary for bad user to submit a script-tag and some poor user get this displayed and executed, you could easily avoid getting this into your application with a simple regex of them

preg_replace('/(<' .'script'. '>)(.*)(</' .'script'. '>)/g', '', $text);

So i think it is safe not to rely on the sanitation of the output, there are many reasons, for example you do not use twig because your application is endpoint driven or for some reason you need to call |raw filter on text fields or maybe you dont even have influence on the display because thirds are displaying the data each on their way.


问:
Change a while loop to foreach?
I'm about to change a code to "WordPress-customized code" (using $wpdb). And with $wpdb->get_results() I get an array that need to be outputted with a foreach loop. But the problem is that my current while-loop has a "$initial_hidden statement" in it that I don't know how to do with the new foreach.

Here is my current code:

```<code>while (($initial_hidden == true) || ($r = mysql_fetch_assoc($q))) {

...

}
</code>```

So, how do I get the "initial hidden" to this:

```<code>foreach ($q as $r) {

...

}
</code>```

答:
So, how do I get the "initial hidden" to this

You can abort foreach with regular break; so simply add if() in loop body and break when condition is met.

```<code>foreach($q as $r) {
     ...

   if ($initial_hidden) {
      break;
   }
}
</code>```

Title: Change a while loop to foreach?

Body:
I'm about to change a code to "WordPress-customized code" (using $wpdb). And with $wpdb->get_results() I get an array that need to be outputted with a foreach loop. But the problem is that my current while-loop has a "$initial_hidden statement" in it that I don't know how to do with the new foreach.

Here is my current code:

while (($initial_hidden == true) || ($r = mysql_fetch_assoc($q))) {

...

}

So, how do I get the "initial hidden" to this:

foreach ($q as $r) {

...

}

Body:
So, how do I get the "initial hidden" to this

You can abort foreach with regular break; so simply add if() in loop body and break when condition is met.

foreach($q as $r) {
     ...

   if ($initial_hidden) {
      break;
   }
}


问:
Java 'constructor in class cannot be applied to given types' 'required: no arguments found: String'
I'm working on an assignment where I have to create a linked list from scratch and have come across an error when compiling that the "constructor Node in class Node cannot be applied to given types;"

This is what I'm trying, the error says:

required: no arguments
found: string

Yet I cannot see where I am going wrong as my constructor for Node requires a string?

```<code>public class Node {
    String data;
    Node next;

    public void Node(String x) {
        data = x;
        next = null;
    }
}

public class stringList {
    private Node head;
    private int count;

    public void stringList() {
        head = null;
        count = null;
    }

    public void add(String x) {
        Node temp = new Node(x);
    }
</code>```

This is a screenshot of the error the compiler is showing

答:
This:

```<code>public void Node(String x) {
    data = x;
    next = null;
}
</code>```

should be:

```<code>   public Node(String x) {
        data = x;
        next = null;
    }
</code>```

Currently you have a default constructor (taking no arguments), which is implicitly defined in the absence of any explicit constructors.

Body:
I'm working on an assignment where I have to create a linked list from scratch and have come across an error when compiling that the "constructor Node in class Node cannot be applied to given types;"

This is what I'm trying, the error says:

required: no arguments
found: string

Yet I cannot see where I am going wrong as my constructor for Node requires a string?

public class Node {
    String data;
    Node next;

    public void Node(String x) {
        data = x;
        next = null;
    }
}

public class stringList {
    private Node head;
    private int count;

    public void stringList() {
        head = null;
        count = null;
    }

    public void add(String x) {
        Node temp = new Node(x);
    }

This is a screenshot of the error the compiler is showing

Body:
This:

public void Node(String x) {
    data = x;
    next = null;
}

should be:

   public Node(String x) {
        data = x;
        next = null;
    }

Currently you have a default constructor (taking no arguments), which is implicitly defined in the absence of any explicit constructors.


问:
using http post to check session and redirect
I am still new to angularjs and trying to understand the concept. i have a working solution but i just need to make sure this is a secure way of doing it. i have a $rootScope.$on('$stateChangeStart', function(){} which sends a http post to a php file, this checks to see if it has session data and returns "1" being true and "0" being false. if false then i perform a $state.go('login'); which redirects to login page. This works exactly how i wish it to but just would like some further knowledge if this is secure enough.

答:
While there are several others way of authenticating the session data, your approach is fine as well.

Enclose the $on in app.run method and check if user is on login page then avoid the $http call.

```<code>app.run(function ($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function (event, next, nextParams, prev, prevParams) {

        //Check if already on login page do not check session
        if (next.name === 'login') {
            return;
        }

        //$http call to check session
    });
});
</code>```

Body:
While there are several others way of authenticating the session data, your approach is fine as well.

Enclose the $on in app.run method and check if user is on login page then avoid the $http call.

app.run(function ($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function (event, next, nextParams, prev, prevParams) {

        //Check if already on login page do not check session
        if (next.name === 'login') {
            return;
        }

        //$http call to check session
    });
});


问:
Java 8: Automatically composite default methods of multiple interfaces
I have class implements multiple interfaces which have a same default  default method. I am wondering how can I composite the default method from all the interfaces. For example:

```<code>interface IA {
    default void doA() {}
    default void process() {
        // do something
    }
}

interface IB {
    default void doB() {}
    default void process() {
        // do something
    }
}

interface IC {
    default void doC() {}
    default void process() {
        // do something
    }
}

// other similar interfaces
....

class MyClass implements IA, IB, IC, ... {
    public void process() {
       // question: how to avoid iterate all the interfaces?
       IA.super.process();
       IB.super.process();
       IC.super.process();
       ...
    }
}

class AnotherClass implements IA, ID, IF, IH, ... {
    public void process() {
        IA.super.process();
        ID.super.process();
        IF.super.process();
        IH.super.process();
        ...
    }
}
</code>```

In the implementation the method is simply compositing process() from all interfaces. However I have to call IA.super.process(), IB.super.process(), IC.super.process() explicitly. If the interface list is long it's painfully to write all of them. Also I may have different classes to implement different combination of interfaces. Is there other syntax sugar/design pattern/library that allows me to do it automatically?

Update: compare with Composite pattern

Composite pattern is also considerable. But I want to use default method as mixin to give classes different behaviors, while composite pattern doesn't give me static type checking here. Composite pattern also introduces extra memory footprint.

答:
I think your mistake is defining multiple interfaces which are effectively identical (aside from differing default behaviour). It seems wrong in my mind and violates DRY.

I would structure this using the composite pattern:

```<code>interface Processable
{
    void process();
}
public interface IA extends Processable //and IB, IC etc.
{
    default void doA()
    {
        // Do some stuff
    }
}

final class A implements IA
{
    void process() { /* whatever */ }
}

class Composite implements IA //, IB, IC etc.
{
    List<Processable> components = Arrays.asList(
         new A(), new B(), ...
    );

    void process()
    {
         for(Processable p : components) p.process();
    }
}
</code>```

Body:
I have class implements multiple interfaces which have a same default  default method. I am wondering how can I composite the default method from all the interfaces. For example:

interface IA {
    default void doA() {}
    default void process() {
        // do something
    }
}

interface IB {
    default void doB() {}
    default void process() {
        // do something
    }
}

interface IC {
    default void doC() {}
    default void process() {
        // do something
    }
}

// other similar interfaces
....

class MyClass implements IA, IB, IC, ... {
    public void process() {
       // question: how to avoid iterate all the interfaces?
       IA.super.process();
       IB.super.process();
       IC.super.process();
       ...
    }
}

class AnotherClass implements IA, ID, IF, IH, ... {
    public void process() {
        IA.super.process();
        ID.super.process();
        IF.super.process();
        IH.super.process();
        ...
    }
}

In the implementation the method is simply compositing process() from all interfaces. However I have to call IA.super.process(), IB.super.process(), IC.super.process() explicitly. If the interface list is long it's painfully to write all of them. Also I may have different classes to implement different combination of interfaces. Is there other syntax sugar/design pattern/library that allows me to do it automatically?

Update: compare with Composite pattern

Composite pattern is also considerable. But I want to use default method as mixin to give classes different behaviors, while composite pattern doesn't give me static type checking here. Composite pattern also introduces extra memory footprint.

Body:
I think your mistake is defining multiple interfaces which are effectively identical (aside from differing default behaviour). It seems wrong in my mind and violates DRY.

I would structure this using the composite pattern:

interface Processable
{
    void process();
}
public interface IA extends Processable //and IB, IC etc.
{
    default void doA()
    {
        // Do some stuff
    }
}

final class A implements IA
{
    void process() { /* whatever */ }
}

class Composite implements IA //, IB, IC etc.
{
    List<Processable> components = Arrays.asList(
         new A(), new B(), ...
    );

    void process()
    {
         for(Processable p : components) p.process();
    }
}


问:
Bullet Physics, Collision between btBvhTriangleMeshShape and btStaticPlaneShape wont work
First some facts:
I try to realise Collision Detection with Bullet in C++ using Visual Studio 2012.
 So far i have a Sphere:

```<code>    btCollisionShape* fallShape = new btSphereShape(100);
    btDefaultMotionState* fallMotionState =
            new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,500,0)));
    btScalar mass = 1000;
    btVector3 fallInertia(0,0,0);
    fallShape->calculateLocalInertia(mass,fallInertia);
    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,fallShape,fallInertia);
    btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
    physicsWorld->addRigidBody(fallRigidBody);
</code>```

and my level, realised as btBvhTriangleMeshShape:

```<code>    triangles.addTriangle(btVector3 (0, 0, 0),btVector3 (0, 0, 0),btVector3 (0, 0, 0));

btCollisionShape* levelShape = new btBvhTriangleMeshShape(&triangles, true, true);
    btDefaultMotionState* levelMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)));
  btRigidBody::btRigidBodyConstructionInfo
      levelRigidBodyCI(0,levelMotionState,levelShape,btVector3(0,0,0));
   btRigidBody* levelRigidBody = new btRigidBody(levelRigidBodyCI);
    physicsWorld->addRigidBody(levelRigidBody);
</code>```

I know that in triangles is only one triangle but they collide.

My Problem is now, that when they collide, my program shuts down with no specific error, simply a unhandle exception window from visual studio.

Anyone an idea?

答:
For future reference, here below is a short working example in C++ of a flat btBvhTriangleMeshShape, inspired by the question above. Mass is 0.0f as the mesh is obviously a static object.

```<code>btVector3 vertex1, vertex2, vertex3, vertex4;
btTriangleMesh* triangleMeshTerrain = new btTriangleMesh();

for (int i = -250; i < 250; i = i + 10) {
    for (int j = -250; j < 250; j = j + 10) {

        vertex1 = btVector3(i, 0.0f, j);
        vertex2 = btVector3(i + 10.0f, 0.0f, j);
        vertex3 = btVector3(i + 10.0f, 0.0f, j + 10.0f);
        vertex4 = btVector3(i, 0.0f, j + 10.0f);

        triangleMeshTerrain->addTriangle(vertex1, vertex2, vertex3);
        triangleMeshTerrain->addTriangle(vertex1, vertex3, vertex4);
    }
}

btCollisionShape* collisionShapeTerrain = new btBvhTriangleMeshShape(triangleMeshTerrain, true);

btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -15, 0)));

btRigidBody::btRigidBodyConstructionInfo rigidBodyConstructionInfo(0.0f, motionState, collisionShapeTerrain, btVector3(0, 0, 0));
btRigidBody* rigidBodyTerrain = new btRigidBody(rigidBodyConstructionInfo);
rigidBodyTerrain->setFriction(btScalar(0.9));

m_dynamicsWorld->addRigidBody(rigidBodyTerrain);
</code>```

Body:
First some facts:
I try to realise Collision Detection with Bullet in C++ using Visual Studio 2012.
 So far i have a Sphere:

    btCollisionShape* fallShape = new btSphereShape(100);
    btDefaultMotionState* fallMotionState =
            new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,500,0)));
    btScalar mass = 1000;
    btVector3 fallInertia(0,0,0);
    fallShape->calculateLocalInertia(mass,fallInertia);
    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,fallShape,fallInertia);
    btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
    physicsWorld->addRigidBody(fallRigidBody);

and my level, realised as btBvhTriangleMeshShape:

    triangles.addTriangle(btVector3 (0, 0, 0),btVector3 (0, 0, 0),btVector3 (0, 0, 0));

btCollisionShape* levelShape = new btBvhTriangleMeshShape(&triangles, true, true);
    btDefaultMotionState* levelMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)));
  btRigidBody::btRigidBodyConstructionInfo
      levelRigidBodyCI(0,levelMotionState,levelShape,btVector3(0,0,0));
   btRigidBody* levelRigidBody = new btRigidBody(levelRigidBodyCI);
    physicsWorld->addRigidBody(levelRigidBody);

I know that in triangles is only one triangle but they collide.

My Problem is now, that when they collide, my program shuts down with no specific error, simply a unhandle exception window from visual studio.

Anyone an idea?

Body:
For future reference, here below is a short working example in C++ of a flat btBvhTriangleMeshShape, inspired by the question above. Mass is 0.0f as the mesh is obviously a static object.

btVector3 vertex1, vertex2, vertex3, vertex4;
btTriangleMesh* triangleMeshTerrain = new btTriangleMesh();

for (int i = -250; i < 250; i = i + 10) {
    for (int j = -250; j < 250; j = j + 10) {

        vertex1 = btVector3(i, 0.0f, j);
        vertex2 = btVector3(i + 10.0f, 0.0f, j);
        vertex3 = btVector3(i + 10.0f, 0.0f, j + 10.0f);
        vertex4 = btVector3(i, 0.0f, j + 10.0f);

        triangleMeshTerrain->addTriangle(vertex1, vertex2, vertex3);
        triangleMeshTerrain->addTriangle(vertex1, vertex3, vertex4);
    }
}

btCollisionShape* collisionShapeTerrain = new btBvhTriangleMeshShape(triangleMeshTerrain, true);

btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -15, 0)));

btRigidBody::btRigidBodyConstructionInfo rigidBodyConstructionInfo(0.0f, motionState, collisionShapeTerrain, btVector3(0, 0, 0));
btRigidBody* rigidBodyTerrain = new btRigidBody(rigidBodyConstructionInfo);
rigidBodyTerrain->setFriction(btScalar(0.9));

m_dynamicsWorld->addRigidBody(rigidBodyTerrain);


问:
Swift: "Ambiguous reference to member" init
There are several posts on this subject, but I can't see the answer to this problem in them. The following lines produce the title error:

```<code>let pdf_url = NSURL.fileURL(withPath: inputfile)
let pdf_doc = PDFDocument.init?(url: pdf_url) as! URL
</code>```

I understand that the init method can take a variety of data types, but surely I've made it pretty clear that I want a URL.

Error message is:

```<code>error: ambiguous reference to member 'init(url:)'
</code>```

A problem which may be related is that Xcode occasionally tells me to use URL, not NSURL, in the first line, but then complains that URL doesn't have the fileURL method.
(I also tried CGPDFDocument, but that wanted a CFURL, and wouldn't accept NSURL, even though they are supposed to be "toll-free bridged".)

答:
The error occurs because you (try to) cast PDFDocument to URL.

You probably mean

```<code>PDFDocument.init?(url: pdf_url as! URL)
</code>```

But the recommended Swift 3 syntax is

```<code>let pdfURL = URL(fileURLWithPath: inputfile) // returns a non-optional URL
let pdfDoc = PDFDocument(url: pdfURL)
</code>```

Please use – Swift – camel case variable names rather than – javascript / php – snake case.

Body:
There are several posts on this subject, but I can't see the answer to this problem in them. The following lines produce the title error:

let pdf_url = NSURL.fileURL(withPath: inputfile)
let pdf_doc = PDFDocument.init?(url: pdf_url) as! URL

I understand that the init method can take a variety of data types, but surely I've made it pretty clear that I want a URL.

Error message is:

error: ambiguous reference to member 'init(url:)'

A problem which may be related is that Xcode occasionally tells me to use URL, not NSURL, in the first line, but then complains that URL doesn't have the fileURL method.
(I also tried CGPDFDocument, but that wanted a CFURL, and wouldn't accept NSURL, even though they are supposed to be "toll-free bridged".)

Body:
The error occurs because you (try to) cast PDFDocument to URL.

You probably mean

PDFDocument.init?(url: pdf_url as! URL)

But the recommended Swift 3 syntax is

let pdfURL = URL(fileURLWithPath: inputfile) // returns a non-optional URL
let pdfDoc = PDFDocument(url: pdfURL)

Please use – Swift – camel case variable names rather than – javascript / php – snake case.


问:
rails 2.1.2 collection_select with an :onchange and a :with
After a lot of searching and reading I've got a collection_select that looks like so

```<code><%= collection_select :selection, :level, User::LEVELS, :to_s, :to_s,{:with => "this.value"},
         {:onchange => remote_function(
             :url => {:action => "updatelevel", :controller => "user", :id=> user.id})
         } %>
</code>```

However its not passing the selected value to my controller, the only thing I've ever got is a nil.

I've messed about with difference combinations of where :with should be and tried test strings but it never seems to do anything.

Am I missing something stupid? Is there a "definative" example I should be looking at?

Rails seems to change so fast that its hard to know which version a forum post is talking about and the api I read for collection_select doesn't show what I can put in the options hash.

答:
I checked this out on my app running Rails 2.3.10.  You have your 'with' parameter in the wrong spot, it is an option for the remote function, not for the collection select. Also, passing the value in that manner will get you a params hash that looks like {"134523456" => ""}, which probably isn't what you want.  You have to have your 'with' value result in a string that is JavaScript centric.</p>

```<code><%= collection_select :selection, :level, User::LEVELS, :to_s, :to_s, {},
      {:onchange => remote_function(
        :url => {:action => "updatelevel", :controller => "user", :id=> user.id},
        :with => "'level_id='+this.value"
      )
    }
%>
</code>```

Body:
After a lot of searching and reading I've got a collection_select that looks like so

<%= collection_select :selection, :level, User::LEVELS, :to_s, :to_s,{:with => "this.value"},
         {:onchange => remote_function(
             :url => {:action => "updatelevel", :controller => "user", :id=> user.id})
         } %>

However its not passing the selected value to my controller, the only thing I've ever got is a nil.

I've messed about with difference combinations of where :with should be and tried test strings but it never seems to do anything.

Am I missing something stupid? Is there a "definative" example I should be looking at?

Rails seems to change so fast that its hard to know which version a forum post is talking about and the api I read for collection_select doesn't show what I can put in the options hash.

Body:
I checked this out on my app running Rails 2.3.10.  You have your 'with' parameter in the wrong spot, it is an option for the remote function, not for the collection select. Also, passing the value in that manner will get you a params hash that looks like {"134523456" => ""}, which probably isn't what you want.  You have to have your 'with' value result in a string that is JavaScript centric.

<%= collection_select :selection, :level, User::LEVELS, :to_s, :to_s, {},
      {:onchange => remote_function(
        :url => {:action => "updatelevel", :controller => "user", :id=> user.id},
        :with => "'level_id='+this.value"
      )
    }
%>


问:
Set theme color dynamically
I am using themes (dynamically) in my android app, like this:

my_layout.xml (extract):

```<code><TextView
    android:id="@+id/myItem"
    style="?my_item_style" />
</code>```

attrs.xml (extract):

```<code><attr name="my_item_style" format="reference" />
</code>```

themes.xml (extract):

```<code><style name="MainTheme.Blue">
      <item name="my_item_style">@style/my_item_style_blue</item>
</style>

<style name="MainTheme.Green">
      <item name="my_item_style">@style/my_item_style_green<item>
</style>
</code>```

styles.xml (extract):

```<code><style name="my_item_style_blue">
      <item name="android:textColor">@color/my_blue</item>
</style>

<style name="my_item_style_green">
      <item name="android:textColor">@color/my_blue</item>
</style>
</code>```

So, as you can see, I am setting themes dynamically. I am using this class:

```<code>public class ThemeUtils {

  private static int sTheme;
  public final static int THEME_BLUE = 1;
  public final static int THEME_GREEN = 2;

  public static void changeToTheme(MainActivity activity, int theme) {
      sTheme = theme;
      activity.startActivity(new Intent(activity, MyActivity.class));
  }

  public static void onActivityCreateSetTheme(Activity activity)
  {
      switch (sTheme)
      {
          default:
          case THEME_DEFAULT:
          case THEME_BLUE:
              activity.setTheme(R.style.MainTheme_Blue);
              break;
          case THEME_GREEN:
              activity.setTheme(R.style.MainTheme_Green);
              break;
      }
  }
</code>```

}

What I want to know, is there a way how to do this (change theme color) in code? For example, I have following code (extract):

```<code>((TextView) findViewById(R.id.myItem)).setTextColor(R.color.blue);
</code>```

It can be done by some helper method, which would use switch command for available themes and return correct color for a theme. But I would like to know if there is some better, nicer and faster way.

Thanks!

答:
Have you check this MultipleThemeMaterialDesign demo?

SettingActivity:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    Preferences.applyTheme(this);
    getDelegate().installViewFactory();
    getDelegate().onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);
    setToolbar();
    addPreferencesFromResource(R.xml.preferences);
    Preferences.sync(getPreferenceManager());
    mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            Preferences.sync(getPreferenceManager(), key);
            if (key.equals(getString(R.string.pref_theme))) {
                finish();
                final Intent intent = IntentCompat.makeMainActivity(new ComponentName(
                        SettingsActivity.this, MainActivity.class));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }
        }
    };
}
</code>```

See full example for demo.

Title: Set theme color dynamically

Body:
I am using themes (dynamically) in my android app, like this:

my_layout.xml (extract):

<TextView
    android:id="@+id/myItem"
    style="?my_item_style" />

attrs.xml (extract):

<attr name="my_item_style" format="reference" />

themes.xml (extract):

styles.xml (extract):

So, as you can see, I am setting themes dynamically. I am using this class:

public class ThemeUtils {

  private static int sTheme;
  public final static int THEME_BLUE = 1;
  public final static int THEME_GREEN = 2;

  public static void changeToTheme(MainActivity activity, int theme) {
      sTheme = theme;
      activity.startActivity(new Intent(activity, MyActivity.class));
  }

  public static void onActivityCreateSetTheme(Activity activity)
  {
      switch (sTheme)
      {
          default:
          case THEME_DEFAULT:
          case THEME_BLUE:
              activity.setTheme(R.style.MainTheme_Blue);
              break;
          case THEME_GREEN:
              activity.setTheme(R.style.MainTheme_Green);
              break;
      }
  }

}

What I want to know, is there a way how to do this (change theme color) in code? For example, I have following code (extract):

((TextView) findViewById(R.id.myItem)).setTextColor(R.color.blue);

It can be done by some helper method, which would use switch command for available themes and return correct color for a theme. But I would like to know if there is some better, nicer and faster way.

Thanks!

Body:
Have you check this MultipleThemeMaterialDesign demo?

SettingActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    Preferences.applyTheme(this);
    getDelegate().installViewFactory();
    getDelegate().onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);
    setToolbar();
    addPreferencesFromResource(R.xml.preferences);
    Preferences.sync(getPreferenceManager());
    mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            Preferences.sync(getPreferenceManager(), key);
            if (key.equals(getString(R.string.pref_theme))) {
                finish();
                final Intent intent = IntentCompat.makeMainActivity(new ComponentName(
                        SettingsActivity.this, MainActivity.class));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }
        }
    };
}

See full example for demo.


答:
You need two levels of aggregation. First to get the users who have more than one row in a month. Then grouping by year,month to get the counts of users for a specific month.</p>

```<code>select cast(mth as varchar(2))+'/'+cast(yr as varchar(4)) as mth,count(*)
from (select user_id,month(event_date) as mth,year(event_date) as yr
      from tablename
      group by user_id,month(event_date),year(event_date)
      having count(*) > 1
     ) t
group by cast(mth as varchar(2))+'/'+cast(yr as varchar(4))
</code>```

Title: Users that returned

Body:
I have a table with [EVENT_DATE] and [USER_ID], I would like to know how to count the users who came back in the same month.

Table_01
-------------------------------------------
    EVENT_DATE          |   USER_ID
-------------------------------------------
2017-03-28 00:00:25.000 | 0006235012201
2017-03-04 23:00:00.000 | 0006235012201
2017-03-19 00:25:15.000 | 0006235012201
2017-02-03 10:00:02.000 | 0006235012202
2017-01-18 00:15:00.000 | 0006235012202
2017-03-28 11:00:15.000 | 0006235012202
2017-03-23 15:20:02.000 | 0006235012203
2017-02-18 12:00:06.000 | 0006235012203
2017-03-21 16:05:09.000 | 0006235012203

The answering being 2, because users 0006235012201 & 0006235012203 both came back within the same month.

EDIT: Sorry

I am looking to get the count by month.

-----------------------
Month | Users Returned
-----------------------
01/17 | 70
02/17 | 60
03/17 | 10

This is what I have, but it isn't correct as it seems to be listing users.

SELECT A.[USER_ID], A.[EVENT_DATE], COUNT(*)
FROM(
    SELECT [USER_ID], [EVENT_DATE], COUNT(*)
    FROM Table_01
    GROUP BY [USER_ID], [EVENT_DATE]
    HAVING COUNT(*) > 1
     ) A
GROUP BY A.[USER_ID], A.[EVENT_DATE]

Microsoft SQL Server 2016. Compatibility level: SQL Server 2005 (90)

Body:
You need two levels of aggregation. First to get the users who have more than one row in a month. Then grouping by year,month to get the counts of users for a specific month.

select cast(mth as varchar(2))+'/'+cast(yr as varchar(4)) as mth,count(*)
from (select user_id,month(event_date) as mth,year(event_date) as yr
      from tablename
      group by user_id,month(event_date),year(event_date)
      having count(*) > 1
     ) t
group by cast(mth as varchar(2))+'/'+cast(yr as varchar(4))


问:
How to make username and password form work - where website cannot be seen by just typing in url
So i have a website on a sever, and am using php code to access a 'log on' page where a person who has a username and password can add stuff to the website. But if you type the url in anyone can just access it without username and password. How do it change this.

So there is a form on html page, that has username and password fields, user types them in, php checks the info and the redirects to the correct page if the info is correct.

PHP code used

```<code>    <?php
    if ($_POST["usn"]=="ag316" || $_POST["psw"]=="rock")
    {
        header("Location: addentry.html");
        exit();
    }
    else
    {
        header("Location: login.html");
        exit();
    }
?>
</code>```

答:
It would be better if you kept the username and passwords in a database and then just keep track of the users your site. But you will have to change addentry.html to addentry.php since you will need to run some php scripts on that page to track your users

You can set up a global sessions variable to track users. if the variable is not set, redirect the user to the login page, if the variable is set, allow them to access the page.

To add username to session variable;

```<code>$_SESSION["user"] = $username;
</code>```

Then on every page that needs access, set an if statement

```<code>//start session
session_start();

 //check if session variable is set
 if(isset($_SESSION["user"])){
 }else{
     header('Location: login.php');
 }
</code>```

Let me know if it helps.

Body:
So i have a website on a sever, and am using php code to access a 'log on' page where a person who has a username and password can add stuff to the website. But if you type the url in anyone can just access it without username and password. How do it change this.

So there is a form on html page, that has username and password fields, user types them in, php checks the info and the redirects to the correct page if the info is correct.

PHP code used

    <?php
    if ($_POST["usn"]=="ag316" || $_POST["psw"]=="rock")
    {
        header("Location: addentry.html");
        exit();
    }
    else
    {
        header("Location: login.html");
        exit();
    }
?>

Body:
It would be better if you kept the username and passwords in a database and then just keep track of the users your site. But you will have to change addentry.html to addentry.php since you will need to run some php scripts on that page to track your users

You can set up a global sessions variable to track users. if the variable is not set, redirect the user to the login page, if the variable is set, allow them to access the page.

To add username to session variable;

$_SESSION["user"] = $username;

Then on every page that needs access, set an if statement

//start session
session_start();

 //check if session variable is set
 if(isset($_SESSION["user"])){
 }else{
     header('Location: login.php');
 }

Let me know if it helps.


问:
Creating table with limited number of rows
I would like to create table that have limited numbers of rows.
For example if we try insert data into that table where rownumber is bigger than 2.000, that return some error or something.

How to manage this?

答:
An approach could be by creating a trigger to check the number of inserted rows; for example, say you have this table

```<code>create table notManyRows(n number)
</code>```

and you want to limit the number of rows to 3, you can add a trigger like:

```<code>create or replace trigger notManyRowsTrg
after insert on notManyRows
declare
    vCheck number;
begin
    select count(*)
    into vCheck
    from notManyRows;
    --
    if vCheck > 3 then
        raise_application_error(-20001, 'Too many rows in the table');
    end if;
end;
</code>```

How it works:

```<code>SQL> insert into notManyRows values (1);

1 row created.

SQL> insert into notManyRows values (1);

1 row created.

SQL> insert into notManyRows values (1);

1 row created.

SQL> insert into notManyRows values (1);
insert into notManyRows values (1)
*
ERROR at line 1:
ORA-20001: Too many rows in the table
ORA-06512: at "ALEK.NOTMANYROWSTRG", line 9
ORA-04088: error during execution of trigger 'ALEK.NOTMANYROWSTRG'

SQL>
</code>```

Body:
An approach could be by creating a trigger to check the number of inserted rows; for example, say you have this table

create table notManyRows(n number)

and you want to limit the number of rows to 3, you can add a trigger like:

create or replace trigger notManyRowsTrg
after insert on notManyRows
declare
    vCheck number;
begin
    select count(*)
    into vCheck
    from notManyRows;
    --
    if vCheck > 3 then
        raise_application_error(-20001, 'Too many rows in the table');
    end if;
end;

How it works:

SQL> insert into notManyRows values (1);

1 row created.

SQL> insert into notManyRows values (1);

1 row created.

SQL> insert into notManyRows values (1);

1 row created.

SQL> insert into notManyRows values (1);
insert into notManyRows values (1)
*
ERROR at line 1:
ORA-20001: Too many rows in the table
ORA-06512: at "ALEK.NOTMANYROWSTRG", line 9
ORA-04088: error during execution of trigger 'ALEK.NOTMANYROWSTRG'

SQL>


问:
Can I put an iAd banner in the middle of View?
Is it possible to place iAd banner somewhere else than is top or bottom? I wish I could place it in the middle of my UIView.

tnx

答: It is possible and it will be approved if done correctly. A good example would be as a row in a UITableView, but most of the time this is a bad idea.</p>


问:
How to grep word from file
I want to grep some word inside a file from another file. My code is able to grep the word on last line of the file but not the word before it. I have no idea why and hope can get help here. Below is the perl script i using:

```<code>open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

use strict;
use warnings;
use List::MoreUtils qw(uniq);

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
my $zone =0;
for ($j=0; $j<=$#file2; $j++){
    $zone = $file2[$j];
    unless ( $zone =~ m/#(.*?)/ ) {
        print "$zone";
        my @fid = grep /$zone/ , @file1;
        @fid = uniq(@fid);
        s{^\s+|\s+$}{}g foreach @fid;                #cancel leading space
        for ($i=0; $i<=$#fid; $i++){
            print FILE3 "$fid[$i]\n";
        }
        #@fid=();

    }
}

close(FILE3);
</code>```

My file1.txt is something like this:

```<code>i am a dog
i am a cat
we are the fish
he is a boy
she is a girl
</code>```

My file2.txt is like this:

```<code>is
am
</code>```

But my file3 can only show those sentence contain am but no is, if i put is in second line and am in first line then my file3 only contain the sentences with is. I not very sure why my code can only grep the last row in my file2. Thanks for the help.

答:
The root of this problems is chomp - you're not removing linefeeds, so the matches aren't working.

But aside from that, there's a few problems with your code that could do with addressing:

opening files, you should use 3 arg open with lexical file handles, as it's better style: open (my $file1, '<', 'file1.txt' ) or die $!;

rather than a loop of loops, you'd probably be better off compiling up a 'match regex'.

Instead of reading all of a file into an array, you can iterate line by line, and you don't need to use the memory.

If you're iterating a loop, and only using the index to acccess the current element, you're far better off using foreach my $line ( @things ) { type syntax.

So your code actually could be reduced to something like:

```<code>#!/usr/bin/env perl
use strict;
use warnings;

open(my $data, '<',"file1.txt") or die $!;
open(my $search, '<', "file2.txt") or die $!;
open(my $output, '>', "file3.txt" ) or die $!;

chomp ( my @search_terms = <$search> );

#quotemeta is needed to avoid 'special' regex characters doing things.
my $search_regex = join "|", map { quotemeta }, @search_terms;

#note - '\b' denotes word boundary, which may not be what you want.
#means 'is' won't match 'fish'
#so get rid of them if that's not what you want.
$search_regex = qr/\b($search_regex)\b/;

print "Using: $search_regex\n";

select $output; #default print destination
while ( <$data> ) {
    print if m/$search_regex/;
}
</code>```

Output (in 'file3.txt'):

```<code>i am a dog
i am a cat
he is a boy
she is a girl
</code>```

Title: How to grep word from file

Body:
I want to grep some word inside a file from another file. My code is able to grep the word on last line of the file but not the word before it. I have no idea why and hope can get help here. Below is the perl script i using:

open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

use strict;
use warnings;
use List::MoreUtils qw(uniq);

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
my $zone =0;
for ($j=0; $j<=$#file2; $j++){
    $zone = $file2[$j];
    unless ( $zone =~ m/#(.*?)/ ) {
        print "$zone";
        my @fid = grep /$zone/ , @file1;
        @fid = uniq(@fid);
        s{^\s+|\s+$}{}g foreach @fid;                #cancel leading space
        for ($i=0; $i<=$#fid; $i++){
            print FILE3 "$fid[$i]\n";
        }
        #@fid=();

    }
}

close(FILE3);

My file1.txt is something like this:

i am a dog
i am a cat
we are the fish
he is a boy
she is a girl

My file2.txt is like this:

is
am

But my file3 can only show those sentence contain am but no is, if i put is in second line and am in first line then my file3 only contain the sentences with is. I not very sure why my code can only grep the last row in my file2. Thanks for the help.

Body:
The root of this problems is chomp - you're not removing linefeeds, so the matches aren't working.

But aside from that, there's a few problems with your code that could do with addressing:

opening files, you should use 3 arg open with lexical file handles, as it's better style: open (my $file1, '<', 'file1.txt' ) or die $!;

rather than a loop of loops, you'd probably be better off compiling up a 'match regex'.

Instead of reading all of a file into an array, you can iterate line by line, and you don't need to use the memory.

If you're iterating a loop, and only using the index to acccess the current element, you're far better off using foreach my $line ( @things ) { type syntax.

So your code actually could be reduced to something like:

#!/usr/bin/env perl
use strict;
use warnings;

open(my $data, '<',"file1.txt") or die $!;
open(my $search, '<', "file2.txt") or die $!;
open(my $output, '>', "file3.txt" ) or die $!;

chomp ( my @search_terms = <$search> );

#quotemeta is needed to avoid 'special' regex characters doing things.
my $search_regex = join "|", map { quotemeta }, @search_terms;

#note - '\b' denotes word boundary, which may not be what you want.
#means 'is' won't match 'fish'
#so get rid of them if that's not what you want.
$search_regex = qr/\b($search_regex)\b/;

print "Using: $search_regex\n";

select $output; #default print destination
while ( <$data> ) {
    print if m/$search_regex/;
}

Output (in 'file3.txt'):

i am a dog
i am a cat
he is a boy
she is a girl


问:
impala string function to extract text after a given separator
Say I have a string of variable length such as:

```<code>'633000000HIQWA4:005160000UT334'
'00YYSKSG004:00YJDJJDA3443'
'300SGDK112WA4:00KFJJD900'
</code>```

which impala string function to use to extract text after :
for e.g.:

```<code>'005160000UT334'
'00YJDJJDA3443'
'00KFJJD900'
</code>```

Body:
Say I have a string of variable length such as:

'633000000HIQWA4:005160000UT334'
'00YYSKSG004:00YJDJJDA3443'
'300SGDK112WA4:00KFJJD900'

which impala string function to use to extract text after :
for e.g.:

'005160000UT334'
'00YJDJJDA3443'
'00KFJJD900'

Body:
Use split_part(string source, string delimiter, bigint n) function. The value of n would be as the fields are numbered starting from 1.

select split_part('633000000HIQWA4:005160000UT334',':',2);

+----------------------------------------------------+
| split_part('633000000HIQWA4:005160000UT334',':',2) |
+----------------------------------------------------+
| 005160000UT334                                     |
+----------------------------------------------------+


问:
What is this thumbnail icon on mobile chrome and how to use it in my website
I don't know what this icon is called and how to use it for my website. Can someone help me out.

答:
That'd be one of the favicons you need to set on your page. If you use an automatic tool like https://realfavicongenerator.net you will be able to easily cover all the required different files using a single image.

The icon that is used to install to the homescreen is determined by using the largest icon found in one of the following  tags:

```<code><link rel="icon" sizes="192x192" href="nice-highres.png"> (recommended)
<link rel="icon" sizes="128x128" href="niceicon.png">
<link rel="apple-touch-icon" sizes="128x128" href="niceicon.png">
<link rel="apple-touch-icon-precomposed" sizes="128x128" href="niceicon.png">
</code>```

Source: https://developer.chrome.com/multidevice/android/installtohomescreen#icon

Chrome uses the same icon as the favicon, bookmark icon and “Add to home screen” icon. It picks the widest PNG icon it can find which is no larger than 192×192.

Source: https://realfavicongenerator.net/blog/android-chrome-and-its-favicon/

Body:
That'd be one of the favicons you need to set on your page. If you use an automatic tool like https://realfavicongenerator.net you will be able to easily cover all the required different files using a single image.

The icon that is used to install to the homescreen is determined by using the largest icon found in one of the following  tags:

<link rel="icon" sizes="192x192" href="nice-highres.png"> (recommended)
<link rel="icon" sizes="128x128" href="niceicon.png">
<link rel="apple-touch-icon" sizes="128x128" href="niceicon.png">
<link rel="apple-touch-icon-precomposed" sizes="128x128" href="niceicon.png">

Source: https://developer.chrome.com/multidevice/android/installtohomescreen#icon

Chrome uses the same icon as the favicon, bookmark icon and “Add to home screen” icon. It picks the widest PNG icon it can find which is no larger than 192×192.

Source: https://realfavicongenerator.net/blog/android-chrome-and-its-favicon/


问:
How to find out what form is on top?
In Compact Framework, how can I find out which form is the form that is showing to the user (even if it is not full screen)?

Any ideas?  I will keep looking and post back if I find an answer (and no one responds).

答:
example from http://www.pinvoke.net/default.aspx/user32/GetForegroundWindow.html:</p>

```<code>public ApplicationState AppState
{
    get
    {
        Process[] processCollection = Process.GetProcessesByName(ProcessName);
        if(processCollection != null && processCollection.Length  >= 1 &&
            processCollection[0] != null)
        {
            IntPtr activeWindowHandle = Win32.GetForegroundWindow();
            //Optional int ProcessID;
            //Optional Win32.GetWindowThreadProcessId(GetForegroundWindow(),out ProcessID)
            foreach(Process wordProcess in processCollection)
            {
                //Optional if( ProcessID == wordProcess.Id ) return ApplicationState.Focused;
                if(wordProcess.MainWindowHandle == activeWindowHandle)
                {
                    return ApplicationState.Focused;
                }
            }
            return ApplicationState.Running;
        }
        return ApplicationState.NotRunning;
    }
}
</code>```

Title: How to find out what form is on top?

Body:
example from http://www.pinvoke.net/default.aspx/user32/GetForegroundWindow.html:

public ApplicationState AppState
{
    get
    {
        Process[] processCollection = Process.GetProcessesByName(ProcessName);
        if(processCollection != null && processCollection.Length  >= 1 &&
            processCollection[0] != null)
        {
            IntPtr activeWindowHandle = Win32.GetForegroundWindow();
            //Optional int ProcessID;
            //Optional Win32.GetWindowThreadProcessId(GetForegroundWindow(),out ProcessID)
            foreach(Process wordProcess in processCollection)
            {
                //Optional if( ProcessID == wordProcess.Id ) return ApplicationState.Focused;
                if(wordProcess.MainWindowHandle == activeWindowHandle)
                {
                    return ApplicationState.Focused;
                }
            }
            return ApplicationState.Running;
        }
        return ApplicationState.NotRunning;
    }
}


答:
You can also have foreach inside the while loop</p>

```<code>while (($initial_hidden == true) || !empty(mysql_fetch_assoc($q))) {
foreach($r = mysql_fetch_assoc($q)){
}
...

}
</code>```

Title: Change a while loop to foreach?

Body:
I'm about to change a code to "WordPress-customized code" (using $wpdb). And with $wpdb->get_results() I get an array that need to be outputted with a foreach loop. But the problem is that my current while-loop has a "$initial_hidden statement" in it that I don't know how to do with the new foreach.

Here is my current code:

while (($initial_hidden == true) || ($r = mysql_fetch_assoc($q))) {

...

}

So, how do I get the "initial hidden" to this:

foreach ($q as $r) {

...

}

Body:
You can also have foreach inside the while loop

while (($initial_hidden == true) || !empty(mysql_fetch_assoc($q))) {
foreach($r = mysql_fetch_assoc($q)){
}
...

}


问:
Cannot create Azure Service Container
I tried to create an Azure Service Container in the UK West region. I went through all the steps without issue however once I clicked 'Create' after a few moments I was met with :

LocationNotAvailableForResourceTypeThe provided location 'ukwest' is not available for resource type 'Microsoft.ContainerService/containerServices'. List of available regions for the resource type is 'japaneast,centralus,eastus2,japanwest,eastasia,southcentralus,australiaeast,australiasoutheast,brazilsouth,southeastasia,westus,northcentralus,westeurope,northeurope,eastus'.

Okay, I realised that was my mistake and went on to create the container in West Europe.

Now when I attempt to create the container I am met with the same error, despite setting the location to West Europe.

I have tried :

Hard refreshing and going through the whole process again.

Clearing my web cache and going through the whole process again.

Opening an incognito window and going through the whole process
again.

I have also ensured that the Azure Container Service and Azure Container Registry are registered on my subscription ID. Initially the resource group I was attempting to deploy on was set to UK West, however after deleting and recreating on West Europe, I still am unable to create the service container.

Update:

I have had Microsoft Azure Support on this case. It looks like there is an issue whereby my subscription ID cannot create the service container in the West Europe region. This has been referred onto the technical team. I'll post the solution here when I receive it.

答:
Ok, So I've had MSFT Support on this with me for a couple weeks. The solution!

I had a dns that you couldn't use. Even though it passes through all validation checks telling me that it's fine the deployment failed.

Changed the dns and it's fine.

So to summarise all the things you need to do, which it doesn't state anywhere:

Make sure you have registered Azure Container Service and Azure Container Registry on your subscription ID.

Make sure you are deploying to a region that actually supports your feature, not only that make sure your resource group is located in the same valid region. (It allows you to pass through all validation selecting a resource group that is in an invalid region)

Make sure your resource group hasn't been created by a previous failed deployment.

Attempt to change your dns to something else, it might be invalid somehow. Although it will not tell you this, just fail the deployment.

Essentially do not trust the validation on Azure at all. It'll tell you you're able to do things and everything is fine, when in fact it isn't.

I'll edit this answer with any further relevant update I receive.

Title: Cannot create Azure Service Container


问:
When loaded as partial, FullCalendar renders but no triggers are activated. No data is loaded
Update 2017/03/29 18:00

After many attempts, I found out that if the page loads with the 'Calendar' TAB being the active TAB it loads correctly, however, when the page is NOT the active tab I get the rangeStart error and no data gets loaded...

Though not clear why, I can at least make it work...somewhat...

Update 2017/03/29 16:00

We've made progress, fortunately through StackOverflow obviously...
first I found attached two posts:
How do I return the response from an asynchronous call?

jQuery: Return data after ajax call success

Which brought me to the fact that the data needs to be called async.

Another post:

Maping Events to FullCalender using JSON

Then gave me the hint how to render the JSON that comes back (my c# controller returns JSON data)

So, I altered my code as per below:

```<code>$('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            //defaultDate: moment().format("DD/MM/YYYY"),
            timeFormat: 'HH(:mm)',
            defaultView: 'month',
            editable: true,
            allDaySlot: false,
            selectable: true,
            slotMinutes: 15,
            events: function (start, end, timezone, callback) {
                $.ajax({
                    url: '@Url.Action("GetDiaryEvents", "Calendar")',
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: {
                        // our hypothetical feed requires UNIX timestamps
                        start: start.format(),
                        end: end.format()
                    },
                    success: function(events)
                    {
                        //debugger;
                        $('#calendar').fullCalendar('removeEvents');
                        $('#calendar').fullCalendar('addEventSource', events);
                        $('#calendar').fullCalendar('rerenderEvents' );
                    }
</code>```

Which works nicely, however...it ONLY does so if the Calendar page is set to be the active page. If it is not the active page, the data does not get loaded and no data gets loaded even when switching views from month -> week -> day and back...

It still gives the rangeStart error after loading the full Index.cshtml page and no data gets loaded and no calendar is rendered.

Adding a 'render call' in the JQuery Tab call solves the 'no rendering' on the page. But still doesn't solve the no-data problem:
https://fullcalendar.io/docs/display/render/

I found this post:
FullCalendar-2.7.3 events not showing on initial load

That would indicate that my standard VS2015 jquery-3.1.1.js would be the main culpritt, anybody able to confirm that ?

The problem:

When loaded as partial, FullCalendar renders but no triggers are activated.
No data is loaded.

Using

Bootstrap 3.3.7

MVC 5.2.3.0

FullCalender 3.0.0

jquery-3.1.1

jquery-ui-1.12.1

VS2015 in C#

The Setup

The page with the

 is a cshtml meant to load as a partial under a tabbed lay-out.

in the _Layout.cshtml of the tabbed Index.cshtml all major js/css gets loaded as per below:

```<code>@{
  ViewBag.Title = "Main";
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Some Application</title>

    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")

    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/datatables")

    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/themes/base/css")
    @Styles.Render("~/Content/datatables")
</code>```

When clicking 'Calendar Tab' the _prtCalendar.cshtml will be shown.

```<code>        <!-- Calendar -->
        <div role="tabpanel" class="tab-pane" id="_calendar">
            @Html.Partial("~/Views/Company/_prtCalendar.cshtml", Model)
        </div>
</code>```

_prtCalendar.cshtml has a  $(document).ready(function () { section that loads the Calendar. The Index.cshtml (in which the document is a part has a $(document).ready(function () { as well...

The JQuery-FullCalendar within that section all refer to CalendarController through @Url.Action('<action>,"Calendar")

```<code>$('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            //defaultDate: moment().format("DD/MM/YYYY"),
            timeFormat: 'HH(:mm)',
            defaultView: 'month',
            editable: true,
            allDaySlot: false,
            selectable: true,
            slotMinutes: 15,
            events: '@Url.Action("GetDiaryEvents", "Calendar")',
            eventClick: function (calEvent, jsEvent, view) {
                alert('You clicked on event id: ' + calEvent.id
                    + "\nSpecial ID: " + calEvent.someKey
                    + "\nAnd the title is: " + calEvent.title);

            },
</code>```

The Trick

If I load _prtCalendar.cshtml directly,
i.e. I load all js/css directly in/through the _prtCalendar.cshtml page and display without _Layout.cshtml and Index.cshtml all works fine and all functions within CalendarController are called correctly.

However, IF I load _prtCalendar.cshtml as partial, things seem to go awry and nothing gets loaded and I get a JS error:

TypeError: rangeStart is undefined[Learn More]
  fullcalendar.js:11023:6

Now, I would assume that is somehow because the rangeStart apparently doesn't get set properly however I do not seem to be able to identify WHY not.

_prtCalendar.cshtml Loads both fullcalendar.js and moment.min.js first before attempting the $(document).ready call through below lines.

```<code><link href="~/Content/fullcalendar.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/lib/moment.min.js"></script>
<script type="text/javascript" src="~/Scripts/fullcalendar.js"></script>
</code>```

If I use the F12 Debugger, I can see that the $('#calendar') function is called but it fails on the rangeStart call.
Other buttons on other TAB's (in same Index.cshmtl) that refer to different controllers get called correctly when called from Index.cshmtl.

Any help would be very very welcome...:-)

答:
Ok, the answer is too bloody simple...really...

Down at the bottom of the $(document).ready is a line that says:

```<code>CalLoading = false;
</code>```

Change that to:

```<code>CalLoading = true;
</code>```

And it would appear that that solves the problem...

Body:
Update 2017/03/29 18:00

After many attempts, I found out that if the page loads with the 'Calendar' TAB being the active TAB it loads correctly, however, when the page is NOT the active tab I get the rangeStart error and no data gets loaded...

Though not clear why, I can at least make it work...somewhat...

Update 2017/03/29 16:00

We've made progress, fortunately through StackOverflow obviously...
first I found attached two posts:
How do I return the response from an asynchronous call?

jQuery: Return data after ajax call success

Which brought me to the fact that the data needs to be called async.

Another post:

Maping Events to FullCalender using JSON

Then gave me the hint how to render the JSON that comes back (my c# controller returns JSON data)

So, I altered my code as per below:

$('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            //defaultDate: moment().format("DD/MM/YYYY"),
            timeFormat: 'HH(:mm)',
            defaultView: 'month',
            editable: true,
            allDaySlot: false,
            selectable: true,
            slotMinutes: 15,
            events: function (start, end, timezone, callback) {
                $.ajax({
                    url: '@Url.Action("GetDiaryEvents", "Calendar")',
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: {
                        // our hypothetical feed requires UNIX timestamps
                        start: start.format(),
                        end: end.format()
                    },
                    success: function(events)
                    {
                        //debugger;
                        $('#calendar').fullCalendar('removeEvents');
                        $('#calendar').fullCalendar('addEventSource', events);
                        $('#calendar').fullCalendar('rerenderEvents' );
                    }

Which works nicely, however...it ONLY does so if the Calendar page is set to be the active page. If it is not the active page, the data does not get loaded and no data gets loaded even when switching views from month -> week -> day and back...

It still gives the rangeStart error after loading the full Index.cshtml page and no data gets loaded and no calendar is rendered.

Adding a 'render call' in the JQuery Tab call solves the 'no rendering' on the page. But still doesn't solve the no-data problem:
https://fullcalendar.io/docs/display/render/

I found this post:
FullCalendar-2.7.3 events not showing on initial load

That would indicate that my standard VS2015 jquery-3.1.1.js would be the main culpritt, anybody able to confirm that ?

The problem:

When loaded as partial, FullCalendar renders but no triggers are activated.
No data is loaded.

Using

Bootstrap 3.3.7

MVC 5.2.3.0

FullCalender 3.0.0

jquery-3.1.1

jquery-ui-1.12.1

VS2015 in C#

The Setup

The page with the

 is a cshtml meant to load as a partial under a tabbed lay-out.

in the _Layout.cshtml of the tabbed Index.cshtml all major js/css gets loaded as per below:

@{
  ViewBag.Title = "Main";
}

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Some Application</title>

    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")

    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/datatables")

    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/themes/base/css")
    @Styles.Render("~/Content/datatables")

When clicking 'Calendar Tab' the _prtCalendar.cshtml will be shown.

            @Html.Partial("~/Views/Company/_prtCalendar.cshtml", Model)

_prtCalendar.cshtml has a  $(document).ready(function () { section that loads the Calendar. The Index.cshtml (in which the document is a part has a $(document).ready(function () { as well...

The JQuery-FullCalendar within that section all refer to CalendarController through @Url.Action('<action>,"Calendar")

$('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            //defaultDate: moment().format("DD/MM/YYYY"),
            timeFormat: 'HH(:mm)',
            defaultView: 'month',
            editable: true,
            allDaySlot: false,
            selectable: true,
            slotMinutes: 15,
            events: '@Url.Action("GetDiaryEvents", "Calendar")',
            eventClick: function (calEvent, jsEvent, view) {
                alert('You clicked on event id: ' + calEvent.id
                    + "\nSpecial ID: " + calEvent.someKey
                    + "\nAnd the title is: " + calEvent.title);

            },

The Trick

If I load _prtCalendar.cshtml directly,
i.e. I load all js/css directly in/through the _prtCalendar.cshtml page and display without _Layout.cshtml and Index.cshtml all works fine and all functions within CalendarController are called correctly.

However, IF I load _prtCalendar.cshtml as partial, things seem to go awry and nothing gets loaded and I get a JS error:

TypeError: rangeStart is undefined[Learn More]
  fullcalendar.js:11023:6

Now, I would assume that is somehow because the rangeStart apparently doesn't get set properly however I do not seem to be able to identify WHY not.

_prtCalendar.cshtml Loads both fullcalendar.js and moment.min.js first before attempting the $(document).ready call through below lines.

<link href="~/Content/fullcalendar.css" rel="stylesheet" />

If I use the F12 Debugger, I can see that the $('#calendar') function is called but it fails on the rangeStart call.
Other buttons on other TAB's (in same Index.cshmtl) that refer to different controllers get called correctly when called from Index.cshmtl.

Any help would be very very welcome...:-)

Body:
Ok, the answer is too bloody simple...really...

Down at the bottom of the $(document).ready is a line that says:

CalLoading = false;

Change that to:

CalLoading = true;

And it would appear that that solves the problem...


问:
Are the decimal places in a CSS width respected?
Something I've been wondering for a while whilst doing CSS design.

Are decimal places in CSS widths respected? Or are they rounded?

.percentage {
  width: 49.5%;
}
```
<p>or</p>
<pre class="lang-css prettyprint-override"><code>.pixel {
  width: 122.5px;
}
</code>```

答:
If it's a percentage width, then yes, it is respected:

#outer {
    width: 200px;
}

#first {
    width: 50%;
    height: 20px;
    background-color: red;
}

#second {
    width: 50.5%;
    height: 20px;
    background-color:green;
}

#third {
    width: 51%;
    height: 20px;
    background-color:blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="outer">
    <div id="first"> </div>
    <div id="second"> </div>
    <div id="third"> </div>
</div></code>```

As Martin pointed out, things break down when you get to fractional pixels, but if your percentage values yield integer pixel value (e.g. 50.5% of 200px in the example) you'll get sensible, expected behaviour.

Edit: I've updated the example to show what happens to fractional pixels (in Chrome the values are truncated, so 50, 50.5 and 50.6 all show the same width.)

#percentage {
    width: 200px;
    color: white;
}

#percentage .first {
    width: 50%;
    height: 20px;
    background-color: red;
}

#percentage .second {
    width: 50.5%;
    height: 20px;
    background-color:green;
}

#percentage .third {
    width: 51%;
    height: 20px;
    background-color:blue;
}

#pixels {
    color: white;
}

#pixels .first {
    width: 50px;
    height: 20px;
    background-color: red;
}

#pixels .second {
    width: 50.5px;
    height: 20px;
    background-color:green;
}

#pixels .third {
    width: 50.6px;
    height: 20px;
    background-color:blue;
}

#pixels .fourth {
    width: 51px;
    height: 20px;
    background-color:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="percentage">
    <div class="first">50%=100px</div>
    <div class="second">50.5%=101px</div>
    <div class="third">51%=102px</div>
</div>
<br />
<div id="pixels">
    <div class="first">50px</div>
    <div class="second">50.5px</div>
    <div class="third">50.6px</div>
    <div class="fourth">51px</div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
Something I've been wondering for a while whilst doing CSS design.

Are decimal places in CSS widths respected? Or are they rounded?

.percentage {
  width: 49.5%;
}

or

.pixel {
  width: 122.5px;
}

Body:
If it's a percentage width, then yes, it is respected:

#outer {
    width: 200px;
}

#first {
    width: 50%;
    height: 20px;
    background-color: red;
}

#second {
    width: 50.5%;
    height: 20px;
    background-color:green;
}

#third {
    width: 51%;
    height: 20px;
    background-color:blue;
}

<div id="outer">
    <div id="first">&nbsp;</div>
    <div id="second">&nbsp;</div>
    <div id="third">&nbsp;</div>
</div>

As Martin pointed out, things break down when you get to fractional pixels, but if your percentage values yield integer pixel value (e.g. 50.5% of 200px in the example) you'll get sensible, expected behaviour.

Edit: I've updated the example to show what happens to fractional pixels (in Chrome the values are truncated, so 50, 50.5 and 50.6 all show the same width.)

#percentage {
    width: 200px;
    color: white;
}

#percentage .first {
    width: 50%;
    height: 20px;
    background-color: red;
}

#percentage .second {
    width: 50.5%;
    height: 20px;
    background-color:green;
}

#percentage .third {
    width: 51%;
    height: 20px;
    background-color:blue;
}

#pixels {
    color: white;
}

#pixels .first {
    width: 50px;
    height: 20px;
    background-color: red;
}

#pixels .second {
    width: 50.5px;
    height: 20px;
    background-color:green;
}

#pixels .third {
    width: 50.6px;
    height: 20px;
    background-color:blue;
}

#pixels .fourth {
    width: 51px;
    height: 20px;
    background-color:red;
}

<div id="percentage">
    <div class="first">50%=100px</div>
    <div class="second">50.5%=101px</div>
    <div class="third">51%=102px</div>
</div>
<br />
<div id="pixels">
    <div class="first">50px</div>
    <div class="second">50.5px</div>
    <div class="third">50.6px</div>
    <div class="fourth">51px</div>
</div>