问:
How to fix overlapping objects
I have recently started understanding on how to code in Android Studio and want to set up basic coding. I created 2 number objects and 1 button, 1 plain text object.
Without writing any piece of code, when I click on Run App button on Android Studio and select any Emulator, all the objects stack up on each other. Is there a simple way to fix this?

Following is the text in activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication70.MainActivity">

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Result"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="223dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="60dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberSigned"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="134dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="100dp"
        tools:layout_editor_absoluteY="319dp" />

</android.support.constraint.ConstraintLayout>
</code>```

答: You're using a constraint layout as your main layout, which means that elements within the layout are going to be placed according to constraints, please check the Android Documentation for using constraint layouts.</p>

Title: How to fix overlapping objects

Body:
I have recently started understanding on how to code in Android Studio and want to set up basic coding. I created 2 number objects and 1 button, 1 plain text object.
Without writing any piece of code, when I click on Run App button on Android Studio and select any Emulator, all the objects stack up on each other. Is there a simple way to fix this?

Following is the text in activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication70.MainActivity">

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Result"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="223dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="60dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberSigned"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="134dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="100dp"
        tools:layout_editor_absoluteY="319dp" />

</android.support.constraint.ConstraintLayout>


来源: stackexchange

问:
Prop Shortcut in Visual Studio
I have been using the shortcut for creating properties for a few weeks now (Prop + tab + tab). Recently intellisense has changed it so when I type in Prop it auto corrects to "Protected" key word. If I type Prop, then backspace out of Protected, then Prop + Tab + Tab works again. How do I tell intellisense not to use "Protected" any more by default? </p>

答:
Toos >> Export Import settings >> Reset all settings.

Sometimes the IDE behavior gets altered due to installation of some extension or some other way. Resetting should solve the issue.

ContentLicense: CC BY-SA 3.0

Title: Prop Shortcut in Visual Studio


问:
Using Angular2 ngFor index
I have this code:

```<code><div class="row list-group">
  <div *ngFor="let product of products" >
    <app-product [product]="product"></app-product>
  </div>
</div>
</code>```

I was wondering is there any way i can get products from array in buckets? Something like this:

```<code><div class="list-group">
  <div *ngFor="products; index+3" >
    <div class="row">
      <app-product [product]="products[index]"></app-product>
      <app-product [product]="products[index+1]"></app-product>
      <app-product [product]="products[index+2]"></app-product>
    </div>
  </div>
</div>
</code>```

That way I could have all elements i need in a row

UPD

Thanks to Teddy Sterne I ended up with this solution:

```<code><div class="list-group">
  <div *ngFor="let product of products;let i = index">
    <div class="row" *ngIf="i%3===0">
      <app-product [product]="products[i]"></app-product>
      <div *ngIf="products[i + 1]">
        <app-product [product]="products[i + 1]"></app-product>
      </div>
      <div *ngIf="products[i + 2]">
        <app-product [product]="products[i + 2]"></app-product>
      </div>
    </div>
  </div>
</div>
</code>```

答:
For index try this:

Controller File add function :

```<code>chunks(array, size) {
  let results = [];
  while (array.length) {
    results.push(array.splice(0, size));
  }
  return results;
};
</code>```

In you view file :

```<code><div *ngFor="let chunkProduct of chunks(products,3);" >
  <div class="row">
      <app-product *ngFor="let product of chunkProduct" [product]="product"></app-product>
  </div>
</div>
</code>```

This will work for all number , not only %3 numbers.

@Teddy Sterne's solution will work incase of the number is %3
If we have 8 products it will show only 6 last 2 will be lost , in this it will also be shown.

And it will create extra blank div tags for not %3 index , if you inspect the element and check , because it will loop through each product and div will get repeated no matter if its index %3 or not.

Title: Using Angular2 ngFor index

Body:
I have this code:

    <app-product [product]="product"></app-product>

I was wondering is there any way i can get products from array in buckets? Something like this:

      <app-product [product]="products[index]"></app-product>
      <app-product [product]="products[index+1]"></app-product>
      <app-product [product]="products[index+2]"></app-product>

That way I could have all elements i need in a row

UPD

Thanks to Teddy Sterne I ended up with this solution:

      <app-product [product]="products[i]"></app-product>

        <app-product [product]="products[i + 1]"></app-product>

        <app-product [product]="products[i + 2]"></app-product>

Body:
For index try this:

Controller File add function :

chunks(array, size) {
  let results = [];
  while (array.length) {
    results.push(array.splice(0, size));
  }
  return results;
};

In you view file :

<div *ngFor="let chunkProduct of chunks(products,3);" >
  <div class="row">
      <app-product *ngFor="let product of chunkProduct" [product]="product"></app-product>
  </div>
</div>

This will work for all number , not only %3 numbers.

@Teddy Sterne's solution will work incase of the number is %3
If we have 8 products it will show only 6 last 2 will be lost , in this it will also be shown.

And it will create extra blank div tags for not %3 index , if you inspect the element and check , because it will loop through each product and div will get repeated no matter if its index %3 or not.


问:
Why is this jQueryUI dialog not working in IE9?
The following code produces the expected jQueryUI modal popup dialog in Firefox, Chrome, and Opera. However, it fails in Internet Explorer 9:

```<code><html><head>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>

<script type="text/javascript">
$(function() {
    $( "#AddUser" ).dialog({
        autoOpen: false, modal: true, height: 'auto', width: 400,
        buttons: {
            "Add": function() {
                alert("Add one!");
            }
        },
        close: function() {
            allFields.val( "" ).removeClass( "ui-state-error" );
        }
    });

    $( "#AddUserButton" ).button().click(function(event) {
        event.preventDefault();
        $( "#AddUser" ).dialog( "open" );
    });

});
</script>

</head><body>

<div id="AddUser" title="Add User">Popup content here</div>
<input type="submit" id="AddUserButton" />

</body></html>
</code>```

In IE 9 the #AddUser div is not a jQueryUI dialog. Is there anything that I am missing?

EDIT: Code updated to closer to production code.

Thanks.

答:
I had the same issue with dialog and adding following in css file did the job for me.</p>

```<code>.ui-widget-overlay
{
        z-index: 0 !important;
}
</code>```

Body:
The following code produces the expected jQueryUI modal popup dialog in Firefox, Chrome, and Opera. However, it fails in Internet Explorer 9:

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" />

Popup content here

<input type="submit" id="AddUserButton" />

In IE 9 the #AddUser div is not a jQueryUI dialog. Is there anything that I am missing?

EDIT: Code updated to closer to production code.

Thanks.

Body:
I had the same issue with dialog and adding following in css file did the job for me.

.ui-widget-overlay
{
        z-index: 0 !important;
}


问:
end argument to print leads to different behavior with time.sleep
I tried to write this script that just prints number after each other on the same line with a one second delay, but it does not work.

Ex this works:

```<code>from time import sleep

for n in range(1, 11):
    print(n)
    sleep(1)
</code>```

But this does not, the program just freezes:

```<code>from time import sleep

for n in range(1, 11):
    print(n, end="")
    sleep(1)
</code>```

Can anyone explain why this is?

答:
The program does not freeze, you just need to flush the stream by passing flush=True:

```<code>print(n, end="", flush=True)
</code>```

sys.stdout, the stream that print uses by default, is line-buffered (when in interactive mode), as stated in the documentation:

When interactive, standard streams are line-buffered

This means that when the default string used for end (\n) is encountered, a call to flush will be made. Using other strings (i.e '') don't trigger flushing so you'll have to force it by using flush=True.

Body:
I tried to write this script that just prints number after each other on the same line with a one second delay, but it does not work.

Ex this works:

from time import sleep

for n in range(1, 11):
    print(n)
    sleep(1)

But this does not, the program just freezes:

from time import sleep

for n in range(1, 11):
    print(n, end="")
    sleep(1)

Can anyone explain why this is?

Body:
The program does not freeze, you just need to flush the stream by passing flush=True:

print(n, end="", flush=True)

sys.stdout, the stream that print uses by default, is line-buffered (when in interactive mode), as stated in the documentation:

When interactive, standard streams are line-buffered

This means that when the default string used for end (\n) is encountered, a call to flush will be made. Using other strings (i.e '') don't trigger flushing so you'll have to force it by using flush=True.


问:
HTML picture in div won't fill out body completely
I want to use a picture (jpg) as a background for my page.

This is how I tried to tackle the problem :
Create the body, inside the body put a div with the id backgroundWallpaper.
Inside the div i put the image.
The problem is though that it's completely filled out to the site (horizontal) and also to the top but at the bottom there is a small gap between the picture and the browser. I changed the body background to crimson red to demonstrate you the gap. I use the latest version of safari as my browser. This is my code :
index.html

```<code><!DOCTYPE html>
 <html>
  <head>
   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">
  </head>
  <body>
   <div id="backgroundWallpaper">
    <img src=".../img/1.jpg" alt="image could not be loaded">
   </div>
  </body>
 </html>
</code>```

This is my css file

```<code>body {
 background: crimson;
 margin: 0;
 padding: 0;
}

#backgroundWallpaper img {
 max-width: 100%;
}
</code>```

答:
You can use background to fit correctly as its explained here

body {
 background: crimson;
 margin: 0;
 padding: 0;
 background: url(http://placehold.it/350x150) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}```

Body:
I want to use a picture (jpg) as a background for my page.

This is how I tried to tackle the problem :
Create the body, inside the body put a div with the id backgroundWallpaper.
Inside the div i put the image.
The problem is though that it's completely filled out to the site (horizontal) and also to the top but at the bottom there is a small gap between the picture and the browser. I changed the body background to crimson red to demonstrate you the gap. I use the latest version of safari as my browser. This is my code :
index.html

<!DOCTYPE html>

   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">

This is my css file

body {
 background: crimson;
 margin: 0;
 padding: 0;
}

#backgroundWallpaper img {
 max-width: 100%;
}


问:
Sphinx: Putting a code segment at the first line of an unordered list item
I'm using Sphinx to manage my project's documentation.

I have an unordered list, and I want the first line of every item to be a code segment. (Not inline, a paragraph.)

How can I do that?

答:
Looking at my own documentation I found a similar scenario, however I can't guarantee that it will work with the documentation as the first text in the list:

```<code>#.  **Defining the Model Class**

    All models must inherit from |LrbBaseModel| either directly or
    indirectly and have the |LrbModelInit| decorator above their
    constructor (a.k.a. ``__init__``)::

        class foo(LrbBaseModel):
            @LrbModelInit()
            def __init__(self):
                ...
</code>```

This produces:

I think you can get away with a code block without pre-amble text like the following:

```<code>#.  ::
        def fooDeFaFa():
            pass
</code>```

Notice that my code block is indented twice.  The :: indicates the empty textual paragraph block, and then my code is a child of this :: syntax via indenting a second time.

Alternatively, this may work:

```<code>#.
    ::
        def fooDeFaFa():
            pass
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Looking at my own documentation I found a similar scenario, however I can't guarantee that it will work with the documentation as the first text in the list:

#.  **Defining the Model Class**

    All models must inherit from |LrbBaseModel| either directly or
    indirectly and have the |LrbModelInit| decorator above their
    constructor (a.k.a. ``__init__``)::

        class foo(LrbBaseModel):
            @LrbModelInit()
            def __init__(self):
                ...

This produces:

I think you can get away with a code block without pre-amble text like the following:

#.  ::
        def fooDeFaFa():
            pass

Notice that my code block is indented twice.  The :: indicates the empty textual paragraph block, and then my code is a child of this :: syntax via indenting a second time.

Alternatively, this may work:

#.
    ::
        def fooDeFaFa():
            pass


问:
Paramiko "Unknown Server"
I'm trying to get started with the Paramiko library, but the library is throwing an exception as soon as I try to connect with the following simple program:

```<code>import paramiko
ssh = paramiko.SSHClient()
ssh.connect('127.0.0.1', username='boatzart', password='mypassword')
</code>```

The error I get is:

Traceback (most recent call last):
File "test.py", line 6, in <module>
ssh.connect('127.0.0.1')
File "build/bdist.macosx-10.7-intel/egg/paramiko/client.py", line 316, in connect
File "build/bdist.macosx-10.7-intel/egg/paramiko/client.py", line 85, in missing_host_key
paramiko.SSHException: Unknown server 127.0.0.1
```

This occurs no matter which server I try.

答:
The correct way is either:

Call the HostKeys.add on the instance returned by SSHClient.get_host_keys before calling the connect, passing it the trusted key.

```<code>from base64 import decodebytes
# ...

keydata = b"""AAAAB3NzaC1yc2EAAAADAQAB..."""
key = paramiko.RSAKey(data=decodebytes(keydata))
client.get_host_keys().add('example.com', 'ssh-rsa', key)
</code>```

Depending on the actual key type, you might need to use ECDSAKey or Ed25519Key instead of RSAKey.

To see how to obtain the key for use in the code, see my answer to:

Verify host key with pysftp.

If you know a fingerprint only, see:

Python - pysftp / paramiko - Verify host key using its fingerprint

Or load the already cached hostkey (e.g. by the OpenSSH command-line ssh) using client.load_system_host_keys().

Or you can at least cache the hostkey from the first attempt to make sure it does not change in the future.

For that use SSHClient.load_host_keys before connect. It makes Paramiko automatically add the new host key to the file (when combined with AutoAddPolicy).

Title: Paramiko "Unknown Server"

Body:
I'm trying to get started with the Paramiko library, but the library is throwing an exception as soon as I try to connect with the following simple program:

import paramiko
ssh = paramiko.SSHClient()
ssh.connect('127.0.0.1', username='boatzart', password='mypassword')

The error I get is:

Traceback (most recent call last):
File "test.py", line 6, in <module>
ssh.connect('127.0.0.1')
File "build/bdist.macosx-10.7-intel/egg/paramiko/client.py", line 316, in connect
File "build/bdist.macosx-10.7-intel/egg/paramiko/client.py", line 85, in missing_host_key
paramiko.SSHException: Unknown server 127.0.0.1

This occurs no matter which server I try.

Body:
The correct way is either:

Call the HostKeys.add on the instance returned by SSHClient.get_host_keys before calling the connect, passing it the trusted key.

from base64 import decodebytes
# ...

keydata = b"""AAAAB3NzaC1yc2EAAAADAQAB..."""
key = paramiko.RSAKey(data=decodebytes(keydata))
client.get_host_keys().add('example.com', 'ssh-rsa', key)

Depending on the actual key type, you might need to use ECDSAKey or Ed25519Key instead of RSAKey.

To see how to obtain the key for use in the code, see my answer to:

Verify host key with pysftp.

If you know a fingerprint only, see:

Python - pysftp / paramiko - Verify host key using its fingerprint

Or load the already cached hostkey (e.g. by the OpenSSH command-line ssh) using client.load_system_host_keys().

Or you can at least cache the hostkey from the first attempt to make sure it does not change in the future.

For that use SSHClient.load_host_keys before connect. It makes Paramiko automatically add the new host key to the file (when combined with AutoAddPolicy).

ContentLicense: CC BY-SA 4.0


问:
Performant way to convert adjacency list to links for undirected graph
I have an adjacency list like below:

```<code>const list = [
 [1, 6, 8],
 [0, 4, 6, 9],
 [4, 6],
 [4, 5, 8],
 // ...
];
</code>```

I need to create a set of links for an undirected graph without duplicates (example bellow).
Such links as [0,1] and [1,0] are considered duplicates.

```<code>const links = [
 [ 0, 1 ], // duplicates
 [ 0, 6 ],
 [ 0, 8 ],
 [ 1, 0 ], // duplicates
 [ 1, 4 ],
 // ...
]
</code>```

Right now I do it this way:

```<code>const links = new Set;
const skip = [];

list.forEach( (v, i) => {
    v.forEach( j => {
        if (skip.indexOf(j) === -1) {
            links.add([i, j]);
        }
    })
    skip.push(i);
})
</code>```

I am wondering if there is a better pattern to solve this kind of task on massive arrays.

答:
You could take a stringed array as value for the for the set, because an array with only sorted value is checking with strict mode in the set.

A primitive data type, like string works best.

var list = [[1, 6, 8], [0, 4, 6, 9], [4, 6], [4, 5, 8]],
    links = new Set;

list.forEach((v, i) => v.forEach(j => links.add([Math.min(i, j), Math.max(i, j)].join())));

console.log([...links]);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an adjacency list like below:

const list = [
 [1, 6, 8],
 [0, 4, 6, 9],
 [4, 6],
 [4, 5, 8],
 // ...
];

I need to create a set of links for an undirected graph without duplicates (example bellow).
Such links as [0,1] and [1,0] are considered duplicates.

const links = [
 [ 0, 1 ], // duplicates
 [ 0, 6 ],
 [ 0, 8 ],
 [ 1, 0 ], // duplicates
 [ 1, 4 ],
 // ...
]

Right now I do it this way:

const links = new Set;
const skip = [];

list.forEach( (v, i) => {
    v.forEach( j => {
        if (skip.indexOf(j) === -1) {
            links.add([i, j]);
        }
    })
    skip.push(i);
})

I am wondering if there is a better pattern to solve this kind of task on massive arrays.

Body:
You could take a stringed array as value for the for the set, because an array with only sorted value is checking with strict mode in the set.

A primitive data type, like string works best.

var list = [[1, 6, 8], [0, 4, 6, 9], [4, 6], [4, 5, 8]],
    links = new Set;

list.forEach((v, i) => v.forEach(j => links.add([Math.min(i, j), Math.max(i, j)].join())));

console.log([...links]);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
My viewDidAppear not called in view controller
It turns out that what I want to do is that when I come from a 3d shortcut, forcing the UITabBarController to choose an index, if I do this in the tab bar viewDidAppear() the problem is that the viewDidAppear() of my main UIViewController Embedded is not called, if I click again on the tab bar item then already if it is called. With the rest of the drivers does not happen, I understand why it is not the one that is first in the list of items in the UITabBarController.

Tab bar controller: (Here it comes)

```<code>override func viewDidAppear(_ animated: Bool) {
    if goTasks {
        self.selectedIndex = 0
    } else if goTodo {
        self.selectedIndex = 2
    } else if goProjects {
        self.selectedIndex = 3
    } else if goSearch {
        self.selectedIndex = 0
    }

}
</code>```

My first UIViewController:
(Not called this method)

```<code>override func viewDidAppear(_ animated: Bool) {
    print("Entry")
}
</code>```

Is the problem override the methods? Any solution?

答:
```<code>override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    if goTasks {
        self.selectedIndex = 0
    } else if goTodo {
        self.selectedIndex = 2
    } else if goProjects {
        self.selectedIndex = 3
    } else if goSearch {
        self.selectedIndex = 0
    }
}
</code>```

You need to add super.viewDidAppear(animated), hope its word now

Body:
It turns out that what I want to do is that when I come from a 3d shortcut, forcing the UITabBarController to choose an index, if I do this in the tab bar viewDidAppear() the problem is that the viewDidAppear() of my main UIViewController Embedded is not called, if I click again on the tab bar item then already if it is called. With the rest of the drivers does not happen, I understand why it is not the one that is first in the list of items in the UITabBarController.

Tab bar controller: (Here it comes)

override func viewDidAppear(_ animated: Bool) {
    if goTasks {
        self.selectedIndex = 0
    } else if goTodo {
        self.selectedIndex = 2
    } else if goProjects {
        self.selectedIndex = 3
    } else if goSearch {
        self.selectedIndex = 0
    }

}

My first UIViewController:
(Not called this method)

override func viewDidAppear(_ animated: Bool) {
    print("Entry")
}

Is the problem override the methods? Any solution?

Body:
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    if goTasks {
        self.selectedIndex = 0
    } else if goTodo {
        self.selectedIndex = 2
    } else if goProjects {
        self.selectedIndex = 3
    } else if goSearch {
        self.selectedIndex = 0
    }
}

You need to add super.viewDidAppear(animated), hope its word now


问:
Excel SUMIFS on single criteria with zero and non-zero values
I'm trying to figure out a formula for SUMIFS where a multi-criteria range may or may not contain zero. Take the following table for example.

```<code>|Title    |Age|Color
|---------|---|------
|Odyssey  |5  |Brown
|Tempest  |2  |Yellow
|Iliad    |3  |
|Macbeth  |9  |Brown
</code>```

My goal is to get a SUMIFS where Color is 'Brown' or blank. What I've tried is

```<code>=SUMIFS(B2:B5,C2:C5,{"Brown",""})
</code>```

However, this returns a value of '14' which is a sum of Brown values only and does not sum the '3' from the blank color row. If I switch it up and use

```<code>=SUMIFS(B2:B5,C2:C5,{"","Brown"})
</code>```

it returns '3' which is just the blank value, and not Brown. It seems to only consider the first value in the array.

What am I doing wrong? What's the correct formula for taking an array where the value can be NULL or a specified value?

PS I've also tried ISBLANK, ISNULL, NULL, etc.

答:
You can wrap it in a sumproduct so it gives the sum of the sums

```<code>=SUMPRODUCT(SUMIFS(B2:B5,C2:C5,{"Brown",""}))
</code>```

otherwise it doesn't recognise the values in curly brackets as an array and just looks at whichever you put first.

Body:
I'm trying to figure out a formula for SUMIFS where a multi-criteria range may or may not contain zero. Take the following table for example.

|Title    |Age|Color
|---------|---|------
|Odyssey  |5  |Brown
|Tempest  |2  |Yellow
|Iliad    |3  |
|Macbeth  |9  |Brown

My goal is to get a SUMIFS where Color is 'Brown' or blank. What I've tried is

=SUMIFS(B2:B5,C2:C5,{"Brown",""})

However, this returns a value of '14' which is a sum of Brown values only and does not sum the '3' from the blank color row. If I switch it up and use

=SUMIFS(B2:B5,C2:C5,{"","Brown"})

it returns '3' which is just the blank value, and not Brown. It seems to only consider the first value in the array.

What am I doing wrong? What's the correct formula for taking an array where the value can be NULL or a specified value?

PS I've also tried ISBLANK, ISNULL, NULL, etc.

Body:
You can wrap it in a sumproduct so it gives the sum of the sums

=SUMPRODUCT(SUMIFS(B2:B5,C2:C5,{"Brown",""}))

otherwise it doesn't recognise the values in curly brackets as an array and just looks at whichever you put first.


问:
WhereIn in eloquent orm
I have two arrays

```<code>temp[]
time[]
</code>```

now for example if i have data in my array something like this

```<code>    temp   time
[0]  80     45
[1]  70     50
[2]  85     65
[3]  90     30
</code>```

i want to query data in terms of these two array params
like (select * from MyTable where (temperature = 80 and time = 45 ))for the next  (select * from MyTable where (temperature = 70 and time = 50 )) and so on

I am doing something like this

```<code> $mix=MyTable::whereIN('temperature', $temp)
         ->whereIN('time', $time)->where('category',$cat)
         ->get();
</code>```

But the output it is qiving me is kind of a combination of these two params.not exactly from array 0 to onwards...

I hope i explained my question correctly..

i tried this..

```<code>    $result=Ergebnisse::where('name_id', $nam)->where('geometrie_id', $geo)->get();
    foreach ($result as $key => $res) {

$mix=Ergebnisse::where('temperatur', $res->temperatur)
         ->where('zeit', $res->zeit)->groupBy('katogorie_id')
         ->get();

}
</code>```

when i dd($mix) it shows only one result. but according to my db it should show more than one

答:
whereIn() will not work here. Do something like this:

```<code>$data = MyTable::where('category', $cat)
    ->where(function($q) use($array) {
        foreach ($array as $item) {
             $q->orWhere(function($q) use($item) {
                 $q->where('temperature', $item['temp'])
                   ->where('time', $item['time']);
            }
        }
    })->get();
</code>```

Title: WhereIn in eloquent orm

Body:
I have two arrays

temp[]
time[]

now for example if i have data in my array something like this

    temp   time
[0]  80     45
[1]  70     50
[2]  85     65
[3]  90     30

i want to query data in terms of these two array params
like (select * from MyTable where (temperature = 80 and time = 45 ))for the next  (select * from MyTable where (temperature = 70 and time = 50 )) and so on

I am doing something like this

 $mix=MyTable::whereIN('temperature', $temp)
         ->whereIN('time', $time)->where('category',$cat)
         ->get();

But the output it is qiving me is kind of a combination of these two params.not exactly from array 0 to onwards...

I hope i explained my question correctly..

i tried this..

    $result=Ergebnisse::where('name_id', $nam)->where('geometrie_id', $geo)->get();
    foreach ($result as $key => $res) {

$mix=Ergebnisse::where('temperatur', $res->temperatur)
         ->where('zeit', $res->zeit)->groupBy('katogorie_id')
         ->get();

}

when i dd($mix) it shows only one result. but according to my db it should show more than one

Body:
whereIn() will not work here. Do something like this:

$data = MyTable::where('category', $cat)
    ->where(function($q) use($array) {
        foreach ($array as $item) {
             $q->orWhere(function($q) use($item) {
                 $q->where('temperature', $item['temp'])
                   ->where('time', $item['time']);
            }
        }
    })->get();


问:
Regex for Twitter's Mentions
I'm having trouble with the "official" regex that parse twitter's mentions. (https://github.com/twitter/twitter-text/blob/master/java/src/com/twitter/Regex.java)

This is my code:

```<code>AT_SIGNS_CHARS = u"@\uFF20"
AT_SIGNS = "[" + AT_SIGNS_CHARS + "]"
mention_pattern = u"([^a-z0-9_!#$%&*" + AT_SIGNS_CHARS + "]|^|(?:^|[^a-z0-9_+~.-])RT:?)(" + AT_SIGNS + "+)([a-z0-9_]{1,20})(/[a-z][a-z0-9_\\-]{0,24})?"

patt = re.compile(mention_pattern)

pr = '@ciao bella'
print patt.findall(pr)
</code>```

Why does it print:

```<code>[('', '@', 'ciao', '')]
</code>```

instead of:

```<code>['@ciao']
</code>```

Thank you in advance

答:
If instead you use match and print group(0), which is the full match irrespective of the separate groups, you will see your desired result:

```<code>>>> patt.match(pr).group(0)
'@ciao'
</code>```

If you want to use findall to find multiple results, you can put an extra set of parenthesis around your pattern so that the complete match is the first element of each tuple in the returned list:

```<code>AT_SIGNS_CHARS = u"@\uFF20"
AT_SIGNS = "[" + AT_SIGNS_CHARS + "]"
mention_pattern = u"(([^a-z0-9_!#$%&*" + AT_SIGNS_CHARS + "]|^|(?:^|[^a-z0-9_+~.-])RT:?)(" + AT_SIGNS + "+)([a-z0-9_]{1,20})(/[a-z][a-z0-9_\\-]{0,24})?)"

patt = re.compile(mention_pattern)

pr = '@ciao bella :-), 123 @adeu guapa'

>>> print patt.findall(pr)

[('@ciao', '', '@', 'ciao', ''), (' @adeu', ' ', '@', 'adeu', '')]
</code>```

EDIT: To find mentions plus latin words

```<code>AT_SIGNS_CHARS = u"@\uFF20"
AT_SIGNS = "[" + AT_SIGNS_CHARS + "]"
mention_pattern = u"([^a-z0-9_!#$%&*" + AT_SIGNS_CHARS + "]|^|(?:^|[^a-z0-9_+~.-])RT:?)(" + AT_SIGNS + "+)([a-z0-9_]{1,20})(/[a-z][a-z0-9_\\-]{0,24})?"
latin = u'[a-zA-Z]+'
mention_or_latin = "(%s|%s)" % (mention_pattern, latin)
patt = re.compile(mention_or_latin)

pr = '@ciao bella, @adeu guapa'

>>> print patt.findall(pr)
[('@ciao', '', '@', 'ciao', ''), ('bella', '', '', '', ''), (' @adeu', ' ', '@', 'adeu', ''), ('guapa', '', '', '', '')]
</code>```

Title: Regex for Twitter's Mentions

Body:
I'm having trouble with the "official" regex that parse twitter's mentions. (https://github.com/twitter/twitter-text/blob/master/java/src/com/twitter/Regex.java)

This is my code:

AT_SIGNS_CHARS = u"@\uFF20"
AT_SIGNS = "[" + AT_SIGNS_CHARS + "]"
mention_pattern = u"([^a-z0-9_!#$%&*" + AT_SIGNS_CHARS + "]|^|(?:^|[^a-z0-9_+~.-])RT:?)(" + AT_SIGNS + "+)([a-z0-9_]{1,20})(/[a-z][a-z0-9_\\-]{0,24})?"

patt = re.compile(mention_pattern)

pr = '@ciao bella'
print patt.findall(pr)

Why does it print:

[('', '@', 'ciao', '')]

instead of:

['@ciao']

Thank you in advance

Body:
If instead you use match and print group(0), which is the full match irrespective of the separate groups, you will see your desired result:

>>> patt.match(pr).group(0)
'@ciao'

If you want to use findall to find multiple results, you can put an extra set of parenthesis around your pattern so that the complete match is the first element of each tuple in the returned list:

AT_SIGNS_CHARS = u"@\uFF20"
AT_SIGNS = "[" + AT_SIGNS_CHARS + "]"
mention_pattern = u"(([^a-z0-9_!#$%&*" + AT_SIGNS_CHARS + "]|^|(?:^|[^a-z0-9_+~.-])RT:?)(" + AT_SIGNS + "+)([a-z0-9_]{1,20})(/[a-z][a-z0-9_\\-]{0,24})?)"

patt = re.compile(mention_pattern)

pr = '@ciao bella :-), 123 @adeu guapa'

>>> print patt.findall(pr)

[('@ciao', '', '@', 'ciao', ''), (' @adeu', ' ', '@', 'adeu', '')]

EDIT: To find mentions plus latin words

AT_SIGNS_CHARS = u"@\uFF20"
AT_SIGNS = "[" + AT_SIGNS_CHARS + "]"
mention_pattern = u"([^a-z0-9_!#$%&*" + AT_SIGNS_CHARS + "]|^|(?:^|[^a-z0-9_+~.-])RT:?)(" + AT_SIGNS + "+)([a-z0-9_]{1,20})(/[a-z][a-z0-9_\\-]{0,24})?"
latin = u'[a-zA-Z]+'
mention_or_latin = "(%s|%s)" % (mention_pattern, latin)
patt = re.compile(mention_or_latin)

pr = '@ciao bella, @adeu guapa'

>>> print patt.findall(pr)
[('@ciao', '', '@', 'ciao', ''), ('bella', '', '', '', ''), (' @adeu', ' ', '@', 'adeu', ''), ('guapa', '', '', '', '')]


问:
AngularJs : Call controller function bound to 'this' from outside(eg. Browser console)
I have below code, now let's assume I want to call foo(val) function from somewhere outside, let's say browser console.

```<code>angular.module('app', []);
angular.module('app')
    .controller('MyController', MyController);

function MyController() {
    var self = this;
    self.foo = function(val) {
        console.log(val);
    };
    return self;
}
</code>```

Below code works only when foo() is bound to $scope.

```<code>angular.element(document.getElementById('MyController')).scope().foo('Hello');
</code>```

Is there any work around or I will be forced to use $scope for this ?

答:
Found a work around :

```<code>angular.module('app', []);
angular.module('app')
    .controller('MyController', MyController);

function MyController() {
    var self = this;
    self.foo = function(val) {
        console.log(val);
    };
    window.callFoo = function(val) {
        self.foo(val);
    }
    return self;
}
</code>```

Now I am able to call this window.callFoo() function from anywhere. Seems like it worked as we work with closures in JavaScript.
Still If someone finds a better approach. Please post it here.

Body:
I have below code, now let's assume I want to call foo(val) function from somewhere outside, let's say browser console.

angular.module('app', []);
angular.module('app')
    .controller('MyController', MyController);

function MyController() {
    var self = this;
    self.foo = function(val) {
        console.log(val);
    };
    return self;
}

Below code works only when foo() is bound to $scope.

angular.element(document.getElementById('MyController')).scope().foo('Hello');

Is there any work around or I will be forced to use $scope for this ?

Body:
Found a work around :

angular.module('app', []);
angular.module('app')
    .controller('MyController', MyController);

function MyController() {
    var self = this;
    self.foo = function(val) {
        console.log(val);
    };
    window.callFoo = function(val) {
        self.foo(val);
    }
    return self;
}

Now I am able to call this window.callFoo() function from anywhere. Seems like it worked as we work with closures in JavaScript.
Still If someone finds a better approach. Please post it here.


答:
Figured out what I was doing wrong:

Need to encapsulate the entire formula in a SUM() function.

```<code>=SUM(SUMIFS(B2:B5,C2:C5,{"Brown",""}))
</code>```

Title: Excel SUMIFS on single criteria with zero and non-zero values

Body:
Figured out what I was doing wrong:

Need to encapsulate the entire formula in a SUM() function.

=SUM(SUMIFS(B2:B5,C2:C5,{"Brown",""}))


问:
Where's the HXML docs?
I've looked all over the Haxe Flash Command-line compiler website but was unable to find any detailed documentation of the HXML files (scroll down to the "Changing SWF properties" section) which describe the compile.

Anybody know of a reference source?

Found HXML:

-swf MyApp.swf .... Compile to SWF

-main MyAppClass .... Entry-point Class (.AS file)

-swf-header 200:300:25:FFFFFF .... Width:Height:FPS:BackColor (of SWF)

Edit:  Scroll down for my answer with the complete list of commands.

答:
Have you tried:

```<code>haxe --help
</code>```

.hxml files are just a convenient way to pass commandline parameters as far as I know.

OwnerDisplayName: Jeremy Rudd

Title: Where's the HXML docs?

LastEditorDisplayName: Jeremy Rudd

Body:
Have you tried:

haxe --help

.hxml files are just a convenient way to pass commandline parameters as far as I know.


问:
Is it possible to pass an object into a graphQL mutation as variables?
Is it possible to pass an object into a graphQL mutation as variables?

```<code>let salesDate = {
    company_id: "abcd",
    source: "tally",
    data: {
        value: "02",
        date: "2016-17-01"
    }
};

const mutation = gql`
  mutation addData($data: Object){
    addData(data: $data){
     data
    }
  }
`;
</code>```

This is not working and I don't see any way to define an object as a parameter type.

答:
You have to define a GraphQL input type. Take a look at this cheat sheet.

So in your case you have to define a input on the server and use it in the mutation, something like:

...

`
input DataInput {
  value: Number!
  data: String!
}

...

addData(data: DataInput!): SalesDate

````
</div>
</div>
</p>

<p>and on the client side you can use it like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const mutation = gql
  mutation addData($data: DataInput!){
    addData(data: $data){
     data
    }
  }
;</code>```

Body:
Is it possible to pass an object into a graphQL mutation as variables?

let salesDate = {
    company_id: "abcd",
    source: "tally",
    data: {
        value: "02",
        date: "2016-17-01"
    }
};

const mutation = gql`
  mutation addData($data: Object){
    addData(data: $data){
     data
    }
  }
`;

This is not working and I don't see any way to define an object as a parameter type.

Body:
You have to define a GraphQL input type. Take a look at this cheat sheet.

So in your case you have to define a input on the server and use it in the mutation, something like:

...

`
input DataInput {
  value: Number!
  data: String!
}

...

addData(data: DataInput!): SalesDate

`

and on the client side you can use it like:

const mutation = gql
  mutation addData($data: DataInput!){
    addData(data: $data){
     data
    }
  }
;


问:
Force Laravel to log in a user using legacy authentication
I am trying to slowly integrate Laravel into a legacy PHP application. One of the tasks is to automatically register a Laravel user session when a user logs in to the old app. I am not trying to implement Laravel authentication, I really just want to piggyback off of existing functionality and force a specific user to be logged in without checking credentials.  What I have so far has been cobbled together from other people's hacks I have found around:

```<code>// Laravel authentication hook - Boostrap application
require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

// Start Laravel session
$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
// Associate server session with the authenticating user id
// I have also tried loading user model instance and then $app['auth']->login($user)
$app['auth']->loginUsingId($user_id);

$app['session']->driver()->start();
// Terminate middleware response chain with naked response
$response = $startSession->handle($request, function() use($response) {
    return $response; // This response will have session cookie attached to it
});

$response->send();
</code>```

After this I get a laravel_session cookie that has contents on the client. During the login request after the code above executes, if I dd(Auth::user()) then I get the user I just logged in with. However, on subsequent requests Auth::user() and $this->request->user()  both return null in all contexts.

How can I force an active Laravel user session without actually authenticating that will persist across requests?

The ultimate outcome is that Laravel will be running as a 'sub-application' underneath the legacy app while existing features are pulled in one by one so that both will exist for a period of time until all features are implemented in Laravel and it will replace the existing app in full. If it makes more sense to try to take over the legacy authentication with Laravel rather than the other way around I'm open to that, but I'd rather avoid having to change the underlying users table (legacy authentication is happening over LDAP, so there are no passwords locally, there's no remember_token, but that's easy enough to add if I have to). I really am just looking for the shortest path with the least amount of effort/headache.

答:
This won't answer your Laravel question directly, but thinking a little bit outside the box, what you are trying to achieve in principle is SSO (single sign on).

For the sake of migration only this might be an overkill solution, but if you're planning to migrate more interconnected websites or develop an app, it's worth considering.

There are three options (as usual):

implement your solution

use library eg. bshaffer/oauth2-server-php

use 3rd party service

If it comes to 3rd party library I can recommend Auth0 service, which can take authentication burden off you. Depending on number of users it might even come as a free solution. I'm recommending this based on my own experience with the service.

More about SSO

Auth0 SSO example

Body:
I am trying to slowly integrate Laravel into a legacy PHP application. One of the tasks is to automatically register a Laravel user session when a user logs in to the old app. I am not trying to implement Laravel authentication, I really just want to piggyback off of existing functionality and force a specific user to be logged in without checking credentials.  What I have so far has been cobbled together from other people's hacks I have found around:

// Laravel authentication hook - Boostrap application
require_once getcwd() . '/../laravel/bootstrap/autoload.php';
$app = require_once getcwd() . '/../laravel/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Console\Kernel');
$kernel->bootstrap();
$app->boot();

// Start Laravel session
$request = Illuminate\Http\Request::capture();
$response = $app->make('Symfony\Component\HttpFoundation\Response');
$startSession = new Illuminate\Session\Middleware\StartSession($app['session']);
// Associate server session with the authenticating user id
// I have also tried loading user model instance and then $app['auth']->login($user)
$app['auth']->loginUsingId($user_id);

$app['session']->driver()->start();
// Terminate middleware response chain with naked response
$response = $startSession->handle($request, function() use($response) {
    return $response; // This response will have session cookie attached to it
});

$response->send();

After this I get a laravel_session cookie that has contents on the client. During the login request after the code above executes, if I dd(Auth::user()) then I get the user I just logged in with. However, on subsequent requests Auth::user() and $this->request->user()  both return null in all contexts.

How can I force an active Laravel user session without actually authenticating that will persist across requests?

The ultimate outcome is that Laravel will be running as a 'sub-application' underneath the legacy app while existing features are pulled in one by one so that both will exist for a period of time until all features are implemented in Laravel and it will replace the existing app in full. If it makes more sense to try to take over the legacy authentication with Laravel rather than the other way around I'm open to that, but I'd rather avoid having to change the underlying users table (legacy authentication is happening over LDAP, so there are no passwords locally, there's no remember_token, but that's easy enough to add if I have to). I really am just looking for the shortest path with the least amount of effort/headache.


问:
Fatal error on phpMyAdmin
I want to configure my database on CI but I have a problem

How can i fix it?
I'm using CI 2.x
And
phpMyAdmin-4.6.6-english

答:
As I can check your using wrong database settings in your database.php file.

If your php version is equals to php 5.5 or above you have to use

```<code>$db['default']['dbdriver'] = 'mysqli';
</code>```

instead of

```<code>$db['default']['dbdriver'] = 'mysql';
</code>```

and also put your database username and password in setting to avoid this error.

I recommend you to use codeigniter 3 the latest version .

Title: Fatal error on phpMyAdmin

Body:
As I can check your using wrong database settings in your database.php file.

If your php version is equals to php 5.5 or above you have to use

$db['default']['dbdriver'] = 'mysqli';

instead of

$db['default']['dbdriver'] = 'mysql';

and also put your database username and password in setting to avoid this error.

I recommend you to use codeigniter 3 the latest version .


问:
HTML/CSS/JS - Changing style of different s only while ctrl/shift/alt key is held down
I'm currently trying to build a webpage as a way of learning event handlers, though I'm having trouble figuring out what I need to do in order to make this work...

Right now, I have a table with 4 cells in a row. I've got them styled as such.

```<code>#testCtrl, #testShift, #testAlt, #testMeta {
  background-color: black;
  color: white
  ...
}
</code>```

What I'm trying to do is change the background color of the cell when the appropriate key is held down. Problem is - I'm unfamiliar with the syntax and what I can and can't do... All I know at this point is that I need to assign the specific td, via ID, to a variable then modify that variable.

```<code>var _ctrlPress = document.getElementById("testCtrl");
</code>```

I'm just not sure how to test against whether or not the ctrl key is currently being pressed or not though and I'm not finding much information online about it, most likely due to poor knowledge of what to search for.

Also, I'd prefer to not go the jquery route at this time.

I apologize for the ignorance, and thank you much for your time.

Edit: After some advice from the comments, here is what I've come up with. Still errors when applying to a bigger file, though the same concept works fine in a small test HTML doc I've been tinkering with... I'm lost, ha.

Script section:

```<code>window.addEventListener("keydown", function(ev) {
    var modP = ev.key;
    if ( modP=== "Shift" ) document.getElementById("testShift").classList.add("highlight");
});
</code>```

Style section:

```<code>#testCtrl, #testShift, #testAlt, #testMeta {
  background: black;
  color: white
}

.highlight {
  background: white !important;
  color: black !important;
}
</code>```

And finally, the HTML section (or at least the relevant bits):

```<code><tr>
  <td id="fillShift"> Shift
  <td id="fillCtrl"> Ctrl
  <td id="fillAlt"> Alt
  <td id="fillMeta"> Meta
</tr>
</code>```

Where am I messing up?

Again, I apologize for my ignorance. Thank you so much for your time.

答:
Add 2 eventListener to window. 1 for keydown and 1 for keyup. on keydown, change the color. on keyup, change the color back

window.addEventListener("keydown",function(e){
    if(/^1[6-8]$/.test(e.keyCode)){
        document.body.style.backgroundColor="#f00";
     }
});
window.addEventListener("keyup",function(){
    document.body.style.backgroundColor="#aaa";
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body style="background-color:#aaa;"></body></code>```

Title: HTML/CSS/JS - Changing style of different <td>s only while ctrl/shift/alt key is held down

Body:
I'm currently trying to build a webpage as a way of learning event handlers, though I'm having trouble figuring out what I need to do in order to make this work...

Right now, I have a table with 4 cells in a row. I've got them styled as such.

#testCtrl, #testShift, #testAlt, #testMeta {
  background-color: black;
  color: white
  ...
}

What I'm trying to do is change the background color of the cell when the appropriate key is held down. Problem is - I'm unfamiliar with the syntax and what I can and can't do... All I know at this point is that I need to assign the specific td, via ID, to a variable then modify that variable.

var _ctrlPress = document.getElementById("testCtrl");

I'm just not sure how to test against whether or not the ctrl key is currently being pressed or not though and I'm not finding much information online about it, most likely due to poor knowledge of what to search for.

Also, I'd prefer to not go the jquery route at this time.

I apologize for the ignorance, and thank you much for your time.

Edit: After some advice from the comments, here is what I've come up with. Still errors when applying to a bigger file, though the same concept works fine in a small test HTML doc I've been tinkering with... I'm lost, ha.

Script section:

window.addEventListener("keydown", function(ev) {
    var modP = ev.key;
    if ( modP=== "Shift" ) document.getElementById("testShift").classList.add("highlight");
});

Style section:

#testCtrl, #testShift, #testAlt, #testMeta {
  background: black;
  color: white
}

.highlight {
  background: white !important;
  color: black !important;
}

And finally, the HTML section (or at least the relevant bits):

   Shift
   Ctrl
   Alt
   Meta

Where am I messing up?

Again, I apologize for my ignorance. Thank you so much for your time.

Body:
Add 2 eventListener to window. 1 for keydown and 1 for keyup. on keydown, change the color. on keyup, change the color back

window.addEventListener("keydown",function(e){
    if(/^1[6-8]$/.test(e.keyCode)){
        document.body.style.backgroundColor="#f00";
     }
});
window.addEventListener("keyup",function(){
    document.body.style.backgroundColor="#aaa";
});

<body style="background-color:#aaa;"></body>


问:
React Js too much recursion when I tried to change a state in reducer.
I have two containers, which are menu_container and add_on_container. Each container has several components. These two containers are mounted in view file.

In my reducer, I have a state showAddOn. So what I want to make is that depends on the state showAddOn, it shows either menu_container or add_on_container

To do that in each container, I wrote code like

//AddOnContainer

```<code>  render () {
     if(showAddOn == true) {
       return false;
     }
     else return (
          <div>
             My Components....
          </div>
       );
</code>```

//MenuContainer

```<code>  render () {
     if(showAddOn == false) {
       return false;
     }
     else return (
          <div>
             My Components....
          </div>
       );
</code>```

But it triggers too much recursion when I tried to dispatch an action to change state showAddOn

How can I fix this?

Thanks in advance

答:
You can do this in View container like this:

```<code>render() {
   {showAddOn ? <MenuContainer /> : <AddOnContainer /> }
}
</code>```

This will load only one component, depending on condition.

Body:
I have two containers, which are menu_container and add_on_container. Each container has several components. These two containers are mounted in view file.

In my reducer, I have a state showAddOn. So what I want to make is that depends on the state showAddOn, it shows either menu_container or add_on_container

To do that in each container, I wrote code like

//AddOnContainer

  render () {
     if(showAddOn == true) {
       return false;
     }
     else return (

             My Components....

       );

//MenuContainer

  render () {
     if(showAddOn == false) {
       return false;
     }
     else return (

             My Components....

       );

But it triggers too much recursion when I tried to dispatch an action to change state showAddOn

How can I fix this?

Thanks in advance

Body:
You can do this in View container like this:

render() {
   {showAddOn ? <MenuContainer /> : <AddOnContainer /> }
}

This will load only one component, depending on condition.


问:
libc++abi.dylib: terminating with uncaught exception of type NSException - SpriteKit
I am creating a game, where I run my app once and I get this type error:

libc++abi.dylib: terminating with uncaught exception of type NSException

Here is the image:

The Image

Build Phases
  My Build Phases

答:
I have faced the same issue.

Check the name of the Storyboard identifier inside the Identity Inspector and make sure you use the same name.

(A good practice is to use the class name as the identifier)


问:
I want to implement floating-menu in Ionic 2 Project

So far I have implemented buttons i.e (ion-fab) but the button labels can only be placed on top or bottom of the buttons. I want to place them on the left side of button. Image attached for more clarification.

答:
HTML CODE

```<code><ion-content>
    <div id="ListBackdrop" *ngIf="fabButtonOpened==true" ></div>
</ion-content>
<ion-fab right bottom #fab>
   <button ion-fab (click)="openFabButton()">
       <ion-icon name="add"></ion-icon>
    </button>
   <ion-fab-list side="top">
     <button ion-fab>
         <img src="assets/friend_add.png">
     </button>
     <ion-label class="fablabelfriend">Friend</ion-label>
     <button ion-fab>
             <img src="assets/family_add.png">
     </button>
     <ion-label class="fablabelfamily">Family</ion-label>
   </ion-fab-list>
 </ion-fab>
</code>```

Css  File

```<code>   .fablabelfamily
            {
              position: absolute;
              width: 100%;
              padding-right: 220px;
              padding-bottom: 75px;
              margin-top: 0px;
              margin-bottom: 0px;
              font-weight: bold;
            }
.fablabelfriend{
             position: absolute;
             width: 100%;
             padding-right: 220px;
             padding-bottom: 30px;
             margin-top: 10px;
             margin-bottom: 0px;
             font-weight: bold;
          }
#ListBackdrop{
         background-color: white !important;
         position: fixed !important;
         height: 100%;
         width: 100%;
         z-index: 1;
         opacity: 0.8
      }
</code>```

TypeScript File

```<code> export class myClass{
     fabButtonOpened: Boolean;
      constructor(public navCtrl: NavController, private global: globalVariable, private http: Http, public platform: Platform) {
         this.fabButtonOpened=false;

//All other functions inside constructor
    }

        openFabButton(){
          if(this.fabButtonOpened==false){
              this.fabButtonOpened=true;
          }else{
              this.fabButtonOpened=false;
          }
        }
    }
</code>```

Body:
HTML CODE

<ion-content>
    <div id="ListBackdrop" *ngIf="fabButtonOpened==true" ></div>
</ion-content>
<ion-fab right bottom #fab>
   <button ion-fab (click)="openFabButton()">
       <ion-icon name="add"></ion-icon>
    </button>
   <ion-fab-list side="top">
     <button ion-fab>
         <img src="assets/friend_add.png">
     </button>
     <ion-label class="fablabelfriend">Friend</ion-label>
     <button ion-fab>
             <img src="assets/family_add.png">
     </button>
     <ion-label class="fablabelfamily">Family</ion-label>
   </ion-fab-list>
 </ion-fab>

Css  File

   .fablabelfamily
            {
              position: absolute;
              width: 100%;
              padding-right: 220px;
              padding-bottom: 75px;
              margin-top: 0px;
              margin-bottom: 0px;
              font-weight: bold;
            }
.fablabelfriend{
             position: absolute;
             width: 100%;
             padding-right: 220px;
             padding-bottom: 30px;
             margin-top: 10px;
             margin-bottom: 0px;
             font-weight: bold;
          }
#ListBackdrop{
         background-color: white !important;
         position: fixed !important;
         height: 100%;
         width: 100%;
         z-index: 1;
         opacity: 0.8
      }

TypeScript File

 export class myClass{
     fabButtonOpened: Boolean;
      constructor(public navCtrl: NavController, private global: globalVariable, private http: Http, public platform: Platform) {
         this.fabButtonOpened=false;

//All other functions inside constructor
    }

        openFabButton(){
          if(this.fabButtonOpened==false){
              this.fabButtonOpened=true;
          }else{
              this.fabButtonOpened=false;
          }
        }
    }


问:
BASE64 decode and ungzip data in PHP
I am working with OpenSubtitles API and need to BASE64 decode and ungzip API response ('$data' parameter) in PHP.

Full '$data' parameter you can find here:
https://jsfiddle.net/noxjmz40/

I can easily BASE64 decode this parameter with base64_decode($data) but I am not sure how to ungzip and get a normal result.

Please, advice me how to solve this task in a short and efficient way.
Thanks!

答:
```<code><?php
$zipStr = 'UEsDBBQACAAIABprdEEAAAAAAAAAAAAAAAAWAAAAb2JqZWN0cy9Db250YWN0Lm9iamVjdI2SX0vDMBTF3/cpSt9NOhERyTJCl+Gga6VNBZ9GlmWuI21mk0799ka7P50TXR4C9+R3L5ecg4bvpfK2sjaFrgZ+HwS+JyuhF0X1MvBzNr6684e4h8LGWF0m87UU1nMtlRn4K2s39xAazTfALHUtJBC6hNdBcAuDG1hKyxfcch/3PHeQKox9KuSbaetvbdkoFfNSYqEry4WdpXxdzBE86EdUaNWUlcHjPIpmMZlSBPfSOUTCMMljBv7jwiRmJGSATVh0Efj4kMS0fwlJp2QS/Q2mFOQZTTNAognJfmOXhbKyzoTeSEydSx925Yxx/9PRf9Kd/p0q1eKwVphSwuhoNnL315yvt1Pezay5dXHAShqT1PS14QrBo3yKb7lqJGbJiDwj2BbHjeDZSkjxuVR7v72d363Y5gR2goJgN3i49wlQSwcI3kTEMT8BAACvAgAAUEsDBBQACAAIABprdEEAAAAAAAAAAAAAAAALAAAAcGFja2FnZS54bWxNj00LwjAMhu/7FaN3lzpkiHTdQfDkQUS9StbFWbXtWIsf/96xDzSX5CF53ySieJtH/KTWa2dzNk84i8kqV2lb5+x42MyWrJCR2KG6Y01xN219zq4hNCsA77BJ/MW1ihLlDKScZ8AXYChghQGZjOIuRPg05Ie6Z0Om7FbKtbMBVei0fT7v8aZLAVP7J7BoSG61DydNLwE9Dtbw5y3GP2SaJVzARJGA8XwZfQFQSwcIaf0pNKsAAADwAAAAUEsBAhQAFAAIAAgAGmt0Qd5ExDE/AQAArwIAABYAAAAAAAAAAAAAAAAAAAAAAG9iamVjdHMvQ29udGFjdC5vYmplY3RQSwECFAAUAAgACAAaa3RBaf0pNKsAAADwAAAACwAAAAAAAAAAAAAAAACDAQAAcGFja2FnZS54bWxQSwUGAAAAAAIAAgB9AAAAZwIAAAAA';

// Prepare Tmp File for Zip archive
$file = tempnam("tmp", "zip");
$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);

// Add contents
$zip->addFromString('your_file_name', base64_decode($zipStr));

// Close and send to users
$zip->close();
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file);
</code>```

Title: BASE64 decode and ungzip data in PHP


问:
Coq MSet of bounded naturals
I am trying to define a type for Set of natural numbers with given upper bound. Standard library's MSet seems to be a way to go. I found this discussion which gives a nice example of how to define a Set of nat. However I do could not figure out how to extend it to subset  types. I tried something like this:

```<code>Module OWL.
  Parameter n : nat.
  Definition t := {i:nat | i<n}.
  Definition eq := @eq t.
  Instance eq_equiv : @Equivalence t eq := eq_equivalence.
  Definition lt (a b:t) := Peano.lt (proj1_sig a) (proj1_sig b).
  Instance lt_strorder : @StrictOrder t lt.
  ...
</code>```

I will be working with sets with different upper bounds. But I do not see how to instantiate this Module with given 'n'. Ideally, I would like to be able to write something like this:

```<code>Module BoundedMNatSets := MakeWithLeibniz OWL.
Definition BoundedMNatSetN (n:nat) : Type := BoundedMNatSets n.
</code>```

P.S. This question is probably rooted in my insufficient understanding of Coq module system, and not specific to Sets.

答:
You need to use a functor. Something like:

```<code>Require Import Orders.

Module Type FIXED_NAT.
    Parameter n : nat.
End FIXED_NAT.

Module OWL (N : FIXED_NAT) <: OrderedType.
    Definition t := {i:nat | i < N.n}.
    ...
End OWL.
</code>```

You can then apply OWL to modules of signature FIXED_NAT.

```<code>Module N1 <: FIXED_NAT.
    Definition n := 10.
End N1.

Module OWL1 := OWL N1.

Require Import MSets.

Module M1 := Make OWL1.
</code>```

EDIT:
What about:

```<code>Require Import Orders.
Require Import OrdersEx.
Require Import MSets.
Require Import Arith.

Module M := Make Nat_as_OT.

Definition has_upper_bound s n := M.For_all (ge n) s.

Definition t n := {s : M.t | has_upper_bound s n}.
</code>```

Title: Coq MSet of bounded naturals

Body:
I am trying to define a type for Set of natural numbers with given upper bound. Standard library's MSet seems to be a way to go. I found this discussion which gives a nice example of how to define a Set of nat. However I do could not figure out how to extend it to subset  types. I tried something like this:

Module OWL.
  Parameter n : nat.
  Definition t := {i:nat | i<n}.
  Definition eq := @eq t.
  Instance eq_equiv : @Equivalence t eq := eq_equivalence.
  Definition lt (a b:t) := Peano.lt (proj1_sig a) (proj1_sig b).
  Instance lt_strorder : @StrictOrder t lt.
  ...

I will be working with sets with different upper bounds. But I do not see how to instantiate this Module with given 'n'. Ideally, I would like to be able to write something like this:

Module BoundedMNatSets := MakeWithLeibniz OWL.
Definition BoundedMNatSetN (n:nat) : Type := BoundedMNatSets n.

P.S. This question is probably rooted in my insufficient understanding of Coq module system, and not specific to Sets.

Body:
You need to use a functor. Something like:

Require Import Orders.

Module Type FIXED_NAT.
    Parameter n : nat.
End FIXED_NAT.

Module OWL (N : FIXED_NAT) <: OrderedType.
    Definition t := {i:nat | i < N.n}.
    ...
End OWL.

You can then apply OWL to modules of signature FIXED_NAT.

Module N1 <: FIXED_NAT.
    Definition n := 10.
End N1.

Module OWL1 := OWL N1.

Require Import MSets.

Module M1 := Make OWL1.

EDIT:
What about:

Require Import Orders.
Require Import OrdersEx.
Require Import MSets.
Require Import Arith.

Module M := Make Nat_as_OT.

Definition has_upper_bound s n := M.For_all (ge n) s.

Definition t n := {s : M.t | has_upper_bound s n}.


问:
Delete all tags from a Git repository
I want to delete all the tags from a Git repository. How can I do that?

Using git tag -d tagname delete the tag tagname locally, and using git push --tags I update the tags on the git provider.

I tried:

```<code>git tag -d *
</code>```

But I see that * means the files from the current directory.

```<code>$ git tag -d *
error: tag 'file1' not found.
error: tag 'file2' not found.
...
</code>```

Consider I have a lot of tags, and I want to delete them, all.

答:
If you don't have the tags in your local repo, you can delete remote tags without have to take it to your local repo.

```<code>git ls-remote --tags --refs origin | cut -f2 | xargs git push origin --delete
</code>```

Don't forget to replace "origin" to your remote handler name.

Title: Delete all tags from a Git repository

Body:
I want to delete all the tags from a Git repository. How can I do that?

Using git tag -d tagname delete the tag tagname locally, and using git push --tags I update the tags on the git provider.

I tried:

git tag -d *

But I see that * means the files from the current directory.

$ git tag -d *
error: tag 'file1' not found.
error: tag 'file2' not found.
...

Consider I have a lot of tags, and I want to delete them, all.

Body:
If you don't have the tags in your local repo, you can delete remote tags without have to take it to your local repo.

git ls-remote --tags --refs origin | cut -f2 | xargs git push origin --delete

Don't forget to replace "origin" to your remote handler name.


问:
C# Model validation throws "Cannot convert from System.DateTime to System.Array"
I'm trying to insert to a table from excel using LinqToExcel and when I call

```<code>ValidateModel(u);
</code>```

It throws an exception:

Cannot convert from System.DateTime to System.Array

I'm using DataAnnotations on the viewmodel.

Datetime in ViewModel:

```<code>[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime FECHA_ADQ { get; set; }
</code>```

Controller:

```<code>foreach (var a in excel.Worksheet<ViewModel>(sheet.First()))
{
    //Validations//
    try
    {
        Context db = new Context();
        ViewModel u = a;
        ModelState.Clear();
        ValidateModel(u);

        //Insert//
    }
    catch(Exception)
    {
        // ...
    }
}
</code>```

Datetime in excel file:

This is what it looks like on the debugger:

答:
I couldn't resolve the issue with excel so i just ended up validating after the mapping to the base model and it worked.</p>

```<code>ModelState.Clear();

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<ViewModel, Model>();
});

IMapper mapper = config.CreateMapper();
var inv = mapper.Map<ViewModel, Model>(u);

if (inv.FECHA_ADQ.Year <= 2005) {
    errors.AppendLine("Serial: " + a.SERIAL + " Error on Row: " + row + " Cause: Invalid Date.");
    counter++;
} else {
    ValidateModel(inv);
    Context.ModelDB.Add(inv);
    Context.SaveChanges();
}
</code>```

Body:
I'm trying to insert to a table from excel using LinqToExcel and when I call

ValidateModel(u);

It throws an exception:

Cannot convert from System.DateTime to System.Array

I'm using DataAnnotations on the viewmodel.

Datetime in ViewModel:

[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime FECHA_ADQ { get; set; }

Controller:

foreach (var a in excel.Worksheet<ViewModel>(sheet.First()))
{
    //Validations//
    try
    {
        Context db = new Context();
        ViewModel u = a;
        ModelState.Clear();
        ValidateModel(u);

        //Insert//
    }
    catch(Exception)
    {
        // ...
    }
}

Datetime in excel file:

This is what it looks like on the debugger:

Body:
I couldn't resolve the issue with excel so i just ended up validating after the mapping to the base model and it worked.

ModelState.Clear();

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<ViewModel, Model>();
});

IMapper mapper = config.CreateMapper();
var inv = mapper.Map<ViewModel, Model>(u);

if (inv.FECHA_ADQ.Year <= 2005) {
    errors.AppendLine("Serial: " + a.SERIAL + " Error on Row: " + row + " Cause: Invalid Date.");
    counter++;
} else {
    ValidateModel(inv);
    Context.ModelDB.Add(inv);
    Context.SaveChanges();
}


问:
Django get the Model name using ORM's related field name
I have a string like this order__product__category__description which is a related expression of my Django's model structure

Now I have a model called Shipment

field = 'order__product__category__description'

Here description is a column name of table/model Category. Here comes the question, just by having this model Shipment and this field string order__product__category__description how do I find these models Order, Product, Category.

My use-case is I need to store all the field_names of Category in a list. Any idea on how to connect the dots? having left with just two details Shipment & that field string.

First thing comes to mind is to split by __ and to come up with a list like this ['order','product','category'] and to iterate the model _meta based on the field name. Any other elegant ways would be appreciated.

答:
Assuming you have split the string it into a list, as you said to these:

```<code>models = ['order', 'product', 'category']
</code>```

First get the app label (a string) that each model refers to:

```<code>from django.contrib.contenttypes.models import ContentType

app_labels = []

for model in models:
    app_labels.append(ContentType.objects.filter(model=model).values('app_label').first().get('app_label'))
</code>```

Now you have both model names and app names. So:

```<code>from django.apps import apps

model_classes = []

for app, model in zip(app_labels, models):
    model_classes.append(apps.get_model(app, model))
</code>```

Finally, get each model fields with the _meta attribute like you already know:

```<code>for model in model_classes:
    print(model._meta.get_fields())
</code>```

Body:
Assuming you have split the string it into a list, as you said to these:

models = ['order', 'product', 'category']

First get the app label (a string) that each model refers to:

from django.contrib.contenttypes.models import ContentType

app_labels = []

for model in models:
    app_labels.append(ContentType.objects.filter(model=model).values('app_label').first().get('app_label'))

Now you have both model names and app names. So:

from django.apps import apps

model_classes = []

for app, model in zip(app_labels, models):
    model_classes.append(apps.get_model(app, model))

Finally, get each model fields with the _meta attribute like you already know:

for model in model_classes:
    print(model._meta.get_fields())


问:
error when i import android eclipse project in Android Studio
Hello guys i'm gald to be here, please i have that error, can you help me?

```<code>Error:Execution failed for task ':app:processDebugManifest'.
</code>```

Manifest merger failed : uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library [com.google.android.gms:play-services:10.2.1] C:\Users\Khalil\StudioProjects\Android eBook Template\app\build\intermediates\exploded-aar\com.google.android.gms\play-services\10.2.1\AndroidManifest.xml
      Suggestion: use tools:overrideLibrary="com.google.android.gms.play_services" to force usage

what i can do?

答: In your Manifest.xml file, update uses-sdk to version 14.

Body:
Hello guys i'm gald to be here, please i have that error, can you help me?

Error:Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library [com.google.android.gms:play-services:10.2.1] C:\Users\Khalil\StudioProjects\Android eBook Template\app\build\intermediates\exploded-aar\com.google.android.gms\play-services\10.2.1\AndroidManifest.xml
      Suggestion: use tools:overrideLibrary="com.google.android.gms.play_services" to force usage

what i can do?


问:
Installing Kivy on Windows 7 with Anaconda Python 3.6
I am trying to install Kivy on my Windows 7 PC for Android development using python.

I have followed the steps mentioned here.kivy installation on Windows

I am getting the following error for

python -m pip install kivy

The first error

```<code>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\OEM\Anaconda3\libs /LIBPATH:C:\Users\OEM\Anaconda3\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.10586.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.10586.0\um\x64" /EXPORT:PyInit_buffer build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.obj /OUT:build\lib.win-amd64-3.6\kivy\graphics\buffer.cp36-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.lib
  buffer.obj : warning LNK4197: export 'PyInit_buffer' specified multiple times; using first specification
     Creating library build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.lib and object build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.exp
  Generating code
  Finished generating code
  cythoning C:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics/context.pyx to C:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.c
  building 'kivy.graphics.context' extension
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\OEM\Anaconda3\include -IC:\Users\OEM\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\winrt" /TcC:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.c /Fobuild\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.obj
  context.c
  c:\users\oem\appdata\local\temp\pip-build-jmayz55y\kivy\kivy\graphics\gl_redirect.h(8): fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or directory
   error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2

  ----------------------------------------
  Running setup.py clean for kivy
Failed to build kivy
Installing collected packages: kivy
  Running setup.py install for kivy: started
    Running setup.py install for kivy: finished with status 'error'
    Complete output from command C:\Users\OEM\Anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\OEM\\AppData\\Local\\Temp\\pip-build-jmayz55y\\kivy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\OEM\AppData\Local\Temp\pip-wg_pau0w-record\install-record.txt --single-version-externally-managed --compile:
    Using distutils

    Detected Cython version 0.25.2
      This version of Cython is untested with Kivy. While this version may
      work perfectly fine, it is possible that you may experience issues. If
      you do have issues, please downgrade to a supported version. It is
      best to use the newest supported version, 0.23, but the minimum
      supported version is 0.20.

      If your platform provides a Cython package, check if you can downgrade
      to a supported version. Otherwise, uninstall the platform package and
      install Cython via pip:

        pip install -I Cython==0.23
    User distribution detected, avoid portable command.
    Windows platform detected, force GLEW usage.
    Using this graphics system: OpenGL
    WARNING: A problem occured while running pkg-config --libs --cflags gstreamer-1.0 (code 1)

    b"'pkg-config' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n"

    WARNING: A problem occured while running pkg-config --libs --cflags sdl2 SDL2_ttf SDL2_image SDL2_mixer (code 1)

    b"'pkg-config' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n"
</code>```

The second error:

```<code>    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\OEM\Anaconda3\libs /LIBPATH:C:\Users\OEM\Anaconda3\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.10586.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.10586.0\um\x64" /EXPORT:PyInit_buffer build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.obj /OUT:build\lib.win-amd64-3.6\kivy\graphics\buffer.cp36-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.lib
    buffer.obj : warning LNK4197: export 'PyInit_buffer' specified multiple times; using first specification
       Creating library build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.lib and object build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.exp
    Generating code
    Finished generating code
    skipping 'C:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.c' Cython extension (up-to-date)
    building 'kivy.graphics.context' extension
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\OEM\Anaconda3\include -IC:\Users\OEM\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\winrt" /TcC:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.c /Fobuild\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.obj
    context.c
    c:\users\oem\appdata\local\temp\pip-build-jmayz55y\kivy\kivy\graphics\gl_redirect.h(8): fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or directory
     error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2

    ----------------------------------------
</code>```

What is wrong with the installation?

答:
Py35+ support was added only recently, therefore Kivy 1.9.1 version (that on pypi) won't work on py35+.

To make it work compile either from source:

```<code>pip install https://github.com/kivy/kivy/zipball/master
</code>```

or use wheels that are exactly on the same documentation page.

Body:
I am trying to install Kivy on my Windows 7 PC for Android development using python.

I have followed the steps mentioned here.kivy installation on Windows

I am getting the following error for

python -m pip install kivy

The first error

  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\OEM\Anaconda3\libs /LIBPATH:C:\Users\OEM\Anaconda3\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.10586.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.10586.0\um\x64" /EXPORT:PyInit_buffer build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.obj /OUT:build\lib.win-amd64-3.6\kivy\graphics\buffer.cp36-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.lib
  buffer.obj : warning LNK4197: export 'PyInit_buffer' specified multiple times; using first specification
     Creating library build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.lib and object build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.exp
  Generating code
  Finished generating code
  cythoning C:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics/context.pyx to C:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.c
  building 'kivy.graphics.context' extension
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\OEM\Anaconda3\include -IC:\Users\OEM\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\winrt" /TcC:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.c /Fobuild\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.obj
  context.c
  c:\users\oem\appdata\local\temp\pip-build-jmayz55y\kivy\kivy\graphics\gl_redirect.h(8): fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or directory
   error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2

  ----------------------------------------
  Running setup.py clean for kivy
Failed to build kivy
Installing collected packages: kivy
  Running setup.py install for kivy: started
    Running setup.py install for kivy: finished with status 'error'
    Complete output from command C:\Users\OEM\Anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\OEM\\AppData\\Local\\Temp\\pip-build-jmayz55y\\kivy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\OEM\AppData\Local\Temp\pip-wg_pau0w-record\install-record.txt --single-version-externally-managed --compile:
    Using distutils

    Detected Cython version 0.25.2
      This version of Cython is untested with Kivy. While this version may
      work perfectly fine, it is possible that you may experience issues. If
      you do have issues, please downgrade to a supported version. It is
      best to use the newest supported version, 0.23, but the minimum
      supported version is 0.20.

      If your platform provides a Cython package, check if you can downgrade
      to a supported version. Otherwise, uninstall the platform package and
      install Cython via pip:

        pip install -I Cython==0.23
    User distribution detected, avoid portable command.
    Windows platform detected, force GLEW usage.
    Using this graphics system: OpenGL
    WARNING: A problem occured while running pkg-config --libs --cflags gstreamer-1.0 (code 1)

    b"'pkg-config' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n"

    WARNING: A problem occured while running pkg-config --libs --cflags sdl2 SDL2_ttf SDL2_image SDL2_mixer (code 1)

    b"'pkg-config' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n"

The second error:

    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\OEM\Anaconda3\libs /LIBPATH:C:\Users\OEM\Anaconda3\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.10586.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.10586.0\um\x64" /EXPORT:PyInit_buffer build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.obj /OUT:build\lib.win-amd64-3.6\kivy\graphics\buffer.cp36-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.lib
    buffer.obj : warning LNK4197: export 'PyInit_buffer' specified multiple times; using first specification
       Creating library build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.lib and object build\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\buffer.cp36-win_amd64.exp
    Generating code
    Finished generating code
    skipping 'C:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.c' Cython extension (up-to-date)
    building 'kivy.graphics.context' extension
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\OEM\Anaconda3\include -IC:\Users\OEM\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\winrt" /TcC:\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.c /Fobuild\temp.win-amd64-3.6\Release\Users\OEM\AppData\Local\Temp\pip-build-jmayz55y\kivy\kivy\graphics\context.obj
    context.c
    c:\users\oem\appdata\local\temp\pip-build-jmayz55y\kivy\kivy\graphics\gl_redirect.h(8): fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or directory
     error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2

    ----------------------------------------

What is wrong with the installation?

Body:
Py35+ support was added only recently, therefore Kivy 1.9.1 version (that on pypi) won't work on py35+.

To make it work compile either from source:

pip install https://github.com/kivy/kivy/zipball/master

or use wheels that are exactly on the same documentation page.


问:
Background Blur - CSS
Hello I try to make this background Blur like this image so I'd like to know if I can do it using CSS3 only or I need to use Javascript & Jquery:

And if I will use css only How to make the blur is responsive.

Here my simple code:

#bg{
  background-image: url('http://store6.up-00.com/2017-03/149079039538851.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}

#bg {
  background-position: center top;
  padding: 70px 90px 120px 90px;
}

#search-container {
  position: relative;
}

#search-bg {
  /* Absolutely position it, but stretch it to all four corners, then put it just behind #search's z-index */
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  z-index: 99;
  /* Pull the background 70px higher to the same place as #bg's */
  /*background-position: center -70px;*/
  -webkit-filter: blur(10px);
  filter: blur(10px);
}

#search {
  position: relative;
  z-index: 100;
  padding: 20px;
  background: rgba(34,34,34,0.75);
}
#search h2{
    color:#ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bg">
        <div id="search-container">
            <div id="search-bg"></div>
            <div id="search">
                <h2>Hello World</h2>
            </div>
        </div>
    </div></code>```

答:
you can use background-attachment:fixed; and set it also in the blured container , background-attachment  is there to set both bg on the same spot, one can be blured.

example with a pseudo instead extra div:

#bg {
  background-image: url('http://store6.up-00.com/2017-03/149079039538851.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed;
  background-position: center top;
  padding: 70px 90px 120px 90px;
}

#search-container {
  position: relative;
}

#search-container:before {/* add same bg-image with same backgrounds values to match main container */
  content: '';
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  z-index: 0;
  background-image: url('http://store6.up-00.com/2017-03/149079039538851.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center top;
  background-attachment: fixed;/* make it match #bg position and size */
  -webkit-filter: blur(5px);
  filter: blur(5px);
}

#search {
  position: relative;
  z-index: 1;
  padding: 20px;
  background: rgba(34, 34, 34, 0.5);
  display:flex;
}

#search h2 {
  color: #ffffff;
  margin:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bg">
  <div id="search-container">
    <div id="search">
      <h2>Hello World</h2>
    </div>
  </div>
</div></code>```

Title: Background Blur - CSS

Body:
Hello I try to make this background Blur like this image so I'd like to know if I can do it using CSS3 only or I need to use Javascript & Jquery:

And if I will use css only How to make the blur is responsive.

Here my simple code:

#bg{
  background-image: url('http://store6.up-00.com/2017-03/149079039538851.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}

#bg {
  background-position: center top;
  padding: 70px 90px 120px 90px;
}

#search-container {
  position: relative;
}

#search-bg {
  /* Absolutely position it, but stretch it to all four corners, then put it just behind #search's z-index */
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  z-index: 99;
  /* Pull the background 70px higher to the same place as #bg's */
  /*background-position: center -70px;*/
  -webkit-filter: blur(10px);
  filter: blur(10px);
}

#search {
  position: relative;
  z-index: 100;
  padding: 20px;
  background: rgba(34,34,34,0.75);
}
#search h2{
    color:#ffffff;
}

Hello World

Body:
you can use background-attachment:fixed; and set it also in the blured container , background-attachment  is there to set both bg on the same spot, one can be blured.

example with a pseudo instead extra div:

#bg {
  background-image: url('http://store6.up-00.com/2017-03/149079039538851.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed;
  background-position: center top;
  padding: 70px 90px 120px 90px;
}

#search-container {
  position: relative;
}

#search-container:before {/* add same bg-image with same backgrounds values to match main container */
  content: '';
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  z-index: 0;
  background-image: url('http://store6.up-00.com/2017-03/149079039538851.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center top;
  background-attachment: fixed;/* make it match #bg position and size */
  -webkit-filter: blur(5px);
  filter: blur(5px);
}

#search {
  position: relative;
  z-index: 1;
  padding: 20px;
  background: rgba(34, 34, 34, 0.5);
  display:flex;
}

#search h2 {
  color: #ffffff;
  margin:auto;
}

<div id="bg">
  <div id="search-container">
    <div id="search">
      <h2>Hello World</h2>
    </div>
  </div>
</div>


问:
Rails nested attributes: require at least two records
How can I make it so that at least two option records are required to submit a product?</p>

```<code>class Product < ActiveRecord::Base
  belongs_to :user
  has_many :options, :dependent => :destroy
  accepts_nested_attributes_for :options, :allow_destroy => :true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
  validates_presence_of :user_id, :created_at
  validates :description, :presence => true, :length => {:minimum => 0, :maximum => 500}
end

class Option < ActiveRecord::Base
  belongs_to :product
  validates :name, :length => {:minimum => 0, :maximum => 60}
end
</code>```

答:
```<code>class Product < ActiveRecord::Base
  #... all your other stuff
  validate :require_two_options

  private
    def require_two_options
      errors.add(:base, "You must provide at least two options") if options.size < 2
    end
end
</code>```

Body:
How can I make it so that at least two option records are required to submit a product?

class Product < ActiveRecord::Base
  belongs_to :user
  has_many :options, :dependent => :destroy
  accepts_nested_attributes_for :options, :allow_destroy => :true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
  validates_presence_of :user_id, :created_at
  validates :description, :presence => true, :length => {:minimum => 0, :maximum => 500}
end

class Option < ActiveRecord::Base
  belongs_to :product
  validates :name, :length => {:minimum => 0, :maximum => 60}
end


问:
Why is the POP3 protocol still in use?
I am still trying to understand e-mail protocols. It seems that IMAP is more powerful than POP3. Why, then, does the POP3 protocol survive? It is still supported by popular email services like GMail.</p>

答:
Another reason is POP3 fetchers. You may have a central IMAP mailbox where you want to download mail from all other accounts of yours to keep all your mail in same place. This is usually done with POP3 fetchers which poll your other mailboxes periodically and load mail from there in your primary mailbox.

Although IMAP fetchers do exist, most of fetchers are still POP3-only and if your other mailbox does not support POP3, you may have troubles using a fetcher to link it with your primary mailbox.

OwnerDisplayName: Morgan Cheng

Title: Why is the POP3 protocol still in use?