问:
Bound objects not releasing
I instantiated a ChromiumWebbrowser on a modal form and then bind an object via JavascriptObjectRepository.Register method. Upon closing the form and re-opening a new modal form and invoking a method on the bound object I notice the bound object's method is incrementally invoking. So after modal has been opened, closed then reopened the bound object's method will be invoked twice and on subsequent open / close cycles this count will increase.

How do I release a bound object from CEF.

I have tried to detect if the object is bound already (using IsBound) but it returns false, however it still executes the method incrementally as the form is opened / closed.

```<code>ChromiumWebBrowser brwsr = new ChromiumWebBrowser("");
if (brwsr.JavascriptObjectRepository.IsBound("test"))
                return;
brwsr.JavascriptObjectRepository.Register("test", [object]);
</code>```

答: The issue experienced was due to the bound object having an event handler that was not released on close of the form containing the cef browser. On subsequent launches of the form the bound object would get the event handler assigned again and cause the issue experienced. This was not an issue with cef but rather the bound object I used.</p>

Title: Bound objects not releasing

Body:
I instantiated a ChromiumWebbrowser on a modal form and then bind an object via JavascriptObjectRepository.Register method. Upon closing the form and re-opening a new modal form and invoking a method on the bound object I notice the bound object's method is incrementally invoking. So after modal has been opened, closed then reopened the bound object's method will be invoked twice and on subsequent open / close cycles this count will increase.

How do I release a bound object from CEF.

I have tried to detect if the object is bound already (using IsBound) but it returns false, however it still executes the method incrementally as the form is opened / closed.

ChromiumWebBrowser brwsr = new ChromiumWebBrowser("");
if (brwsr.JavascriptObjectRepository.IsBound("test"))
                return;
brwsr.JavascriptObjectRepository.Register("test", [object]);


来源: stackexchange

问:
Ways to limit output of NN regression problem in certain limit(i.e. I want my NN to always predict output values only between -20 to +30)
I am training NN for the regression problem. So the output layer has a linear activation function. NN output is supposed to be between -20 to 30. My NN is performing good most of the time. However, sometimes it gives output more than 30 which is not desirable for my system. So does anyone know any activation function that can provide such kind of restriction on output or any suggestions on modifying linear activation function for my application?

I am using Keras with tenserflow backend for this application

答:
What you should do is normalize your target outputs to the range [-1, 1] or [0, 1], and then use a tanh (for [-1, 1]) or sigmoid (for [0, 1]) activation at the output, and train the model with normalize data.

Then you can denormalize the predictions to get values in your original ranges during inference.

ContentLicense: CC BY-SA 4.0


问:
Iterate over a json input and create the treeview like hierarchy based on the "keys" taking account of the children "keys"
I have the following piece of code:

```<code> JObject my_obj = JsonConvert.DeserializeObject<JObject>(ReceivedJson);
 ParseJson(my_obj); //method to store all the nested "keys" and the "id" values

     public void ParseJson(JObject obj)
        {

            foreach (KeyValuePair<string, JToken> sub_obj in (JObject)obj["Soccer"])
            {
                Console.WriteLine(sub_obj.Key);
            }
        }
//this does not work well as I cant access all the nested keys :/
</code>```

I am receiving a json in the following format. It could be nested on several levels and I want to be able to store the nested "keys" and their respective "T_id" value in a dictionary.

The json is as follows:

```<code>{
   "Soccer":{
      "T_id":0,
      "T_state":"valid",
      "Clubs":{
         "ClubA":{
            "T_id":"1",
            "T_state":"Champs"
         },
         "ClubB":{
            "T_id":"2",
            "T_state":"Runnerups"
         }
      },
      "Subs":{
         "SubA":{
            "T_id":"3",
            "T_state":"Unfit",
            //this is nested key
            "SubE":{
               "T_id":"3",
               "T_state":"Unfit"
            }
         }
      },
      "Subs_Used":{
         "SubK":{
            "T_id":"3",
            "T_state":"Unfit"
         }
      }
      //many more nested n-levels
   }
}
</code>```

I want to be able to extract the "keys" and create a nested structure like this:

```<code>>Soccer
  >Clubs
    ClubA
    ClubB
  >Subs
    SubA
  >Subs_Used
    SubK
</code>```

where each node has two fields, { string key, int T_id }

The "keys" could be nested deeply and I want to have a generic method which allows me to create this hierarchy while iterating over the JObject.

Is there a simple approach to do this? I am really lost and would appreciate help to make progress.

答:
What you want to do is to map your deeply nested JSON into a c# tree where each node has two properties -- a string key and a long T_id -- as well as a collection of children of the same type.

You could model this as follows, using a list:

```<code>public partial class KeyIdObject
{
    public string key { get; set; }
    public long T_id { get; set; }
    public List<KeyIdObject> Children { get; set; }
}
</code>```

Once you have you data model, you need to use a recursive algorithm to generate your nodes.  A related algorithms is shown in Searching for a specific JToken by name in a JObject hierarchy, but you need a two-stage recursion:

Descend through the JToken hierarchy until you find a JObject with a T_id property.

Once you have found a match, construct a KeyIdObject for it and populate its list of children by searching the matching JObject's children using a nested recursive search.

Then move on to the matches's next sibling in the outer recursive search.

This can be accomplished by introducing an extension method that searches for the topmost descendants of a given JToken that match a given condition:

```<code>public static partial class JsonExtensions
{
    /// <summary>
    /// Enumerates through all descendants of the given element, returning the topmost elements that match the given predicate
    /// </summary>
    /// <param name="root"></param>
    /// <param name="filter"></param>
    /// <returns></returns>
    public static IEnumerable<TJToken> TopDescendantsWhere<TJToken>(this JToken root, Func<TJToken, bool> predicate) where TJToken : JToken
    {
        if (predicate == null)
            throw new ArgumentNullException();
        return GetTopDescendantsWhere<TJToken>(root, predicate, false);
    }

    static IEnumerable<TJToken> GetTopDescendantsWhere<TJToken>(JToken root, Func<TJToken, bool> predicate, bool includeSelf) where TJToken : JToken
    {
        if (root == null)
            yield break;
        if (includeSelf)
        {
            var currentOfType = root as TJToken;
            if (currentOfType != null && predicate(currentOfType))
            {
                yield return currentOfType;
                yield break;
            }
        }
        var rootContainer = root as JContainer;
        if (rootContainer == null)
            yield break;
        var current = root.First;
        while (current != null)
        {
            var currentOfType = current as TJToken;
            var isMatch = currentOfType != null && predicate(currentOfType);
            if (isMatch)
                yield return currentOfType;

            // If a match, skip children, but if not, advance to the first child of the current element.
            var next = (isMatch ? null : current.FirstChild());

            if (next == null)
                // If no first child, get the next sibling of the current element.
                next = current.Next;

            // If no more siblings, crawl up the list of parents until hitting the root, getting the next sibling of the lowest parent that has more siblings.
            if (next == null)
            {
                for (var parent = current.Parent; parent != null && parent != root && next == null; parent = parent.Parent)
                {
                    next = parent.Next;
                }
            }

            current = next;
        }
    }

    static JToken FirstChild(this JToken token)
    {
        var container = token as JContainer;
        return container == null ? null : container.First;
    }
}
</code>```

Then, you can use it to generate a recursive List<KeyIdObject> like so:

```<code>public partial class KeyIdObject
{
    public static List<KeyIdObject> ToIdObjects(JToken root)
    {
        return root.TopDescendantsWhere<JObject>(o => o["T_id"] != null)
            .Select(o => new KeyIdObject { key = ((JProperty)o.Parent).Name, T_id = (long)o["T_id"], Children = ToIdObjects(o) })
            .ToList();
    }
}
</code>```

Demo fiddle #1 here, which generates the following structure:

```<code>[
  {
    "key": "Soccer",
    "T_id": 0,
    "Children": [
      {
        "key": "ClubA",
        "T_id": 1
      },
      {
        "key": "ClubB",
        "T_id": 2
      },
      {
        "key": "SubA",
        "T_id": 3,
        "Children": [
          {
            "key": "SubE",
            "T_id": 3
          }
        ]
      },
      {
        "key": "SubK",
        "T_id": 3
      }
    ]
  }
]
</code>```

However, in your JSON some of your object node(s), specifically "Clubs" and "Subs", do not have a T_id property.  Thus, they can't be captured into the node hierarchy as there is no way to populate the long T_id value.  If you do need to capture these nodes, you can modify your data model to have a nullable value for the id and capture the intermediate nodes as follows:

```<code>public partial class KeyIdObject
{
    public string key { get; set; }
    public long? T_id { get; set; }
    public List<KeyIdObject> Children { get; set; }
}

public partial class KeyIdObject
{
    public static List<KeyIdObject> ToIdObjects(JToken root)
    {
        return root.TopDescendantsWhere<JObject>(o => true)
            .Select(o => new KeyIdObject { key = ((JProperty)o.Parent).Name, T_id = (long?)o["T_id"], Children = ToIdObjects(o) })
            .ToList();
    }
}
</code>```

Demo fiddle #2 here.

Finally, if you are sure your keys are unique at any given level, you could use a dictionary instead of a list, like so:

```<code>public partial class IdObject
{
    public long T_id { get; set; }
    public Dictionary<string, IdObject> Children { get; set; }
}

public partial class IdObject
{
    public static Dictionary<string, IdObject> ToIdObjects(JToken root)
    {
        return root.TopDescendantsWhere<JObject>(o => o["T_id"] != null)
            .ToDictionary(o => ((JProperty)o.Parent).Name,
                          o => new IdObject { T_id = (long)o["T_id"], Children = ToIdObjects(o) });
    }
}
</code>```

Demo fiddle #3 here.

Note that, in all cases, I chose long instead of int for the T_id for safety.

Update

If you are going to bind this into a WPF TreeView or something similar like a Syncfusion.Xamarin.SfTreeView, you will want to implement INotifyPropertyChanged and use ObservableCollection<T>.  You may also want to use a different ItemTemplate for nodes with and without T_id values, in which case you can define a different c# POCO for each case.  The following is one example:

```<code>public abstract partial class KeyItemBase : INotifyPropertyChanged
{
    public KeyItemBase() : this(null, Enumerable.Empty<KeyItemBase>()) { }

    public KeyItemBase(string key, IEnumerable<KeyItemBase> children)
    {
        this.m_key = key;
        this.m_children = new ObservableCollection<KeyItemBase>(children);
    }

    string m_key;
    public string key
    {
        get { return m_key; }
        set
        {
            m_key = value;
            RaisedOnPropertyChanged("key");
        }
    }

    ObservableCollection<KeyItemBase> m_children;
    public ObservableCollection<KeyItemBase> Children { get { return m_children; } }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisedOnPropertyChanged(string _PropertyName)
    {
        var changed = PropertyChanged;
        if (changed != null)
        {
            changed(this, new PropertyChangedEventArgs(_PropertyName));
        }
    }
}

public abstract partial class KeyItemBase
{
    // Generate clean JSON on re-serialization.
    public bool ShouldSerializeChildren() { return Children != null && Children.Count > 0; }
}

public sealed class KeyItem : KeyItemBase
{
    // Use for a JSON object with no T_id property.
    // Bind an appropriate SfTreeView.ItemTemplate to this type.

    public KeyItem() : base() { }

    public KeyItem(string key, IEnumerable<KeyItemBase> children) : base(key, children) { }
}

public class KeyIdItem : KeyItemBase
{
    // Use for a JSON object with a T_id property.
    // Bind an appropriate SfTreeView.ItemTemplate to this type.

    public KeyIdItem() : base() { }

    public KeyIdItem(string key, IEnumerable<KeyItemBase> children, long t_id) : base(key, children) { this.m_id = t_id; }

    long m_id;
    public long T_id
    {
        get { return m_id; }
        set
        {
            m_id = value;
            RaisedOnPropertyChanged("T_id");
        }
    }
}

public static class KeyItemFactory
{
    public static KeyItemBase ToKeyObject(string name, long? id, IEnumerable<KeyItemBase> children)
    {
        if (id == null)
            return new KeyItem(name, children);
        else
            return new KeyIdItem(name, children, id.Value);
    }

    public static IEnumerable<KeyItemBase> ToKeyObjects(JToken root)
    {
        return root.TopDescendantsWhere<JObject>(o => true)
            .Select(o => ToKeyObject(((JProperty)o.Parent).Name, (long?)o["T_id"], ToKeyObjects(o)));
    }
}
</code>```

Which you would use as follows:

```<code>var items = new ObservableCollection<KeyItemBase>(KeyItemFactory.ToKeyObjects(root));

// Now bind items to your ItemsSource
// https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfTreeView.XForms~Syncfusion.XForms.TreeView.SfTreeView~ItemsSource.html
</code>```

Demo fiddle #4 here.

Body:
I have the following piece of code:

 JObject my_obj = JsonConvert.DeserializeObject<JObject>(ReceivedJson);
 ParseJson(my_obj); //method to store all the nested "keys" and the "id" values

     public void ParseJson(JObject obj)
        {

            foreach (KeyValuePair<string, JToken> sub_obj in (JObject)obj["Soccer"])
            {
                Console.WriteLine(sub_obj.Key);
            }
        }
//this does not work well as I cant access all the nested keys :/

I am receiving a json in the following format. It could be nested on several levels and I want to be able to store the nested "keys" and their respective "T_id" value in a dictionary.

The json is as follows:

{
   "Soccer":{
      "T_id":0,
      "T_state":"valid",
      "Clubs":{
         "ClubA":{
            "T_id":"1",
            "T_state":"Champs"
         },
         "ClubB":{
            "T_id":"2",
            "T_state":"Runnerups"
         }
      },
      "Subs":{
         "SubA":{
            "T_id":"3",
            "T_state":"Unfit",
            //this is nested key
            "SubE":{
               "T_id":"3",
               "T_state":"Unfit"
            }
         }
      },
      "Subs_Used":{
         "SubK":{
            "T_id":"3",
            "T_state":"Unfit"
         }
      }
      //many more nested n-levels
   }
}

I want to be able to extract the "keys" and create a nested structure like this:

>Soccer
  >Clubs
    ClubA
    ClubB
  >Subs
    SubA
  >Subs_Used
    SubK

where each node has two fields, { string key, int T_id }

The "keys" could be nested deeply and I want to have a generic method which allows me to create this hierarchy while iterating over the JObject.

Is there a simple approach to do this? I am really lost and would appreciate help to make progress.

Body:
What you want to do is to map your deeply nested JSON into a c# tree where each node has two properties -- a string key and a long T_id -- as well as a collection of children of the same type.

You could model this as follows, using a list:

public partial class KeyIdObject
{
    public string key { get; set; }
    public long T_id { get; set; }
    public List<KeyIdObject> Children { get; set; }
}

Once you have you data model, you need to use a recursive algorithm to generate your nodes.  A related algorithms is shown in Searching for a specific JToken by name in a JObject hierarchy, but you need a two-stage recursion:

Descend through the JToken hierarchy until you find a JObject with a T_id property.

Once you have found a match, construct a KeyIdObject for it and populate its list of children by searching the matching JObject's children using a nested recursive search.

Then move on to the matches's next sibling in the outer recursive search.

This can be accomplished by introducing an extension method that searches for the topmost descendants of a given JToken that match a given condition:

public static partial class JsonExtensions
{
    /// <summary>
    /// Enumerates through all descendants of the given element, returning the topmost elements that match the given predicate
    /// </summary>
    /// <param name="root"></param>
    /// <param name="filter"></param>
    /// <returns></returns>
    public static IEnumerable<TJToken> TopDescendantsWhere<TJToken>(this JToken root, Func<TJToken, bool> predicate) where TJToken : JToken
    {
        if (predicate == null)
            throw new ArgumentNullException();
        return GetTopDescendantsWhere<TJToken>(root, predicate, false);
    }

    static IEnumerable<TJToken> GetTopDescendantsWhere<TJToken>(JToken root, Func<TJToken, bool> predicate, bool includeSelf) where TJToken : JToken
    {
        if (root == null)
            yield break;
        if (includeSelf)
        {
            var currentOfType = root as TJToken;
            if (currentOfType != null && predicate(currentOfType))
            {
                yield return currentOfType;
                yield break;
            }
        }
        var rootContainer = root as JContainer;
        if (rootContainer == null)
            yield break;
        var current = root.First;
        while (current != null)
        {
            var currentOfType = current as TJToken;
            var isMatch = currentOfType != null && predicate(currentOfType);
            if (isMatch)
                yield return currentOfType;

            // If a match, skip children, but if not, advance to the first child of the current element.
            var next = (isMatch ? null : current.FirstChild());

            if (next == null)
                // If no first child, get the next sibling of the current element.
                next = current.Next;

            // If no more siblings, crawl up the list of parents until hitting the root, getting the next sibling of the lowest parent that has more siblings.
            if (next == null)
            {
                for (var parent = current.Parent; parent != null && parent != root && next == null; parent = parent.Parent)
                {
                    next = parent.Next;
                }
            }

            current = next;
        }
    }

    static JToken FirstChild(this JToken token)
    {
        var container = token as JContainer;
        return container == null ? null : container.First;
    }
}

Then, you can use it to generate a recursive List<KeyIdObject> like so:

public partial class KeyIdObject
{
    public static List<KeyIdObject> ToIdObjects(JToken root)
    {
        return root.TopDescendantsWhere<JObject>(o => o["T_id"] != null)
            .Select(o => new KeyIdObject { key = ((JProperty)o.Parent).Name, T_id = (long)o["T_id"], Children = ToIdObjects(o) })
            .ToList();
    }
}

Demo fiddle #1 here, which generates the following structure:

[
  {
    "key": "Soccer",
    "T_id": 0,
    "Children": [
      {
        "key": "ClubA",
        "T_id": 1
      },
      {
        "key": "ClubB",
        "T_id": 2
      },
      {
        "key": "SubA",
        "T_id": 3,
        "Children": [
          {
            "key": "SubE",
            "T_id": 3
          }
        ]
      },
      {
        "key": "SubK",
        "T_id": 3
      }
    ]
  }
]

However, in your JSON some of your object node(s), specifically "Clubs" and "Subs", do not have a T_id property.  Thus, they can't be captured into the node hierarchy as there is no way to populate the long T_id value.  If you do need to capture these nodes, you can modify your data model to have a nullable value for the id and capture the intermediate nodes as follows:

public partial class KeyIdObject
{
    public string key { get; set; }
    public long? T_id { get; set; }
    public List<KeyIdObject> Children { get; set; }
}

public partial class KeyIdObject
{
    public static List<KeyIdObject> ToIdObjects(JToken root)
    {
        return root.TopDescendantsWhere<JObject>(o => true)
            .Select(o => new KeyIdObject { key = ((JProperty)o.Parent).Name, T_id = (long?)o["T_id"], Children = ToIdObjects(o) })
            .ToList();
    }
}

Demo fiddle #2 here.

Finally, if you are sure your keys are unique at any given level, you could use a dictionary instead of a list, like so:

public partial class IdObject
{
    public long T_id { get; set; }
    public Dictionary<string, IdObject> Children { get; set; }
}

public partial class IdObject
{
    public static Dictionary<string, IdObject> ToIdObjects(JToken root)
    {
        return root.TopDescendantsWhere<JObject>(o => o["T_id"] != null)
            .ToDictionary(o => ((JProperty)o.Parent).Name,
                          o => new IdObject { T_id = (long)o["T_id"], Children = ToIdObjects(o) });
    }
}

Demo fiddle #3 here.

Note that, in all cases, I chose long instead of int for the T_id for safety.

Update

If you are going to bind this into a WPF TreeView or something similar like a Syncfusion.Xamarin.SfTreeView, you will want to implement INotifyPropertyChanged and use ObservableCollection<T>.  You may also want to use a different ItemTemplate for nodes with and without T_id values, in which case you can define a different c# POCO for each case.  The following is one example:

public abstract partial class KeyItemBase : INotifyPropertyChanged
{
    public KeyItemBase() : this(null, Enumerable.Empty<KeyItemBase>()) { }

    public KeyItemBase(string key, IEnumerable<KeyItemBase> children)
    {
        this.m_key = key;
        this.m_children = new ObservableCollection<KeyItemBase>(children);
    }

    string m_key;
    public string key
    {
        get { return m_key; }
        set
        {
            m_key = value;
            RaisedOnPropertyChanged("key");
        }
    }

    ObservableCollection<KeyItemBase> m_children;
    public ObservableCollection<KeyItemBase> Children { get { return m_children; } }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisedOnPropertyChanged(string _PropertyName)
    {
        var changed = PropertyChanged;
        if (changed != null)
        {
            changed(this, new PropertyChangedEventArgs(_PropertyName));
        }
    }
}

public abstract partial class KeyItemBase
{
    // Generate clean JSON on re-serialization.
    public bool ShouldSerializeChildren() { return Children != null && Children.Count > 0; }
}

public sealed class KeyItem : KeyItemBase
{
    // Use for a JSON object with no T_id property.
    // Bind an appropriate SfTreeView.ItemTemplate to this type.

    public KeyItem() : base() { }

    public KeyItem(string key, IEnumerable<KeyItemBase> children) : base(key, children) { }
}

public class KeyIdItem : KeyItemBase
{
    // Use for a JSON object with a T_id property.
    // Bind an appropriate SfTreeView.ItemTemplate to this type.

    public KeyIdItem() : base() { }

    public KeyIdItem(string key, IEnumerable<KeyItemBase> children, long t_id) : base(key, children) { this.m_id = t_id; }

    long m_id;
    public long T_id
    {
        get { return m_id; }
        set
        {
            m_id = value;
            RaisedOnPropertyChanged("T_id");
        }
    }
}

public static class KeyItemFactory
{
    public static KeyItemBase ToKeyObject(string name, long? id, IEnumerable<KeyItemBase> children)
    {
        if (id == null)
            return new KeyItem(name, children);
        else
            return new KeyIdItem(name, children, id.Value);
    }

    public static IEnumerable<KeyItemBase> ToKeyObjects(JToken root)
    {
        return root.TopDescendantsWhere<JObject>(o => true)
            .Select(o => ToKeyObject(((JProperty)o.Parent).Name, (long?)o["T_id"], ToKeyObjects(o)));
    }
}

Which you would use as follows:

var items = new ObservableCollection<KeyItemBase>(KeyItemFactory.ToKeyObjects(root));

// Now bind items to your ItemsSource
// https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfTreeView.XForms~Syncfusion.XForms.TreeView.SfTreeView~ItemsSource.html

Demo fiddle #4 here.


问:
Printing a dataframe from a function nicely as in Jupyter
I've seen a lot of very helpful posts on using prettyprint and such; they have been very helpful -- thanks.

What I'm wondering if there is anyway to print a dataframe from a function and have it output as "prettily" as Jupyter notebook does:

My main reason is I would like to use pandas's styling functions to highlight/shade.  I also want to print from a function and not a Jupyter code box if possible as I have some packages I have created and I may want to spit out 2 or more dataframes in a call.

Using prettyprint or print() alone gives a purely text output:

```<code>>       Year      Month  Mean Maximum Temperature Albury  \
> 672   1955    January                             30.8
> 673   1955   February                             27.9
> 674   1955      March                             26.7
> 675   1955      April                             22.1
> ....
</code>```

I'd like the graphical output.  Not using print(), e.g.

```<code>historic_dataframe
</code>```

does nothing if within a function.

My thanks for your time.

答:
Use display from IPython instead of print

```<code>import pandas as pd
from IPython.display import display

df = pd.DataFrame(pd.np.random.random((10, 10)))
display(df)
</code>```

display docs

Body:
I've seen a lot of very helpful posts on using prettyprint and such; they have been very helpful -- thanks.

What I'm wondering if there is anyway to print a dataframe from a function and have it output as "prettily" as Jupyter notebook does:

My main reason is I would like to use pandas's styling functions to highlight/shade.  I also want to print from a function and not a Jupyter code box if possible as I have some packages I have created and I may want to spit out 2 or more dataframes in a call.

Using prettyprint or print() alone gives a purely text output:

>       Year      Month  Mean Maximum Temperature Albury  \
> 672   1955    January                             30.8
> 673   1955   February                             27.9
> 674   1955      March                             26.7
> 675   1955      April                             22.1
> ....

I'd like the graphical output.  Not using print(), e.g.

historic_dataframe

does nothing if within a function.

My thanks for your time.

Body:
Use display from IPython instead of print

import pandas as pd
from IPython.display import display

df = pd.DataFrame(pd.np.random.random((10, 10)))
display(df)

display docs


问:
Converting Char to Integer in Common Lisp
What is the proper way to convert the character #\1 to the integer 1?
I coerced a number into a list and got this:
(#\1 #\2 #\3)

and want to convert that into

```<code>(1 2 3)
</code>```

答:
```<code>CL-USER > (digit-char-p #\1)
1
</code>```

digit-char-p returns

the numeric value of the character, if it is a digit char

NIL otherwise

Thus it is both:

a predicate, since numbers are true

a conversion function

Body:
What is the proper way to convert the character #\1 to the integer 1?
I coerced a number into a list and got this:
(#\1 #\2 #\3)

and want to convert that into

(1 2 3)

Body:
CL-USER > (digit-char-p #\1)
1

digit-char-p returns

the numeric value of the character, if it is a digit char

NIL otherwise

Thus it is both:

a predicate, since numbers are true

a conversion function


问:
Need to add a column to a CSV that adds a number for each line of data (1,2,3,etc)
Need to append a CSV file to add a Column (Pkey) with an increment numeric starting from 1 for every line of data.  I prefer to have a VB script do this, but if theres an easier method I can run on a windows task scheduler I am open to anything.

I just need a script that creates a column in the CSV named "Pkey" and adds a increasing numeric +1 to every line of data, starting with 1.  This has to be unique counts all the way down to the final line of data.

Expected to have a column added with header Pkey, then number down the lines of data 1,2,3,4,5,etc till all lines of data have been numbered with a unique integer

Code that I currently use to pull the query into the CSV and save it, everytime I try to do the increment it breaks the script:

```<code>    Option Explicit

Dim TextExportPath
Dim TextExportFile
Dim db
Dim cn
Dim strCon
Dim objFileSys

db = "X:\VPP DATABASE\Pham.mdb"
TextExportPath = "X:\Scripts\FTP\QuickBase Sync\CustomerData\"
TextExportFile = NewFileName(TextExportPath)

Set objFileSys = CreateObject("Scripting.FileSystemObject")
If objFileSys.FileExists("X:\Scripts\FTP\QuickBase Sync\CustomerData\MMD_Abacus.csv") Then
objFileSys.DeleteFile "X:\Scripts\FTP\QuickBase Sync\CustomerData\MMD_Abacus.csv"

End If

Set cn = CreateObject("ADODB.Connection")

cn.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
    "Data Source =" & db

cn.Execute "SELECT * INTO [text;HDR=Yes;Database=" & TextExportPath & _
   "]." & TextExportFile & " FROM 83AFFNIGHT"

Function NewFileName(TextExportPath)
Dim fs
Dim NewFileTemp
Dim a, i

Set fs = CreateObject("Scripting.FileSystemObject")

NewFileTemp = "MMD_Abacus" & ".csv"

a = fs.FileExists(TextExportPath & NewFileTemp)

NewFileName = NewFileTemp
End Function
</code>```

So would I add something like this, or even create a separate vb script to run after this one?

```<code>Dim lines As New List(Of String)
Dim lineNumber = 1

Using parser As New TextFieldParser("TextFile1.txt") With {.Delimiters = {","}}
    Do Until parser.EndOfData
        Dim fields = parser.ReadFields()

        'Add quotes around the column that may be multiline.
        fields(1) = $"""{fields(1)}"""

        lines.Add(String.Join(",", fields) & "," & lineNumber)
        lineNumber += 1
    Loop
End Using

File.WriteAllLines("TextFile1.txt", lines)
</code>```

答:
... if theres an easier method I can run on a windows task scheduler I am open to anything.

Let's do PowerShell!

Make sure you're using the 32-bit powershell for this:

```<code>function Get-MSAccessTable {
Param(
    [parameter(Mandatory=$true)] $filePath,
    [parameter(Mandatory=$true)] $tableName
)
    $conn = New-Object System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=$filePath;Persist Security Info=False")
    $cmd=$conn.CreateCommand()
    $cmd.CommandText="Select * from $tableName"
    $conn.open()
    $rdr = $cmd.ExecuteReader()
    $dt = New-Object System.Data.Datatable
    $dt.Load($rdr)
    $conn.close()
    $dt
}

$TextExportPath = "X:\Scripts\FTP\QuickBase Sync\CustomerData"
$TextExportFile = "$TextExportPath\MMD_Abacus.csv"

$db = "X:\VPP DATABASE\Pham.mdb"
$data = Get-MSAccessTable -filePath $db -tableName "83AFFNIGHT"

$Global:seq = 1;
$data = $data | Select-Object <LIST COLUMNS HERE>, @{label = “PKey”; Expression = {$Global:seq;$Global:seq++ }}

Remove-Item -Path "X:\Scripts\FTP\QuickBase Sync\CustomerData\MMD_Abacus.csv"
$data | Export-Csv -Path $TextExportFile -NoTypeInformation
</code>```

Body:
Need to append a CSV file to add a Column (Pkey) with an increment numeric starting from 1 for every line of data.  I prefer to have a VB script do this, but if theres an easier method I can run on a windows task scheduler I am open to anything.

I just need a script that creates a column in the CSV named "Pkey" and adds a increasing numeric +1 to every line of data, starting with 1.  This has to be unique counts all the way down to the final line of data.

Expected to have a column added with header Pkey, then number down the lines of data 1,2,3,4,5,etc till all lines of data have been numbered with a unique integer

Code that I currently use to pull the query into the CSV and save it, everytime I try to do the increment it breaks the script:

    Option Explicit

Dim TextExportPath
Dim TextExportFile
Dim db
Dim cn
Dim strCon
Dim objFileSys

db = "X:\VPP DATABASE\Pham.mdb"
TextExportPath = "X:\Scripts\FTP\QuickBase Sync\CustomerData\"
TextExportFile = NewFileName(TextExportPath)

Set objFileSys = CreateObject("Scripting.FileSystemObject")
If objFileSys.FileExists("X:\Scripts\FTP\QuickBase Sync\CustomerData\MMD_Abacus.csv") Then
objFileSys.DeleteFile "X:\Scripts\FTP\QuickBase Sync\CustomerData\MMD_Abacus.csv"

End If

Set cn = CreateObject("ADODB.Connection")

cn.Open _
    "Provider = Microsoft.Jet.OLEDB.4.0; " & _
    "Data Source =" & db

cn.Execute "SELECT * INTO [text;HDR=Yes;Database=" & TextExportPath & _
   "]." & TextExportFile & " FROM 83AFFNIGHT"

Function NewFileName(TextExportPath)
Dim fs
Dim NewFileTemp
Dim a, i

Set fs = CreateObject("Scripting.FileSystemObject")

NewFileTemp = "MMD_Abacus" & ".csv"

a = fs.FileExists(TextExportPath & NewFileTemp)

NewFileName = NewFileTemp
End Function

So would I add something like this, or even create a separate vb script to run after this one?

Dim lines As New List(Of String)
Dim lineNumber = 1

Using parser As New TextFieldParser("TextFile1.txt") With {.Delimiters = {","}}
    Do Until parser.EndOfData
        Dim fields = parser.ReadFields()

        'Add quotes around the column that may be multiline.
        fields(1) = $"""{fields(1)}"""

        lines.Add(String.Join(",", fields) & "," & lineNumber)
        lineNumber += 1
    Loop
End Using

File.WriteAllLines("TextFile1.txt", lines)

Body:
... if theres an easier method I can run on a windows task scheduler I am open to anything.

Let's do PowerShell!

Make sure you're using the 32-bit powershell for this:

function Get-MSAccessTable {
Param(
    [parameter(Mandatory=$true)] $filePath,
    [parameter(Mandatory=$true)] $tableName
)
    $conn = New-Object System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=$filePath;Persist Security Info=False")
    $cmd=$conn.CreateCommand()
    $cmd.CommandText="Select * from $tableName"
    $conn.open()
    $rdr = $cmd.ExecuteReader()
    $dt = New-Object System.Data.Datatable
    $dt.Load($rdr)
    $conn.close()
    $dt
}

$TextExportPath = "X:\Scripts\FTP\QuickBase Sync\CustomerData"
$TextExportFile = "$TextExportPath\MMD_Abacus.csv"

$db = "X:\VPP DATABASE\Pham.mdb"
$data = Get-MSAccessTable -filePath $db -tableName "83AFFNIGHT"

$Global:seq = 1;
$data = $data | Select-Object <LIST COLUMNS HERE>, @{label = “PKey”; Expression = {$Global:seq;$Global:seq++ }}

Remove-Item -Path "X:\Scripts\FTP\QuickBase Sync\CustomerData\MMD_Abacus.csv"
$data | Export-Csv -Path $TextExportFile -NoTypeInformation


问:
iPhone SDK - Passing Data in an Array that is NOT shown in a UITableViewCell when that UITableViewCell is Selected
I have have searched all over for a tutorial or something that could show me how to pass data from an array that populates a cells cell.textlabel.text field that also has additional information in that node...

For simplicity sake I'm taking data I'm parsing from a Webservice that's producing an XML file. Which returns a "ID", "Name", "OtherID" field. Then populating a UITableViewController with the parsed XML essentially just the "Name" field to cell.textLabel.text.  I have all of this working.

However, what I need to happen now is:

When a user does select a row I need the "ID" and "OtherID" field (that are not shown in the cell) to be set into variables, switch views, and set the new view's UILabels with the variables from the old view.

And this is where I'm at a loss...

Could someone point me in the direction of a tutorial or code example of how this code be done?  Or if you have something similar share that with me?

Thank you so much for your time!

答:
When you setup the UITableViewCell in tableView:cellForRowAtIndexPath:, you're using data from a certain index in the array of results, based on the index path of the cell.

The easiest way to do what you ask is to use the index path for the selected cell and perform the same calculation as above to find that certain index. Then you can fetch everything you need from the original array. That would look something like this:

```<code>- (NSUInteger)arrayIndexFromIndexPath:(NSIndexPath *)path {
    // You could inline this, if you like.
    return path.row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)path {
    NSUInteger index = [self arrayIndexFromIndexPath:path];
    NSDictionary *data = [self.dataArray objectAtIndex:index];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:...];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];
    }

    // ... Set up cell ...

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
    NSUInteger index = [self arrayIndexFromIndexPath:path];
    NSDictionary *data = [self.dataArray objectAtIndex:index];

    // ... Do whatever you need with the data ...
}
</code>```

A slightly more complex (but possibly more robust) method would be to subclass UITableViewCell to add properties or ivars to hold the data you will need; this could be as simple as a single property to hold the entire value from the original array. Then in the selection method, you can fetch everything you need from the cell itself. That would look something like this:

MyTableViewCell.h:

```<code>@interface MyTableViewCell : UITableViewCell {
    NSDictionary *data_;
}

@property (nonatomic, retain) NSDictionary *data;

@end
</code>```

MyTableViewCell.m:

```<code>@implementation MyTableViewCell

@synthesize data=data_;

- (void)dealloc {
    [data_ release]; data_ = nil;
    [super dealloc];
}

@end
</code>```

And then:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)path {
    NSUInteger index = [self arrayIndexFromIndexPath:path];
    NSDictionary *data = [self.dataArray objectAtIndex:index];

    // Remember, of course, to use a different reuseIdentifier for each different kind of cell.
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:...];
    if (!cell) {
        cell = [[[MyTableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];
    }

    cell.data = data;

    // ... Set up cell ...

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
    MyTableViewCell *cell = [tableView cellForRowAtIndexPath:path];
    NSDictionary *data = cell.data;

    // ... Do whatever you need with the data ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When you setup the UITableViewCell in tableView:cellForRowAtIndexPath:, you're using data from a certain index in the array of results, based on the index path of the cell.

The easiest way to do what you ask is to use the index path for the selected cell and perform the same calculation as above to find that certain index. Then you can fetch everything you need from the original array. That would look something like this:

- (NSUInteger)arrayIndexFromIndexPath:(NSIndexPath *)path {
    // You could inline this, if you like.
    return path.row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)path {
    NSUInteger index = [self arrayIndexFromIndexPath:path];
    NSDictionary *data = [self.dataArray objectAtIndex:index];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:...];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];
    }

    // ... Set up cell ...

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
    NSUInteger index = [self arrayIndexFromIndexPath:path];
    NSDictionary *data = [self.dataArray objectAtIndex:index];

    // ... Do whatever you need with the data ...
}

A slightly more complex (but possibly more robust) method would be to subclass UITableViewCell to add properties or ivars to hold the data you will need; this could be as simple as a single property to hold the entire value from the original array. Then in the selection method, you can fetch everything you need from the cell itself. That would look something like this:

MyTableViewCell.h:

@interface MyTableViewCell : UITableViewCell {
    NSDictionary *data_;
}

@property (nonatomic, retain) NSDictionary *data;

@end

MyTableViewCell.m:

@implementation MyTableViewCell

@synthesize data=data_;

- (void)dealloc {
    [data_ release]; data_ = nil;
    [super dealloc];
}

@end

And then:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)path {
    NSUInteger index = [self arrayIndexFromIndexPath:path];
    NSDictionary *data = [self.dataArray objectAtIndex:index];

    // Remember, of course, to use a different reuseIdentifier for each different kind of cell.
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:...];
    if (!cell) {
        cell = [[[MyTableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];
    }

    cell.data = data;

    // ... Set up cell ...

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
    MyTableViewCell *cell = [tableView cellForRowAtIndexPath:path];
    NSDictionary *data = cell.data;

    // ... Do whatever you need with the data ...
}


问:
Override default queryset in Django admin
One of my models has a deleted flag, which is used to hide objects globally:

```<code>class NondeletedManager(models.Manager):
    """Returns only objects which haven't been deleted"""

    def get_query_set(self):
        return super(NondeletedManager, self).get_query_set().exclude(deleted=True)

class Conversation(BaseModel):
    ...
    deleted = models.BooleanField(default=False)
    objects = NondeletedManager()
    all_conversations = models.Manager() # includes deleted conversations
</code>```

How can I override the default queryset used by Django admin module to include deleted conversations?

答:
Natan Yellin is correct, but you can change the managers order and the first will be the default, then it is the used by the admin:

```<code>class Conversation(BaseModel):
    ...
    deleted = models.BooleanField(default=False)

    all_conversations = models.Manager() # includes deleted conversations
    objects = NondeletedManager()
</code>```

The admin implementation of get_queryset() use ._default_manager instead .objects, as show next

```<code>qs = self.model._default_manager.get_queryset()
</code>```

ref Django github BaseModelAdmin implementation

This only ensures that every time you use YourModel.objects, you will not include deleted objects, but the generic views and others uses ._default_manager too. Then if you don't override get_queryset is not a solution. I've just check on a ListView and admin.

Body:
One of my models has a deleted flag, which is used to hide objects globally:

class NondeletedManager(models.Manager):
    """Returns only objects which haven't been deleted"""

    def get_query_set(self):
        return super(NondeletedManager, self).get_query_set().exclude(deleted=True)

class Conversation(BaseModel):
    ...
    deleted = models.BooleanField(default=False)
    objects = NondeletedManager()
    all_conversations = models.Manager() # includes deleted conversations

How can I override the default queryset used by Django admin module to include deleted conversations?

Body:
Natan Yellin is correct, but you can change the managers order and the first will be the default, then it is the used by the admin:

class Conversation(BaseModel):
    ...
    deleted = models.BooleanField(default=False)

    all_conversations = models.Manager() # includes deleted conversations
    objects = NondeletedManager()

The admin implementation of get_queryset() use ._default_manager instead .objects, as show next

qs = self.model._default_manager.get_queryset()

ref Django github BaseModelAdmin implementation

This only ensures that every time you use YourModel.objects, you will not include deleted objects, but the generic views and others uses ._default_manager too. Then if you don't override get_queryset is not a solution. I've just check on a ListView and admin.


问:
How come my code only returns the first element from my list?
How come when I call the function I get only the first element from the list printed, but when I replace "return" for "print" inside the function and then call it I get the full list?</p>

```<code>def show_magicians(magicians):

    for magician in magicians:
        return(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))
</code>```

答:
The print() function writes, i.e., "prints", a string in the console. The return statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.

In first iteration when code reach return it go out of function, because of that iterates just one time

Body:
How come when I call the function I get only the first element from the list printed, but when I replace "return" for "print" inside the function and then call it I get the full list?

def show_magicians(magicians):

    for magician in magicians:
        return(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))


问:
How to specify JSON node property values when parsing/iterating in Azure Logic Apps?
TL;DR How do I specify a specific JSON node property within Azure Logic Apps' ParseJSON > For Each step, when the designer only gives me access to the parent nodes?

I'm building a Logic App that:

Receives and parses a list of people as JSON data from an external system

Constructs a new JSON file with different structure

Posts the new file to a second external system

The JSON response from item 1 has this structure:

```<code>{
    "Success": true,
    "Message": "Completed",
    "Result": [
        {
            "EmployeeId": {
                "DisplayValue": "PW123",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        {
            "EmployeeId": {
                "DisplayValue": "PW789",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        .... removed for brevity
    ]
}
</code>```

Within the designer, if I add a Data Operations > Parse JSON > For Each step, it lets me specify the properties, but at too high a level:

Notice the designer gives me EmployeeId, but I actually need EmployeeId.DisplayValue, which is both properties and their values in JSON format, rather than a simple string containing only the EmployeeId or EmailId values.

Can the JSON be read at the deeper level I require using the designer?

答:
If I am not mistaken you can do something in the lines of Parse_JSON()['EmployeeId']['DisplayValue'] <-- this is probably not the exact match, but the syntax is something like that.

They way you do this is that you either write it in code view or in the designer you start on an expression, add the blanks with dynamic content and finish by adding the ['DisplayValue'] tag.

Body:
TL;DR How do I specify a specific JSON node property within Azure Logic Apps' ParseJSON > For Each step, when the designer only gives me access to the parent nodes?

I'm building a Logic App that:

Receives and parses a list of people as JSON data from an external system

Constructs a new JSON file with different structure

Posts the new file to a second external system

The JSON response from item 1 has this structure:

{
    "Success": true,
    "Message": "Completed",
    "Result": [
        {
            "EmployeeId": {
                "DisplayValue": "PW123",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        {
            "EmployeeId": {
                "DisplayValue": "PW789",
                "FieldHistory": []
            },
            "EmailId": {
                "DisplayValue": "*****.*****@******.co.uk",
                "FieldHistory": []
            }
        },
        .... removed for brevity
    ]
}

Within the designer, if I add a Data Operations > Parse JSON > For Each step, it lets me specify the properties, but at too high a level:

Notice the designer gives me EmployeeId, but I actually need EmployeeId.DisplayValue, which is both properties and their values in JSON format, rather than a simple string containing only the EmployeeId or EmailId values.

Can the JSON be read at the deeper level I require using the designer?


问:
How to fix 'Error 111 connecting to localhost:6379. Connection refused' when I start rq-worker?
I'm working with flask, redis and rq-worker in my web application that is hosted ina debian 9 machine. When I start rq-worker I get this error: "Error 111 connecting to localhost:6379. Connection refused".

I already checked if Redis was installed and running, I tried these comands:

/opt/apps/mywebapp/flask$ ps aux | grep redis
sib       4987  0.0  0.0  12784   976 pts/2    S+   09:37   0:00 grep redis
redis     6574  0.1  0.0  40860  3512 ?        Ssl  may28   3:38 /usr/bin/redis-server 127.0.0.1:6379
```

<pre class="lang-sh prettyprint-override"><code>/opt/apps/mywebapp/flask$ redis-cli ping
PONG
</code>```

I've read other post and this is an evidence that Redis is running and woking.

I also check the file redis.conf and I set this variable:

bind 127.0.0.1
```

<p>I tried again.</p>

<pre class="lang-sh prettyprint-override"><code>/opt/apps/mywebapp/flask$ rq worker
</code>```

But I keep receiving the error.

```<code>Error 111 connecting to localhost:6379. Connection refused.
</code>```

答: Sorry, It was the redis configuration bind property, I set it 127.0.0.1 ::00 but the correct configuration was 127.0.0.1 ::01. </p>

Body:
I'm working with flask, redis and rq-worker in my web application that is hosted ina debian 9 machine. When I start rq-worker I get this error: "Error 111 connecting to localhost:6379. Connection refused".

I already checked if Redis was installed and running, I tried these comands:

/opt/apps/mywebapp/flask$ ps aux | grep redis
sib       4987  0.0  0.0  12784   976 pts/2    S+   09:37   0:00 grep redis
redis     6574  0.1  0.0  40860  3512 ?        Ssl  may28   3:38 /usr/bin/redis-server 127.0.0.1:6379

/opt/apps/mywebapp/flask$ redis-cli ping
PONG

I've read other post and this is an evidence that Redis is running and woking.

I also check the file redis.conf and I set this variable:

bind 127.0.0.1

I tried again.

/opt/apps/mywebapp/flask$ rq worker

But I keep receiving the error.

Error 111 connecting to localhost:6379. Connection refused.


问:
Can you Schedule a Gitlab Runner?
Is it possible to schedule the uptime on a runner?
We have a machine that is used heavily for other non-gitlab jobs during the day, so would only like it only accept jobs overnight, as we used to have on jenkins. Is this possible? If so - how?</p>

答:
You can use gitlab api to activate or disable runners. see the documentation

For example:

```<code>PUT /runners/:id

active: false

</code>```

Title: Can you Schedule a Gitlab Runner?

Body:
You can use gitlab api to activate or disable runners. see the documentation

For example:

PUT /runners/:id

active: false


问:
Span columns with docxTemplate python
I'm having trouble trying to fill in a table row by row using DocxTemplate. I'm  only confused on how the template should look like.

This is my python code:

```<code>from docxtpl import Docxtemplate

doc = DocxTemplate("Template.docx")
context = {}
table_info = [{start: "A", end: "C"}, {start: "B", end: "C"}, {start:"F", end:"L"}, {start:"B", end:"R"}]
context["table_info"] = table_info

doc.render(context)
doc.save("Finish.docx")
</code>```

I want the final result to be in a table like this:

```<code>| start | end |
|  A    | C   |
|  B    | C   |
|  F    | L   |
|  B    | R   |
</code>```

Would anyone be willing to show me how I can accomplish this? I saw the dynamic_table_tpl example but I wasn't able to wrap my head around what I'm trying to do. Thanks in advance!

答:
Adapting the code test from https://github.com/elapouya/python-docx-template/blob/master/tests/dynamic_table.py to your need:

```<code>from docxtpl import DocxTemplate

doc = DocxTemplate('Template.docx')

context = {
    'col_labels' : ['start', 'end'],
    'tbl_contents': [
        {'label': 'black', 'cols': ['A', 'C']},
        {'label': 'black', 'cols': ['B', 'C']},
        {'label': 'black', 'cols': ['F', 'L']},
        {'label': 'black', 'cols': ['B', 'R']},
        ]
}

doc.render(context)
doc.save('Finish.docx')
</code>```

Your build for context is using wrong key names.

Title: Span columns with docxTemplate python

Body:
I'm having trouble trying to fill in a table row by row using DocxTemplate. I'm  only confused on how the template should look like.

This is my python code:

from docxtpl import Docxtemplate

doc = DocxTemplate("Template.docx")
context = {}
table_info = [{start: "A", end: "C"}, {start: "B", end: "C"}, {start:"F", end:"L"}, {start:"B", end:"R"}]
context["table_info"] = table_info

doc.render(context)
doc.save("Finish.docx")

I want the final result to be in a table like this:

| start | end |
|  A    | C   |
|  B    | C   |
|  F    | L   |
|  B    | R   |

Would anyone be willing to show me how I can accomplish this? I saw the dynamic_table_tpl example but I wasn't able to wrap my head around what I'm trying to do. Thanks in advance!

Body:
Adapting the code test from https://github.com/elapouya/python-docx-template/blob/master/tests/dynamic_table.py to your need:

from docxtpl import DocxTemplate

doc = DocxTemplate('Template.docx')

context = {
    'col_labels' : ['start', 'end'],
    'tbl_contents': [
        {'label': 'black', 'cols': ['A', 'C']},
        {'label': 'black', 'cols': ['B', 'C']},
        {'label': 'black', 'cols': ['F', 'L']},
        {'label': 'black', 'cols': ['B', 'R']},
        ]
}

doc.render(context)
doc.save('Finish.docx')

Your build for context is using wrong key names.


问:
How are everyday machines programmed?
How are everyday machines (not so much computers and mobile devices as appliances, digital watches, etc) programmed? What kind of code goes into the programming of a Coca-Cola vending machine? How does my coffee maker accept a pre-programmed time and begin brewing a pot of coffee hours later, when that time arrives?

Do these kinds of machines have operating systems inside of them, or is it something even more basic? Are they written in Assembly, C, or some other language?

And, I would really like to find some resource that lists these operating systems or underlying code systems, possibly even with source code if possible. If anyone knows of such a resource (searching yielded nothing for me), that would be fantastic.

答:
Low-end microcontrollers found in everyday appliances typically do not run an operating system. They are chosen for low cost, and the main factors driving that cost are the number of pins on the chip (from a dozen to a couple hundred) and the amount of memory inside (from a couple kilobytes to a megabyte ROM, from a few bytes to a hundred kilobytes RAM).

As feature creep works its magic, it does happen that a microwave may need to multitask. In this case, the programmer recalls their operating systems course and implements message-passing, task scheduling, asynchronous I/O, etc as necessary!

Of course, for the sake of expedience, simplicity, code size, etc, features tend to be done in a rudimentary way. Often it depends how you analyze the program, to find generalized OS functionality within task-specific code. But it's a long way from a hard-coded task scheduler to an operating system, and when you have only a few kilobytes to work with, an off-the-shelf OS is not the solution.

Take a look at DigiKey, a popular electronic parts selection site, to learn about low-end MCUs. Here is their info on a very cheap MCU with an LCD controller, such as might be found in a coffee machine. It's easy enough to get the programming manual and everything.

Title: How are everyday machines programmed?


问:
Is there a way to make a graphql query once without rendering?
I have a react app that I need to make GraphQL queries to an endpoint in order to get data. The data doesn't change during the lifetime of the app. So I would like to make the query when the component mounts, and store the data.

I've tried making the Query call in the ComponentDidMount method, but it doesn't work, I BELIEVE, because I need to render the results. The truth is, I'm very new to these frameworks and libraries and am not sure how some/most of it works. I want to believe that I'm mistaken and there is some way to store data from a query without needing to render it... but I can't seem to figure it out :(

Can anyone help me out? Point me in a direction, or correct my probably wrong assumptions about the issue I'm facing?

答:
With react-apollo you could do it like this:

```<code>import { withApollo } from 'react-apollo'

class SomeComponent extends Component {
  async componentDidMount() {
    const result = await this.props.client.query({
      query: GRAPHQL_QUERY,
      variables: QUERY_VARIABLES
    })
    // do something with result
  }
}

export default withApollo(SomeComponent)
</code>```

Body:
With react-apollo you could do it like this:

import { withApollo } from 'react-apollo'

class SomeComponent extends Component {
  async componentDidMount() {
    const result = await this.props.client.query({
      query: GRAPHQL_QUERY,
      variables: QUERY_VARIABLES
    })
    // do something with result
  }
}

export default withApollo(SomeComponent)


问:
How to Browser test a Vue.js app mocking API calls?
I have an app that uses Vue.js as Frontend and Spring-boot as Backend.

I want to "unit test" (or integration test, whatever you wanna call it) my views, using browser and selenium, but mocking API calls (ajax requests).

Which tools are recommended to do that?

答:
Selenium testing is called Integration or End-to-End (E2E) testing. Unit testing is not done with Selenium, it is usually done with one of the following tools: Jest, Karma, Jasmine, Mocha, or Chai. (some of these are "expectations libraries", some of these are "test runners", some are both)

Unit testing in Vue

Please check out the Vue Unit Testing guide. The community has strong preferences toward Jest currently, which means most of the tooling you can download for free is aimed toward people using Jest.

E2E testing in Vue

The modern, recommended tools for e2e testing a Vue app are Cypress or Nightwatch. I would start with those. Check out this article to get started.

If you still want to use Selenium, there is literally no difference between testing a normal web app and testing a Vue web app. This is because Selenium operates at the level of abstraction of the Browser, and doesn't care what network requests you make, what backend you use, or what frontend you use.

Which one do you need?

Well, both. This article will help guide you to choose between them, or to do both. There are tradeoffs to each. We recently ditched our e2e tests entirely in favor of writing more unit tests. It's been about 2 years, and it's going great


答:
A little love for the low-tech solution?

```<code>(parse-integer (string #\1))
</code>```

Less efficient but still worth mentioning.

Title: Converting Char to Integer in Common Lisp

Body:
A little love for the low-tech solution?

(parse-integer (string #\1))

Less efficient but still worth mentioning.


问:
Convert Python Opencv Image (numpy array) to PyQt QPixmap image
I am trying to convert python opencv image to QPixmap.

I follow the instruction shows Page Link and my code is attached below

```<code>img = cv2.imread('test.png')[:,:,::1]/255.
imgDown = cv2.pyrDown(img)
imgDown = np.float32(imgDown)
cvRGBImg = cv2.cvtColor(imgDown, cv2.cv.CV_BGR2RGB)
qimg = QtGui.QImage(cvRGBImg.data,cvRGBImg.shape[1], cvRGBImg.shape[0], QtGui.QImage.Format_RGB888)
pixmap01 = QtGui.QPixmap.fromImage(qimg)
self.image01TopTxt = QtGui.QLabel('window',self)
self.imageLable01 = QtGui.QLabel(self)
self.imageLable01.setPixmap(pixmap01)
</code>```

The code has no compile and runtime error but the conversion is wrong and I just get some noise image. I am not sure what the problem is. Could anyone help?

答:
Hate to add to the large number of answers, but as this was the only thing that worked for me I will, in case others run into the same issue.

As mentioned here on GitHub

Wrap the numpy array/ndarry in a np.require(array, np.uint8, 'C') call first, such as:

```<code>arr2 = np.require(arr, np.uint8, 'C')
qImg = QtGui.QImage(arr2, width, height, QtGui.QImage.Format_RGB888)
</code>```

Body:
I am trying to convert python opencv image to QPixmap.

I follow the instruction shows Page Link and my code is attached below

img = cv2.imread('test.png')[:,:,::1]/255.
imgDown = cv2.pyrDown(img)
imgDown = np.float32(imgDown)
cvRGBImg = cv2.cvtColor(imgDown, cv2.cv.CV_BGR2RGB)
qimg = QtGui.QImage(cvRGBImg.data,cvRGBImg.shape[1], cvRGBImg.shape[0], QtGui.QImage.Format_RGB888)
pixmap01 = QtGui.QPixmap.fromImage(qimg)
self.image01TopTxt = QtGui.QLabel('window',self)
self.imageLable01 = QtGui.QLabel(self)
self.imageLable01.setPixmap(pixmap01)

The code has no compile and runtime error but the conversion is wrong and I just get some noise image. I am not sure what the problem is. Could anyone help?

Body:
Hate to add to the large number of answers, but as this was the only thing that worked for me I will, in case others run into the same issue.

As mentioned here on GitHub

Wrap the numpy array/ndarry in a np.require(array, np.uint8, 'C') call first, such as:

arr2 = np.require(arr, np.uint8, 'C')
qImg = QtGui.QImage(arr2, width, height, QtGui.QImage.Format_RGB888)


问:
How to get CircleCI status badge for particular branch
I have a CircleCI badge in my readme file, which is just retrieved via:

```<code><img src="https://circleci.com/gh/ORESoftware/live-mutex.png?circle-token=8ee836581">
</code>```

is there a way to retrieve the badge for just a certain branch? Is there a way to keep it updated? Sometimes it lags - probably because of http caching.

答:
It was only a matter of putting ?branch=dev in the query params like so:

```<code><img src="https://circleci.com/gh/ORESoftware/live-mutex.png?branch=dev&circle-token=8ee836581">
</code>```

Body:
I have a CircleCI badge in my readme file, which is just retrieved via:

is there a way to retrieve the badge for just a certain branch? Is there a way to keep it updated? Sometimes it lags - probably because of http caching.

Body:
It was only a matter of putting ?branch=dev in the query params like so:

<img src="https://circleci.com/gh/ORESoftware/live-mutex.png?branch=dev&circle-token=8ee836581">


问:
Is reading one byte at a time endianness agnostic regardless of value size?
Say I am reading and writing uint32_t values to and from a stream. If I read/write one byte at a time to/from a stream and shift each byte like the below examples, will the results be consistent regardless of machine endianness?

In the examples here the stream is a buffer in memory called p.

static uint32_t s_read_uint32(uint8_t** p)
{
    uint32_t value;
    value  = (*p)[0];
    value |= (((uint32_t)((*p)[1])) << 8);
    value |= (((uint32_t)((*p)[2])) << 16);
    value |= (((uint32_t)((*p)[3])) << 24);
    *p += 4;
    return value;
}

static void s_write_uint32(uint8_t** p, uint32_t value)
{
    (*p)[0] = value & 0xFF;
    (*p)[1] = (value >> 8 ) & 0xFF;
    (*p)[2] = (value >> 16) & 0xFF;
    (*p)[3] = value >> 24;
    *p += 4;
}
```

I don't currently have access to a big-endian machine to test this out, but the idea is if each byte is written one at a time each individual byte can be independently written or read from the stream. Then the CPU can handle endianness by hiding these details behind the shifting operations. Is this true, and if not could anyone please explain why not?

答:
If I read/write one byte at a time to/from a stream and shift each byte like the below examples, will the results be consistent regardless of machine endianness?

Yes.  Your s_write_uint32() function stores the bytes of the input value in order from least significant to most significant, regardless of their order in the native representation of that value.  Your s_read_uint32() correctly reverses this process, regardless of the underlying representation of uint32_t.  These work because

the behavior of the shift operators (<<, >>) is defined in terms of the value of the left operand, not its representation

the & 0xff masks off all bits of the left operand but those of its least-significant byte, regardless of the value's representation (because 0xff has a matching representation), and

the |= operations just put the bytes into the result; the positions are selected, appropriately, by the preceding left shift.  This might be more clear if += were used instead, but the result would be no different.

Note, however, that to some extent, you are reinventing the wheel.  POSIX defines a function pair htonl() and nothl() -- supported also on many non-POSIX systems -- for dealing with byte-order issues in four-byte numbers.  The idea is that when sending, everyone uses htonl() to convert from host byte order (whatever that is) to network byte order (big endian) and sends the resulting four-byte buffer.  On receipt, everyone accepts four bytes into one number, then uses ntohl() to convert from network to host byte order.

Body:
Say I am reading and writing uint32_t values to and from a stream. If I read/write one byte at a time to/from a stream and shift each byte like the below examples, will the results be consistent regardless of machine endianness?

In the examples here the stream is a buffer in memory called p.

static uint32_t s_read_uint32(uint8_t** p)
{
    uint32_t value;
    value  = (*p)[0];
    value |= (((uint32_t)((*p)[1])) << 8);
    value |= (((uint32_t)((*p)[2])) << 16);
    value |= (((uint32_t)((*p)[3])) << 24);
    *p += 4;
    return value;
}

static void s_write_uint32(uint8_t** p, uint32_t value)
{
    (*p)[0] = value & 0xFF;
    (*p)[1] = (value >> 8 ) & 0xFF;
    (*p)[2] = (value >> 16) & 0xFF;
    (*p)[3] = value >> 24;
    *p += 4;
}

I don't currently have access to a big-endian machine to test this out, but the idea is if each byte is written one at a time each individual byte can be independently written or read from the stream. Then the CPU can handle endianness by hiding these details behind the shifting operations. Is this true, and if not could anyone please explain why not?


问:
Generic IDisposable wrapper for stream - alternative to catching all exceptions
So I've just written this implementation for a type that abstracts a file and implements IDisposable over the stream that it contains.  It is intended to be used in any project:

```<code>public void Dispose()
{
  if (_contentStream == null)
    return;
  lock (_contentStreamLocker)
  {
    if (_contentStream == null)
      return;

    try
    {
      _contentStream.Dispose();
    }
    catch (Exception)
    {
      //legitimate? - don't let any exception prevent
      //us from successfully disposing?
    }
    _contentStream = null;
  }
}
</code>```

So I feel dirty, obviously, because:

I'm catching Exception

I'm doing nothing with Exception

But since I can't guarantee the behaviour of the underlying stream (also accounting for custom implementations) - i.e. if it's already disposed or if it's in a state where the implementation decides disposal is impossible - I can't really see what else to do.

Obviously I shouldn't be hiding bad implementations of Stream's Dispose(); but I think there is a half-way-house here.

In particular is the fact that this object doesn't necessarily 'own' the stream, and therefore won't have to be always responsible for Dispose()ing.  It should therefore be tolerant to when the stream has been disposed by somebody else.

Clearly, in most cases this won't be an issue; get a file in a using block perhaps, read it, do something with it and then dispose of it.  But there's those edge-cases; and they bother me!

Initially I wrote it as catch(ObjectDisposedException){ } - but that's only an informal pattern that can't be relied upon either.

What should I do?  Keep it as this, despite the fact that exception gulping is bad karma? Gulp only ObjectDisposedException, even though that's not much better?  Or should I just not have any exception gulping or handling at all?

I can see merits in all cases; just can't figure out which of them wins.

答:
Generally, if you can't figure out which one wins, it's because there's going to be useful information that can't be handled "generically". In this case, I think it preferable to let the caller deal with it, because they'll be in a concrete situation that allows them to better judge.

How is the stream introduced to this class? If you can engineer such that it is passed in, then why not let the caller deal with its disposal and not concern yourself with it. It's always bugged me that StreamReader takes on this responsibility. I wouldn't much care if it didn't.

DO NOT SWALLOW the exception, especially in code intended for external consumption.

Body:
So I've just written this implementation for a type that abstracts a file and implements IDisposable over the stream that it contains.  It is intended to be used in any project:

public void Dispose()
{
  if (_contentStream == null)
    return;
  lock (_contentStreamLocker)
  {
    if (_contentStream == null)
      return;

    try
    {
      _contentStream.Dispose();
    }
    catch (Exception)
    {
      //legitimate? - don't let any exception prevent
      //us from successfully disposing?
    }
    _contentStream = null;
  }
}

So I feel dirty, obviously, because:

I'm catching Exception

I'm doing nothing with Exception

But since I can't guarantee the behaviour of the underlying stream (also accounting for custom implementations) - i.e. if it's already disposed or if it's in a state where the implementation decides disposal is impossible - I can't really see what else to do.

Obviously I shouldn't be hiding bad implementations of Stream's Dispose(); but I think there is a half-way-house here.

In particular is the fact that this object doesn't necessarily 'own' the stream, and therefore won't have to be always responsible for Dispose()ing.  It should therefore be tolerant to when the stream has been disposed by somebody else.

Clearly, in most cases this won't be an issue; get a file in a using block perhaps, read it, do something with it and then dispose of it.  But there's those edge-cases; and they bother me!

Initially I wrote it as catch(ObjectDisposedException){ } - but that's only an informal pattern that can't be relied upon either.

What should I do?  Keep it as this, despite the fact that exception gulping is bad karma? Gulp only ObjectDisposedException, even though that's not much better?  Or should I just not have any exception gulping or handling at all?

I can see merits in all cases; just can't figure out which of them wins.


问:
PHP output is empty
this is my code php5.6

```<code>$lang = array(
  "HTML" => "60%",
  "CSS" => "80%",
  "JS" => "70%",
  "PHP" => "50%",
);

echo "<ul>";

for ($lang=0; $lang < count($lang) ; $lang++) {
  echo "<li>" . $lang[$lang] . "</li>";
}

echo "</ul>";
</code>```

When i run my page it does't show any thing

答:
Use foreach on arrays.</p>

```<code>$langs = array(
  'HTML'=> '60%',
  'CSS' => '80%',
  'JS'  => '70%',
  'PHP' => '50%',
);

echo '<ul>';

foreach ($langs as $lang=>$per) {
  echo "<li>$lang $per</li>";
}

echo '</ul>';
</code>```

Title: PHP output is empty

Body:
this is my code php5.6

$lang = array(
  "HTML" => "60%",
  "CSS" => "80%",
  "JS" => "70%",
  "PHP" => "50%",
);

echo "
";

for ($lang=0; $lang < count($lang) ; $lang++) {
  echo "
" . $lang[$lang] . "
";
}

echo "
";

When i run my page it does't show any thing

Body:
Use foreach on arrays.

$langs = array(
  'HTML'=> '60%',
  'CSS' => '80%',
  'JS'  => '70%',
  'PHP' => '50%',
);

echo '<ul>';

foreach ($langs as $lang=>$per) {
  echo "<li>$lang $per</li>";
}

echo '</ul>';


问:
How to find out the correct encoding when using beautifulsoup?
In python3 and beautifulsoup4 I want to get information from a website, after making the requests. I did so:

```<code>import requests
from bs4 import BeautifulSoup

req = requests.get('https://sisgvarmazenamento.blob.core.windows.net/prd/PublicacaoPortal/Arquivos/201901.htm').text

soup = BeautifulSoup(req,'lxml')

soup.find("h1").text
'\r\n                        CÃ\x82MARA MUNICIPAL DE SÃ\x83O PAULO'
</code>```

I do not know what the encoding is, but it's a site with Brazilian Portuguese, so it should be utf-8 or latin1

Please, is there a way to find out which encoding is correct?

And then do the beautifulsoup read this encoding correctly?

答:
When you use requests, you can use the encoding function, for example:

```<code>req = requests.get('https://sisgvarmazenamento.blob.core.windows.net/prd/PublicacaoPortal/Arquivos/201901.htm')

encoding = req.encoding
text = req.content

decoded_text = text.decode(encoding)
</code>```

Body:
In python3 and beautifulsoup4 I want to get information from a website, after making the requests. I did so:

import requests
from bs4 import BeautifulSoup

req = requests.get('https://sisgvarmazenamento.blob.core.windows.net/prd/PublicacaoPortal/Arquivos/201901.htm').text

soup = BeautifulSoup(req,'lxml')

soup.find("h1").text
'\r\n                        CÃ\x82MARA MUNICIPAL DE SÃ\x83O PAULO'

I do not know what the encoding is, but it's a site with Brazilian Portuguese, so it should be utf-8 or latin1

Please, is there a way to find out which encoding is correct?

And then do the beautifulsoup read this encoding correctly?

Body:
When you use requests, you can use the encoding function, for example:

req = requests.get('https://sisgvarmazenamento.blob.core.windows.net/prd/PublicacaoPortal/Arquivos/201901.htm')

encoding = req.encoding
text = req.content

decoded_text = text.decode(encoding)


问:
How to find the vnet/subnet associated with an Azure Virtual Machine using java sdk?
I am using Java SDK to collect the Azure Virutal Machines. However I am not able to figure out the vnet/subnet associated with the VM. The SDK doesn't provide this info directly and the REST API as well.</p>

答:
I finally figure it out and posting the answer . We need to get it from the Primary IP Configuration associated with the primary network interface. Please let me know if anyone has a better solution.</p>

```<code>NicIPConfiguration ipConfiguration = virtualMachine.getPrimaryNetworkInterface().primaryIPConfiguration();

String vnet = ipConfiguration.networkId();
String subnet = ipConfiguration.subnetName();
</code>```

Body:
I finally figure it out and posting the answer . We need to get it from the Primary IP Configuration associated with the primary network interface. Please let me know if anyone has a better solution.

NicIPConfiguration ipConfiguration = virtualMachine.getPrimaryNetworkInterface().primaryIPConfiguration();

String vnet = ipConfiguration.networkId();
String subnet = ipConfiguration.subnetName();


问:
Swift 3: func largestNumber
I do not have good skills at development so don't laugh at me. But now I make some tests to improve my skills at coding and I have some question. At Apple dev guide I can't find an answer.

So Swift 3 title "Given an integer n, return the largest number that contains exactly n digits"

All I know is it is

```<code>func largestNumber(n: Int) -> Int {
</code>```

Example:
For n = 2, the output should be
largestNumber(n) = 99

Tell me please how to code it.

答:
I think this would work for you</p>

```<code>func largestNumber(digits: Int) -> Int{
    var numStr = "0"

    for i in 0..<digits {
        //since the biggest digit in the decimal system is 9 we append that to our String
        numStr += "9"
    }

    //convert String to Int
    return Int(numStr) ?? 0
}
</code>```

Title: Swift 3: func largestNumber

Body:
I do not have good skills at development so don't laugh at me. But now I make some tests to improve my skills at coding and I have some question. At Apple dev guide I can't find an answer.

So Swift 3 title "Given an integer n, return the largest number that contains exactly n digits"

All I know is it is

func largestNumber(n: Int) -> Int {

Example:
For n = 2, the output should be
largestNumber(n) = 99

Tell me please how to code it.

Body:
I think this would work for you

func largestNumber(digits: Int) -> Int{
    var numStr = "0"

    for i in 0..<digits {
        //since the biggest digit in the decimal system is 9 we append that to our String
        numStr += "9"
    }

    //convert String to Int
    return Int(numStr) ?? 0
}


问:
How to use an external variables file inside a script
Is it possible read variables from a file and sent it to a bash script via Parallel?

Example:

I have a file called data.txt with the following content:

```<code>apple red
banana yellow
grape green
</code>```

Id like to read this file using Parallel and run a bash script using each line as variable.
The result of this script must be:

```<code>Fruit: apple
Color: red

Fruit banana
Color: yellow

Fruit: grape
Color: green
</code>```

答:
Sure:

```<code>parallel -a  data.txt --colsep ' ' ./script
</code>```

Where script is:

```<code>#!/bin/bash
echo -e "Fruit: $1"
echo -e "Colour: $2"
</code>```

You will get the same result with a slightly different syntax, depending on how you like to see things:

```<code>cat data.txt | parallel --colsep ' ' ./script {1} {2}
</code>```

Body:
Is it possible read variables from a file and sent it to a bash script via Parallel?

Example:

I have a file called data.txt with the following content:

apple red
banana yellow
grape green

Id like to read this file using Parallel and run a bash script using each line as variable.
The result of this script must be:

Fruit: apple
Color: red

Fruit banana
Color: yellow

Fruit: grape
Color: green

Body:
Sure:

parallel -a  data.txt --colsep ' ' ./script

Where script is:

#!/bin/bash
echo -e "Fruit: $1"
echo -e "Colour: $2"

You will get the same result with a slightly different syntax, depending on how you like to see things:

cat data.txt | parallel --colsep ' ' ./script {1} {2}


问:
Is there a way to check for markers whos icons intersect / overlap visibly?
I am building a map and want to use the leaflet markercluster plugin to cluster any markers that intersect visibly (the icons overlap each other). I can't seem to figure out a way to check whether the markers icons intersect though.

I've examined the documentation and the Marker objects. The marker object has no "bounds" object and has no function to return the bounds of the icon.

答:
Yes, it's possible.

This is implemented in some Leaflet plugins, like Leaflet.LayerGroup.Collision - the technique involves fetching the computed style of each icon's HTML element to get the actual size in CSS pixels, offset those numbers by the relative pixel position of the marker's LatLng, and using a rtree data structure to speed up the calculation of the overlaps. Do have a look at the complete source for LayerGroup.Collision plugin.

Note that this technique only takes into account the rectangular bounding boxes of the icons; while it would be possible to check for the individual transparent pixels, that would involve more complex data structures and a different technique to fetch the opacity of each pixel.


问:
Count number of times a particular value follows another particular value for each column in a data frame
I would like to create a table or a new data frame that displays, for each row in the original data frame, how many times a specific value precedes another specific value. For example, if I have the following data frame:

```<code>x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "b", "a", "b", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))
</code>```

and I want to know, for each color (Red, Blue, and Green) how many times the sequence "b", "a" occurs (i.e., how many times b precedes a in the sequence).

The correct answer would look something like this:

```<code>     Color ba
1   Red  1
2  Blue  3
3 Green  2
</code>```

答:
here is one solution using stringr

```<code>library(stringr)

count_pair <- function(x, pattern) {
   p <- paste(pattern, collapse = "")
   s <- paste(x, collapse = "")
   str_count(s, pattern = p)
}

z <- apply(x, 2, count_pair, pattern = c("b", "a"))
# Red  Blue Green
# 1     3     2

# if you want the output in form of a data.frame you could run:
df <- as.data.frame(as.table(z))

#    Var1 Freq
# 1   Red    1
# 2  Blue    3
# 3 Green    2
</code>```

Body:
I would like to create a table or a new data frame that displays, for each row in the original data frame, how many times a specific value precedes another specific value. For example, if I have the following data frame:

x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "b", "a", "b", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))

and I want to know, for each color (Red, Blue, and Green) how many times the sequence "b", "a" occurs (i.e., how many times b precedes a in the sequence).

The correct answer would look something like this:

     Color ba
1   Red  1
2  Blue  3
3 Green  2

Body:
here is one solution using stringr

library(stringr)

count_pair <- function(x, pattern) {
   p <- paste(pattern, collapse = "")
   s <- paste(x, collapse = "")
   str_count(s, pattern = p)
}

z <- apply(x, 2, count_pair, pattern = c("b", "a"))
# Red  Blue Green
# 1     3     2

# if you want the output in form of a data.frame you could run:
df <- as.data.frame(as.table(z))

#    Var1 Freq
# 1   Red    1
# 2  Blue    3
# 3 Green    2


问:
UICollectionView Self Sizing Cells with Auto Layout
I'm trying to get self sizing UICollectionViewCells working with Auto Layout, but I can't seem to get the cells to size themselves to the content. I'm having trouble understanding how the cell's size is updated from the contents of what's inside the cell's contentView.

Here's the setup I've tried:

Custom UICollectionViewCell with a UITextView in its contentView.

Scrolling for the UITextView is disabled.

The contentView's horizontal constraint is: "H:|[_textView(320)]", i.e. the UITextView is pinned to the left of the cell with an explicit width of 320.

The contentView's vertical constraint is: "V:|-0-[_textView]", i.e. the UITextView pinned to the top of the cell.

The UITextView has a height constraint set to a constant which the UITextView reports will fit the text.

Here's what it looks like with the cell background set to red, and the UITextView background set to Blue:

I put the project that I've been playing with on GitHub here.

答:
In addition to above answers,

Just make sure you set estimatedItemSize property of UICollectionViewFlowLayout to some size and do not implement sizeForItem:atIndexPath delegate method.

That's it.


问:
Firebase dynamic link doesn't work on iOS
I am making some app and use firebase dynamic link.
When I tested dynamic link on my android phone, It works well.
And in my iOS, it also works, but the page does not change and any parameter does not pass.

When I input deeplink like below picture on safari, it works well.

Is there something else that I missed?
I set Associated Domains on xcode.

I am using iOS 10 and using ionic2(cordova)!

答:
You can do that using SMS app.

Paste your deepLink and send it. So when you click on the link your app will be open.

This answer also applies to the question: Firebase dynamic link not opening the app iOS

Testing dynamic link using SMS app


问:
BBEdit chomp off excessive decimals
Having a very large data set of float values where the precision is not longer needed, what is a regular expression that I can use with BBEdit to allow me to keep a maximum of 5 digits after a period?

Physically, the decimal value always has a character preceeding the period, is always preceeded by a space, but can have a comma or a space after the string.

sample:

```<code> -162.40904700399989, -82.896416924999954
</code>```

答:
You may use

Find:       (\d\.\d{5})\d+

Replace: \1

Details

(\d\.\d{5}) - Group 1 (referred to via \1 from the replacement pattern): a digit, . and then 5 digits (note the first \d has no quantifier, we are not interested if there are more than one, one is enough, before the decimal separator)

\d+ - one or more digits. Note the + quantifier makes more sense than * because we only want to match those numbers that we want to modify, those that already have 5 digits after the decimal separator do not have to be matched.

Title: BBEdit chomp off excessive decimals

Body:
Having a very large data set of float values where the precision is not longer needed, what is a regular expression that I can use with BBEdit to allow me to keep a maximum of 5 digits after a period?

Physically, the decimal value always has a character preceeding the period, is always preceeded by a space, but can have a comma or a space after the string.

sample:

 -162.40904700399989, -82.896416924999954


问:
Get commit hash for a commit in a branch
In a git branch I store the latest commit hash SHA using

latest_sha=$(git log --pretty=oneline | head -1 | cut -d ' ' -f 1)

After a bunch of commits in this branch, how do I get the next commit SHA after the latest_sha.

Say if there are 5 commits made to this branch after the $latest_sha.

I want to always get the SHA of the first commit after the latest_sha.

```<code>b8eead8ba4ff375911af6
c2452680eb7731e4d36ca
da2e113ca4768f5f34730
95b98d42a6e567ed56fc2
716c4f84a855f48bee55c
6a7223a74269f925cfd9e---I need this one
e945bcfabf3fbafc85084---latest_sha
159df375376ded565bec0
d725350982626f46a8b80
56a4b6ca91d93acc8d751
de584608616b1ed99a554
3cfc15339a98bb286d5baa
6ae834bf36c90fbd81854
fa9bdebd0f814f04ee05ba
cc44c4d9ff14314c1255da
5a6145586a8fdcaa2da659
bfea8cfe121d24a0ff1525

</code>```

Thanks!

答:
You could do that with rev-list:

git rev-list --ancestry-path HEAD ^${latest_sha} | tail -n1
```

rev-list lists all reachable commits in reverse chronological order for the given branches/commits. The caret (^) here means "not", which makes Git exclude all reachable commits starting at the given commit.

Concretely that means: Include all commits reachable from HEAD, exclude all commits reachable from ${latest_sha}, and then take the oldest one there using tail.

Edit: Add --ancestry-path to make sure only commits that are in the direct ancestry path between the specified commits are used (as mentioned by @jthill).

Body:
In a git branch I store the latest commit hash SHA using

latest_sha=$(git log --pretty=oneline | head -1 | cut -d ' ' -f 1)

After a bunch of commits in this branch, how do I get the next commit SHA after the latest_sha.

Say if there are 5 commits made to this branch after the $latest_sha.

I want to always get the SHA of the first commit after the latest_sha.

b8eead8ba4ff375911af6
c2452680eb7731e4d36ca
da2e113ca4768f5f34730
95b98d42a6e567ed56fc2
716c4f84a855f48bee55c
6a7223a74269f925cfd9e---I need this one
e945bcfabf3fbafc85084---latest_sha
159df375376ded565bec0
d725350982626f46a8b80
56a4b6ca91d93acc8d751
de584608616b1ed99a554
3cfc15339a98bb286d5baa
6ae834bf36c90fbd81854
fa9bdebd0f814f04ee05ba
cc44c4d9ff14314c1255da
5a6145586a8fdcaa2da659
bfea8cfe121d24a0ff1525

Thanks!

Body:
You could do that with rev-list:

git rev-list --ancestry-path HEAD ^${latest_sha} | tail -n1

rev-list lists all reachable commits in reverse chronological order for the given branches/commits. The caret (^) here means "not", which makes Git exclude all reachable commits starting at the given commit.

Concretely that means: Include all commits reachable from HEAD, exclude all commits reachable from ${latest_sha}, and then take the oldest one there using tail.

Edit: Add --ancestry-path to make sure only commits that are in the direct ancestry path between the specified commits are used (as mentioned by @jthill).


问:
How to subtract a time constant in a LibreOffice/OpenOffice/Excel formula?
In a LibreOffice/OpenOffice spreadsheet, cell A1 contains a time, as does cell B1.

Cell C1 contains the formula =B1-A1, which returns the difference between the times (which gives me the duration of an event).

Instead of C1 being the exact duration, I want it to be the duration minus 1 hour and 45 minutes.  I have tried =B1-A1-1:45, =B1-A1-01:45, and =B1-A1-1.75 but none of these work.

How can this be accomplished?

答:
You can use TIME()

```<code>=B1-A1-TIME(1,45,0)
</code>```

or put the time in quotes:

```<code>=B1-A1-"01:45"
</code>```

Body:
You can use TIME()

=B1-A1-TIME(1,45,0)

or put the time in quotes:

=B1-A1-"01:45"