text:
Q: How to check for duplicate entries in a gridview and prevent them I am relatively new to programming and I am having trouble figuring out how to detect and prevent a user from entering in duplicate values into a gridview I have containing multiple controls.  Currently I am using a foreach loop to loop through the controls that contain the values that cannot be duplicates and it works for the most part, however when I edit the first record in a table and try to "update" the record, even if I haven't changed any values, I receive a null reference exception and I don't know why.  I have attached any pertinent code below and would appreciate any and all help to come to a solution.
Please excuse the long post, I am trying to be as thorough as possible without adding irrelevant information.
To start I have a grid view with a series of controls in it allowing a user to enter information into our database. The gridview and the relevant controls can be seen below.
<asp:GridView ID="GridView2" runat="server"
        EmptyDataText="No Miscellaneous" AutoGenerateColumns="False"
        ShowHeaderWhenEmpty="True" DataKeyNames="RecID"
        ShowFooter="True" DataSourceID="SqlDataSource7" Width="95%"
        OnRowDataBound="OnRowDataBound" >

    <EmptyDataTemplate>
        <asp:DropDownList ID="ddlMiscEquipmentNew" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="RecID"
            DataTextField="EquipmentPart" AppendDataBoundItems="True" AutoPostBack="True" Width="220px" Height="20px" style="margin-left: 70px;" >
            <asp:ListItem Value="0">---SELECT---</asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="ddlMiscNew" runat="server" DataSourceID="SqlDataSourceMisc" DataValueField="RecID" DataTextField="Description"
            AppendDataBoundItems="true" Width="220px" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="ddlMiscNew_SelectedIndexChanged"
            OnDataBound="ddlMiscNew_DataBinding">
            <asp:ListItem Value="0">---SELECT---</asp:ListItem>
        </asp:DropDownList>
        <asp:TextBox ID="txtMiscQuantityNew" runat="server" Width="95px" Style="margin-left: 68px;" AutoPostBack="True" OnTextChanged="txtMiscQuantityNew_TextChanged" />
        <asp:TextBox ID="txtMiscCostNew" runat="server" Width="95px" Text="0" ReadOnly="True" />
        <asp:TextBox ID="txtMiscRequestedNew" runat="server" Width="95px" Text="0" ReadOnly="True" />
        <asp:TextBox ID="txtMiscTaxNew" runat="server" Width="95px" Text="0" />
        <asp:Button ID="InsertDetail" runat="server" CommandName="InsertDetail" Height="25px" Text="Add Detail" Width="85px" UseSubmitBehavior="True" />
    </EmptyDataTemplate>

    <AlternatingRowStyle BackColor="#CCCCCC" />
        <Columns>
            <asp:CommandField ShowEditButton="True" FooterText="Add -->" ShowDeleteButton="true" HeaderStyle-Width="70px" />
            <asp:BoundField DataField="RecID" HeaderText="RecID" SortExpression="RecID" ReadOnly="True" Visible="False" />

            <asp:TemplateField HeaderText="Miscellaneous" ItemStyle-HorizontalAlign="center">
                <ItemTemplate>
                    <asp:Label ID="lblMiscEquipmentAdd" Text='<%# Bind("EquipmentType") %>' runat="server" Width="220px" />
                    <asp:Label ID="lblMiscDescriptionAdd" Text='<%# Bind("MiscDescription") %>' runat="server" Width="220px" />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList ID="ddlMiscEquipmentEdit" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="RecID" DataTextField="EquipmentPart" SelectedValue='<%# Eval("EquipmentID") %>'
                        AppendDataBoundItems="True" AutoPostBack="True" Width="220px" Height="20px">
                        <asp:ListItem Value="0">---SELECT---</asp:ListItem>
                    </asp:DropDownList>
                    <asp:DropDownList ID="ddlMiscEdit" runat="server" DataSourceID="SqlDataSourceMisc" DataValueField="RecID" DataTextField="Description" SelectedValue='<%# Eval("MiscType") %>' AppendDataBoundItems="True" Width="220px" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="ddlMiscEdit_SelectedIndexChanged">
                        <asp:ListItem Value="0">---SELECT---</asp:ListItem>
                    </asp:DropDownList>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="ddlMiscEquipmentInsert" runat="server" DataSourceID="SqlDataSourcePartEquipment" DataValueField="RecID" DataTextField="EquipmentPart"
                        AppendDataBoundItems="True" Width="220px" Height="20px" style="margin-left: 29px;">
                        <asp:ListItem Value="0">---SELECT---</asp:ListItem>
                    </asp:DropDownList>
                    <asp:DropDownList ID="ddlMiscInsert" runat="server" DataSourceID="SqlDataSourceMisc" DataValueField="RecID" DataTextField="Description" AppendDataBoundItems="True" Width="220px" Height="20px" AutoPostBack="True" OnSelectedIndexChanged="ddlMiscInsert_SelectedIndexChanged">
                        <asp:ListItem Value="0">---SELECT---</asp:ListItem>
                    </asp:DropDownList>
                </FooterTemplate>
            </asp:TemplateField>

There are more controls in the gridview but these are where the problem lies.  As you can see there are a number of drop down lists and textboxes, the controls in question are the drop down list "ddlMiscEdit" in the edit item template and the label "lblMiscDescriptionAdd". When the user makes a selection in the aforementioned ddl and proceeds to hit the insert detail button at the end of each row it adds the values to the gridview, and in turn they are added to my database through a row command event. This works as intended, the problem I run into is when a user trys to edit the first row of the gridview and changes the value for ddlMiscEdit, it triggers a null reference exception for the label lblMiscDescriptionAdd.
In order to detect duplicates I have a For Each loop in the selectedIndexChanged event for the ddlMiscEdit drop down as shown below.
 For Each row In GridView2.Rows
        Dim miscdescription As Label = (CType(row.FindControl("lblMiscDescriptionAdd"), Label))
        If miscdescription.Text = ddlMiscEdit.SelectedItem.Text Then
            lblErrorMisc.Text = "Miscellaneous items can only be claimed once"
            Return
        Else
            lblErrorMisc.Text = ""
            Return
        End If
    Next

I am thinking this exception has to do with the fact that when the user clicks edit it activates the drop down list and hides the label, thus when it comes to the loop "lblMiscDescriptionAdd" doesn't exist in that specific context.
I have also tried putting the foreach loop in the row command event for the gridview in the "Update" commandName section, which leads to the same issue but in a different place.  When this loop is in the Update section mentioned above, instead of receiving this exception on the first record of the gridview I receive it in the second/third/fourth record, basically everything except the first record.
I use that same foreach loop in the InsertDetail command and it works as intended preventing duplicate values from being entered into the gridview, the exception only appears when I am trying to edit a given row depending on where I put the loop.
I apologize for the long post but I don't really know how to simplify my issue beyond what I have done here.  I am pretty new to programming so I don't know if I could go about doing this in a better/more efficient manner, but any help/critiques would be greatly appreciated as I am at a loss as to how to fix this problem.  Thank you in advance for any effort on your part for helping me solve this.

A: To make a long story short?
Don't try and process the GV.What happens if other users are adding data. You may well not have re-loaded the grid with updated data.
In your save code for the one record, simple hit/pull/query the main database and check for the record. That way you not messing around all day trying to process and pull values out of the GV.
Always try to think in terms of data management, not trying to use the actual GV as some kind of database - it only for display, and selecting the data to edit, but to check for duplicates, then simple query the database for that information and check if such records already exist.
For example, I have a simple GV with some hotels. (that working example you can try here: http://www.kallal.ca/Website11/WebForm2 ).
So, I have a add button to allow adding of a new reocrd. And I also have a "save" button. It would be in that save button that I simple add code to check say if the hotel name already exists in the database, and not allow that addition.
And what happens with edits? If a user edits existing, and again changes a name to some existing value, then again you have to deal with code to test/check that case.
So, be it adding, or editing, you need to check for that duplicate.
The code thus becomes rather simple. My save button code thus with code to check for the hotel already existing could/would look/work like this:
Protected Sub cmdSave_ServerClick(sender As Object, e As EventArgs)

    ' check for dupliate hotel name when saving or adding new reocrd.
    Dim intPK As Integer = ViewState("PK")

    Dim strSQL As String =
        "SELECT HotelName FROM tblHotelsA
        WHERE HotelName = @HotelName AND ID <> @ID"

    Dim cmdSQL As New SqlCommand(strSQL)
    cmdSQL.Parameters.Add("@HotelName", SqlDbType.NVarChar).Value = txtHotel.Text
    cmdSQL.Parameters.Add("@ID", SqlDbType.NVarChar).Value = intPK
    Dim rstDataCheck As DataTable = MyrstP(cmdSQL)
    If rstDataCheck.Rows.Count > 0 Then
        ' we have a duplicate hotel, don't allow adding!
        ' code here to inform user that this is a duplicate
        ' hotel and you can't add it.
        Me.MyCustomMessage.InnerText = "Can't add this hotel - duplicate"
        Exit Sub

    End If

    ' code here to save the edit back to database
    strSQL = "SELECT * FROM tblHotelsA WHERE ID = " & intPK

    Using conn = New SqlConnection(My.Settings.TEST4)
        Using cmdSQL2 = New SqlCommand(strSQL, conn)
            conn.Open()
            Dim da As New SqlDataAdapter(cmdSQL2)
            Dim daU As New SqlCommandBuilder(da)

            Dim rstData As New DataTable
            rstData.Load(cmdSQL2.ExecuteReader)

            With rstData.Rows(0)

                .Item("HotelName") = txtHotel.Text
                .Item("FirstName") = tFN.Text
                .Item("LastName") = tLN.Text
                .Item("City") = tCity.Text
                .Item("Province") = tProvince.Text
                .Item("Description") = txtNotes.Text
                .Item("Active") = chkActive.Checked
                .Item("Balcony") = chkBalcony.Checked
                .Item("Smoking") = chkSmoking.Checked
            End With

            da.Update(rstData)

        End Using
    End Using

    LoadGrid()   ' refrsh grid to show any new edits

    ShowGrid(True)  ' hide edit area, show grid

End Sub

So, in action, then the above will look like this.
We will edit the record and try to create a duplicate.


text:
Q: Switch pip from /usr/local/bin/pip to /usr/bin/pip I m forcefully started pip from /usr/local/bin/pip by executing sudo python3 -m pip install -U pip command.
Now I want to use pip from /usr/bin/pip
to achieve this, I have rename the pip as /usr/local/bin/pip_backup
now in I ask, which pip or which pip -a it shows /usr/bin/pip only.
But i can not download or install any package using pip. It says:
[root@localhost file_name]# pip install snips-nlu

-bash: /usr/local/bin/pip: No such file or directory
some relevant

[root@localhost bot_v4.0]# which python -a /usr/bin/python

[root@localhost bot_v4.0]# which pip -a /usr/bin/pip
[root@localhost bot_v4.0]#

[root@localhost bot_v4.0]# ll /usr/bin/pip*
-rwxr-xr-x. 1 root root 407 May 5 2018 /usr/bin/pip
lrwxrwxrwx. 1 root root 9 May 5 2018 /usr/bin/pip-2 -> ./pip-2.7
-rwxr-xr-x. 1 root root 407 May 5 2018 /usr/bin/pip2
lrwxrwxrwx. 1 root root 8 May 5 2018 /usr/bin/pip-2.7 -> ./pip2.7
-rwxr-xr-x. 1 root root 407 May 5 2018 /usr/bin/pip2.7
lrwxrwxrwx. 1 root root 9 May 5 2018 /usr/bin/pip-3 -> ./pip-3.6
lrwxrwxrwx. 1 root root 8 May 5 2018 /usr/bin/pip-3.6 -> ./pip3.6
-rwxr-xr-x. 1 root root 16184 Oct 18 15:38 /usr/bin/pipewire

[root@localhost bot_v4.0]# ll /usr/local/bin/pip*
-rwxr-xr-x. 1 root root 223 Apr 4 10:25 /usr/local/bin/pip2
-rwxr-xr-x. 1 root root 223 Apr 4 10:25 /usr/local/bin/pip2.7
-rwxr-xr-x. 1 root root 216 Apr 3 17:05 /usr/local/bin/pip3
-rwxr-xr-x. 1 root root 216 Apr 3 17:05 /usr/local/bin/pip3.6
-rwxr-xr-x. 1 root root 223 Apr 4 10:25 /usr/local/bin/pip_bak

redpajama_set_name: RedPajamaStackExchange


text:
Q: Optimizing excel arrays I have a very large data set (600,000 rows) of data structured in the following format:
1) There are around 60 products. One is a Total US number, while the others are for Manufacturers and are labled as KMFs. There are also some labeled as PCKGs(but aren't relevant for this question)
2) Each product is located in 60 different markets
3) Each market has 20 different locations
4) I have 12 metrics for which I need to calculate data in the following manner: Total US number - sum(KMFs) for each metric
I have written vba code for this but it is taking too long to run(around 20 minutes) I need to run similar code on at least 20 worksheets. I have tried various methods such as setting screenUpdating etc. to false. Here is my code. I am new to vba coding so I may have missed obvious things. Please let me know anything is unclear. Please help!
Sub beforeRunningCode()
    Application.ScreenUpdating = False
    Application.DisplayStatusBar = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    ActiveSheet.DisplayPageBreaks = False
End Sub
Sub returnToOriginal()
    Application.ScreenUpdating = screenUpdateState
    Application.DisplayStatusBar = statusBarState
    Application.Calculation = calcState
    Application.EnableEvents = eventsState
    ActiveSheet.DisplayPageBreaks = displayPageBreaksState
End Sub
Function LastRowFunc(Sheet) As Long
    LastRowFunc = ActiveWorkbook.Worksheets(Sheet).Range("A2", Worksheets(Sheet).Range("A2").End(xlDown)).Rows.Count
End Function
Function LastColFunc(Sheet) As Long
    With ActiveSheet
        LastColFunc = ActiveWorkbook.Sheets(Sheet).Cells(1, .Columns.Count).End(xlToLeft).Column
    End With
End Function
Sub AOCalculate()
    Call beforeRunningCode 'Optimize Excel
    Dim LastRow As Long
    Dim LastCol As Long
    Dim Period As String
    Dim Sheet As String
    Dim Arr(1 To 16)
    Dim Count As Integer
    Sheet = "Energy_LS_Bottler"
    Period = "2016 WAVE 1 - 3 W/E 05/07"
    LastRow = LastRowFunc(Sheet) 'Calculate last row for which data exists
    LastCol = LastColFunc(Sheet) 'Calculate last column for which data exists
    For Each Location In ActiveWorkbook.Sheets("Locations").Range("D7:D28").Value
        For Each Market In ActiveWorkbook.Sheets("Markets").Range("A5:A92").Value
            Count = Count + 1
            Arr(1) = Market
            Arr(2) = "AO"
            Arr(3) = Location
            Arr(4) = Period
            With ActiveWorkbook.Sheets(Sheet) 'Filtering for KMF
                .AutoFilterMode = False
                .Range(Cells(1, 1), Cells(LastRow, LastCol)).AutoFilter
                .Range(Cells(1, 1), Cells(LastRow, LastCol)).AutoFilter field:=17, Criteria1:="=KMF"
                .Range(Cells(1, 1), Cells(LastRow, LastCol)).AutoFilter field:=1, Criteria1:=Market
                .Range(Cells(1, 1), Cells(LastRow, LastCol)).AutoFilter field:=3, Criteria1:=Location
            End With
            For k = 5 To 16
                    Arr(k) = Application.WorksheetFunction.Sum(ActiveWorkbook.Sheets(Sheet).Range(Cells(1, k), Cells(LastRow, k)).SpecialCells(xlCellTypeVisible))
            Next k
            With ActiveWorkbook.Sheets(Sheet) ' filtering for Total US
                .AutoFilterMode = False
                .Range(Cells(1, 1), Cells(LastRow, LastCol)).AutoFilter
                .Range(Cells(1, 1), Cells(LastRow, LastCol)).AutoFilter field:=17, Criteria1:="=Total US"
                .Range(Cells(1, 1), Cells(LastRow, LastCol)).AutoFilter field:=1, Criteria1:=Market
                .Range(Cells(1, 1), Cells(LastRow, LastCol)).AutoFilter field:=3, Criteria1:=Location
            End With
            For k = 5 To 16
                Arr(k) = -Arr(k) + Application.WorksheetFunction.Sum(ActiveWorkbook.Sheets(Sheet).Range(Cells(1, k), Cells(LastRow, k)).SpecialCells(xlCellTypeVisible))
            Next k
            For j = 1 To 16
                ActiveWorkbook.Sheets(Sheet).Cells(LastRow + Count, j).Value = Arr(j)
            Next j
            Erase Arr
        Next
    Next
    ActiveWorkbook.Sheets(Sheet).AutoFilterMode = False
    Call returnToOriginal

End Sub

[Edit]: Here is a link to a sample data set https://drive.google.com/file/d/0B3MkGa57h6g_WGl2WWlWekd4NU0/view?usp=sharing

A: I think that this will work (though I haven't had a chance to test it), and should be a lot faster:
Sub AOCalculate()
    Call beforeRunningCode 'Optimize Excel
    Dim LastRow As Long
    Dim LastCol As Long
    Dim Period As String
    Dim Sheet As String
    Dim Arr()   '1 To 2000, 1 To 16)
    Dim Count As Integer
    Sheet = "Energy_LS_Bottler"
    Period = "2016 WAVE 1 - 3 W/E 05/07"
    LastRow = LastRowFunc(Sheet) 'Calculate last row for which data exists
    LastCol = LastColFunc(Sheet) 'Calculate last column for which data exists

    'copy all of the relevant cells to local arrays for speed
    Dim Locations(), Markets(), data()
    Markets = ActiveWorkbook.Sheets("Markets").Range("A5:A92").Value
    Locations = ActiveWorkbook.Sheets("Locations").Range("D7:D28").Value
    '(pretty sure the following line needs to localize the Cells() to .Cells())
    data = ActiveWorkbook.Sheets(Sheet).Range(Cells(1, 1), Cells(LastRow, LastCol)).Value    '**'

    ReDim Arr(1 To UBound(Markets, 1) * UBound(Locations, 1), 16)

    'make an index of pointers into our accumulation array
    Dim counts As New Collection
    Dim i As Long, l As Long, m As Long
    For l = 1 To UBound(Locations, 1)
        Location = Locations(l, 1)      '**'
        For m = 1 To UBound(Markets, 1)
            Market = Markets(m, 1)      '**'
            i = i + 1
            counts.Add i, CStr(Location) & "~" & CStr(Market)
            'counts.Add NewAccumArray(Location, Market, Period), CStr(Location) & "~" & CStr(Market)
            Arr(i, 1) = Market
            Arr(i, 2) = "AO"
            Arr(i, 3) = Location
            Arr(i, 4) = Period
        Next
    Next

    ' go through each row and add it to the appropiate count in the array
    Dim r As Long
    Dim key As String, idx As Long
    For r = 1 To UBound(data, 1)

        key = CStr(data(r, 3)) & "~" & CStr(data(r, 1))
        If data(r, 17) = "KMF" Then
            idx = counts(key)
            For k = 5 To 16
                    Arr(idx, k) = Arr(idx, k) - data(r, k)
            Next k
        Else
            If data(r, 17) = "Total US" Then
            idx = counts(key)
            For k = 5 To 16
                    Arr(idx, k) = Arr(idx, k) + data(r, k)
            Next k
            End If
        End If

    Next r

    ' output the results
    ActiveWorkbook.Sheets(Sheet).Range(Cells(LastRow + 1, 1), Cells(LastRow + Count, 16)).Value = Arr

    ActiveWorkbook.Sheets(Sheet).AutoFilterMode = False
    Call returnToOriginal
End Sub

Answering the query "What did I mean by this?"
    '(pretty sure the following line needs to localize the Cells() to .Cells())
    data = ActiveWorkbook.Sheets(Sheet).Range(Cells(1, 1), Cells(LastRow, LastCol)).Value    '**'

The use of Cells(..) here is fundamentally unreliable and broken.  this is because Cells(..) is really a shortcut for ActiveSheet.Cells(..) and the Active* properties are inherently slow and unreliable because they can change while the code is running.  Worse, this code is assuming that ActiveSheet = Energy_LS_Blotter which is far from certain.
The correct way to write this line would be like this:
data = ActiveWorkbook.Sheets(Sheet).Range( _
            ActiveWorkbook.Sheets(Sheet).Cells(1, 1), _
            ActiveWorkbook.Sheets(Sheet).Cells(LastRow, LastCol) _
            ).Value

But that is long, ugly and inconvenient.  An easier way would be to use either a Sheet variable, or a With:
With ActiveWorkbook.Sheets(Sheet)
    data = .Range(.Cells(1, 1), .Cells(LastRow, LastCol)).Value
End With


text:
Q: Python list to split and only pull certain items to make a new list I've used python to connect to a SQL server to execute a query.
I have a current list showing something like the below sample:
[('TEST', 'dbo', 'XXX', 'Practice', 1, 'char', 3, 3, None, None, 1, None, None, 1, None, 3, 1, 'YES', 39)
('TEST', 'dbo', 'XXX', 'ParPracticeCode', 1, 'char', 3, 3, None, None, 1, None, None, 1, None, 3, 2, 'YES', 39)
('TEST', 'dbo', 'XXX', 'PracOnlyName', 12, 'varchar', 100, 100, None, None, 1, None, None, 12, None, 100, 3, 'YES', 39)]

However, I would like to split the list and create a new list by including only the 4th item such as Practice, ParPracticeCode and PracOnlyName.
so it becomes, new_list = [Practice, ParPracticeCode, PracOnlyName]

A: sample = [('TEST', 'dbo', 'XXX', 'Practice', 1, 'char', 3, 3, None, None, 1, None, None, 1, None, 3, 1, 'YES', 39), ('TEST', 'dbo', 'XXX', 'ParPracticeCode', 1, 'char', 3, 3, None, None, 1, None, None, 1, None, 3, 2, 'YES', 39), ('TEST', 'dbo', 'XXX', 'PracOnlyName', 12, 'varchar', 100, 100, None, None, 1, None, None, 12, None, 100, 3, 'YES', 39)]
new_list = [x[3] for x in sample]

A: x = [('TEST', 'dbo', 'XXX', 'Practice', 1, 'char', 3, 3, None, None, 1, None, None, 1, None, 3, 1, 'YES', 39),
     ('TEST', 'dbo', 'XXX', 'ParPracticeCode', 1, 'char', 3, 3, None, None, 1, None, None, 1, None, 3, 2, 'YES', 39),
     ('TEST', 'dbo', 'XXX', 'PracOnlyName', 12, 'varchar', 100, 100, None, None, 1, None, None, 12, None, 100, 3, 'YES', 39)]

Write a for loop to access the  '4' the value of each element in list like a 2D matrix
new_list = []

for i in range(len(x)):
    new_list.append(x[i][3])

This implementation will do


text:
Q: Parsing HTML of Website in a dedicated-server instead of doing it in a mobile phone I have an iOS app that downloads HTML from web (that is not mine) and parses it to obtain the data I need. The problem is that when they change the HTML of the web the mobile app crashed, and I've to change the code, and Apple stay more than one week to accept the update.
The idea is to to all the operations that now I do in the mobile app in a server or web, like have to act like a bridge, i.e., this server/web would download the HTML web, parse it and send the results to the mobile app. In this form I can do any change instantaneously.
My question is if I can do this without doing an application that needs servlets and a Tomcat server. Can I do it with a php file or something like that? I don't need need to save any data, only parse a HTML and return to the mobile a response with a specified format.
Thanks for all.
PD: Sorry for my english, but it's not my native language.

A: Yes, you can do that with PHP. BUT only when your web space is configured correct, very cheap and free providers often disable outgoing connections from your server.

In PHP you can make a HTTP GET request with just a single line:
$htmlContent = file_get_contents("http://www.example.com/file.html");

If you need ability to get more information about the result of your HTTP GET request (like headers) you can still do this very easily by using http_get():
$htmlContent = http_get("http://www.example.com/file.html", array("timeout"=>10), $info);
print_r($info); // <- $info now contains information about header fields

For more advanced GET/POST requests, you can install the CURL library:
$ch = curl_init("http://www.example.com/file.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$htmlContent = curl_exec($ch);
curl_close($ch);


text:
Q: Retrieve the value of the column excel I need your help, I would like to retrieve the value of the column where the cell contains 1 here is an example:
Image

A | B | C | D
1 | 0 | 0 |
0 | 1 | 1 |
1 | 1 | 0 |
The desired result:
A | B | C | D
1 | 0 | 0 | A
0 | 1 | 1 | B,C
1 | 1 | 0 | A,B
Thank you !

A: Here is a VBA approach that works for any number of columns:
Function SelectedColumns(R As Range) As String
    Dim i As Long, n As Long, count As Long
    Dim cols As Variant

    n = R.Columns.count
    ReDim cols(1 To n)
    For i = 1 To n
        If R.Cells(1, i).Value = 1 Then
            count = count + 1
            cols(count) = Split(R.Cells(1, i).Address, "$")(1)
        End If
    Next i
    If count > 0 Then
        ReDim Preserve cols(1 To count)
        SelectedColumns = Join(cols, ",")
    End If
End Function

Put the above code in a standard code module. The, in your example, if you enter =SelectedColumns(A1:C1) in cell D1 and copy down then it will work as expected.

A: Here is the TEXTJOIN formula that can be used in Office 365 Excel:
=TEXTJOIN(",",,IF(A1:C1=1,{"A","B","C"},""))

This is an array formula and must be confirmed with Ctrl-Shift-Enter instead if Enter When exiting edit mode.

For Earlier versions you can use an if for each and concatenate:
=MID(IF(A1=1,",A","") & IF(B1=1,",B","") & IF(C1=1,",C",""),2,100)

A: I am a little unclear of your formatting (how you want the answer etc), but perhaps this will help you out a bit.
I am assuming your headers are in cells A1 through C1, then your data in cells A2 through C4. Ane you want the data in Cells D2 to F4.
If you copy the following into cell D2 then use the drag function it will produce the result you are after.
    =IF(A2=1,A$1,"")
Have a look at the screen capture where I have displayed the formulas then another with the result displayer.
Formulars Displayed
Just the results
Hope this helps --- Best of Luck !!!


text:
Q: Fast, vectorisable distance from points to ellipse I am writing a program im Matlab to find ellipses in noisy XY data using a Random Sampling Consensus (RANSAC) algorithm. It basically samples enough points to define an ellipse and then determines the consensus as the number of points within a certain distance to this ellipse. After X trials, the ellipse with the most inliers is chosen.
Right now, I compute the distance of the points to the ellipse by generating 500 points on the ellipse boundary, compute the distance of every one of these ellipse points to the points to be fit, and select the least distance as the distance between the point and the ellipse. For the 1000 - 10000 points I want to fit to, this distance calculation is the bottleneck of the computation.
The algorithms I found for distance point to ellipse usually need to solve rather complex equations. Ideally, I am looking for an algorithm that can be vectorised, so the calculations can be done for every point I want to fit at the same time. If that isn't possible, fast methods that can be done in a loop for every point are also ok. Approximate solutions (maybe using an interpolation of the ellipse or something) are welcome.
 Thanks!


text:
Q: django makemigrations override to create migration files with custom names I have a python2.7 django project (I know, I am in 20th century!) that has some models in it. I need to override makemigrations so that the migration filenames are of the form 0001.py, 0002.py and so on, and not like 0001_initial.py, 0002_model1.py and so on which is by default what happens.
I already looked at how to create custom manage.py commands and I am able to override makemigrations command. Presently my code for the custom command (python2.7) looks like this:

path/to/project/app/management/commands/makemigrations.py

from django.core.management.commands.makemigrations import Command as CoreMakeMigrationsCommand

class Command(CoreMakeMigrationsCommand):
    def handle(self, *args, **options):
        super(Command, self).handle(*args, **options)

It is doing nothing more than calling the original makemigrations at the moment. I need to be able to modify the behaviour of how autodetector.py(which is part of the makemigrations flow) decides the naming of the files. In this file, there's method suggest_name as shown below:
@classmethod
    def suggest_name(cls, ops):
        """
        Given a set of operations, suggest a name for the migration they might
        represent. Names are not guaranteed to be unique, but put some effort
        into the fallback name to avoid VCS conflicts if possible.
        """
        if len(ops) == 1:
            if isinstance(ops[0], operations.CreateModel):
                return ops[0].name_lower
            elif isinstance(ops[0], operations.DeleteModel):
                return "delete_%s" % ops[0].name_lower
            elif isinstance(ops[0], operations.AddField):
                return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
            elif isinstance(ops[0], operations.RemoveField):
                return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
        elif ops:
            if all(isinstance(o, operations.CreateModel) for o in ops):
                return "_".join(sorted(o.name_lower for o in ops))
        return "auto_%s" % get_migration_name_timestamp()

The above gets called from here, in the same file in another method arrange_for_graph:
            for i, migration in enumerate(migrations):
                if i == 0 and app_leaf:
                    migration.dependencies.append(app_leaf)
                if i == 0 and not app_leaf:
                    new_name = "0001_%s" % migration_name if migration_name else "0001_initial"
                else:
                    new_name = "%04i_%s" % (
                        next_number,
                        migration_name or self.suggest_name(migration.operations)[:100],
                    )

I am new to overriding core files, and cannot figure out how to override only this part from my original custom command file, so that my requirements are met?
Also, please advise on how that is going to affect the subsequent calls to makemigrations, since they will be dependent on the new set of migrations files (with modified names).
Thanks

A: Ok, here is how I did it.
Create a makemigrations.py file (as shown in django docs for overriding manage.py commands), inside that create a Command class inheriting "django.core.management.commands.makemigrations.Command" and override the method write_migration_files, as show below:
from django.core.management.commands.makemigrations import Command as CoreMakeMigrationsCommand

class Command(CoreMakeMigrationsCommand):
    def write_migration_files(self, changes):
        for item in changes.values():
            print('Overriding default names of migrations supplied by django core')
            item[0].name = item[0].name.split('_')[0]
        super(Command, self).write_migration_files(changes)

A: Unless you have hundreds of migrations, I think the easiest would be the following:

*

*Create migrations one by one as you need but with the names decided by Django.

*Rename the migrations:

*

*Rename the files: 0002_migration_name.py -> 0002.py, etc.

*Rename the references in the files, for example, replacing:
dependencies = [
    ('appname', '0002_migration_name'),
]

by:
dependencies = [
    ('appname', '0002'),
]

*Only apply any migration when it, and all the previous ones, have the name you want.


text:
Q: Codeigniter helper function to validation rules I created a helper for checking if a user id exists in my user database table:
   if ( ! function_exists('valid_user'))
    {
        function valid_user($user_id)
        {
            $ci=& get_instance();
            $ci->load->database();

            $ci->db->select('id');
            $ci->db->where('id', $user_id);
            $ci->db->where('activated', 1);
            $ci->db->where('banned', 0);
            $ci->db->limit(1);
            $query = $ci->db->get('users');

            if ($query->num_rows() > 0) //if user exists
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
    }

I added the function to my validation rule like so
$this->form_validation->set_rules('user_id', 'User ID', 'required|xss_clean|max_length[11]|is_natural_no_zero|valid_user');

It does not perform the valid_user function. What am I doing wrong here?

A: In my previous experience, I usually added a validation function (in your case, valid_user) in the same place where the callback is called.
For example, I would put valid_user method in a users_controller where one of the registration methods will invoke the valid_user method.
Also, it seems that, in your set_rules, you have to set callback_valid_user not valid_user according to the Codeigniter user guides.
http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks

A: $this->form_validation->set_rules('user_id', 'User ID',
'required|xss_clean|max_length[11]|is_natural_no_zero|callback_valid_user');
//note the callback_                                     ↑


text:
Q: Prevent Spaces In Text Box On my page, I have a text box that allows the user to enter a string. What I wish to do is prevent the user from entering spaces into the textbox.
<form>

        Skype Name
        <input class="form-control" id="InputSkype" placeholder="Enter Skype Name" style="text-transform: lowercase;">

    <button type="submit" class="btn btn-primary">Resolve</button>
</form>


text:
Q: Prevent JavaScript function from running multiply I read this answer but I can't migrate it with this code.
<button class="btn btn-success pause" id="btnFunction" onclick="toggleFunction();" type="button">Play</button>

If I click two times the button it's run two times function, and if code cant get image from playSocket.php it's showing two times iziToast.warning and repeat showing after 2.5 seconds and after that until its getting image and its image load.
How to prevent the function from running multiply?
There is a better way to knowing image it's loaded successfully and getting the next image or error in getting image and try again? alternative for newImage.onload and newImage.onerror

A: I think the best solution will be checking whether there is any ongoing ajax call exist before triggering the action of the click event. Only if there is no existing event, only them trigger the action for the click. I have added a sample code. Hope you can convert this to your exact requirement.

var ajaxInProgress = false;
function play() {
  if ($("#btnFunction").hasClass("play")) {
    console.log('clicked');
    ajaxInProgress = true;
    var newImage = new Image(),
      count = 0;
    newImage.onload = function() {
      ajaxInProgress = false;
      updateImage();
    };
    newImage.onerror = function() {
      ajaxInProgress = false;
      document.getElementById("mainImage").src = "https://www.w3schools.com/html/pic_trulli.jpg";
      console.error('error in getting image');
      setTimeout(play, 2500);
    };
    newImage.src = "https://www.w3schools.com/html/pic_trulliddd.jpg";

    function updateImage() {
      if (newImage.complete) {
        document.getElementById("mainImage").src = newImage.src;
        newImage.src= 'https://www.w3schools.com/html/img_girl.jpg';
      } else {
        console.error('error in getting image');
        setTimeout(updateImage, 2500);
      }
    }
  }
}

function toggleFunction() {
  if(!ajaxInProgress) {
    if ($("#btnFunction").hasClass("pause")) {
      $("#btnFunction").html("Disable Playing");
      $("#btnFunction").removeClass("btn-success pause");
      $("#btnFunction").addClass("btn-danger play");
      play();
    } else if ($("#btnFunction").hasClass("play")) {
      $("#btnFunction").html("Enable Playing");
      $("#btnFunction").removeClass("btn-danger play");
      $("#btnFunction").addClass("btn-success pause");
    }
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />

<button class="btn btn-success pause" id="btnFunction" onclick="toggleFunction();" type="button">Play</button>

A: <button class="btn btn-success" id="btnFunction" type="button">Play</button>


text:
Q: Failed to upload packages to PyPI: 410 Gone After pypi.python.org has been migrated to pypi.org, I got an error when trying to upload a package to PyPI using the command as usual:
python2.7 setup.py sdist upload
The error message is:
Upload failed (410): Gone (This API has been deprecated and removed from legacy PyPI in favor of using the APIs available in the new PyPI.org implementation of PyPI (located at https://pypi.org/). For more information about migrating your use of this API to PyPI.org, please see https://packaging.python.org/guides/migrating-to-pypi-org/#uploading. For more information about the sunsetting of this API, please see https://mail.python.org/pipermail/distutils-sig/2017-June/030766.html)
I looked into the solution mentioned in the message and then googled a little bit. Unfortunately, the solutions I found were not working, including updating my local ~/.pypirc file. Like this:
[distutils]
index-servers =
    pypi

[pypi]
repository:https://pypi.python.org/pypi   or  repository:https://upload.pypi.org/legacy/
username:yourusername
password:yourpassword

I still got the same error message. What should I do?

A: Upgrade to the very latest pip and setuptools; install twine:
pip install -U pip setuptools twine

Edit ~/.pypirc and comment out or remove repository:
[pypi]
#repository:https://pypi.python.org/pypi

Use twine to upload your module to pypi from within the folder containing the module source, setup.py, and other files:
python setup.py sdist
twine upload dist/*

See https://packaging.python.org/guides/migrating-to-pypi-org/#uploading

A: If you are looking for legacy solution, try updating your ~/.pypirc file to this
[distutils]
index-servers =
    pypi

[pypi]
repository: https://upload.pypi.org/legacy/
username: username
password: password

And running
python setup.py sdist upload -r pypi
Not sure if it will work right away. Since I did multiple things in order to get it working such as

*

*Updating both python and python3 (I am still on 2.7.12 and 3.5.2 though)

*Installing twine if your system does not have it yet

*Updating pip, setuptools and twine per phd's suggestion

*Also pip3 install -U pip setuptools twine might help

A: I recommend using twine.
Just install it:
pip install twine

And simply do:
twine upload dist/*

Note: Do this from root of your project


text:
Q: A condition for one domain to be included in another domain? Consider two domains:
domain1 = Rectangle[{-2.5, -2.5}, {2.5, 2.5}];
domain2[R_] := Disk[{0, 0}, R]

I would like to check whether the second domain is completely included in the first domain. My attempt is
condition[R_] := If[domain2[R] \[Element] domain1, 1, 0]
condition[1]

However, it does not work, as the commands used are incorrect. Could you please tell me how to do this?

A: domain1 = Rectangle[{-2.5, -2.5}, {2.5, 2.5}];
domain2[R_] := Disk[{0, 0}, R]

You can use RegionWithin:
ClearAll[condition]
condition[R_] := Boole @ RegionWithin[domain1, domain2[R]]

{condition[1], condition[3]}

{1, 0}

You can also use a combination of ForAll and Resolve:
ClearAll[conditionB]
conditionB[R_] := Resolve[ForAll[x, Implies[x ∈ domain2[R], x ∈ domain1]], Reals]

{conditionB[1], conditionB[2], conditionB[3]}

 {True, True, False}

ClearAll[conditionC]
conditionC[R_] := Resolve[ForAll[x, ! x ∈ domain2[R] || x ∈ domain1], Reals]

{conditionC[1], conditionC[2], conditionC[3]}

{True, True, False}

A: domain1 = Rectangle[{-2.5, -2.5}, {2.5, 2.5}];
domain2[R_] := Disk[{0, 0}, R]
Table[RegionEqual[RegionIntersection[domain1, domain2[R]],
  domain2[R]], {R, {1, 2, 3}}]

{True, True, False}


text:
Q: Mongoose / Mongodb - should I explicitly add objectid to populate? So I have 2 models, one is users and the other is sessions.
It was initially setup as:
const users = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    username: {type: String, unique: true},
}
);
module.exports = mongoose.model('User', users,);

I then went on and added another model, called sessions,
const sessions = mongoose.Schema({
    _id: {type: mongoose.Schema.Types.ObjectId, default: mongoose.Schema.Types.ObjectId, null: false},
    user_id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    timestamp: {type: Date},
});

module.exports = mongoose.model('Sessions', sessions);

I then decided, I want to to be able to pull the user's sessions along with the users and added
    sessions: [{type: mongoose.Schema.Types.ObjectId, ref: 'SurfSessions', default: null}] to my users model schema.
I quickly learnt that users.findOne(username:admin).populate('sessions') isn't gonna fill up sessions by itself, as sessions returns as an empty array [].
Since I don't have sessions inside users populated with objectid's does that mean I cannot populate sessions or is there another way?

A: You should be able to do this with virtual populate:
const users = new mongoose.Schema(
  {
    _id: mongoose.Schema.Types.ObjectId,
    username: { type: String, unique: true },
  },
  { toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
module.exports = mongoose.model('User', users);

Then:
userSchema.virtual('sessions', {
  ref: 'Session', // model to search in
  foreignField: 'user_id',
  localField: '_id', // checks where user_id on session === _id on user
});

After this, use .populate('sessions') as normal. For more check this out: https://mongoosejs.com/docs/tutorials/virtuals.html#populate


text:
Q: Keeping a consistent parentId/id relationship with a flatten function Suppose I have a nested object list like this:
[{
    "id": "a",
    "name": "Object a",
    "parentId": "root",
    "children": [{
        "id": "c",
        "name": "Object c"
    },{
        "id": "d",
        "name": "Object D",
        "parentId": "a"
    }]
}, {
    "id": "b",
    "name": "Object b",
    "parentId": "root"
}]

The object anatomy is simple: id, name, children (if any) and parentId. I'm using this flatten function that turns the nested object
into a flat array:
 function flatten(array) {
  var result = [];
  array.forEach(function (a) {
      result.push(a);
      if (Array.isArray(a.children)) {
          result = result.concat(flatten(a.children));
      }
  });
  return result;
}

The thing is that the parentId value is not always persistent for every object, and therefore when the object gets flattened into an array, it's possible to lose a parent & child object relationship.
I need the flatten method to rebuild the parentId value according to the object structure. And there's only one catch, if the object is not a child, then it should have a parentId of root.
Help is very much appreciated

A: If I follow correctly, you just want to flatten your structure into an array that maintains the parentId relationship inherent in the original tree.  If so, then I believe this will do:

const flatten = (xs, parentId = 'root') =>
  xs .flatMap (({children = [], id, ...rest}) => [
    {id, ...rest, parentId},
    ... flatten (children, id)
  ])

const input = [{id: "a", name: "Object a", parentId: "root", children: [{id: "c", name: "Object c"},{id: "d", name: "Object D", parentId: "a"}]}, {id: "b", name: "Object b", parentId: "root"}]

console .log (flatten (input))
.as-console-wrapper {max-height: 100% !important; top: 0}

It's a fairly simple recursion, using flatMap to combine the records and parameter destructuring (with default a parameter for children) to simplify our object handling.

A: Sounds like you just need to add the parentId to the objects that don't have them. Change
result = result.concat(flatten(a.children));

to
result = result.concat(flatten(a.children.map(addParent(a.parentId)));

const addParent = parentId => item => ({ ...item, parentId });

where the root is called with a parentId of root.

A: You can pass the parentId in as the second argument to your flatten function like so, with the default parent just being "root".

const arr = [{
    "id": "a",
    "name": "Object a",
    "parentId": "root",
    "children": [{
        "id": "c",
        "name": "Object c"
    },{
        "id": "d",
        "name": "Object D",
        "parentId": "a"
    }]
}, {
    "id": "b",
    "name": "Object b",
    "parentId": "root"
}]

function flatten(array, parentId = "root") {
  let result = [];
  array.forEach(function(a) {
    a.parentId = parentId;
    result.push(a);
    if (Array.isArray(a.children)) {
      result = result.concat(flatten(a.children, a.id));
    }
    delete a.children; // optional
  });
  return result;
}

console.log(flatten(arr));


text:
Q: Deploying WSP, Sharepoint Version In my current environment we have SH 2010 RTM, and deployment works fine.
But in the near future there is going to be another farm, and in this one we would like to have it up to date with SP 1, all CUs, hotfixes, etc.
I suppose that developer VMs and its sharepoint versions, should match the versions otherwise SharePoint wont allow to deploy the WSPs. Is that correct?
So I suppose I have 2 options:
1. Leave the new farm in RTM
2. Upgrade the current FARM to SP1, and June 2012 CU. (do the same with developer VMs)

A: No it's not correct.
Nothing in the wsp is mentionning the version of SharePoint. If you look into the wsp file (it's a zip file, use any dezipper), you will see that's only Xml and dll files (+ some assets depending on the project).
You will be able to deploy the wsp file with no issue.
BUT
I highly recommend you to migrate the development environment to the same version than target platform. If you don't, you will have a risk to fall in a bug on previous service packs that have been solved in the latest release. Or you will have something that works on dev computer, but that does not works on production platform (Microsoft regression, raise security requirement, etc.).
In other words, reduce the risk of different behaviors by duplicating as nearly as possible the production environment.


text:
Q: Saving a created .msg file as readonly Hi I had a requirement wherein I convert dxl to .msg file. Since there is no out of the box .NET way to do so, I parsed the xml, got the required fields out, created a .msg file using Microsoft.Office.Interop.Outlook. But when I open the file it looks like a draft mail, ready to be sent. But I would want the file to open as an inbox mail or a sent mail, wherein the fields are 'Not Editable' meaning should be readonly.
My code:
mailitem.To = "reciever@recieve.com";
mailitem.SentOnBehalfOfName = "sender@send.com";
mailitem.Subject = "Test for MSG";
mailitem.Body = "Sample Body";
mailitem.SaveAs(temppath + ".msg", OlSaveAsType.olMSG);

There is something called SaveSentMessageFolder in mailItem, couldn't figure out how to do so.
Thanks


text:
Q: D unknown function _xopEquals I downloaded druntime from https://github.com/xomboverlord/xomb-bare-bones/tree/master. It's druntime made for bare bones XOmB OS. If I want to compile it to object files, dmd return error "undefined identifier _xopEquals". Then I was look to official druntime and I found function _xopEquals. When I add this function to XOmB druntime, nothing changed...
I found this function in druntime/src/object_.d :
bool _xopEquals(in void*, in void*)
{
     throw new Error("TypeInfo.equals is not implemented");
}

And I add it to module where DMD invoke the error.

A: *

*What is the first question?

*Yes, druntime's documentation is on this page: http://dlang.org/phobos/index.html . All modules in the core package are druntime modules. DMD's Phobos distribution contains druntime. However, some other implementations may or may not do so. GDC project, for an example, distributes a separated libgdruntime.a from libgphobos2.a .


text:
Q: finding min and max value in an object like array I am trying to find a minimum and maximum value from an array
tried various things, but could not find the solution to satisfy my needs
I have an array object like
its values are
{
    0:exchange:bitfix

    totaleth:334

    1:exchange:coinbase

    totaleth:6000

    2:exchange:koinex

    totaleth:3000
}

now this object like an array, I want to show the minimum and maximum values, based on totaleth field, does any 1 have a solution
I tried various things like map reduce for loop, nothing seems to be working

A: Assuming an array of objects, you could reduce the array by taking min and max values.

var array = [{ exchange: 'bitfix', totaleth: 334 }, { exchange: 'coinbase', totaleth: 6000 }, { exchange: 'koinex', totaleth: 3000 }],
    { min, max } = array.reduce(
        (r, o, i) => i
            ? {
                min: r.min.totaleth < o.totaleth ? r.min : o,
                max: r.max.totaleth > o.totaleth ? r.max : o
            }
            : { min: o, max: o },
        undefined
    );

console.log('min', min);
console.log('max', max);

A: Ok, so you can use sort function, but remember that it modifies original array.
const someArr = [{"_id":"5c585ed5a9a5b931c3057d48","exchange":"Poloniex","totaleth":-338,"dt":"2019-02-04T15:48:37.232Z","__v":0},{"_id":"5c585ed5a9a5b931c3057d47","exchange":"Bitrex","totaleth":-227,"dt":"2019-02-04T15:48:37.222Z","__v":0},{"_id":"5c585ed5a9a5b931c3057d46","exchange":"Gemini","totaleth":86,"dt":"2019-02-04T15:48:37.220Z","__v":0},{"_id":"5c585ed5a9a5b931c3057d45","exchange":"Bitfinex","totaleth":-373,"dt":"2019-02-04T15:48:37.219Z","__v":0},{"_id":"5c585ed4a9a5b931c3057d44","exchange":"Binance","totaleth":6531,"dt":"2019-02-04T15:48:36.586Z","__v":0}];

console.log(
  someArr.sort((a, b) => {
    return a.totaleth - b.totaleth;
  })
);

A: your code worked thanks a lot nina scholz

var array = [{ exchange: 'bitfix', totaleth: 334 }, { exchange: 'coinbase', totaleth: 6000 }, { exchange: 'koinex', totaleth: 3000 }],
    { min, max } = array.reduce(
        (r, o, i) => i
            ? {
                min: r.min.totaleth < o.totaleth ? r.min : o,
                max: r.max.totaleth > o.totaleth ? r.max : o
            }
            : { min: o, max: o },
        undefined
    );

console.log('min', min);
console.log('max', max);


text:
Q: What should be the input to Convolution neural network (CNN) using keras and tensorflow? I'm trying to create CNN model using keras ad tensorflow as backend.
below is code for the same..
Cannot understand what input it is expecting...
import cv2,os
import glob
import numpy as np
from sklearn.utils import shuffle
from sklearn.cross_validation import train_test_split
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Input, Convolution2D, MaxPooling2D, Dense, Dropout, Flatten

PATH = os.getcwd()
data_path = PATH + '/data1/cat/*.PNG'

files = glob.glob(data_path)
X_data = []
for myFile in files:
    image = cv2.imread (myFile)
    image_resize = cv2.resize(image,(128,128))
    X_data.append (image_resize)

image_data = np.array(X_data)
image_data = image_data.astype('float32')
image_data /= 255
print('X_data shape:', image_data.shape)

#Class ani labels
class_num = 2

total_Images = image_data.shape[0]
labels = np.ones((total_Images),dtype='int64')

labels[0:30] = 0
labels[31:] = 1

Y = to_categorical(labels,class_num)

#print(Y);

# Shuffle the dataset
x, y = shuffle(image_data, Y, random_state=2)
# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)

input_shape = image_data[0].shape

#print(input_shape)

model = Sequential()

conv1 = Convolution2D(32,(3,3),padding='same',activation='relu')(input_shape)
conv2 = Convolution2D(32,(3,3),padding='same',activation='relu')(conv1)
pool_1 = MaxPooling2D(pool_size=(2,2))(conv2)
drop1 = Dropout(0.5)(pool_1)

conv3 = Convolution2D(64,(3,3),padding='same',activation='relu')(drop1)
conv4 = Convolution2D(64,(3,3),padding='same',activation='relu')(conv3)

pool_2 = MaxPooling2D(pool_size=(2,2))(conv4)
drop2 = Dropout(0.5)(pool_2)

flat = Flatten()(drop2)
hidden = Dense(64,activation='relu')(flat)
drop3 = Dropout(0.5)(hidden)
out = Dense(class_num,activation='softmax')(drop3)

model.compile(loss = 'categorical_crossentropy', optimizer= 'adam', metrics=['accuracy'])

model.fit(X_train,y_train,batch_size=16,nb_epoch=20, verbose=1, validation_data=(X_test,y_test))

model.evaluate(X_test,y_test,verbose=1)

Error: ValueError: Layer conv2d_1 was called with an input that isn't a
symbolic tensor. Received type: <class 'tuple'>. Full input: [(128, 128,3)].
All inputs to the layer should be tensors.

A: You are attempting to use the functional API and the sequential model all at once you need to first eliminate this line
model = Sequential()

Then, from the documentation of the functional API, we add an Input(channels,rows,columns) layer, and fill in the size values from your X_train matrix.
input_shape = Input()


text:
Q: How to check whether a table exists in my database My page

displays "mysql_num_rows() expects parameter 1 to be resource,
  boolean given in ....

table does not exist" I dont know where my problem is.
Here is my code:
$sql="SELECT *
    FROM
    $db_name    WHERE
    table_name='{$_SESSION
    ["group"]}'";
    $texist=mysql_query($sql);
    $count=mysql_num_rows($texist);

    if($count==1){
    echo"table exists";
    }else{
    echo "table does not exist";
    }

A: NOTE : mysql_* deprecated in PHP.Use MySQLi or PDO_MySQL
try with
    if (mysql_num_rows(mysql_query("SHOW TABLES LIKE '" . $_SESSION["group"] . "'")) == 1)
    {
          echo "exists";
    }
    else
    {
          echo "not";
    }

A: Here we  Select one row from table will return false if the table does not exist.We need to strong comparison opertator here instead of == you need to use === or !==
$result = mysql_query('select 1 from `tbl_student`');

if($result !== FALSE)
{
   echo "table is exist";
}
else
{
   echo "table isnot exist";
}

A: To check if table exists in DB or not you can use one of this two way
1.
SHOW TABLES LIKE 'table_name';

2.
SELECT count(*)
FROM information_schema.tables
WHERE table_schema = 'db_name'
AND table_name = 'table_name'

for more information see Here

A: mysql_query returns false on error, instead of a resource. Check for that error before proceeding.
Example check:
<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}


text:
Q: Python-Multiprocessing Error when working with astropy I want to speed up some scripts that I need to analyze astronomical data. I have scripts that are run independently for every single image file that I have (which are in .fits file format). I was trying to simply start multiple files at once using Multiprocessing.Pool() and map. My code looks like this:
def sextract(name):
    # creates a class instance and calls the method
    astro = astrometry(name, *some_more_args)
    astro.sextract()

arguments = ['PART1_cal.fits', 'PART2_cal.fits', 'PART3_cal.fits',
            'PART4_cal.fits', 'PART5_cal.fits']

with closing(Pool()) as pool:
    pool.map(sextract, arguments)
    pool.terminate()

and the astrometry.sextract method looks like this:
def sextract(self):
    sex = 'sextractor'
    headerlist = ['JD-START', 'OBSERVER', 'DATE', 'TM-START', 'OBJECT',
                  'FLTRNAME', 'RA', 'DEC', 'AIRMASS',
                  'EXP_TIME']
    calib = self._from
    # calls the SourceExtrator in the shell with a config-file and
    # the file name
    os.system(sex + ' -c ' + self.sexpath + ' ' + calib)
    # copies the extracted file to a folder on an external HDD
    shutil.copy2(self.ext_path, self._to + '/' +
                 calib.split('/')[-1])
    # opens the old .fits image and extracts the header
    old = fits.open(calib)
    o = old[0].header
    # opens the new(copied) .fits image and extracts the header
    # this produces the error
    extr = fits.open(self._to + '/' + calib.split('/')[-1],
                     mode='update')
    e = extr[1].header
    # goes through the old header entries and copies all entries
    # in the to the new header
    for g in headerlist:
        e[g] = o[g]
    # saves the new header to the new(copied) file and closes both
    # files
    extr[1].header = e
    extr.flush()
    extr.close()
    old.close()

Every time I run this code, I get an IOError: Header missing END card., which is thrown by the line where I open the new .fits and put it in the variable extr. At first I thought this would happen because the copy procedure would take too long, and the python tries to access the file before it's finished copying. I inserted a time.sleep(10) to check that, but the error still appears.
I tried using pool.apply() and the normal map() and in both cases I don't get an error. When using pool.apply() it takes almost as long as for the map() case though, so I haven't really accomplished anything doing it this way.
I know this is a very specific question, but I hope someone might know where my problem lies, or got something similar working already.


text:
Q: URL to Publish to TeamCity NuGet server Trying to use PowerShell's Publish-Module to upload a PowerShell Module to TeamCity's NuGet server.
I can use PowerShell with Find-Module to find modules that were added to TeamCity from previous build artefacts, but would also like to upload "manually".
On other NuGet Servers I am used to see the /Packages/ folder. Does that not exist on TeamCity?
Thanks.

A: TeamCity NuGet feed is readonly. The only way to publish a package is running a build and publish it as an artifact.


text:
Q: Correct way to define a Gradle plugin property extension with Java? I'm trying to create a Gradle plugin in Java that has property extensions (not conventions, as this is apparently the old, wrong way). For the record, I'm working with Gradle 1.6 on a Linux machine (Ubuntu 12.04).
I've gotten as far as figuring out that the this should be done in the Plugin class definition. Here is A way of adding an extension. Create an extension class that contains your properties:
public class MyPluginExtensions {

    File sourceDir;
    File outputDir;

    public MyPluginExtensions(Project project) {
        this.project = project;
        sourceDir = new File(project.getProjectDir(), "src");
        outputDir = new File(project.getBuildDir(), "out");
    }

}

Now add these extensions to the project in the main plugin class:
public class MyPlugin implements Plugin<Project> {

    @Override
    public void apply(Project project) {

        Map<String,Object> taskInfo = new HashMap<String,Object>();
        taskInfo.put("type", MyPluginTask.class);
        taskInfo.put("description", "Generates blah from blah.");
        taskInfo.put("group", "Blah");
        Task myPluginTask = project.task(taskInfo, "myPluginTask");

        // Define conventions and attach them to tasks
        MyPluginExtensions extensions = new MyPluginExtensions(project);
        myPluginTask.getExtensions().add(
                "sourceDir",
                extensions.sourceDir);
        myPluginTask.getExtensions().add(
                "outputDir",
                extensions.outputDir);
    }
}

This approach, however, doesn't seem to be correct. A new project property is shows up in the project.ext namespace. I expect to be able to address the plugin extensions as:
in my build.gradle:
myPluginTask.sourceDir = file('the/main/src')
myPluginTask.outputDir = file('the/output')

However, when I put such things in a gradle script that uses my plugin and try to set this property, gradle tells me I can't set it:
* What went wrong:
A problem occurred evaluating script.
> There's an extension registered with name 'sourceDir'. You should not reassign it via a property setter.

So, what's the right way to add property extensions for a task in a Java-based Gradle plugin?
EDIT:
Based on some other SO posts, I tried just adding my extensions object in one shot:
// first attempt:
//myPluginTask.getExtensions().add("sourceDir", extensions.sourceDir);
//myPluginTask.getExtensions().add("outputDir",extensions.outputDir);

// second attempt
myPluginTask.getExtensions().add("myPluginTask", extensions);

This appears to work. However, Gradle is now complaining that I've added a dynamic property:
Deprecated dynamic property: "sourceDir" on "task ':myPluginTask'", value: "/Users/jfer...".

So, again, what's the right way to add a plugin extension property?
EDIT 2
So, taking yet another shot at this, I'm adding the extension to the project object and using the create method instead:
// first attempt:
//myPluginTask.getExtensions().add("sourceDir", extensions.sourceDir);
//myPluginTask.getExtensions().add("outputDir",extensions.outputDir);

// second attempt
// myPluginTask.getExtensions().add("myPluginTask", extensions);

// third attempt
project.getExtensions().create("myPluginTask", MyPluginExtensions.class, project);

However, this fails for a couple of reasons:

*

*Creating a properties extension with the same name ("myPluginTask") as the task creates a collision between the task name and extension name, causing the task to disappear from gradle's perspective (and throw oblique errors, such as "No such property: dependsOn for class ...MyPluginExtensions").

*If I provide a name that does not collide with a task name (e.g., "myPluginPropExt"), the create() method works, but DOES NOT add the extension in its own namespace as expected (e.g., project.myPluginPropExt.propertyName and instead adds it in the project namespace (e.g., project.propertyName) which is not correct and causes Gradle to throw a bunch of "deprecated dynamic property" warnings.

A: So here is a solution to my problem:
public class MyPlugin implements Plugin<Project> {

    @Override
    public void apply(Project project) {

        Map<String,Object> taskInfo = new HashMap<String,Object>();
        taskInfo.put("type", MyPluginTask.class);
        taskInfo.put("description", "Generates blah from blah.");
        taskInfo.put("group", "Blah");
        Task myPluginTask = project.task(taskInfo, "myPluginTask");

        // Define conventions and attach them to tasks
        MyPluginExtensions extensions = new MyPluginExtensions(project);

        // the magic extension code:
        project.getExtensions().add("myPluginName", extensions);
    }
}

Now I can set a value for one of the extension properties in my gradle.build file like so (and I don't get a warning about adding deprecated dynamic properties):
 myPluginName.sourceDir = file('the/main/src')

The final trick is to get this value in my Plugin's task:
public class MyPluginTask extends DefaultTask {
    @TaskAction
    public void action() {
        MyPluginExtensions extensions = (MyPluginExtensions) getProject()
                .getExtensions().findByName("myPluginName");

        System.out.println("sourceDir value: " + extensions.sourceDir);
    }
}

This works, but what annoys me about this solution is that I want to be able to put the extension properties in the same namespace as the task (e.g., myPluginTask.sourceDir) which I have seen in groovy-based plugins, but this apparently is not supported or just doesn't work.
In the meantime, hope this helps someone else.

A: The code is adding an extension to a task (rather than a project), which is rarely useful. After that, it tries to set myPluginTask.sourceDir = file('the/main/src'), which isn't possible because the extension was just registered under that same name.

A: When your task and your extension have the same name, you can do this in your build.gradle:
myPluginTask.sourceDir = file('the/main/src')
project.tasks.myPluginTask.dependsOn clean


text:
Q: Extracting string based on 2 lists of integers. Python seq = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

start = [2,9,18]
end = [6,12,20]

#output = seq[end[k]:start[k+1]]

i'm trying to the sequence between end[k] and start[k+1] #seq[end[k]:start[k+1]]
so there should be 2 sequences in this case.
outp1 = seq[6:9] #'GHI'

out2 = seq[12:18] #'MNOPQR'

A: Use zip:
>>> seq = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> start = [2,9,18]
>>> end = [6,12,20]
>>> for x,y in zip(end, start[1:]):
...     print seq[x:y]
...
GHI
MNOPQR

Memory efficient version:
>>> from itertools import izip,islice
>>> for x,y in izip(end,islice(start,1,None)):
    print seq[x:y]
...
GHI
MNOPQR

A: for i in range(len(end)-1):
    seq[end[i]:start[i+1]]

answer:-
    'GHI'
    'MNOPQR'


text:
Q: PUT method is not working in front end but works in Postman Please, help me. I am doing PERN stack app, and I can't understand why my PUT method is not working in front end but works in Postman perfectly. When I add a todo - "drink water" for example, in database id appears as should "drink water" and in fron end as well it appears, but when I edit that todo  in front end it's null in database and front end as well,
looks like that: description {id: 56, todo: null}
Here is a code of EditTodo.js:

export default function EditTodo({ todo }) {
  const [description, setDescription] = useState(todo);
  console.log("todos", todo);
  console.log("description", description);
  //   Edit function
  const editText = async (id) => {
    try {
      const body = { description };
      const response = await fetch(`http://localhost:5000/todos/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      console.log("response", response);
      window.location = "/";
    } catch (error) {
      console.error(error.message);
    }
  };
  return (
    <Fragment>
      <button
        type="button"
        className="btn btn-warning"
        data-toggle="modal"
        data-target="#myModal"
      >
        Edit
      </button>

Edit Todo

              <button
                type="button"
                className="close"
                data-dismiss="modal"
              ></button>

              <input
                type="text"
                className="form-control"
                value={description.todo}
                onChange={(e) => setDescription(e.target.value)}
              />

              <button
                type="button"
                className="btn btn-warning"
                data-dismiss="modal"
                onClick={() => editText(todo.id)}
              >
                Edit
              </button>
              <button
                type="button"
                className="btn btn-danger"
                data-dismiss="modal"
              >
                Close
              </button>

    </Fragment>
  );
}

Looks like EditText function is not executed when I edit the todo.
Thanks in advance.

A: Where do you set the todo? A put request replaces the current values with new ones. If you only set the description property but leave the todo out, it will overwrite it with an empty string, clearing any data you had in there. Either set the old value of the todo before making your put request or use a patch instead. A patch only affect certain selected values instead of everything. Anyway, it's still very possible to do this with a put instead.
Try creating a useEffect where you set your todo to state.
Something like this:
    const todoVar = description.find((desc)=> desc.id === todo.id);

    useEffect(()=>{
      if(todoVar){
        setDescription(description.todo)
      }
    },[todoVar, setDescription])

Basically, you want to set the todo value from your database to it's original value before making your PUT request. This way it won't be empty/null.


text:
Q: How to retrieve image from Django through database? I am trying to have user see their photo once they login. The images already saved into the db, I just need it to appear once they login.
Here is my Models & Forms:
Models:
I am trying to have user see their photo once they login. The images already saved into the db, I just need it to appear once they login.
Here is my Models & Forms:
Models:
class UserProfileInfo(models.Model):
class UserProfileInfo(models.Model):

    # Create relationship (don't inherit from User!)
    user = models.OneToOneField(User)

    # Add any additional attributes you want
    portfolio_site = models.URLField(blank=True)
    # pip install pillow to use this!
    profile_pic = models.ImageField(upload_to='profile_pics',blank=True)

    def __str__(self):
        # Built-in attribute of django.contrib.auth.models.User !
        return self.user.username

Forms:
class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta():
        model = User
        fields = ('username','email','password')

class UserProfileInfoForm(forms.ModelForm):
    class Meta():
        model = UserProfileInfo
        fields = ('portfolio_site','profile_pic')

in Views.py:
def register(request):
    registered = False
    if request.method == 'POST':
        # Get info from "both" forms
        # It appears as one form to the user on the .html page
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)

        # Check to see both forms are valid
        if user_form.is_valid() and profile_form.is_valid():
            # Save User Form to Database
            user = user_form.save()
            # Hash the password
            user.set_password(user.password)
            # Update with Hashed password
            user.save()
            # Now we deal with the extra info!
            # Can't commit yet because we still need to manipulate
            profile = profile_form.save(commit=False)
            # Set One to One relationship between
            # UserForm and UserProfileInfoForm
            profile.user = user
            # Check if they provided a profile picture
            if 'profile_pic' in request.FILES:
                print('found it')
                # If yes, then grab it from the POST form reply
                profile.profile_pic = request.FILES['profile_pic']
            # Now save model
            profile.save()
            # Registration Successful!
            registered = True
        else:
            # One of the forms was invalid if this else gets called.
            print(user_form.errors,profile_form.errors)
    else:
        # Was not an HTTP post so we just render the forms as blank.
        user_form = UserForm()
        profile_form = UserProfileInfoForm()
    # This is the render and context dictionary to feed
    # back to the registration.html file page.
    return render(request,'basic_app/registration.html',
                          {'user_form':user_form,
                           'profile_form':profile_form,
                           'registered':registered})

A: i think you need replace:
profile_form = UserProfileInfoForm(data=request.POST)

to
profile_form = UserProfileInfoForm(request.POST, request.FILES)

more details django file-uploads


text:
Q: Reading Real data into Complex variables in Fortran using binary read and write I have a code where I have to do a great deal of file I/O and as such would like a pretty efficient way of dealing with the following problem. For the sake of convenience, my code always write to restart files only the real part, coded as follows:
OPEN(UNIT = 2, FILE = filename, STATUS = 'UNKNOWN', form = 'unformatted')
    write(2) CFL
    write(2) W
CLOSE(2)

When I run my code in the real analysis mode, reading these files is trivial:
OPEN(UNIT = 2, FILE = filename, STATUS = 'OLD', form = 'unformatted')
    read(2) CFL
    read(2) W
CLOSE(2)

But when I run in complex I have to do this somewhat clumsy hack:
open(UNIT = funit, FILE = filename, STATUS = 'old', form='unformatted')
#ifdef COMPLEX_ON
        read(funit) CFL
        read(funit) W_t
        CFL_in = CFL
        W = W_t
#else
        read(funit) CFL_in
        read(funit) W
#endif
close(funit)

This means that now I need two copies of the data, and if I use implied do-loops like I did previously, I can do this hack one entry at a time and the copy to the W array, but this is a slower way of handling the I/O. Is there a way to tell fortran I want to read real binary data into a complex variable array?
Thanks.

A: If your compiler is very up to date, or even claims to be Fortran 2008 conforming, you could use one of the least supported F2008 features and read just the real part
write(2) CFL%re
write(2) W%re

You still need the #ifdef, but you don't need another array. However, the compile may well be in need to create a temporary array anyway.
Else you could use the plain old equivalence to view the complex arrayas a real array with an extra dimension. Or storage association of procedure arguments to do the same.


text:
Q: Memory Leak when compiling angular 12 application Me and my colleague are trying to optimize our enterprise Angular 12 application.
The Problem:
Straight away, we noticed that the biggest problem about developing our application is that the memory usage is steadily increasing with each time the angular CLI recompiles the project (after pressing CTRL+S). It works fine for some time but after a few recompiles, the memory hits over 4000MB and the angular CLI crashes.
What We Tried:
After turning up the memory capacity to 24 gigabytes, we noticed that the project compiles much faster (at least two times faster). However, the memory usage will still keep increasing until it hits its cap and crashes, (of course 24 gigs of RAM is no solution anyways), so there definitively is a memory leak.
The Question:
How are we supposed to find out what exactly causes this problem? We tried lots of things, like removing all of our modules and let it recompile(with errors of course because we removed our modules) but the RAM usage still kept rising. I think the problem might come from some "random" NPM module but i am not really sure. If this helps: we are using asp.net zero boilerplate.

A: Unfortunately it's a bug of Angular 12 itself, there's an issue on Github: https://github.com/angular/angular-cli/issues/20801


text:
Q: How to validate an object before saving in Rails? I'm very new in Rails, and I have the following problem. I have this class  Url that has its own validations:
class Url
  validates :ipaddress, :format => {
    :with => Resolv::IPv4::Regex,
    :message => 'Deve ser um endereco IP valido'
  }

  validates :domain, :format => {
    :with => URI.regexp,
    :message => 'Deve ser um dominio valido'
  }
end

I have another class Link that has an Url. The validations are:
class Link
  validates :path, :format => {
    :with => /\A[\S]+\Z/,
    :message => 'Deve conter uma path valida'
  }
end

But the problem is when I run this test:
test 'test a link with a valid path' do
  link = Link.new()
  link.url = Url.new()
  link.path = 'this/is/my/favorite/path'
  assert_equal(true, link.valid?, 'Test a valid path')
end

The test says that everything is okay, but the validation of the URL is not occurring. How can I force Rails to validate the URL too?


text:
Q: "Mixed effect" ANOVA in R with JAGS/BUGS I would like to be able to code the following linear mixed model into a bayesian framework. In the traditional/frequentist view, the model would be coded like this:
# Generation of simulated data
set.seed(123)
varY <- rnorm(100, 0, 1)
facX <- gl(n = 4, k = 25, labels = c("A", "B", "C", "D"))
block <- factor(rep(x = paste("B",1:25, sep = ""), times = 4))
df <- data.frame(varY, facX, block)

# Frequentist analysis
library(lme4)
model.freq <- lmer(varY ~ facX + (1|block), data = df)

where varY is a continuous response variable, facX is a categorical predictor with 4 levels and block is a random effect. This is similar to a one-way ANOVA with a fixed effect and a random block effect.
I can work out the code for the fixed effect one-way ANOVA:
# Data reshaping
matY <- matrix(data = varY, nrow = 25, ncol = 4, byrow = FALSE)

# Model specification
model.bayes <- function(){
# Likelihood
 for(j in 1:Nlev){
  for(i in 1:N){
   varY[i,j] ~ dnorm(mu + theta[j], 1/(sig*sig))
   }
 }
theta[1] <- 0
  for(j in 2:Nlev){
   theta[j] ~ dnorm(0, 0.001)
  }
# Priors
mu ~ dnorm(0, 0.001)
sig ~ dunif(0, 1000)
}

# Bayesian analysis with JAGS
dat <- list(varY = matY, Nlev = ncol(matY), N = nrow(matY))
params <- c("mu", "theta", "sig")
inits <- function(){list(mu = rnorm(1), sig = rlnorm(1))}

library(R2jags)
out <- jags(data = dat, inits = inits, parameters.to.save = params, model.file = model.bayes, n.chains = 3, n.iter = 10000, n.burnin = 1000, n.thin = 1)

However, I don't know how to integrate the random block effect into this model. My question is: how would I integrate this block effect into the model to get a similar analysis as the frequentist one?

A: In order to include a random effect (and potentially other fixed effects) you need to format your data in long (rather than wide) format, and use nested indexing with separate vectors as indicator variables for your fixed and random effects.  The easiest way to generate this model is to use the runjags::template.jags function to create the model for you based on your lme4 model syntax:
# Generation of simulated data
set.seed(123)
varY <- rnorm(100, 0, 1)
facX <- gl(n = 4, k = 25, labels = c("A", "B", "C", "D"))
block <- factor(rep(x = paste("B",1:25, sep = ""), times = 4))
df <- data.frame(varY, facX, block)

library('runjags')
template.jags(varY ~ facX + (1|block), data = df)

You will then have a text file within your working directory that contains a fully functional JAGS model.  The important parts are within the main loop:
regression_fitted[i] <- intercept + facX_effect[facX[i]] + block_randomeffect[block[i]]

This includes the fixed effect of facX and random effect of block, both indexed using the appropriate explanatory variable.  The other part for the random effect is:
for(block_iterator in 1:25){
    block_randomeffect[block_iterator] ~ dnorm(0, block_precision)
}

Which ensures that each random effect level is normally distributed with a mean of zero and precision to be estimated, which is equivalent to your frequentist model (although remember that precision is 1/variance!).
Once you have checked/edited the model as appropriate (e.g. adjusting priors) then you can run it using:
results <- run.jags("JAGSmodel.txt")

The help file for ?template.jags contains another example of comparing a frequentist linear model to an equivalent Bayesian model, which may be of interest to you.


text:
Q: How to download tarball from Github I have this:
curl -L "https://github.com/cmtr/cp-go-api/tarball/$commit_id" | tar x -C "$project_dir/"

I am just trying to download a tarball from github and extract it to an existing directory. The problem is I am getting this error:
Step 10/13 : RUN curl -L "https://github.com/channelmeter/cp-go-api/tarball/$commit_id" | tar x -C "$project_dir/"
 ---> Running in a883449de956
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100     9  100     9    0     0     35      0 --:--:-- --:--:-- --:--:--    35
tar: This does not look like a tar archive
tar: Exiting with failure status due to previous errors
The command '/bin/sh -c curl -L "https://github.com/channelmeter/cp-go-api/tarball/$commit_id" | tar x -C "$project_dir/"' returned a non-zero code: 2

does anyone know why it's not a tar archive? If you go to github.com in the browser and put in this pattern, it will download a tar.gz archive:
https://github.com/<org>/<repo>/tarball/<sha>

so not sure why it's not working.

A: So ultimately it's because Github wants credentials. Without 2-factor auth, you can just do this with curl:
curl -u username:password https://github.com/<org>/<repo>/tarball/<sha>

but if you have 2-factor auth setup, then you need to use a Github access token, and you should use api.github.com instead of github.com, like so:
 curl -L "https://api.github.com/repos/<org>/<repo>/tarball/$commit_sha?access_token=$github_token" | tar -xz -C "$extract_dir/"

the access token thing is documented here:
https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

A: Another approach to this is to use a GitHub cookie. It still starts with the
normal user/pass, but after the initial request, you can make further requests
by utilizing the cookie. Here is example with PHP:
<?php

# GET
$get = curl_init('https://github.com/login');
curl_setopt($get, CURLOPT_COOKIEJAR, 'github.txt');
curl_setopt($get, CURLOPT_RETURNTRANSFER, true);
$log = curl_exec($get);
curl_close($get);

# POST
preg_match('/name="authenticity_token" value="([^"]*)"/', $log, $auth);
$pf['authenticity_token'] = $auth[1];
$pf['login'] = getenv('USER');
$pf['password'] = getenv('PASS');
$post = curl_init('https://github.com/session');
curl_setopt($post, CURLOPT_COOKIEFILE, 'github.txt');
curl_setopt($post, CURLOPT_POSTFIELDS, $pf);
curl_exec($post);

Then after that, you can use shell cURL with -b github.txt, or PHP cURL with
CURLOPT_COOKIEFILE github.txt. Make sure to curl_close as shown above, else
the cookie file gets created after its needed.


text:
Q: Using GNU LGPLv3 platform on back-end of a commercially-hosted solution My company is wanting to productionize a suite of drawing (CAD) and mapping solutions (GIS) as a commercial solution in a hosted environment (users would access via the web on a subscription basis).  On the back-end, we wish to implement a content/document management platform that is available under GNU LGPLv3.  It is our intent to not distribute the LGPL application nor will we expose its user interface to end-users (it will be used akin to a database for our solutions).  That said, does this usage comply with the license given that we will charge customers for our solution?  Also, as we are not modifying the LGPL platform's source code (we are accessing it programmatically only via its published web services API), are we required to make available our source code?

A: Accessing GPL or LGPL services via an API doesn't require you to make the source code of your application available, as long as you don't give the code to your customers.  See the related question here about MySQL.
If the platform was AGPL, I believe that would be a different story, as accessing an AGPL service via a network is considered as equivalent to distribution.

A: The LGPL does not prohibit commercial use. And as long as you're not distributing the software, I don't see why this should be even a question. Anyway you're merely asking for a compliance check but that can only be done by your companies lawyers, if it's an issue for them. So ask a lawyer instead, and that lawyer will ask you about the specifics of your software and then checks if it's compliant or not.


text:
Q: Code not executing in order (Firebase). Synchronization issues const signIn = async e => {
      var recaptcha = new firebase.auth.RecaptchaVerifier('recaptcha');
      var number = '+91'+mobile;
      firebase.auth().signInWithPhoneNumber(number, recaptcha).then( function(e) {
      var code = prompt('Enter the otp', '');
      if(code === null)
      {
        return false;
      }

         e.confirm(code).then(function (result) {
             console.log(result.user);

             alert("INSIDE");
             return true;

         }).catch(function (error) {
             console.error( error);

         });

     })
     .catch(function (error) {
         console.error( error);
         return false;
     });
  }

And the other function
const func1 = async e => {
alert("OUTSIDE1");
var check=await signIn();
if(check)
{
   alert("true value");
}
else
{
   alert("false value");
}

The output is always-
OUTPUT1
false value
and then the OTP code gets executed?
Can someone help to make the necessary changes to make OTP code synchronous?

A: You are not returning an appropriate promise to the caller of your async function.  You probably meant to write:
return firebase.auth().signInWithPhoneNumber(...).then(...)

Even better, since you are using async/await, just await the result of signInWithPhoneNumber inside your signIn function, and avoid the use of then()/catch() entirely.


text:
Q: Check OS version and variable for Network Label I've been using this code successfully however, looking to adjust it and use when performing netsh commands to rename NIC's - although whilst writing this i'm not sure it's the best route anymore.
SET _OSVer=OTHER
FOR /F "Tokens=2 Delims=[]" %%a IN ('VER') DO SET _VerNo=%%a
FOR /F "Tokens=2-3 Delims=. " %%b IN ("%_VerNo%") DO (
    IF "%%b.%%c" EQU "5.2" SET _OSVer=2003
    IF "%%b.%%c" EQU "6.0" SET _OSVer=2008
    IF "%%b.%%c" EQU "6.1" SET _OSVer=2008R2
    IF "%%b.%%c" EQU "6.2" SET _OSVer=2012
    IF "%%b.%%c" EQU "6.3" SET _OSVer=2012R2
)

IF "%_OSVer%" EQU "2003" (ECHO %_OSVer% )
IF "%_OSVer%" EQU "2008" (ECHO %_OSVer% )
IF "%_OSVer%" EQU "2008R2" (ECHO %_OSVer% )
IF "%_OSVer%" EQU "20012" (ECHO %_OSVer% )
IF "%_OSVer%" EQU "20012R2" (ECHO %_OSVer% )

FYI: Pre2012 network labels are Local Area Connection, 2012 is Ethernet.
I want to execute the following command
netsh interface set interface name = "%NETWORKNAME%" newname = "network-storage"  >nul 2>&1

I'm thinking based on the OSversion %NETWORKNAME% would be defined as either "Local Area Connection" or "Ethernet"
Can I use something like
  IF "%_OSVer%" EQU "2003" + "2008" + "2008R2" SET Networkname="Local Area Network"

Or is there a better way to do this?
EDIT - From Pauls Feeback, final code is
 SET NICNaming=OTHER
FOR /F "Tokens=2 Delims=[]" %%a IN ('VER') DO SET _VerNo=%%a
FOR /F "Tokens=2-3 Delims=. " %%b IN ("%_VerNo%") DO (
    IF "%%b.%%c" LEQ  "6.1" SET NICNaming=Local Area Connection
    IF "%%b.%%c" GEQ  "6.2" SET NICNaming=Ethernet

)

ECHO %NICNaming%

netsh interface set interface name = "%NICNaming%" newname = "network-storage"  >nul 2>&1
if %errorlevel%== 0 (Echo found) ELSE (Echo missing abort)

Thanks
B

A: There are a valuable answer for such thing.
If I had to adapt, it would be like this:
@echo off
setlocal
GOTO CHKVERS

:action
rem action
SET "Networkname=Local Area Network"
GOTO:EOF

:CHKVERS
for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" == "6.3" goto action &REM Windows 8.1
if "%version%" == "6.2" goto action &REM Windows 8.
if "%version%" == "6.1" goto action &REM Windows 7.
if "%version%" == "6.0" goto action &REM Windows Vista.

echo Version undetermined, please contact an administrator.

endlocal
exit /b 0

You may also like:
IF "%A%"=="1" IF "%B%"=="1" IF "%C%"=="1" GOTO YES
GOTO NO

You may use GEQ and LEQ
IF "%version%" GEQ "6.0" IF "%version%" LEQ "6.3" GOTO YES
GOTO NO

EQU : Equal
NEQ : Not equal
LSS : Less than <
LEQ : Less than or Equal <=
GTR : Greater than >
GEQ : Greater than or equal >=
This 3 digit syntax is necessary because the > and < symbols are recognised as redirection operators

http://ss64.com/nt/if.html


text:
Q: How to check input values present in array or not using inArray in Jquery I have array like below.
var myArray = [];
myArray = [70, 68, 64, 29, 1, 44, 39, 31, 26];

I need to check if any given number is in above array or not

A: You can use .indexOf() for that
if(myArray.indexOf(number) > -1){
    alert(number+" exists !!!");
}

Demo
Using Jquery
 if($.inArray(number, myArray)>-1){
       alert(number+" exists !!!");
 }

Demo using inArray()

A: -------1.---------
for(var i=0; i<myArray.length; i++) {
   if(number==myArray[i]) {
       //process
       break;
   }
 }

-------2.---------
if(myArray.indexOf(number) > -1) {
      //process
}


text:
Q:  va dentro de  o al reves? Estoy viendo que mucha gente pone el section dentro del article o al reves y a veces ponen el section y el article no, A que se debe. Pd: Soy nuevo.

       lfsdjkfjkjdf
       sdfisdfjlsdf

    </section

A: Se puede de las dos maneras, esto dependiendo de la estructura de la web.
Pueden ir juntos, uno dentro de otro y viceversa e incluso por separado.
El section nada más define una sección del documento.
El articulo, especifica un contenido independiente o autónomo.

A: De forma primaria partimos que ambas son elementos de bloque por lo cual la una puede contener a la otra....
Sin embargo
El sentido semántico es el que debe tener mayor relevancia a la hora de identificar si se puede o no, dicho lo anterior revisemos.
De acuerdo con la especificación de dichas etiquetas ambas son:

*

*Etiquetas de seccionadoras

Una etiqueta section
Por si misma representa dentro de un sitio web elementos tales como:

*

*Información de contacto

*Elementos noticias

*Introducción

Mientras que una etiqueta article sirve para identificar dentro de un sitio web:

*

*Aquel contenido que pueda ser sindicado y que dicho eso sirve indexar para hacerlo accesible  e identificable al usuario

*Contenido que es reusable

*Contenido de una naturaleza independiente, tales como:

*

*Entradas de blog

*Un artículo de una revista

*etc.

Ahora por ejemplo aunque un section pueda tener incluidos dentro múltiples articles con contenido de naturaleza independiente como los anteriormente listados incluso estos a su vez pueden tener mas etiquetas article anidadas dentro de ellas; es decir un article con articles internos anidados.

Entonces...
Aunque el navegador de forma explícita no te va a mostrar un error si haces el acomodo que tu decidas, dada la naturaleza de uso de cada una entonces hace mas sentido:
Edito pues me equivoqué en la idea expuesta
Que un article contenga elementos section dentro de si tantos como la estructura ocupe y sean necesarios ya que el del contenido que será indexado es el primero mencionado


text:
Q: Can one use a current transformer with turns ratio of 100:5A instead of 100:1A? There is an MV switchgear with a rated current of 100 amps. knowing that a CT with 5 amperes secondary rated current is cheaper than a 1 amperes secondary rated current. In order to cut costs I chose a CT with 100:5 amps instead of a CT with a turns ratio of 100:1 amps.
My question, when is it preferred to use CT of 100:1 turns ratio instead of a cheaper 100:5 amps?
Is there a criteria for selecting the secondary rated current to be 5 instead of 1?

A:
My question, when is it preferred to use CT of 100:1 turns ratio instead of a cheaper 100:5 amps?

*

*When the meter has a full-scale of 1 A then you need a 100:1 CT so that you don't destroy the meter when the primary current goes over 20 A.

*When the protection circuit has a full-scale of 1 A the 100:5 CT will cause it to trip at 20 A.

*The VA rating of the CT must not be exceeded. If, for example, it's rated at 5 VA then the 5 A CT max burden is \$ R = \frac P {I^2} = \frac 5 {25} = 0.2 \ \Omega \$ whereas the 1 A CT has a max burden of \$ R = \frac 5 1 = 5 \ \Omega \$. This is probably the only thing that won't be a problem.

Is there a criteria for selecting the secondary rated current to be 5 instead of 1?

Yes, it has to match whatever it is driving - either metering or protection equipment.

From the comments:

For a relay CT, the ratio of the CT say it's 100:1. Does this mean that at 100 Amperes on the primary the relay would operate to trip the CB? or is the 100 Amps is the normal condition current and the tripping current is much higher?

The circuit breaker will have an actual trip setting of 5 A. If you use a 100:5 CT it will trip at 100 A primary current. If you put 3 primary turns through the  CT the CB will trip at 33.3 A primary current.
If you use a 100:1 transformer it will only put out 1 A and the 5 A trip on the CB will not be activated at 100 A. This will cause your protection circuit to fail.
Note: SI units named after a person have their symbols capitalised but are lowercase when spelled out. 'V' for volt, 'A' for ampere, 'K' for kelvin, 'Ω' (capital omega) for ohm, etc. Meanwhile 'k' is for kilo.
Capitals matter.


text:
Q: Integration test with clause 'in' in sql cause error when run individuallly I have an integration (h2, spock, grails-2.5.5) tests that running inside a sql (gorm) consult.
This test works fine when running all tests together "grails test-app", but when i'm running individually the test broken and show me the following error:
count_subscriber_brands subscriber6_ on br2_.id=subscriber6_.brand_id left outer join account_subscriber brs3_ on subscriber6_.account_subscriber_id=brs3_.id left outer join account brs3_1_ on brs3_.id=brs3_1_.id left outer join product_subscriber_publish sp1_ on this_.id=sp1_.product_id where this_.gtin=? and ((sp1_.subscriber_id=? and sp1_.is_published=?) or (this_.status in (?, ?) and ((br2_.exclusive=? and brs3_.id=?) or br2_.exclusive is null or br2_.exclusive=?))) [22018-176]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:344)
    at org.h2.message.DbException.get(DbException.java:167)
    at org.h2.value.Value.convertTo(Value.java:902)
    at org.h2.expression.ConditionIn.getValue(ConditionIn.java:57)
    at org.h2.expression.ConditionAndOr.getValue(ConditionAndOr.java:87)
    at org.h2.expression.ConditionAndOr.getValue(ConditionAndOr.java:110)
    at org.h2.expression.ConditionAndOr.getValue(ConditionAndOr.java:94)
    at org.h2.expression.Expression.getBooleanValue(Expression.java:179)
    at org.h2.command.dml.Select.queryFlat(Select.java:535)
    at org.h2.command.dml.Select.queryWithoutCache(Select.java:646)
    at org.h2.command.dml.Query.query(Query.java:323)
    at org.h2.command.dml.Query.query(Query.java:291)
    at org.h2.command.dml.Query.query(Query.java:37)
    at org.h2.command.CommandContainer.query(CommandContainer.java:91)
    at org.h2.command.Command.executeQuery(Command.java:197)
    at org.h2.jdbc.JdbcPreparedStatement.executeQuery(JdbcPreparedStatement.java:109)
    ... 7 more
Caused by: java.lang.NumberFormatException: For input string: "INACTIVATED"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at org.h2.value.Value.convertTo(Value.java:852)
    ... 20 more

gorm clause contains 'in'('status', [FINE, WORK, INACTIVATED])
When i run individually the tests works fine too


text:
Q: Open folder vs create new project from existing files, located under shared network drive in PhpStorm It's not clear to my why I should use the option in PhpStorm to create a new project from existing files instead of just opening a folder and declaring the project directory.
I have a web server installed and I can access it's root by a shared network drive. Now I can just open the a folder in PhpStorm and declare it's root. It will generate a PhpStorm project at the given directory.
But there is also an option to open a new project from existing files (located under shared network drive). My best guess is that this option is the way to go. Is this true and if so, why? Or if it doesn't matter, why doesn't it?
There will be several people using the same shared drive to work in different projects in the webroot.

A: You can, of course, create a project on mounted network drive via File/Open, but note that this is not officially supported. All IDE functionality is based on the index of the project files which PHPStorm builds when the project is loaded and updates on the fly as you edit your code. To provide efficient coding assistance, PHPStorm needs to re-index code fast, which requires fast access to project files and caches storage. The latter can be ensured only for local files, that is, files that are stored on you hard disk and are accessible through the file system. Sure, mounts are typically in the fast network, but one day some hiccup happen and a user sends a stacktrace and all we see in it is blocking I/O call.
So, the suggested approach is downloading files to your local drive and use deployment configuiration to synchronize local files with remote. See https://confluence.jetbrains.com/display/PhpStorm/Sync+changes+and+automatic+upload+to+a+deployment+server+in+PhpStorm


text:
Q: Django REST Framework pagination: Not found: GET /api/blog/list HTTP/1.1" 404 0 I am trying to implement simple pagination using Django rest frame work. But I am getting Status 404 Not Found in Postman.
Custom urls.py included from base urls.py
Base urls.py
urlpatterns = [
...
    path('api/blog/', include('item.api.urls', 'item-api-name')),
...

url.py used in include() mentioned above
from django.urls import path

from item.api.views import (
    api_detail_item_view,
    api_create_item_view,
    ApiBlogListView
)

app_name = 'item'
urlpatterns = [
    path('<slug_from_api_url>', api_detail_item_view, name="item_detail_api"),
    path('create_api/', api_create_item_view, name="item_create_api"),
    path('list', ApiBlogListView.as_view(), name="list"),

]

serializers.py file:
from rest_framework import serializers
from item.models import ItemMaint

class ItemMaintSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemMaint
        fields = ['name', 'itemDescription', 'active', 'slug']

views.py file:
class ApiBlogListView(ListAPIView):
    queryset = ItemMaint.objects.all()
    serializer_class = ItemMaintSerializer
    pagination_class = PageNumberPagination

Settings.py file
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 1,
}

Thanks in advance.

A: Appended / in the custom urls.py file.
Changed from
 path('list', ApiBlogListView.as_view(), name="list"),

to
 path('list/', ApiBlogListView.as_view(), name="list"),


text:
Q: Azure Notification Hub Not Reflecting on Portal after Installation with .net Backend I am trying to register an app using .NET Backend Installation method. The method is executed successfully but the Active Device Registered is not getting updated on the azure portal.
But when I am executing GetAllRegistrationsAsync method, it is showing the new installed device. Can anyone help on this?

Installation Method on the backend (C#)

public async Task CreateOrUpdateInstallation(DeviceInstallation deviceInstallation)
{
    Installation installation = new Installation();
    installation.InstallationId = deviceInstallation.InstallationId;
    installation.PushChannel = deviceInstallation.PushChannel;
    installation.Platform = NotificationPlatform.Gcm;
    await hub.CreateOrUpdateInstallationAsync(installation);
}

Get all Registrations Method

var allRegistrations = await hub.GetAllRegistrationsAsync(0);

Active Device Registered on the Azure Portal

A: Normally Azure portal does not update "Active devices registered" on realtime basis rather it takes upto 24 hrs to show them. You may try after 24 hrs and you will get the devices if properly registered.