问:
Is it correct to attach code through volume in kubernetes?
In order to do ease development in Docker, the code is attached to the containers through volumes. In that way, there is no need to rebuild the images each time the code is changed.

So, is it correct to think to use the same idea in Kubernetes?

PS: I know that the concepts PersistentVolume and PersistentVolumeClaim allow to attach volume, but they are intended for data.

Update

To ease the development, I do need to use the volume for both code and data. This will avoid me to rebuild the images at each change of code.

Below this is what I am trying to do in minikube:

the deployment

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: '/home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube/src/'
</code>```

the service

```<code>apiVersion: v1
kind: Service
metadata:
  name: php-hostpath
  namespace: default
  labels:
    app: php-hostpath
spec:
  selector:
    app: php-hostpath
  ports:
  - port: 80
    targetPort: 80
  type: "LoadBalancer"
</code>```

The service and the deployment are well created in minikube:

```<code>$ kubectl get pods -l app=php-hostpath
NAME                            READY     STATUS    RESTARTS   AGE
php-hostpath-3796606162-bt94w   1/1       Running   0          19m

$ kubectl get service -l app=php-hostpath
NAME           CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
php-hostpath   10.0.0.110   <pending>     80:30135/TCP   27m
</code>```

The folder src and the file src/index.php are also well created.

```<code><?php
echo "This is my first docker project";
</code>```

Now I want to check that every thing is running:

```<code>$ kubectl exec -ti php-hostpath-3796606162-bt94w bash
root@php-hostpath-3796606162-bt94w:/var/www/html# ls
root@php-hostpath-3796606162-bt94w:/var/www/html# exit
exit
</code>```

The folder src and the file index.php are not in /var/www/html!

Have I missed something?

PS: if I were in production env, I will not put my code in a volume.
Thanks,

答:
Based on this doc, Host folder sharing is not implemented in the KVM driver yet. This is the driver I am using actually.

To overcome this, there are 2 solutions:

Use the virtualbox driver so that you can mount your hostPath volume by changing the path on you localhost /home/THE_USR/... to /hosthome/THE_USR/...

Mount your volume to the minikube VM based on the command $ minikube mount /home/THE_USR/.... The command will return you the path of your mounted volume on the minikube VM. Example is given down.

Example

(a) mounting a volume on the minikube VM

the minikube mount command returned that path /mount-9p

```<code>$ minikube mount -v 3 /home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube
Mounting /home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube into /mount-9p on the minikubeVM
This daemon process needs to stay alive for the mount to still be accessible...
2017/03/31 06:42:27 connected
2017/03/31 06:42:27 >>> 192.168.42.241:34012 Tversion tag 65535 msize 8192 version '9P2000.L'
2017/03/31 06:42:27 <<< 192.168.42.241:34012 Rversion tag 65535 msize 8192 version '9P2000'
</code>```

(b) Specification of the path on the deployment

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: /mount-9p
</code>```

(c) Checking if mounting the volume worked well

```<code>amine@amine-Inspiron-N5110:~/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube$ kubectl exec -ti php-hostpath-3498998593-6mxsn bash
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php
echo "This is my first docker project";
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php

echo 'This is my first hostPath on kubernetes';
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php

echo 'This is my first hostPath on kubernetes';
root@php-hostpath-3498998593-6mxsn:/var/www/html#
</code>```

PS: this kind of volume mounting is only development environment. If I were in production environment, the code will not be mounted: it will be in the image.

PS: I recommend the virtualbox in stead of KVM.

Hope it helps others.

Body:
In order to do ease development in Docker, the code is attached to the containers through volumes. In that way, there is no need to rebuild the images each time the code is changed.

So, is it correct to think to use the same idea in Kubernetes?

PS: I know that the concepts PersistentVolume and PersistentVolumeClaim allow to attach volume, but they are intended for data.

Update

To ease the development, I do need to use the volume for both code and data. This will avoid me to rebuild the images at each change of code.

Below this is what I am trying to do in minikube:

the deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: '/home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube/src/'

the service

apiVersion: v1
kind: Service
metadata:
  name: php-hostpath
  namespace: default
  labels:
    app: php-hostpath
spec:
  selector:
    app: php-hostpath
  ports:
  - port: 80
    targetPort: 80
  type: "LoadBalancer"

The service and the deployment are well created in minikube:

$ kubectl get pods -l app=php-hostpath
NAME                            READY     STATUS    RESTARTS   AGE
php-hostpath-3796606162-bt94w   1/1       Running   0          19m

$ kubectl get service -l app=php-hostpath
NAME           CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
php-hostpath   10.0.0.110   <pending>     80:30135/TCP   27m

The folder src and the file src/index.php are also well created.

<?php
echo "This is my first docker project";

Now I want to check that every thing is running:

$ kubectl exec -ti php-hostpath-3796606162-bt94w bash
root@php-hostpath-3796606162-bt94w:/var/www/html# ls
root@php-hostpath-3796606162-bt94w:/var/www/html# exit
exit

The folder src and the file index.php are not in /var/www/html!

Have I missed something?

PS: if I were in production env, I will not put my code in a volume.
Thanks,

Body:
Based on this doc, Host folder sharing is not implemented in the KVM driver yet. This is the driver I am using actually.

To overcome this, there are 2 solutions:

Use the virtualbox driver so that you can mount your hostPath volume by changing the path on you localhost /home/THE_USR/... to /hosthome/THE_USR/...

Mount your volume to the minikube VM based on the command $ minikube mount /home/THE_USR/.... The command will return you the path of your mounted volume on the minikube VM. Example is given down.

Example

(a) mounting a volume on the minikube VM

the minikube mount command returned that path /mount-9p

$ minikube mount -v 3 /home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube
Mounting /home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube into /mount-9p on the minikubeVM
This daemon process needs to stay alive for the mount to still be accessible...
2017/03/31 06:42:27 connected
2017/03/31 06:42:27 >>> 192.168.42.241:34012 Tversion tag 65535 msize 8192 version '9P2000.L'
2017/03/31 06:42:27 <<< 192.168.42.241:34012 Rversion tag 65535 msize 8192 version '9P2000'

(b) Specification of the path on the deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: /mount-9p

(c) Checking if mounting the volume worked well

amine@amine-Inspiron-N5110:~/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube$ kubectl exec -ti php-hostpath-3498998593-6mxsn bash
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php
echo "This is my first docker project";
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php

echo 'This is my first hostPath on kubernetes';
root@php-hostpath-3498998593-6mxsn:/var/www/html# cat index.php
<?php

echo 'This is my first hostPath on kubernetes';
root@php-hostpath-3498998593-6mxsn:/var/www/html#

PS: this kind of volume mounting is only development environment. If I were in production environment, the code will not be mounted: it will be in the image.

PS: I recommend the virtualbox in stead of KVM.

Hope it helps others.


来源: stackexchange

问:
CSS image with positiion absolute keep in div
I have img inside div. The image contains position: absolute.

```<code><div id="page">
        <div class="content">
            <div class="post_container">
                <div class="post_content">
                    Mau beli e-book di Google Play? Pakai pulsa Telkomsel aja! Berkesempatan dapat hadiah di Festival #JajanOnline
                    Cek http://tsel.me/festival

                    <div class="img">
                        <img src="https://scontent-sin6-1.cdninstagram.com/t51.2885-15/sh0.08/e35/p640x640/17494073_1872822862961864_3051963374960115712_n.jpg"/>
                    </div>

                    <div class="post_action">
                        Comment
                    </div>
                </div>
            </div>
        </div>
    </div>
</code>```

CSS

```<code>#page .content
{
position: absolute;
margin-top: 10px;
width: 1000px;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}

#page .content .post_container
{
width: 500px;
border: 1px solid #dddddd;
}

#page .content .post_container .post_content
{
background: #fff;
}

#page .content .post_container .post_content .img
{
position: relative;
}

#page .content .post_container .post_content .img img
{
position: absolute;
width: 100%;
clip: rect(0, 500px, 400px, 0);
}
</code>```

I want the img keep inside div. The fact: the image is not inside.

You can see in the fiddle for the demo.

I don't want to use height/min-height on post_container.

答:
First, try to avoid calling a class img. Reserve that for the element, as this can get confusing while looking at your code. try calling it img-container. Set that container to width: 90% and center it with margin: auto. Then add some margin to the container to give it some space from the text.

Working with what you have already set up try this:

```<code>#page .content .post_container .post_content .img
{
  position: relative;
  width: 90%;
  margin: 10px auto;
}

#page .content .post_container .post_content .img img
{
    position: relative;
    width: 100%;
    clip: rect(0, 500px, 400px, 0);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have img inside div. The image contains position: absolute.

                    Mau beli e-book di Google Play? Pakai pulsa Telkomsel aja! Berkesempatan dapat hadiah di Festival #JajanOnline
                    Cek http://tsel.me/festival

                        Comment

CSS

#page .content
{
position: absolute;
margin-top: 10px;
width: 1000px;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}

#page .content .post_container
{
width: 500px;
border: 1px solid #dddddd;
}

#page .content .post_container .post_content
{
background: #fff;
}

#page .content .post_container .post_content .img
{
position: relative;
}

#page .content .post_container .post_content .img img
{
position: absolute;
width: 100%;
clip: rect(0, 500px, 400px, 0);
}

I want the img keep inside div. The fact: the image is not inside.

You can see in the fiddle for the demo.

I don't want to use height/min-height on post_container.

Body:
First, try to avoid calling a class img. Reserve that for the element, as this can get confusing while looking at your code. try calling it img-container. Set that container to width: 90% and center it with margin: auto. Then add some margin to the container to give it some space from the text.

Working with what you have already set up try this:

#page .content .post_container .post_content .img
{
  position: relative;
  width: 90%;
  margin: 10px auto;
}

#page .content .post_container .post_content .img img
{
    position: relative;
    width: 100%;
    clip: rect(0, 500px, 400px, 0);
}


问:
Generate random password string with requirements in javascript
I want to generate a random string that has to have 5 letters from a-z and 3 numbers.

How can I do this with JavaScript?

I've got the following script, but it doesn't meet my requirements.

```<code>        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        var string_length = 8;
        var randomstring = '';
        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }
</code>```

答:
In case you need a password generated with at least 1 number, 1 upper case character, and 1 lower case character:

```<code>function generatePassword(passwordLength) {
  var numberChars = "0123456789";
  var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var lowerChars = "abcdefghijklmnopqrstuvwxyz";
  var allChars = numberChars + upperChars + lowerChars;
  var randPasswordArray = Array(passwordLength);
  randPasswordArray[0] = numberChars;
  randPasswordArray[1] = upperChars;
  randPasswordArray[2] = lowerChars;
  randPasswordArray = randPasswordArray.fill(allChars, 3);
  return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(Math.random() * x.length)] })).join('');
}

function shuffleArray(array) {
  for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

alert(generatePassword(12));
</code>```

Here's the fiddle if you want to play/test: http://jsfiddle.net/sJGW4/155/

Props to @mwag for giving me the start to create this.

ContentLicense: CC BY-SA 4.0

Body:
I want to generate a random string that has to have 5 letters from a-z and 3 numbers.

How can I do this with JavaScript?

I've got the following script, but it doesn't meet my requirements.

        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        var string_length = 8;
        var randomstring = '';
        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }

Body:
In case you need a password generated with at least 1 number, 1 upper case character, and 1 lower case character:

function generatePassword(passwordLength) {
  var numberChars = "0123456789";
  var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var lowerChars = "abcdefghijklmnopqrstuvwxyz";
  var allChars = numberChars + upperChars + lowerChars;
  var randPasswordArray = Array(passwordLength);
  randPasswordArray[0] = numberChars;
  randPasswordArray[1] = upperChars;
  randPasswordArray[2] = lowerChars;
  randPasswordArray = randPasswordArray.fill(allChars, 3);
  return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(Math.random() * x.length)] })).join('');
}

function shuffleArray(array) {
  for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

alert(generatePassword(12));

Here's the fiddle if you want to play/test: http://jsfiddle.net/sJGW4/155/

Props to @mwag for giving me the start to create this.


问:
LINQ binding refresh problem
I have a ListView bound to a LINQ to SQL object.  When I double click an article in the ListView it opens the article details window and allow the user to change article properties.

So far, it all works fine, but when the user saves and closes the article details, the ListView doesn't reflect the changes made (like the article's description for example). I don't want to implement INotifyPropertyChanged in all my LINQ classes because I use VS2010 to generate my Linq table schema, so it would be a pain to alter auto generated designer code... (and it will certainly override all my changes each time I will make a change to the table's schema)

How can I simply force the ListView to refresh the LINQ binding when the details window is closed?

Thank in advance for your help.

答:
A quick and easy solution is to use a DynamicObject decorator to add the change notificcation behaviour without having to change your original classes, or writing a suite of partial class definitions

```<code>public class DynamicBindingProxy<T> : DynamicObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private static readonly Dictionary<string, Dictionary<string,
        PropertyInfo>> properties = new Dictionary<string,
            Dictionary<string, PropertyInfo>>();
    private readonly T instance;
    private readonly string typeName;

    public DynamicBindingProxy(T instance)
    {
        this.instance = instance;
        var type = typeof(T);
        typeName = type.FullName;
        if (!properties.ContainsKey(typeName))
            SetProperties(type, typeName);
    }

    private static void SetProperties(Type type, string typeName)
    {
        var props = type.GetProperties(
            BindingFlags.Public | BindingFlags.Instance);
        var dict = props.ToDictionary(prop => prop.Name);
        properties.Add(typeName, dict);
    }

    public override bool TryGetMember(GetMemberBinder binder,
        out object result)
    {
        if (properties[typeName].ContainsKey(binder.Name))
        {
            result = properties[typeName][binder.Name]
                .GetValue(instance, null);
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder,
        object value)
    {
        if (properties[typeName].ContainsKey(binder.Name))
        {
            properties[typeName][binder.Name]
                .SetValue(instance, value, null);
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(binder.Name));
            return true;
        }
        return false;
    }
}
</code>```

and heres a sample useage:

```<code>public partial class MainWindow : Window
{
    private readonly TestObj tObj;
    private DynamicBindingProxy<TestObj> dynObj;
    public MainWindow()
    {
        InitializeComponent();
        tObj = new TestObj() { Name = "test", Amount = 123.45, ID = 44, SomeDate = DateTime.Now };
        dynObj = new DynamicBindingProxy<TestObj>(tObj);
        DataContext = dynObj;
    }

    private void UpdateName(object sender, RoutedEventArgs e)
    {
        ((dynamic)dynObj).Name = newText.Text;
    }
}
</code>```

full details can be found on a blog post I wrote specifically about this issues
http://www.deanchalk.me.uk/post/WPF-e28093-Easy-INotifyPropertyChanged-Via-DynamicObject-Proxy.aspx

ContentLicense: CC BY-SA 2.5

Title: LINQ binding refresh problem

Body:
A quick and easy solution is to use a DynamicObject decorator to add the change notificcation behaviour without having to change your original classes, or writing a suite of partial class definitions

public class DynamicBindingProxy<T> : DynamicObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private static readonly Dictionary<string, Dictionary<string,
        PropertyInfo>> properties = new Dictionary<string,
            Dictionary<string, PropertyInfo>>();
    private readonly T instance;
    private readonly string typeName;

    public DynamicBindingProxy(T instance)
    {
        this.instance = instance;
        var type = typeof(T);
        typeName = type.FullName;
        if (!properties.ContainsKey(typeName))
            SetProperties(type, typeName);
    }

    private static void SetProperties(Type type, string typeName)
    {
        var props = type.GetProperties(
            BindingFlags.Public | BindingFlags.Instance);
        var dict = props.ToDictionary(prop => prop.Name);
        properties.Add(typeName, dict);
    }

    public override bool TryGetMember(GetMemberBinder binder,
        out object result)
    {
        if (properties[typeName].ContainsKey(binder.Name))
        {
            result = properties[typeName][binder.Name]
                .GetValue(instance, null);
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder,
        object value)
    {
        if (properties[typeName].ContainsKey(binder.Name))
        {
            properties[typeName][binder.Name]
                .SetValue(instance, value, null);
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(binder.Name));
            return true;
        }
        return false;
    }
}

and heres a sample useage:

public partial class MainWindow : Window
{
    private readonly TestObj tObj;
    private DynamicBindingProxy<TestObj> dynObj;
    public MainWindow()
    {
        InitializeComponent();
        tObj = new TestObj() { Name = "test", Amount = 123.45, ID = 44, SomeDate = DateTime.Now };
        dynObj = new DynamicBindingProxy<TestObj>(tObj);
        DataContext = dynObj;
    }

    private void UpdateName(object sender, RoutedEventArgs e)
    {
        ((dynamic)dynObj).Name = newText.Text;
    }
}

full details can be found on a blog post I wrote specifically about this issues
http://www.deanchalk.me.uk/post/WPF-e28093-Easy-INotifyPropertyChanged-Via-DynamicObject-Proxy.aspx


问:
OData property with internal setter -- like UpdateDate
I have a model with a class called "Animal".

The "Animal" class has several properties but let's focus on the following properties:

CreateDate

CreateUser

In the "Animal" class I can get the CreateDate to work by doing the following:

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreateDate { get; set; }
</code>```

This lets me generate the CreateDate in the database by setting the default value in the database as "GetDate()".

When an outside caller tries to "set" the CreateDate field on the OData service, it ignores the data being passed.

This makes it a "read only" property for outside callers.

I need to do something similar to the CreateUser except I need to set the CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name on the OData server.

If I try a private set then the OData service does not expose the property at all.

If I try a public set then the outside caller can change the property.

In the "Animal" constructor I have set the internal _CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name

I'm not sure how to set it on the server side.

答:
You could fake it out with an empty setter.  It will see the public set and generate the property in the OData entity.  Not the cleanest solution but it should work.</p>

```<code>public class Animal
{
     private string _createUser;

     public string CreateUser
     {
         get { return _createUser; }
         set { }
     }

     internal SetCreateUser(string user)
     {
         _createUser = user;
     }
}
</code>```

Body:
I have a model with a class called "Animal".

The "Animal" class has several properties but let's focus on the following properties:

CreateDate

CreateUser

In the "Animal" class I can get the CreateDate to work by doing the following:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreateDate { get; set; }

This lets me generate the CreateDate in the database by setting the default value in the database as "GetDate()".

When an outside caller tries to "set" the CreateDate field on the OData service, it ignores the data being passed.

This makes it a "read only" property for outside callers.

I need to do something similar to the CreateUser except I need to set the CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name on the OData server.

If I try a private set then the OData service does not expose the property at all.

If I try a public set then the outside caller can change the property.

In the "Animal" constructor I have set the internal _CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name

I'm not sure how to set it on the server side.

Body:
You could fake it out with an empty setter.  It will see the public set and generate the property in the OData entity.  Not the cleanest solution but it should work.

public class Animal
{
     private string _createUser;

     public string CreateUser
     {
         get { return _createUser; }
         set { }
     }

     internal SetCreateUser(string user)
     {
         _createUser = user;
     }
}


问:
C# null check chain in method call
I suppose method call chain below.

```<code>void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
    ObjectB b = CreateB();
    if (b != null)
    {
        ObjectA a = b.ToA();
        return a;
    }
    return null;
}
</code>```

If method call depth get deeper, null checking will be more overlapped.
Is there any good solution for this?

Modified

I changed example code. It can't solve my problem that change CreateA to constructor.
The problem is only unnecessary null check chaining overlapping.

```<code>void SetImage()
{
    UISprite image = GetSprite();
    if (image  != null)
    {
        image.spriteName = "hat";
    }
}

UISprite GetSprite()
{
    UISprite image = GetComponent<UISprite>();
    if (image  != null)
    {
        image.width = 100;
        image.height = 100;
        return image;
    }
    return null;
}
</code>```

答:
If you are using C# 6.0 or higher, you got an easy solution with Null conditional operators for this issue.

see this link

https://msdn.microsoft.com/en-au/library/dn986595.aspx?f=255&MSPPError=-2147217396&cs-save-lang=1&cs-lang=csharp#code-snippet-1

Title: C# null check chain in method call

Body:
I suppose method call chain below.

void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
    ObjectB b = CreateB();
    if (b != null)
    {
        ObjectA a = b.ToA();
        return a;
    }
    return null;
}

If method call depth get deeper, null checking will be more overlapped.
Is there any good solution for this?

Modified

I changed example code. It can't solve my problem that change CreateA to constructor.
The problem is only unnecessary null check chaining overlapping.

void SetImage()
{
    UISprite image = GetSprite();
    if (image  != null)
    {
        image.spriteName = "hat";
    }
}

UISprite GetSprite()
{
    UISprite image = GetComponent<UISprite>();
    if (image  != null)
    {
        image.width = 100;
        image.height = 100;
        return image;
    }
    return null;
}


问:
iOS custom keyboard blur view as background
This is really simple, but maybe not easy?

I'm trying to build a custom keyboard app for iOS, and so far I've made a concept work pretty well. But I really want to have the whole container/background view to be a blur view (frosted glass effect built in iOS), much like the system keyboard. It's very subtle, but I really want that effect.

Any idea how to apply it? Help!

答:
One solution I found (which is great but not ideal) is to simply set the background color of the ViewController to transparent. By giving it a color with alpha = 0, it has the same color as the system keyboard background.

But this doesn't let you go any further in terms of transparency, so the blur is very subtle.


问:
How can I perfectly center my image?
So I have an image on my website and I want to perfectly center it. I have tried many things but none have worked.

body{
background-color: black;
}

img {
  position: absolute;
  margin-top: 10%;
  text-align: center;
  height: 40%;
  z-index: -5
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="images/astronaut.png"></code>```

答:
body{
background-color: black;
}

img {
  position: absolute;
  text-align: center;
  height: 40%;
  top: 50%;
  left: 50%;
  z-index: -5
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="images/astronaut.png"></code>```

Title: How can I perfectly center my image?

Body:
body{
background-color: black;
}

img {
  position: absolute;
  text-align: center;
  height: 40%;
  top: 50%;
  left: 50%;
  z-index: -5
}

<img src="images/astronaut.png">


问:
find count of element over multiple array
Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2.
How to do it efficienlty with reasonable time and space complexity ?

my solution:
using dictionary:

```<code>from collections import defaultdict

L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']

d=defaultdict(int)

for i in L:
    d[i]+=1
for j in K:
    d[j]+=1

print d
result=[]
for key,val in d.iteritems():
  if val == 2:
     result.append(key)

print result
</code>```

My desired output would be:

```<code>['e', 'd', 'i', 'r']
</code>```

Can I get a better pythonic solution?

Thanks.

答:
This will work well with respect to space complexity, it's also pythonic, but I'm not too sure about the run time

```<code>set([x for x in L.extend(K) if L.extend(K).count(x) == 2])
</code>```

Notice that this returns a set and not a list!

Body:
Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2.
How to do it efficienlty with reasonable time and space complexity ?

my solution:
using dictionary:

from collections import defaultdict

L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']

d=defaultdict(int)

for i in L:
    d[i]+=1
for j in K:
    d[j]+=1

print d
result=[]
for key,val in d.iteritems():
  if val == 2:
     result.append(key)

print result

My desired output would be:

['e', 'd', 'i', 'r']

Can I get a better pythonic solution?

Thanks.

Body:
This will work well with respect to space complexity, it's also pythonic, but I'm not too sure about the run time

set([x for x in L.extend(K) if L.extend(K).count(x) == 2])

Notice that this returns a set and not a list!


问:
jQuery: Search and filter one table with two search bars simultaneously
I currently have a large table (~500 rows) that I would like to search with two search bars concurrently. By this I mean that I can enter a query into each and the results will match both of them.
I put a sample of the table and all of the javascript into a Jfiddle.

I have also tried using jets.js

```<code>var jets = new Jets({
    searchTag  : '#stateSearch', // which searchbox?
    contentTag : '#jetsContent', // where is the data?
    columns    : [2]             // which column to search? (index starts at 0)
});
</code>```

The same problem is reproduced with one search by Jets and one by the Jsfiddle code, as well as both with the Jsfiddle code. Two Jets instances on the same page is not supported.

答:
By merging the two functions and using a boolean to see if the query matches both the state field (in the state column) and the name field (in the name column).

   $('#stateSearch, #allSearch').on('keyup', function(e) {

   var stateFilter = $('#stateSearch').val();
   var nameFilter = $('#allSearch').val();

   var stateReg = new RegExp(stateFilter, 'i')
   var nameReg = new RegExp(nameFilter, 'i')

   $('#jetsContent').find('tr').hide().each(function() {
     var $me = $(this);

     var matchesState = $me.children('td:nth-child(3)').text().match(stateReg);
     var matchesName = $me.children('td:nth-child(2)').text().match(nameReg);

     if (matchesState && matchesName) {
       $me.show()
     }

   })

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="search" id="stateSearch" class="form-control" placeholder="2 Letter Code...">
<input type="search" id="allSearch" class="form-control" placeholder="Maria">

    <table>
      <tbody id="jetsContent">
        <tr>
          <td>Senator</td>
          <td>Alexander, Lamar</td>
          <td>TN</td>
          <td class="republican">Rep.</td>
          <td>455 Dirksen</td>
          <td>(202) 224-4944</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td>Barrasso, John</td>
          <td>WY</td>
          <td class="republican">Rep.</td>
          <td>307 Dirksen</td>
          <td>(202) 224-6441</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td>Bennet, Michael F.</td>
          <td>CO</td>
          <td class="democrat">Dem.</td>
          <td>261 Russell</td>
          <td>(202) 224-5852</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td>Blumenthal, Richard</td>
          <td>CT</td>
          <td class="democrat">Dem.</td>
          <td>706 Hart</td>
          <td>(202) 224-2823</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td>Blunt, Roy</td>
          <td>MO</td>
          <td class="republican">Rep.</td>
          <td>260 Russell</td>
          <td>(202) 224-5721</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td>Booker, Cory A.</td>
          <td>NJ</td>
          <td class="democrat">Dem.</td>
          <td>359 Dirksen</td>
          <td>(202) 224-3224</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td>Boozman, John</td>
          <td>AR</td>
          <td class="republican">Rep.</td>
          <td>141 Hart</td>
          <td>(202) 224-4843</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td>Brown, Sherrod</td>
          <td>OH</td>
          <td class="democrat">Dem.</td>
          <td>713 Hart</td>
          <td>(202) 224-2315</td>
          <td></td>
        </tr>
                <tr>
          <td>Senator</td>
          <td>joe shmoe</td>
          <td>OH</td>
          <td class="democrat">Dem.</td>
          <td>713 Hart</td>
          <td>(202) 224-2315</td>
          <td></td>
        </tr>
                <tr>
          <td>Senator</td>
          <td>whoever</td>
          <td>OH</td>
          <td class="democrat">Dem.</td>
          <td>713 Hart</td>
          <td>(202) 224-2315</td>
          <td></td>
        </tr>
      </tbody>
    </table></code>```

Body:
I currently have a large table (~500 rows) that I would like to search with two search bars concurrently. By this I mean that I can enter a query into each and the results will match both of them.
I put a sample of the table and all of the javascript into a Jfiddle.

I have also tried using jets.js

var jets = new Jets({
    searchTag  : '#stateSearch', // which searchbox?
    contentTag : '#jetsContent', // where is the data?
    columns    : [2]             // which column to search? (index starts at 0)
});

The same problem is reproduced with one search by Jets and one by the Jsfiddle code, as well as both with the Jsfiddle code. Two Jets instances on the same page is not supported.

Body:
By merging the two functions and using a boolean to see if the query matches both the state field (in the state column) and the name field (in the name column).

   $('#stateSearch, #allSearch').on('keyup', function(e) {

   var stateFilter = $('#stateSearch').val();
   var nameFilter = $('#allSearch').val();

   var stateReg = new RegExp(stateFilter, 'i')
   var nameReg = new RegExp(nameFilter, 'i')

   $('#jetsContent').find('tr').hide().each(function() {
     var $me = $(this);

     var matchesState = $me.children('td:nth-child(3)').text().match(stateReg);
     var matchesName = $me.children('td:nth-child(2)').text().match(nameReg);

     if (matchesState && matchesName) {
       $me.show()
     }

   })

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="search" id="stateSearch" class="form-control" placeholder="2 Letter Code...">
<input type="search" id="allSearch" class="form-control" placeholder="Maria">

    <table>
      <tbody id="jetsContent">
        <tr>
          <td>Senator</td>
          <td><a href="http://www.alexander.senate.gov/">Alexander, Lamar</a></td>
          <td>TN</td>
          <td class="republican">Rep.</td>
          <td>455 Dirksen</td>
          <td>(202) 224-4944</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td><a href="http://www.barrasso.senate.gov">Barrasso, John</a></td>
          <td>WY</td>
          <td class="republican">Rep.</td>
          <td>307 Dirksen</td>
          <td>(202) 224-6441</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td><a href="http://www.bennet.senate.gov">Bennet, Michael F.</a></td>
          <td>CO</td>
          <td class="democrat">Dem.</td>
          <td>261 Russell</td>
          <td>(202) 224-5852</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td><a href="http://www.blumenthal.senate.gov">Blumenthal, Richard</a></td>
          <td>CT</td>
          <td class="democrat">Dem.</td>
          <td>706 Hart</td>
          <td>(202) 224-2823</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td><a href="http://www.blunt.senate.gov">Blunt, Roy</a></td>
          <td>MO</td>
          <td class="republican">Rep.</td>
          <td>260 Russell</td>
          <td>(202) 224-5721</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td><a href="http://www.booker.senate.gov">Booker, Cory A.</a></td>
          <td>NJ</td>
          <td class="democrat">Dem.</td>
          <td>359 Dirksen</td>
          <td>(202) 224-3224</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td><a href="http://www.boozman.senate.gov/">Boozman, John</a></td>
          <td>AR</td>
          <td class="republican">Rep.</td>
          <td>141 Hart</td>
          <td>(202) 224-4843</td>
          <td></td>
        </tr>

        <tr>
          <td>Senator</td>
          <td><a href="http://www.brown.senate.gov/">Brown, Sherrod</a></td>
          <td>OH</td>
          <td class="democrat">Dem.</td>
          <td>713 Hart</td>
          <td>(202) 224-2315</td>
          <td></td>
        </tr>
                <tr>
          <td>Senator</td>
          <td><a href="http://www.brown.senate.gov/">joe shmoe</a></td>
          <td>OH</td>
          <td class="democrat">Dem.</td>
          <td>713 Hart</td>
          <td>(202) 224-2315</td>
          <td></td>
        </tr>
                <tr>
          <td>Senator</td>
          <td><a href="http://www.brown.senate.gov/">whoever</a></td>
          <td>OH</td>
          <td class="democrat">Dem.</td>
          <td>713 Hart</td>
          <td>(202) 224-2315</td>
          <td></td>
        </tr>
      </tbody>
    </table>


问:
Automatic translate transform with respect to borders in WPF
I need to have my TextBox translated by the vector, say X = 10, Y = 10 , when the  TextBox is placed in the top left corner of my window.
However, if it's situated in the right bottom corner, it should be translated by the vector X = -10, Y = -10.

I wonder, if it is possible to set the translate transform for a certain control according to its position (bottom-right/left / top-right/left) by a quick hack.

Do you have any ideas?

Cheers.

答:
You need to have two property XValue and YValue, based on the orientation you need to coerce the value using CoerceValueCallback of the dependency property.

http://msdn.microsoft.com/en-us/library/system.windows.coercevaluecallback.aspx
HTH


问:
Web Scraping with VBA (when HTML <> DOM)
I have having a horrible time scraping this particular webpage's data... Basically I can see the information that I need in the 'DOM Explorer' when I load the URL in a browser and hit F12 manually, but when I programmatically attempt to do the same (see below) the HTMLDoc does not contain the same information that I can see in the 'DOM Explorer'...

```<code>Public Sub testCode()

    Dim IE As SHDocVw.InternetExplorer
    Dim HTMLDoc As MSHTML.HTMLDocument
    Set IE = New SHDocVw.InternetExplorer
    With IE
        .navigate "https://www.wunderground.com/cgi-bin/findweather/getForecast?query=EIDW"
        While .Busy = True Or .ReadyState <> READYSTATE_COMPLETE: Wend
        Set HTMLDoc = .Document
    End With

End Sub
</code>```

Can someone please help me access the information in the 'DOM Explorer'? I know that HTML is not always what you see in a browser, but rather the instructions to create what you can see in the browser, but then there must be a way to programmatically create the DOM from the HTML...

Also, I believe that the data I am after is being generated by scripts or iFrames, but I have been unable to generate the data I am looking for from messing around with either....

UPDATE

See picture of DOM Explorer below:

答:
The outline:

Make GET XHR to https://www.wunderground.com/cgi-bin/findweather/getForecast?query=EIDW.

Extract the location from the HTML response line var query = 'zmw:' + '00000.271.03969'; and the key from the lines var citypage_options = {k: 'c991975b7f4186c0', ....

Make GET XHR using the location 00000.271.03969 and the key c991975b7f4186c0 to https://api-ak-aws.wunderground.com/api/c991975b7f4186c0/forecast10day/hourly10day/labels/conditions/astronomy10day/lang:en/units:metric/v:2.0/bestfct:1/q/zmw:00000.271.03969.json.

Parse JSON response (with e. g. VBA JSON parser) using Parse(), convert the necessary data using ToArray(), and output as tables to the worksheet(s).

Actually web browser do almost the same stuff each time you open that webpage.

You may use the below VBA code to parse response and output result. Import JSON.bas module into the VBA project for JSON processing.

Sub TestScrapeWunderground()

    Dim sContent As String
    Dim sKey As String
    Dim sLocation As String
    Dim vJSON As Variant
    Dim sState As String
    Dim oDays As Object
    Dim oHours As Object
    Dim vDay As Variant
    Dim vHour As Variant
    Dim aRows() As Variant
    Dim aHeader() As Variant

    ' GET XHR to retrieve location and key
    With CreateObject("MSXML2.ServerXMLHTTP")
        .Open "GET", "https://www.wunderground.com/cgi-bin/findweather/getForecast?query=EIDW", False
        .Send
        sContent = .responseText
    End With
    ' Extract location and key from HTML content
    sLocation = Split(Split(sContent, "var query = 'zmw:' + '", 2)(1), "'", 2)(0)
    sKey = Split(Split(sContent, vbTab & "k: '", 2)(1), "'", 2)(0)
    ' GET XHR to retrieve JSON data
    With CreateObject("MSXML2.ServerXMLHTTP")
        .Open "GET", "https://api-ak-aws.wunderground.com/api/" & sKey & "/forecast10day/hourly10day/labels/conditions/astronomy10day/lang:en/units:metric/v:2.0/bestfct:1/q/zmw:" & sLocation & ".json", False
        .Send
        sContent = .responseText
    End With
    ' Parse JSON response to data structure
    JSON.Parse sContent, vJSON, sState
    ' Populate dictionaries with daily and hourly forecast data
    Set oDays = CreateObject("Scripting.Dictionary")
    Set oHours = CreateObject("Scripting.Dictionary")
    For Each vDay In vJSON("forecast")("days")
        oDays(vDay("summary")) = ""
        For Each vHour In vDay("hours")
            oHours(vHour) = ""
        Next
    Next
    ' Convert daily forecast data to arrays
    JSON.ToArray oDays.Keys(), aRows, aHeader
    ' Output daily forecast data to table
    With Sheets(1)
        .Cells.Delete
        OutputArray .Cells(1, 1), aHeader
        Output2DArray .Cells(2, 1), aRows
        .Columns.AutoFit
    End With
    ' Convert hourly forecast data to arrays
    JSON.ToArray oHours.Keys(), aRows, aHeader
    ' Output hourly forecast data to table
    With Sheets(2)
        .Cells.Delete
        OutputArray .Cells(1, 1), aHeader
        Output2DArray .Cells(2, 1), aRows
        .Columns.AutoFit
    End With
    ' Convert response data to arrays
    JSON.ToArray Array(vJSON("response")), aRows, aHeader
    ' Output response transposed data to table
    With Sheets(3)
        .Cells.Delete
        Output2DArray .Cells(1, 1), WorksheetFunction.Transpose(aHeader)
        Output2DArray .Cells(1, 2), WorksheetFunction.Transpose(aRows)
        .Columns.AutoFit
    End With
    ' Convert current data to arrays
    JSON.ToArray Array(vJSON("current_observation")), aRows, aHeader
    ' Output current transposed data to table
    With Sheets(4)
        .Cells.Delete
        Output2DArray .Cells(1, 1), WorksheetFunction.Transpose(aHeader)
        Output2DArray .Cells(1, 2), WorksheetFunction.Transpose(aRows)
        .Columns.AutoFit
    End With
    ' Populate dictionary with daily astronomy data
    Set oDays = CreateObject("Scripting.Dictionary")
    For Each vDay In vJSON("astronomy")("days")
        oDays(vDay) = ""
    Next
    ' Convert daily astronomy data to arrays
    JSON.ToArray oDays.Keys(), aRows, aHeader
    ' Output daily astronomy transposed data to table
    With Sheets(5)
        .Cells.Delete
        Output2DArray .Cells(1, 1), WorksheetFunction.Transpose(aHeader)
        Output2DArray .Cells(1, 2), WorksheetFunction.Transpose(aRows)
        .Columns.AutoFit
    End With
    ' Convert hourly history data to arrays
    JSON.ToArray vJSON("history")("days")(0)("hours"), aRows, aHeader
    ' Output hourly history data to table
    With Sheets(6)
        .Cells.Delete
        OutputArray .Cells(1, 1), aHeader
        Output2DArray .Cells(2, 1), aRows
        .Columns.AutoFit
    End With
    MsgBox "Completed"

End Sub

Sub OutputArray(oDstRng As Range, aCells As Variant)

    With oDstRng
        .Parent.Select
        With .Resize( _
                1, _
                UBound(aCells) - LBound(aCells) + 1)
            .NumberFormat = "@"
            .Value = aCells
        End With
    End With

End Sub

Sub Output2DArray(oDstRng As Range, aCells As Variant)

    With oDstRng
        .Parent.Select
        With .Resize( _
                UBound(aCells, 1) - LBound(aCells, 1) + 1, _
                UBound(aCells, 2) - LBound(aCells, 2) + 1)
            .NumberFormat = "@"
            .Value = aCells
        End With
    End With

End Sub
```

<p>The second XHR returns JSON data, to make it clear how the necessary data is being extracted from it, you may save the JSON to file, copy the contents and paste it to any JSON viewer for further study. I use online tool http://jsonviewer.stack.hu, root element structure is shown below:</p>

<p><img src="https://i.stack.imgur.com/B2C3G.png" alt="JSON structure"></p>

<p>There are 6 main sections, the relevant part of the data is extracted and output to 6 worksheets (which have to be created manually before run):</p>

<pre class="lang-none prettyprint-override"><code>Sheet1 - Daily forecast
Sheet2 - Horly forecast
Sheet3 - Response data (transposed)
Sheet4 - Current data (transposed)
Sheet5 - Astronomy (transposed)
Sheet6 - Hourly history data
</code>```

Having that example you can extract the data you need from that JSON response.

Body:
I have having a horrible time scraping this particular webpage's data... Basically I can see the information that I need in the 'DOM Explorer' when I load the URL in a browser and hit F12 manually, but when I programmatically attempt to do the same (see below) the HTMLDoc does not contain the same information that I can see in the 'DOM Explorer'...

Public Sub testCode()

    Dim IE As SHDocVw.InternetExplorer
    Dim HTMLDoc As MSHTML.HTMLDocument
    Set IE = New SHDocVw.InternetExplorer
    With IE
        .navigate "https://www.wunderground.com/cgi-bin/findweather/getForecast?query=EIDW"
        While .Busy = True Or .ReadyState <> READYSTATE_COMPLETE: Wend
        Set HTMLDoc = .Document
    End With

End Sub

Can someone please help me access the information in the 'DOM Explorer'? I know that HTML is not always what you see in a browser, but rather the instructions to create what you can see in the browser, but then there must be a way to programmatically create the DOM from the HTML...

Also, I believe that the data I am after is being generated by scripts or iFrames, but I have been unable to generate the data I am looking for from messing around with either....

UPDATE

See picture of DOM Explorer below:

Body:
The outline:

Make GET XHR to https://www.wunderground.com/cgi-bin/findweather/getForecast?query=EIDW.

Extract the location from the HTML response line var query = 'zmw:' + '00000.271.03969'; and the key from the lines var citypage_options = {k: 'c991975b7f4186c0', ....

Make GET XHR using the location 00000.271.03969 and the key c991975b7f4186c0 to https://api-ak-aws.wunderground.com/api/c991975b7f4186c0/forecast10day/hourly10day/labels/conditions/astronomy10day/lang:en/units:metric/v:2.0/bestfct:1/q/zmw:00000.271.03969.json.

Parse JSON response (with e. g. VBA JSON parser) using Parse(), convert the necessary data using ToArray(), and output as tables to the worksheet(s).

Actually web browser do almost the same stuff each time you open that webpage.

You may use the below VBA code to parse response and output result. Import JSON.bas module into the VBA project for JSON processing.

Sub TestScrapeWunderground()

    Dim sContent As String
    Dim sKey As String
    Dim sLocation As String
    Dim vJSON As Variant
    Dim sState As String
    Dim oDays As Object
    Dim oHours As Object
    Dim vDay As Variant
    Dim vHour As Variant
    Dim aRows() As Variant
    Dim aHeader() As Variant

    ' GET XHR to retrieve location and key
    With CreateObject("MSXML2.ServerXMLHTTP")
        .Open "GET", "https://www.wunderground.com/cgi-bin/findweather/getForecast?query=EIDW", False
        .Send
        sContent = .responseText
    End With
    ' Extract location and key from HTML content
    sLocation = Split(Split(sContent, "var query = 'zmw:' + '", 2)(1), "'", 2)(0)
    sKey = Split(Split(sContent, vbTab & "k: '", 2)(1), "'", 2)(0)
    ' GET XHR to retrieve JSON data
    With CreateObject("MSXML2.ServerXMLHTTP")
        .Open "GET", "https://api-ak-aws.wunderground.com/api/" & sKey & "/forecast10day/hourly10day/labels/conditions/astronomy10day/lang:en/units:metric/v:2.0/bestfct:1/q/zmw:" & sLocation & ".json", False
        .Send
        sContent = .responseText
    End With
    ' Parse JSON response to data structure
    JSON.Parse sContent, vJSON, sState
    ' Populate dictionaries with daily and hourly forecast data
    Set oDays = CreateObject("Scripting.Dictionary")
    Set oHours = CreateObject("Scripting.Dictionary")
    For Each vDay In vJSON("forecast")("days")
        oDays(vDay("summary")) = ""
        For Each vHour In vDay("hours")
            oHours(vHour) = ""
        Next
    Next
    ' Convert daily forecast data to arrays
    JSON.ToArray oDays.Keys(), aRows, aHeader
    ' Output daily forecast data to table
    With Sheets(1)
        .Cells.Delete
        OutputArray .Cells(1, 1), aHeader
        Output2DArray .Cells(2, 1), aRows
        .Columns.AutoFit
    End With
    ' Convert hourly forecast data to arrays
    JSON.ToArray oHours.Keys(), aRows, aHeader
    ' Output hourly forecast data to table
    With Sheets(2)
        .Cells.Delete
        OutputArray .Cells(1, 1), aHeader
        Output2DArray .Cells(2, 1), aRows
        .Columns.AutoFit
    End With
    ' Convert response data to arrays
    JSON.ToArray Array(vJSON("response")), aRows, aHeader
    ' Output response transposed data to table
    With Sheets(3)
        .Cells.Delete
        Output2DArray .Cells(1, 1), WorksheetFunction.Transpose(aHeader)
        Output2DArray .Cells(1, 2), WorksheetFunction.Transpose(aRows)
        .Columns.AutoFit
    End With
    ' Convert current data to arrays
    JSON.ToArray Array(vJSON("current_observation")), aRows, aHeader
    ' Output current transposed data to table
    With Sheets(4)
        .Cells.Delete
        Output2DArray .Cells(1, 1), WorksheetFunction.Transpose(aHeader)
        Output2DArray .Cells(1, 2), WorksheetFunction.Transpose(aRows)
        .Columns.AutoFit
    End With
    ' Populate dictionary with daily astronomy data
    Set oDays = CreateObject("Scripting.Dictionary")
    For Each vDay In vJSON("astronomy")("days")
        oDays(vDay) = ""
    Next
    ' Convert daily astronomy data to arrays
    JSON.ToArray oDays.Keys(), aRows, aHeader
    ' Output daily astronomy transposed data to table
    With Sheets(5)
        .Cells.Delete
        Output2DArray .Cells(1, 1), WorksheetFunction.Transpose(aHeader)
        Output2DArray .Cells(1, 2), WorksheetFunction.Transpose(aRows)
        .Columns.AutoFit
    End With
    ' Convert hourly history data to arrays
    JSON.ToArray vJSON("history")("days")(0)("hours"), aRows, aHeader
    ' Output hourly history data to table
    With Sheets(6)
        .Cells.Delete
        OutputArray .Cells(1, 1), aHeader
        Output2DArray .Cells(2, 1), aRows
        .Columns.AutoFit
    End With
    MsgBox "Completed"

End Sub

Sub OutputArray(oDstRng As Range, aCells As Variant)

    With oDstRng
        .Parent.Select
        With .Resize( _
                1, _
                UBound(aCells) - LBound(aCells) + 1)
            .NumberFormat = "@"
            .Value = aCells
        End With
    End With

End Sub

Sub Output2DArray(oDstRng As Range, aCells As Variant)

    With oDstRng
        .Parent.Select
        With .Resize( _
                UBound(aCells, 1) - LBound(aCells, 1) + 1, _
                UBound(aCells, 2) - LBound(aCells, 2) + 1)
            .NumberFormat = "@"
            .Value = aCells
        End With
    End With

End Sub

The second XHR returns JSON data, to make it clear how the necessary data is being extracted from it, you may save the JSON to file, copy the contents and paste it to any JSON viewer for further study. I use online tool http://jsonviewer.stack.hu, root element structure is shown below:

There are 6 main sections, the relevant part of the data is extracted and output to 6 worksheets (which have to be created manually before run):

Sheet1 - Daily forecast
Sheet2 - Horly forecast
Sheet3 - Response data (transposed)
Sheet4 - Current data (transposed)
Sheet5 - Astronomy (transposed)
Sheet6 - Hourly history data

Having that example you can extract the data you need from that JSON response.


问:
Java URLDecode fails while PHP urldecode partially decodes
Here is a malformed URL http%3A%2F%2Fexample.com%2.

With PHP

```<code>var_dump(urldecode("http%3A%2F%2Fexample.com%2"));
</code>```

I get

```<code>string(20) "http://example.com%2"
</code>```

However, when using Java

```<code>URLDecoder.decode("http%3A%2F%2Fexample.com%2", StandardCharsets.UTF_8.toString());
</code>```

I get

```<code>java.lang.IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern
</code>```

This is a simplified URL to showcase my example. How can I still parse as much of the URL as possible in Java, even if it is malformed? Basically, return what PHP is returning.

答:
What is the natural URL?
I mean, at the end, there is 2%, what is the natural meanning of http%3A%2F%2Fexample.com%2 ?
Is it http://example.com/ ?
It seems that a character was stripped at the end.</p>

Body:
Here is a malformed URL http%3A%2F%2Fexample.com%2.

With PHP

var_dump(urldecode("http%3A%2F%2Fexample.com%2"));

I get

string(20) "http://example.com%2"

However, when using Java

URLDecoder.decode("http%3A%2F%2Fexample.com%2", StandardCharsets.UTF_8.toString());

I get

java.lang.IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern

This is a simplified URL to showcase my example. How can I still parse as much of the URL as possible in Java, even if it is malformed? Basically, return what PHP is returning.


问:
Bootstrap button sizing and alignment
This is what I have so far http://www.bootply.com/SDIQQr0dZJ or    https://jsfiddle.net/sjgz57b8/

```<code><div class="panel panel-default">
 <div class="panel-heading">
           <strong>myusername</strong>
    <div class="btn-group btn-group-sm pull-right">
       <button type="button" class="btn btn-danger">Dislike</button>
       <button type="button" class="btn btn-success">Like</button>
    </div>
 </div>
     <div class="panel-body">
              Panel content
     </div>
 </div>
</code>```

I'm trying to make the buttons fit within that space and centered vertically, but I already added the btn-group-sm class so I'm not sure what else I can do. I'm also trying to make the dislike button the same width as the like button. Thanks for any help

答:
For proper alignment of button'

Add to .panel-heading

```<code> .panel-heading{
   display:table;
   width:100%;
 }
</code>```

Making both buttons the same width

The buttons are styled to display inline-block which means the word "dislike" has greater length than the word "like". You can set both width of the button. I suggest adding a class named "button" to each button and set the width to avoid other elements being affected

```<code> .button{
   width:50px;
 }
</code>```

#logo .short {
  position: relative;
  margin-top: 0;
  padding: 0 10px;
  font-size: 36px;
  display: inline-block;
  text-transform: uppercase;
  transition: all .3s ease-out;
  border: solid black;
}

.short:after {
  position: relative;
  margin-left: -20px;
  content: "est1";
  opacity: 0;
  -webkit-transition: all .3s ease-out;
}

.short:hover:after {
  opacity: 1;
  display: inline-block;
  margin-left: -10px;
}

#logo span {
  position: relative;
  transition: margin .3s ease-out;
}

span:hover {
  margin-left: 20px;
}

span:after {
  position: relative;
  margin-left: -20px;
  content: "est2";
  opacity: 0;
  -webkit-transition: all .3s ease-out;
}

span:hover:after {
  opacity: 1;
  margin-left: 0px;
}

.panel-heading {
  display: table;
  width: 100%;
}

.button {
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="panel panel-default">
  <div class="panel-heading">
    <strong>myusername</strong>
    <div class="btn-group btn-group-sm pull-right">
      <button type="button" class="btn btn-danger button">Dislike</button>
      <button type="button" class="btn btn-success button">Like</button>
    </div>
  </div>
  <div class="panel-body">
    Panel content
  </div>
</div></code>```

Title: Bootstrap button sizing and alignment

Body:
This is what I have so far http://www.bootply.com/SDIQQr0dZJ or    https://jsfiddle.net/sjgz57b8/

           myusername

       <button type="button" class="btn btn-danger">Dislike</button>
       <button type="button" class="btn btn-success">Like</button>

              Panel content

I'm trying to make the buttons fit within that space and centered vertically, but I already added the btn-group-sm class so I'm not sure what else I can do. I'm also trying to make the dislike button the same width as the like button. Thanks for any help

Body:
For proper alignment of button'

Add to .panel-heading

 .panel-heading{
   display:table;
   width:100%;
 }

Making both buttons the same width

The buttons are styled to display inline-block which means the word "dislike" has greater length than the word "like". You can set both width of the button. I suggest adding a class named "button" to each button and set the width to avoid other elements being affected

 .button{
   width:50px;
 }

#logo .short {
  position: relative;
  margin-top: 0;
  padding: 0 10px;
  font-size: 36px;
  display: inline-block;
  text-transform: uppercase;
  transition: all .3s ease-out;
  border: solid black;
}

.short:after {
  position: relative;
  margin-left: -20px;
  content: "est1";
  opacity: 0;
  -webkit-transition: all .3s ease-out;
}

.short:hover:after {
  opacity: 1;
  display: inline-block;
  margin-left: -10px;
}

#logo span {
  position: relative;
  transition: margin .3s ease-out;
}

span:hover {
  margin-left: 20px;
}

span:after {
  position: relative;
  margin-left: -20px;
  content: "est2";
  opacity: 0;
  -webkit-transition: all .3s ease-out;
}

span:hover:after {
  opacity: 1;
  margin-left: 0px;
}

.panel-heading {
  display: table;
  width: 100%;
}

.button {
  width: 50px;
}

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="panel panel-default">
  <div class="panel-heading">
    <strong>myusername</strong>
    <div class="btn-group btn-group-sm pull-right">
      <button type="button" class="btn btn-danger button">Dislike</button>
      <button type="button" class="btn btn-success button">Like</button>
    </div>
  </div>
  <div class="panel-body">
    Panel content
  </div>
</div>


问:
Environment properties not getting read in spring boot
I have a utility class to read the environment variables.

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public final class PropertyUtil {

    /** The system environment. */
    private static Environment environment;

    public static String getConfigProp(final String key) {
        return environment.getProperty(key);
    }

    @Autowired
    public void setEnvironment(Environment environment) {
        PropertyUtil.environment = environment;
    }
}
</code>```

And I use it in one bean while initialization. The problem is that it runs file if I deploy the war file on tomcat but if I run the same application as a spring boot application from eclipse, it does not read the environment properties and the return values are therefore null.

Any idea what could be the cause of this problem?

答:
```<code>package com.myspringboot.controller;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public  class PropertyUtil  implements EnvironmentAware {

    /** The system environment. */
    public  Environment environment;

    public  String getConfigProp(String key) {
        return environment.getProperty(key);
    }
    @Override
    public void setEnvironment(Environment arg0) {
        environment=arg0;

    }
}
    @Test
    public void testProperty(){
/*      String driver= System.getenv().get("spring.datasource.driverClassName");
        System.out.println(driver);
        System.out.println(PropertyUtil.environment);*/
        String str= propertyUtil.getConfigProp("spring.datasource.driverClassName");
        System.out.println(str);
    }
</code>```

Body:
I have a utility class to read the environment variables.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public final class PropertyUtil {

    /** The system environment. */
    private static Environment environment;

    public static String getConfigProp(final String key) {
        return environment.getProperty(key);
    }

    @Autowired
    public void setEnvironment(Environment environment) {
        PropertyUtil.environment = environment;
    }
}

And I use it in one bean while initialization. The problem is that it runs file if I deploy the war file on tomcat but if I run the same application as a spring boot application from eclipse, it does not read the environment properties and the return values are therefore null.

Any idea what could be the cause of this problem?


问:
What exactly is RESTful programming?
What exactly is RESTful programming?</p>

答:
Here is my basic outline of REST. I tried to demonstrate the thinking behind each of the components in a RESTful architecture so that understanding the concept is more intuitive. Hopefully this helps demystify REST for some people!

REST (Representational State Transfer) is a design architecture that outlines how networked resources (i.e. nodes that share information) are designed and addressed. In general, a RESTful architecture makes it so that the client (the requesting machine) and the server (the responding machine) can request to read, write, and update data without the client having to know how the server operates and the server can pass it back without needing to know anything about the client. Okay, cool...but how do we do this in practice?

The most obvious requirement is that there needs to be a universal language of some sort so that the server can tell the client what it is trying to do with the request and for the server to respond.

But to find any given resource and then tell the client where that resource lives, there needs to be a universal way of pointing at resources. This is where Universal Resource Identifiers (URIs) come in; they are basically unique addresses to find the resources.

But the REST architecture doesn’t end there! While the above fulfills the basic needs of what we want, we also want to have an architecture that supports high volume traffic since any given server usually handles responses from a number of clients. Thus, we don’t want to overwhelm the server by having it remember information about previous requests.

Therefore, we impose the restriction that each request-response pair between the client and the server is independent, meaning that the server doesn’t have to remember anything about previous requests (previous states of the client-server interaction) to respond to a new request. This means that we want our interactions to be stateless.

To further ease the strain on our server from redoing computations that have already been recently done for a given client, REST also allows caching. Basically, caching means to take a snapshot of the initial response provided to the client. If the client makes the same request again, the server can provide the client with the snapshot rather than redo all of the computations that were necessary to create the initial response. However, since it is a snapshot, if the snapshot has not expired--the server sets an expiration time in advance--and the response has been updated since the initial cache (i.e. the request would give a different answer than the cached response), the client will not see the updates until the cache expires (or the cache is cleared) and the response is rendered from scratch again.

The last thing that you’ll often here about RESTful architectures is that they are layered. We have actually already been implicitly discussing this requirement in our discussion of the interaction between the client and server. Basically, this means that each layer in our system interacts only with adjacent layers. So in our discussion, the client layer interacts with our server layer (and vice versa), but there might be other server layers that help the primary server process a request that the client does not directly communicate with. Rather, the server passes on the request as necessary.

Now, if all of this sounds familiar, then great. The Hypertext Transfer Protocol (HTTP), which defines the communication protocol via the World Wide Web is an implementation of the abstract notion of RESTful architecture (or an implementation of the abstract REST class if you're an OOP fanatic like me). In this implementation of REST, the client and server interact via GET, POST, PUT, DELETE, etc., which are part of the universal language and the resources can be pointed to using URLs.

OwnerDisplayName: hasen j

Title: What exactly is RESTful programming?

Body: What exactly is RESTful programming?

LastEditorDisplayName: Emil H


问:
pandas: New column by combining numbers of two columns as strings
I want to combine the two columns 'Day/Night?' and 'Abbreviated' as strings to get another column that displays the numbers in the form of the 'Abbreviated' value, followed by the 'Day/Night?' value.

The DataFrame I currently have:

```<code>    Route       Date        Collection Type Tonnage Day/Night?  Abbreviated
0   321-2_2     2014-07-11  2               12.96   2           1107
0   325-1_1     2014-07-14  1               1.85    1           1407
1   321-323_2   2014-07-14  1               4.42    2           1407
1   325-2_1     2014-07-15  3               13.20   1           1507
2   321-2_2     2014-07-15  1               3.25    2           1507
</code>```

For example, I would have the extra column output as:

```<code>11072
14071
14072
15071
15072
</code>```

I have tried this code:

```<code>daily['New'] = daily['Abbreviated']+str(daily['Day/Night?'])
</code>```

where Daily is the name of the DF.

The output is strange though:

```<code>New
11070 2\n0 1\n1 2\n1 1\n2 ...
14070 2\n0 1\n1 2\n1 1\n2 ...
14070 2\n0 1\n1 2\n1 1\n2 ...
15070 2\n0 1\n1 2\n1 1\n2 ...
15070 2\n0 1\n1 2\n1 1\n2 ...
</code>```

Does anyone have any advice on how I could do this?

thanks.

答:
You need to use astype for type conversion:

```<code>df['Abbreviated'].astype(str) + df['Day/Night?'].astype(str)

#0    11072
#0    14071
#1    14072
#1    15071
#2    15072
#dtype: object
</code>```

Body:
I want to combine the two columns 'Day/Night?' and 'Abbreviated' as strings to get another column that displays the numbers in the form of the 'Abbreviated' value, followed by the 'Day/Night?' value.

The DataFrame I currently have:

    Route       Date        Collection Type Tonnage Day/Night?  Abbreviated
0   321-2_2     2014-07-11  2               12.96   2           1107
0   325-1_1     2014-07-14  1               1.85    1           1407
1   321-323_2   2014-07-14  1               4.42    2           1407
1   325-2_1     2014-07-15  3               13.20   1           1507
2   321-2_2     2014-07-15  1               3.25    2           1507

For example, I would have the extra column output as:

11072
14071
14072
15071
15072

I have tried this code:

daily['New'] = daily['Abbreviated']+str(daily['Day/Night?'])

where Daily is the name of the DF.

The output is strange though:

New
11070 2\n0 1\n1 2\n1 1\n2 ...
14070 2\n0 1\n1 2\n1 1\n2 ...
14070 2\n0 1\n1 2\n1 1\n2 ...
15070 2\n0 1\n1 2\n1 1\n2 ...
15070 2\n0 1\n1 2\n1 1\n2 ...

Does anyone have any advice on how I could do this?

thanks.

Body:
You need to use astype for type conversion:

df['Abbreviated'].astype(str) + df['Day/Night?'].astype(str)

#0    11072
#0    14071
#1    14072
#1    15071
#2    15072
#dtype: object


问:
Initialise string function result?
I've just been debugging a problem with a function that returns a string that has got me worried. I've always assumed that the implicit Result variable for functions that return a string would be empty at the start of the function call, but the following (simplified) code produced an unexpected result:

```<code>function TMyObject.GenerateInfo: string;

        procedure AppendInfo(const AppendStr: string);
        begin
          if(Result > '') then
            Result := Result + #13;
          Result := Result + AppendStr;
        end;

begin
  if(ACondition) then
    AppendInfo('Some Text');
end;
</code>```

Calling this function multiple times resulted in:

```<code>"Some Text"
</code>```

the first time,

```<code>"Some Text"
"Some Text"
</code>```

the second time,

```<code>"Some Text"
"Some Text"
"Some Text"
</code>```

the third time, etc.

To fix it I had to initialise the Result:

```<code>begin
  Result := '';
  if(ACondition) then
    AppendInfo('Some Text');
end;
</code>```

Is it necessary to initialise a string function result? Why (technically)? Why does the compiler not emit a warning "W1035 Return value of function 'xxx' might be undefined" for string functions? Do I need to go through all my code to make sure a value is set as it is not reliable to expect an empty string from a function if the result is not explicitly set?

I've tested this in a new test application and the result is the same.

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
  i: integer;
  S: string;
begin
  for i := 1 to 5 do
    S := GenerateInfo;
  ShowMessage(S); // 5 lines!
end;
</code>```

答:
Alex's answer is nearly always right and it answers why I was seeing the strange behaviour that I was, but it isn't the whole story.

The following, compiled without optimisation, produces the expected result of sTemp being an empty string. If you swap the function out for the procedure call you get a different result.

There seems to be a different rule for the actual program unit.

Admittedly this is a corner case.

```<code>program Project1;

{$APPTYPE CONSOLE}

uses System.SysUtils;

  function PointlessFunction: string;
  begin
  end;

  procedure PointlessProcedure(var AString: string);
  begin
  end;

var
  sTemp: string;
begin
  sTemp := '1234';
  sTemp := PointlessFunction;
  //PointlessProcedure(sTemp);
  WriteLn('Result:' + sTemp);
  ReadLn;
end.
</code>```

Title: Initialise string function result?

Body:
I've just been debugging a problem with a function that returns a string that has got me worried. I've always assumed that the implicit Result variable for functions that return a string would be empty at the start of the function call, but the following (simplified) code produced an unexpected result:

function TMyObject.GenerateInfo: string;

        procedure AppendInfo(const AppendStr: string);
        begin
          if(Result > '') then
            Result := Result + #13;
          Result := Result + AppendStr;
        end;

begin
  if(ACondition) then
    AppendInfo('Some Text');
end;

Calling this function multiple times resulted in:

"Some Text"

the first time,

"Some Text"
"Some Text"

the second time,

"Some Text"
"Some Text"
"Some Text"

the third time, etc.

To fix it I had to initialise the Result:

begin
  Result := '';
  if(ACondition) then
    AppendInfo('Some Text');
end;

Is it necessary to initialise a string function result? Why (technically)? Why does the compiler not emit a warning "W1035 Return value of function 'xxx' might be undefined" for string functions? Do I need to go through all my code to make sure a value is set as it is not reliable to expect an empty string from a function if the result is not explicitly set?

I've tested this in a new test application and the result is the same.

procedure TForm1.Button1Click(Sender: TObject);
var
  i: integer;
  S: string;
begin
  for i := 1 to 5 do
    S := GenerateInfo;
  ShowMessage(S); // 5 lines!
end;

Body:
Alex's answer is nearly always right and it answers why I was seeing the strange behaviour that I was, but it isn't the whole story.

The following, compiled without optimisation, produces the expected result of sTemp being an empty string. If you swap the function out for the procedure call you get a different result.

There seems to be a different rule for the actual program unit.

Admittedly this is a corner case.

program Project1;

{$APPTYPE CONSOLE}

uses System.SysUtils;

  function PointlessFunction: string;
  begin
  end;

  procedure PointlessProcedure(var AString: string);
  begin
  end;

var
  sTemp: string;
begin
  sTemp := '1234';
  sTemp := PointlessFunction;
  //PointlessProcedure(sTemp);
  WriteLn('Result:' + sTemp);
  ReadLn;
end.


问:
Xamarin - apk App Size
So, after all the hard-work developing the app using Xamarin.Forms, when I tried to create a release build today, I was shocked to see the app size is ~25MB - ~31MB (after SDK Only Linking, ProGuard, Creating apk for each abi). My resource folder is only in KBs. The apk actually was just 5MB in debug mode and was so happy to see it. I later realized that this is because of the option "Use Shared Runtime" which we are not supposed to use in Release Mode.

I then tried creating a blank Xamarin.Android app, but the release build with Linking SDK & User Assemblies, ProGuard, APK for each abi is still ~8MB to ~13MB.

Per the below link the minimum size is 2.9MB with the Hello World app, however I am unable to create such size. https://developer.xamarin.com/guides/android/advanced_topics/application_package_sizes/

For my app and the blank app I created, the necessary dlls seem to be high (example mscorlib.dll is 2.2mb etc, where as the link says after linking it will become 1 mb) Here is what I see as my assembly folder after extracting the apk

In one of the recent Microsoft tech conferences I happened to know that "9 News" app (link below) was built using xamarin, and the creators were present on the stage. However I was surprised with it's app size. It is only 5.85 MB. I am unsure how that is achieved?

Can any one help me with these?

https://play.google.com/store/apps/details?id=nineNewsAlerts.nine.com

I am also curious to know if Microsoft doing something to improve app package sizes? Or will this be resolved if they bring .NET core to xamarin?

答:
I understand your problem when you create a mobile app, you always wanted to create small size apk file which can easily be downloaded and used by users.
For this try to reduce the code duplication in your project and reduce all the image size.
Use following steps, it will help you to reduce your apk size.
Right Click on droid properties.
Open Android Options ->
Click on packaging then check generate one package (.apk) per selected ABI.
Check Multi-Dex and proguard options as well.
Now move to Linker option, select SDK assemblies Only under Linking dropdown.
Now move to Advance tab-
Check all the option under Supported architecture.
Save all the setting and keep you project in release mode clean and build your project then you can create reduced size of apk file.
Use following link for more info.

http://motzcod.es/post/112072508362/how-to-keep-your-android-app-size-down

Title: Xamarin - apk App Size


问:
How would I direct all traffic that hasn't logged in to django allauth login
Want to direct all un-logged in traffic to the login page. How would I go about doing this? I don't want visitors to be able to see the site at all if they are not logged in. As well, the allauth signup page should not be able to be accessed either. Users will be pre-registered for the site. I'm fairly new to django and would not want to abandon allauth as I have it working.</p>

答:
In your urls.py file import following:

```<code>from django.contrib.auth.decorators import login_required
</code>```

Then all you have to do is to add this decorator before the views in your urlpatterns. Something like this:

```<code>urlpatterns = [
    url(r'^index/$', login_required(views.index), name='home'),
    url(r'^update-profile/$', login_required(views.update_profile), name="update_profile"),
]
</code>```

As long as you have defined registration model and have login.html page setup, this should direct all the traffic to login page automatically.

Body:
In your urls.py file import following:

from django.contrib.auth.decorators import login_required

Then all you have to do is to add this decorator before the views in your urlpatterns. Something like this:

urlpatterns = [
    url(r'^index/$', login_required(views.index), name='home'),
    url(r'^update-profile/$', login_required(views.update_profile), name="update_profile"),
]

As long as you have defined registration model and have login.html page setup, this should direct all the traffic to login page automatically.


问:
How to use a DocumentDB(MongoDB) connection string as an Environment variable in an Azure Resource Management Template
I want to use a DocumentDB(MongoDB) connection string as an environment variable in an Azure Resource Management Template. Forexample i have a resource group which has a wep app and a DocumentDB(MongoDB) database.

```<code>"siteConfig": {
          "appSettings": [
            {
              "name": "db",
              "value": "connection string"
            }
          ]
        }
</code>```

How can i assign an environment variable to a connection string in template?

答:
ARM template supports listKeys and list{Value} function, more details we can refer to ARM template function.
We can find DocumentDB list connection strings API, so we can use listconnectionstrings function to get documentdb connection string in the ARM template.

```<code>"appSettings": [
            {
              "name": "db",
              "value": " [listConnectionStrings(resourceId('Microsoft.DocumentDb/databaseAccounts', parameters('documentdb')), '2015-04-08').connectionStrings[0].connectionString]"
            }
</code>```

It works correct on my side. If we want to add appsetting for WebApp, we also can do with following code

```<code>  "resources": [
      {
          "name": "appsettings",
          "type": "config",
          "apiVersion": "2015-08-01",
          "dependsOn": [
              "[resourceId('Microsoft.Web/sites', variables('webSiteName'))]"
          ],
          "tags": {
              "displayName": "appsetting"
          },
        "properties": {
          "db": "[listConnectionStrings(resourceId('Microsoft.DocumentDb/databaseAccounts', parameters('documentdb')), '2015-04-08').connectionStrings[0].connectionString]"
        }
      }

  ]
</code>```

Check the result from the Azure portal.

Update:

ARM template demo code

```<code>{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "hostingPlanName": {
      "type": "string",
      "minLength": 1
    },
    "documentdb": {
      "type": "string",
      "minLength": 1
    },
    "skuName": {
      "type": "string",
      "defaultValue": "S1",
      "allowedValues": [
        "F1",
        "D1",
        "B1",
        "B2",
        "B3",
        "S1",
        "S2",
        "S3",
        "P1",
        "P2",
        "P3",
        "P4"
      ],
      "metadata": {
        "description": "Describes plan's pricing tier and instance size. Check details at https://azure.microsoft.com/en-us/pricing/details/app-service/"
      }
    },
    "skuCapacity": {
      "type": "int",
      "defaultValue": 1,
      "minValue": 1,
      "metadata": {
        "description": "Describes plan's instance count"
      }
    }
  },
  "variables": {
    "webSiteName": "[concat('webSite', uniqueString(resourceGroup().id))]",
    "docDbName": "tomdocumentdb",
    "storageAccountId": "[concat(resourceGroup().id,'/providers/Microsoft.Storage/storageAccounts/', parameters('storageAccountName'))]"
  },
  "resources": [
    {
      "apiVersion": "2015-08-01",
      "name": "[parameters('hostingPlanName')]",
      "type": "Microsoft.Web/serverfarms",
      "location": "[resourceGroup().location]",
      "tags": {
        "displayName": "HostingPlan"
      },
      "sku": {
        "name": "[parameters('skuName')]",
        "capacity": "[parameters('skuCapacity')]"
      },
      "properties": {
        "name": "[parameters('hostingPlanName')]"
      }
    },
    {
      "apiVersion": "2015-08-01",
      "name": "[variables('webSiteName')]",
      "type": "Microsoft.Web/sites",
      "location": "[resourceGroup().location]",
      "tags": {
        "[concat('hidden-related:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
        "displayName": "Website"
      },
      "dependsOn": [
        "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
      ],
      "properties": {
        "name": "[variables('webSiteName')]",
        "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', parameters('hostingPlanName'))]"
      },

      "resources": [
          {
              "name": "appsettings",
              "type": "config",
              "apiVersion": "2015-08-01",
              "dependsOn": [
                  "[resourceId('Microsoft.Web/sites', variables('webSiteName'))]"
              ],
              "tags": {
                  "displayName": "appsetting"
              },
            "properties": {
              "db": "[listConnectionStrings(resourceId('Microsoft.DocumentDb/databaseAccounts', parameters('documentdb')), '2015-04-08').connectionStrings[0].connectionString]"
            }
          }

      ]
    }
  ]
}
</code>```

Paramter file

```<code>{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "hostingPlanName": {
            "value": "tomtest" //your hostingplan name
        },
        "skuName": {
            "value": "B1"
        },
        "documentdb": {
            "value": "tomdocument" // your documentdb name
        }

    }
}
</code>```

Body:
I want to use a DocumentDB(MongoDB) connection string as an environment variable in an Azure Resource Management Template. Forexample i have a resource group which has a wep app and a DocumentDB(MongoDB) database.

"siteConfig": {
          "appSettings": [
            {
              "name": "db",
              "value": "connection string"
            }
          ]
        }

How can i assign an environment variable to a connection string in template?

Body:
ARM template supports listKeys and list{Value} function, more details we can refer to ARM template function.
We can find DocumentDB list connection strings API, so we can use listconnectionstrings function to get documentdb connection string in the ARM template.

"appSettings": [
            {
              "name": "db",
              "value": " [listConnectionStrings(resourceId('Microsoft.DocumentDb/databaseAccounts', parameters('documentdb')), '2015-04-08').connectionStrings[0].connectionString]"
            }

It works correct on my side. If we want to add appsetting for WebApp, we also can do with following code

  "resources": [
      {
          "name": "appsettings",
          "type": "config",
          "apiVersion": "2015-08-01",
          "dependsOn": [
              "[resourceId('Microsoft.Web/sites', variables('webSiteName'))]"
          ],
          "tags": {
              "displayName": "appsetting"
          },
        "properties": {
          "db": "[listConnectionStrings(resourceId('Microsoft.DocumentDb/databaseAccounts', parameters('documentdb')), '2015-04-08').connectionStrings[0].connectionString]"
        }
      }

  ]

Check the result from the Azure portal.

Update:

ARM template demo code

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "hostingPlanName": {
      "type": "string",
      "minLength": 1
    },
    "documentdb": {
      "type": "string",
      "minLength": 1
    },
    "skuName": {
      "type": "string",
      "defaultValue": "S1",
      "allowedValues": [
        "F1",
        "D1",
        "B1",
        "B2",
        "B3",
        "S1",
        "S2",
        "S3",
        "P1",
        "P2",
        "P3",
        "P4"
      ],
      "metadata": {
        "description": "Describes plan's pricing tier and instance size. Check details at https://azure.microsoft.com/en-us/pricing/details/app-service/"
      }
    },
    "skuCapacity": {
      "type": "int",
      "defaultValue": 1,
      "minValue": 1,
      "metadata": {
        "description": "Describes plan's instance count"
      }
    }
  },
  "variables": {
    "webSiteName": "[concat('webSite', uniqueString(resourceGroup().id))]",
    "docDbName": "tomdocumentdb",
    "storageAccountId": "[concat(resourceGroup().id,'/providers/Microsoft.Storage/storageAccounts/', parameters('storageAccountName'))]"
  },
  "resources": [
    {
      "apiVersion": "2015-08-01",
      "name": "[parameters('hostingPlanName')]",
      "type": "Microsoft.Web/serverfarms",
      "location": "[resourceGroup().location]",
      "tags": {
        "displayName": "HostingPlan"
      },
      "sku": {
        "name": "[parameters('skuName')]",
        "capacity": "[parameters('skuCapacity')]"
      },
      "properties": {
        "name": "[parameters('hostingPlanName')]"
      }
    },
    {
      "apiVersion": "2015-08-01",
      "name": "[variables('webSiteName')]",
      "type": "Microsoft.Web/sites",
      "location": "[resourceGroup().location]",
      "tags": {
        "[concat('hidden-related:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
        "displayName": "Website"
      },
      "dependsOn": [
        "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
      ],
      "properties": {
        "name": "[variables('webSiteName')]",
        "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', parameters('hostingPlanName'))]"
      },

      "resources": [
          {
              "name": "appsettings",
              "type": "config",
              "apiVersion": "2015-08-01",
              "dependsOn": [
                  "[resourceId('Microsoft.Web/sites', variables('webSiteName'))]"
              ],
              "tags": {
                  "displayName": "appsetting"
              },
            "properties": {
              "db": "[listConnectionStrings(resourceId('Microsoft.DocumentDb/databaseAccounts', parameters('documentdb')), '2015-04-08').connectionStrings[0].connectionString]"
            }
          }

      ]
    }
  ]
}

Paramter file

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "hostingPlanName": {
            "value": "tomtest" //your hostingplan name
        },
        "skuName": {
            "value": "B1"
        },
        "documentdb": {
            "value": "tomdocument" // your documentdb name
        }

    }
}


问:
Method to block image, flash, style when use gecko navigate?
I need to make a bot  "get video link" from abc..

I use httpwebrequest and httprespone but I realize this website has ajax text and httpwebsite can't get it.

-> I decide to use geckowebrowser

Step by step

1. use geckowebrowser documentcomplete event and use navigate to website

2. use geckobutton to click and wait 5 seconds to get ajax text

-> It success but too slow, it delay to load style, image, flash, etc

so I try to search and I get this
"DOMContentLoaded event fires when the DOM is loaded, but before all page assets are loaded (CSS, images, etc.)." ya, this is what i want, i don't want to load image, flash...

but when i use it, i get this code

```<code>    GeckoWebBrowser web2 = new GeckoWebBrowser();
    web2.DOMContentLoaded += Web2_DOMContentLoaded;
    private void Web2_DOMContentLoaded(object sender, DomEventArgs e)
    {
        ...
        //When domcontent loaded i need to get some element
        but i can't find any function can do that here
        i need to use document.getElementById or something like that :(

    }
</code>```

How can I do that "without global variable" ? or any other "method to block image, css, flash" when use gecko navigate.... please help :(

Thanks for read my post !!

答:
The answer is correct, I only want to point to the same answer in C#

GeckoFX Observer Service

Body:
I need to make a bot  "get video link" from abc..

I use httpwebrequest and httprespone but I realize this website has ajax text and httpwebsite can't get it.

-> I decide to use geckowebrowser

Step by step

1. use geckowebrowser documentcomplete event and use navigate to website

2. use geckobutton to click and wait 5 seconds to get ajax text

-> It success but too slow, it delay to load style, image, flash, etc

so I try to search and I get this
"DOMContentLoaded event fires when the DOM is loaded, but before all page assets are loaded (CSS, images, etc.)." ya, this is what i want, i don't want to load image, flash...

but when i use it, i get this code

    GeckoWebBrowser web2 = new GeckoWebBrowser();
    web2.DOMContentLoaded += Web2_DOMContentLoaded;
    private void Web2_DOMContentLoaded(object sender, DomEventArgs e)
    {
        ...
        //When domcontent loaded i need to get some element
        but i can't find any function can do that here
        i need to use document.getElementById or something like that :(

    }

How can I do that "without global variable" ? or any other "method to block image, css, flash" when use gecko navigate.... please help :(

Thanks for read my post !!


问:
how to get file path from sd card in android
hi all i have mp3 files in sd card. how to get file path of mp3 song from sd card.

please assist me.

答:
As some people indicated, the officially accepted answer does not quite return the external removable SD card. And i ran upon the following thread that proposes a method I've tested on some Android devices and seems to work reliably, so i thought of re-sharing here as i don't see it in the other responses:

http://forums.androidcentral.com/samsung-galaxy-s7/668364-whats-external-sdcard-path.html

Kudos to paresh996 for coming up with the answer itself, and i can attest I've tried on Samsung S7 and S7edge and seems to work.

Now, i needed a method that returned a valid path where to read files, and that considered the fact that there might not be an external SD, in which case the internal storage should be returned, so i modified the code from paresh996 to this :

```<code>File getStoragePath() {
    String removableStoragePath;
    File fileList[] = new File("/storage/").listFiles();
    for (File file : fileList) {
       if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
            return file;
        }
    }
    return Environment.getExternalStorageDirectory();
}
</code>```

Body:
As some people indicated, the officially accepted answer does not quite return the external removable SD card. And i ran upon the following thread that proposes a method I've tested on some Android devices and seems to work reliably, so i thought of re-sharing here as i don't see it in the other responses:

http://forums.androidcentral.com/samsung-galaxy-s7/668364-whats-external-sdcard-path.html

Kudos to paresh996 for coming up with the answer itself, and i can attest I've tried on Samsung S7 and S7edge and seems to work.

Now, i needed a method that returned a valid path where to read files, and that considered the fact that there might not be an external SD, in which case the internal storage should be returned, so i modified the code from paresh996 to this :

File getStoragePath() {
    String removableStoragePath;
    File fileList[] = new File("/storage/").listFiles();
    for (File file : fileList) {
       if(!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
            return file;
        }
    }
    return Environment.getExternalStorageDirectory();
}