问:
Creating WebBrowser Control on a separate thread
Well, i have a form which contains 5 WebBrowser controls each opens a page and handle DocumentComplete event, The problem is sometimes events don't fire. After reading i came across an answer saying that if the thread is busy the events like Navigated, DocumentComplete won't fire so i tried to create the WebBrowser in a separate thread then add it to the form which results in a cross thread exception

Code

```<code>        new Thread(() =>
        {
            WebBrowser1 = new WebBrowser
            {
                Location = new Point(15, 14),
                MinimumSize = new Size(20, 20),
                Name = "WebBrowser1",
                ScriptErrorsSuppressed = true,
                Size = new Size(250, 370),
                TabIndex = 0,
                Url = new Uri("", UriKind.Relative)
            };

            ((WebBrowser_V1) WebBrowser1.ActiveXInstance).NewWindow += (string u, int f, string n, ref object d, string h, ref bool p) =>
            {
                p = true;
                WebBrowser1.Navigate(u);
            };

            WebBrowser1.DocumentCompleted += async (sender, args) =>
            {
                // Code...
            };

            WebBrowser1.Navigated += (sender, args) =>
            {
                // Code...
            };

            WebBrowser1.Navigate(Service.LinkTL.Find(_ => _.Valid)?.Use()?.Address);

            //Cross-Thread Exception
            base.Invoke(new MethodInvoker(() =>
            {
                Controls.Add(WebBrowser1);
            }));

            Application.Run();
        }) {ApartmentState = ApartmentState.STA}.Start();
</code>```

I need the WebBrowser control to be visible in the form yet be able to intercept all triggered events.

Edit: if i invoke WebBrowser i get Controls created on one thread cannot be parented to a control on a different thread exception.

答:
You need to check InvokeRequired on Cross Thread operations (see: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired(v=vs.110).aspx).

If it is, you need to invoke the delegate from your code.

```<code> myFormControl1.Invoke(myFormControl1.myDelegate);
</code>```

A typical pattern is:

```<code>private void DoFoo() {
    if (myFormControl1.InvokeRequired) {
        myFormControl1.Invoke(new MethodInvoker(() => { DoFoo(); }));
    } else {
        object1.Visible = true;
        object2.Visible = false;
    }
}
</code>```

This thread discusses ways to implement this cleanly without dirtying your code: Automating the InvokeRequired code pattern

A useful answer in the thread, shows a static method to handle invocation:

```<code>public static void InvokeIfRequired(this Control control, MethodInvoker action)
{

    if (control.InvokeRequired) {
        control.Invoke(action);
    } else {
        action();
    }
}
</code>```

And then defining the delegates like:

```<code>richEditControl1.InvokeIfRequired(() =>
{
    // Do anything you want with the control here
    richEditControl1.RtfText = value;
    RtfHelpers.AddMissingStyles(richEditControl1);
});
</code>```

Using this to accomplish your specific question:

```<code>public static class myExtension
{
    public static void InvokeIfRequired(this Control control, MethodInvoker action)
    {
        // See Update 2 for edits Mike de Klerk suggests to insert here.

        if (control.InvokeRequired)
        {
            control.Invoke(action);
        }
        else
        {
            action();
        }
    }
}

// ...

protected WebBrowser WebBrowser1;
public void loadBrowser()
{
    new Thread(() =>
        {

            var WebBrowser1 = new WebBrowser
            {
                Location = new Point(15, 14),
                MinimumSize = new Size(20, 20),
                Name = "WebBrowser1",
                ScriptErrorsSuppressed = true,
                Size = new Size(250, 370),
                TabIndex = 0,

            };
            var form = new Form()
            {
                Name = "Other Form",
                Text = "Thread Start Browser",
                AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F),
                AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font,
                ClientSize = new System.Drawing.Size(284, 261),
            };
            form.Controls.Add(WebBrowser1);
            form.Show();
            //((WebBrowser_V1)WebBrowser1.ActiveXInstance).NewWindow += (string u, int f, string n, ref object d, string h, ref bool p) =>
            //{
            //    p = true;
            //    WebBrowser1.Navigate(u);
            //};

            //WebBrowser1.DocumentCompleted += async (sender, args) =>
            //{
            //    // Code...
            //};

            WebBrowser1.Navigated += (sender, args) =>
            {
                // Code...
            };

            //WebBrowser1.Navigate(Service.LinkTL.Find(_ => _.Valid)?.Use()?.Address);

             WebBrowser1.Navigated += (sender, args) =>
            {
                // Code...
            };

            //WebBrowser1.Navigate(Service.LinkTL.Find(_ => _.Valid)?.Use()?.Address);

            this.InvokeIfRequired(() =>
            {
                this.WebBrowser1 = WebBrowser1;
                this.CreatedBrowser();

            });

            Application.Run();
        })

        { ApartmentState = ApartmentState.STA }.Start();
    }
private void Form1_Load(object sender, EventArgs e)
{
    loadBrowser();
}
public void CreatedBrowser()
{
    Console.WriteLine("Created browser");
}
private void btnGo_Click(object sender, EventArgs e)
{
    string url = txtUrl.Text;
    WebBrowser1.InvokeIfRequired(() => WebBrowser1.Navigate(url));
}
</code>```

Here's a screen shot:

Body:
Well, i have a form which contains 5 WebBrowser controls each opens a page and handle DocumentComplete event, The problem is sometimes events don't fire. After reading i came across an answer saying that if the thread is busy the events like Navigated, DocumentComplete won't fire so i tried to create the WebBrowser in a separate thread then add it to the form which results in a cross thread exception

Code

        new Thread(() =>
        {
            WebBrowser1 = new WebBrowser
            {
                Location = new Point(15, 14),
                MinimumSize = new Size(20, 20),
                Name = "WebBrowser1",
                ScriptErrorsSuppressed = true,
                Size = new Size(250, 370),
                TabIndex = 0,
                Url = new Uri("", UriKind.Relative)
            };

            ((WebBrowser_V1) WebBrowser1.ActiveXInstance).NewWindow += (string u, int f, string n, ref object d, string h, ref bool p) =>
            {
                p = true;
                WebBrowser1.Navigate(u);
            };

            WebBrowser1.DocumentCompleted += async (sender, args) =>
            {
                // Code...
            };

            WebBrowser1.Navigated += (sender, args) =>
            {
                // Code...
            };

            WebBrowser1.Navigate(Service.LinkTL.Find(_ => _.Valid)?.Use()?.Address);

            //Cross-Thread Exception
            base.Invoke(new MethodInvoker(() =>
            {
                Controls.Add(WebBrowser1);
            }));

            Application.Run();
        }) {ApartmentState = ApartmentState.STA}.Start();

I need the WebBrowser control to be visible in the form yet be able to intercept all triggered events.

Edit: if i invoke WebBrowser i get Controls created on one thread cannot be parented to a control on a different thread exception.

Body:
You need to check InvokeRequired on Cross Thread operations (see: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired(v=vs.110).aspx).

If it is, you need to invoke the delegate from your code.

 myFormControl1.Invoke(myFormControl1.myDelegate);

A typical pattern is:

private void DoFoo() {
    if (myFormControl1.InvokeRequired) {
        myFormControl1.Invoke(new MethodInvoker(() => { DoFoo(); }));
    } else {
        object1.Visible = true;
        object2.Visible = false;
    }
}

This thread discusses ways to implement this cleanly without dirtying your code: Automating the InvokeRequired code pattern

A useful answer in the thread, shows a static method to handle invocation:

public static void InvokeIfRequired(this Control control, MethodInvoker action)
{

    if (control.InvokeRequired) {
        control.Invoke(action);
    } else {
        action();
    }
}

And then defining the delegates like:

richEditControl1.InvokeIfRequired(() =>
{
    // Do anything you want with the control here
    richEditControl1.RtfText = value;
    RtfHelpers.AddMissingStyles(richEditControl1);
});

Using this to accomplish your specific question:

public static class myExtension
{
    public static void InvokeIfRequired(this Control control, MethodInvoker action)
    {
        // See Update 2 for edits Mike de Klerk suggests to insert here.

        if (control.InvokeRequired)
        {
            control.Invoke(action);
        }
        else
        {
            action();
        }
    }
}

// ...

protected WebBrowser WebBrowser1;
public void loadBrowser()
{
    new Thread(() =>
        {

            var WebBrowser1 = new WebBrowser
            {
                Location = new Point(15, 14),
                MinimumSize = new Size(20, 20),
                Name = "WebBrowser1",
                ScriptErrorsSuppressed = true,
                Size = new Size(250, 370),
                TabIndex = 0,

            };
            var form = new Form()
            {
                Name = "Other Form",
                Text = "Thread Start Browser",
                AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F),
                AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font,
                ClientSize = new System.Drawing.Size(284, 261),
            };
            form.Controls.Add(WebBrowser1);
            form.Show();
            //((WebBrowser_V1)WebBrowser1.ActiveXInstance).NewWindow += (string u, int f, string n, ref object d, string h, ref bool p) =>
            //{
            //    p = true;
            //    WebBrowser1.Navigate(u);
            //};

            //WebBrowser1.DocumentCompleted += async (sender, args) =>
            //{
            //    // Code...
            //};

            WebBrowser1.Navigated += (sender, args) =>
            {
                // Code...
            };

            //WebBrowser1.Navigate(Service.LinkTL.Find(_ => _.Valid)?.Use()?.Address);

             WebBrowser1.Navigated += (sender, args) =>
            {
                // Code...
            };

            //WebBrowser1.Navigate(Service.LinkTL.Find(_ => _.Valid)?.Use()?.Address);

            this.InvokeIfRequired(() =>
            {
                this.WebBrowser1 = WebBrowser1;
                this.CreatedBrowser();

            });

            Application.Run();
        })

        { ApartmentState = ApartmentState.STA }.Start();
    }
private void Form1_Load(object sender, EventArgs e)
{
    loadBrowser();
}
public void CreatedBrowser()
{
    Console.WriteLine("Created browser");
}
private void btnGo_Click(object sender, EventArgs e)
{
    string url = txtUrl.Text;
    WebBrowser1.InvokeIfRequired(() => WebBrowser1.Navigate(url));
}

Here's a screen shot:


来源: stackexchange

问:
Cannot connect to MongoDB via node.js in Docker
My node.js express app cannot connect to the MongoDB in a Docker. I'm not that familiar with Docker.

node.js connection:

```<code>import mongodb from 'mongodb';
...
mongodb.MongoClient.connect('mongodb://localhost:27017', ... );
</code>```

Dockerfile:

```<code>FROM node:argon
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
EXPOSE 3000
CMD ["npm", "start"]
</code>```

docker-compose.yml

```<code>version: “2”
 services:
  web:
   build: .
   volumes:
     — ./:/app
   ports:
   — “3000:3000”
   links:
    — mongo
   mongo:
    image: mongo
    ports:
      — “27017:27017”
</code>```

Build command: docker build -t NAME .

Run command: docker run -ti -p 3000:3000 NAME

Connection error:

```<code>[MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]]
  name: 'MongoError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]'
</code>```

答:
Try this.

When using linked docker containers you should use the name of the container in this case for example your connection to mongodb should be mongodb.MongoClient.connect('mongodb://mongo:27017', ... ); instead of mongodb.MongoClient.connect('mongodb://localhost:27017', ... );. The reason for changing it to mongo is because you used the links attribute to mongo in your docker-compose.yml. That would result to a hostname of  mongo in your /etc/hosts of the web docker container. Reference linking-containers.

The docker-compose.yml seems to be lacking an indention. On the mongo attribute should be the same level as web.

```<code>version: '2'
services:
  web:
   build: .
   volumes: ['./:/app']
   ports: [ '3000:3000' ]
   links: [ mongo ]
  mongo:
   image: mongo
   ports: [ '27017:27017' ]
</code>```

I tried your configuration using my docker what Ive done is update docker-compose.yml then I docker-compose build then docker-compose up. Logs of my local run

ContentLicense: CC BY-SA 3.0

Body:
My node.js express app cannot connect to the MongoDB in a Docker. I'm not that familiar with Docker.

node.js connection:

import mongodb from 'mongodb';
...
mongodb.MongoClient.connect('mongodb://localhost:27017', ... );

Dockerfile:

FROM node:argon
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
EXPOSE 3000
CMD ["npm", "start"]

docker-compose.yml

version: “2”
 services:
  web:
   build: .
   volumes:
     — ./:/app
   ports:
   — “3000:3000”
   links:
    — mongo
   mongo:
    image: mongo
    ports:
      — “27017:27017”

Build command: docker build -t NAME .

Run command: docker run -ti -p 3000:3000 NAME

Connection error:

[MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]]
  name: 'MongoError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]'

Body:
Try this.

When using linked docker containers you should use the name of the container in this case for example your connection to mongodb should be mongodb.MongoClient.connect('mongodb://mongo:27017', ... ); instead of mongodb.MongoClient.connect('mongodb://localhost:27017', ... );. The reason for changing it to mongo is because you used the links attribute to mongo in your docker-compose.yml. That would result to a hostname of  mongo in your /etc/hosts of the web docker container. Reference linking-containers.

The docker-compose.yml seems to be lacking an indention. On the mongo attribute should be the same level as web.

version: '2'
services:
  web:
   build: .
   volumes: ['./:/app']
   ports: [ '3000:3000' ]
   links: [ mongo ]
  mongo:
   image: mongo
   ports: [ '27017:27017' ]

I tried your configuration using my docker what Ive done is update docker-compose.yml then I docker-compose build then docker-compose up. Logs of my local run


问:
jQuery validation cannot work properly
I am just new to jQuery. Now I am trying to use the validation method for the form, but I found that the page will not stop there to show the error message, rather than show the message 2 seconds, then submit the data and reload the page.

My HTML code:

```<code><form class="plform" id="pricelistform" method="get" action="" enctype="multipart/form-data">
<fieldset>
    <div id="add_item" class="overlay">
        <div class="popup">
            <h2 class="div_title">Add Item</h2>
            <a class="close" href="#">×</a>
            <hr class="heading_divide">
            <div class="content">
                <div class="control-group">
                    <div class="col-xs-12 col-sm-3">
                        <div class="control-label">
                            <label id="supply_search-lbl" for="supply_search" class="hasTooltip" title="" data-original-title="<strong>Existing Supplier</strong>Please select an existing supplier<br/>">Existing Supplier</label>
                        </div>
                    </div>
                    <div class="col-xs-12 col-sm-9">
                        <div class="controls">
                            <select name="supplyerid[]" id="supply_search" class="input-medium form-control">
                                <option value="-1"><?php echo JText::_('--- Select Supplier ---');?></option>
                                <?php echo JHtml::_('select.options', JFormFieldSelect::getSupplier(),'id', 'companyname', $this->escape($this->state->get('filter.supply_search')));?>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="control-group">
                    <div class="con-xs-12 col-sm-3">
                        <div class="control-label">
                            <label id="product_name-lbl" for="product_name">Product Name<span class="star"> *</span></label>
                        </div>
                    </div>
                    <div class="col-xs-12 col-sm-9">
                        <div class="controls">
                            <input type='text' name='productname[]' id="product_name" class="required form-control" aria-required="true"/>
                        </div>
                    </div>
                </div>
                <div class="control-group">
                    <div class="con-xs-12 col-sm-3">
                        <div class="control-label">
                            <label id="product_code-lbl" for="product_code">Product Code</label>
                        </div>
                    </div>
                    <div class="col-xs-12 col-sm-9">
                        <div class="controls">
                            <input type='text' name='productcode[]' id="product_code" class="form-control"/>
                        </div>
                    </div>
                </div>
                <div class="control-group">
                    <div class="con-xs-12 col-sm-3">
                        <div class="control-label">
                            <label id="cost_price-lbl" for="cost_price">Cost Price<span class="star"> *</span></label>
                        </div>
                    </div>
                    <div class="col-xs-12 col-sm-9">
                        <div class="controls">
                            <input type='text' name='costprice[]' id="cost_price" class="form-control" />
                        </div>
                    </div>
                </div>
                <div class="control-group">
                    <div class="con-xs-12 col-sm-3">
                        <div class="control-label">
                            <label id="sell_price-lbl" for="sell_price">Sell Price<span class="star"> *</span></label>
                        </div>
                    </div>
                    <div class="col-xs-12 col-sm-9">
                        <div class="controls">
                            <input type='text' name='sellprice[]' id="sell_price" class="form-control" />
                        </div>
                    </div>
                </div>
                <div class="buttons">
                    <button type="submit" class="gs-btn-2 additem" id="add_btn">Add</button>
                </div>
            </div>
        </div>
    </div>
</fieldset></form>
</code>```

jQuery:

```<code>$(document).ready(function(){

//close add item popover
    $('.close').click(function(){
        e.preventDefault();
        $('.overlay','#add_item').hide();
    });

    //click button "Add" in add item popover
    $(".additem").on('click', function(){

    var temp={
        productname: pname.val(),
        productcode: pcode.val(),
        costprice: cprice.val(),
        sellprice: sprice.val(),
        accountid: accid.val(),
        warranty: warraty.val(),
    };

    //console.log(temp);
    $.ajax({
        type:'post',
        url:'index.php?option=com_gsprlist&task=additem.addItem',
        data:{data:temp},
        success:function(re){
            //console.log(re);
            $('.overlay').hide();

            },
            error:function(re){

                alert('error saving order');
            }
        });

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

Validation scripts:

```<code>$('#pricelistform').validate({
    rules:{
        'productname[]':{
            required:true,
            minlength:2
        },
        'costprice[]':"required",
        'sellprice[]':"required",
        'indiname':"required",
        'comname':"required",
        'indiphone':"required",
        'indiemail':"required",
        'accid[]':"required",

    },
    messages:{
        'productname[]':{
            required:"Please enter your productname",
            minlength:" Your product name must consist of at least 2 characters"
        },
        'costprice[]':"Please enter your cost price",
        'sellprice[]':"Please enter your sell price",
        'accid[]':"Please enter your Account ID",
    }
});
</code>```

答:
Give it a try, I think this will do</p>

```<code>$(".additem").on('click', function(event){
event.preventDefault();
var temp={
    productname: pname.val(),
    productcode: pcode.val(),
    costprice: cprice.val(),
    sellprice: sprice.val(),
    accountid: accid.val(),
    warranty: warraty.val(),
};

//console.log(temp);
$.ajax({
    type:'post',
    url:'index.php?option=com_gsprlist&task=additem.addItem',
    data:{data:temp},
    success:function(re){
        //console.log(re);
        $('.overlay').hide();

        },
        error:function(re){

            alert('error saving order');
        }
    });

});
</code>```

Title: jQuery validation cannot work properly

Body:
I am just new to jQuery. Now I am trying to use the validation method for the form, but I found that the page will not stop there to show the error message, rather than show the message 2 seconds, then submit the data and reload the page.

My HTML code:

<form class="plform" id="pricelistform" method="get" action="" enctype="multipart/form-data">
<fieldset>

Add Item

            ×

                            <label id="supply_search-lbl" for="supply_search" class="hasTooltip" title="" data-original-title="Existing SupplierPlease select an existing supplier
">Existing Supplier

                            <select name="supplyerid[]" id="supply_search" class="input-medium form-control">
                                <option value="-1"><?php echo JText::_('--- Select Supplier ---');?></option>
                                <?php echo JHtml::_('select.options', JFormFieldSelect::getSupplier(),'id', 'companyname', $this->escape($this->state->get('filter.supply_search')));?>
                            </select>

                            Product Name *

                            <input type='text' name='productname[]' id="product_name" class="required form-control" aria-required="true"/>

                            Product Code

                            <input type='text' name='productcode[]' id="product_code" class="form-control"/>

                            Cost Price *

                            <input type='text' name='costprice[]' id="cost_price" class="form-control" />

                            Sell Price *

                            <input type='text' name='sellprice[]' id="sell_price" class="form-control" />

                    <button type="submit" class="gs-btn-2 additem" id="add_btn">Add</button>

</fieldset></form>

jQuery:

$(document).ready(function(){

//close add item popover
    $('.close').click(function(){
        e.preventDefault();
        $('.overlay','#add_item').hide();
    });

    //click button "Add" in add item popover
    $(".additem").on('click', function(){

    var temp={
        productname: pname.val(),
        productcode: pcode.val(),
        costprice: cprice.val(),
        sellprice: sprice.val(),
        accountid: accid.val(),
        warranty: warraty.val(),
    };

    //console.log(temp);
    $.ajax({
        type:'post',
        url:'index.php?option=com_gsprlist&task=additem.addItem',
        data:{data:temp},
        success:function(re){
            //console.log(re);
            $('.overlay').hide();

            },
            error:function(re){

                alert('error saving order');
            }
        });

    });
})

Validation scripts:

$('#pricelistform').validate({
    rules:{
        'productname[]':{
            required:true,
            minlength:2
        },
        'costprice[]':"required",
        'sellprice[]':"required",
        'indiname':"required",
        'comname':"required",
        'indiphone':"required",
        'indiemail':"required",
        'accid[]':"required",

    },
    messages:{
        'productname[]':{
            required:"Please enter your productname",
            minlength:" Your product name must consist of at least 2 characters"
        },
        'costprice[]':"Please enter your cost price",
        'sellprice[]':"Please enter your sell price",
        'accid[]':"Please enter your Account ID",
    }
});

Body:
Give it a try, I think this will do

$(".additem").on('click', function(event){
event.preventDefault();
var temp={
    productname: pname.val(),
    productcode: pcode.val(),
    costprice: cprice.val(),
    sellprice: sprice.val(),
    accountid: accid.val(),
    warranty: warraty.val(),
};

//console.log(temp);
$.ajax({
    type:'post',
    url:'index.php?option=com_gsprlist&task=additem.addItem',
    data:{data:temp},
    success:function(re){
        //console.log(re);
        $('.overlay').hide();

        },
        error:function(re){

            alert('error saving order');
        }
    });

});


问:
How do I return JSON from an Azure Function
I am playing with Azure Functions. However, I feel like I'm stumped on something pretty simple. I'm trying to figure out how to return some basic JSON. I'm not sure how to create some JSON and get it back to my request.

Once upon a time,  I would create an object, populate its properties, and serialize it. So, I started down this path:

```<code>#r "Newtonsoft.Json"

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"Running Function");
    try {
      log.Info($"Function ran");

      var myJSON = GetJson();

      // I want myJSON to look like:
      // {
      //   firstName:'John',
      //   lastName: 'Doe',
      //   orders: [
      //     { id:1, description:'...' },
      //     ...
      //   ]
      // }
      return ?;
    } catch (Exception ex) {
        // TODO: Return/log exception
        return null;
    }
}

public static ? GetJson()
{
  var person = new Person();
  person.FirstName = "John";
  person.LastName = "Doe";

  person.Orders = new List<Order>();
  person.Orders.Add(new Order() { Id=1, Description="..." });

  ?
}

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public List<Order> Orders { get; set; }
}

public class Order
{
  public int Id { get; set; }
  public string Description { get; set; }
}
</code>```

However, I'm totally stuck on the serialization and return process now.I guess I'm used to returning JSON in ASP.NET MVC where everything is an Action

答:
Here's a full example of an Azure function returning a properly formatted JSON object instead of XML:

```<code>#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;
using System.Text;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    var myObj = new {name = "thomas", location = "Denver"};
    var jsonToReturn = JsonConvert.SerializeObject(myObj);

    return new HttpResponseMessage(HttpStatusCode.OK) {
        Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
    };
}
</code>```

Navigate to the endpoint in a browser and you will see:

```<code>{
  "name": "thomas",
  "location": "Denver"
}
</code>```

Body:
I am playing with Azure Functions. However, I feel like I'm stumped on something pretty simple. I'm trying to figure out how to return some basic JSON. I'm not sure how to create some JSON and get it back to my request.

Once upon a time,  I would create an object, populate its properties, and serialize it. So, I started down this path:

#r "Newtonsoft.Json"

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"Running Function");
    try {
      log.Info($"Function ran");

      var myJSON = GetJson();

      // I want myJSON to look like:
      // {
      //   firstName:'John',
      //   lastName: 'Doe',
      //   orders: [
      //     { id:1, description:'...' },
      //     ...
      //   ]
      // }
      return ?;
    } catch (Exception ex) {
        // TODO: Return/log exception
        return null;
    }
}

public static ? GetJson()
{
  var person = new Person();
  person.FirstName = "John";
  person.LastName = "Doe";

  person.Orders = new List<Order>();
  person.Orders.Add(new Order() { Id=1, Description="..." });

  ?
}

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public List<Order> Orders { get; set; }
}

public class Order
{
  public int Id { get; set; }
  public string Description { get; set; }
}

However, I'm totally stuck on the serialization and return process now.I guess I'm used to returning JSON in ASP.NET MVC where everything is an Action

Body:
Here's a full example of an Azure function returning a properly formatted JSON object instead of XML:

#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;
using System.Text;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    var myObj = new {name = "thomas", location = "Denver"};
    var jsonToReturn = JsonConvert.SerializeObject(myObj);

    return new HttpResponseMessage(HttpStatusCode.OK) {
        Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
    };
}

Navigate to the endpoint in a browser and you will see:

{
  "name": "thomas",
  "location": "Denver"
}


问:
QProcess returning an exit code of 0
I'm using QProcess to run a ping to a few hosts. When I use QProcess with the command as "ping -c 1 -W 1 hostname" the exit code being returned is always 0 regardless if the ping is successful or not. I have tested hosts that are offline in the terminal and the exit code is as expected. Assume hostname is an actual host that is offline.
This is the code snippet that includes QProcess:</p>

```<code>QProcess *process = new QProcess(this);
QString cmd("ping -c 1- W 1 hostname");
process->start(cmd);
std::cout << process->exitCode() << std::endl;
</code>```

答:
QProcess::exitCode() says:

Returns the exit code of the last process that finished.

So, you need to wait for the process (QProcess::waitForFinished) to exit before checking its exit code.

Example:

```<code>if ( !process->waitForFinished( -1 ) )
{
    qWarning() << "Error:" << process->errorString();
    return;
}

qDebug() << "Exit code:" << process->exitCode();
</code>```

Title: QProcess returning an exit code of 0

Body:
I'm using QProcess to run a ping to a few hosts. When I use QProcess with the command as "ping -c 1 -W 1 hostname" the exit code being returned is always 0 regardless if the ping is successful or not. I have tested hosts that are offline in the terminal and the exit code is as expected. Assume hostname is an actual host that is offline.
This is the code snippet that includes QProcess:

QProcess *process = new QProcess(this);
QString cmd("ping -c 1- W 1 hostname");
process->start(cmd);
std::cout << process->exitCode() << std::endl;

Body:
QProcess::exitCode() says:

Returns the exit code of the last process that finished.

So, you need to wait for the process (QProcess::waitForFinished) to exit before checking its exit code.

Example:

if ( !process->waitForFinished( -1 ) )
{
    qWarning() << "Error:" << process->errorString();
    return;
}

qDebug() << "Exit code:" << process->exitCode();


问:
How combine word embedded vectors to one vector?
I know the meaning and methods of word embedding(skip-gram, CBOW) completely. And I know, that Google has a word2vector API that by getting the word can produce the vector.
but my problem is this: we have a clause that includes the subject, object, verb... that each word is previously embedded by the Google API, now "How we can combine these vectors together to create a vector that is equal to the clause?"
Example:
Clause: V= "dog bites man"
after word embedding by the Google, we have V1, V2, V3 that each of them maps to the dog, bites, man. and we know that:
V = V1+ V2 +V3
How can we provide V?
I will appreciate if you explain it by taking an example of real vectors.</p>

答:
A vector is basically just a list of numbers. You add vectors by adding the number in the same position in each list together. Here's an example:

```<code>a = [1, 2, 3]
b = [4, 5, 6]
c = a + b # vector addition
c is [(1+4), (2+5), (3+6)], or [5, 7, 9]
</code>```

As indicated in this question, a simple way to do this in python is like this:

```<code>map(sum, zip(a, b))
</code>```

Vector addition is part of linear algebra. If you don't understand operations on vectors and matrices the math around word vectors will be very hard to understand, so you may want to look into learning more about linear algebra in general.

Normally adding word vectors together is a good way to approximate a sentence vector, since for any given set of words there's an obvious order. However, your example of Dog bites man and Man bites dog shows the weakness of adding vectors - the result doesn't change based on word order, so the results for those two sentences would be the same, even though their meanings are very different.

For methods of getting sentence vectors that are affected by word order, look into doc2vec or the just-released InferSent.

Body:
A vector is basically just a list of numbers. You add vectors by adding the number in the same position in each list together. Here's an example:

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b # vector addition
c is [(1+4), (2+5), (3+6)], or [5, 7, 9]

As indicated in this question, a simple way to do this in python is like this:

map(sum, zip(a, b))

Vector addition is part of linear algebra. If you don't understand operations on vectors and matrices the math around word vectors will be very hard to understand, so you may want to look into learning more about linear algebra in general.

Normally adding word vectors together is a good way to approximate a sentence vector, since for any given set of words there's an obvious order. However, your example of Dog bites man and Man bites dog shows the weakness of adding vectors - the result doesn't change based on word order, so the results for those two sentences would be the same, even though their meanings are very different.

For methods of getting sentence vectors that are affected by word order, look into doc2vec or the just-released InferSent.


问:
Azure Data Lake Count All Items
Is there a way to recursively count all items on an Azure Data lake Store instance?

When assigning permissions, all files and folders are cycled through.. but there isn't much in the way of knowing how far you have gone through the process.

Knowing how many files in total would be pretty helpful!

I got this far:

```<code>$m = Get-AzureRmDataLakeStoreChildItem 'batadlspdnetpdtest01' -Path '/' | measure
$m.Count
</code>```

and then started looking for a switch to also check children...

am i missing something?

答:
Your approach is sound, but there's not a built-in way to get the list of items recursively. There's a bit of code you can write on top of the cmdlets to do this very thing, by looking at each item and recursively listing if the item is a directory.

Here's some sample code that accomplishes this.

Title: Azure Data Lake Count All Items

Body:
Is there a way to recursively count all items on an Azure Data lake Store instance?

When assigning permissions, all files and folders are cycled through.. but there isn't much in the way of knowing how far you have gone through the process.

Knowing how many files in total would be pretty helpful!

I got this far:

$m = Get-AzureRmDataLakeStoreChildItem 'batadlspdnetpdtest01' -Path '/' | measure
$m.Count

and then started looking for a switch to also check children...

am i missing something?


问:
Format data from store before binding
I have a store with data like this:

name: "black", color: "RGB: 0, 0, 0"

Now I want to create a grid that shows the data with an extra column that shows a thumbnail of the color. Basically just a small square with a background color. I know there is tpl and renderer but the documentation advises using bind. So how can I transform a field from the store with bind? There's Ext.util.Format and I can make it work by combining several formatters but it would be much cleaner if I could use my own function.

答:
Here's an alternate version based off an existing answer. It's a simpler version that uses a column renderer to display the value. A widget column may be a bit heavy for this use. YMMV, depending on what your needs are.

```<code>Ext.application({
    name: 'Fiddle',

    launch: function () {
        new Ext.grid.Panel({
            renderTo: Ext.getBody(),
            store: {
                data: [{
                    name: 'red',
                    color: 'RGB: 255, 0, 0'
                }]
            },
            columns: [{
                text: 'Name',
                dataIndex: 'name'
            }, {
                text: 'Color',
                dataIndex: 'color',
                flex: 1
            }, {
                text: 'Preview',
                renderer: function (v, meta, rec) {
                    var color = rec.get('color');
                    // Parse model value into displayable color
                    return '<div style="width: 100%; height: 1em; background-color: #FF0000;"></div>';
                }
            }]
        });
    }
});
</code>```

Fiddle

Title: Format data from store before binding

Body:
Here's an alternate version based off an existing answer. It's a simpler version that uses a column renderer to display the value. A widget column may be a bit heavy for this use. YMMV, depending on what your needs are.

Ext.application({
    name: 'Fiddle',

    launch: function () {
        new Ext.grid.Panel({
            renderTo: Ext.getBody(),
            store: {
                data: [{
                    name: 'red',
                    color: 'RGB: 255, 0, 0'
                }]
            },
            columns: [{
                text: 'Name',
                dataIndex: 'name'
            }, {
                text: 'Color',
                dataIndex: 'color',
                flex: 1
            }, {
                text: 'Preview',
                renderer: function (v, meta, rec) {
                    var color = rec.get('color');
                    // Parse model value into displayable color
                    return '<div style="width: 100%; height: 1em; background-color: #FF0000;"></div>';
                }
            }]
        });
    }
});

Fiddle


问:
Webpack 3: css-loader style-loader error
I am receiving the following error:

ERROR in ./common/app.css Module parse failed:
  E:\universal-starter\common\app.css Unexpected token (1:5) You may
  need an appropriate loader to handle this file type.

```<code>| body {
|     background-color: orange;
| }
</code>```

My App.js file:

```<code>import React from 'react';
require('./app.css');

const App = () => <div>Hello from React</div>;

export default App;
</code>```

My webpack.config:

```<code>const webpack = require('webpack');
const path = require('path');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  devtool: 'inline-source-map',
  entry: [
    'react-hot-loader/patch',
    'webpack-dev-server/client?http://localhost:3001',
    'webpack/hot/only-dev-server',
    './client/index',
  ],
  target: 'web',
</code>```

```<code>  module: {
    rules: [
      {
        enforce: 'pre',
        exclude: /node_modules/,
        loader: 'eslint-loader',
        options: {
          emitWarning: true
        },
        test: /\.(js|jsx)$/
      },
      {
        exclude: /node_modules/,
        test: /\.js?$/,
        use: ['babel-loader']},
</code>```

// WHY IS THIS WRONG & CAUSING THE PROBLEM?!?!?!?!

```<code>      // embed styles in styles folder
      {

        test: /\.css$/,
        use: ExtractTextWebpackPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader']
        })
      },
</code>```

```<code>      // fonts
      {
        test: /\.(woff|woff2|eot|ttf|svg)$/,
        exclude: /node_modules/,
        loader: 'url-loader?limit=1024&name=fonts/[name].[ext]'
      },
      // examine img file size
      {
        test: /\.(jpe?g|png|svg|gif)$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 40000,
            name: 'images/[name].[hash].[ext]',
          }
        },
        {
          loader: 'image-webpack-loader',
        }
        ]
      }
    ],
  },
</code>```

```<code>  plugins: [
    new ExtractTextWebpackPlugin('./css/styles.css'),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new HTMLWebpackPlugin({
      template: './client/template/index.html',
    }),
    new webpack.DefinePlugin({
      'process.env': { BUILD_TARGET: JSON.stringify('client') },
    }),
  ],
</code>```

```<code>  devServer: {
    host: 'localhost',
    port: 3001,
    historyApiFallback: true,
    hot: true,
  },
  output: {
    path: path.join(__dirname, '.build'),
    publicPath: 'http://localhost:3001/',
    filename: 'client.js',
  },
};
</code>```

Very little help out there so far on Webpack 3.
Any ideas?
Thanks!!

答:
Try this:
In your App.js file, replace require('./app.css'); for import './app.css'

Body:
I am receiving the following error:

ERROR in ./common/app.css Module parse failed:
  E:\universal-starter\common\app.css Unexpected token (1:5) You may
  need an appropriate loader to handle this file type.

| body {
|     background-color: orange;
| }

My App.js file:

import React from 'react';
require('./app.css');

const App = () =>
Hello from React
;

export default App;

My webpack.config:

const webpack = require('webpack');
const path = require('path');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  devtool: 'inline-source-map',
  entry: [
    'react-hot-loader/patch',
    'webpack-dev-server/client?http://localhost:3001',
    'webpack/hot/only-dev-server',
    './client/index',
  ],
  target: 'web',

  module: {
    rules: [
      {
        enforce: 'pre',
        exclude: /node_modules/,
        loader: 'eslint-loader',
        options: {
          emitWarning: true
        },
        test: /\.(js|jsx)$/
      },
      {
        exclude: /node_modules/,
        test: /\.js?$/,
        use: ['babel-loader']},

// WHY IS THIS WRONG & CAUSING THE PROBLEM?!?!?!?!

      // embed styles in styles folder
      {

        test: /\.css$/,
        use: ExtractTextWebpackPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader']
        })
      },

      // fonts
      {
        test: /\.(woff|woff2|eot|ttf|svg)$/,
        exclude: /node_modules/,
        loader: 'url-loader?limit=1024&name=fonts/[name].[ext]'
      },
      // examine img file size
      {
        test: /\.(jpe?g|png|svg|gif)$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 40000,
            name: 'images/[name].[hash].[ext]',
          }
        },
        {
          loader: 'image-webpack-loader',
        }
        ]
      }
    ],
  },

  plugins: [
    new ExtractTextWebpackPlugin('./css/styles.css'),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new HTMLWebpackPlugin({
      template: './client/template/index.html',
    }),
    new webpack.DefinePlugin({
      'process.env': { BUILD_TARGET: JSON.stringify('client') },
    }),
  ],

  devServer: {
    host: 'localhost',
    port: 3001,
    historyApiFallback: true,
    hot: true,
  },
  output: {
    path: path.join(__dirname, '.build'),
    publicPath: 'http://localhost:3001/',
    filename: 'client.js',
  },
};

Very little help out there so far on Webpack 3.
Any ideas?
Thanks!!


问:
Python util module call set up first
I have a util.py file that has a bunch of methods used by other modules. The util module relies on a setup() function being called before any other functions can be called. Is there anyway to have this function be called before other functions are called? The functions will be called by other modules as util.some_func(**args).

答:
When a module is imported, all code at the "top" level (or the outermost indent level) is executed.  This includes function definitions, class definitions, variables, and function calls.

So, at the bottom of your util.py file, just call the function:

```<code>setup()
</code>```

All code which imports your module will execute the function automatically.

You'll probably want to put in safeguards to avoid performing the setup twice.

Title: Python util module call set up first

Body:
When a module is imported, all code at the "top" level (or the outermost indent level) is executed.  This includes function definitions, class definitions, variables, and function calls.

So, at the bottom of your util.py file, just call the function:

setup()

All code which imports your module will execute the function automatically.

You'll probably want to put in safeguards to avoid performing the setup twice.


问:
Using text-overflow: ellipsis; on a parent div when the child is an input
I have multiple non-wrapping, inline child elements within a parent div that has a set width and text-overflow set to ellipsis.

When the last child is an anchor tag, the ellipses work fine, but when it's an input, the text just clips. Because the preceding items are variable width, I can't set a reasonable max width on the last input.

.parent {
    width: 120px;
    background: #eee;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <span class="child1">
    link 1 text
    Lorem ipsum dolor
  </span>
</div>
<div class="parent">
  <span class="child1">
    link 2 text
    <input type="submit" class="request-topic-link" value="lorem-ipsum-dolor">
  </span>
</div></code>```

Any suggestions? Here's a JSFiddle.

答:
Well here is what I came up with. It needs some adjustments to your markup, but other than that it works.

a) The submit input can be safely replaced with a button submit that is also semantic and you can style it to your needs.
b) The simple text has to be wrapped within a span

Since you have variable content, the only way to do it is by using table-cells ...wrapped within a table obviously. Using table-layout:fixed would do the trick IF your content was not of variable width. This is why I added a width 33% to all table-cells which is just an indicator of what to be used; table-cells will disregard the set value and still expand accordingly and arbitrarily depending on their content.

Here is the updated markup and a working fiddle:
HTML:

```<code><div class="parent">
  <span class="child1">
    <a href="#">link 1</a> text <a href="#">Lorem ipsum dolor</a>               </span>
</div>
<div class="parent">
  <span class="child1">
  <a href="#">link 1</a><span> textdfgg </span>
  <button type="submit" class="request-topic-link">lorem-ipsum-dolor</button>
  </span>
</div>
</code>```

CSS:

```<code>.parent {
  width: 120px;
  background: #fff;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.child1 {
  display: table;
  width: 100%;
}

.child1 > * {
  display: table-cell;
  width: 33%;
}

button {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display: inline-block;
  width: 100%;
}
</code>```

Working fiddle: http://jsfiddle.net/5muarho3/3/

Body:
I have multiple non-wrapping, inline child elements within a parent div that has a set width and text-overflow set to ellipsis.

When the last child is an anchor tag, the ellipses work fine, but when it's an input, the text just clips. Because the preceding items are variable width, I can't set a reasonable max width on the last input.

.parent {
    width: 120px;
    background: #eee;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

    link 1 text
    Lorem ipsum dolor

    link 2 text
    <input type="submit" class="request-topic-link" value="lorem-ipsum-dolor">

Any suggestions? Here's a JSFiddle.

Body:
Well here is what I came up with. It needs some adjustments to your markup, but other than that it works.

a) The submit input can be safely replaced with a button submit that is also semantic and you can style it to your needs.
b) The simple text has to be wrapped within a span

Since you have variable content, the only way to do it is by using table-cells ...wrapped within a table obviously. Using table-layout:fixed would do the trick IF your content was not of variable width. This is why I added a width 33% to all table-cells which is just an indicator of what to be used; table-cells will disregard the set value and still expand accordingly and arbitrarily depending on their content.

Here is the updated markup and a working fiddle:
HTML:

<div class="parent">
  <span class="child1">
    <a href="#">link 1</a> text <a href="#">Lorem ipsum dolor</a>               </span>
</div>
<div class="parent">
  <span class="child1">
  <a href="#">link 1</a><span> textdfgg </span>
  <button type="submit" class="request-topic-link">lorem-ipsum-dolor</button>
  </span>
</div>

CSS:

.parent {
  width: 120px;
  background: #fff;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.child1 {
  display: table;
  width: 100%;
}

.child1 > * {
  display: table-cell;
  width: 33%;
}

button {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display: inline-block;
  width: 100%;
}

Working fiddle: http://jsfiddle.net/5muarho3/3/


问:
error while pushing to GitHub
i want to commit changes to GitHub
i can do it with GitHub desktop but i get this error when i try with android studio commit changes button :
"Failed with error: fatal: unable to access 'https://github. ... .git/': The requested URL returned error: 403"</p>

答:
You need to first find the correct SSH/ HTTP address to the repository that you would like to commit to then you can run this command in your terminal:

git remote add origin [remote repository URL]

once connected, you should be able to commit the changes.

Title: error while pushing to GitHub


问:
Multiple dex files define Lcom/amazonaws/AmazonClientException
When trying to sign my AKP in Android Studio I keep getting an error:

```<code>Error:Error converting bytecode to dex:
Cause: com.android.dex.DexException: Multiple dex files define Lcom/amazonaws/AmazonClientException;
</code>```

I tried to clean my project and other various solutions. I'm afraid of getting into deep directories and messing something up so I was hoping someone could help me!

My dependencies:

```<code>dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.amazonaws:aws-android-sdk-s3:2.4.4'

//compile project(path: ':backend', configuration: 'android-endpoints')
compile 'com.github.chrisbanes:PhotoView:1.2.6'
compile 'com.davemorrissey.labs:subsampling-scale-image-view:3.5.0'
compile 'com.github.amlcurran.showcaseview:library:5.4.3'
compile 'com.github.d-max:spots-dialog:0.7@aar'
compile 'com.victor:lib:1.0.4'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'me.grantland:autofittextview:0.2.0'//Removed the 0.2.+
compile 'com.wang.avi:library:1.0.5'
compile 'com.braintreepayments.api:drop-in:2.3.8'
compile 'com.android.support:design:24.2.1'

compile 'com.braintreepayments.api:braintree:2.3.9'
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.mxn.soul:flowingdrawer-core:1.2.2'
compile 'com.github.rengwuxian:MaterialEditText:2.1.4'

compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'

compile files('libs/sinch-android-rtc-3.9.14.jar')
compile 'com.amazonaws:aws-android-sdk-s3:2.4.4'  // you already have this
compile 'com.amazonaws:aws-android-sdk-cognito:2.4.4'

compile 'in.srain.cube:ultra-ptr:1.0.11'
}
</code>```

答:
Remove these jar files from the folder, not just from Gradle

```<code>compile files('libs/aws-android-sdk-s3-2.2.14.jar')
compile files('libs/aws-android-sdk-core-2.2.14.jar')
compile files('libs/aws-android-sdk-cognito-2.2.14.jar')
</code>```

Use these dependencies from Maven Central instead

```<code>compile 'com.amazonaws:aws-android-sdk-s3:2.4.4'  // you already have this
compile 'com.amazonaws:aws-android-sdk-cognito:2.4.4'
</code>```

Core is not needed because it's a transitive dependency

Body:
When trying to sign my AKP in Android Studio I keep getting an error:

Error:Error converting bytecode to dex:
Cause: com.android.dex.DexException: Multiple dex files define Lcom/amazonaws/AmazonClientException;

I tried to clean my project and other various solutions. I'm afraid of getting into deep directories and messing something up so I was hoping someone could help me!

My dependencies:

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.amazonaws:aws-android-sdk-s3:2.4.4'

//compile project(path: ':backend', configuration: 'android-endpoints')
compile 'com.github.chrisbanes:PhotoView:1.2.6'
compile 'com.davemorrissey.labs:subsampling-scale-image-view:3.5.0'
compile 'com.github.amlcurran.showcaseview:library:5.4.3'
compile 'com.github.d-max:spots-dialog:0.7@aar'
compile 'com.victor:lib:1.0.4'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'me.grantland:autofittextview:0.2.0'//Removed the 0.2.+
compile 'com.wang.avi:library:1.0.5'
compile 'com.braintreepayments.api:drop-in:2.3.8'
compile 'com.android.support:design:24.2.1'

compile 'com.braintreepayments.api:braintree:2.3.9'
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.mxn.soul:flowingdrawer-core:1.2.2'
compile 'com.github.rengwuxian:MaterialEditText:2.1.4'

compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'

compile files('libs/sinch-android-rtc-3.9.14.jar')
compile 'com.amazonaws:aws-android-sdk-s3:2.4.4'  // you already have this
compile 'com.amazonaws:aws-android-sdk-cognito:2.4.4'

compile 'in.srain.cube:ultra-ptr:1.0.11'
}

Body:
Remove these jar files from the folder, not just from Gradle

compile files('libs/aws-android-sdk-s3-2.2.14.jar')
compile files('libs/aws-android-sdk-core-2.2.14.jar')
compile files('libs/aws-android-sdk-cognito-2.2.14.jar')

Use these dependencies from Maven Central instead

compile 'com.amazonaws:aws-android-sdk-s3:2.4.4'  // you already have this
compile 'com.amazonaws:aws-android-sdk-cognito:2.4.4'

Core is not needed because it's a transitive dependency


问:
What is the concept behind creating instance of TransactionScope which uses DependentTransaction
I would like to ask about DependentTransaction aspects, the following code got from MSDN, https://msdn.microsoft.com/en-us/library/system.transactions.dependenttransaction

```<code>private static void WorkerThread(object transaction)
{
    //Create a DependentTransaction from the object passed to the WorkerThread
    DependentTransaction dTx = (DependentTransaction)transaction;

    //Sleep for 1 second to force the worker thread to delay
    Thread.Sleep(1000);

    //Pass the DependentTransaction to the scope, so that work done in the scope becomes part of the transaction passed to the worker thread
    using (TransactionScope ts = new TransactionScope(dTx))
    {
        //Perform transactional work here.

        //Call complete on the transaction scope
        ts.Complete();
    }

    //Call complete on the dependent transaction
    dTx.Complete();
}
</code>```

why would we need to create an instance of TransactionScope again where it uses DependentTransaction? Wouldn't be enough just to depend on DependentTransaction and to call DependentTransaction.Complete()?

答: TransactionScope creates the actual consructor for the Transaction ( 1 Transaction Constructor:Many Transactions). DependentTransaction is kind of different in that it relies on usage of the scope TransactionScope to end before that specific Transaction can complete. Meaning pretty much 1 or many transactions will complete after destruction. Try using directive Transactions, and then creating a DependentTransaction object. The rest should be self-explanatory.</p>

Body:
I would like to ask about DependentTransaction aspects, the following code got from MSDN, https://msdn.microsoft.com/en-us/library/system.transactions.dependenttransaction

private static void WorkerThread(object transaction)
{
    //Create a DependentTransaction from the object passed to the WorkerThread
    DependentTransaction dTx = (DependentTransaction)transaction;

    //Sleep for 1 second to force the worker thread to delay
    Thread.Sleep(1000);

    //Pass the DependentTransaction to the scope, so that work done in the scope becomes part of the transaction passed to the worker thread
    using (TransactionScope ts = new TransactionScope(dTx))
    {
        //Perform transactional work here.

        //Call complete on the transaction scope
        ts.Complete();
    }

    //Call complete on the dependent transaction
    dTx.Complete();
}

why would we need to create an instance of TransactionScope again where it uses DependentTransaction? Wouldn't be enough just to depend on DependentTransaction and to call DependentTransaction.Complete()?


问:
Installing Cloud SQL Proxy on Dataproc
I'm trying to install the Cloud MySQL Proxy on a Dataproc cluster with the initialization-action given as an example here. I removed all the hive-metadata part because I don't need it. The proxy is installed but I can't connect to my instance. The created cloud-sql-proxy.service file looks fine:

```<code>> cat /usr/lib/systemd/system/cloud-sql-proxy.service
[Unit]
Description=Google Cloud SQL Proxy
After=local-fs.target network-online.target
After=google.service
Before=shutdown.target

[Service]
Type=simple
ExecStart=/usr/local/bin/cloud_sql_proxy   -dir=/var/run/cloud_sql_proxy    -instances_metadata=attributes/additional-cloud-sql-instances

[Install]
WantedBy=multi-user.target
</code>```

Also, if I try to get the value of attributes/additional-cloud-sql-instances it looks fine:

```<code>> /usr/share/google/get_metadata_value attributes/additional-cloud-sql-instances
> myproject-12345:europe-west1:my-db-instance=tcp:3333
</code>```

Yet I can't connect to the instance. When I stop the service and start it again I see an error message:

```<code>> /usr/local/bin/cloud_sql_proxy -dir=/var/run/cloud_sql_proxy -instances_metadata=attributes/additional-cloud-sql-instances
2017/07/03 09:23:44 Ready for new connections
2017/07/03 09:23:44 Error on receiving new instances from metadata: metadata: GCE metadata "attributes/additional-cloud-sql-instances" not defined
</code>```

Am I doing something wrong?
In the meantime I can get this to work by using -instances=myproject-12345:europe-west1:my-db-instance=tcp:3333 instead of using the metadata key, but I wonder why it doesn't work as provided in the example.

答:
There's a subtle difference in how the Cloud SQL proxy interprets flags and how get_metadata_value interprets its input.

When using get_metadata_value, the attribute to read is assumed to be relative to

```<code>http://metadata.google.internal/computeMetadata/v1/instance/
</code>```

while in the case of the Cloud SQL proxy, all paths should be relative to:

```<code>http://metadata.google.internal/computeMetadata/v1/
</code>```

So if you're intention is to have the Cloud SQL proxy read instance metadata, pass in:

```<code>-instances_metadata=instance/attributes/additional-cloud-sql-instances
</code>```

Title: Installing Cloud SQL Proxy on Dataproc

Body:
I'm trying to install the Cloud MySQL Proxy on a Dataproc cluster with the initialization-action given as an example here. I removed all the hive-metadata part because I don't need it. The proxy is installed but I can't connect to my instance. The created cloud-sql-proxy.service file looks fine:

> cat /usr/lib/systemd/system/cloud-sql-proxy.service
[Unit]
Description=Google Cloud SQL Proxy
After=local-fs.target network-online.target
After=google.service
Before=shutdown.target

[Service]
Type=simple
ExecStart=/usr/local/bin/cloud_sql_proxy   -dir=/var/run/cloud_sql_proxy    -instances_metadata=attributes/additional-cloud-sql-instances

[Install]
WantedBy=multi-user.target

Also, if I try to get the value of attributes/additional-cloud-sql-instances it looks fine:

> /usr/share/google/get_metadata_value attributes/additional-cloud-sql-instances
> myproject-12345:europe-west1:my-db-instance=tcp:3333

Yet I can't connect to the instance. When I stop the service and start it again I see an error message:

> /usr/local/bin/cloud_sql_proxy -dir=/var/run/cloud_sql_proxy -instances_metadata=attributes/additional-cloud-sql-instances
2017/07/03 09:23:44 Ready for new connections
2017/07/03 09:23:44 Error on receiving new instances from metadata: metadata: GCE metadata "attributes/additional-cloud-sql-instances" not defined

Am I doing something wrong?
In the meantime I can get this to work by using -instances=myproject-12345:europe-west1:my-db-instance=tcp:3333 instead of using the metadata key, but I wonder why it doesn't work as provided in the example.

Body:
There's a subtle difference in how the Cloud SQL proxy interprets flags and how get_metadata_value interprets its input.

When using get_metadata_value, the attribute to read is assumed to be relative to

http://metadata.google.internal/computeMetadata/v1/instance/

while in the case of the Cloud SQL proxy, all paths should be relative to:

http://metadata.google.internal/computeMetadata/v1/

So if you're intention is to have the Cloud SQL proxy read instance metadata, pass in:

-instances_metadata=instance/attributes/additional-cloud-sql-instances


问:
Stylecop tells me to add this keyword, but it's redundant - any performance implications?
I use Stylecop for Resharper and whenever I call something in my class, Stylecop tells me to use the this keyword. But the IDE says this is redundant code (which it sure is), so why should I use the this keyword?

Does redundant code mean its not needed (obviously) and the compiler won't even do anything with the this keyword? So I assume the this keyword is just for clarity.

Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET? I assume it is all for clarity as stylecop keeps an eye on this and Fxcop (which I will use later on) keeps an eye on my code's quality from a technical point of view.

Thanks

答: Apart from the clarity examples provided the only other valid usage of the "this" keyword is to pass the current instance of an object as a paremeter. </p>

OwnerDisplayName: GSS

OwnerDisplayName: lomaxx

ContentLicense: CC BY-SA 2.5


问:
Generalizing Concurrent Map Function with Empty Interface In GOlang
So I'm super new to Golang and seeing as the big buzz around the language seems to be concurrency I figured a good way to get my toes wet would be to write a generalized map function. In psudo code:

```<code>map(F funtion,A array){
    return([F(k) for k in A])
}
</code>```

And obviously I want the calculations for each F(k) occur concurrently. For organization I have a main file with my implementation and a supporting file Mr with my required definitions.

```<code>.
├── main.go
└── Mr
    └── Mr.go
</code>```

Main is a simple test implementation which should convert an array of strings to an array of ints where each member of the result is the length of the corresponding string in the input array.

```<code>package main

import(
    "fmt"
    "./Mr"
)

func exfunc(i int, c chan int){
    c<-i
}

func main(){
    data := make(map[int]string)
    data[1]="these"
    data[2]="are"
    data[3]="some"
    data[4]="words"
    data[5]="and a few more..."
    f := func(w string)int{
        return(len(w))
    }
    testMr := Mr.Map(f,data) // this is line 22 (matters later)
    fmt.Println(testMr)
}
</code>```

Which works great with my Mr.Map function given that I specify all the types explicitly.

```<code>package Mr

type result struct{
    key,value int
}

func wrapper(f func(string) int,k int,v string, c chan result){
    c <- result{k,f(v)}
}

func Map(f func(string) int,m map[int]string) map[int]int{
    c := make(chan result)
    ret := make(map[int]int)
    n := 0
    for k := range m{
        go wrapper(f,k,m[k],c)
        n++
    }
    for ;n>0; {
        r := <-c
        ret[r.key]=r.value
        n--
    }
    return(ret)
}
</code>```

However I was hoping that I would be able to generalize this mapping with the empty interface.

```<code>package Mr

type T interface{}

type result struct{
    key,value T
}

func wrapper(f func(T) T,k T,v T, c chan result){
    c <- result{k,f(v)}
}

func Map(f func(T) T,m map[T]T) map[T]T{
    c := make(chan result)
    ret := make(map[T]T)
    n := 0
    for k := range m{
        go wrapper(f,k,m[k],c)
        n++
    }
    for ;n>0; {
        r := <-c
        ret[r.key]=r.value
        n--
    }
    return(ret)
}
</code>```

Unfortunately when I run main with this generalize Mr.Map I get the following error.

```<code># command-line-arguments
./main.go:22: cannot use f (type func(string) int) as type func(Mr.T) Mr.T in argument to Mr.Map
./main.go:22: cannot use data (type map[int]string) as type map[Mr.T]Mr.T in argument to Mr.Map
</code>```

So yeah, obviously I understand what the errors are telling me but it seems wild that I would have to re-write my Map function for each possible combination of key and value types.

Is there a work around here, or is this just the nature of the beast?

答:
No real workaround there, that's the nature of the beast.

The language was designed after struggling with C++ for some time, and the idea of the creators was simplifying all non-vital things but at the same time make key additions to make the language more expressive.

You can read a bit about their reasoning here, which I believe is quite interesting even if you don't agree with all the decisions they made:

https://commandcenter.blogspot.com.ar/2012/06/less-is-exponentially-more.html

In your example, if you wanted to, you could make your maps and functions use interface{} (which by the way is called the empty interface and not "nil" interface).

But of course you would lose compile-time type checking and would have to add casts all around.

You can also try to find an interface to express the commonalities of the types you want to use (which might not be so easy or even possible at all), and then build your mapping API around that interface.

Body:
So I'm super new to Golang and seeing as the big buzz around the language seems to be concurrency I figured a good way to get my toes wet would be to write a generalized map function. In psudo code:

map(F funtion,A array){
    return([F(k) for k in A])
}

And obviously I want the calculations for each F(k) occur concurrently. For organization I have a main file with my implementation and a supporting file Mr with my required definitions.

.
├── main.go
└── Mr
    └── Mr.go

Main is a simple test implementation which should convert an array of strings to an array of ints where each member of the result is the length of the corresponding string in the input array.

package main

import(
    "fmt"
    "./Mr"
)

func exfunc(i int, c chan int){
    c<-i
}

func main(){
    data := make(map[int]string)
    data[1]="these"
    data[2]="are"
    data[3]="some"
    data[4]="words"
    data[5]="and a few more..."
    f := func(w string)int{
        return(len(w))
    }
    testMr := Mr.Map(f,data) // this is line 22 (matters later)
    fmt.Println(testMr)
}

Which works great with my Mr.Map function given that I specify all the types explicitly.

package Mr

type result struct{
    key,value int
}

func wrapper(f func(string) int,k int,v string, c chan result){
    c <- result{k,f(v)}
}

func Map(f func(string) int,m map[int]string) map[int]int{
    c := make(chan result)
    ret := make(map[int]int)
    n := 0
    for k := range m{
        go wrapper(f,k,m[k],c)
        n++
    }
    for ;n>0; {
        r := <-c
        ret[r.key]=r.value
        n--
    }
    return(ret)
}

However I was hoping that I would be able to generalize this mapping with the empty interface.

package Mr

type T interface{}

type result struct{
    key,value T
}

func wrapper(f func(T) T,k T,v T, c chan result){
    c <- result{k,f(v)}
}

func Map(f func(T) T,m map[T]T) map[T]T{
    c := make(chan result)
    ret := make(map[T]T)
    n := 0
    for k := range m{
        go wrapper(f,k,m[k],c)
        n++
    }
    for ;n>0; {
        r := <-c
        ret[r.key]=r.value
        n--
    }
    return(ret)
}

Unfortunately when I run main with this generalize Mr.Map I get the following error.

# command-line-arguments
./main.go:22: cannot use f (type func(string) int) as type func(Mr.T) Mr.T in argument to Mr.Map
./main.go:22: cannot use data (type map[int]string) as type map[Mr.T]Mr.T in argument to Mr.Map

So yeah, obviously I understand what the errors are telling me but it seems wild that I would have to re-write my Map function for each possible combination of key and value types.

Is there a work around here, or is this just the nature of the beast?


问:
Can´t Create Virtual network gateway on Azure
I´m trying to connect my local network to Azure VPC, but I´m having trouble creating a "Virtual network gateway" I´m following this Tutorial, but on step 4 he ask me create a "Virtual network gateway" which I can´t do because he don´t detect my virtual network ("No virtual networks found in the selected subscription and location 'Brazil South'."). I have already created "the gateway subnet" manually but nothing seems to work. Any Ideas?

This is my configuration so far and also a print of the error.

VNet Name: SPI_VPC

Address Space: 10.11.0.0/16

Subnets:

default: 10.11.0.0/24

GatewaySubnet: 10.11.255.0/27

Location: Brazil South

Prints Virtual Gateway Error

答:
When you create Virtual Network, please ensure subnet address ranges don't use all address space. Because when you create VPN gateway, it needs create a gateway subnet. If you create Virtual Network like below:

when you create VPN gateway, you could not select the Virtual Network.

You should create Virtual Network like below:

Update:

Your Virtual Network is a classic Virtual Network. ARM Virtual Network Gateway only could select ARM mode Virtual Network. You could check your Virtual Network on Azure Portal.

You should create ARM mode Virtual Network.


问:
Why aren't my less files compiling in grunt?
I installed npm,
ran npm init,
installed grunt grunt-contrib-less grunt-contrib-watch jit-grunt --save-dev

and my gruntfile.js looks like:

```<code>module.exports = function(grunt) {
  require('jit-grunt')(grunt);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    less: {
      development: {
        options: {
          compress: true,
          yuicompress: true,
          optimization: 2
        },
        files: {
          "css/main.css": "less/main.less" // destination file : source file
        }
      }
    },
    watch: {
      styles: {
        files: ['_components/**/*.less'], // which files to watch
        tasks: ['less']
      }
    }
  });

  grunt.registerTask('default', ['less', 'watch']);
};
</code>```

when I run grunt in this directory everything seems to be going ok, except nothing is happening.

If I make a change grunt correctly spits out:

```<code>Running "watch" task
Waiting...
>> File "_components\less\_mixins.less" changed.
Running "less:development" (less) task
>> 1 stylesheet created.

Done.
Completed in 0.606s at Wed Jul 05 2017 12:45:41 GMT-0500 (Central Daylight Time) - Waiting...
</code>```

however when I go to check my main.less file it is empty and when I go to check my main.css file it is also empty. Is my code just not being compiled or is it going somewhere I'm not aware of?

答:
It's probably obvious, but make sure your paths to css and less files are correct and that your css/main.css file gets updated when you run less task.

Also, is there anything in your main.less file or do you import anything there? It might happen that there's just nothing to compile. I believe the way it's configured it's watching for changes in all your _components\less_mixins.less files and then compiles less/main.less into css/main.css, so you need to make sure there's something in there to compile.

Body:
I installed npm,
ran npm init,
installed grunt grunt-contrib-less grunt-contrib-watch jit-grunt --save-dev

and my gruntfile.js looks like:

module.exports = function(grunt) {
  require('jit-grunt')(grunt);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    less: {
      development: {
        options: {
          compress: true,
          yuicompress: true,
          optimization: 2
        },
        files: {
          "css/main.css": "less/main.less" // destination file : source file
        }
      }
    },
    watch: {
      styles: {
        files: ['_components/**/*.less'], // which files to watch
        tasks: ['less']
      }
    }
  });

  grunt.registerTask('default', ['less', 'watch']);
};

when I run grunt in this directory everything seems to be going ok, except nothing is happening.

If I make a change grunt correctly spits out:

Running "watch" task
Waiting...
>> File "_components\less\_mixins.less" changed.
Running "less:development" (less) task
>> 1 stylesheet created.

Done.
Completed in 0.606s at Wed Jul 05 2017 12:45:41 GMT-0500 (Central Daylight Time) - Waiting...

however when I go to check my main.less file it is empty and when I go to check my main.css file it is also empty. Is my code just not being compiled or is it going somewhere I'm not aware of?


问:
Excel2007 Is it possible add/remove data to/from pivot table programmatically?
Is it possible add/remove data to/from pivot table programmatically?

I created a pivot table for historical data.
I need to do what-if analysis.
So, I want the table to be updated automatically when I add/remove new data to/from the data table programmatically.

The first image show my pivot table.

Is it possible add an entry to the pivot table without touching the data source?

I am using excel 2007.

答:
You can update the pivot table by updating the pivot cache, the following code allows multiple pivot table in a sheet to be updated.</p>

```<code>Sub UpdateDataSource()

  Dim pt As PivotTable
  Dim Data As String

  'Data source of data
  Data = "'Data'!$B:$AB"

    For Each pt In ThisWorkbook.Sheets("Sheet1").PivotTables
      pt.ChangePivotCache _
      ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
      SourceData:=Data)
    Next pt

End Sub
</code>```

Body:
You can update the pivot table by updating the pivot cache, the following code allows multiple pivot table in a sheet to be updated.

Sub UpdateDataSource()

  Dim pt As PivotTable
  Dim Data As String

  'Data source of data
  Data = "'Data'!$B:$AB"

    For Each pt In ThisWorkbook.Sheets("Sheet1").PivotTables
      pt.ChangePivotCache _
      ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
      SourceData:=Data)
    Next pt

End Sub


问:
jumping to a certain point in the video
while using laravel 5 and google chrome to return the view that include a video tag
  I can't get to allow video seeking I found that it could relate to not
  accepting range in laravel but being quite noob I don't know what to do?? </p>

```<code>     <!-- the view -->
      <!DOCTYPE html>
      <html>
      <head>
        <title></title>
     </head>
      <body>
        <div id="app">
            <video id="xx" class="video-js vjs-big-play-centered"
            data-setup={} height="300px" width="300px"
            preload="none"  controls>
             <source src="{{asset('videos/property.mp4#t=120')}}"
             type="video/mp4" media="" >
             </video>
         </div>
      </body>
        </html>
</code>```

答:
It looks like you're using VideoJS as a video player. This is where you'll be able to handle scrubbing and jumping to a timestamp within the video. I'd check their documentation for the best way to handle that, and look at your Google Chrome dev tools console to see if there are any JavaScript errors.

There isn't currently a non-JavaScript way to start a video at a specified point, so I don't believe Laravel is the culprit here.

Title: jumping to a certain point in the video

Body:
while using laravel 5 and google chrome to return the view that include a video tag
  I can't get to allow video seeking I found that it could relate to not
  accepting range in laravel but being quite noob I don't know what to do??

      <!DOCTYPE html>

        <title></title>

            <video id="xx" class="video-js vjs-big-play-centered"
            data-setup={} height="300px" width="300px"
            preload="none"  controls>
             <source src="{{asset('videos/property.mp4#t=120')}}"
             type="video/mp4" media="" >
             </video>


问:
Working with TimeStamps and Moment.js
I have a script that updates my database every day at 9:30am. I’m using Ember.js for my application and I need to write a function that checks if a timestamp is past 9:30am or not. The feature should always be showing data, so if it is before 9:30am it should show the previous day’s data and if it's after then it should show the current day's data. So essentially the function would return a correct timestamp depending on what time of day it is. I’ve tried this using moment.js but cannot figure it out. Any help would be great.</p>

```<code>    payload.forEach(function(value) {
        // console.log("value: ", value );
        var nineThirty = ' 09:30:00';
        // Create date from input value
        var inputDate = moment( value.updated_at ).format('MM/DD/YYYY');
        var date = moment(inputDate + nineThirty);
        console.log("input Date: ", date );

        // yesterday
        var yesterdayDate = moment().subtract(1, 'days');
        var YD = moment( yesterdayDate ).format('MM/DD/YYYY');
        var yesterday = moment(YD + nineThirty );
        console.log("here: ", yesterday );

        // Get today's date
        var todaysDate = moment().format('MM/DD/YYYY');
        var today_date = moment(todaysDate + nineThirty);

        //... than something
    });
</code>```

答:
use isBefore
this will check if now if 9:30 is before the current time
if true date = today's date else the date is yesterdays date</p>

```<code>If(moment().set({hour: 9, minute: 30}).isBefore(moment())){
    date = moment().format('MM/DD/YYYY');
}
else{
    date= moment().subtract(1, 'days').format('MM/DD/YYYY');
}
</code>```

Title: Working with TimeStamps and Moment.js

Body:
I have a script that updates my database every day at 9:30am. I’m using Ember.js for my application and I need to write a function that checks if a timestamp is past 9:30am or not. The feature should always be showing data, so if it is before 9:30am it should show the previous day’s data and if it's after then it should show the current day's data. So essentially the function would return a correct timestamp depending on what time of day it is. I’ve tried this using moment.js but cannot figure it out. Any help would be great.

    payload.forEach(function(value) {
        // console.log("value: ", value );
        var nineThirty = ' 09:30:00';
        // Create date from input value
        var inputDate = moment( value.updated_at ).format('MM/DD/YYYY');
        var date = moment(inputDate + nineThirty);
        console.log("input Date: ", date );

        // yesterday
        var yesterdayDate = moment().subtract(1, 'days');
        var YD = moment( yesterdayDate ).format('MM/DD/YYYY');
        var yesterday = moment(YD + nineThirty );
        console.log("here: ", yesterday );

        // Get today's date
        var todaysDate = moment().format('MM/DD/YYYY');
        var today_date = moment(todaysDate + nineThirty);

        //... than something
    });

Body:
use isBefore
this will check if now if 9:30 is before the current time
if true date = today's date else the date is yesterdays date

If(moment().set({hour: 9, minute: 30}).isBefore(moment())){
    date = moment().format('MM/DD/YYYY');
}
else{
    date= moment().subtract(1, 'days').format('MM/DD/YYYY');
}


问:
replace string with patterns in file
I've used sed to replace variables on *.go files using sed -i 's/\<old_name\>/newName/g' *.go
My objective is to eliminate golinter errors.
How can strings with common patterns, e.g. replace 1 with 2

fmt.Printf("blah blah blah") or fmt.Printf("yadda yadda yadda")

fmt.Println("blah blah blah") or fmt.Println("yadda yadda yadda")

In this case, we do NOT want to replace:
1. fmt.Printf("print speed= %d",speed) //So the key here is the ending pattern should be ").
2. log.Printf statements //only replace "fmt."
Any pointers on this?

答:
I'm slightly confused by your question, but think you're trying to do the following:

```<code>replace      printf("yada yada yada") with println("yada yada yada")
not replace  printf("print speed = %d", speed)
</code>```

If that is the case, I would do something like the following:

```<code>sed -i '/Printf(\".*\")/ s/Printf/Println/g' *.go
</code>```

That should leave cases intact where you actually want to use formatting. Here is an example:

```<code>[sborza@msandn]:~$ cat tester.go
package main

import "fmt"

func main() {
        speed = 1
        fmt.Printf("vim-go")
        fmt.Printf("speed = %d\n", speed)
}

[sborza@msandn]:~$ sed '/Printf(\".*\")/ s/Printf/Println/g' tester.go
package main

import "fmt"

func main() {
        speed = 1
        fmt.Println("vim-go")
        fmt.Printf("speed = %d\n", speed)
}
</code>```

Title: replace string with patterns in file

Body:
I'm slightly confused by your question, but think you're trying to do the following:

replace      printf("yada yada yada") with println("yada yada yada")
not replace  printf("print speed = %d", speed)

If that is the case, I would do something like the following:

sed -i '/Printf(\".*\")/ s/Printf/Println/g' *.go

That should leave cases intact where you actually want to use formatting. Here is an example:

[sborza@msandn]:~$ cat tester.go
package main

import "fmt"

func main() {
        speed = 1
        fmt.Printf("vim-go")
        fmt.Printf("speed = %d\n", speed)
}

[sborza@msandn]:~$ sed '/Printf(\".*\")/ s/Printf/Println/g' tester.go
package main

import "fmt"

func main() {
        speed = 1
        fmt.Println("vim-go")
        fmt.Printf("speed = %d\n", speed)
}


问:
How to upload APN Certification to firebase for FCM
Now I'm trying to get FCM in IOS

So I use firebase doc

Mac - keychain ; get .certisigningRequest file

apple developer console ; generating .cer file using 1. file

apple developer console ; generating 'APP ID' using bundle id.
ex) com.google.PushTest

Mac - keychain ; generating .p12 file

firebase console ; adding IOS app and set Firebase SDK

firebase console ; upload APN certi( from num 4. )

My problem is num 6!!

I can't upload APN when I try to upload firebase give to like this error

"There was an error reading the certificate."

What should I do??

Please help me thanks

答:
i solve my problem my self!!

when i extract .p12 file i chose 2types so firebase console can not accept...

now my pushTest app is work!

thx


问:
How to parse output of dependency tree into flattened structure
Okay, I am completely at a loss. I have some output from a dependency tree parsing tool that looks like the following:

```<code>(S
    (NP
        (PRP It)
    )
    (VP
        (VBD said)
        (CLAUSE
            (S
                (NP
                    (DT the)
                    (NN figure)
                )
                (VP
                    (VBD was)
                    (VBN rounded)
                )
            )
        )
    )
    (PUNC .)
)
</code>```

These parse outputs are saved as plain-text. The output is basically a binary tree as far as I can tell. What I would like is to have an output file where each word is on a new line, and each word contains all of the labels associated with the word. An example is:

```<code>It  S   NP  PRP
said    S   VP
the S   VP  CLAUSE  S   NP  DT
figure  S   VP  CLAUSE  S   NP  NN
was S   VP  CLAUSE  S   VP  VBD
rounded S   VP  CLAUSE  S   VP  VBN
. PUNC  S
</code>```

How can I parse this output into the output I'm looking for? I've attempted to use the pyparsing library, and have been able to parse the string into a hierarchical list of lists, but this doesn't quite match my output needs.

I think recursion is probably a good candidate tool here, but I'm not sure how to apply it to this problem. Any help on this would be appreciated - even pseudo-code to get the implementation idea.

答:
First up, there are mistakes in your output transitions.

To approach a solution, recursion is required. But you don't have to invent the wheel. There's a nice little module called pyparsing just for tasks like this. We can convert that string to a nested list of lists using recursive regex:

```<code>from pyparsing import nestedExpr

astring = '''(S
    (NP
        (PRP It)
    )
    (VP
        (VBD said)
        (CLAUSE
            (S
                (NP
                    (DT the)
                    (NN figure)
                )
                (VP
                    (VBD was)
                    (VBN rounded)
                )
            )
        )
    )
    (PUNC .)
)'''

expr = nestedExpr('(', ')')
result = expr.parseString(astring).asList()[0]

print(result)
</code>```

This prints out:

```<code>['S',
 ['NP', ['PRP', 'It']],
 ['VP',
  ['VBD', 'said'],
  ['CLAUSE',
   ['S',
    ['NP', ['DT', 'the'], ['NN', 'figure']],
    ['VP', ['VBD', 'was'], ['VBN', 'rounded']]]]],
 ['PUNC', '.']]
</code>```

Next up, we'll need to write a function that can build transitions from the given parse tree. Sadly, there's no easy way to do this. We'll need to write a hardcore recursive subroutine ourselves. Here's one approach. Use the nth symbol and retrieve all transitions for the n+1 symbols, and then build a new list of transitions by appending the nth symbol to those transitions.

Sounds a little complicated, but maybe the code will help you understand:

```<code>def get_rules(rule_list):
    transitions = []

    if len(rule_list) == 2 and isinstance(rule_list[1], str):
        return [rule_list]

    for rule in rule_list[1:]:
        for r in get_rules(rule):
            transitions.append([rule_list[0]] + r)

    return transitions
</code>```

It's pretty simple. There's a base case, where you return a singleton transition if you reach a terminal. Otherwise build transitions recursively.

Calling this function and printing the results are done next:

```<code>for r in get_rules(result):
    print(r[-1] + '\t' + '\t'.join(r[:-1]))
</code>```

Output:

```<code>It  S   NP  PRP
said    S   VP  VBD
the S   VP  CLAUSE  S   NP  DT
figure  S   VP  CLAUSE  S   NP  NN
was S   VP  CLAUSE  S   VP  VBD
rounded S   VP  CLAUSE  S   VP  VBN
.   S   PUNC
</code>```

I mentioned earlier that your transitions were represented incorrectly. You can cross check with this, this is the right answer.

Body:
Okay, I am completely at a loss. I have some output from a dependency tree parsing tool that looks like the following:

(S
    (NP
        (PRP It)
    )
    (VP
        (VBD said)
        (CLAUSE
            (S
                (NP
                    (DT the)
                    (NN figure)
                )
                (VP
                    (VBD was)
                    (VBN rounded)
                )
            )
        )
    )
    (PUNC .)
)

These parse outputs are saved as plain-text. The output is basically a binary tree as far as I can tell. What I would like is to have an output file where each word is on a new line, and each word contains all of the labels associated with the word. An example is:

It  S   NP  PRP
said    S   VP
the S   VP  CLAUSE  S   NP  DT
figure  S   VP  CLAUSE  S   NP  NN
was S   VP  CLAUSE  S   VP  VBD
rounded S   VP  CLAUSE  S   VP  VBN
. PUNC  S

How can I parse this output into the output I'm looking for? I've attempted to use the pyparsing library, and have been able to parse the string into a hierarchical list of lists, but this doesn't quite match my output needs.

I think recursion is probably a good candidate tool here, but I'm not sure how to apply it to this problem. Any help on this would be appreciated - even pseudo-code to get the implementation idea.

Body:
First up, there are mistakes in your output transitions.

To approach a solution, recursion is required. But you don't have to invent the wheel. There's a nice little module called pyparsing just for tasks like this. We can convert that string to a nested list of lists using recursive regex:

from pyparsing import nestedExpr

astring = '''(S
    (NP
        (PRP It)
    )
    (VP
        (VBD said)
        (CLAUSE
            (S
                (NP
                    (DT the)
                    (NN figure)
                )
                (VP
                    (VBD was)
                    (VBN rounded)
                )
            )
        )
    )
    (PUNC .)
)'''

expr = nestedExpr('(', ')')
result = expr.parseString(astring).asList()[0]

print(result)

This prints out:

['S',
 ['NP', ['PRP', 'It']],
 ['VP',
  ['VBD', 'said'],
  ['CLAUSE',
   ['S',
    ['NP', ['DT', 'the'], ['NN', 'figure']],
    ['VP', ['VBD', 'was'], ['VBN', 'rounded']]]]],
 ['PUNC', '.']]

Next up, we'll need to write a function that can build transitions from the given parse tree. Sadly, there's no easy way to do this. We'll need to write a hardcore recursive subroutine ourselves. Here's one approach. Use the nth symbol and retrieve all transitions for the n+1 symbols, and then build a new list of transitions by appending the nth symbol to those transitions.

Sounds a little complicated, but maybe the code will help you understand:

def get_rules(rule_list):
    transitions = []

    if len(rule_list) == 2 and isinstance(rule_list[1], str):
        return [rule_list]

    for rule in rule_list[1:]:
        for r in get_rules(rule):
            transitions.append([rule_list[0]] + r)

    return transitions

It's pretty simple. There's a base case, where you return a singleton transition if you reach a terminal. Otherwise build transitions recursively.

Calling this function and printing the results are done next:

for r in get_rules(result):
    print(r[-1] + '\t' + '\t'.join(r[:-1]))

Output:

It  S   NP  PRP
said    S   VP  VBD
the S   VP  CLAUSE  S   NP  DT
figure  S   VP  CLAUSE  S   NP  NN
was S   VP  CLAUSE  S   VP  VBD
rounded S   VP  CLAUSE  S   VP  VBN
.   S   PUNC

I mentioned earlier that your transitions were represented incorrectly. You can cross check with this, this is the right answer.


问:
What is the lookup procedure when setting an attribute from a class or from an instance?
Python in a Nutshell describes  the lookup procedure when getting an attribute from a class, e.g. cls.name and the lookup procedure when getting an attribute from an instance, e.g. obj.name

But I am not sure when it comes to setting an attribute:

Setting an attribute

Note that the attribute lookup steps happen as just described only
  when you refer to an attribute, not when you bind an attribute. When
  you bind (on either a class or an instance) an attribute whose name is
  not special (unless a  __setattr__  method, or the  __set__
  method  of  an  overriding  descriptor,  intercepts  the  binding  of
  an instance attribute), you affect only the  __dict__  entry for the
  attribute (in the class or instance, respectively). In other words,
  for attribute binding, there is no lookup procedure involved, except
  for the check for overriding descriptors.

My questions are:

What is the "lookup" procedure when setting an attribute from a class, e.g. cls.name=value?

What is the "lookup" procedure when setting an attribute from an object, e.g. obj.name=value?

The procedures seem to involve

the __setattr__  method

__setattr__(self, name, value)

At every request to bind attribute x.y (typically, an assignment statement
  x.y=value, but also, for example, setattr(x, 'y', value)), Python calls
  x.__setattr__('y', value). Python always calls __setattr__ for any
  attribute binding on x—a major diff erence from __getattr__ (__setattr__ is
  closer to __getattribute__ in this sense). To avoid recursion, when
  x.__setattr__ binds x’s attributes, it must modify x.__dict__ directly (e.g.,
  via x.__dict__[name]=value); even better, __setattr__ can delegate the
  setting to the superclass (by calling super(C, x).__setattr__('y', value)
  or, in v3, just super().__setattr__('y', value)). Python ignores the
  return value of __setattr__. If __setattr__ is absent (i.e., inherited from
  object), and C.y is not an overriding descriptor, Python usually translates x.y=z
  into x.__dict__['y']=z.

the  __set__  method  of  an  overriding  descriptor (So I asked  Why does `object.__get__` have an argument `owner` for the owner class, while `object.__set__` doesn't?)

the  __dict__  entry for the attribute (in the class or instance, respectively)

Given that the book distinguishes the lookup procedures for getting an attribute from a class and from an instance, it is natural to think that the "lookup" procedures are different when setting an attribute from a class and when setting an attribute from an instance.

But since in Python3, every class object is actually an instance of its metaclass (e.g. type class), are the "lookup" procedure for setting an attribute from a class and the "lookup" procedure for setting an attribute from an instance really different?

Thanks.

答:
For x.y = z, Python looks up x.__setattr__ in a way that bypasses __getattribute__, __getattr__, and x's own __dict__, then calls x.__setattr__('y', z).

A custom __setattr__ can do whatever the heck it wants, but here's the default:

Search type(x).__mro__ for a __dict__ entry matching the attribute name.

If this search finds a descriptor descr with a __set__ method (looking up __set__ the same way we looked up __setattr__), call descr.__set__(x, z).

2.a. In the highly unusual case that the search finds a descriptor with __delete__ but no __set__, raise an AttributeError.

Otherwise, set x.__dict__['y'] = z, or raise an AttributeError if x has no __dict__. (This uses the "real" __dict__, bypassing things like mappingproxy.)

This applies to both types and other objects, with the caveats that type.__setattr__ will refuse to set attributes of a class written in C, and type.__setattr__ does some extra internal maintenance you'll never need to worry about unless you do something crazy and unsupported to bypass it.

ContentLicense: CC BY-SA 4.0


问:
Programming app for multiple targets?
I'm programming an app that will have a free version. I have added another target to my app (MyApp Free) and am wondering how I can now add the proper #ifdef declarations to my code. If anyone knows of a tutorial or can provide me with more information on this I will be very grateful.

答:
Keith Peters has a great tutorial on this: http://www.bit-101.com/blog/?p=2098

As for me, I just released two apps, one a lite version of the other. I set up two different projects, with the lite version getting most of its code from the non-lite one. Personally, I like having it separate like this (though by no means am I saying it's the preferred/good-practice way of doing this).

In the future, for what it's worth, I plan on just having one version in the App Store and enabling the premium features with an In-App purchase. Unlocking functionality seems really easy to implement with In-App purchases...

Title: Programming app for multiple targets?