问:
IDictionary<int, MyClass> Custom Collection
Can anyone look at this and tell me what I'm doing wrong?  I am having issue implementing the GetEnumerator methods, I have figured out a way to have the IDE create all of the methods so I can learn how to override them.  Can anyone help complete the ProductCollection class so I can understand it better.

```<code>using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// Product
/// </summary>
[Serializable]
public class Product
{
    //0 _ItemNumber = null;
    //1 _Title = null;
    //2 _Author = null;
    //3 _ISBN = null;
    //4 _ItemMessage = null;
    //5 _ISBNEAN = null;
    //6 _SystemName = null;
    //7 _ItemCategory = null;
    //8 _AccessService = null;
    //9 _AlternateItem = null;
    //10 _FullTitle = null;
    //11 _SalesAnalysisCode = null;
    //12 _SACSummaryCode = null;
    //13 _OwningOrganization = null;
    //14 _ProductManager = null;
    //15 _ProductFormat = null;
    //16 _DefaultWarehouse = null;
    //17 _ItemStatusCode = null;
    //18 _AccessType = null;
    //19 _SubstitutionReason = null;
    //20 _Saleable = null;
    //21 _OKToBackOrder = null;
    //22 _Taxable = null;
    //23 _ExcludeShipping = null;
    //24 _Commissionable = null;
    //25 _Package = null;
    //26 _Royalty = null;
    //27 _PrintOnDemand = null;
    //28 _AllowDescriptionOverride = null;
    private string[] _Product = new string[29];

    /// <summary>
    /// Advantage Product Object
    /// </summary>
    public Product()
    {
    }

    public string Title
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Author
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ItemNumber
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ISBN
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ItemMessage
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ISBNEAN
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string AccessService
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string SystemName
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ItemCategory
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string AlternateItem
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string FullTitle
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string SalesAnalysisCode
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string SACSummaryCode
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string OwningOrganization
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ProductManager
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ProductFormat
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string DefaultWarehouse
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ItemStatusCode
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string AccessType
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string SubstitutionReason
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Saleable
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string OKToBackOrder
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Taxable
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ExcludeShipping
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Commissionable
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Package
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Royalty
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string PrintOnDemand
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string AllowDescriptionOverride
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string[] ProductArray
    {
        get
        {
            return _Product;
        }
        set
        {
            _Product = value;
        }
    }
}

/// <summary>
///
/// </summary>
public class ProductCollection : IDictionary<int, Product>
{
private Dictionary<int, Product> dictionaryProduct;

public ProductCollection(int numberOfItem)
{
    dictionaryProduct = new Dictionary<int, Product>(numberOfItem);
}

void IDictionary<int, Product>.Add(int productKey, Product productValue)
{
    dictionaryProduct.Add(productKey, productValue);
}

bool IDictionary<int, Product>.ContainsKey(int productKey)
{
    return dictionaryProduct.ContainsKey(productKey);
}

ICollection<int> IDictionary<int, Product>.Keys
{
    get
    {
        return dictionaryProduct.Keys;
    }
}

bool IDictionary<int, Product>.Remove(int productKey)
{
    return (dictionaryProduct.Remove(productKey));
}

bool IDictionary<int, Product>.TryGetValue(int productKey, out Product productValue)
{
    return (dictionaryProduct.TryGetValue(productKey, out productValue));
}

ICollection<Product> IDictionary<int, Product>.Values
{
    get
    {
        return dictionaryProduct.Values;
    }
}

Product IDictionary<int, Product>.this[int productKey]
{
    get
    {
        return dictionaryProduct[productKey];
    }
    set
    {
        dictionaryProduct[productKey] = value;
    }
}

void ICollection<KeyValuePair<int, Product>>.Add(KeyValuePair<int, Product> productItem)
{
    throw new NotImplementedException();
}

void ICollection<KeyValuePair<int, Product>>.Clear()
{
    dictionaryProduct.Clear();
}

bool ICollection<KeyValuePair<int, Product>>.Contains(KeyValuePair<int, Product> productItem)
{
    return (dictionaryProduct.Contains(productItem));
}

void ICollection<KeyValuePair<int, Product>>.CopyTo(KeyValuePair<int, Product>[] productArray, int arrayIndex)
{
    throw new NotImplementedException();
}

int ICollection<KeyValuePair<int, Product>>.Count
{
    get
    {
        return dictionaryProduct.Count;
    }
}

bool ICollection<KeyValuePair<int, Product>>.IsReadOnly
{
    get
    {
        throw new NotImplementedException();
    }
}

bool ICollection<KeyValuePair<int, Product>>.Remove(KeyValuePair<int, Product> productItem)
{
    throw new NotImplementedException();
}

IEnumerator<KeyValuePair<int, Product>> IEnumerable<KeyValuePair<int, Product>>.GetEnumerator()
{
    throw new NotImplementedException();
}

public IEnumerator<KeyValuePair<int, Product>> GetEnumerator()
{
    throw new NotImplementedException();
}

IEnumerator IEnumerable.GetEnumerator()
{
    throw new NotImplementedException();
}
</code>```

}

After more then a week I have a custom dictionary class object for a product that can be binded to a datasource with out casting.  Does anyone else see a problem or a way to make this better?

```<code>using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

[Serializable]
public class Product
{
// 0 _ItemNumber = null;
// 1 _Title = null;
// 2 _Author = null;
// 3 _ItemNumber = null;
// ..etc

private string[] _Product = new string[29];

public Product()
{
}

public string Title
{
    get
    {
        return _Product[1];
    }
    set
    {
        _Product[1] = value;
    }
}

public string Author
{
    get
    {
        return _Product[2];
    }
    set
    {
        _Product[2] = value;
    }
}

public string ISBN
{
    get
    {
        return _Product[3];
    }
    set
    {
        _Product[3] = value;
    }
}

public string ItemNumber
{
    get
    {
        return _Product[4];
    }
    set
    {
        _Product[4] = value;
    }
}

}

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

/// <summary>
///
/// </summary>
public class ProductCollection : DictionaryBase, IEnumerable
{
public ProductCollection this[int productKey]
{
    get
    {
        return ((ProductCollection)(Dictionary[productKey]));
    }
    set
    {
        Dictionary[productKey] = value;
    }
}

public bool Contains(Product objectProduct)
{
    return Dictionary.Contains(objectProduct);
}

public void Add(Product objectProduct)
{
    Dictionary.Add(objectProduct.ItemNumber, objectProduct);
}

public void Remove(int productKey)
{
    Dictionary.Remove(productKey);
}

IEnumerator IEnumerable.GetEnumerator()
{
    foreach (Product productObject in this.Dictionary.Values)
    {
        yield return productObject;
    }
}
}

protected void Page_Load(object sender, EventArgs e)
{
    Product objectProduct = new Product();
    objectProduct.Title = "Hello Title";
    objectProduct.Author = "Hello Author";
    objectProduct.ISBN = "Hello ISBN";
    objectProduct.ItemNumber = "Hello ItemNumber";

    ProductCollection productCollection = new ProductCollection();
    productCollection.Add(objectProduct);

    rpProducts.DataSource = productCollection;
    rpProducts.DataBind();
}

<asp:Repeater ID="rpProducts" runat="server">
        <ItemTemplate>
            <%# DataBinder.Eval(Container.DataItem, "Title") %>
            <br />
            <%# DataBinder.Eval(Container.DataItem, "Author") %>
        </ItemTemplate>
    </asp:Repeater>
</code>```

答:
Try adding this to ProductEnumerator

```<code>public IEnumerator IEnumerable.GetEnumerator()
{
   return (IEnumerator) GetEnumerator();
}
</code>```

I think it's complaining because you haven't fully defined the IEnumerable interface.

Body:
Can anyone look at this and tell me what I'm doing wrong?  I am having issue implementing the GetEnumerator methods, I have figured out a way to have the IDE create all of the methods so I can learn how to override them.  Can anyone help complete the ProductCollection class so I can understand it better.

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

///
/// Product
///
[Serializable]
public class Product
{
    //0 _ItemNumber = null;
    //1 _Title = null;
    //2 _Author = null;
    //3 _ISBN = null;
    //4 _ItemMessage = null;
    //5 _ISBNEAN = null;
    //6 _SystemName = null;
    //7 _ItemCategory = null;
    //8 _AccessService = null;
    //9 _AlternateItem = null;
    //10 _FullTitle = null;
    //11 _SalesAnalysisCode = null;
    //12 _SACSummaryCode = null;
    //13 _OwningOrganization = null;
    //14 _ProductManager = null;
    //15 _ProductFormat = null;
    //16 _DefaultWarehouse = null;
    //17 _ItemStatusCode = null;
    //18 _AccessType = null;
    //19 _SubstitutionReason = null;
    //20 _Saleable = null;
    //21 _OKToBackOrder = null;
    //22 _Taxable = null;
    //23 _ExcludeShipping = null;
    //24 _Commissionable = null;
    //25 _Package = null;
    //26 _Royalty = null;
    //27 _PrintOnDemand = null;
    //28 _AllowDescriptionOverride = null;
    private string[] _Product = new string[29];

    ///
    /// Advantage Product Object
    ///
    public Product()
    {
    }

    public string Title
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Author
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ItemNumber
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ISBN
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ItemMessage
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ISBNEAN
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string AccessService
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string SystemName
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ItemCategory
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string AlternateItem
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string FullTitle
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string SalesAnalysisCode
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string SACSummaryCode
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string OwningOrganization
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ProductManager
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ProductFormat
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string DefaultWarehouse
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ItemStatusCode
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string AccessType
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string SubstitutionReason
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Saleable
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string OKToBackOrder
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Taxable
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string ExcludeShipping
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Commissionable
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Package
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string Royalty
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string PrintOnDemand
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string AllowDescriptionOverride
    {
        get
        {
            return _Product[0];
        }
        set
        {
            _Product[0] = value;
        }
    }

    public string[] ProductArray
    {
        get
        {
            return _Product;
        }
        set
        {
            _Product = value;
        }
    }
}

///
///
///
public class ProductCollection : IDictionary<int, Product>
{
private Dictionary<int, Product> dictionaryProduct;

public ProductCollection(int numberOfItem)
{
    dictionaryProduct = new Dictionary<int, Product>(numberOfItem);
}

void IDictionary<int, Product>.Add(int productKey, Product productValue)
{
    dictionaryProduct.Add(productKey, productValue);
}

bool IDictionary<int, Product>.ContainsKey(int productKey)
{
    return dictionaryProduct.ContainsKey(productKey);
}

ICollection<int> IDictionary<int, Product>.Keys
{
    get
    {
        return dictionaryProduct.Keys;
    }
}

bool IDictionary<int, Product>.Remove(int productKey)
{
    return (dictionaryProduct.Remove(productKey));
}

bool IDictionary<int, Product>.TryGetValue(int productKey, out Product productValue)
{
    return (dictionaryProduct.TryGetValue(productKey, out productValue));
}

ICollection<Product> IDictionary<int, Product>.Values
{
    get
    {
        return dictionaryProduct.Values;
    }
}

Product IDictionary<int, Product>.this[int productKey]
{
    get
    {
        return dictionaryProduct[productKey];
    }
    set
    {
        dictionaryProduct[productKey] = value;
    }
}

void ICollection<KeyValuePair<int, Product>>.Add(KeyValuePair<int, Product> productItem)
{
    throw new NotImplementedException();
}

void ICollection<KeyValuePair<int, Product>>.Clear()
{
    dictionaryProduct.Clear();
}

bool ICollection<KeyValuePair<int, Product>>.Contains(KeyValuePair<int, Product> productItem)
{
    return (dictionaryProduct.Contains(productItem));
}

void ICollection<KeyValuePair<int, Product>>.CopyTo(KeyValuePair<int, Product>[] productArray, int arrayIndex)
{
    throw new NotImplementedException();
}

int ICollection<KeyValuePair<int, Product>>.Count
{
    get
    {
        return dictionaryProduct.Count;
    }
}

bool ICollection<KeyValuePair<int, Product>>.IsReadOnly
{
    get
    {
        throw new NotImplementedException();
    }
}

bool ICollection<KeyValuePair<int, Product>>.Remove(KeyValuePair<int, Product> productItem)
{
    throw new NotImplementedException();
}

IEnumerator<KeyValuePair<int, Product>> IEnumerable<KeyValuePair<int, Product>>.GetEnumerator()
{
    throw new NotImplementedException();
}

public IEnumerator<KeyValuePair<int, Product>> GetEnumerator()
{
    throw new NotImplementedException();
}

IEnumerator IEnumerable.GetEnumerator()
{
    throw new NotImplementedException();
}

}

After more then a week I have a custom dictionary class object for a product that can be binded to a datasource with out casting.  Does anyone else see a problem or a way to make this better?

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

[Serializable]
public class Product
{
// 0 _ItemNumber = null;
// 1 _Title = null;
// 2 _Author = null;
// 3 _ItemNumber = null;
// ..etc

private string[] _Product = new string[29];

public Product()
{
}

public string Title
{
    get
    {
        return _Product[1];
    }
    set
    {
        _Product[1] = value;
    }
}

public string Author
{
    get
    {
        return _Product[2];
    }
    set
    {
        _Product[2] = value;
    }
}

public string ISBN
{
    get
    {
        return _Product[3];
    }
    set
    {
        _Product[3] = value;
    }
}

public string ItemNumber
{
    get
    {
        return _Product[4];
    }
    set
    {
        _Product[4] = value;
    }
}

}

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

///
///
///
public class ProductCollection : DictionaryBase, IEnumerable
{
public ProductCollection this[int productKey]
{
    get
    {
        return ((ProductCollection)(Dictionary[productKey]));
    }
    set
    {
        Dictionary[productKey] = value;
    }
}

public bool Contains(Product objectProduct)
{
    return Dictionary.Contains(objectProduct);
}

public void Add(Product objectProduct)
{
    Dictionary.Add(objectProduct.ItemNumber, objectProduct);
}

public void Remove(int productKey)
{
    Dictionary.Remove(productKey);
}

IEnumerator IEnumerable.GetEnumerator()
{
    foreach (Product productObject in this.Dictionary.Values)
    {
        yield return productObject;
    }
}
}

protected void Page_Load(object sender, EventArgs e)
{
    Product objectProduct = new Product();
    objectProduct.Title = "Hello Title";
    objectProduct.Author = "Hello Author";
    objectProduct.ISBN = "Hello ISBN";
    objectProduct.ItemNumber = "Hello ItemNumber";

    ProductCollection productCollection = new ProductCollection();
    productCollection.Add(objectProduct);

    rpProducts.DataSource = productCollection;
    rpProducts.DataBind();
}

<asp:Repeater ID="rpProducts" runat="server">
        <ItemTemplate>
            <%# DataBinder.Eval(Container.DataItem, "Title") %>

            <%# DataBinder.Eval(Container.DataItem, "Author") %>
        </ItemTemplate>
    </asp:Repeater>

Body:
Try adding this to ProductEnumerator

public IEnumerator IEnumerable.GetEnumerator()
{
   return (IEnumerator) GetEnumerator();
}

I think it's complaining because you haven't fully defined the IEnumerable interface.


来源: stackexchange

问:
How do I make Open CV work on deployed web app
I have an application that I can run locally and have it open my web camera then detect a qr code. It works well when I run the app locally but then I used the app on my web server and it gets a Server Error (500).

The app was made on Django, then for deployment I used digital ocean(ubuntu) and I also use nginx and gunicorn.

html

```<code><li style= "margin: auto; width:auto"><a style="color:white" href="{% url 'attendees:qrscanner' %}" target="_blank"><button style="margin:15px; width:200px" class="btn btn-outline-primary">Check QR Scanner</button></a></li>
</code>```

views.py

```<code>from django.shortcuts import get_object_or_404, render, redirect
from django.utils import timezone
from django.db.models import Sum
from .models import Attendee, ActivityLog

import re, qrcode, cv2, csv, io, os
import numpy as np
import pyzbar.pyzbar as pyzbar

def qrscanner(request):
    cap = cv2.VideoCapture(0)
    font = cv2.FONT_HERSHEY_PLAIN

    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))

    aid = None

    while aid is None:
        _, frame = cap.read()

        decodedObjects = pyzbar.decode(frame)

        for obj in decodedObjects:
            aid = re.findall('/attendees/confirmation/([0-9]+)', str(obj.data))
            try:
                attendee = Attendee.objects.get(pk=str(aid[0]))
                attendee.present = True
                attendee.timestamp = timezone.now()
                attendee.activity.update_or_create(time_log=attendee.timestamp)
                attendee.save()
                context = {
                    'scan': 'QR Successfully Scanned',
                    'attendee': attendee,
                }
            except:
                context = {
                    'noscan': 'QR Scan Unsuccessful'
                }

        cv2.imshow("QR Reader", frame)

        if aid is not None:
            cv2.destroyAllWindows()
            break

        key = cv2.waitKey(1) & 0xFF
        if key == 27:
            context = {
                'noscan': 'No QR Scanned',
            }
            cv2.destroyAllWindows()
            break

    return render(request, 'attendees/qrscanner.html', context)
</code>```

Expected results:
-Like when my app runs locally, I go to my site where I included the app, I click the qr scanner button and "cap = cv2.VideoCapture(0)" opens up a frame using my computers camera to detect a qr.

Actual results:
-locally everything is fine, I click the qr scanner button and "cap = cv2.VideoCapture(0)" opens up a frame using my computers camera to detect a qr. BUT on my website, once I access that part of the application, I get Server Error (500).

Note:
-I had to install via pip some additional files for the online app to even get the app to show some html and I have other apps in the site.
LIBRARIES INSTALLED LOCALLY (pip freeze):

```<code>colorama==0.4.1
dj-database-url==0.5.0
Django==2.2.3
django-qr-code==1.0.0
django-widget-tweaks==1.4.5
docutils==0.15.2
mysqlclient==1.4.2
numpy==1.17.0
opencv-python==4.1.0.25
pathlib==1.0.1
Pillow==6.0.0
python-decouple==3.1
pytz==2019.1
pyzbar==0.1.8
qrcode==6.1
six==1.12.0
sqlparse==0.3.0
</code>```

LIBRARIES INSTALLED in website (pip freeze):

```<code>beautifulsoup4==4.8.0
certifi==2019.9.11
chardet==3.0.4
cycler==0.10.0
demjson==2.2.4
Django==2.2.6
django-authentication==3.2
django-qr==2.0
django-realestate==4.0
django-widget-tweaks==1.4.5
gunicorn==19.9.0
idna==2.8
jtutils==0.0.6
kiwisolver==1.1.0
leven==1.0.4
matplotlib==3.1.1
nose==1.3.7
numpy==1.17.2
opencv-python==4.1.1.26
opencv-python-headless==4.1.1.26
pandas==0.25.1
Pillow==6.2.0
pkg-resources==0.0.0
psycopg2==2.8.3
psycopg2-binary==2.8.3
pyparsing==2.4.2
python-csv==0.0.11
python-dateutil==2.8.0
pytz==2019.2
pyzbar==0.1.8
qrcode==6.1
requests==2.22.0
six==1.12.0
soupsieve==1.9.4
sqlparse==0.3.0
urllib3==1.25.6
xlrd==1.2.0
xmltodict==0.12.0
</code>```

答:
Here is the actual javascript guide for this

Git Source

ContentLicense: CC BY-SA 4.0

Body:
I have an application that I can run locally and have it open my web camera then detect a qr code. It works well when I run the app locally but then I used the app on my web server and it gets a Server Error (500).

The app was made on Django, then for deployment I used digital ocean(ubuntu) and I also use nginx and gunicorn.

html

<button style="margin:15px; width:200px" class="btn btn-outline-primary">Check QR Scanner</button>

views.py

from django.shortcuts import get_object_or_404, render, redirect
from django.utils import timezone
from django.db.models import Sum
from .models import Attendee, ActivityLog

import re, qrcode, cv2, csv, io, os
import numpy as np
import pyzbar.pyzbar as pyzbar

def qrscanner(request):
    cap = cv2.VideoCapture(0)
    font = cv2.FONT_HERSHEY_PLAIN

    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))

    aid = None

    while aid is None:
        _, frame = cap.read()

        decodedObjects = pyzbar.decode(frame)

        for obj in decodedObjects:
            aid = re.findall('/attendees/confirmation/([0-9]+)', str(obj.data))
            try:
                attendee = Attendee.objects.get(pk=str(aid[0]))
                attendee.present = True
                attendee.timestamp = timezone.now()
                attendee.activity.update_or_create(time_log=attendee.timestamp)
                attendee.save()
                context = {
                    'scan': 'QR Successfully Scanned',
                    'attendee': attendee,
                }
            except:
                context = {
                    'noscan': 'QR Scan Unsuccessful'
                }

        cv2.imshow("QR Reader", frame)

        if aid is not None:
            cv2.destroyAllWindows()
            break

        key = cv2.waitKey(1) & 0xFF
        if key == 27:
            context = {
                'noscan': 'No QR Scanned',
            }
            cv2.destroyAllWindows()
            break

    return render(request, 'attendees/qrscanner.html', context)

Expected results:
-Like when my app runs locally, I go to my site where I included the app, I click the qr scanner button and "cap = cv2.VideoCapture(0)" opens up a frame using my computers camera to detect a qr.

Actual results:
-locally everything is fine, I click the qr scanner button and "cap = cv2.VideoCapture(0)" opens up a frame using my computers camera to detect a qr. BUT on my website, once I access that part of the application, I get Server Error (500).

Note:
-I had to install via pip some additional files for the online app to even get the app to show some html and I have other apps in the site.
LIBRARIES INSTALLED LOCALLY (pip freeze):

colorama==0.4.1
dj-database-url==0.5.0
Django==2.2.3
django-qr-code==1.0.0
django-widget-tweaks==1.4.5
docutils==0.15.2
mysqlclient==1.4.2
numpy==1.17.0
opencv-python==4.1.0.25
pathlib==1.0.1
Pillow==6.0.0
python-decouple==3.1
pytz==2019.1
pyzbar==0.1.8
qrcode==6.1
six==1.12.0
sqlparse==0.3.0

LIBRARIES INSTALLED in website (pip freeze):

beautifulsoup4==4.8.0
certifi==2019.9.11
chardet==3.0.4
cycler==0.10.0
demjson==2.2.4
Django==2.2.6
django-authentication==3.2
django-qr==2.0
django-realestate==4.0
django-widget-tweaks==1.4.5
gunicorn==19.9.0
idna==2.8
jtutils==0.0.6
kiwisolver==1.1.0
leven==1.0.4
matplotlib==3.1.1
nose==1.3.7
numpy==1.17.2
opencv-python==4.1.1.26
opencv-python-headless==4.1.1.26
pandas==0.25.1
Pillow==6.2.0
pkg-resources==0.0.0
psycopg2==2.8.3
psycopg2-binary==2.8.3
pyparsing==2.4.2
python-csv==0.0.11
python-dateutil==2.8.0
pytz==2019.2
pyzbar==0.1.8
qrcode==6.1
requests==2.22.0
six==1.12.0
soupsieve==1.9.4
sqlparse==0.3.0
urllib3==1.25.6
xlrd==1.2.0
xmltodict==0.12.0


问:
How to repeat elements in list n times?
How do I repeat each element of a list n times and form a new list? For example:

```<code>x=[1,2,3,4]
n=3
</code>```

Looking for:

```<code>[1,1,1,2,2,2,3,3,3,4,4,4]
</code>```

答:
An inner argument to repeat is what I was looking for:

```<code>repeat([1, 2, 3, 4], inner = 3)
</code>```

Title: How to repeat elements in list n times?

Body:
How do I repeat each element of a list n times and form a new list? For example:

x=[1,2,3,4]
n=3

Looking for:

[1,1,1,2,2,2,3,3,3,4,4,4]

Body:
An inner argument to repeat is what I was looking for:

repeat([1, 2, 3, 4], inner = 3)


问:
How to expand ZIP archive using PowerShell (UTF-8 filenames)
My zip archive has a single file:

Père-Noël.txt
```

The zip expands nicely with Windows File Explorer, 7-Zip or any other tool I've tried. But I cannot figure out how to do it from PowerShell. Obviously I've tried Expand-Archive but it cannot handle the file name and garbles it into PŠre-N”el.txt. Note: The problem isn't specifically with this example, but indeed with any file name which uses characters outside of the ASCII-127 range. Or so it seems.

Any solution which uses PowerShell and which doesn't rely on an external tool - whose presence cannot be guaranteed - will be accepted. Windows 10 is the platform. I cannot do system-level changes and cannot rely on users of the script having any specific global setting on their system. It has to be a solution within the script.

Is there another way, besides Expand-Archive ? Or is there a setting in PowerShell which will magically do the trick?

Steps to reproduce:

On your Windows 10 host:

Create an empty file named Père-Noël.txt.

ZIP the file using Windows Explorer ("Compressed Folders" feature) into an ZIP archive of your choice, say myarchive.zip.

Delete the Père-Noël.txt file.

Now try to unpack the myarchive.zip using PowerShell. This operation should create the file Père-Noël.txt again.

Compressing using PowerShell Compress-Archive cmdlet

True, if the ZIP was originally created using Compress-Archive cmdlet then it actually works as intended when decompressing using Expand-Archive. So you can say that PowerShell is compatible with itself. It is just not compatible with Windows Explorer ZIPs.

答:
You'll likely need to check the encoding [System.Text.Encoding]::GetEncodings() but the below works with your example Père-Noël

```<code>$zipfile = 'C:\test\Père-Noël.zip' #Contains Père-Noël.txt
$outpath = 'C:\test\out'
$enc = [System.Text.Encoding]::GetEncoding(29001) #29001, x-Europa, Europa
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath, $enc)
</code>```

Hope this helps,

Body:
My zip archive has a single file:

Père-Noël.txt

The zip expands nicely with Windows File Explorer, 7-Zip or any other tool I've tried. But I cannot figure out how to do it from PowerShell. Obviously I've tried Expand-Archive but it cannot handle the file name and garbles it into PŠre-N”el.txt. Note: The problem isn't specifically with this example, but indeed with any file name which uses characters outside of the ASCII-127 range. Or so it seems.

Any solution which uses PowerShell and which doesn't rely on an external tool - whose presence cannot be guaranteed - will be accepted. Windows 10 is the platform. I cannot do system-level changes and cannot rely on users of the script having any specific global setting on their system. It has to be a solution within the script.

Is there another way, besides Expand-Archive ? Or is there a setting in PowerShell which will magically do the trick?

Steps to reproduce:

On your Windows 10 host:

Create an empty file named Père-Noël.txt.

ZIP the file using Windows Explorer ("Compressed Folders" feature) into an ZIP archive of your choice, say myarchive.zip.

Delete the Père-Noël.txt file.

Now try to unpack the myarchive.zip using PowerShell. This operation should create the file Père-Noël.txt again.

Compressing using PowerShell Compress-Archive cmdlet

True, if the ZIP was originally created using Compress-Archive cmdlet then it actually works as intended when decompressing using Expand-Archive. So you can say that PowerShell is compatible with itself. It is just not compatible with Windows Explorer ZIPs.

Body:
You'll likely need to check the encoding [System.Text.Encoding]::GetEncodings() but the below works with your example Père-Noël

$zipfile = 'C:\test\Père-Noël.zip' #Contains Père-Noël.txt
$outpath = 'C:\test\out'
$enc = [System.Text.Encoding]::GetEncoding(29001) #29001, x-Europa, Europa
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath, $enc)

Hope this helps,


问:
When do I use if/endif versus If{}?
Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

```<code><?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>
</code>```

Versus:

```<code><?php if($a == 5){ ?>
A is equal to 5
<?php } ?>
</code>```

答: You can use both, but preffered style and currently known style is the standard if(expr).

ContentLicense: CC BY-SA 3.0

Title: When do I use if/endif versus If{}?

Body:
Well the question is self explanatory.

In PHP when do I use the if/endif notation instead of the standard if(something){} notation?

Example:

<?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>

Versus:

<?php if($a == 5){ ?>
A is equal to 5
<?php } ?>


问:
MongoDB aggregation - how to get a percentage value by rate
I'm trying to get information on row base all data collection

my data :

```<code>{
    _id : 1,
    age : 21,
    salary : 2500
},
{
    _id : 2,
    age : 42,
    salary : 4300
},
{
    _id : 3,
    age : 32,
    salary : 3100
},
{
    _id : 4,
    age : 18,
    salary : 7000
},
{
    _id : 5,
    age : 25,
    salary : 5600
},
{
    _id : 6,
    age : 28,
    salary : 5200
}
,
{
    _id : 7,
    age : 38,
    salary : 5000
},
{
    _id : 8,
    age : 28,
    salary : 5200
}
</code>```

I want to divide the values into four options.

First option is 25 percent.

Second option values between 25 and 50 percent.

Third option between 50 and 75 percent and

last option between 75 and 100 percent.

So when I want to pull out an object it will show me the values relative to the other values.

for example :

```<code>{
    _id : 4,
    age : 'less than 25 percent',
    salary : 'more than 75 percent'
}
</code>```

答:
You can do that using $bucketAuto which would by default split all the documents of a collection into no.of buckets specified most likely equally,

Steps :

Use $facet to create array's one for age & one for salary, each array 4 sub documents with all documents spliced equally into 4 buckets(sub-docs). Adds every mapped document into data array.

Unwind age & salary to get objects out along with their specific indexes.

Use $addFields to replacing existing fields age & salary with texts respective to their positions in buckets.

Use $project & $concatArrays to merge two arrays in to single array named data.

unwind data array & $group on _id adding unique texts to age & salary.

age & salary are array of single elements(string) so by using $arrayElemAt getting first element to make age & salary as fields with type string.

Query :

```<code>db.collection.aggregate([
    {
        $facet: {
            "age": [
                {
                    $bucketAuto: {
                        groupBy: "$age",
                        buckets: 4,
                        output: {
                            "data": { $push: { '_id': "$$ROOT._id", age: "$$ROOT.age" } }
                        }
                    }
                }
            ],
            "salary": [
                {
                    $bucketAuto: {
                        groupBy: "$salary",
                        buckets: 4,
                        output: {
                            "data": { $push: { '_id': "$$ROOT._id", salary: "$$ROOT.salary" } }
                        }
                    }
                }
            ]
        }
    }, { $unwind: { path: '$age', includeArrayIndex: "arrayIndexAge" } },
       { $unwind: { path: '$salary', includeArrayIndex: "arrayIndexSalary" } },
    {
        $addFields: {
            'age.data.age': {
                $switch: {
                    branches: [
                        { case: { $eq: ['$arrayIndexAge', 0] }, then: "less than 25 percent" },
                        { case: { $eq: ['$arrayIndexAge', 1] }, then: "between 25 and 50 percent" },
                        { case: { $eq: ['$arrayIndexAge', 2] }, then: "between 50 and 75 percent" },
                        { case: { $eq: ['$arrayIndexAge', 3] }, then: "more than 75 percent" }
                    ]
                }
            },
            'salary.data.salary': {
                $switch: {
                    branches: [
                        { case: { $eq: ['$arrayIndexSalary', 0] }, then: "less than 25 percent" },
                        { case: { $eq: ['$arrayIndexSalary', 1] }, then: "between 25 and 50 percent" },
                        { case: { $eq: ['$arrayIndexSalary', 2] }, then: "between 50 and 75 percent" },
                        { case: { $eq: ['$arrayIndexSalary', 3] }, then: "more than 75 percent" }
                    ]
                }
            }
        }
    }, { $project: { data: { $concatArrays: ['$age.data', '$salary.data'] } } }, { $unwind: '$data' },
    { $group: { _id: '$data._id', age: { $addToSet: '$data.age' }, salary: { $addToSet: '$data.salary' } } },
    { $addFields: { age: { $arrayElemAt: ['$age', 0] }, salary: { $arrayElemAt: ['$salary', 0] } } }])
</code>```

Test : MongoDB-Playground

Body:
I'm trying to get information on row base all data collection

my data :

{
    _id : 1,
    age : 21,
    salary : 2500
},
{
    _id : 2,
    age : 42,
    salary : 4300
},
{
    _id : 3,
    age : 32,
    salary : 3100
},
{
    _id : 4,
    age : 18,
    salary : 7000
},
{
    _id : 5,
    age : 25,
    salary : 5600
},
{
    _id : 6,
    age : 28,
    salary : 5200
}
,
{
    _id : 7,
    age : 38,
    salary : 5000
},
{
    _id : 8,
    age : 28,
    salary : 5200
}

I want to divide the values into four options.

First option is 25 percent.

Second option values between 25 and 50 percent.

Third option between 50 and 75 percent and

last option between 75 and 100 percent.

So when I want to pull out an object it will show me the values relative to the other values.

for example :

{
    _id : 4,
    age : 'less than 25 percent',
    salary : 'more than 75 percent'
}

Body:
You can do that using $bucketAuto which would by default split all the documents of a collection into no.of buckets specified most likely equally,

Steps :

Use $facet to create array's one for age & one for salary, each array 4 sub documents with all documents spliced equally into 4 buckets(sub-docs). Adds every mapped document into data array.

Unwind age & salary to get objects out along with their specific indexes.

Use $addFields to replacing existing fields age & salary with texts respective to their positions in buckets.

Use $project & $concatArrays to merge two arrays in to single array named data.

unwind data array & $group on _id adding unique texts to age & salary.

age & salary are array of single elements(string) so by using $arrayElemAt getting first element to make age & salary as fields with type string.

Query :

db.collection.aggregate([
    {
        $facet: {
            "age": [
                {
                    $bucketAuto: {
                        groupBy: "$age",
                        buckets: 4,
                        output: {
                            "data": { $push: { '_id': "$$ROOT._id", age: "$$ROOT.age" } }
                        }
                    }
                }
            ],
            "salary": [
                {
                    $bucketAuto: {
                        groupBy: "$salary",
                        buckets: 4,
                        output: {
                            "data": { $push: { '_id': "$$ROOT._id", salary: "$$ROOT.salary" } }
                        }
                    }
                }
            ]
        }
    }, { $unwind: { path: '$age', includeArrayIndex: "arrayIndexAge" } },
       { $unwind: { path: '$salary', includeArrayIndex: "arrayIndexSalary" } },
    {
        $addFields: {
            'age.data.age': {
                $switch: {
                    branches: [
                        { case: { $eq: ['$arrayIndexAge', 0] }, then: "less than 25 percent" },
                        { case: { $eq: ['$arrayIndexAge', 1] }, then: "between 25 and 50 percent" },
                        { case: { $eq: ['$arrayIndexAge', 2] }, then: "between 50 and 75 percent" },
                        { case: { $eq: ['$arrayIndexAge', 3] }, then: "more than 75 percent" }
                    ]
                }
            },
            'salary.data.salary': {
                $switch: {
                    branches: [
                        { case: { $eq: ['$arrayIndexSalary', 0] }, then: "less than 25 percent" },
                        { case: { $eq: ['$arrayIndexSalary', 1] }, then: "between 25 and 50 percent" },
                        { case: { $eq: ['$arrayIndexSalary', 2] }, then: "between 50 and 75 percent" },
                        { case: { $eq: ['$arrayIndexSalary', 3] }, then: "more than 75 percent" }
                    ]
                }
            }
        }
    }, { $project: { data: { $concatArrays: ['$age.data', '$salary.data'] } } }, { $unwind: '$data' },
    { $group: { _id: '$data._id', age: { $addToSet: '$data.age' }, salary: { $addToSet: '$data.salary' } } },
    { $addFields: { age: { $arrayElemAt: ['$age', 0] }, salary: { $arrayElemAt: ['$salary', 0] } } }])

Test : MongoDB-Playground


问:
Converting string from MongoDB into int using MongoDB decode
I am having some trouble with the mongodb driver for Go when trying to decode a property in my collection which is of type string to a property in my struct which is of type int.  I have a collection that has a property that is supposed to be of type int that was converted to type string by someone editing a single document.  Since all of the documents have that property as int except that one, I am getting an error "cannot decode string into an integer type".  I figured out a way to do it but it's not something that "should" be done.  I modified the IntDecodeValue func in the default_value_decoders.go in the mongodb driver for Go.  Below is what I added.

```<code>    case bsontype.String:
    s, err := vr.ReadString()
    if err != nil {
        return err
    }
    i32, err := strconv.Atoi(s)
    if err != nil {
        return err
    }
    i64 = int64(i32)
</code>```

I know this will be overwritten when I update the driver but have been beating my head against the wall trying to figure out how to handle such a case.  I know the best solution is to not allow editing of the documents directly but want to account for that case.

答:
You can do this via a custom BSON decoder. An example of this in the documentation is https://pkg.go.dev/go.mongodb.org/mongo-driver/bson/bsoncodec?tab=doc#example-Registry-CustomDecoder. For your specific use case, the following should work:

```<code>func intDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) {

// Same logic as DefaultValueDecoders.IntDecodeValue
// In the switch statement for vr.Type, you can add a case for bsontype.String

}
</code>```

To register this decoder so it's used when performing CRUD operations, you can use the SetRegistry client option:

```<code>decoder := bsoncodec.ValueDecoderFunc(intDecodeValue)
registry := bson.NewRegistryBuilder().RegisterDefaultDecoder(reflect.Int, decoder).Build()

clientOpts := options.Client().SetRegistry(registry)
client, err := mongo.Connect(context.TODO(), clientOpts)
</code>```

Note that because Go differentiates between different integer types (e.g. int8/int16/int32/int64), you'll need to call RegisterDefaultDecoder to register the custom decoder for each integer type that you may see in your structs, similar to what is done in the RegisterDefaultDecoders function in default_value_decoders.go.

Body:
I am having some trouble with the mongodb driver for Go when trying to decode a property in my collection which is of type string to a property in my struct which is of type int.  I have a collection that has a property that is supposed to be of type int that was converted to type string by someone editing a single document.  Since all of the documents have that property as int except that one, I am getting an error "cannot decode string into an integer type".  I figured out a way to do it but it's not something that "should" be done.  I modified the IntDecodeValue func in the default_value_decoders.go in the mongodb driver for Go.  Below is what I added.

    case bsontype.String:
    s, err := vr.ReadString()
    if err != nil {
        return err
    }
    i32, err := strconv.Atoi(s)
    if err != nil {
        return err
    }
    i64 = int64(i32)

I know this will be overwritten when I update the driver but have been beating my head against the wall trying to figure out how to handle such a case.  I know the best solution is to not allow editing of the documents directly but want to account for that case.

Body:
You can do this via a custom BSON decoder. An example of this in the documentation is https://pkg.go.dev/go.mongodb.org/mongo-driver/bson/bsoncodec?tab=doc#example-Registry-CustomDecoder. For your specific use case, the following should work:

func intDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) {

// Same logic as DefaultValueDecoders.IntDecodeValue
// In the switch statement for vr.Type, you can add a case for bsontype.String

}

To register this decoder so it's used when performing CRUD operations, you can use the SetRegistry client option:

decoder := bsoncodec.ValueDecoderFunc(intDecodeValue)
registry := bson.NewRegistryBuilder().RegisterDefaultDecoder(reflect.Int, decoder).Build()

clientOpts := options.Client().SetRegistry(registry)
client, err := mongo.Connect(context.TODO(), clientOpts)

Note that because Go differentiates between different integer types (e.g. int8/int16/int32/int64), you'll need to call RegisterDefaultDecoder to register the custom decoder for each integer type that you may see in your structs, similar to what is done in the RegisterDefaultDecoders function in default_value_decoders.go.


问:
Map an environment variable in Github Actions
I created a GitHub Actions Job with a strategy matrix that creates a set of environment variables.
One of them is machine_architecture which is either 32 or 64.

In most steps I can use it directly i.e. via ${{ machine_architecture }}.
But some steps requires strings like 'i386' vs 'x86_64'. Is there an easy way in github actions to create a map-object that I can use in expressions like:

```<code>map_object = { 32: "i386", 64: 'x86_64' }
...
${{ map_object[machine_architecture] }}
</code>```

If not, what is the idiomatic way in github actions to solve that problem?

PS: I am aware, that I can set environment variables in steps, but the problem is, that these variables are only available for the following steps (i.e. not for usage in "run-on:" tag)

答:
Here is a way to do it with JSON and jq. It creates the step output ${{ steps.vars.outputs.arch }} which you can use in later steps.

```<code>jobs:
  varMap:
    strategy:
      matrix:
        machine_architecture: [32, 64]
    runs-on: ubuntu-latest
    steps:
      - name: Set arch var
        id: vars
        run: |
          echo ::set-output name=arch::\
          $(echo '{ "32": "i386", "64": "x86_64" }' | jq -r 'to_entries[] | select(.key=="${{ matrix.machine_architecture }}") | .value')

      - name: Test arch var
        run: echo "Testing ${{ steps.vars.outputs.arch }}"
</code>```

Body:
I created a GitHub Actions Job with a strategy matrix that creates a set of environment variables.
One of them is machine_architecture which is either 32 or 64.

In most steps I can use it directly i.e. via ${{ machine_architecture }}.
But some steps requires strings like 'i386' vs 'x86_64'. Is there an easy way in github actions to create a map-object that I can use in expressions like:

map_object = { 32: "i386", 64: 'x86_64' }
...
${{ map_object[machine_architecture] }}

If not, what is the idiomatic way in github actions to solve that problem?

PS: I am aware, that I can set environment variables in steps, but the problem is, that these variables are only available for the following steps (i.e. not for usage in "run-on:" tag)

Body:
Here is a way to do it with JSON and jq. It creates the step output ${{ steps.vars.outputs.arch }} which you can use in later steps.

jobs:
  varMap:
    strategy:
      matrix:
        machine_architecture: [32, 64]
    runs-on: ubuntu-latest
    steps:
      - name: Set arch var
        id: vars
        run: |
          echo ::set-output name=arch::\
          $(echo '{ "32": "i386", "64": "x86_64" }' | jq -r 'to_entries[] | select(.key=="${{ matrix.machine_architecture }}") | .value')

      - name: Test arch var
        run: echo "Testing ${{ steps.vars.outputs.arch }}"


问:
historyserver not able to read log after enabling kerberos
I enable the Kerberos on the cluster and it is working fine. But due to some issue mapred user is not able to read and display log over JobHistory server. I check the logs of job history server and it giving access error as:

```<code>org.apache.hadoop.security.AccessControlException: Permission denied:user=mapred, access=READ_EXECUTE, inode="/user/history/done_intermediate/prakul":prakul:hadoop:drwxrwx---
</code>```

as we can see the directory have access to hadoop group and mapred is in hadoop group, even then it is not able to read the logs. Similar error it is giving for /tmp/logs/ folder due to which no log was displayed on resource manager UI.

I verify over all machine that hadoop group contains mapred user on all machine:

```<code>[cloudera]# id mapred uid=491(mapred) gid=489(mapred) groups=489(mapred),496(hadoop)
</code>```

I also kinit the mapred user and try to access manually to these directory, but mapred not able to access even when folder having 770 permission:

```<code>[root@mn0 cloudera]# hdfs dfs -ls /tmp/logs/prakul
ls: Permission denied: user=mapred, access=READ_EXECUTE, inode="/tmp/logs/prakul":prakul:hadoop:drwxrwx---

[root@mn0 cloudera]# hdfs dfs -ls /tmp/logs/
Found 8 items
drwxrwx--- - xyz hadoop 0 2016-06-14 19:19 /tmp/logs/xyz
drwxrwx--- - abc hadoop 0 2016-06-13 06:06 /tmp/logs/abc
drwxrwx--- - prakul hadoop 0 2016-06-10 04:47 /tmp/logs/prakul

[root@mn0 cloudera]# klist
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: mapred/mn0.eastus.cloudapp.azure.com@AD.COM
Valid starting Expires Service principal
06/27/16 01:07:32 06/27/16 11:07:32 krbtgt/AD.COM@AD.COM
renew until 07/04/16 01:07:32
</code>```

If i give 777 permission to the directory then mapred is able to read and show log over UI as well as CLI.

Can any one know whether it is some Cloudera bug or there is some configuration issue due to which mapred not able to access the log even having full permission at group level?

I am using Cloudera 5.7 with Kerberos enabled.

thanks in advance

答:
I have followed below permissions to cloudera /tmp/logs

/tmp/logs
 —————----

Assume user1 is a valid local OS user. The following folder structure comprises of a proper JobHistory functionality:

drwxrwxrwt - hdfs   supergroup 0 2014-09-15 17:01 /tmp

drwxrwxrwt - mapred hadoop     0 2014-09-18 12:02 /tmp/logs

drwxrwx--- - user1  hadoop     0 2014-09-18 12:03 /tmp/logs/user1

drwxrwx--- - user1  hadoop     0 2014-09-18 12:03 /tmp/logs/user1/logs

Here is an example entry for incorrect permissions:

drwxrwx--- - hive supergroup 0 2014-09-18 12:00 /tmp/logs/user1/logs/

Adjust the /tmp/logs/ folders recursively to reflect the ownership and permissions similar to the above:

Example commands to update the customer's permissions in HDFS:

sudo -u hdfs hadoop fs -chown mapred:hadoop /tmp/logs

sudo -u hdfs hadoop fs -chown -R :hadoop /tmp/logs/*

Body:
I enable the Kerberos on the cluster and it is working fine. But due to some issue mapred user is not able to read and display log over JobHistory server. I check the logs of job history server and it giving access error as:

org.apache.hadoop.security.AccessControlException: Permission denied:user=mapred, access=READ_EXECUTE, inode="/user/history/done_intermediate/prakul":prakul:hadoop:drwxrwx---

as we can see the directory have access to hadoop group and mapred is in hadoop group, even then it is not able to read the logs. Similar error it is giving for /tmp/logs/ folder due to which no log was displayed on resource manager UI.

I verify over all machine that hadoop group contains mapred user on all machine:

[cloudera]# id mapred uid=491(mapred) gid=489(mapred) groups=489(mapred),496(hadoop)

I also kinit the mapred user and try to access manually to these directory, but mapred not able to access even when folder having 770 permission:

[root@mn0 cloudera]# hdfs dfs -ls /tmp/logs/prakul
ls: Permission denied: user=mapred, access=READ_EXECUTE, inode="/tmp/logs/prakul":prakul:hadoop:drwxrwx---

[root@mn0 cloudera]# hdfs dfs -ls /tmp/logs/
Found 8 items
drwxrwx--- - xyz hadoop 0 2016-06-14 19:19 /tmp/logs/xyz
drwxrwx--- - abc hadoop 0 2016-06-13 06:06 /tmp/logs/abc
drwxrwx--- - prakul hadoop 0 2016-06-10 04:47 /tmp/logs/prakul

[root@mn0 cloudera]# klist
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: mapred/mn0.eastus.cloudapp.azure.com@AD.COM
Valid starting Expires Service principal
06/27/16 01:07:32 06/27/16 11:07:32 krbtgt/AD.COM@AD.COM
renew until 07/04/16 01:07:32

If i give 777 permission to the directory then mapred is able to read and show log over UI as well as CLI.

Can any one know whether it is some Cloudera bug or there is some configuration issue due to which mapred not able to access the log even having full permission at group level?

I am using Cloudera 5.7 with Kerberos enabled.

thanks in advance


问:
How to proportionally (respecting aspect ratio) scale a rectangle?
I'm trying to simply take a given box of x by y and scale it up, either by setting x and finding y, or vice versa. How would this formula be expressed in Python (for readability's sake). I'm trying to fit this box inside of a larger box so that the inner box always fits within the larger box.

答:
new_y = (float(new_x) / x) * y

or

new_x = (float(new_y) / y) * x


问:
Reduce a number down to a static set of numbers
Okay, so I have a Google Sheet that I need to reduce a number down to a specific set of 4 numbers.  Then count how many times those numbers occur.

For example:

The numbers it breaks down to:  1, 2, 3, 4

Disregard their individual values other than for the purpose of being broken down.

Now take the number 17.

```<code>Count+Add 1, 2, 3, 4, 1, 2, 3 = 7 r1
</code>```

Take number 12

```<code>Count+Add 1, 2, 3, 4, 1 =  r1
</code>```

The remainder is rounded DOWN

So, basically, it breaks down Cell A1 into a count of how many sequences it takes to reach the total of the number in A1, rounddown.

答:
try:

```<code>=ARRAYFORMULA(COUNTA(IFERROR(QUERY(MMULT(TRANSPOSE((
 ROW(INDIRECT("A1:A"&A2*COUNTA(SPLIT(B2, ","))))<=TRANSPOSE(
 ROW(INDIRECT("A1:A"&A2*COUNTA(SPLIT(B2, ","))))))*TRANSPOSE(
 SPLIT(QUERY(B2&IF(ROW(INDIRECT("A1:A"&A2))<>"", ",")
 ,,9^9), ","))), SIGN(TRANSPOSE(
 SPLIT(QUERY(B2&IF(ROW(INDIRECT("A1:A"&A2))<>"", ",")
 ,,9^9), ",")))), "where Col1 <="&A2, 0))))
</code>```

Body:
Okay, so I have a Google Sheet that I need to reduce a number down to a specific set of 4 numbers.  Then count how many times those numbers occur.

For example:

The numbers it breaks down to:  1, 2, 3, 4

Disregard their individual values other than for the purpose of being broken down.

Now take the number 17.

Count+Add 1, 2, 3, 4, 1, 2, 3 = 7 r1

Take number 12

Count+Add 1, 2, 3, 4, 1 =  r1

The remainder is rounded DOWN

So, basically, it breaks down Cell A1 into a count of how many sequences it takes to reach the total of the number in A1, rounddown.

Body:
try:

=ARRAYFORMULA(COUNTA(IFERROR(QUERY(MMULT(TRANSPOSE((
 ROW(INDIRECT("A1:A"&A2*COUNTA(SPLIT(B2, ","))))<=TRANSPOSE(
 ROW(INDIRECT("A1:A"&A2*COUNTA(SPLIT(B2, ","))))))*TRANSPOSE(
 SPLIT(QUERY(B2&IF(ROW(INDIRECT("A1:A"&A2))<>"", ",")
 ,,9^9), ","))), SIGN(TRANSPOSE(
 SPLIT(QUERY(B2&IF(ROW(INDIRECT("A1:A"&A2))<>"", ",")
 ,,9^9), ",")))), "where Col1 <="&A2, 0))))


问:
How to combine multiple arrays (that represent columns of data) into a nested/jagged array (or even a 2D) array
I have a program that I'm writing to extract certain data from various excel spreadsheet.

The process so far is:

for each spreadsheet identified:

-read in the data as a multidimensional array using interop excel (Even though it is slow, it is the best choice due to all of the different file formats I need to read in)

```<code>    Sample: object[,] cellValues = (object[,])range.Value2;
</code>```

-Identify the columns that I actually need and what order I need them in.  This is stored in a jagged array of bytes:

```<code>    byte[][] targetColumns
</code>```

-THe jagged array essentially is (columnIndexFromSpreadsheet, preferredColumnOrder) e.g. if the first column in the spreadsheet should be read in as column 10 it would be (1, 10)

-I sort the jagged array by the preferred column order (that way I can just loop through the array in that order and extract those columns):

```<code>        public static byte[][] SortTargetColumns(byte[][] targetColumns)
        {
            return targetColumns.OrderBy(x => x.Skip(1).First()).ToArray();
        }
</code>```

-I then extract that column by creating an array from that column index of the multidimensional array.  This is the method that is called:

```<code>    public static object[]  ExtractColumn(object[,] dataArray ,byte columnIndex)
    {
        return Enumerable.Range(ArrayIndexStart, dataArray.GetLength(0)).Select(x => dataArray[x, columnIndex]).ToArray();
    }

    Usage:

    array = ExtractColumn(dataArray, (byte) colIndex);
</code>```

Now I am trying to piece these extracted arrays back together to make it readable.  I will need to do some manipulation on some of the columns and then write to a text file after consolidating.  The only problem is that I have no idea how to do this correctly.  I have tried the following methods but continue to get a null reference exception:

```<code>// Get Row Count of dataArray
int rowCount = dataArray.GetLength(0);

// Create List to store extracted arrays
List<object[]> extractedDataList = new List<object[]>();

// Loop through target columns and extract the column as an array
for (byte colIndex = 1; colIndex <= targetColumns.Length + 1; colIndex++)
{
    object[] array = ExtractColumn(dataArray, (byte) colIndex);
    extractedDataList.Add(array);
}

// Create jagged array
object[][] extractedDataArray = new object[rowCount][] ;

for(int i = 0; i < extractedDataArray.GetLength(0); i++)
{
    List<object> row = new List<object>();
    for (int j = 0; j < extractedDataList.Count; j++)
    {
        row.Add(extractedDataList[j][i].ToString());
        //extractedDataArray[i][j] = extractedDataList[j][i].ToString(); <-- null reference
    }
    extractedDataArray[i] = row.ToArray();
}
</code>```

I'm at a loss of what else to try to put these column arrays back in a form that I can easily work with.  Any and all tips/recommendations would be greatly appreciated.

答:
Whenever you get confused like this, break the problem down into small pieces, and use meaningful names.

Let's say you have an array of columns, each of which has one element per row. That might be declared like this:

```<code>object[][] columns;
</code>```

First, let's get the row and column counts:

```<code>var columnCount = columns.Length;
var rowCount = columns[0].Length;
</code>```

Now write a small local function to accept a row and column index and return the right cell. In case not all of your columns have the same number of rows, you can include a boundary check and just return null if a cell isn't there.

```<code>object Getter(int row, int col)
{
    bool outOfBounds = (row >= columns[col].Length);
    return outOfBounds ? null : columns[col][row];
}
</code>```

Now all we have to do is iterate over the rows to create the inner arrays:

```<code>object[][] target = new object[rowCount][]
for (int row = 0; row < rowCount; row++)
{
    target[row] = new object[columnCount];
}
</code>```

And add in the code that uses the getter to populate the cells:

```<code>object[][] target = new object[rowCount][];
for (int row = 0; row < rowCount; row++)
{
    target[row] = new object[columnCount];
    for (int col = 0; col < columnCount; col++)
    {
        var cellValue = Getter(row, col);
        target[row][columnCount] = cellValue;
    }
}
</code>```

All together, it is simple to read:

```<code>var columnCount = columns.Length;
var rowCount = columns[0].Length;

object Getter(int row, int col)
{
    bool outOfBounds = (row >= columns[col].Length);
    return outOfBounds ? null : columns[col][row];
}

object[][] target = new object[rowCount][];

for (int row = 0; row < rowCount; row++)
{
    target[row] = new object[columnCount];
    for (int col = 0; col < columnCount; col++)
    {
        var cellValue = Getter(row, col);
        target[row][columnCount] = cellValue;
    }
}
</code>```

Body:
I have a program that I'm writing to extract certain data from various excel spreadsheet.

The process so far is:

for each spreadsheet identified:

-read in the data as a multidimensional array using interop excel (Even though it is slow, it is the best choice due to all of the different file formats I need to read in)

    Sample: object[,] cellValues = (object[,])range.Value2;

-Identify the columns that I actually need and what order I need them in.  This is stored in a jagged array of bytes:

    byte[][] targetColumns

-THe jagged array essentially is (columnIndexFromSpreadsheet, preferredColumnOrder) e.g. if the first column in the spreadsheet should be read in as column 10 it would be (1, 10)

-I sort the jagged array by the preferred column order (that way I can just loop through the array in that order and extract those columns):

        public static byte[][] SortTargetColumns(byte[][] targetColumns)
        {
            return targetColumns.OrderBy(x => x.Skip(1).First()).ToArray();
        }

-I then extract that column by creating an array from that column index of the multidimensional array.  This is the method that is called:

    public static object[]  ExtractColumn(object[,] dataArray ,byte columnIndex)
    {
        return Enumerable.Range(ArrayIndexStart, dataArray.GetLength(0)).Select(x => dataArray[x, columnIndex]).ToArray();
    }

    Usage:

    array = ExtractColumn(dataArray, (byte) colIndex);

Now I am trying to piece these extracted arrays back together to make it readable.  I will need to do some manipulation on some of the columns and then write to a text file after consolidating.  The only problem is that I have no idea how to do this correctly.  I have tried the following methods but continue to get a null reference exception:

// Get Row Count of dataArray
int rowCount = dataArray.GetLength(0);

// Create List to store extracted arrays
List<object[]> extractedDataList = new List<object[]>();

// Loop through target columns and extract the column as an array
for (byte colIndex = 1; colIndex <= targetColumns.Length + 1; colIndex++)
{
    object[] array = ExtractColumn(dataArray, (byte) colIndex);
    extractedDataList.Add(array);
}

// Create jagged array
object[][] extractedDataArray = new object[rowCount][] ;

for(int i = 0; i < extractedDataArray.GetLength(0); i++)
{
    List<object> row = new List<object>();
    for (int j = 0; j < extractedDataList.Count; j++)
    {
        row.Add(extractedDataList[j][i].ToString());
        //extractedDataArray[i][j] = extractedDataList[j][i].ToString(); <-- null reference
    }
    extractedDataArray[i] = row.ToArray();
}

I'm at a loss of what else to try to put these column arrays back in a form that I can easily work with.  Any and all tips/recommendations would be greatly appreciated.

Body:
Whenever you get confused like this, break the problem down into small pieces, and use meaningful names.

Let's say you have an array of columns, each of which has one element per row. That might be declared like this:

object[][] columns;

First, let's get the row and column counts:

var columnCount = columns.Length;
var rowCount = columns[0].Length;

Now write a small local function to accept a row and column index and return the right cell. In case not all of your columns have the same number of rows, you can include a boundary check and just return null if a cell isn't there.

object Getter(int row, int col)
{
    bool outOfBounds = (row >= columns[col].Length);
    return outOfBounds ? null : columns[col][row];
}

Now all we have to do is iterate over the rows to create the inner arrays:

object[][] target = new object[rowCount][]
for (int row = 0; row < rowCount; row++)
{
    target[row] = new object[columnCount];
}

And add in the code that uses the getter to populate the cells:

object[][] target = new object[rowCount][];
for (int row = 0; row < rowCount; row++)
{
    target[row] = new object[columnCount];
    for (int col = 0; col < columnCount; col++)
    {
        var cellValue = Getter(row, col);
        target[row][columnCount] = cellValue;
    }
}

All together, it is simple to read:

var columnCount = columns.Length;
var rowCount = columns[0].Length;

object Getter(int row, int col)
{
    bool outOfBounds = (row >= columns[col].Length);
    return outOfBounds ? null : columns[col][row];
}

object[][] target = new object[rowCount][];

for (int row = 0; row < rowCount; row++)
{
    target[row] = new object[columnCount];
    for (int col = 0; col < columnCount; col++)
    {
        var cellValue = Getter(row, col);
        target[row][columnCount] = cellValue;
    }
}


问:
How can I set a BIT variable based on a value variable?
I have:

```<code>DECLARE @Authenticated BIT

If @@ROWCOUNT > 0
 begin
   SELECT @Authenticated = 1
 end ELSE
 begin
   SELECT @Authenticated = 0
 end
</code>```

Is there a way I could do this without the BEGIN END and also is setting a BIT datatype a good way to represent True of False?

答:
```<code>DECLARE @Authenticated BIT
SET @Authenticated = @@ROWCOUNT
</code>```

should also work since BIT values are true/1 if not zero.

Body:
I have:

DECLARE @Authenticated BIT

If @@ROWCOUNT > 0
 begin
   SELECT @Authenticated = 1
 end ELSE
 begin
   SELECT @Authenticated = 0
 end

Is there a way I could do this without the BEGIN END and also is setting a BIT datatype a good way to represent True of False?

Body:
DECLARE @Authenticated BIT
SET @Authenticated = @@ROWCOUNT

should also work since BIT values are true/1 if not zero.


问:
Show location marker in new browser window
Actually in the current page I'm deep linking the google maps location on the button,i.e: when I clicked in button it should open new window and show the location marker.

I'm getting co-ordinates from the google maps api, the resultant window url

https://www.google.com/maps/@13.0106708,77.5552532,17z

but I want to show the marker to that particular location like below

https://www.google.com/maps/place/Orion+Mall/@13.0106708,77.5552532,17z/data=!4m8!1m2!3m1!2sOrion+Mall!3m4!1s0x3bae3d4b805e4167:0xa4c255e80b7e5464!8m2!3d13.0110723!4d77.5549934

how to can show the marker in new window

答:
I would suggest having a look at the Google Maps URLs. Google designed Google Maps URLs as universal, cross-platform URL to launch Google Maps and perform searches, get directions and navigation, and display map views and panoramic images.

So, instead of the following URL

https://www.google.com/maps/@13.0106708,77.5552532,17z

use the official Google Maps URLs link

https://www.google.com/maps/search/?api=1&query=13.0106708,77.5552532

It will open Google Maps with marker. In case if you want to show some specific place and you retrieved a place Id from Google Maps API you can add place id in URL as well

https://www.google.com/maps/search/?api=1&query=13.0106708,77.5552532&query_place_id=ChIJZ0FegEs9rjsRZFR-C-hVwqQ

The latter will show Orion Mall place.

I hope this helps!


问:
MySQL FIND_IN_SET search result needed in original sequence
I am using FIND_IN_SET in MySQL as below :

```<code>SELECT
        color, b.id
FROM    cards b
        where FIND_IN_SET(b.color, 'gold,gold,bronze,silver,silver') > 0
GROUP   BY b.id
        ORDER BY RAND()
        limit 5;

</code>```

And I get output as below :

However, I want to get cards in the same sequence as in the parameter string supplied to FIND_IN_SET i.e.

```<code>gold, gold, bronze, silver, silver
</code>```

So the first output row should be of gold color, then another gold, then bronze and so on - in the same sequence without any random search.

I cannot have self join as it's a big table.

答:
You will need to do this using a UNION of 3 queries to find random 'gold', 'silver' and 'bronze' medallists, and then order those results using FIELD:

```<code>SELECT color, id
FROM (
    (
        SELECT color, id
        FROM cards
        WHERE color = 'gold'
        ORDER BY RAND()
        LIMIT 2
    )
    UNION ALL
    (
        SELECT color, id
        FROM cards
        WHERE color = 'bronze'
        ORDER BY RAND()
        LIMIT 1
    )
    UNION ALL
    (
        SELECT color, id
        FROM cards
        WHERE color = 'silver'
        ORDER BY RAND()
        LIMIT 2
    )
) m
ORDER BY FIELD(color, 'gold', 'bronze', 'silver')
</code>```

Demo on SQLFiddle

Here's a way you might implement this as a combination of PHP/MySQL:

```<code>$pack_sql_comma_separated = 'gold,silver,gold,gold,silver,gold';
$colors = explode(',', $pack_sql_comma_separated);
$counts = array_count_values($colors);
$sql = "SELECT color, id FROM (";
$subqueries = [];
foreach ($counts as $color => $count) {
    $subqueries[] = "(
        SELECT color, id
        FROM cards
        WHERE color = '$color'
        ORDER BY RAND()
        LIMIT $count
    )";
}
$sql .= implode(' UNION ALL ', $subqueries) . ') m';
// run SQL query
// ...
// assume all query results read into $rows according to medal colour, something like this
$rows = array('gold' => array(array('id' => 20),
                              array('id' => 5),
                              array('id' => 4),
                              array('id' => 27)
                              ),
              'silver' => array(array('id' => 19),
                                array('id' => 11)
                                )
             );

//display in required order
foreach ($colors as $color) {
    $card = array_shift($rows[$color]);
    echo "$color {$card['id']}\n";
}
</code>```

Demo on 3v4l.org

Body:
I am using FIND_IN_SET in MySQL as below :

SELECT
        color, b.id
FROM    cards b
        where FIND_IN_SET(b.color, 'gold,gold,bronze,silver,silver') > 0
GROUP   BY b.id
        ORDER BY RAND()
        limit 5;

And I get output as below :

However, I want to get cards in the same sequence as in the parameter string supplied to FIND_IN_SET i.e.

gold, gold, bronze, silver, silver

So the first output row should be of gold color, then another gold, then bronze and so on - in the same sequence without any random search.

I cannot have self join as it's a big table.

Body:
You will need to do this using a UNION of 3 queries to find random 'gold', 'silver' and 'bronze' medallists, and then order those results using FIELD:

SELECT color, id
FROM (
    (
        SELECT color, id
        FROM cards
        WHERE color = 'gold'
        ORDER BY RAND()
        LIMIT 2
    )
    UNION ALL
    (
        SELECT color, id
        FROM cards
        WHERE color = 'bronze'
        ORDER BY RAND()
        LIMIT 1
    )
    UNION ALL
    (
        SELECT color, id
        FROM cards
        WHERE color = 'silver'
        ORDER BY RAND()
        LIMIT 2
    )
) m
ORDER BY FIELD(color, 'gold', 'bronze', 'silver')

Demo on SQLFiddle

Here's a way you might implement this as a combination of PHP/MySQL:

$pack_sql_comma_separated = 'gold,silver,gold,gold,silver,gold';
$colors = explode(',', $pack_sql_comma_separated);
$counts = array_count_values($colors);
$sql = "SELECT color, id FROM (";
$subqueries = [];
foreach ($counts as $color => $count) {
    $subqueries[] = "(
        SELECT color, id
        FROM cards
        WHERE color = '$color'
        ORDER BY RAND()
        LIMIT $count
    )";
}
$sql .= implode(' UNION ALL ', $subqueries) . ') m';
// run SQL query
// ...
// assume all query results read into $rows according to medal colour, something like this
$rows = array('gold' => array(array('id' => 20),
                              array('id' => 5),
                              array('id' => 4),
                              array('id' => 27)
                              ),
              'silver' => array(array('id' => 19),
                                array('id' => 11)
                                )
             );

//display in required order
foreach ($colors as $color) {
    $card = array_shift($rows[$color]);
    echo "$color {$card['id']}\n";
}

Demo on 3v4l.org


答:
When you call print(layer) its printing a representation of that object which is an array of chars/strings.

To print the individual strings consecutively in lines you could use this code:

```<code>for layer in self.map: #iterate over the layers
    for item in layer:  #iterate over the items in the layer
        print(item, end='') # the end='' prevents a line break
    print('') #make a line break
</code>```

Title: Printing just the elements in a 2D list

Body:
I am making a text based game and the map is a 2D list.  The way i have been doing until now is like this:

self.map = [[" " for i in range(34)]
                 for i in range(40)]  # initialize the 2d array
    for layer in self.map: #print the array
        print(layer)

However, this prints the commas and quote marks as well. Is there any way to print the array with just the elements in the list and the printed list should be in the same format as the text printed by the code above above.

EDIT
This is how i would like to print it, but without the speech marks and commas:

[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

Body:
When you call print(layer) its printing a representation of that object which is an array of chars/strings.

To print the individual strings consecutively in lines you could use this code:

for layer in self.map: #iterate over the layers
    for item in layer:  #iterate over the items in the layer
        print(item, end='') # the end='' prevents a line break
    print('') #make a line break


问:
Bash: Spurious "command not found" messages (I think)
I am trying to write a simple utility function in Bash, which will perform an "action" in the given directory.  So I am basically abstracting the "go to a directory, do something, and come back" pattern.

```<code>inDir() {
    if [$# -le 1]; then
        return;
    else
        local dir="$1";
        local action="$2";
        local cwd=`pwd`;

        if [ -d "$dir" ]; then
            cd "$dir";
            $action;
            cd "$cwd";
        else
            return;
        fi
    fi
}
</code>```

Unfortunately, I get what I think is a spurious error when I run this, and I'm not sure where it is coming from.  For example:

```<code>$ inDir "/tmp" "touch hi"
</code>```

correctly creates the file /tmp/hi, but also gives the error:

```<code>[2: command not found
</code>```

I'm not sure if this matters to reading the error, but my prompt starts off with a "[".

Any help?

答:
@NeilButterworth answer is correct.

bash tries to solve the above common error and introduces built-in numeric compare structure (()).
For example:

```<code>if (($# < 1)); then
fi
</code>```

The advanteges over [] structure is that it used regular compare operators (e.g. <, >, ==) and doesn't requires space as [] does.

For string comparison there's similar structure [[]]

Body:
I am trying to write a simple utility function in Bash, which will perform an "action" in the given directory.  So I am basically abstracting the "go to a directory, do something, and come back" pattern.

inDir() {
    if [$# -le 1]; then
        return;
    else
        local dir="$1";
        local action="$2";
        local cwd=`pwd`;

        if [ -d "$dir" ]; then
            cd "$dir";
            $action;
            cd "$cwd";
        else
            return;
        fi
    fi
}

Unfortunately, I get what I think is a spurious error when I run this, and I'm not sure where it is coming from.  For example:

$ inDir "/tmp" "touch hi"

correctly creates the file /tmp/hi, but also gives the error:

[2: command not found

I'm not sure if this matters to reading the error, but my prompt starts off with a "[".

Any help?

Body:
@NeilButterworth answer is correct.

bash tries to solve the above common error and introduces built-in numeric compare structure (()).
For example:

if (($# < 1)); then
fi

The advanteges over [] structure is that it used regular compare operators (e.g. <, >, ==) and doesn't requires space as [] does.

For string comparison there's similar structure [[]]