问:
jQuery: hover (mouseleave event fired when mouse is over child)
I want to create a zoom effect on some thumbs.

Here is my javascript simplified code :

```<code>parent.hover(
 function(){
   parent.stop().animate({/* css */}, inputZoomDuration, "linear");
   wrapper.stop().animate({/* css */}, inputZoomDuration, "linear");
   child.stop().animate({/* css */}, inputZoomDuration, "linear");
 },
 function(){
  alert("leave");
  child.stop().animate({/* css */}, 140, "linear");
  wrapper.stop().animate({/* css */}, 140, "linear");
  parent.stop().animate({/* css */}, 140, "linear");
 }
);
</code>```

and the html is like :

```<code><div parent>
 <div wrapper>
  <div child>

  </div>
 </div>
</div>
</code>```

I increase the size of all my divs when I over the "parent". But a soon as I over (or leave, btw) one of the child, the alert appears.
Without the alert, the result is a very bugy animation.
Is there any way to prevent the mouseleave event to be fired when a child is overed?

Best regards,

thanks.

Edit :
Here is the greasemonkey script : http://userscripts.org/scripts/show/94786
and a link to test it : http://browse.deviantart.com/
We can see in the console that the mouseleave event is trigerred when I leave the orange div, unlike this example : http://www.jsfiddle.net/wnuS6/3/ where the event is not fired when I leave the red div.

答:
After some investigations, it seems that the problem comes from greasemonkey.
Here is what the wiki said :

Some versions of jQuery will not run
  inside the Greasemonkey sandbox. As of
  this writing, 1.3.2 does work, but
  1.4.1 does not. It is possible to patch 1.4 versions of jQuery to work,
  see jQuery Forum: Importing jQuery
  1.4.1 into greasemonkey scripts generates an error

However, all versions 1.4.x patched of jQuery still don't work in my specific hover case AND only with greasemonkey (indeed, I test the same script in jsFiddle, and that works with jQuery 1.4.4).

To solve the problem, I simply use jQuery 1.3.2 (and of course, I have to adapt my code a bit).

Body:
I want to create a zoom effect on some thumbs.

Here is my javascript simplified code :

parent.hover(
 function(){
   parent.stop().animate({/* css */}, inputZoomDuration, "linear");
   wrapper.stop().animate({/* css */}, inputZoomDuration, "linear");
   child.stop().animate({/* css */}, inputZoomDuration, "linear");
 },
 function(){
  alert("leave");
  child.stop().animate({/* css */}, 140, "linear");
  wrapper.stop().animate({/* css */}, 140, "linear");
  parent.stop().animate({/* css */}, 140, "linear");
 }
);

and the html is like :

I increase the size of all my divs when I over the "parent". But a soon as I over (or leave, btw) one of the child, the alert appears.
Without the alert, the result is a very bugy animation.
Is there any way to prevent the mouseleave event to be fired when a child is overed?

Best regards,

thanks.

Edit :
Here is the greasemonkey script : http://userscripts.org/scripts/show/94786
and a link to test it : http://browse.deviantart.com/
We can see in the console that the mouseleave event is trigerred when I leave the orange div, unlike this example : http://www.jsfiddle.net/wnuS6/3/ where the event is not fired when I leave the red div.


来源: stackexchange

问:
How to add default argument values in C# client code from Swagger API definition
Has anyone had much experience converting Swagger API definitions to C#.NET client code?

Mostly, Swagger Editor works ok, but the issue we have is that the generated code for some calls has a bunch of required-but-nullable arguments. Eg (truncated argument list for illustration only):

```<code>GetCustomers(bool? includeDeceased, string postalCode, string id, string dateAdded)
</code>```

We would like the generated parameter list to be defined with default values to avoid having to explicitly provide null arguments. So something like this:

```<code>GetCustomers(bool? includeDeceased = null, string postalCode = null, int? id = null, string dateAdded = null)
</code>```

This allows us to make the following call:

```<code>GetCustomers(postalCode: "12345")
</code>```

Rather than:

```<code>GetCustomers(includeDeceased: null, postalCode="12345", id: null, dateAdded: null)
</code>```

We've tried adding "default": null to the Swagger call definitions where appropriate but this doesn't result in the desired code (in fact, no change, so probably not supported).

Short of manually modifying the resulting client code – which we want to avoid so we can quickly and easily update our code to the latest API definitions – we're a bit stuck.

答:
Well, it seems that the Swagger Editor CsharpDotNet2 client code generator is the culprit here.

I just tried the bog-standard csharp client code generator and it added = null to all arguments not marked "required": true.

So I guess it's manually edit the CsharpDotNet2 generator or use the csharp one if you can.

UPDATE And, in case you're wondering, it turns out that the csharp generator is actually the newer one, targeted at .NET 4.5. I was thinking that if one had "DotNet" in the name and the other didn't that that was the one to go for. Silly me.

ContentLicense: CC BY-SA 3.0

Body:
Has anyone had much experience converting Swagger API definitions to C#.NET client code?

Mostly, Swagger Editor works ok, but the issue we have is that the generated code for some calls has a bunch of required-but-nullable arguments. Eg (truncated argument list for illustration only):

GetCustomers(bool? includeDeceased, string postalCode, string id, string dateAdded)

We would like the generated parameter list to be defined with default values to avoid having to explicitly provide null arguments. So something like this:

GetCustomers(bool? includeDeceased = null, string postalCode = null, int? id = null, string dateAdded = null)

This allows us to make the following call:

GetCustomers(postalCode: "12345")

Rather than:

GetCustomers(includeDeceased: null, postalCode="12345", id: null, dateAdded: null)

We've tried adding "default": null to the Swagger call definitions where appropriate but this doesn't result in the desired code (in fact, no change, so probably not supported).

Short of manually modifying the resulting client code – which we want to avoid so we can quickly and easily update our code to the latest API definitions – we're a bit stuck.


问:
Removing class from scrollspy link
How can i remove the active class on this link and replace it with active2 using jQuery?

```<code><li class="contact active"><a href="#contact" class="contact">Contact</a></li>
</code>```

remove

active {background-color: black;}

replace

active2 {background-color: red;}

答:
Here you go with a solution

Remove old class

```<code>$('li.contact').removeClass('active');
</code>```

Adding new Class

```<code>$('li.contact').addClass('active2');
</code>```

You can do it in a single statement using jQuery chaining feature

```<code>$('li.contact')
  .removeClass('active')
  .addClass('active2');
</code>```

Demo

$('li.contact').hover(function(){
  $(this).removeClass('active').addClass('active2');
}, function(){
  $(this).removeClass('active2').addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {background-color: black;}
.active2 {background-color: red;}</code>```

Contact
```

Hope this will help you.

Title: Removing class from scrollspy link

Body:
How can i remove the active class on this link and replace it with active2 using jQuery?

Contact

remove

active {background-color: black;}

replace

active2 {background-color: red;}

Body:
Here you go with a solution

Remove old class

$('li.contact').removeClass('active');

Adding new Class

$('li.contact').addClass('active2');

You can do it in a single statement using jQuery chaining feature

$('li.contact')
  .removeClass('active')
  .addClass('active2');

Demo

$('li.contact').hover(function(){
  $(this).removeClass('active').addClass('active2');
}, function(){
  $(this).removeClass('active2').addClass('active');
});

.active {background-color: black;}
.active2 {background-color: red;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="contact active"><a href="#contact" class="contact">Contact</a></li>

Hope this will help you.


问:
Creating Immutable JObject
I am trying to create an extension class of JObject, which is immutable.

If I create a class like below, can it prevent the actual JObject being modified?

```<code>public class ImmutableJObejct: JObject
{
    public readonly JObject JObject;
    public ImmutableJObejct(JObject jObject)
    {
        this.JObject = jObject;
    }
}
</code>```

Which is the right approach?
should I not be expending the code and implement each methods that I need from JOBject?

答:
To answer your question: Yes and no. Or "it depends".

There are basically 2 kinds of immutable objects: "shallow" immutable objects where all properies are readonly and does not have any methods that modify state, and "deep" immutable objects where not only are all  properties readonly, they are also either themselves immutable or copies of a mutable object.

Your example is an example of a shallow immutable object.  It doesn't allow you to give your ImmutableJobject a new JOject once it is created, but you can possibly change properties on that object. To make it a deep immutable object, the field JObject needs to be changed to a readonly property, that creates a new JObject everytime it is accessed.

Update: As with all things, immutablility comes with cost and benefits.  The primary cost is in the need to create more objects, either to capture a new state, or to keep deep immutable objects from having their properties changed. Depending upon how many such objects are created and how long they are tracked/referenced, this can impact both cpu and memory.  Unless you control all of the objects in the object's graph/hierarchy, there is little you can do to avoid this cost.

Title: Creating Immutable JObject

Body:
I am trying to create an extension class of JObject, which is immutable.

If I create a class like below, can it prevent the actual JObject being modified?

public class ImmutableJObejct: JObject
{
    public readonly JObject JObject;
    public ImmutableJObejct(JObject jObject)
    {
        this.JObject = jObject;
    }
}

Which is the right approach?
should I not be expending the code and implement each methods that I need from JOBject?


问:
Custom Sort By "%%" in mysql
I have a table like this:

```<code>|city_name|
 Shadyside
 Chalkyitsik
 Wyalusing
 Quartzsite
 Seaside
 Shawnee Mission
 Siberia
 Sibley
 Nicasio
 Lacassine
 Sicily Island
 Andalusia
 Sidell
 Sidney
 ...
 ..
 .
</code>```

And selected with the following queries:

```<code>SELECT city_name FROM my_table WHERE city_name LIKE '%si%'
</code>```

Instead of '%si%', anything can be put.

I want to sort by the words first started with 'si'.

And the output is like this:

```<code>|city_name|
 Siberia
 Sibley
 Sicily Island
 Sidell
 Sidney
 ... And the rest of the words that are '%si%'
</code>```

How should this sorting(ORDER BY) be done?

答:
```<code>SELECT city_name
FROM my_table
WHERE city_name LIKE '%si%'
ORDER BY (city_name LIKE 'si%') DESC;
</code>```

Title: Custom Sort By "%%" in mysql

Body:
I have a table like this:

|city_name|
 Shadyside
 Chalkyitsik
 Wyalusing
 Quartzsite
 Seaside
 Shawnee Mission
 Siberia
 Sibley
 Nicasio
 Lacassine
 Sicily Island
 Andalusia
 Sidell
 Sidney
 ...
 ..
 .

And selected with the following queries:

SELECT city_name FROM my_table WHERE city_name LIKE '%si%'

Instead of '%si%', anything can be put.

I want to sort by the words first started with 'si'.

And the output is like this:

|city_name|
 Siberia
 Sibley
 Sicily Island
 Sidell
 Sidney
 ... And the rest of the words that are '%si%'

How should this sorting(ORDER BY) be done?


问:
Is there any way to prevent people from making my web game available offline?
It's not the type of game that really need a server to operate. I'm using javascript and html5 right now, and I cant think of a way to prevent the game from being rip off.

Using obsfucator is useless, the game would still work offline.

Implementing a validation scheme is not invincible either. Someone smart can just crack the script and remove the validation part.

答: You could continue to use html5 and javascript, but move your javascript to the server side using node.js For example http://www.yuiblog.com/blog/2010/09/29/video-glass-node/</p>

ContentLicense: CC BY-SA 2.5


问:
RTSP streaming on VLC
We have implemented RTSP server on our MCU. For testing purpose we are using VLC media player as a client.  We coded our MCU such a way that only after receiving PLAY command from client, MCU reads data from camera. And we are seeing MCU receives data from camera and streams thorugh RTSP.  We could see  data streaming from server through UDP on Wireshark. And Also Codec information getting dispalyed on VLC media player. But video doesn't get played in VLC.What could be the issue?
Below is our SDP file info

"v=0\r\ns=Unnamed\r\ni=N/A\r\nc=IN IP4 sumukha-PC\r\nt=0 0\r\na=tool:vlc 2.2.2\r\na=recvonly\r\na=type:broadcast\r\na=charset:UTF-8\r\na=control:rtsp://192.168.1.100:8555\r\nm=video 0 RTP/AVP 96\r\nb=RR:0\r\na=rtpmap:96 H264/90000\r\na=fmtp:96 packetization-mode=1\r\na=control:rtsp://192.168.1.100:8555/trackID=0\r\n\r\n");

Thanks,
Ck

答:
I suggest using ffmpeg and ffplay to test your streaming from a RTSP source.

It is command line, but the information and logs are very helpful

Title: RTSP streaming on VLC


问:
How to create AutoCAD Layers using windows forms?
I'm working on creating a windows form plugin to create Layers from the user selected items on my windows form.

I am reading a list of Layers in to a list box(lbGetLayers), a list of modifiers in to another listbox(lbModifyer) from two different csv files. Additionally, I have created two classes to hold the layer, modifier objects.

Goal: is to create a new layer with the correct Name, Color, Line Style, and Line Weight based on user selected items.

Issue:
I am trying to write a function to build the logic before creating the layer to satisfy the below two conditions:

1) Layer- Will have a color, line style, and line weight. Let the user pick 1 or more. If the user picks more than 1 then the app will create all layers selected.

2)Modifier – will override the color, line style, and line weight. The user can pick 0 or 1.

3)Status(Edited) - will again override the color, line style and the line weight. The user can pick 0 or 1.

I came up with the a function which is not appropriate to satisfy these conditions.
I'd really appreciate if somebody could help me solving this problem.

Thanks!!

BuildLayers:

```<code>  public Intellayer Buildlayer()
{
    //can select Layer - 1 or more
    //Get Selected Layer Object - color, line style & line weight
       foreach(Intellayer SelectedLayer in lbGetLayers.Items)
       {
            foreach (Modifyer SelectedModifyer in lbModifyer.Items)
            {
                if(lbGetLayers.SelectedItems.Count > 1 || lbModifyer.SelectedItems.Count <= 1)
                System.Diagnostics.Debug.WriteLine(SelectedLayer.layername + "-" + SelectedModifyer.name);
            }
        }
</code>```

Class:

```<code>public class layer
    {
       public string disciplane { get; set; }
       public string layername { get; set; }
       public string Linetype { get; set; }
       public int? Layercolor { get; set; }
       public string Description { get; set; }
       public string Lineweight { get; set; }
       public override string ToString()
        {
            return layername;
        }
    }

 public class Modifyer
    {
        public string discipline { get; set; }
        public string name { get; set; }
        public int? color { get; set; }
        public string Linetype {get;set;}
        public string Lineweight { get; set; }
        public string Description { get; set; }
        public override string ToString()
        {
            return name;
        }
    }
</code>```

Edited:

BuildLayers:

```<code> public List<layer> Buildlayers()
        {
            //Build selected layers

            List<layer> Getselectedlayers = null;//list of selected layers
            if (lbGetLayers.SelectedItems.Count >= 1)
            {
                    Getselectedlayers = new List<layer>();
                    Getselectedlayers.AddRange(lbGetLayers.SelectedItems.Cast<layer>());
                    foreach (layer lname in Getselectedlayers)
                    {
                        lbGetLayers.SelectedItems.Cast<layer>();
                        System.Diagnostics.Debug.WriteLine(lname.Linetype + "," + lname.Lineweight + "," + lname.Layercolor);
                     }
                if (lbModifyer.SelectedItems.Count == 1)
                {
                    Modifyer modifyer = (Modifyer)lbModifyer.SelectedItem;
                    foreach (layer lname in Getselectedlayers)
                    {
                        lname.Override(modifyer);//Override with Modifyers
                    }
                }
                if(lbStatus.SelectedItems.Count == 1)
                {
                     Status status = (Status)lbStatus.SelectedItem;
                    foreach (layer lname in Getselectedlayers)
                    {
                        lname.Override(status);//Override with Status
                    }
                }
            }
            return Getselectedlayers;//return list of selected layers
        }
        }
    }
</code>```

Class:

```<code> public class layer
        {
           public string disciplane { get; set; }
           public string layername { get; set; }
           public string Linetype { get; set; }
           public int? Layercolor { get; set; }
           public string Description { get; set; }
           public string Lineweight { get; set; }

            public layer Override(Modifyer modifyer)
            {
                layer newLayer = new layer();
                newLayer.layername = this.layername;
                newLayer.Layercolor = modifyer.color;
                newLayer.Linetype = modifyer.Linetype;
                newLayer.Lineweight = modifyer.Lineweight;
                return newLayer;
            }
           public layer Override(Status status)
            {
                layer newlayer = new layer();
                newlayer.layername = this.layername;
                newlayer.Layercolor = status.color;
                newlayer.Linetype = status.Linetype;
                newlayer.Lineweight = status.Lineweight;
                return newlayer;
            }
            public override string ToString()
            {
                return layername;
            }
        }
</code>```

答:
You seem to have most of the meat there, but there are a couple issues in the code you posted aside from the logic inside the Buildlayer() method.

Let's start with the constructor. The point of the constructor is to initialize the form. This is also a good place to assign data to your controls. Here, the user has not had a chance to select any items as the forms is not yet visible. This is where you should be parsing your CSV file and assigning the resulting objects to your respective listboxes.

```<code>public LayerCreationTool()
{
    InitializeComponent();
    fillListBoxes();
}

private void fillListBoxes()
{
    //get layers from CSV here and put them into ListBox
    lbGetLayers.Items.AddRange(getLayersFromCSV().ToArray());
    lbModifyer.Items.AddRange(getModifiersFromCSV().ToArray());
}

private List<layer> getLayersFromCSV()
{
    List<layer> layers = new List<layer>();
    //...Do your parsing here;
    return layers;
}

private List<Modifier> getModifiersFromCSV()
{
    List<Modifier> modifiers = new List<Modifier>();
    //...Do your parsing here;
    return modifiers;
}
</code>```

I also added a method Override() to your layer class. This will allow you to easily utilize your modifier.

```<code>public class layer
{
    public string layername { get; set; }
    public string Linetype { get; set; }
    public int? Layercolor { get; set; }
    public string Lineweight { get; set; }

    public layer Override(Modifier modifier)
    {
        layer newLayer = new layer();
        newLayer.layername = this.layername;
        newLayer.Layercolor = modifier.color;
        newLayer.Linetype = modifier.Linetype;
        newLayer.Lineweight = modifier.Lineweight;
        return newLayer;
    }

    public override string ToString()
    {
        return layername;
    }
}
</code>```

Now that you have a functional form, you need a way for the user to say "Go". I've taken the liberty of adding a button to the form, and in the click event of the button is where you should be creating your layers as per your logic. Also, Since you want to be returning more than one layer, Buildlayers() should return List<layer> rather than layer.

The idea for the logic is simple: if a modifier is NOT selected, then add all the selected layers to add to AutoCad. If a modifier IS selected, then use the Override() method to grab and modify all selected items one at a time.

```<code>private void btnImport_Click(object sender, EventArgs e)
{
    List<layer> layersToAddToAutoCad = Buildlayers();
    //now use your these layers to add to AutoCad...
}

//You need to return a List of layers that you then use
//to add layers to AutoCad
public List<layer> Buildlayers()
{
    List<layer> ret = null;

    if(lbGetLayers.SelectedItems.Count > 0)
    {
        ret  = new List<layer>();
        //if no modifier selected, great, just grab all the selected layers
        if (lbModifyer.SelectedItems.Count == 0)
        {
            ret.AddRange(lbGetLayers.SelectedItems.Cast<layer>());
        }
        else
        {
            Modifier modifier = (Modifier)lbModifyer.SelectedItem;
            foreach (layer layerToAdd in lbGetLayers.SelectedItems)
            {
                ret.Add(layerToAdd.Override(modifier));
            }
        }
    }
    return ret;//method must return something.
}
</code>```

Body:
I'm working on creating a windows form plugin to create Layers from the user selected items on my windows form.

I am reading a list of Layers in to a list box(lbGetLayers), a list of modifiers in to another listbox(lbModifyer) from two different csv files. Additionally, I have created two classes to hold the layer, modifier objects.

Goal: is to create a new layer with the correct Name, Color, Line Style, and Line Weight based on user selected items.

Issue:
I am trying to write a function to build the logic before creating the layer to satisfy the below two conditions:

1) Layer- Will have a color, line style, and line weight. Let the user pick 1 or more. If the user picks more than 1 then the app will create all layers selected.

2)Modifier – will override the color, line style, and line weight. The user can pick 0 or 1.

3)Status(Edited) - will again override the color, line style and the line weight. The user can pick 0 or 1.

I came up with the a function which is not appropriate to satisfy these conditions.
I'd really appreciate if somebody could help me solving this problem.

Thanks!!

BuildLayers:

  public Intellayer Buildlayer()
{
    //can select Layer - 1 or more
    //Get Selected Layer Object - color, line style & line weight
       foreach(Intellayer SelectedLayer in lbGetLayers.Items)
       {
            foreach (Modifyer SelectedModifyer in lbModifyer.Items)
            {
                if(lbGetLayers.SelectedItems.Count > 1 || lbModifyer.SelectedItems.Count <= 1)
                System.Diagnostics.Debug.WriteLine(SelectedLayer.layername + "-" + SelectedModifyer.name);
            }
        }

Class:

public class layer
    {
       public string disciplane { get; set; }
       public string layername { get; set; }
       public string Linetype { get; set; }
       public int? Layercolor { get; set; }
       public string Description { get; set; }
       public string Lineweight { get; set; }
       public override string ToString()
        {
            return layername;
        }
    }

 public class Modifyer
    {
        public string discipline { get; set; }
        public string name { get; set; }
        public int? color { get; set; }
        public string Linetype {get;set;}
        public string Lineweight { get; set; }
        public string Description { get; set; }
        public override string ToString()
        {
            return name;
        }
    }

Edited:

BuildLayers:

 public List<layer> Buildlayers()
        {
            //Build selected layers

            List<layer> Getselectedlayers = null;//list of selected layers
            if (lbGetLayers.SelectedItems.Count >= 1)
            {
                    Getselectedlayers = new List<layer>();
                    Getselectedlayers.AddRange(lbGetLayers.SelectedItems.Cast<layer>());
                    foreach (layer lname in Getselectedlayers)
                    {
                        lbGetLayers.SelectedItems.Cast<layer>();
                        System.Diagnostics.Debug.WriteLine(lname.Linetype + "," + lname.Lineweight + "," + lname.Layercolor);
                     }
                if (lbModifyer.SelectedItems.Count == 1)
                {
                    Modifyer modifyer = (Modifyer)lbModifyer.SelectedItem;
                    foreach (layer lname in Getselectedlayers)
                    {
                        lname.Override(modifyer);//Override with Modifyers
                    }
                }
                if(lbStatus.SelectedItems.Count == 1)
                {
                     Status status = (Status)lbStatus.SelectedItem;
                    foreach (layer lname in Getselectedlayers)
                    {
                        lname.Override(status);//Override with Status
                    }
                }
            }
            return Getselectedlayers;//return list of selected layers
        }
        }
    }

Class:

 public class layer
        {
           public string disciplane { get; set; }
           public string layername { get; set; }
           public string Linetype { get; set; }
           public int? Layercolor { get; set; }
           public string Description { get; set; }
           public string Lineweight { get; set; }

            public layer Override(Modifyer modifyer)
            {
                layer newLayer = new layer();
                newLayer.layername = this.layername;
                newLayer.Layercolor = modifyer.color;
                newLayer.Linetype = modifyer.Linetype;
                newLayer.Lineweight = modifyer.Lineweight;
                return newLayer;
            }
           public layer Override(Status status)
            {
                layer newlayer = new layer();
                newlayer.layername = this.layername;
                newlayer.Layercolor = status.color;
                newlayer.Linetype = status.Linetype;
                newlayer.Lineweight = status.Lineweight;
                return newlayer;
            }
            public override string ToString()
            {
                return layername;
            }
        }

Body:
You seem to have most of the meat there, but there are a couple issues in the code you posted aside from the logic inside the Buildlayer() method.

Let's start with the constructor. The point of the constructor is to initialize the form. This is also a good place to assign data to your controls. Here, the user has not had a chance to select any items as the forms is not yet visible. This is where you should be parsing your CSV file and assigning the resulting objects to your respective listboxes.

public LayerCreationTool()
{
    InitializeComponent();
    fillListBoxes();
}

private void fillListBoxes()
{
    //get layers from CSV here and put them into ListBox
    lbGetLayers.Items.AddRange(getLayersFromCSV().ToArray());
    lbModifyer.Items.AddRange(getModifiersFromCSV().ToArray());
}

private List<layer> getLayersFromCSV()
{
    List<layer> layers = new List<layer>();
    //...Do your parsing here;
    return layers;
}

private List<Modifier> getModifiersFromCSV()
{
    List<Modifier> modifiers = new List<Modifier>();
    //...Do your parsing here;
    return modifiers;
}

I also added a method Override() to your layer class. This will allow you to easily utilize your modifier.

public class layer
{
    public string layername { get; set; }
    public string Linetype { get; set; }
    public int? Layercolor { get; set; }
    public string Lineweight { get; set; }

    public layer Override(Modifier modifier)
    {
        layer newLayer = new layer();
        newLayer.layername = this.layername;
        newLayer.Layercolor = modifier.color;
        newLayer.Linetype = modifier.Linetype;
        newLayer.Lineweight = modifier.Lineweight;
        return newLayer;
    }

    public override string ToString()
    {
        return layername;
    }
}

Now that you have a functional form, you need a way for the user to say "Go". I've taken the liberty of adding a button to the form, and in the click event of the button is where you should be creating your layers as per your logic. Also, Since you want to be returning more than one layer, Buildlayers() should return List<layer> rather than layer.

The idea for the logic is simple: if a modifier is NOT selected, then add all the selected layers to add to AutoCad. If a modifier IS selected, then use the Override() method to grab and modify all selected items one at a time.

private void btnImport_Click(object sender, EventArgs e)
{
    List<layer> layersToAddToAutoCad = Buildlayers();
    //now use your these layers to add to AutoCad...
}

//You need to return a List of layers that you then use
//to add layers to AutoCad
public List<layer> Buildlayers()
{
    List<layer> ret = null;

    if(lbGetLayers.SelectedItems.Count > 0)
    {
        ret  = new List<layer>();
        //if no modifier selected, great, just grab all the selected layers
        if (lbModifyer.SelectedItems.Count == 0)
        {
            ret.AddRange(lbGetLayers.SelectedItems.Cast<layer>());
        }
        else
        {
            Modifier modifier = (Modifier)lbModifyer.SelectedItem;
            foreach (layer layerToAdd in lbGetLayers.SelectedItems)
            {
                ret.Add(layerToAdd.Override(modifier));
            }
        }
    }
    return ret;//method must return something.
}


问:
Update intermediary npm dependencies with package-lock.json
What is the proper way to update an intermediary dependency with npm in the presence of the package-lock.json file?

For example:

```<code>$ npm outdated --depth=1 eslint
Package  Current  Wanted  Latest  Location
eslint     4.9.0  4.10.0  4.10.0  MyApplication1 > grunt-eslint
</code>```

The package-lock.json is doing its job by keeping eslint (an intermediary dependency, in this case for grunt-eslint) at 4.9.0. How do I update to eslint@4.10?

I have tried the following commands but npm doesn't do anything:

```<code>npm update grunt-eslint --dev --depth 1
npm update eslint --dev
</code>```

It works if I add eslint as a top-level dependency but I don't think that is the correct way to do this.

答:
This is clearly a hacky workaround but it serves the purpose:

```<code>npm install eslint --save-dev && npm uninstall eslint --save-dev
</code>```

I'll be happy to accept another answer if there is a better method of doing this.

Body:
What is the proper way to update an intermediary dependency with npm in the presence of the package-lock.json file?

For example:

$ npm outdated --depth=1 eslint
Package  Current  Wanted  Latest  Location
eslint     4.9.0  4.10.0  4.10.0  MyApplication1 > grunt-eslint

The package-lock.json is doing its job by keeping eslint (an intermediary dependency, in this case for grunt-eslint) at 4.9.0. How do I update to eslint@4.10?

I have tried the following commands but npm doesn't do anything:

npm update grunt-eslint --dev --depth 1
npm update eslint --dev

It works if I add eslint as a top-level dependency but I don't think that is the correct way to do this.

Body:
This is clearly a hacky workaround but it serves the purpose:

npm install eslint --save-dev && npm uninstall eslint --save-dev

I'll be happy to accept another answer if there is a better method of doing this.


问:
What is the difference between "expose" and "publish" in Docker?
I'm experimenting with Dockerfiles, and I think I understand most of the logic. However, I don't see the difference between "exposing" and "publishing" a port in this context.

All the tutorials I have seen first include the EXPOSE command in the Dockerfile:

```<code>...
EXPOSE 8080
...
</code>```

They then build an image from this Dockerfile:

```<code>$ docker build -t an_image - < Dockerfile
</code>```

And then publish the same port as above when running the image:

```<code>$ docker run -d -p 8080 an_image
</code>```

or publish all ports using

```<code>$ docker run -d -P an_image
</code>```

What is the point of exposing a port in the Dockerfile, if it will be published anyway? Would there ever be a need to expose a port first, and not publish it later? Effectively, I would like to specify all the ports that I will use in the Dockerfile when creating the image, and then not bother with them again, running them simply with:

```<code>$ docker run -d an_image
</code>```

Is this possible?

答:
You expose ports using the EXPOSE keyword in the Dockerfile or the
--expose flag to docker run. Exposing ports is a way of documenting which
ports are used, but does not actually map or open any ports. Exposing ports
is optional.

Source: github commit

Body:
I'm experimenting with Dockerfiles, and I think I understand most of the logic. However, I don't see the difference between "exposing" and "publishing" a port in this context.

All the tutorials I have seen first include the EXPOSE command in the Dockerfile:

...
EXPOSE 8080
...

They then build an image from this Dockerfile:

$ docker build -t an_image - < Dockerfile

And then publish the same port as above when running the image:

$ docker run -d -p 8080 an_image

or publish all ports using

$ docker run -d -P an_image

What is the point of exposing a port in the Dockerfile, if it will be published anyway? Would there ever be a need to expose a port first, and not publish it later? Effectively, I would like to specify all the ports that I will use in the Dockerfile when creating the image, and then not bother with them again, running them simply with:

$ docker run -d an_image

Is this possible?


问:
Maven Java Home Path: \bin, or not to \bin
So I find myself kind of stuck in between.

I set JAVA_HOME to C:\Program Files\Java\jdk1.8.0_121 then Maven works but

```<code>java -version
</code>```

shows 'java' is not recognized as an internal or external command,
operable program or batch file.

If I set JAVA_HOME to C:\Program Files\Java\jdk1.8.0_121\bin, Maven doesn't work but at least I get java -version right.

I'm pretty sure I'm doing something fundamentally wrong but I can't put my finger on it, obviously :(

答: java -version will look at your $PATH, so normally we need to add %JAVA_HOME%/bin to $PATH for any ad-hoc command. For maven, internally it checks $JAVA_HOME/bin. Hope it helps.

Body:
So I find myself kind of stuck in between.

I set JAVA_HOME to C:\Program Files\Java\jdk1.8.0_121 then Maven works but

java -version

shows 'java' is not recognized as an internal or external command,
operable program or batch file.

If I set JAVA_HOME to C:\Program Files\Java\jdk1.8.0_121\bin, Maven doesn't work but at least I get java -version right.

I'm pretty sure I'm doing something fundamentally wrong but I can't put my finger on it, obviously :(


问:
How to extract a representative subset of triples from a triple store
We have an OpenLink Virtuoso-based triple (or rather quad-) store with about ~6bn triples in it. Our collaborators are asking us to give them a small subset of the data so they can test some of their queries and algorithms. Naturally, if we extract a random subset of graph-subject-predicate-object quads from the entire set, most of their SPARQL queries against the subset will find no solutions, because a small random subset of quads will represent an almost entirely disconnected graph. Is there a technique (possibly Virtuoso-specific) that would allow the extraction of a subset of quads s from the entire set S such that, for a given “select” or “construct” SPARQL query Q, Q executed against s would return the same solution as Q executed against the entire set S? If this could be done, it would be possible to run all sample queries that the collaborators want to be able to run against our dataset, extract that smallest possible subset and send it to them (as an n-quads file) so they can load it into their triple store.</p>

答:
You must have a known count of entity types in your database, right? Assuming that to be true, why don't you simply apply a SPARQL DESCRIBE to a sampling of each entity per entity type?

Example:

DESCRIBE ?EntitySample
{
    {
        SELECT SAMPLE(?Entity) as ?EntitySample
               COUNT (?Entity) as ?EntityCount
               ?EntityType
    WHERE {?Entity a ?EntityType}
    GROUP BY ?EntityType
    HAVING (COUNT (?Entity) > 10)
        LIMIT 50
      }
 }


问:
Floating Point in Python
I'm learning via Learn Python The Hard Way and I've come across:

Notice the math seems “wrong”? There are no fractions, only whole numbers. Find out why by researching
  what a “floating point” number is.

I've read what it is on: http://docs.python.org/tutorial/floatingpoint.html

I can't figure out on how I can output floating point numbers, I've thought about using round(3 + 3, 2).

Is this right?

答:
python console
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
I get 7
but in pycharm I get
6.75.</p>

Title: Floating Point in Python


问:
Fixing date labels when plotting bar chart of resampled Pandas time series data in Matplotlib
Using the command monthly[monthly.columns[:3]].resample('Q').sum() in pandas, I create a DataFrame that looks like this:

```<code>DateIndex   C1  C2  C3
2012-09-30  94  139 181
2012-12-31  111 236 162
2013-03-31  113 321 259
2013-06-30  96  238 219
</code>```

I can then plot those numbers using the command monthly[monthly.columns[:3]].resample('Q').sum().plot(kind='bar',stacked=True) to produce a figure that looks like this:

What I can't do is fix the x-axis date labels so they're not so ugly.

Using Matplotlib's .bar function, described here, might be a better option. But I can't work out how to get the DateIndex into the right format so .plot will accept x and y variables. Matplotlib also has a useful page about date labels, but those commands don't seem to work the with Pandas .plot function. Can you help? I've hunted around on here but so far not discovered a solution that works for me. Thanks!

答:
```<code>y = monthly[monthly.columns[:3]].resample('Q').sum()

fig, ax = plt.subplots(figsize=(12,5))
y.plot(ax=ax,kind='bar',stacked=True)
ax.xaxis.set_ticklabels(y.index.to_period('Q'))
</code>```

Body:
Using the command monthly[monthly.columns[:3]].resample('Q').sum() in pandas, I create a DataFrame that looks like this:

DateIndex   C1  C2  C3
2012-09-30  94  139 181
2012-12-31  111 236 162
2013-03-31  113 321 259
2013-06-30  96  238 219

I can then plot those numbers using the command monthly[monthly.columns[:3]].resample('Q').sum().plot(kind='bar',stacked=True) to produce a figure that looks like this:

What I can't do is fix the x-axis date labels so they're not so ugly.

Using Matplotlib's .bar function, described here, might be a better option. But I can't work out how to get the DateIndex into the right format so .plot will accept x and y variables. Matplotlib also has a useful page about date labels, but those commands don't seem to work the with Pandas .plot function. Can you help? I've hunted around on here but so far not discovered a solution that works for me. Thanks!


问:
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding?

I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.

Also, why should encoding even be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?

答:
You need to take the encoding into account, because 1 character could be represented by 1 or more bytes (up to about 6), and different encodings will treat these bytes differently.

Joel has a posting on this:

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

OwnerDisplayName: Vulcan Eager

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Dale Ragan

OwnerDisplayName: Zhaph - Ben Duguid


问:
How replace returned observable with a new one RxJava2
I have one case when I need to return an observable immediately, but then replace this observable with another one.

Here is an example

```<code>    private Flowable<byte[]> mFlowableStream = Flowable.empty();

   @Override
    public Flowable<byte[]> startStreamRead() {
        bindToService();
        return mFlowableStream;
    }
</code>```

And then after binding to service I provide it a callback connection like that

```<code>@Override
public void bindToService() {
    mAppContext.bindService(new Intent(mAppContext,StreamService.class), mServiceConnection, 0);
}

    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {

       mServiceInterection = ((StreamServiceInterection.LocalBinder) binder).getServiceInteractor();
        mStreamDisposable = mServiceInterection.getStream()
                .subscribe(new Consumer<byte[]>() {
                    @Override
                    public void accept(byte[] data) throws Exception {

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

What I want to do is to somehow replace returned previously mFlowableStream with a new observable that I got from service.

What are possible strategies to implement this ? Maybe I should return some other value, like Future.

Please suggest how to solve this problem

Thanks

答:
You can use Flowable.create instead of Flowable.empty

Then when new data come, just push to flowable.
Like Example

```<code>final ArrayList<FlowableEmitter<Integer>> arrEmitter = new ArrayList<>();

    Flowable<Integer> futureFlow = Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(final FlowableEmitter<Integer> e) throws Exception {
            e.onNext(1);
            e.onNext(2);

            arrEmitter.add(e); // hold emitter to use later
        }
    }, BackpressureStrategy.BUFFER);

    futureFlow.subscribe(new ResourceSubscriber<Integer>() {
        @Override
        public void onNext(Integer integer) {
            System.out.println("onNext: " + integer);
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {
            System.out.println("onComplete");
        }
    });

    // =========== When data come
    FlowableEmitter<Integer> holdEmitter = arrEmitter.get(0);

    holdEmitter.onNext(3);
</code>```

Or use you can use **Subject* type according to your need

Understanding RxJava Subject — Publish, Replay, Behavior and Async Subject

Body:
I have one case when I need to return an observable immediately, but then replace this observable with another one.

Here is an example

    private Flowable<byte[]> mFlowableStream = Flowable.empty();

   @Override
    public Flowable<byte[]> startStreamRead() {
        bindToService();
        return mFlowableStream;
    }

And then after binding to service I provide it a callback connection like that

@Override
public void bindToService() {
    mAppContext.bindService(new Intent(mAppContext,StreamService.class), mServiceConnection, 0);
}

    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {

       mServiceInterection = ((StreamServiceInterection.LocalBinder) binder).getServiceInteractor();
        mStreamDisposable = mServiceInterection.getStream()
                .subscribe(new Consumer<byte[]>() {
                    @Override
                    public void accept(byte[] data) throws Exception {

                    }
                });
    }

What I want to do is to somehow replace returned previously mFlowableStream with a new observable that I got from service.

What are possible strategies to implement this ? Maybe I should return some other value, like Future.

Please suggest how to solve this problem

Thanks

Body:
You can use Flowable.create instead of Flowable.empty

Then when new data come, just push to flowable.
Like Example

final ArrayList<FlowableEmitter<Integer>> arrEmitter = new ArrayList<>();

    Flowable<Integer> futureFlow = Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(final FlowableEmitter<Integer> e) throws Exception {
            e.onNext(1);
            e.onNext(2);

            arrEmitter.add(e); // hold emitter to use later
        }
    }, BackpressureStrategy.BUFFER);

    futureFlow.subscribe(new ResourceSubscriber<Integer>() {
        @Override
        public void onNext(Integer integer) {
            System.out.println("onNext: " + integer);
        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {
            System.out.println("onComplete");
        }
    });

    // =========== When data come
    FlowableEmitter<Integer> holdEmitter = arrEmitter.get(0);

    holdEmitter.onNext(3);

Or use you can use **Subject* type according to your need

Understanding RxJava Subject — Publish, Replay, Behavior and Async Subject


问:
Does Excel if statement see the cells returned Value or the statement with in it?
I have Two Columns returning a vlookup. How can I run an If statement on them? My return is always false. Here is what i have.

```<code>=IFERROR(VLOOKUP(B172,Salaries!$B$2:$F$1000,5,FALSE),"")
</code>```

This returns the Team of the Player, in this Case EDM.
I have another column returning the Home Team (also EDM).

In a new column I run an =if(Team column = Home column(Vlookup(player, Home Stats,3,false), (Vlookup(player,Road stats,3,false)) It will always return the Road stats because to me it see's each column as its statement not as EDM. It works in google sheets just fine, that's why I assume that would work in Excel. Thanks!

答:
You've omitted the literal references (i.e. cell addresses) of the player_cell, team_cell, home_cell, Home_Stats_range and Road_stats_range pretty vague but you could try this.</p>

```<code>=vlookup(player_cell, if(team_cell=home_cell, Home_Stats_range, Road_stats_range), 3, false)
</code>```

Body:
I have Two Columns returning a vlookup. How can I run an If statement on them? My return is always false. Here is what i have.

=IFERROR(VLOOKUP(B172,Salaries!$B$2:$F$1000,5,FALSE),"")

This returns the Team of the Player, in this Case EDM.
I have another column returning the Home Team (also EDM).

In a new column I run an =if(Team column = Home column(Vlookup(player, Home Stats,3,false), (Vlookup(player,Road stats,3,false)) It will always return the Road stats because to me it see's each column as its statement not as EDM. It works in google sheets just fine, that's why I assume that would work in Excel. Thanks!

Body:
You've omitted the literal references (i.e. cell addresses) of the player_cell, team_cell, home_cell, Home_Stats_range and Road_stats_range pretty vague but you could try this.

=vlookup(player_cell, if(team_cell=home_cell, Home_Stats_range, Road_stats_range), 3, false)


问:
2FA / Apple, using Authy
Here is a question about two-factor-authentication on Apple.

I use 2FA when logging into my Apple Developer account, receiving the verification code on some device.
Beside I use the Authy app (for 2FA) to log into some other service.

The question is: could I use the same Authy app when logging in to my Apple Developer account?

If the answer is YES, how do I set this up?

答:
Authy developer evangelist here.

As far as I know, and I've set it up this way, Apple rely on a proprietary 2FA implementation that uses macOS or iOS, so you are not able to use Authy to generate a verification code.

Title: 2FA / Apple, using Authy


问:
Group transactions on a single row
Suppose I have the following dataset containing transactional data.  Subset below for illustration purposes:

```<code>BillName    Item Number
Customer A  477565
Customer A  8400212
Customer A  8400213
Customer A  461230
Customer A  461240
Customer A  477545
Customer A  8657915
Customer B  672050
Customer B  892223
Customer C  640741
Customer C  640772
Customer C  640660
</code>```

How do I transform it to look like the following using Excel or SQL Server?

```<code>Customer A  477565  8400212 8400213 461230  461240  477545  8657915
Customer B  672050  892223
Customer C  640741  640772  640660
</code>```

答:
I think the solution by @ivan7707 is the way to go.  It leverages the power of Excel, and you can even bring the dataset in via MS Query.

That said, if you're looking for a brute-force solution, you could always to something like this in VBA:

```<code>Dim Conn As New ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim bill, item, priorBill As String
Dim row, col As Integer
Dim ws As Worksheet

Set ws = ActiveWorkbook.ActiveSheet

Conn.Open "Your Connection String"
Set rs = Conn.Execute("select bill_name, item_number from bills order by 1")

row = 1
col = 2

Do While Not rs.EOF
  bill = rs.Fields(0).Value
  item = rs.Fields(1).Value

  If bill <> priorBill Then
    row = row + 1
    col = 2

    ws.Cells(row, 1).Value = bill
    priorBill = bill
  End If

  ws.Cells(row, col).Value = item
  col = col + 1

  rs.MoveNext
Loop

Conn.Close
</code>```

Results:

Title: Group transactions on a single row

Body:
Suppose I have the following dataset containing transactional data.  Subset below for illustration purposes:

BillName    Item Number
Customer A  477565
Customer A  8400212
Customer A  8400213
Customer A  461230
Customer A  461240
Customer A  477545
Customer A  8657915
Customer B  672050
Customer B  892223
Customer C  640741
Customer C  640772
Customer C  640660

How do I transform it to look like the following using Excel or SQL Server?

Customer A  477565  8400212 8400213 461230  461240  477545  8657915
Customer B  672050  892223
Customer C  640741  640772  640660

Body:
I think the solution by @ivan7707 is the way to go.  It leverages the power of Excel, and you can even bring the dataset in via MS Query.

That said, if you're looking for a brute-force solution, you could always to something like this in VBA:

Dim Conn As New ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim bill, item, priorBill As String
Dim row, col As Integer
Dim ws As Worksheet

Set ws = ActiveWorkbook.ActiveSheet

Conn.Open "Your Connection String"
Set rs = Conn.Execute("select bill_name, item_number from bills order by 1")

row = 1
col = 2

Do While Not rs.EOF
  bill = rs.Fields(0).Value
  item = rs.Fields(1).Value

  If bill <> priorBill Then
    row = row + 1
    col = 2

    ws.Cells(row, 1).Value = bill
    priorBill = bill
  End If

  ws.Cells(row, col).Value = item
  col = col + 1

  rs.MoveNext
Loop

Conn.Close

Results:


问:
Added some word in the middle of existing text using jquery?
Here my code for example.

```<code><div class="modal-body">
  <p>Do you really want to delete  files ?</p>
</div>
</code>```

I would like to add a word Insert_your_file_here between word delete and word files and a word right now at the end of the text. I can handle the right now sentences, but not with Document1 word.

What i expect the result is just like this.

```<code><div class="modal-body">
      <p>Do you really want to delete Document1 file right now ?</p>
</div>
</code>```

WHat i have tried is use append but i dont know how to specific location of the word that would be added

```<code>$('.modal-body p').append('Document1');
$('.modal-body p').append('right now');
</code>```

答:
```<code>  var text = $('.modal-body p').text();
  text = text.substr(0,28)+' Document1 , Document2 '+text.substr(29 ,-1)+' right now?'
  $('.modal-body p').text(text)
</code>```

Let me explain:

substr() method is used to extract string and make sub-string of big string . (0,28 ) is the position of string to be extracted starting from 0 till 28 position and (29,-1) means start from 29 and end at -1 from backward .Negative positioning is to be counted from backwards .

If your document is in list of array :

```<code>var text = $('.modal-body p').text();
  var document = ['Document1','Document2'].join(' , ');
  text = text.substr(0,28)+' '+ document +text.substr(29 ,-1)+' right now?'
     $('.modal-body p').text(text)
</code>```

Body:
Here my code for example.

Do you really want to delete  files ?

I would like to add a word Insert_your_file_here between word delete and word files and a word right now at the end of the text. I can handle the right now sentences, but not with Document1 word.

What i expect the result is just like this.

Do you really want to delete Document1 file right now ?

WHat i have tried is use append but i dont know how to specific location of the word that would be added

$('.modal-body p').append('Document1');
$('.modal-body p').append('right now');

Body:
  var text = $('.modal-body p').text();
  text = text.substr(0,28)+' Document1 , Document2 '+text.substr(29 ,-1)+' right now?'
  $('.modal-body p').text(text)

Let me explain:

substr() method is used to extract string and make sub-string of big string . (0,28 ) is the position of string to be extracted starting from 0 till 28 position and (29,-1) means start from 29 and end at -1 from backward .Negative positioning is to be counted from backwards .

If your document is in list of array :

var text = $('.modal-body p').text();
  var document = ['Document1','Document2'].join(' , ');
  text = text.substr(0,28)+' '+ document +text.substr(29 ,-1)+' right now?'
     $('.modal-body p').text(text)


问:
Getting rows inserted with SqlBulkCopy
I am switching some of my Linq to Sql code to use SqlBulkCopy, and problem is I need to do two inserts of multiple thousands of rows into two tables.

The service takes your batch of 10,000 links (imported from sitemap, backlink builders, etc), and chops them into RSS feeds of X per feed for aggregation. Problem is, I already have a table of 32 million rows. If i am doing linq to sql inserts, it takes depending on site traffic anywhere between 5 and 10 mintues to load 10,000 links.

The structure is very basic.

Feeds: Id bigint (PK), Title varchar(1000), Description varchar(1000), Published datetime, Aggregated datetime null, ShortCode varchar(8) [antiquated, not inserted anymore, but used for legacy data]

Items: Id bigint (PK), FeedId bigint (FK), Title varchar(1000), Description varchar(1000), Published datetime, ShortCode varchar(8) [antiquated, not inserted anymore, but used for legacy data], ShortId bigint null [updated after insert to equal Id (used in partitioning)]

FutureItems: Id bigint (PK), FeedId bigint (FK), Title varchar(1000), Description varchar(1000), Published datetime, ShortCode varchar(8) [antiquated, not inserted anymore, but used for legacy data], ShortId bigint null [updated after insert to equal Id (used in partitioning)]

OldItems: Id bigint (PK), FeedId bigint (FK), Title varchar(1000), Description varchar(1000), Published datetime, ShortCode varchar(8) [antiquated, not inserted anymore, but used for legacy data], ShortId bigint null [updated after insert to equal Id (used in partitioning)]

So if you have a feed size of 20, you get 500 inserts into the Feeds table, then 10000 inserted into the Items table, then and update runs to set the ShortId equal to the Id. Once a night, a job runs that separates the data into the other two tables, and shift future items into the Items table.

I read that SqlBulkCopy can do 20 million rows in the matter of mintues, but I can't find any good examples of doing it into multiple tables with a FK Constraint.

Our SQL server is a "monster" especially for this application. It is SQL 2008 R2 Web, Windows 2008 R2 Enterprise, 12GB Ram, Dual 4 core Xeons @ 2.8ghz.

Our web server is a clone without the database service.

The CPU runs about 85% when inserting links, and the database fills the RAM.

If SqlBulkCopy isn't good, any suggestion is welcome, we have paying customers who are getting mad, and I am not a DBA, just a plain-old-programmer.

答: I think your real problem in just using a plain bulk insert is that you need the feed ids from the initial insert for the other tables. Here's what I would do. Use bulk insert to insert to a staging table. Then use a stored proc to do the inserts to the real table in a set-based fashion. You can use the output clause in the intial insert to the feed table to get back a table variable with the feed ids you need for the inserts to the other tables. </p>

Title: Getting rows inserted with SqlBulkCopy


问:
Excel VBA - Dictionary of collections (with some other methods and items)
Trying to implement a container of containers and can’t seem to figure out the best way to do it. Basically, I have a series of transactions that can contain multiple sub transactions so I’m trying to create a Dictionary of Collections. Each Transaction will have a unique key and hold a series of Sub Transactions. Each Sub Transaction will have a currency (key), notional and commission.

I’ve created a Sub Transaction class with SumNotional and SumCommission items as I’d ideally like to able to track each individual Sub Transaction as well as the net amounts.

```<code>Private Sub Class_Initialize()

    SumNotional = 0

    SumCommission = 0

    Set ItemList = New Collection

End Sub
</code>```

Some pseudo code would theoretically look like:

```<code>- Create Dictionary
- Get TransactionKey
- Create Sub Transaction with currency, notional and commission

- If Dictionary(TransactionKey) with currency doesn’t exist
    - create new Sub Transaction and add to Dictionary
- Else If Dictionary(TransactionKey) with currency exists
    - add line items to Sub Transaction for notional and commission
      - and add values to sum variables
</code>```

Not married to any way of doing it, this just seemed like an effective and efficient way to implement. Example would be data going in looks like:

```<code>Transaction  Currency  Notional  Commission
     A1        USD        500        50
     A2        USD      1,000       100
     A2        CAD        750        75
     A1        CAD        600        60
     A2        EUR        400        40
     A1        USD        300        30
     A1        CAD        175        20
</code>```

And results would be a data store looking like

```<code>A1
    USD    800    80
    CAD    775    80
A2
    USD  1,000   100
    CAD    750    75
    EUR    400    40
</code>```

答:
You could use a dictionary of dictionaries

.

```<code>Option Explicit 'add Reference to "Microsoft Scripting Runtime" (VBA Editor -> Tools)

Public Sub NestedList()
    Const TR As Long = 1, CU As Long = 2, NO As Long = 3, CO As Long = 4
    Dim ws As Worksheet, itms As Dictionary, subs As Dictionary, prop As Dictionary
    Dim ur As Variant, lr As Long, r As Long, t As String, c As String

    Set ws = Worksheets("Sheet1")
    ur = ws.UsedRange
    lr = UBound(ur)
    Set itms = New Dictionary

    For r = 2 To lr
        t = ur(r, TR)   'Transaction
        c = ur(r, CU)   'Currency
        Set prop = New Dictionary
        Set subs = New Dictionary
        If Not itms.Exists(t) Then
            prop.Add Key:="N", Item:=ur(r, NO)  'Notional
            prop.Add Key:="C", Item:=ur(r, CO)  'Commission
            subs.Add Key:=c, Item:=prop         'Add Currency
            itms.Add Key:=t, Item:=subs         'Add Transaction
        Else
            If Not itms(t).Exists(c) Then
                prop.Add Key:="N", Item:=ur(r, NO)
                prop.Add Key:="C", Item:=ur(r, CO)
                itms(t).Add Key:=c, Item:=prop      'Add Currency
            Else
                itms(t)(c)("N") = itms(t)(c)("N") + ur(r, NO)   'Sum Notionals
                itms(t)(c)("C") = itms(t)(c)("C") + ur(r, CO)   'Sum Commissions
            End If
        End If
    Next
    ShowItms itms
End Sub
</code>```

```<code>Private Sub ShowItms(ByRef itms As Dictionary)
    Dim t As Variant, c As Variant

    For Each t In itms
        Debug.Print t
        For Each c In itms(t)
            Debug.Print vbTab & c & " " & itms(t)(c)("N") & " " & itms(t)(c)("C")
        Next
    Next
End Sub
</code>```

At high level:

Get intended sheet to work with (Sheet1)

Get its UsedRange into a variant array (ur)

Get last row: lr = Ubound(ur, 1) - upper bound of dimension 1 (implied in the code)

Initialize main dictionary (outside of the loop)

Loop over all rows in the array / sheet

If main dictionary doesn't contain current transaction (ex. A1)

Add a new prop dictionary, with 2 values N (Notional) and C (Commission)

Add prop dictionary as item to dictionary subs

Add subs dictionary to main dictionary (itms)

Else (main dictionary contains current transaction A1)

If subs dictionary doesn't contain current currency

Add a new prop dictionary, with 2 values N (Notional) and C (Commission)

Add prop dictionary to subs(USD) sub-dictionary, using Currency as key

Add subs dictionary to itms(A1) dictionary (main)

Else

Sum up the Notionals values accumulated so far (for this Transaction and Currency)

Sum up the Commissions values accumulated so far

At the end we just print the results to the immediate window with the sub ShowItms()

Sheet1

Result:

```<code>A1
    USD 800 80
    CAD 775 80
A2
    USD 1000 100
    CAD 750 75
    EUR 400 40
</code>```

Body:
Trying to implement a container of containers and can’t seem to figure out the best way to do it. Basically, I have a series of transactions that can contain multiple sub transactions so I’m trying to create a Dictionary of Collections. Each Transaction will have a unique key and hold a series of Sub Transactions. Each Sub Transaction will have a currency (key), notional and commission.

I’ve created a Sub Transaction class with SumNotional and SumCommission items as I’d ideally like to able to track each individual Sub Transaction as well as the net amounts.

Private Sub Class_Initialize()

    SumNotional = 0

    SumCommission = 0

    Set ItemList = New Collection

End Sub

Some pseudo code would theoretically look like:

- Create Dictionary
- Get TransactionKey
- Create Sub Transaction with currency, notional and commission

- If Dictionary(TransactionKey) with currency doesn’t exist
    - create new Sub Transaction and add to Dictionary
- Else If Dictionary(TransactionKey) with currency exists
    - add line items to Sub Transaction for notional and commission
      - and add values to sum variables

Not married to any way of doing it, this just seemed like an effective and efficient way to implement. Example would be data going in looks like:

Transaction  Currency  Notional  Commission
     A1        USD        500        50
     A2        USD      1,000       100
     A2        CAD        750        75
     A1        CAD        600        60
     A2        EUR        400        40
     A1        USD        300        30
     A1        CAD        175        20

And results would be a data store looking like

A1
    USD    800    80
    CAD    775    80
A2
    USD  1,000   100
    CAD    750    75
    EUR    400    40

Body:
You could use a dictionary of dictionaries

.

Option Explicit 'add Reference to "Microsoft Scripting Runtime" (VBA Editor -> Tools)

Public Sub NestedList()
    Const TR As Long = 1, CU As Long = 2, NO As Long = 3, CO As Long = 4
    Dim ws As Worksheet, itms As Dictionary, subs As Dictionary, prop As Dictionary
    Dim ur As Variant, lr As Long, r As Long, t As String, c As String

    Set ws = Worksheets("Sheet1")
    ur = ws.UsedRange
    lr = UBound(ur)
    Set itms = New Dictionary

    For r = 2 To lr
        t = ur(r, TR)   'Transaction
        c = ur(r, CU)   'Currency
        Set prop = New Dictionary
        Set subs = New Dictionary
        If Not itms.Exists(t) Then
            prop.Add Key:="N", Item:=ur(r, NO)  'Notional
            prop.Add Key:="C", Item:=ur(r, CO)  'Commission
            subs.Add Key:=c, Item:=prop         'Add Currency
            itms.Add Key:=t, Item:=subs         'Add Transaction
        Else
            If Not itms(t).Exists(c) Then
                prop.Add Key:="N", Item:=ur(r, NO)
                prop.Add Key:="C", Item:=ur(r, CO)
                itms(t).Add Key:=c, Item:=prop      'Add Currency
            Else
                itms(t)(c)("N") = itms(t)(c)("N") + ur(r, NO)   'Sum Notionals
                itms(t)(c)("C") = itms(t)(c)("C") + ur(r, CO)   'Sum Commissions
            End If
        End If
    Next
    ShowItms itms
End Sub

Private Sub ShowItms(ByRef itms As Dictionary)
    Dim t As Variant, c As Variant

    For Each t In itms
        Debug.Print t
        For Each c In itms(t)
            Debug.Print vbTab & c & " " & itms(t)(c)("N") & " " & itms(t)(c)("C")
        Next
    Next
End Sub

At high level:

Get intended sheet to work with (Sheet1)

Get its UsedRange into a variant array (ur)

Get last row: lr = Ubound(ur, 1) - upper bound of dimension 1 (implied in the code)

Initialize main dictionary (outside of the loop)

Loop over all rows in the array / sheet

If main dictionary doesn't contain current transaction (ex. A1)

Add a new prop dictionary, with 2 values N (Notional) and C (Commission)

Add prop dictionary as item to dictionary subs

Add subs dictionary to main dictionary (itms)

Else (main dictionary contains current transaction A1)

If subs dictionary doesn't contain current currency

Add a new prop dictionary, with 2 values N (Notional) and C (Commission)

Add prop dictionary to subs(USD) sub-dictionary, using Currency as key

Add subs dictionary to itms(A1) dictionary (main)

Else

Sum up the Notionals values accumulated so far (for this Transaction and Currency)

Sum up the Commissions values accumulated so far

At the end we just print the results to the immediate window with the sub ShowItms()

Sheet1

Result:

A1
    USD 800 80
    CAD 775 80
A2
    USD 1000 100
    CAD 750 75
    EUR 400 40


问:
Python requests in AWS Lambda cannot connect to site behind proxy
I have an AWS Lambda function that needs to connect to an internal website which is behind a proxy. In my code I am doing the following:

```<code>from botocore.vendored import requests

https_proxy = "https://myproxy:myport"
proxyDict = {
          "https" : https_proxy
    }
request.get("https://myurl.json", proxies=proxyDict)
</code>```

Running this gives me the following error message:

HTTPSConnectionPool(host='myproxyhost', port=443): Max retries exceeded with url: myurl.json (Caused by ProxyError('Cannot connect to proxy.', gaierror(-2, 'Name or service not known')))

I have tried replacing the proxied URL with google.com to confirm I can connect to other sites (without the proxy).

It looks like the address space that Lambda runs it gets blocked by the proxy.

Is there something else I need to set with requests and lambda to get this to work?

答:
We can make use of lambda environment variables and can add  https_proxy as a environment variable to lambda function.
By which your lambda function can access the website via proxy.</p>

Body:
I have an AWS Lambda function that needs to connect to an internal website which is behind a proxy. In my code I am doing the following:

from botocore.vendored import requests

https_proxy = "https://myproxy:myport"
proxyDict = {
          "https" : https_proxy
    }
request.get("https://myurl.json", proxies=proxyDict)

Running this gives me the following error message:

HTTPSConnectionPool(host='myproxyhost', port=443): Max retries exceeded with url: myurl.json (Caused by ProxyError('Cannot connect to proxy.', gaierror(-2, 'Name or service not known')))

I have tried replacing the proxied URL with google.com to confirm I can connect to other sites (without the proxy).

It looks like the address space that Lambda runs it gets blocked by the proxy.

Is there something else I need to set with requests and lambda to get this to work?


问:
bluestacks stuck on loading channels
Bluestacks stuck up on loading channel with a circle in the middle...

so far I had uninstalled and re-installed bluestacks several times but ended with the same issue.

I am using fastest internet connection in my pc using LAN / Wifi.

答: I had the same issue and what I figured is the GamePopMain is a launcher for BlueStacks.  It has some issue in the Mac version for sure and on windows may have them as well.  Install any other launcher and you will stop getting crashes and will be able to use it with out problems. </p>

Title: bluestacks stuck on loading channels


问:
Get DNS server IP addresses associated with Azure VMs
I have a list of servers which I need to get the DNS server IP settings from, these servers are in Azure. I thought this would be simple to get the nic and query the properties of the nic to isolate the dns ip assigned to it.

I used:

```<code>$rg = main-rg
Get-AzureRmNetworkInterface -ResourceGroupName $rg | ForEach { $Interface = $_.Name; $IPs = $_ |`
     Get-AzureRmNetworkInterfaceIpConfig | Select PrivateIPAddress; Write-Host $Interface $IPs.PrivateIPAddress }
</code>```

To get privateIPaddress, but this is for a single resource group. Would I need to put this into a foreach loop?

Maybe like:

```<code>    $rg = get-content c:\temp\list-of-res-grps.txt
foreach ($rgs in $rg)
{
    Get-AzureRmNetworkInterface -ResourceGroupName $rg | ForEach { $Interface = $_.Name; $IPs = $_ |`
         Get-AzureRmNetworkInterfaceIpConfig | Select PrivateIPAddress; Write-Host $Interface $IPs.PrivateIPAddress }
}
</code>```

To get the name of the nics I used, which also gives hostname.

```<code>get-azurermvm | out-file c:\temp\servers.txt
</code>```

Is there a way to query the nic for the dns server ip address? Or do I need to be digging deeper into the Get-AzureRmNetworkInterfaceIpConfig cmdlet?

Hope I haven't missed anything obvious.

Thanks in advance :)

答:
In Azure, if you have not change DNS, the default private DNS is 168.63.129.16.

1.If you change DNS settings via Azure Virtual Network, we can use this command to list the DNS server:

```<code>PS C:\Users\jason> $a = Get-AzureRmVirtualNetwork -Name 'jasonvm-vnet' -ResourceGroupName jasonvm
PS C:\Users\jason> $a.DhcpOptions

DnsServers
----------
{8.8.8.8}

PS C:\Users\jason>
</code>```

2.If you change the DNS settings with Azure PowerShell, like this:

```<code>$nic = Get-AzureRmNetworkInterface -ResourceGroupName "ResourceGroup1" -Name "NetworkInterface1"
$nic.DnsSettings.DnsServers.Add("9.9.9.9")
</code>```

We can use this command to list the DNS server:

```<code>PS C:\Users\jason> $d = Get-AzureRmNetworkInterface -Name jasonvms790 -ResourceGroupName jasonvm
PS C:\Users\jason> $d.DnsSettings.DnsServers
9.9.9.9
</code>```

3.If you change DNS settings in Azure VM, we can't use PowerShell to get it. we should login to this VM then to check it.

Hope this helps:)

Body:
I have a list of servers which I need to get the DNS server IP settings from, these servers are in Azure. I thought this would be simple to get the nic and query the properties of the nic to isolate the dns ip assigned to it.

I used:

$rg = main-rg
Get-AzureRmNetworkInterface -ResourceGroupName $rg | ForEach { $Interface = $_.Name; $IPs = $_ |`
     Get-AzureRmNetworkInterfaceIpConfig | Select PrivateIPAddress; Write-Host $Interface $IPs.PrivateIPAddress }

To get privateIPaddress, but this is for a single resource group. Would I need to put this into a foreach loop?

Maybe like:

    $rg = get-content c:\temp\list-of-res-grps.txt
foreach ($rgs in $rg)
{
    Get-AzureRmNetworkInterface -ResourceGroupName $rg | ForEach { $Interface = $_.Name; $IPs = $_ |`
         Get-AzureRmNetworkInterfaceIpConfig | Select PrivateIPAddress; Write-Host $Interface $IPs.PrivateIPAddress }
}

To get the name of the nics I used, which also gives hostname.

get-azurermvm | out-file c:\temp\servers.txt

Is there a way to query the nic for the dns server ip address? Or do I need to be digging deeper into the Get-AzureRmNetworkInterfaceIpConfig cmdlet?

Hope I haven't missed anything obvious.

Thanks in advance :)

Body:
In Azure, if you have not change DNS, the default private DNS is 168.63.129.16.

1.If you change DNS settings via Azure Virtual Network, we can use this command to list the DNS server:

PS C:\Users\jason> $a = Get-AzureRmVirtualNetwork -Name 'jasonvm-vnet' -ResourceGroupName jasonvm
PS C:\Users\jason> $a.DhcpOptions

DnsServers
----------
{8.8.8.8}

PS C:\Users\jason>

2.If you change the DNS settings with Azure PowerShell, like this:

$nic = Get-AzureRmNetworkInterface -ResourceGroupName "ResourceGroup1" -Name "NetworkInterface1"
$nic.DnsSettings.DnsServers.Add("9.9.9.9")

We can use this command to list the DNS server:

PS C:\Users\jason> $d = Get-AzureRmNetworkInterface -Name jasonvms790 -ResourceGroupName jasonvm
PS C:\Users\jason> $d.DnsSettings.DnsServers
9.9.9.9

3.If you change DNS settings in Azure VM, we can't use PowerShell to get it. we should login to this VM then to check it.

Hope this helps:)


问:
Number of positive integers in [1,1e18] that cannot be divided by any integers in [2,10]
I am having difficulty trying to solve the following problem:

For Q queries, Q <= 1e6, where each query is a positive integer N, N <= 1e18, find the number of integers in [1,N] that cannot be
  divided by integers in [2,10] for each query.

I thought of using using a sieve method to filter out numbers in [1,1e18] for each query (similar to sieve of eratosthenes). However, the value of N  could be very large. Hence, there is no way I could use this method. The most useful observation that I could make is that numbers ending with 0,2,4,5,6,8 are invalid. But that does not help me with this problem.

I saw a solution for a similar problem that uses a smaller number of queries (Q <= 200). But it doesn't work for this problem (and I don't understand that solution).

Could someone please advise me on how to solve this problem?

答:
Here is an approach on how to handle this.

The place to start is to think about how you can split this into pieces.  With such a problem, a place to start is the least common denominator (LCD) -- in this case 2,520 (the smallest number divisible by all the numbers less than 10).

The idea is that if x is not divisible by any number from 2-10, then x + 2,520 is also not divisible.

Hence, you can divide the problem into two pieces:

How many numbers between 1 and 2,520 are "relatively prime" to the numbers from 2-10?

How many times does 2,520 go into your target number?  You need to take the remainder into account as well.


问:
mysql select all table names except
Alright, I know you can do the following to get all column names.

```<code>SHOW COLUMNS FROM person;
</code>```

However, it does not allow where statements.

Is there any way to get the full list and just say not this one?

So I am basically looking for something like this:

```<code>select (show columns from person where Field <> 'id') from person
</code>```

答: MySQL documentation says that WHERE clause is allowed. Read the docs.</p>

Title: mysql select all table names except

Body:
Alright, I know you can do the following to get all column names.

SHOW COLUMNS FROM person;

However, it does not allow where statements.

Is there any way to get the full list and just say not this one?

So I am basically looking for something like this:

select (show columns from person where Field <> 'id') from person


问:
How to use UIGraphicsBeginImageContextWithOptions to draw non-standard shapes?
I have an image which is a bubble shape, and I wish to add text to the middle of the image, so I tried to use UIGraphicsBeginImageContextWithOptions to redraw the image.

The code is as following:

```<code> let imageSize = CGSize(width: 40, height: 40)

        // the rect in which the image will be drawn in
        let imageRect = CGRect(origin: CGPoint.zero, size: imageSize)
        UIGraphicsBeginImageContextWithOptions(imageSize, true, 1.0)
        // begining drawing things

        // first, we draw the image in the specified rect
        image.draw(in: imageRect)

        let attributes = [ NSAttributedStringKey.foregroundColor: UIColor.red,
                           NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 20)]
        let text = "55"
        let size = text.size(withAttributes: attributes)
        let rect = CGRect(x: 20 - size.width / 2, y: 20 - size.height / 2, width: size.width, height: size.height)
        text.draw(in: rect, withAttributes: attributes)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
</code>```

but I get a square with a black background with the desired image inside:

the blue is the original image, the black is the re-drawn image. Anyone knows how can I draw the image as the original image?

Thanks!

答:
You need to pass false, not true, to the 2nd argument (the opaque parameter) of the call to UIGraphicsBeginImageContextWithOptions function.

```<code>UIGraphicsBeginImageContextWithOptions(imageSize, false, 1.0)
</code>```

You should also pass 0 as the 3rd argument (scale) so the image is scaled to match the current device's screen scale.

Body:
I have an image which is a bubble shape, and I wish to add text to the middle of the image, so I tried to use UIGraphicsBeginImageContextWithOptions to redraw the image.

The code is as following:

 let imageSize = CGSize(width: 40, height: 40)

        // the rect in which the image will be drawn in
        let imageRect = CGRect(origin: CGPoint.zero, size: imageSize)
        UIGraphicsBeginImageContextWithOptions(imageSize, true, 1.0)
        // begining drawing things

        // first, we draw the image in the specified rect
        image.draw(in: imageRect)

        let attributes = [ NSAttributedStringKey.foregroundColor: UIColor.red,
                           NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 20)]
        let text = "55"
        let size = text.size(withAttributes: attributes)
        let rect = CGRect(x: 20 - size.width / 2, y: 20 - size.height / 2, width: size.width, height: size.height)
        text.draw(in: rect, withAttributes: attributes)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage

but I get a square with a black background with the desired image inside:

the blue is the original image, the black is the re-drawn image. Anyone knows how can I draw the image as the original image?

Thanks!

Body:
You need to pass false, not true, to the 2nd argument (the opaque parameter) of the call to UIGraphicsBeginImageContextWithOptions function.

UIGraphicsBeginImageContextWithOptions(imageSize, false, 1.0)

You should also pass 0 as the 3rd argument (scale) so the image is scaled to match the current device's screen scale.


问:
Adjusting intensity on an image
I am trying to increase the intensity of a grayscale image while maintaining the outline of the image.The algorithm I'm creating only looks at values in the left, right, upper and lower neighbors of each cell, effectively only processing the interior cells of the array. Obviously there are lines and lines of code but I am being thrown the ArrayOutOfBoundsException on this one block (I can provide it all if needed). Can someone tell me what my problem is or offer advice on what needs a second look?

```<code>public Image getEdgeImage(){
    Image edge = new Image(this);
    for(int row = 1; row < numRows; row++) {

        for(int col = 1 ; col < numColumns; col++) {

        double Lx = -.5 * edge.pixels[row -1][col].getRed() + (.5 * edge.pixels[row + 1][col].getRed()) ;
        double Ly = -.5 * edge.pixels[row][col -1].getRed() + (.5 * edge.pixels[row][col + 1].getRed());

        int L = (int) Math.sqrt((Lx * Lx) + (Ly * Ly));
        edge.pixels[row][col] = new Color(L, L, L);
        }
    }
    return edge;
}
</code>```

答:
If your getting ArrayOutOfBoundException, Please do watch on the area your accessing the Array element by +/- the index.

In your program the line No 5 & 6, your accusing the next elements with out checking the array length.

```<code> edge.pixels[row + 1]
 edge.pixels[row][col + 1]
</code>```

Array Index will start from 0 to length-1, Suppose your array has the length of 10, and on the 9th iteration your program will check for the index 10 in line 5&6 the code highlighted above.

Title: Adjusting intensity on an image

Body:
I am trying to increase the intensity of a grayscale image while maintaining the outline of the image.The algorithm I'm creating only looks at values in the left, right, upper and lower neighbors of each cell, effectively only processing the interior cells of the array. Obviously there are lines and lines of code but I am being thrown the ArrayOutOfBoundsException on this one block (I can provide it all if needed). Can someone tell me what my problem is or offer advice on what needs a second look?

public Image getEdgeImage(){
    Image edge = new Image(this);
    for(int row = 1; row < numRows; row++) {

        for(int col = 1 ; col < numColumns; col++) {

        double Lx = -.5 * edge.pixels[row -1][col].getRed() + (.5 * edge.pixels[row + 1][col].getRed()) ;
        double Ly = -.5 * edge.pixels[row][col -1].getRed() + (.5 * edge.pixels[row][col + 1].getRed());

        int L = (int) Math.sqrt((Lx * Lx) + (Ly * Ly));
        edge.pixels[row][col] = new Color(L, L, L);
        }
    }
    return edge;
}

Body:
If your getting ArrayOutOfBoundException, Please do watch on the area your accessing the Array element by +/- the index.

In your program the line No 5 & 6, your accusing the next elements with out checking the array length.

 edge.pixels[row + 1]
 edge.pixels[row][col + 1]

Array Index will start from 0 to length-1, Suppose your array has the length of 10, and on the 9th iteration your program will check for the index 10 in line 5&6 the code highlighted above.


问:
Notify Google Search about updated sitemap
For Google search engine in my robots.txt file I got the line

```<code>Sitemap: http://example.com/sitemap.xml
</code>```

If I updated the file sitemap.xml, how would I notify Google about it and make it crawl my site again?

答:
Go to Google's Webmasters tool here => https://www.google.com/webmasters/tools/home?hl=en

Find your site in the list of sites you own (if you have added it) or add it.

Once added if you click on the site to manage properties, you will see menu options on the left hand side that says "Crawl->Fetch as Google".

Or wait for Google to crawl your site in its own scheduled time!

Body:
For Google search engine in my robots.txt file I got the line

Sitemap: http://example.com/sitemap.xml

If I updated the file sitemap.xml, how would I notify Google about it and make it crawl my site again?


问:
Make Jenkins Build a SUCCESS After successful Spring-boot run
I have CI system using Jenkins that automatically clones a repository,
then runs mvn clean install and then mvn spring-boot:run (using windows batch).

My problem is that the Jenkins Build does not stop even though the spring-boot:run is successful.

Is there any way to work this out?

答:
I found a workaround for this.

I added a Build Step that executes a Windows Batch file as a child process
but before starting the batch process, I changed the BUILD_ID to something like BUILD_ID='NO_DELETE' so that Jenkins won't automatically kill it.


问:
Efficient Prime Number Computing Program Java
So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.

One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.

However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.

For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.

So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.

Here's my code, I can't figure out why it's not working

```<code>    Scanner sc = new Scanner (System.in);
    System.out.print ("Enter the upper limit: ");
    int high = sc.nextInt();

    boolean isPrime = true;
    int[] primearray = new int[0];

    for (int num = 1; num <= high; num++)
    {
        for (int x: primearray)
        {
            if (num%x==0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime == true) {
            int size = primearray.length;
            primearray = new int[size+1];
            primearray [size] = num;

            System.out.println (num);
        }
    }
</code>```

答:
First of all, 1 isn't prime. By starting your outer loop at 1, your prime array ends up with 1 in it and everything else will then test as not prime. Start your outer loop at int num = 2.

Second, you aren't copying over the existing known primes when you expand primearray. You can use

```<code>primearray = Arrays.copyOf(primearray, size+1);
</code>```

which will make a new array with all the old contents copied and space for one more value.

Finally, you might want to check out the Sieve of Eratosthenes. A careful implementation of that algorithm will be more efficient than your current algorithm, which requires an expensive array reallocation every time you find a prime. You can use a BitSet to keep track of the flags that the sieve needs.

Body:
So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.

One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.

However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.

For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.

So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.

Here's my code, I can't figure out why it's not working

    Scanner sc = new Scanner (System.in);
    System.out.print ("Enter the upper limit: ");
    int high = sc.nextInt();

    boolean isPrime = true;
    int[] primearray = new int[0];

    for (int num = 1; num <= high; num++)
    {
        for (int x: primearray)
        {
            if (num%x==0)
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime == true) {
            int size = primearray.length;
            primearray = new int[size+1];
            primearray [size] = num;

            System.out.println (num);
        }
    }

Body:
First of all, 1 isn't prime. By starting your outer loop at 1, your prime array ends up with 1 in it and everything else will then test as not prime. Start your outer loop at int num = 2.

Second, you aren't copying over the existing known primes when you expand primearray. You can use

primearray = Arrays.copyOf(primearray, size+1);

which will make a new array with all the old contents copied and space for one more value.

Finally, you might want to check out the Sieve of Eratosthenes. A careful implementation of that algorithm will be more efficient than your current algorithm, which requires an expensive array reallocation every time you find a prime. You can use a BitSet to keep track of the flags that the sieve needs.


问:
R Markdown HTML Number Figures
Does anyone know how to number the figures in the captions, for HTML format R Markdown script?

For PDF documents, the caption will say something like:

Figure X: Some Caption Text

However, the equivalent caption for the HTML version will simply say:

Some Caption Text

This makes cross-referencing figures by number completely useless.

Here is a minimal example:

```<code>---
title: "My Title"
author: "Me"
output:
  pdf_document: default
  html_document: default
---

```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```

```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```
</code>```

I have tried setting toc, fig_caption and number_sections within each of the output formats, but this does not seem to change the result.

答:
I solve cross-referencing using a solution similar to that posted by Nicholas above.  I use bookdown for some projects but I find that awkward to use for other projects where I just want simple cross-referencing.

I use the following when I am writing a paper with rmarkdown and I want it in standard format for submission to a journal.  I want a figure legend at the end, then tables, then I'll have the tables and figures.  As I am writing, I only have a rough idea of what order the figures will be referenced in the text. I just want to reference them with a text code like fig:foobar and have the number assigned based appearance in the text.  When I look at the figure legend list, I'll see what order to put the legends and will move legends around as needed.

Here's my structure.

I have an R package where I have things I need for papers, like various bibliographies and helper R functions.  In that package, I have the following function which uses some variables defined in the main Rmd environment: .rmdenvir and .rmdctr  .

```<code>ref <- function(useName) {
require(stringr)
if(!exists(".refctr")) .refctr <- c(`_` = 0)
if(any(names(.refctr)==useName)) return(.refctr[useName])
type=str_split(useName,":")[[1]][1]
nObj <- sum(str_detect(names(.refctr),type))
useNum <- nObj + 1
newrefctr <- c(.refctr, useNum)
names(newrefctr)[length(.refctr) + 1] <- useName
assign(".refctr", newrefctr, envir=.rmdenvir)
return(useNum)
}
</code>```

It assumes that I name things I want referenced with something like cntname:foo, for example fig:foo.   It makes a new counter for each one and I can make up new counters on the fly (while writing) if needed.

In my main Rmd file, I have some set-up lines:

```<code>    ```{r setup_main}
    require(myPackageforPapers)
    # here is where the variables needed by ref() are defined.
    .rmdenvir = environment()
    .refctr <- c(`_` = 0)
    ````
</code>```

In the text I use the following

```<code>    You can see what I am trying to show in Figure `r ref("fig:foo")`
    and you can see it also in Tables `r ref("tab:foo")`
    and A`r ref("tabappA:foobig")`.
</code>```

to get "You can see what I am trying to show in Figure 1 and you can see it also in Tables 1 and A1."  Although the numbers might not be 1; the number to use will be dynamically determined.  I don't have to use a special function for the first time I reference a figure, table or whatever I am counting.  ref() figures that out by looking to see if the label exists already.  If not it assigns the next number, and returns it.  So you don't have to use "label" in one place and "ref" in another.

In the course of writing, I might decide that appendix A is getting too big, and that I will split off some of the tables into an appendix B.  All I need to do is change the above to

```<code>    You can see what I am trying to show in Figure `r ref("fig:foo")`
    and you can see it also in Tables `r ref("tab:foo")`
    and B`r ref("tabappB:foobig")`.
</code>```

I just specify a new counter name 'tabappB' and the numbers for that are dynamically determined.

At the end of my Rmd file, I have a figure list that will look like

```<code>    # Figure Legends

    Figure `r ref("fig:foo")`. This is the legend for this figure.

    Figure  `r ref("fig:foo2")`. This is the legend for another figure.
</code>```

Then my tables appear like so

```<code>    ```{r print-tablefoo, echo=FALSE}
    tablefoo=mtcars
    thecap = "Tables appear with a legend while figures do not."
    fullcap = paste("Table ", ref("tab:foo"), ". ", thecap, sep="")
    kable(tablefoo, caption=fullcap)
    ```
</code>```

and then the figures like so:

```<code>    ```{r fig-foo, echo=FALSE, fig.cap=paste("Figure",ref("fig:foo"))}
    plot(1,1)
    ```
</code>```

Appendix A is an Rmd file that included as a child.  It will have tables like

```<code>    ```{r print-tableAfoo, echo=FALSE}
    tablefoo=mtcars
    thecap = "This is a legend."
    fullcap = paste("Table A", ref("tabappA:foobig"), ". ", thecap, sep="")
    kable(tablefoo, caption=fullcap)
    ```
</code>```

I do have to add the "A" to get Table A1, but I find it easier if R doesn't think too much for me in terms of labelling my counters.  I just I want it to return the right number.

The cross-referencing works for html, pdf/latex or word.  I'd happily stick with latex solutions, but my co-authors use word so I need a solution that works with pandoc and word.  Also sometimes I want html or some other output and I need a solution that works for any output that works with rmarkdown.

Title: R Markdown HTML Number Figures

Body:
Does anyone know how to number the figures in the captions, for HTML format R Markdown script?

For PDF documents, the caption will say something like:

Figure X: Some Caption Text

However, the equivalent caption for the HTML version will simply say:

Some Caption Text

This makes cross-referencing figures by number completely useless.

Here is a minimal example:

---
title: "My Title"
author: "Me"
output:
  pdf_document: default
  html_document: default
---

```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```

```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```

I have tried setting toc, fig_caption and number_sections within each of the output formats, but this does not seem to change the result.

Body:
I solve cross-referencing using a solution similar to that posted by Nicholas above.  I use bookdown for some projects but I find that awkward to use for other projects where I just want simple cross-referencing.

I use the following when I am writing a paper with rmarkdown and I want it in standard format for submission to a journal.  I want a figure legend at the end, then tables, then I'll have the tables and figures.  As I am writing, I only have a rough idea of what order the figures will be referenced in the text. I just want to reference them with a text code like fig:foobar and have the number assigned based appearance in the text.  When I look at the figure legend list, I'll see what order to put the legends and will move legends around as needed.

Here's my structure.

I have an R package where I have things I need for papers, like various bibliographies and helper R functions.  In that package, I have the following function which uses some variables defined in the main Rmd environment: .rmdenvir and .rmdctr  .

ref <- function(useName) {
require(stringr)
if(!exists(".refctr")) .refctr <- c(`_` = 0)
if(any(names(.refctr)==useName)) return(.refctr[useName])
type=str_split(useName,":")[[1]][1]
nObj <- sum(str_detect(names(.refctr),type))
useNum <- nObj + 1
newrefctr <- c(.refctr, useNum)
names(newrefctr)[length(.refctr) + 1] <- useName
assign(".refctr", newrefctr, envir=.rmdenvir)
return(useNum)
}

It assumes that I name things I want referenced with something like cntname:foo, for example fig:foo.   It makes a new counter for each one and I can make up new counters on the fly (while writing) if needed.

In my main Rmd file, I have some set-up lines:

    ```{r setup_main}
    require(myPackageforPapers)
    # here is where the variables needed by ref() are defined.
    .rmdenvir = environment()
    .refctr <- c(`_` = 0)
    ````

In the text I use the following

    You can see what I am trying to show in Figure `r ref("fig:foo")`
    and you can see it also in Tables `r ref("tab:foo")`
    and A`r ref("tabappA:foobig")`.

to get "You can see what I am trying to show in Figure 1 and you can see it also in Tables 1 and A1."  Although the numbers might not be 1; the number to use will be dynamically determined.  I don't have to use a special function for the first time I reference a figure, table or whatever I am counting.  ref() figures that out by looking to see if the label exists already.  If not it assigns the next number, and returns it.  So you don't have to use "label" in one place and "ref" in another.

In the course of writing, I might decide that appendix A is getting too big, and that I will split off some of the tables into an appendix B.  All I need to do is change the above to

    You can see what I am trying to show in Figure `r ref("fig:foo")`
    and you can see it also in Tables `r ref("tab:foo")`
    and B`r ref("tabappB:foobig")`.

I just specify a new counter name 'tabappB' and the numbers for that are dynamically determined.

At the end of my Rmd file, I have a figure list that will look like

    # Figure Legends

    Figure `r ref("fig:foo")`. This is the legend for this figure.

    Figure  `r ref("fig:foo2")`. This is the legend for another figure.

Then my tables appear like so

    ```{r print-tablefoo, echo=FALSE}
    tablefoo=mtcars
    thecap = "Tables appear with a legend while figures do not."
    fullcap = paste("Table ", ref("tab:foo"), ". ", thecap, sep="")
    kable(tablefoo, caption=fullcap)
    ```

and then the figures like so:

    ```{r fig-foo, echo=FALSE, fig.cap=paste("Figure",ref("fig:foo"))}
    plot(1,1)
    ```

Appendix A is an Rmd file that included as a child.  It will have tables like

    ```{r print-tableAfoo, echo=FALSE}
    tablefoo=mtcars
    thecap = "This is a legend."
    fullcap = paste("Table A", ref("tabappA:foobig"), ". ", thecap, sep="")
    kable(tablefoo, caption=fullcap)
    ```

I do have to add the "A" to get Table A1, but I find it easier if R doesn't think too much for me in terms of labelling my counters.  I just I want it to return the right number.

The cross-referencing works for html, pdf/latex or word.  I'd happily stick with latex solutions, but my co-authors use word so I need a solution that works with pandoc and word.  Also sometimes I want html or some other output and I need a solution that works for any output that works with rmarkdown.