问:
Go type assertion with interface don't understand how does it
I'm reading "Go Bootcamp" and there is an example in the Chapter 3, page 20 I cannot understand. In this example, in the line printString(s), s is a variable of type fakeString, but in the switch, enters in the "Stringer" case. I'm trying to understand how is this possible. Any help would be appreciated.

The code is:

```<code>package main
import "fmt"

type Stringer interface {
   String() string
}
type fakeString struct {
   content string
}
// function used to implement the Stringer interface
func (s *fakeString) String() string {
    return s.content
}
func printString(value interface{}) {
    switch str := value.(type) {
        case string:
            fmt.Println(str)
        case Stringer:
            fmt.Println(str.String())
    }
}
func main() {
    s := &fakeString{"Ceci n'est pas un string"}
    printString(s)
    printString("Hello, Gophers")
}
</code>```

答:
Because the fakeString is a different type than string, but it implements Stringer interface. Every type with given function implements the type. The fakeString contains the String() func so it also implements Stringer interface. This is some kind of fundamental stones of Go.

Check the built-in libs for Reader interface, it is usually given as an example for this.

Body:
I'm reading "Go Bootcamp" and there is an example in the Chapter 3, page 20 I cannot understand. In this example, in the line printString(s), s is a variable of type fakeString, but in the switch, enters in the "Stringer" case. I'm trying to understand how is this possible. Any help would be appreciated.

The code is:

package main
import "fmt"

type Stringer interface {
   String() string
}
type fakeString struct {
   content string
}
// function used to implement the Stringer interface
func (s *fakeString) String() string {
    return s.content
}
func printString(value interface{}) {
    switch str := value.(type) {
        case string:
            fmt.Println(str)
        case Stringer:
            fmt.Println(str.String())
    }
}
func main() {
    s := &fakeString{"Ceci n'est pas un string"}
    printString(s)
    printString("Hello, Gophers")
}


来源: stackexchange

问:
Print a square of * (asterisks) with Unix
First of all, sorry if my English isn't very good, but it isn't my primary language (edited).

I'm self-learning to script on Unix, and I'm trying to make an script that asks for a number and then prints a square out of the given number, for example:

```<code>Size of square?
4
</code>```

****
****
****
****
```
<p>But I can't get it to print more than a single <code>*</code> (asterisk) character per line.</p>
<p>This is my code right now:</p>
<pre class="lang-sh prettyprint-override"><code>echo "Size of the square?"
    read size

clear

for (( i=0;i<size;i++ ))
do
    echo "*"
done
</code>```

I'm trying to make it work, and tried to use 2 for loops, but I just can't make it work.

答:
you can also try out this one

size 4

it will show

```<code>{****
*  *
*  *
****}
</code>```

```<code>echo "enter the sizeof the square"
read size
clear
for (( i = 1; i <= size; i++ )); do
    for (( j = 1; j <= size; j++ )); do

        if [ "$i" == 1 ] || [ "$i" == "$size" ] || [ "$j" == 1 ] || [ "$j" == "$size" ]
         then
            #statements
            tput cup $i $j
            echo "*"
        fi
     done
done
</code>```

ContentLicense: CC BY-SA 4.0

Body:
First of all, sorry if my English isn't very good, but it isn't my primary language (edited).

I'm self-learning to script on Unix, and I'm trying to make an script that asks for a number and then prints a square out of the given number, for example:

Size of square?
4

****
****
****
****

But I can't get it to print more than a single * (asterisk) character per line.

This is my code right now:

echo "Size of the square?"
    read size

clear

for (( i=0;i<size;i++ ))
do
    echo "*"
done

I'm trying to make it work, and tried to use 2 for loops, but I just can't make it work.

Body:
you can also try out this one

size 4

it will show

{****
*  *
*  *
****}

echo "enter the sizeof the square"
read size
clear
for (( i = 1; i <= size; i++ )); do
    for (( j = 1; j <= size; j++ )); do

        if [ "$i" == 1 ] || [ "$i" == "$size" ] || [ "$j" == 1 ] || [ "$j" == "$size" ]
         then
            #statements
            tput cup $i $j
            echo "*"
        fi
     done
done

ContentLicense: CC BY-SA 3.0


问:
Send large stream to ServiceFabric Service
I have a ServiceFabric service hosting WebAPI. On a controller, I receive, in my Request, a FileStream. I have no problem reading the FileStream there.

Then, I want this WebAPI service to call another SF service (stateful) - let's call it Service2, giving a MemoryStream in parameter.

```<code>try
{
    await _service2Proxy.MyService2Method(myMemoryStream, otherParameters);
    // Line after
}
catch
{
    // Error handling
}
</code>```

And in the Service2

```<code>public Task MyService2Method(MemoryStream ms, string otherParam)
{
    // Log line
    // Do something
}
</code>```

It works perfectly well with a File < 3 MB. Yet, with a file > 5 MB, the call doesn't work. We never go on // Line after, // Error handling or // Log line.

I did add [assembly: FabricTransportServiceRemotingProvider(MaxMessageSize = int.MaxValue)] on the controller assembly, the WebAPI service assembly and the Service2 assembly.
The Service2 interface has the [OperationContract] and [ServiceContract] attributes.

I also tried sending a byte[] instead of a MemoryStream. The problem is still the same.

答:
It works fine for us.

Makes sure you are setting the assembly attribute  properly.
https://msdn.microsoft.com/en-us/library/4w8c1y2s(v=vs.110).aspx

Here is what we are doing.

using Microsoft.ServiceFabric.Services.Remoting.FabricTransport;
[assembly: FabricTransportServiceRemotingProvider(MaxMessageSize = 134217728)]

Again make sure this is available in the assembly that is creating the service remoting listener and the assembly that is calling it with ServiceProxy.

Alternatively, you can set the max message size programmatically when you create the listener, or in a settings.xml config file. See here for more info on that: https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reliable-services-secure-communication/

Body:
I have a ServiceFabric service hosting WebAPI. On a controller, I receive, in my Request, a FileStream. I have no problem reading the FileStream there.

Then, I want this WebAPI service to call another SF service (stateful) - let's call it Service2, giving a MemoryStream in parameter.

try
{
    await _service2Proxy.MyService2Method(myMemoryStream, otherParameters);
    // Line after
}
catch
{
    // Error handling
}

And in the Service2

public Task MyService2Method(MemoryStream ms, string otherParam)
{
    // Log line
    // Do something
}

It works perfectly well with a File < 3 MB. Yet, with a file > 5 MB, the call doesn't work. We never go on // Line after, // Error handling or // Log line.

I did add [assembly: FabricTransportServiceRemotingProvider(MaxMessageSize = int.MaxValue)] on the controller assembly, the WebAPI service assembly and the Service2 assembly.
The Service2 interface has the [OperationContract] and [ServiceContract] attributes.

I also tried sending a byte[] instead of a MemoryStream. The problem is still the same.


问:
Java Tree Recursion parameter issues
I am attempting to give a void function to a Tree. It calculates some parameters and uses Ids  to reference some coordinates and the distance between them. The problem I have is that every recursion call returns me 0 on both parameters I use, I thought in Java every variable was a reference so this would work, but  I seem to be missing something. Here is the code:

```<code>public void volumeandcost(Integer  volume,Float cost){
    if(children().equals(0)){//children() returns the number of children our tree has
        volume=volume+getCapacidad(this.root);//root is the Id
    }
    else{//recursive call
        ArrayList<Integer> myvol= new ArrayList();
        ArrayList<Float> mycost=new ArrayList();
        for(int i=0;i<this.children();i++){
            myvol.add(new Integer(0));
            mycost.add(new Float(0.0));
            children.get(i).volumeandcost(myvol.get(i), mycost.get(i));
            cost=cost+mycost.get(i)+myvol.get(i)*
                  square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId()));
        }
        //this calculates our volume in case we have children
        volume=min(getCapacidad(root)*3,mysum(myvol)+getCapacidad(root));
    }
}
</code>```

I call this function with both parameters initially set at 0, and they come back in the same way after the call to volumeandcost.

After following some advice I implemented a new class Pair like this:

```<code>public class Pair {
Integer vol;Float cost;
public Pair (){this.vol=new Integer(0);this.cost=new Float(0);}
Integer getVol(){ return this.vol;}
Float getCost(){ return this.cost;}
void setVol(Integer x){this.vol=x ;}
void setCost(Float x){this.cost=x ;}
void addVol(Integer x){this.vol=this.vol+x;}
    void addCost(Float x){this.cost=this.cost+x;}
}
</code>```

and modified the function so that it's like this:

```<code>    public void volumeandcostp(Pair p){
    if(children().equals(0)){
        p.setVol(p.getVol() + getCapacidad(this.root));//tenemos el volumen
    }
    else{//recursion
        ArrayList<Pair> myvol= new ArrayList();
        for(int i=0;i<this.children();i++){
            myvol.add(new Pair());
            children.get(i).volumeandcostp(myvol.get(i));
            myvol.get(i).getCost());
            p.addCost(myvol.get(i).getCost()+ myvol.get(i).getVol()*                            square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId())));
        }              p.setVol(min(getCapacidad(root)*3,mysump(myvol)+getCapacidad(root)));
    }
}
</code>```

But all the getters from Pair keep giving me 0 as answer.

答:
I thought in Java every variable was a reference.

First of all that statement is wrong: you have primitive types like int, float, char. Those are not references to begin with. But indeed variables with types other than those eight are references.

But when you call a function, Java does a call-by-value. That means the references are copied. When you call: volumeandcost(a,b). Java will make a copy of the reference. So volume and cost work independently. Setting them (i.e. assigning a new value to them) in your method has no effect.

You can alter the state of the objects you are given: since you copy the reference a refers to the same object as volume (in the example above), you can call methods on the objects the references refer to and alter the state, but you cannot change the reference itself.

Title: Java Tree Recursion parameter issues

Body:
I am attempting to give a void function to a Tree. It calculates some parameters and uses Ids  to reference some coordinates and the distance between them. The problem I have is that every recursion call returns me 0 on both parameters I use, I thought in Java every variable was a reference so this would work, but  I seem to be missing something. Here is the code:

public void volumeandcost(Integer  volume,Float cost){
    if(children().equals(0)){//children() returns the number of children our tree has
        volume=volume+getCapacidad(this.root);//root is the Id
    }
    else{//recursive call
        ArrayList<Integer> myvol= new ArrayList();
        ArrayList<Float> mycost=new ArrayList();
        for(int i=0;i<this.children();i++){
            myvol.add(new Integer(0));
            mycost.add(new Float(0.0));
            children.get(i).volumeandcost(myvol.get(i), mycost.get(i));
            cost=cost+mycost.get(i)+myvol.get(i)*
                  square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId()));
        }
        //this calculates our volume in case we have children
        volume=min(getCapacidad(root)*3,mysum(myvol)+getCapacidad(root));
    }
}

I call this function with both parameters initially set at 0, and they come back in the same way after the call to volumeandcost.

After following some advice I implemented a new class Pair like this:

public class Pair {
Integer vol;Float cost;
public Pair (){this.vol=new Integer(0);this.cost=new Float(0);}
Integer getVol(){ return this.vol;}
Float getCost(){ return this.cost;}
void setVol(Integer x){this.vol=x ;}
void setCost(Float x){this.cost=x ;}
void addVol(Integer x){this.vol=this.vol+x;}
    void addCost(Float x){this.cost=this.cost+x;}
}

and modified the function so that it's like this:

    public void volumeandcostp(Pair p){
    if(children().equals(0)){
        p.setVol(p.getVol() + getCapacidad(this.root));//tenemos el volumen
    }
    else{//recursion
        ArrayList<Pair> myvol= new ArrayList();
        for(int i=0;i<this.children();i++){
            myvol.add(new Pair());
            children.get(i).volumeandcostp(myvol.get(i));
            myvol.get(i).getCost());
            p.addCost(myvol.get(i).getCost()+ myvol.get(i).getVol()*                            square(ProbIA5Board.m_dist.get(this.root).get(this.children.get(i).getId())));
        }              p.setVol(min(getCapacidad(root)*3,mysump(myvol)+getCapacidad(root)));
    }
}

But all the getters from Pair keep giving me 0 as answer.


问:
JavaScript regular expression for two-letter tokens separated by commas
I am trying to get the regular expression that accepts only characters with specific pattern like two characters separated by comma, but I am not able to get it.

Here i included the acceptable sting

```<code>string = ab,ca,ls,gz,tv......
</code>```

I tried:

```<code>/^([a-zA-Z]{2},)|([a-zA-Z]{2})*$/
</code>```

but it is not working as expected.

答:
Try using /^[a-z]{2}(?:,[a-z]{2})*$/i instead (the | inside your pattern was problematic):

var string = 'ab,ca,ls,gz,tv'

var regex = /^[a-z]{2}(?:,[a-z]{2})*$/i

console.log(regex.test(string)) //=> true```

Body:
I am trying to get the regular expression that accepts only characters with specific pattern like two characters separated by comma, but I am not able to get it.

Here i included the acceptable sting

string = ab,ca,ls,gz,tv......

I tried:

/^([a-zA-Z]{2},)|([a-zA-Z]{2})*$/

but it is not working as expected.


问:
Loop through leaflet FeatureGroup
I have a map with 3 geoJson layers representing school district boundaries. The functionality I need is simple: click the map, get a popup with the school names for each level (elementary, middle, and high school.) [eLayer,mLayer,hLayer]

Here's my feature group:

```<code>var fGroup = new L.featureGroup([eLayer,mLayer,hLayer]).addTo(map);
</code>```

I figured I could use the eachLayer method with a click event to get the school name for each polygon at that location. The code below gets me close.

```<code>fGroup.on('click',function(e){
    fGroup.eachLayer(function(layer){
        alert(e.layer.feature.properties.School);
    });
});
</code>```

I only get the name of the last added geoJson layer, which in this case is the high school. I'm a novice programmer, but I researched this for days now and I found one example that sort of had a suggestion, but their solution didn't actually work.

Just to be perfectly clear, I want my output to be like below.

```<code>___________________________
|                         |
|Lincoln Elementary School|
|Tubman Middle School     |
|Frederick High School    |
|_________________________|
</code>```

答:
I guess you have several feature groups and each one just concerns one triplet of schools.

You are close. If i understand you correctly, what you need is :

```<code>fGroup.on('click',function(e){
    var txt = '';
    fGroup.eachLayer(function(layer){
        txt = txt + layer.feature.properties.School + ' ; ';
    });
    alert(txt);
});
</code>```

The click on the group generates one single alert with the three names.

Edit

I still don't get how you retrieve the geojson contents. eLayer, for example, contains one school or several ? What follows only works if each of your *Layer contains just one school. Otherwise, if they contain several features, i don't see how you could make an association between one of the eLayer feature and one of mLayer...

```<code>var txt = '';
var eLayer = L.geoJson(ejsoncontent, {
    onEachFeature: function(feature, layer){
      txt = txt + feature.properties.School;
    }
});
var mLayer = L.geoJson(mjsoncontent, {
    onEachFeature: function(feature, layer){
      txt = txt + ' ; ' + feature.properties.School;
    }
});
var hLayer = L.geoJson(hjsoncontent, {
    onEachFeature: function(feature, layer){
      txt = txt + ' ; ' + feature.properties.School;
    }
});

var fGroup = new L.featureGroup([eLayer,mLayer,hLayer]).addTo(map);
fGroup.on('click',function(e){
    alert(txt);
});
</code>```

Title: Loop through leaflet FeatureGroup

Body:
I have a map with 3 geoJson layers representing school district boundaries. The functionality I need is simple: click the map, get a popup with the school names for each level (elementary, middle, and high school.) [eLayer,mLayer,hLayer]

Here's my feature group:

var fGroup = new L.featureGroup([eLayer,mLayer,hLayer]).addTo(map);

I figured I could use the eachLayer method with a click event to get the school name for each polygon at that location. The code below gets me close.

fGroup.on('click',function(e){
    fGroup.eachLayer(function(layer){
        alert(e.layer.feature.properties.School);
    });
});

I only get the name of the last added geoJson layer, which in this case is the high school. I'm a novice programmer, but I researched this for days now and I found one example that sort of had a suggestion, but their solution didn't actually work.

Just to be perfectly clear, I want my output to be like below.

___________________________
|                         |
|Lincoln Elementary School|
|Tubman Middle School     |
|Frederick High School    |
|_________________________|

Body:
I guess you have several feature groups and each one just concerns one triplet of schools.

You are close. If i understand you correctly, what you need is :

fGroup.on('click',function(e){
    var txt = '';
    fGroup.eachLayer(function(layer){
        txt = txt + layer.feature.properties.School + ' ; ';
    });
    alert(txt);
});

The click on the group generates one single alert with the three names.

Edit

I still don't get how you retrieve the geojson contents. eLayer, for example, contains one school or several ? What follows only works if each of your *Layer contains just one school. Otherwise, if they contain several features, i don't see how you could make an association between one of the eLayer feature and one of mLayer...

var txt = '';
var eLayer = L.geoJson(ejsoncontent, {
    onEachFeature: function(feature, layer){
      txt = txt + feature.properties.School;
    }
});
var mLayer = L.geoJson(mjsoncontent, {
    onEachFeature: function(feature, layer){
      txt = txt + ' ; ' + feature.properties.School;
    }
});
var hLayer = L.geoJson(hjsoncontent, {
    onEachFeature: function(feature, layer){
      txt = txt + ' ; ' + feature.properties.School;
    }
});

var fGroup = new L.featureGroup([eLayer,mLayer,hLayer]).addTo(map);
fGroup.on('click',function(e){
    alert(txt);
});


问:
Print the contents of the file
I am trying to print the contents of my file byte by byte. However, I do get the compiler error "invalid type argument of unary *(have int)

my code is :

```<code> void print_the_file ()
    {
       void *file_hndl;
       UINT32 file_size = 2048;
       UINT8 *hndl;
       file_hndl = fopen("my_bin_file.bin", "r") ;
       if ( file_hndl == NULL )
       {
          printf("file open failed");
       }
       hndl = (UINT8*)file_hndl;
     /* print the contents */
      for ( UINT32 i = 0; i< 2048; i++ )
    {
        printf ("%02x", *hndl[i] );
    }
   }
</code>```

Please advise me where i am going wrong and right way to print the contents of the file.

答:
Try something like this:

```<code>void print_the_file()
{
    FILE* file_hndl = fopen("my_bin_file.bin", "rb");
    if (file_hndl == NULL)
    {
        printf("file open failed");
    }
    else
    {
        while (!feof(file_hndl) && !ferror(file_hndl))
        {
            int c = fgetc(file_hndl);
            if (c != EOF) /* should be redundant */
            {
                printf("%02x", c);
            }
        }
        fclose(file_hndl);
    }
}
</code>```

Note the file mode to fopen is "rb" to open the file for read as binary.

Also, the routine processes the entire file character by character until EOF or error occurs.

Title: Print the contents of the file

Body:
I am trying to print the contents of my file byte by byte. However, I do get the compiler error "invalid type argument of unary *(have int)

my code is :

 void print_the_file ()
    {
       void *file_hndl;
       UINT32 file_size = 2048;
       UINT8 *hndl;
       file_hndl = fopen("my_bin_file.bin", "r") ;
       if ( file_hndl == NULL )
       {
          printf("file open failed");
       }
       hndl = (UINT8*)file_hndl;
     /* print the contents */
      for ( UINT32 i = 0; i< 2048; i++ )
    {
        printf ("%02x", *hndl[i] );
    }
   }

Please advise me where i am going wrong and right way to print the contents of the file.

Body:
Try something like this:

void print_the_file()
{
    FILE* file_hndl = fopen("my_bin_file.bin", "rb");
    if (file_hndl == NULL)
    {
        printf("file open failed");
    }
    else
    {
        while (!feof(file_hndl) && !ferror(file_hndl))
        {
            int c = fgetc(file_hndl);
            if (c != EOF) /* should be redundant */
            {
                printf("%02x", c);
            }
        }
        fclose(file_hndl);
    }
}

Note the file mode to fopen is "rb" to open the file for read as binary.

Also, the routine processes the entire file character by character until EOF or error occurs.


问:
pandas - Replaceing values in a column
I have a dataframe df like this:

```<code>            ID_USER  CODE
0          433805  11.0
24          5448   44.0
48          3434   11.0
72          34434  11.0
96          3202   33.0
120         23766  33.0
153         39457  44.0
168         4113   33.0
172         3435   13.0
374         34093  11.0
</code>```

And I try to replace the values from the 'CODE' column with other values.

```<code>11.0 and 44.0 -> 1
33.0 -> 0
all other -> 5
</code>```

So I did among others the following:

```<code>df['CODE'] = df.apply(lambda s:func1(s))

def func1(x):
    if (x['CODE'] == 11.0) or (x['CODE'] == 44.0):
        return 1
    elif (x['CODE'] == 33.0):
        return 0
    else:
        return 5
</code>```

And I get this error:

```<code>KeyError: ('NTL', u'occurred at index ID_UC')
</code>```

How can I solve my problem?

Title: pandas - Replaceing values in a column

Body:
I have a dataframe df like this:

            ID_USER  CODE
0          433805  11.0
24          5448   44.0
48          3434   11.0
72          34434  11.0
96          3202   33.0
120         23766  33.0
153         39457  44.0
168         4113   33.0
172         3435   13.0
374         34093  11.0

And I try to replace the values from the 'CODE' column with other values.

11.0 and 44.0 -> 1
33.0 -> 0
all other -> 5

So I did among others the following:

df['CODE'] = df.apply(lambda s:func1(s))

def func1(x):
    if (x['CODE'] == 11.0) or (x['CODE'] == 44.0):
        return 1
    elif (x['CODE'] == 33.0):
        return 0
    else:
        return 5

And I get this error:

KeyError: ('NTL', u'occurred at index ID_UC')

How can I solve my problem?

Body:
You can use np.where

df1.CODE = np.where((df1.CODE == 11.0) | (df1.CODE == 44.0), 1, np.where((df1.CODE == 33.0), 0, 5))

    ID_USER CODE
0   433805  1
24  5448    1
48  3434    1
72  34434   1
96  3202    0
120 23766   0
153 39457   1
168 4113    0
172 3435    5
374 34093   1


问:
Enable editing after an unhandled exception in Visual Studio 2017
How can I continue execution after an unhandled exception in Visual Studio 2017?

In version 2015 and below this was easily done by clicking Enable Editing which "unwinds the callstack to the point before the exception". It was then possible to edit the execution point, variables and code.

This option is gone when a library throws the exception:

```<code>"".Substring(1);
</code>```

In case the exception happens in user code it still works:

```<code>int x = 0;
Console.WriteLine(1 / x);
</code>```

Notice the yellow arrow which can be dragged.

I really hope this feature was not removed because salvaging a crashing program (here, by setting x = 1 for example, changing the string constant or by skipping the problematic line) is something I do a lot. Right now I have a multi-hour operation 99% completed in this state and I'd really like to rescue it by suppressing an unimportant error.

This is Visual Studio 2017 build 26228 on .NET 4.6.1.

答:
You can have the application not send exceptions to the debugger:

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

Works for me in VS 2017.

Body:
How can I continue execution after an unhandled exception in Visual Studio 2017?

In version 2015 and below this was easily done by clicking Enable Editing which "unwinds the callstack to the point before the exception". It was then possible to edit the execution point, variables and code.

This option is gone when a library throws the exception:

"".Substring(1);

In case the exception happens in user code it still works:

int x = 0;
Console.WriteLine(1 / x);

Notice the yellow arrow which can be dragged.

I really hope this feature was not removed because salvaging a crashing program (here, by setting x = 1 for example, changing the string constant or by skipping the problematic line) is something I do a lot. Right now I have a multi-hour operation 99% completed in this state and I'd really like to rescue it by suppressing an unimportant error.

This is Visual Studio 2017 build 26228 on .NET 4.6.1.


问:
Setting up a staging environment
I've been working for a few years on a project for a friend of mine, and it has slowly grown into a large website.

In the early stages, I just did development on my local machine with a local database, then deployed any site and database changes to the live site.

This worked well for a while, but lately we've been having issues with deployment. We'd like to set up a staging environment for testing before we deploy to the production environment.

I'm using DiscountASP.Net for hosting, does anyone know if they offer a service for a staging environment? Or is there another way I should go about setting it up?

答:
A staging environment it basically a another space (usually a server, but if you're using shared hosting then another account) that is identical to your production space, so you can test as if you're on the real server without breaking your live site.

Anything can be a staging environment, but there's no point in testing unless it's an identical space.

ContentLicense: CC BY-SA 2.5

Title: Setting up a staging environment


问:
Getting the id of the last record inserted into a MySQL database
I'm trying to get the id of the last record inserted into a MySQL database using MAX(id).
I can't figure out why my query is not returning any results. Is there something wrong with my PHP?Tthe query works if I try it inside phpmyadmin.

```<code>include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];
</code>```

答:
Try with this :

```<code>$sql = "SELECT * FRON tbl_uploads ORDER BY id DESC LIMIT 1";
</code>```

It will output your id.

Body:
I'm trying to get the id of the last record inserted into a MySQL database using MAX(id).
I can't figure out why my query is not returning any results. Is there something wrong with my PHP?Tthe query works if I try it inside phpmyadmin.

include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];

Body:
Try with this :

$sql = "SELECT * FRON tbl_uploads ORDER BY id DESC LIMIT 1";

It will output your id.


问:
How can i allign an object to the center with an image to the left of it?
Here is what I want:

In iOS this is sooooo simple, but android it seems impossible. I want the text boxes center of the screen no matter what. When I add an image, the text boxes shift even though they are center aligned and the images are not. I want the icons centered with one another, but that also seems difficult unless they are in the same layout. Should I have them all in the same Relative Layout?

I have the main layout as a Linear layout using weights to give everything an appropriate height dimension with individual Relative or linear layouts being what is weighted. Is this an accepted pattern?

Here is an example of one of the icon textViews and textEdits.

```<code>            <RelativeLayout
                android:id="@+id/passwordRelativeLayout"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="83"
                android:gravity="center">

                <ImageView
                    android:id="@+id/passwordImageView"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/email_ph"
                    android:gravity="center_horizontal"
                    android:src="@mipmap/lock_icon"
                    android:layout_alignParentBottom="true"
                    android:layout_toStartOf="@+id/passwordTextView" />

                <TextView
                    android:id="@+id/passwordTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_alignStart="@+id/passwordEditText"
                    android:labelFor="@+id/passwordEditText"
                    android:text="@string/password"
                    android:textColor="@color/white"
                    android:textSize="24sp" />

                <EditText
                    android:id="@+id/passwordEditText"
                    android:layout_width="500dp"
                    android:layout_height="45dp"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentEnd="true"
                    android:layout_below="@+id/passwordTextView"
                    android:layout_gravity="center_horizontal"
                    android:background="@mipmap/text_box_background"
                    android:gravity="center"
                    android:inputType="textPassword" />
            </RelativeLayout>\
</code>```

This doesn't have the margins setup, but I'm just concerned with getting the pixel perfect centering setup for now.

答: First of all, remove the android:gravity="center" attribute from the RelativeLayout, and use android:layout_centerHorizontal="true" on the childs you want to center (the EditText in this case, also remove the android:layout_gravity="center_horizontal" attribute from it). Let me know if it helps

Body:
Here is what I want:

In iOS this is sooooo simple, but android it seems impossible. I want the text boxes center of the screen no matter what. When I add an image, the text boxes shift even though they are center aligned and the images are not. I want the icons centered with one another, but that also seems difficult unless they are in the same layout. Should I have them all in the same Relative Layout?

I have the main layout as a Linear layout using weights to give everything an appropriate height dimension with individual Relative or linear layouts being what is weighted. Is this an accepted pattern?

Here is an example of one of the icon textViews and textEdits.

            <RelativeLayout
                android:id="@+id/passwordRelativeLayout"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="83"
                android:gravity="center">

                <ImageView
                    android:id="@+id/passwordImageView"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/email_ph"
                    android:gravity="center_horizontal"
                    android:src="@mipmap/lock_icon"
                    android:layout_alignParentBottom="true"
                    android:layout_toStartOf="@+id/passwordTextView" />

                <TextView
                    android:id="@+id/passwordTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_alignStart="@+id/passwordEditText"
                    android:labelFor="@+id/passwordEditText"
                    android:text="@string/password"
                    android:textColor="@color/white"
                    android:textSize="24sp" />

                <EditText
                    android:id="@+id/passwordEditText"
                    android:layout_width="500dp"
                    android:layout_height="45dp"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentEnd="true"
                    android:layout_below="@+id/passwordTextView"
                    android:layout_gravity="center_horizontal"
                    android:background="@mipmap/text_box_background"
                    android:gravity="center"
                    android:inputType="textPassword" />
            </RelativeLayout>\

This doesn't have the margins setup, but I'm just concerned with getting the pixel perfect centering setup for now.


问:
Difference between Delphi 2007 and 2010 when drawing on bitmaps
The following code works as expected with Delphi 2007. It takes a bitmap from an image list, draws a red X over it, and adds the new bitmap to the end of the same image list:

```<code>  DynBmp:=Graphics.TBitMap.Create;
  DynBmp.Transparent:=TRUE;
  DynBmp.TransparentMode:=tmFixed;
  ImgList.GetBitmap(9, DynBmp);
  DynBmp.TransparentColor:=DynBmp.canvas.pixels[0, DynBmp.Height - 1];
  DynBmp.Canvas.MoveTo(1, 1);
  DynBmp.Canvas.Pen.Style:=psAlternate; //psSolid;
  DynBmp.Canvas.Pen.Color:=clRed;
  DynBmp.Canvas.Pen.Width:=2;
  DynBmp.Canvas.LineTo(DynBmp.Width - 1, DynBmp.Height - 1);
  DynBmp.Canvas.MoveTo(DynBmp.Width - 1, 1);
  DynBmp.Canvas.LineTo(1, DynBmp.Height - 1);
  FErrBmpIdx:=ImgList.AddMasked(DynBmp, DynBmp.TransParentColor);
  aResetIcon.ImageIndex:=FErrBmpIdx;
  FreeAndNil(DynBmp);
</code>```

On Delphi 2010, using the same code, the red X becomes a transparent X. What do I need to add/change to get it working as expected with Delphi 2010? Thanks

答: DynBmp.TransParentColor is probably clRed before you add it to the imagelist again. Maybe TransparentMode is not tmFixed anymore? Try debugging and fix your code according to your findings.</p>

Body:
The following code works as expected with Delphi 2007. It takes a bitmap from an image list, draws a red X over it, and adds the new bitmap to the end of the same image list:

  DynBmp:=Graphics.TBitMap.Create;
  DynBmp.Transparent:=TRUE;
  DynBmp.TransparentMode:=tmFixed;
  ImgList.GetBitmap(9, DynBmp);
  DynBmp.TransparentColor:=DynBmp.canvas.pixels[0, DynBmp.Height - 1];
  DynBmp.Canvas.MoveTo(1, 1);
  DynBmp.Canvas.Pen.Style:=psAlternate; //psSolid;
  DynBmp.Canvas.Pen.Color:=clRed;
  DynBmp.Canvas.Pen.Width:=2;
  DynBmp.Canvas.LineTo(DynBmp.Width - 1, DynBmp.Height - 1);
  DynBmp.Canvas.MoveTo(DynBmp.Width - 1, 1);
  DynBmp.Canvas.LineTo(1, DynBmp.Height - 1);
  FErrBmpIdx:=ImgList.AddMasked(DynBmp, DynBmp.TransParentColor);
  aResetIcon.ImageIndex:=FErrBmpIdx;
  FreeAndNil(DynBmp);

On Delphi 2010, using the same code, the red X becomes a transparent X. What do I need to add/change to get it working as expected with Delphi 2010? Thanks


问:
How to subtract each item in a group against other items in group in t-sql
I have a table of transactions per company.  If company, transaction date, and transaction type are the same and the difference between one record's transaction price is greater than .25% with another record's of the same company, transaction date, and transaction type, then I need to select the two (or more) records.

I know I need to use group by to do this, and I will probably need to join the table to itself, but I am struggling to come up with an approach here.  How should I do this?

```<code>Transaction_ID | Company | Transction_date | Transaction_Type | Price
1              | A       |   01/01/2017     |       BUY       |   30.01
2              |   A     |     01//01/2017  |         BUY     |       37
3              |   A     |     01/02/2017   |         BUY     |      31
</code>```

答:
No, you do not need to use group by to do this, because you do not talk about group, instead you specify condition between 2 records.
As you said, the condition is: same company, transaction date, and transaction type for the 2 records, and .25% price difference (you might want 25%, because .25% is very small difference).
You should specify your goal more precisely. You said, you want the 2 or more records. As you see, you have one answer which gives records from your table, and an other answer, which combines 2 records, which fulfill the conditions.
One solution which can do what you have asked:

```<code>select distinct t.*
from yourtable t
where exists (
  select 1
  from yourtable t2
  where t2.Company = t.Company and
        t2.Transaction_date = t.Transaction_date and
        t2.Transaction_Type = t.Transaction_Type and
        t2.Price not between t.Price / 1.0025 and t.Price * 1.0025
)
</code>```

Body:
I have a table of transactions per company.  If company, transaction date, and transaction type are the same and the difference between one record's transaction price is greater than .25% with another record's of the same company, transaction date, and transaction type, then I need to select the two (or more) records.

I know I need to use group by to do this, and I will probably need to join the table to itself, but I am struggling to come up with an approach here.  How should I do this?

Transaction_ID | Company | Transction_date | Transaction_Type | Price
1              | A       |   01/01/2017     |       BUY       |   30.01
2              |   A     |     01//01/2017  |         BUY     |       37
3              |   A     |     01/02/2017   |         BUY     |      31

Body:
No, you do not need to use group by to do this, because you do not talk about group, instead you specify condition between 2 records.
As you said, the condition is: same company, transaction date, and transaction type for the 2 records, and .25% price difference (you might want 25%, because .25% is very small difference).
You should specify your goal more precisely. You said, you want the 2 or more records. As you see, you have one answer which gives records from your table, and an other answer, which combines 2 records, which fulfill the conditions.
One solution which can do what you have asked:

select distinct t.*
from yourtable t
where exists (
  select 1
  from yourtable t2
  where t2.Company = t.Company and
        t2.Transaction_date = t.Transaction_date and
        t2.Transaction_Type = t.Transaction_Type and
        t2.Price not between t.Price / 1.0025 and t.Price * 1.0025
)


问:
React.js 'Unexpected token' < when using form tag
I've been making a web app using mern stack with babel, webpack, redux and semantic-ui-react.

But I got an error saying

"Unexpected token <" in bundle.js.

This error only occurs when I send a request clicking a button in form tag. If I make the page without a form tag, it works fine without any error.

This is my codes in React.

```<code>handleUpload(title, contents, userId) {
  return this.props.createPostRequest(title, contents, userId).then(
    () => {
      if(this.props.post.status === 'SUCCESS') {
        alert('Your post is saved successfully.');
        browserHistory.push('/');
        return true;
      } else {
        alert('Save Fail: ' + this.props.post.failReason);
        return false;
      }
    }
  );
}

render() {
  return(
    <div className="Write">
      <br/>
      <br/>
      <Form>
        <Container text>
          <Form.Input label='Title' fluid name='title' placeholder='title'
            value={this.state.title} onChange={this.handleChange}>
            <input/>
          </Form.Input>
          <Form.TextArea rows='20' name='contents' placeholder='Write here!'
            value={this.state.contents} onChange={this.handleChange}>
            <textarea/>
          </Form.TextArea>
          <br/>
          <Button.Group>
            <Button color='orange' as={Link} to='/'>Cancel</Button>
            <Button.Or/>
            <Button positive onClick={this.handleUpload}>Save</Button>
          </Button.Group>
        </Container>
      </Form>
    </div>
  );
}
</code>```

When I type letters and click the save button, I can see an alert message saying

Your post is saved successfully..

And also the data I put is saved in mongodb. But after I click ok, the url changes from 'localhost:3000/post/write' to 'localhost:3000/post/write?title=blah&contents=blah'. blah in the url is what I put in input tags. Then console says

Unxpected token <.

But, if I don't use a form tag in above codes, it works fine, which I totally have no idea what's wrong about.. The Form tag is from semantic-ui-react. So I need it. If I don't use Form, it would work fine but I should give up the design provided from semantic-ui.

Is there anyone who knows about this? I guess it's related to the HTTP POST in form tags that make trouble for react.js to understand bundle.js in index.html after the server-side handles the post request from that form tag.

答:
TL;DR

```<code>handleSubmit = (e) => e.preventDefault()

<Form onSubmit={this.handleSubmit} />
</code>```

Why?

By default, an HTML form will make GET request to the current URI on submit, see here.  Also by default, a button in a form will submit it:

http://codepen.io/levithomason/pen/RpEwWP

```<code><form onsubmit="alert('submitted!')">
  <button>I'll submit</button>
  <button>Me too</button>
</form>
</code>```

What is happening is, React is rendering a <form /> with some <button />s inside of it and when you click them, it is making a GET request to the current URI with the form data.

Going out on a limb, I bet your local server that is serving your app doesn't have a handler to accept this request.  Going further, I bet it also has a fallback that responds with the index.html on unknown requests.  This is commonplace for single page apps to allow the app's soft router to handle routing, rather than the server.  This is probably causing your request for bundle.js to actually receive the index.html, hence the unexpected token.

Since you've stated:

...if I don't use a form tag in above codes, it works fine...

Simply preventing the form submit should solve it for you.

Body:
I've been making a web app using mern stack with babel, webpack, redux and semantic-ui-react.

But I got an error saying

"Unexpected token <" in bundle.js.

This error only occurs when I send a request clicking a button in form tag. If I make the page without a form tag, it works fine without any error.

This is my codes in React.

handleUpload(title, contents, userId) {
  return this.props.createPostRequest(title, contents, userId).then(
    () => {
      if(this.props.post.status === 'SUCCESS') {
        alert('Your post is saved successfully.');
        browserHistory.push('/');
        return true;
      } else {
        alert('Save Fail: ' + this.props.post.failReason);
        return false;
      }
    }
  );
}

render() {
  return(

      <Form>
        <Container text>
          <Form.Input label='Title' fluid name='title' placeholder='title'
            value={this.state.title} onChange={this.handleChange}>
            <input/>
          </Form.Input>
          <Form.TextArea rows='20' name='contents' placeholder='Write here!'
            value={this.state.contents} onChange={this.handleChange}>
            <textarea/>
          </Form.TextArea>

          <Button.Group>
            <Button color='orange' as={Link} to='/'>Cancel</Button>
            <Button.Or/>
            <Button positive onClick={this.handleUpload}>Save</Button>
          </Button.Group>
        </Container>
      </Form>

  );
}

When I type letters and click the save button, I can see an alert message saying

Your post is saved successfully..

And also the data I put is saved in mongodb. But after I click ok, the url changes from 'localhost:3000/post/write' to 'localhost:3000/post/write?title=blah&contents=blah'. blah in the url is what I put in input tags. Then console says

Unxpected token <.

But, if I don't use a form tag in above codes, it works fine, which I totally have no idea what's wrong about.. The Form tag is from semantic-ui-react. So I need it. If I don't use Form, it would work fine but I should give up the design provided from semantic-ui.

Is there anyone who knows about this? I guess it's related to the HTTP POST in form tags that make trouble for react.js to understand bundle.js in index.html after the server-side handles the post request from that form tag.

Body:
TL;DR

handleSubmit = (e) => e.preventDefault()

<Form onSubmit={this.handleSubmit} />

Why?

By default, an HTML form will make GET request to the current URI on submit, see here.  Also by default, a button in a form will submit it:

http://codepen.io/levithomason/pen/RpEwWP

<form onsubmit="alert('submitted!')">
  <button>I'll submit</button>
  <button>Me too</button>
</form>

What is happening is, React is rendering a <form /> with some <button />s inside of it and when you click them, it is making a GET request to the current URI with the form data.

Going out on a limb, I bet your local server that is serving your app doesn't have a handler to accept this request.  Going further, I bet it also has a fallback that responds with the index.html on unknown requests.  This is commonplace for single page apps to allow the app's soft router to handle routing, rather than the server.  This is probably causing your request for bundle.js to actually receive the index.html, hence the unexpected token.

Since you've stated:

...if I don't use a form tag in above codes, it works fine...

Simply preventing the form submit should solve it for you.


问:
Fragments inside Activity - with Toolbar and Action buttons (similar to Windows windows)
I would like to have an Activity populated with Fragments. Every Fragment behaves as a windows in Windows OS - it has its Toolbar with title and action buttons:

Fragment:

```<code>    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Show Toolbar in Fragment
        setHasOptionsMenu(true);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_entries_list, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        inflater.inflate(R.menu.menu_common, menu);
    }
</code>```

Question:

How to change the title of the Fragment?

How to display three-dot actions button?

Edit:

I have now modified menu_common.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_categories"
        android:title="Categories"
        android:visible="true"
        app:showAsAction="never"/>
    <item
        android:id="@+id/action_settings"
        android:title="Settings"/>
</menu>
</code>```

Fragment

```<code>@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup view = (ViewGroup) inflater.inflate(
                R.layout.fragment_entries_list, container, false);

        // Toolbar
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.tb_actions);
        toolbar.setTitle("Bar");
        toolbar.showOverflowMenu();
        setHasOptionsMenu(true);

        // Inflate the layout for this fragment
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_common, menu);
    }
</code>```

Edit 2:

This is what I want to achieve:

答:
It seems not possible to have more then 1 Toolbar on the page (at least I haven't found the way).

My solution was to use custom TextView and ImageView (icon-button) along with PopupMenu for each Fragment.

Body:
I would like to have an Activity populated with Fragments. Every Fragment behaves as a windows in Windows OS - it has its Toolbar with title and action buttons:

Fragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Show Toolbar in Fragment
        setHasOptionsMenu(true);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_entries_list, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        inflater.inflate(R.menu.menu_common, menu);
    }

Question:

How to change the title of the Fragment?

How to display three-dot actions button?

Edit:

I have now modified menu_common.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_categories"
        android:title="Categories"
        android:visible="true"
        app:showAsAction="never"/>
    <item
        android:id="@+id/action_settings"
        android:title="Settings"/>
</menu>

Fragment

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup view = (ViewGroup) inflater.inflate(
                R.layout.fragment_entries_list, container, false);

        // Toolbar
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.tb_actions);
        toolbar.setTitle("Bar");
        toolbar.showOverflowMenu();
        setHasOptionsMenu(true);

        // Inflate the layout for this fragment
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_common, menu);
    }

Edit 2:

This is what I want to achieve:


问:
Python: Output while waiting for input
So I currently have a thread that is outputting, and I need a way to handle input while still allowing output from the thread in the meantime.

Currently I have something like this

```<code>def thread_func():
    while True:
        print("Information")

threading.Thread(target=thread_func).start()

while True:
    command = raw_input("Enter a command:")
    #dostuff with command
</code>```

My issue now is that my thread isn't printing anything.  Or if it is it isn't showing up

Edit:

Found a solution here
Exiting while loop by pressing enter without blocking. How can I improve this method?

答: You want to use a Queue. New input will go into the back of the queue, and work will be started from the front. </p>

Title: Python: Output while waiting for input

Body:
So I currently have a thread that is outputting, and I need a way to handle input while still allowing output from the thread in the meantime.

Currently I have something like this

def thread_func():
    while True:
        print("Information")

threading.Thread(target=thread_func).start()

while True:
    command = raw_input("Enter a command:")
    #dostuff with command

My issue now is that my thread isn't printing anything.  Or if it is it isn't showing up

Edit:

Found a solution here
Exiting while loop by pressing enter without blocking. How can I improve this method?


问:
How to filter() out NaN, null, 0, false in an array (JS)
I was asked to filter out NaN, null, 0, false in an array.

Luckily I have answered the question.

```<code>function bouncer(arr) {
  function filterer(arr) {
     return arr > 0|| isNaN(arr) === true;
  }
  arr = arr.filter(filterer);
  return arr;
}

//example input
bouncer([0, 1, 2, 3, 'ate', '', false]); //output [1, 2, 3, 'ate']
</code>```

but the thing is I really don't know how I came up with the answer or rather I don't know how it works. Specially on arr > 0 how did the filter know that arr is alread on arr[1], arr[2], etc.. without using a loop to iterate in all array.

or can simply just explain on how to code works. [I've tried to explain it clearly ---]

答:
Looks like Boolean is the simplest fix/answer for the "FreeCodeCamp" challenge, however it might be useful to try a couple of things just to get the hang of "why" and "how".

```<code>function bouncer(arr) {
      return arr.filter(function(val){
        return val;
     });
    }
</code>```

This evaluates everything passing through the filter, using the function(callback) passed in, which returns values. If it doesn't return a value, which null etc won't, it won't be included in the return. At least this method helped me understand why rather than just pass the test.

Body:
I was asked to filter out NaN, null, 0, false in an array.

Luckily I have answered the question.

function bouncer(arr) {
  function filterer(arr) {
     return arr > 0|| isNaN(arr) === true;
  }
  arr = arr.filter(filterer);
  return arr;
}

//example input
bouncer([0, 1, 2, 3, 'ate', '', false]); //output [1, 2, 3, 'ate']

but the thing is I really don't know how I came up with the answer or rather I don't know how it works. Specially on arr > 0 how did the filter know that arr is alread on arr[1], arr[2], etc.. without using a loop to iterate in all array.

or can simply just explain on how to code works. [I've tried to explain it clearly ---]

Body:
Looks like Boolean is the simplest fix/answer for the "FreeCodeCamp" challenge, however it might be useful to try a couple of things just to get the hang of "why" and "how".

function bouncer(arr) {
      return arr.filter(function(val){
        return val;
     });
    }

This evaluates everything passing through the filter, using the function(callback) passed in, which returns values. If it doesn't return a value, which null etc won't, it won't be included in the return. At least this method helped me understand why rather than just pass the test.


问:
C# folders and sub folders
How to do this:

Check if folder upload exists (if nor then create it) ~/ uploads

Check if subfolder with username exists ~/uploads/folder with username

It as to check for each case individually because I could add a new user to the system and of course the folder uploads alredy exists, just need to create a sub folder with username

答:
In short:

Use HttpServerUtility.MapPath to convert the virtual path (such as ~/uploads) to a physical path.

Use Directory.Exists to determine if the directory exists or not

If the directory does not exist, use Directory.CreateDirectory to create it.

Title: C# folders and sub folders


问:
Install multiple version of cocoa pods
Is it possible to install multiple versions of cocoa pods on the same machine ? I need one project to be build from cocoa pod 0.33 and another one from the latest version. Is this possible ?</p>

答:
You can use bundler.  CocoaPods even recommends this from their site

In the root of your project, include a Gemfile:

```<code>source 'https://rubygems.org'

gem 'cocoapods', '1.0.0'
</code>```

You can customize the version of cocoapods used for each project in its local Gemfile.  To run, simply call your pod commands from bundler (after running "bundle install"):

```<code>bundle install
bundle exec pod install
bundle exec pod update
</code>```

Title: Install multiple version of cocoa pods

Body:
You can use bundler.  CocoaPods even recommends this from their site

In the root of your project, include a Gemfile:

source 'https://rubygems.org'

gem 'cocoapods', '1.0.0'

You can customize the version of cocoapods used for each project in its local Gemfile.  To run, simply call your pod commands from bundler (after running "bundle install"):

bundle install
bundle exec pod install
bundle exec pod update


问:
How to fix "Configuration system failed to initialize/Root element is missing" error when loading config file?
I got this error in my c# windows application: "Configuration system failed to initialize".

It was working fine. Suddenly I got this exception. It shows inner exception detail as "Root element is missing". (C:\Users\company\AppData\Local\Clickbase_Corp_Sverige_AB\TouchStation.vshost.exe_Url_no1nets4fg3oy2p2q2pnwgulbvczlv33\1.1.0.12\user.config)"}.This happens when I try to get values from Settings.cs class.

In program.cs file the below code is written

```<code>if (Properties.Settings.Default.CallUpgrade)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.CallUpgrade = false;
                Properties.Settings.Default.Save();
            }
</code>```

And calls settings.cs class where the below code throws above exception

```<code>    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("True")]

    public bool CallUpgrade {
        get {
            return ((bool)(this["CallUpgrade"]));
        }
        set {
            this["CallUpgrade"] = value;
        }
    }
</code>```

The below is my entire app.config

<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>

  </configSections>
  <appSettings>
    <add key="WebRoot" value="webroot" />
    <add key="TempDir" value="temp" />
    <add key="ServerPort" value="9338" />
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <userSettings>
    <TouchStation.Properties.Settings>
      <setting name="Site" serializeAs="String">
        <value />
      </setting>
      <setting name="StationID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="Location" serializeAs="String">
        <value />
      </setting>
      <setting name="ShutdownTime" serializeAs="String">
        <value>0000</value>
      </setting>
      <setting name="ReportStatusEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="SynchronizeEvery" serializeAs="String">
        <value>10</value>
      </setting>
      <setting name="DefaultUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="DefaultPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="WatchdogTimeout" serializeAs="String">
        <value>60</value>
      </setting>
      <setting name="RebootOnTimeout" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="AnonymousLogin" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="RefID" serializeAs="String">
        <value />
      </setting>
      <setting name="AutoStart" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="DemoMode" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="UnlockPassword" serializeAs="String">
        <value>needle</value>
      </setting>
      <setting name="SynchronizerUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="SynchronizerPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="RunClientApplications" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="MapID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="ServerName" serializeAs="String">
        <value />
      </setting>
      <setting name="CallUpgrade" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="ServerPort" serializeAs="String">
        <value>9338</value>
      </setting>
    </TouchStation.Properties.Settings>
    <TouchStation.TouchStation>
      <setting name="ServerURL" serializeAs="String">
        <value />
      </setting>
      <setting name="Site" serializeAs="String">
        <value />
      </setting>
      <setting name="StationID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="Location" serializeAs="String">
        <value />
      </setting>
      <setting name="ShutdownTime" serializeAs="String">
        <value />
      </setting>
      <setting name="ReportStatusEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="SynchronizeEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="HideMouse" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="HideDesktopOnStart" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="DefaultUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="DefaultPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="LogServerPort" serializeAs="String">
        <value>9050</value>
      </setting>
      <setting name="WatchdogTimeout" serializeAs="String">
        <value>60</value>
      </setting>
      <setting name="RebootOnTimeout" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="AnonymousLogin" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="RefID" serializeAs="String">
        <value />
      </setting>
    </TouchStation.TouchStation>
  </userSettings>
  <applicationSettings>
    <TouchStation.TouchStation>
      <setting name="ClientSettingsURL" serializeAs="String">
        <value />
      </setting>
    </TouchStation.TouchStation>
  </applicationSettings>
  <SitesInfo>
    <sites>
      <site Name="Local" FullName="Local Site" DatabaseConnectionString="Data\local.db" />
    </sites>
  </SitesInfo>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>
```

can anyone help me in this?

Thank You.

Regards,

jennie

答:
Just in case if any one reads This :

For me i solved the issue by just going to the user.config location, for this question it is :

(C:\Users\company\AppData\Local\Clickbase_Corp_Sverige_AB\TouchStation.vshost.exe_Url_no1nets4fg3oy2p2q2pnwgulbvczlv33\1.1.0.12\user.config)"

I deleted the config file and restarted visual studio and it worked.

Hope this helps!

Thanks

Body:
I got this error in my c# windows application: "Configuration system failed to initialize".

It was working fine. Suddenly I got this exception. It shows inner exception detail as "Root element is missing". (C:\Users\company\AppData\Local\Clickbase_Corp_Sverige_AB\TouchStation.vshost.exe_Url_no1nets4fg3oy2p2q2pnwgulbvczlv33\1.1.0.12\user.config)"}.This happens when I try to get values from Settings.cs class.

In program.cs file the below code is written

if (Properties.Settings.Default.CallUpgrade)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.CallUpgrade = false;
                Properties.Settings.Default.Save();
            }

And calls settings.cs class where the below code throws above exception

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("True")]

    public bool CallUpgrade {
        get {
            return ((bool)(this["CallUpgrade"]));
        }
        set {
            this["CallUpgrade"] = value;
        }
    }

The below is my entire app.config

<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    </sectionGroup>

  </configSections>
  <appSettings>
    <add key="WebRoot" value="webroot" />
    <add key="TempDir" value="temp" />
    <add key="ServerPort" value="9338" />
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <userSettings>
    <TouchStation.Properties.Settings>
      <setting name="Site" serializeAs="String">
        <value />
      </setting>
      <setting name="StationID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="Location" serializeAs="String">
        <value />
      </setting>
      <setting name="ShutdownTime" serializeAs="String">
        <value>0000</value>
      </setting>
      <setting name="ReportStatusEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="SynchronizeEvery" serializeAs="String">
        <value>10</value>
      </setting>
      <setting name="DefaultUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="DefaultPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="WatchdogTimeout" serializeAs="String">
        <value>60</value>
      </setting>
      <setting name="RebootOnTimeout" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="AnonymousLogin" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="RefID" serializeAs="String">
        <value />
      </setting>
      <setting name="AutoStart" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="DemoMode" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="UnlockPassword" serializeAs="String">
        <value>needle</value>
      </setting>
      <setting name="SynchronizerUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="SynchronizerPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="RunClientApplications" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="MapID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="ServerName" serializeAs="String">
        <value />
      </setting>
      <setting name="CallUpgrade" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="ServerPort" serializeAs="String">
        <value>9338</value>
      </setting>
    </TouchStation.Properties.Settings>
    <TouchStation.TouchStation>
      <setting name="ServerURL" serializeAs="String">
        <value />
      </setting>
      <setting name="Site" serializeAs="String">
        <value />
      </setting>
      <setting name="StationID" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="Location" serializeAs="String">
        <value />
      </setting>
      <setting name="ShutdownTime" serializeAs="String">
        <value />
      </setting>
      <setting name="ReportStatusEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="SynchronizeEvery" serializeAs="String">
        <value>0</value>
      </setting>
      <setting name="HideMouse" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="HideDesktopOnStart" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="DefaultUsername" serializeAs="String">
        <value />
      </setting>
      <setting name="DefaultPassword" serializeAs="String">
        <value />
      </setting>
      <setting name="LogServerPort" serializeAs="String">
        <value>9050</value>
      </setting>
      <setting name="WatchdogTimeout" serializeAs="String">
        <value>60</value>
      </setting>
      <setting name="RebootOnTimeout" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="AnonymousLogin" serializeAs="String">
        <value>True</value>
      </setting>
      <setting name="RefID" serializeAs="String">
        <value />
      </setting>
    </TouchStation.TouchStation>
  </userSettings>
  <applicationSettings>
    <TouchStation.TouchStation>
      <setting name="ClientSettingsURL" serializeAs="String">
        <value />
      </setting>
    </TouchStation.TouchStation>
  </applicationSettings>
  <SitesInfo>
    <sites>
      <site Name="Local" FullName="Local Site" DatabaseConnectionString="Data\local.db" />
    </sites>
  </SitesInfo>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

can anyone help me in this?

Thank You.

Regards,

jennie


问:
jquery fullcalendar not rendering custom fields
I added jquery full calendar and it works fine. But its not rendering custom fields properly.

```<code>$('.calendar').each(function () {
    var calendar = $(this);
    calendar.fullCalendar({
        header: {
            left: 'prev, next today',
            center: 'title',
            right: 'month,basicWeek,basicDay'
        },
        selectable: true,
        selectHelper: true,
        editable: false,
        displayEventTime: false,
        eventLimit: true,
        events: [{"id":22,"title":"john","start":"2017-03-30","end":"2017-03-31","color":"green","allDay":true,"last_name":"doe"}],
        eventRender: function(event, element) {
            element.attr("content",event.last_name)

        }

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

Here the last_name is not showing in calendar. But default fields are showing fine. How can I show last_name in calendar?

答:
So this is the way to go if someone needs. Got this solution with some help from github issues.

```<code>eventRender: function(event, element) {
    element.append(event.last_name);
}
#or wrapping it with html:

eventRender: function(event, element) {
    element.append('<span style="color: pink;">' + event.last_name + '</span>');
}
</code>```

Body:
I added jquery full calendar and it works fine. But its not rendering custom fields properly.

$('.calendar').each(function () {
    var calendar = $(this);
    calendar.fullCalendar({
        header: {
            left: 'prev, next today',
            center: 'title',
            right: 'month,basicWeek,basicDay'
        },
        selectable: true,
        selectHelper: true,
        editable: false,
        displayEventTime: false,
        eventLimit: true,
        events: [{"id":22,"title":"john","start":"2017-03-30","end":"2017-03-31","color":"green","allDay":true,"last_name":"doe"}],
        eventRender: function(event, element) {
            element.attr("content",event.last_name)

        }

    });
})

Here the last_name is not showing in calendar. But default fields are showing fine. How can I show last_name in calendar?

Body:
So this is the way to go if someone needs. Got this solution with some help from github issues.

eventRender: function(event, element) {
    element.append(event.last_name);
}
#or wrapping it with html:

eventRender: function(event, element) {
    element.append('<span style="color: pink;">' + event.last_name + '</span>');
}


问:
Best practices if your Build is taking too long in Visual Studio
I have moderate size solution in Visual Studio which takes around 5 minutes to build (It take that long because of FxCop and other post build steps).
My problem is, Visual Studio stops responding while it's building. You can't continue working as VS almost hangs. I tried using two VS instances, just using one for build, but it keeps crashing every now and then.

My question is, How to not waste time looking at Visual Studio building your large/moderate project. Are there any best practices for this?

答:
Two excellent MSBuild tips I just learned yesterday...

You can run tasks in parallel by using the /m:n switch where n is the number of processors to use. All you have to do is set BuildInParallel on your MSBuild task.

The other trick is that if you have several <exec /> tasks to run you can actually run them in parallel too by calling <exec command="sleep 10|sleep 10|sleep 20" /> by using the pipe character between each command. A more practical example:

```<code><CreateItem Include="server1;server2;server3;server2">
  <Output ItemName="IISServer" TaskParameter="Include"/>
</CreateItem>
<CreateProperty Value="@(IISServer->'iisreset.exe /start %(Identity)', '|')">
  <Output TaskParameter="Value" PropertyName="IISServerStartAll" />
</CreateProperty>
<exec command="$(IISServerStartAll)" />
</code>```

Body:
Two excellent MSBuild tips I just learned yesterday...

You can run tasks in parallel by using the /m:n switch where n is the number of processors to use. All you have to do is set BuildInParallel on your MSBuild task.

The other trick is that if you have several <exec /> tasks to run you can actually run them in parallel too by calling <exec command="sleep 10|sleep 10|sleep 20" /> by using the pipe character between each command. A more practical example:

<CreateItem Include="server1;server2;server3;server2">
  <Output ItemName="IISServer" TaskParameter="Include"/>
</CreateItem>
<CreateProperty Value="@(IISServer->'iisreset.exe /start %(Identity)', '|')">
  <Output TaskParameter="Value" PropertyName="IISServerStartAll" />
</CreateProperty>
<exec command="$(IISServerStartAll)" />

OwnerDisplayName: David Thomas Garcia


问:
(De)Normalization of two relations
People who read C.J.Date's Introduction to Database System or books of similar level should not have problems with definition of normalization and denormalization.

However, memory is not what it used to be and I find myself often looking at some design and saying that it is not normalized even though I can not find which of the normal forms it is breaking.

The actual example that illustrate it is:

If we have relations

r1 (A, B, C) and r2 (A, D)

with FDs: AB->C and A->D

and r1 represent detailed data, while r2 is summary of that data (in another words each instance of D is a function of values in r1. in this example let it be subtotal of values C according to A from r1).

Example instance

```<code>r1 =
A  B  C
1  1  10
1  2  20
2  1  10
2  2  25

r2 =
A  D
1  30
2  35
</code>```

So, even though I can not say that it breaks for example 2NF or 3NF, I seem to be stuck on the idea that the design is still denormalised in the following sense (from Codd, E.F. "Further Normalization of the Data Base Relational Model", p. 34, commenting on the reasons to normalize beyond 1NF):

To free the collection of relations from undesirable insertion,
  update and deletion dependencies;

To reduce the need for restructuring the collection of
  relations as new types of data are
  introduced, and thus increase the life
  span of application programs;

To make the relational model more informative to users;

To make the collection of relations neutral to the query
  statistics, where these statistics are
  liable to change as time goes by.

As I can say, that if we define D as a sum of all Cs from r1 where A from r1 is equal to A from r2 then, if we update C in r1 and we don't update D in r2, we can end up with undesirable update dependency and the data ends up in inconsistent state I find this reason to call r1 and r2 denormalized and to think of them as denormalized. (In fact whole r2 is a function of r1 and bring zero new facts into the model; r2 = f(r1))

So the questions are

can we call r1 and r2 denormalized?

if yes, why? if not, why? (according to which rule? or according to which definition?)

NOTE:

To those who find the question(s) interesting enough to put in an answer, I kindly ask to provide either something quotable or to put it in a form of specific assumptions and conclusions (or in another words, if you are going to put in your opinion, please follow it with some reasoning).

EDIT
I accepted dportas answer. I'll try to add a bit to it here:
C.J.Date can makes a clear and strict distinction:

Much of design theory has to do with
  reducing redundancy; normalization
  reduces redundancy within relvars,
  orthogonality reduces it across
  relvars.

quoted from Database in depth: relational theory for practitioners

and on the next page

just as a failure to normalize all the
  way implies redundancy and can lead to
  certain anomalies, so too can a
  failure to adhere to orthogonality.

答:
Assuming AB is a key in r1 and A is a key in r2 then it seems that the schema is in 6NF. The Relational Database Dictionary (Date) defines denormalization as:

Replacing a set of relvars R1, R2, . .
  ., Rn by their join R, such that for
  all i the projection of R on the
  attributes of Ri is guaranteed to be
  equal to Ri (i = 1, 2, . . ., n).

Fundamentally, normalization/denormalization is about composition and nonloss decomposition using projection and join operators. In this example you have redundancy caused by a different operator: summation. I expect it would be quite possible in principle to form a theory of "normalization" for operators other than projection and join, perhaps even for non-relational functions like summation. That's not how normalization is conventionally defined however and in the absence of any sound basis for doing otherwise I think we ought to apply the technical meaning denormalization as defined by Date in the above quotation.

Title: (De)Normalization of two relations

Body:
People who read C.J.Date's Introduction to Database System or books of similar level should not have problems with definition of normalization and denormalization.

However, memory is not what it used to be and I find myself often looking at some design and saying that it is not normalized even though I can not find which of the normal forms it is breaking.

The actual example that illustrate it is:

If we have relations

r1 (A, B, C) and r2 (A, D)

with FDs: AB->C and A->D

and r1 represent detailed data, while r2 is summary of that data (in another words each instance of D is a function of values in r1. in this example let it be subtotal of values C according to A from r1).

Example instance

r1 =
A  B  C
1  1  10
1  2  20
2  1  10
2  2  25

r2 =
A  D
1  30
2  35

So, even though I can not say that it breaks for example 2NF or 3NF, I seem to be stuck on the idea that the design is still denormalised in the following sense (from Codd, E.F. "Further Normalization of the Data Base Relational Model", p. 34, commenting on the reasons to normalize beyond 1NF):

To free the collection of relations from undesirable insertion,
  update and deletion dependencies;

To reduce the need for restructuring the collection of
  relations as new types of data are
  introduced, and thus increase the life
  span of application programs;

To make the relational model more informative to users;

To make the collection of relations neutral to the query
  statistics, where these statistics are
  liable to change as time goes by.

As I can say, that if we define D as a sum of all Cs from r1 where A from r1 is equal to A from r2 then, if we update C in r1 and we don't update D in r2, we can end up with undesirable update dependency and the data ends up in inconsistent state I find this reason to call r1 and r2 denormalized and to think of them as denormalized. (In fact whole r2 is a function of r1 and bring zero new facts into the model; r2 = f(r1))

So the questions are

can we call r1 and r2 denormalized?

if yes, why? if not, why? (according to which rule? or according to which definition?)

NOTE:

To those who find the question(s) interesting enough to put in an answer, I kindly ask to provide either something quotable or to put it in a form of specific assumptions and conclusions (or in another words, if you are going to put in your opinion, please follow it with some reasoning).

EDIT
I accepted dportas answer. I'll try to add a bit to it here:
C.J.Date can makes a clear and strict distinction:

Much of design theory has to do with
  reducing redundancy; normalization
  reduces redundancy within relvars,
  orthogonality reduces it across
  relvars.

quoted from Database in depth: relational theory for practitioners

and on the next page

just as a failure to normalize all the
  way implies redundancy and can lead to
  certain anomalies, so too can a
  failure to adhere to orthogonality.


问:
CSS: keep image aspect ratio as viewport width decreases
At this page, there are 3 "doorway" graphics:

```<code><div class="textwidget">
    <div class="one-third first">
        <div id="doorway1" class="doorway">
            <h3>The Best Core Exercise Ever</h3>
            <div class="doorway-action">
                <a href="http://vmpersonal.com/product/core-strength-level-1/"><img src="http://vmpersonal.com/wp-content/themes/vmpersonal/images/doorway-action.png" alt="Watch Video Now" title="Watch Video Now" /> Watch Video Now</a>
            </div>
        </div>
    </div>
    <div class="one-third">
        <div id="doorway2" class="doorway">
            <h3>Core Strength Level 1 Program</h3>
            <div class="doorway-action">
                <a href="http://vmpersonal.com/product/core-strength-level-1/"><img src="http://vmpersonal.com/wp-content/themes/vmpersonal/images/doorway-action.png" alt="Watch Video Now" title="Watch Video Now" /> Watch Video Now</a>
            </div>
        </div>
    </div>
    <div class="one-third">
        <div id="doorway3" class="doorway">
            <h3>Cardio Program</h3>
            <div class="doorway-action">
                <a href="http://vmpersonal.com/product/cardio-fitness-level-1/"><img src="http://vmpersonal.com/wp-content/themes/vmpersonal/images/doorway-action.png" alt="Watch Video Now" title="Watch Video Now" /> Watch Video Now</a>
            </div>
        </div>
    </div>
</div>
</code>```

I'd like to make the graphics and the divs that contain them responsive.

They are contained in div.one-third containers.

The images are 409px x 292px, meaning the height is 71.39364303% of the width.

I thought if I used CSS:

```<code>#doorway1 {background-image: url('images/doorway1.png'); height: 71.39364303%;}
#doorway2 {background-image: url('images/doorway2.png'); height: 71.39364303%;}
#doorway3 {background-image: url('images/doorway3.png'); height: 71.39364303%;}
</code>```

they would scale down with the div.one-third as the viewport decreased in width, but they don't, the images are cut off.

How can I keep the images aspect ration consistent as the viewport width decreases?

Help appreciated.

Update: AJ Funk has helped me make the background images scale down, but how do I make the divs that contain them scale down proportionally too?

答:
You should combine the background-size: contain with a padding-bottom CSS trick to maintain aspect ratio. This could work as follows. Note that the main ideas are the background-size: contain and padding-bottom: 71.39364303% on .doorway elements, in combination with height: 0. The rest is minimal styling to illustrate the point.

It should be straightforward to apply this on your linked test page.

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.textwidget {
  width: 100%:
  font-size: 0; /* to prevent space between inline-block doorways */
}

.one-third {
  display: inline-block;
  vertical-align: top;
  box-sizing: border-box;
  width: 30%;
  padding: 20px;
}

.doorway {
  box-sizing: border-box;
  width: 100%;
  height: 0;
  padding-bottom: 71.39364303%;
  background-image: url('https://placehold.it/409x292');
  background-size: contain;
  border: 1px solid #000;
  font-size: 1rem; /* reset font-size */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="textwidget">
  <div class="one-third">
    <div id="doorway1" class="doorway">
      <h3>The Best Core Exercise Ever</h3>
      <div class="doorway-action">
        Watch Video Now
      </div>
    </div>
  </div>
  <div class="one-third">
    <div id="doorway2" class="doorway">
      <h3>Core Strength Level 1 Program</h3>
      <div class="doorway-action">
        Watch Video Now
      </div>
    </div>
  </div>
  <div class="one-third">
    <div id="doorway3" class="doorway">
      <h3>Cardio Program</h3>
      <div class="doorway-action">
        Watch Video Now
      </div>
    </div>
  </div>
</div></code>```

Body:
At this page, there are 3 "doorway" graphics:

The Best Core Exercise Ever

                 Watch Video Now

Core Strength Level 1 Program

                 Watch Video Now

Cardio Program

                 Watch Video Now

I'd like to make the graphics and the divs that contain them responsive.

They are contained in div.one-third containers.

The images are 409px x 292px, meaning the height is 71.39364303% of the width.

I thought if I used CSS:

#doorway1 {background-image: url('images/doorway1.png'); height: 71.39364303%;}
#doorway2 {background-image: url('images/doorway2.png'); height: 71.39364303%;}
#doorway3 {background-image: url('images/doorway3.png'); height: 71.39364303%;}

they would scale down with the div.one-third as the viewport decreased in width, but they don't, the images are cut off.

How can I keep the images aspect ration consistent as the viewport width decreases?

Help appreciated.

Update: AJ Funk has helped me make the background images scale down, but how do I make the divs that contain them scale down proportionally too?

Body:
You should combine the background-size: contain with a padding-bottom CSS trick to maintain aspect ratio. This could work as follows. Note that the main ideas are the background-size: contain and padding-bottom: 71.39364303% on .doorway elements, in combination with height: 0. The rest is minimal styling to illustrate the point.

It should be straightforward to apply this on your linked test page.

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.textwidget {
  width: 100%:
  font-size: 0; /* to prevent space between inline-block doorways */
}

.one-third {
  display: inline-block;
  vertical-align: top;
  box-sizing: border-box;
  width: 30%;
  padding: 20px;
}

.doorway {
  box-sizing: border-box;
  width: 100%;
  height: 0;
  padding-bottom: 71.39364303%;
  background-image: url('https://placehold.it/409x292');
  background-size: contain;
  border: 1px solid #000;
  font-size: 1rem; /* reset font-size */
}

<div class="textwidget">
  <div class="one-third">
    <div id="doorway1" class="doorway">
      <h3>The Best Core Exercise Ever</h3>
      <div class="doorway-action">
        <a href="#">Watch Video Now</a>
      </div>
    </div>
  </div>
  <div class="one-third">
    <div id="doorway2" class="doorway">
      <h3>Core Strength Level 1 Program</h3>
      <div class="doorway-action">
        <a href="#">Watch Video Now</a>
      </div>
    </div>
  </div>
  <div class="one-third">
    <div id="doorway3" class="doorway">
      <h3>Cardio Program</h3>
      <div class="doorway-action">
        <a href="#">Watch Video Now</a>
      </div>
    </div>
  </div>
</div>


问:
How do I return focus to an element when the entire page changes?
I have a complicated setup. My application is driven by a set of "rules" which dictate what the user interface is. The UI is rendered by looping through the rules and creating the individual dropdowns. Initially, everything renders properly. However, once a user makes a change to the UI, other rules may be affected. In my application, an api call is made, which then returns a modified set of rules. In the attached plunker, I've simplified things such that only the new set of rules is applied, which causes the page to re-render. The problem is that my users would like to be able to tab between all of the entries on the page and make changes. However, once the page is re-rendered, the currently selected page element is now gone nothing has the focus. I've tried to put the focus back on the proper element by tracking a common Id, but to no avail.

Using either of these doesn't seem to work.

var el = document.getElementById(focusId);
el.focus();
angular.element(el).focus();

I've also tried using the autofocus attribute on the dropdown that I want to have focus, but that didn't work either. I'm using angularjs 1.2. Any ideas are appreciated.

http://plnkr.co/edit/ND9PKqULIOlixWR4XChN?p=preview

答:
Problem here is, you are trying to focus the element before the blur event completes. So you need to execute the focus code after blur event. Async execution of your focus code would solve the problem. You can use either setTimeout or $timeout.

```<code>setTimeout(function(){
    angular.element('#'+focusId).focus();

    /* //or
    var el = document.getElementById(focusId);
    el.focus();
    */

});
</code>```

or

```<code>$timeout(function(){
    angular.element('#'+focusId).focus();

    /* //or
    var el = document.getElementById(focusId);
    el.focus();
    */

});
</code>```

dont forgot to inject $timeout to your controller if you are using second code. Hope this helps :)

Body:
Problem here is, you are trying to focus the element before the blur event completes. So you need to execute the focus code after blur event. Async execution of your focus code would solve the problem. You can use either setTimeout or $timeout.

setTimeout(function(){
    angular.element('#'+focusId).focus();

    /* //or
    var el = document.getElementById(focusId);
    el.focus();
    */

});

or

$timeout(function(){
    angular.element('#'+focusId).focus();

    /* //or
    var el = document.getElementById(focusId);
    el.focus();
    */

});

dont forgot to inject $timeout to your controller if you are using second code. Hope this helps :)


问:
flip animation is not working in chrome on mac OS X
I have a dashboard in that I am using CSS3 flip animations,the flip animations are working fine in windows but when comes to chrome on Mac OS X the flip animation is flickering when I am hovering on that DIV.Please provide me some fix.

Thanks.

CSS:

Here the problem is only with 'back face' when I am hovering on that div it is flickering.

```<code>#f1_container {
  position: relative;
  width: 100%;
  z-index: 1;
  margin-bottom: 20px;
  display: inline-block;
}
#f1_container {
  -webkit-perspective: 1000;
  -moz-perspective: 1000;
  -ms-perspective: 1000;
  -o-perspective: 1000;
  perspective: 1000;
}
#f1_card {
  width: 100%;
  height: 100%;
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  -ms-transform-style: preserve-3d;
  -o-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-transition: 1.5s ease-in-out;
  -moz-transition: 1.5s ease-in-out;
  -ms-transition: 1.5s ease-in-out;
  -o-transition: 1.5s ease-in-out;
  transition: 1.5s ease-in-out;
  background-color: white;
}
#f1_container:hover #f1_card {
  -webkit-transform: rotateY(180deg);
  -moz-transform: rotateY(180deg);
  -ms-transform: rotateY(180deg);
  -o-transform: rotateY(180deg);
  transform: rotateY(180deg);
}
.face {
  position: relative;
  width: 100%;
  height: 100%;
  -moz-transform-style: preserve-3d;
  -moz-backface-visibility: hidden;
  -webkit-transform-style: preserve-3d;
  -webkit-backface-visibility: hidden;
  top: 0;
}
.face.back {
  display: block;
  -webkit-transform: rotateY(-180deg);
  -moz-transform: rotateY(-180deg);
  -ms-transform: rotateY(-180deg);
  -o-transform: rotateY(-180deg);
  transform: rotateY(-180deg);
  box-sizing: border-box;
  color: white;
  text-align: center;
  position: absolute;
  -moz-transform-style: preserve-3d;
  -moz-backface-visibility: hidden;
  -webkit-transform-style: preserve-3d;
  -webkit-backface-visibility: hidden;
  -moz-transform: rotateY(-180deg);
  -webkit-transform: rotateY(-180deg);
}
.no-flick{
  -webkit-transform:translate3d(0,0,0);
  -moz-transform:translate3d(0,0,0);
  -ms-transform:translate3d(0,0,0);
  -o-transform:translate3d(0,0,0);
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  -ms-backface-visibility: hidden;
  -o-backface-visibility: hidden;
  backface-visibility: hidden;
}
</code>```

答:
I experienced the same issue using Chrome 57 on OSX. Upon flipping the card, the back would show briefly and then disappear to white.

My solution was to set background-color: white; on the front and back instead of the flip container. Not 100% sure why the background color is an issue but it flips correctly now with no flicker! :)

Body:
I have a dashboard in that I am using CSS3 flip animations,the flip animations are working fine in windows but when comes to chrome on Mac OS X the flip animation is flickering when I am hovering on that DIV.Please provide me some fix.

Thanks.

CSS:

Here the problem is only with 'back face' when I am hovering on that div it is flickering.

#f1_container {
  position: relative;
  width: 100%;
  z-index: 1;
  margin-bottom: 20px;
  display: inline-block;
}
#f1_container {
  -webkit-perspective: 1000;
  -moz-perspective: 1000;
  -ms-perspective: 1000;
  -o-perspective: 1000;
  perspective: 1000;
}
#f1_card {
  width: 100%;
  height: 100%;
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  -ms-transform-style: preserve-3d;
  -o-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-transition: 1.5s ease-in-out;
  -moz-transition: 1.5s ease-in-out;
  -ms-transition: 1.5s ease-in-out;
  -o-transition: 1.5s ease-in-out;
  transition: 1.5s ease-in-out;
  background-color: white;
}
#f1_container:hover #f1_card {
  -webkit-transform: rotateY(180deg);
  -moz-transform: rotateY(180deg);
  -ms-transform: rotateY(180deg);
  -o-transform: rotateY(180deg);
  transform: rotateY(180deg);
}
.face {
  position: relative;
  width: 100%;
  height: 100%;
  -moz-transform-style: preserve-3d;
  -moz-backface-visibility: hidden;
  -webkit-transform-style: preserve-3d;
  -webkit-backface-visibility: hidden;
  top: 0;
}
.face.back {
  display: block;
  -webkit-transform: rotateY(-180deg);
  -moz-transform: rotateY(-180deg);
  -ms-transform: rotateY(-180deg);
  -o-transform: rotateY(-180deg);
  transform: rotateY(-180deg);
  box-sizing: border-box;
  color: white;
  text-align: center;
  position: absolute;
  -moz-transform-style: preserve-3d;
  -moz-backface-visibility: hidden;
  -webkit-transform-style: preserve-3d;
  -webkit-backface-visibility: hidden;
  -moz-transform: rotateY(-180deg);
  -webkit-transform: rotateY(-180deg);
}
.no-flick{
  -webkit-transform:translate3d(0,0,0);
  -moz-transform:translate3d(0,0,0);
  -ms-transform:translate3d(0,0,0);
  -o-transform:translate3d(0,0,0);
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  -ms-backface-visibility: hidden;
  -o-backface-visibility: hidden;
  backface-visibility: hidden;
}