text:
Q: Only One table in Sql-server 2008R2 Database working slow while accessing with ADODB ODBC connection Only One table in Sql-server 2008R2 Database working slow while accessing with ADODB ODBC connection. Table has properly defined clustered primary key. The only thing is table has 60 columns and 50000 rows.
But even other bigger tables are working with better speed. The select statement is working very fast in management studio editor.

A: SSMS has a peculiar way of working : session parameters are not the same and it uses firehose cursors that do not need to have the last row to display the data.
Give the exact query done and the table structure please to help you.

A: You may try this class I wrote
Option Explicit
'//////////////////////////////////////////////////////////////////////////////
'@@summary
'@@require
'---Class:CHashTable.cls
'---Import:Microsoft ActiveX Data Objects 2.8 Library
'@@reference
'@@license
'@@author sunsoft
'@@create
'@@modify
'---20160812:create this class
'//////////////////////////////////////////////////////////////////////////////

'//////////////////////////////////////////////////////////////////////////////
'//
'//      Public Declare
'//
'//////////////////////////////////////////////////////////////////////////////

'------------------------------------------------------------------------------
'       Interface
'------------------------------------------------------------------------------

'------------------------------------------------------------------------------
'       Public Const
'------------------------------------------------------------------------------

'------------------------------------------------------------------------------
'       Public DataType
'------------------------------------------------------------------------------

'------------------------------------------------------------------------------
'       Public Variable
'------------------------------------------------------------------------------

'------------------------------------------------------------------------------
'       Public API
'------------------------------------------------------------------------------

'------------------------------------------------------------------------------
'       Event Declare
'------------------------------------------------------------------------------

'//////////////////////////////////////////////////////////////////////////////
'//
'//      Private Declare
'//
'//////////////////////////////////////////////////////////////////////////////

'------------------------------------------------------------------------------
'       Private Const
'------------------------------------------------------------------------------

'------------------------------------------------------------------------------
'       Private DataType
'------------------------------------------------------------------------------

'------------------------------------------------------------------------------
'       Private Variable
'------------------------------------------------------------------------------
Private m_Conn       As ADODB.Connection

Private m_Command    As ADODB.Command

Private m_ConnString As String

Private m_FilePath   As String

Private m_AutoConnect As Boolean

'------------------------------------------------------------------------------
'       Property Variable
'------------------------------------------------------------------------------

'------------------------------------------------------------------------------
'       Private API
'------------------------------------------------------------------------------

'//////////////////////////////////////////////////////////////////////////////
'//
'//      Class
'//
'//////////////////////////////////////////////////////////////////////////////

'------------------------------------------------------------------------------
'       Initialize
'------------------------------------------------------------------------------
Private Sub Class_Initialize()
  m_ConnString = ""
  m_FilePath = ""
  m_AutoConnect = True
End Sub

'------------------------------------------------------------------------------
'       Terminate
'------------------------------------------------------------------------------
Private Sub Class_Terminate()
  Set m_Conn = Nothing
  Set m_Command = Nothing
End Sub

'//////////////////////////////////////////////////////////////////////////////
'//
'//      Events
'//
'//////////////////////////////////////////////////////////////////////////////

'//////////////////////////////////////////////////////////////////////////////
'//
'//      Private Property
'//
'//////////////////////////////////////////////////////////////////////////////

'//////////////////////////////////////////////////////////////////////////////
'//
'//      Private Methods
'//
'//////////////////////////////////////////////////////////////////////////////

Private Sub OpenConn()
  Set m_Conn = New ADODB.Connection
  m_Conn.CursorLocation = adUseClient
  m_Conn.Open ConnectionString
End Sub

Private Sub CloseConn()
  m_Conn.Close
  Set m_Conn = Nothing
End Sub

Private Function m_ApostropheCount(ByVal SQL As String) As Long
'count number of "'"
  m_ApostropheCount = Len(SQL) - Len(Replace(SQL, "'", ""))
End Function

Private Function m_ProcessNameParams(mSQL As String, mDic As CHashTable, mParams() As Variant) As Boolean
  Dim mNewSql As String, mWord As String, mFieldName As String
  Dim mParamCount As Long, i As Long, comaCount As Long
  Dim mBeginParam As Boolean

  If m_ApostropheCount(mSQL) Mod 2 = 1 Then
    Err.Raise 110000000, "Symbal "" '"" must be in pairs,please check SQL statement"
  End If

  'init mDic
  mBeginParam = False
  mFieldName = ""
  mParamCount = 0

  For i = 1 To Len(mSQL)
    mWord = Mid(mSQL, i, 1)
    Select Case mWord
      Case " ", ",", ")"
        mNewSql = mNewSql & mWord
        If mBeginParam Then
          ReDim Preserve mParams(mParamCount)
          mParams(mParamCount) = mDic.Item(mFieldName)
          mFieldName = ""
          mParamCount = mParamCount + 1
        End If
        mBeginParam = False
      Case "'"
        comaCount = comaCount + 1
        mNewSql = mNewSql & mWord
      Case "@"
        If comaCount Mod 2 = 0 Then
          mBeginParam = True
          mNewSql = mNewSql & "?"
        Else
          'odd number of "'" means that "@" is only string of content
          mNewSql = mNewSql & mWord
        End If
      Case Else
        If mBeginParam = False Then
          mNewSql = mNewSql & mWord
        Else
          mFieldName = mFieldName & mWord
        End If
    End Select
  Next i
  'all done but check last word for that last word maybe param
  If mFieldName <> "" Then
    ReDim Preserve mParams(mParamCount)
    mParams(mParamCount) = mDic.Item(mFieldName)
    mFieldName = ""
  End If
  'return
  mSQL = mNewSql
  m_ProcessNameParams = True
End Function

Private Function m_GetVarType(ByRef Value As Variant) As ADODB.DataTypeEnum
  Select Case VarType(Value)
    Case VbVarType.vbString
      m_GetVarType = ADODB.DataTypeEnum.adVarWChar
    Case VbVarType.vbInteger
      m_GetVarType = ADODB.DataTypeEnum.adSmallInt
    Case VbVarType.vbBoolean
      m_GetVarType = ADODB.DataTypeEnum.adBoolean
    Case VbVarType.vbCurrency
      m_GetVarType = ADODB.DataTypeEnum.adCurrency
    Case VbVarType.vbDate
      m_GetVarType = ADODB.DataTypeEnum.adDate
    Case 8209
      m_GetVarType = ADODB.DataTypeEnum.adLongVarBinary
    Case Else
      m_GetVarType = ADODB.DataTypeEnum.adVariant
  End Select
End Function

'//////////////////////////////////////////////////////////////////////////////
'//
'//      Inherit
'//
'//////////////////////////////////////////////////////////////////////////////

'//////////////////////////////////////////////////////////////////////////////
'//
'//      Public Property
'//
'//////////////////////////////////////////////////////////////////////////////
Public Property Get ConnectionString() As String
  ConnectionString = m_ConnString
End Property

Public Property Let ConnectionString(ByVal vNewValue As String)
  m_ConnString = vNewValue
End Property

Public Property Get IsReady() As Boolean
  IsReady = IIf(Len(ConnectionString) > 0, True, False)
End Property

'//////////////////////////////////////////////////////////////////////////////
'//
'//      Public Methods
'//
'//////////////////////////////////////////////////////////////////////////////
'---------------------Data Base Connection
Public Function DbConnFromFile(ByVal filePath As String) As ADODB.Connection
  Dim mConn As New ADODB.Connection

  mConn.CursorLocation = adUseClient
  mConn.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";"
  Set DbConnFromFile = mConn
End Function

Public Sub SetConnToFile(ByVal filePath As String)
  m_ConnString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";"
End Sub

Public Sub SetConnToAccdb(ByVal filePath As String)
  m_ConnString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Persist Security Info=False"
End Sub

Public Sub OpenDB()
  m_AutoConnect = False
  Call OpenConn
End Sub

Public Sub CloseDB()
  m_AutoConnect = True
  Call CloseConn
End Sub
'---------------------Querys
Public Function ExecQuery(ByVal SQL As String) As ADODB.Recordset
  Dim mRes As New ADODB.Recordset

  Set m_Command = New ADODB.Command
  If m_AutoConnect Then
    Call OpenConn
  End If
  m_Command.ActiveConnection = m_Conn
  m_Command.CommandText = SQL
  Set mRes = m_Command.Execute()
  'disconnect from database
  mRes.ActiveConnection = Nothing
  If m_AutoConnect Then
    Call CloseConn
  End If
  Set ExecQuery = mRes
  Set m_Command = Nothing
End Function

Public Function ExecParamQuery(ByVal SQL As String, _
                               ParamArray Params()) As ADODB.Recordset
  Dim mRes As ADODB.Recordset
  Dim mParamArr As Variant, mParam As Variant
  Dim i As Long

  Set m_Command = New ADODB.Command

  If m_AutoConnect Then
    Call OpenConn
  End If
  m_Command.ActiveConnection = m_Conn
  m_Command.CommandText = SQL
  m_Command.CommandType = adCmdText

  mParamArr = Params
  If VarType(Params(0)) = 8204 Then
    mParamArr = Params(0)
  End If

  With m_Command
    For Each mParam In mParamArr
      Dim Para As ADODB.Parameter

      Set Para = .CreateParameter(CStr(i), m_GetVarType(mParam), adParamInput, LenB(mParam))
      Para.Value = mParam
      If VarType(mParam) = vbEmpty Then
        Para.size = 1
      ElseIf VarType(mParam) = vbString Then
        If LenB(mParam) = 0 Then
          Para.size = 1
        End If
      End If
      .Parameters.Append Para
    Next
  End With

  Set mRes = m_Command.Execute()
  mRes.ActiveConnection = Nothing
  If m_AutoConnect Then
    Call CloseConn
  End If
  Set ExecParamQuery = mRes
  Set m_Command = Nothing
End Function

Public Function ExecNamedQuery(ByVal SQL As String, HashedParams As CHashTable) As ADODB.Recordset
  Dim mParams() As Variant
  m_ProcessNameParams SQL, HashedParams, mParams
  Set ExecNamedQuery = ExecParamQuery(SQL, mParams)
End Function

Public Function ExecNonQuery(ByVal SQL As String) As Long
  Dim affectedRows As Long

  Set m_Command = New ADODB.Command
  If m_AutoConnect Then
    Call OpenConn
  End If
  m_Command.ActiveConnection = m_Conn
  m_Command.CommandText = SQL
  m_Command.CommandType = adCmdText
  m_Command.Execute affectedRows
  If m_AutoConnect Then
    Call CloseConn
  End If
  Set m_Command = Nothing
  ExecNonQuery = affectedRows
End Function

Public Function ExecParamNonQuery(ByVal SQL As String, ParamArray Params()) As Long
  Dim i As Long, affectedRows As Long
  Dim mParamArr As Variant, mParam As Variant

  Set m_Command = New ADODB.Command
  If m_AutoConnect Then
    Call OpenConn
  End If
  m_Command.ActiveConnection = m_Conn
  m_Command.CommandText = SQL
  m_Command.CommandType = adCmdText
  mParamArr = Params
  If VarType(Params(0)) = 8204 Then
    mParamArr = Params(0)
  End If
  With m_Command
    For Each mParam In mParamArr
      Dim Para As ADODB.Parameter

      Set Para = .CreateParameter(CStr(i), m_GetVarType(mParam), adParamInput, LenB(mParam))
      Para.Value = mParam
      If VarType(mParam) = vbEmpty Then
        Para.size = 1
      ElseIf VarType(mParam) = vbString Then
        If LenB(mParam) = 0 Then
          Para.size = 1
        End If
      End If
      .Parameters.Append Para
    Next
  End With

  m_Command.Execute affectedRows
  If m_AutoConnect Then
    Call CloseConn
  End If
  Set m_Command = Nothing
  ExecParamNonQuery = affectedRows
End Function

Public Function ExecNamedNonQuery(ByVal SQL As String, HashedParams As CHashTable) As Long
  Dim mParams() As Variant
  m_ProcessNameParams SQL, HashedParams, mParams
  ExecNamedNonQuery = ExecParamNonQuery(SQL, mParams)
End Function

Public Function ExecCreate(ByVal SQL As String) As Variant
  Dim mRes As ADODB.Recordset

  Set m_Command = New ADODB.Command
  If m_AutoConnect Then
    Call OpenConn
  End If
  m_Command.ActiveConnection = m_Conn
  m_Command.CommandText = SQL
  m_Command.CommandType = adCmdText
  m_Command.Execute

  m_Command.CommandText = "SELECT @@identity"
  Set mRes = m_Command.Execute
  If mRes.RecordCount > 0 Then
    ExecCreate = mRes.Fields(0).Value
  Else
    ExecCreate = Empty
  End If
  If m_AutoConnect Then
    Call CloseConn
  End If
  Set m_Command = Nothing
  Set mRes = Nothing
End Function

Public Function ExecParamCreate(ByVal SQL As String, ParamArray Params()) As Variant
  Dim mParamArr As Variant, mParam As Variant
  Dim mRes As ADODB.Recordset
  Dim i As Long

  Set m_Command = New ADODB.Command
  If m_AutoConnect Then
    Call OpenConn
  End If
  m_Command.ActiveConnection = m_Conn
  m_Command.CommandText = SQL
  m_Command.CommandType = adCmdText
  mParamArr = Params
  If VarType(Params(0)) = 8204 Then
    mParamArr = Params(0)
  End If
  With m_Command
    For Each mParam In mParamArr
      Dim Para As ADODB.Parameter

      Set Para = .CreateParameter(CStr(i), m_GetVarType(mParam), adParamInput, LenB(mParam))
      Para.Value = mParam
      If VarType(mParam) = vbEmpty Then
        Para.size = 1
      ElseIf VarType(mParam) = vbString Then
        If LenB(mParam) = 0 Then
          Para.size = 1
        End If
      End If
      .Parameters.Append Para
    Next
  End With

  m_Command.Execute
  m_Command.CommandText = "SELECT @@identity"
  Set mRes = m_Command.Execute
  If mRes.RecordCount > 0 Then
    ExecParamCreate = mRes.Fields(0).Value
  Else
    ExecParamCreate = Empty
  End If
  If m_AutoConnect Then
    Call CloseConn
  End If
  Set m_Command = Nothing
  Set mRes = Nothing
End Function

Public Function ExecNamedCreate(ByVal SQL As String, HashedParams As CHashTable) As Variant
  Dim mParams() As Variant
  m_ProcessNameParams SQL, HashedParams, mParams
  ExecNamedCreate = ExecParamCreate(SQL, mParams)
End Function

Public Function ExecScalar(ByVal SQL As String) As Variant
  Dim mRes As ADODB.Recordset

  Set mRes = ExecQuery(SQL)
  If mRes.RecordCount <= 0 Then
    ExecScalar = Empty
  Else
    ExecScalar = mRes.Fields(0).Value
  End If
  Set mRes = Nothing
End Function

Public Function ExecParamScalar(ByVal SQL As String, _
                                     ParamArray Params()) As Variant
  Dim mRes As ADODB.Recordset

  If VarType(Params(0)) = 8204 Then
    Params = Params(0)
  End If

  Set mRes = ExecParamQuery(SQL, Params)
  If mRes.RecordCount <= 0 Then
    Set ExecParamScalar = Nothing
  Else
    ExecParamScalar = mRes.Fields(0).Value
  End If
  Set mRes = Nothing
End Function

Public Function ExecNamedScalar(ByVal SQL As String, HashedParams As CHashTable) As Variant
  Dim mParams() As Variant
  m_ProcessNameParams SQL, HashedParams, mParams
  ExecNamedScalar = ExecParamScalar(SQL, mParams)
End Function

'---------------------Table Structure
Public Function Tables() As ADODB.Recordset
  Dim mRes As ADODB.Recordset
  If m_AutoConnect Then
    Call OpenConn
  End If
  Set mRes = m_Conn.OpenSchema(adSchemaTables)
  mRes.ActiveConnection = Nothing
  If m_AutoConnect Then
    Call CloseConn
  End If
  Set Tables = mRes
End Function

Public Function UserTables() As ADODB.Recordset
  Dim mRes As ADODB.Recordset
  If m_AutoConnect Then
    Call OpenConn
  End If
  Set mRes = m_Conn.OpenSchema(adSchemaTables)
  mRes.Filter = "table_type = 'TABLE'"
  mRes.ActiveConnection = Nothing
  If m_AutoConnect Then
    Call CloseConn
  End If
  Set UserTables = mRes
End Function

Public Function Fields(ByVal TableName As String) As ADODB.Recordset
  Dim mRes As ADODB.Recordset
  If m_AutoConnect Then
    Call OpenConn
  End If
  Set mRes = m_Conn.OpenSchema(adSchemaColumns)
  mRes.Filter = "table_name = '" & TableName & "'"
  mRes.Sort = "ORDINAL_POSITION ASC"
  mRes.ActiveConnection = Nothing
  If m_AutoConnect Then
    Call CloseConn
  End If
  Set Fields = mRes
End Function

Public Function KeyField(ByVal TableName As String) As String
  Dim mRes As ADODB.Recordset
  Dim mKeyFieldName As String
  If m_AutoConnect Then
    Call OpenConn
  End If
  Set mRes = m_Conn.OpenSchema(adSchemaPrimaryKeys)
  mRes.Filter = "table_name = '" & TableName & "'"
  mRes.ActiveConnection = Nothing
  If m_AutoConnect Then
    Call CloseConn
  End If
  If mRes.RecordCount > 0 Then
    mRes.MoveFirst
    Do While Not mRes.EOF
      If mRes.Fields("column_name").Value <> "" Then
        mKeyFieldName = mRes.Fields("column_name").Value
        Exit Do
      End If
    Loop
  End If
  KeyField = mKeyFieldName
End Function

Public Sub ReleaseRecordset(res As ADODB.Recordset)
  Set res = Nothing
End Sub


text:
Q: How to control a dynamic checkbox in reactjs I have 2 arrays say Array1 and Array2. Where Array2 is some subset of Array1. Now I am creating checkbox of all the items present in array1 and I want the ones to be checked which are present in array2. I hope you understand my problem and suggest me what I can do.

A: You may try the following snippet,
return (

Your Checklist Items:

            {array1.map((item, index) => (

                    <input
                        value={item}
                        type="checkbox"
                        checked={array2.includes(item) ? "checked" : "unchecked"}
                    />
                    {item}

            ))}

);

A: Firstly you need a state holding two arrays (or at least one, that will be controled by checkboxes).
this.state = {
    a: [11,22,33,44,55,66,77,88,99],
    b: [22,44,66,88],
}

Secondly you need handler for change of that array when checkbox is changed.
handleChange(e, number) {
    this.setState(prevState => {
        const index = prevState.b.indexOf(number);
        if(index >= 0){
            prevState.b.splice(index, 1);
        } else {
            prevState.b.push(number)
        }
        return { b: prevState.b }
    })
}

Lastly you need to render checkboxes and control them with state.
render() {
    return(

            {this.state.a.map((item, index) => (

                    {item + " "}
                    <input
                        checked = { this.state.b.includes(item) }
                        onChange = { e => { this.handleChange(e, item) } }
                        type = "checkbox"
                        />

            ))}

    )}
}

Full demo here: http://jsfiddle.net/nogare/76spduct/

redpajama_set_name: RedPajamaStackExchange


text: Q: Installation of Pyobject in windows 10 Anaconda environment. I am trying to use gstreamer with my Anaconda environment on Windows 10 machine. I get gstreamer successfully installed on my machine. The version of Gstreamer is 1.13, the latest for windows. But now I want to use it through Python IDE. But as my machine does not have installed Pyobject ,it throws error like no module named gi.I have used pip install, downloaded the zip file and then run python setup.py install and also through conda install command, but nothing works. How can I install pyobject and pygst on Anaconda environment ?


text:
Q: Tag suggestion: [icon-fonts] I recently made a question regarding icon-fonts and there were no icon-fonts tag.
icon-fonts is the new way to embed small images in webpages.
Google returns about 29M pages with that keyword: https://www.google.com/search?q=icon-fonts
Should we add an icon-fonts tag?

A: The icon-fonts tag has just been created.
Now off you go and suggest a great tag wiki & excerpt :-)


text:
Q: Privacy violation in c# We are using the HPFortify demand to verify the security finding in my application. I got some privacy violation issues in my application but i didn't understand how to fix this.
 public void Info(LogMessage message)
        {
            SetContextProperties(message, LogLevelEnum.Info);
            log.Info(message);
        }

 private void SetContextProperties(LogMessage message, LogLevelEnum level)
        {
            if (message.Title == string.Empty) throw new ArgumentException("Title");
            if (message.LogSource == string.Empty) throw new ArgumentException("LogSource");
            if (message.Message == string.Empty) throw new ArgumentException("Message");

            ThreadContext.Properties["LogType"] = (int)level;
            ThreadContext.Properties["LogSource"] = message.LogSource ?? logSource;
            ThreadContext.Properties["UserName"] = message.UserName;
            ThreadContext.Properties["LogTitle"] = message.Title;
            ThreadContext.Properties["LogMessage"] = message.Message;
            ThreadContext.Properties["ServerName"] = message.ServerName;
            ThreadContext.Properties["IPAddress"] = message.IPAddress;
            ThreadContext.Properties["SessionId"] = message.SessionId;
        }

can anyone explain me what is the privacy violation in the above code and how to fix ?


text:
Q: scrapy error when crawling over a link I have a problem which is IndentationError: unexpected indent
the code is working good on shell but not on code.

A: You are getting Indentation Error because you are mixing tabs or spaces anywhere in file. So you should convert all tabs to 4 spaces
or
If you want you can use tabs only but don't mix with spaces or else you will get Indentation Error again.
Also you said you keep mixing spaces and tabs so i advice you to enable showing Invisible characters so that you know you aren't mixing tabs and spaces.
In Notepad++ you can do that by :
View->Show Symbol->Show All Characters

or

View->Show Symbol->Show White Space and Tab

If you use Sublime Text 2, you can do this:
Go to Preferences -> Settings- default
Change
"draw_white_space": "selection"

 to

 "draw_white_space":"all"


text:
Q: Returning an array of strings and assigning it to a variable in C So the problem I am facing is the following:
On one component, I read file names and store them in an array. There can be a maximum of 100 names of maximum 20 characters in length. This is defined as follows:
static Char_t fileList[100][20] = {};

where
fileList[1]= "name1"
fileList[2]= "name2"  and so on.

By creating a function that returns a pointer to it I want to have access to this array of strings from another component of my code:
Char_t** getAllFiles(void)
{
    return &fileList;
}

And I assign the pointer like this:
Char_t **fileList = getAllFiles();

This does not seem to work. The best I have achieved is to get the pointer to the first component of the array. But I cannot get the rest of the components.

A: One simple option is to use pointer to array return type.
Here is a reproducible example:
#include <stdio.h>

char (*getAllFiles())[];

int main(void)
{
    char (*str_array)[20] = getAllFiles();
    printf("%s %s", str_array[0], str_array[1]); //test print
}

char (*getAllFiles())[]
{
    static char fileList[100][20] = {"name1", "name2"};
    return fileList;
}

If you don't want/need to use static storage, you can use the same type but with memory allocation, this will allow you to free the memory reserved for your array when you no longer need it. Note that using static storage can have its disadvantages as @RobertS supports Monica Cellio pointed out.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char (*getAllFiles())[];

int main(void)
{
    char (*str_array)[20] = getAllFiles();
    printf("%s %s", str_array[0], str_array[1]); //test print
    free(str_array); //free the allocated memory after it's used
}

char (*getAllFiles())[]
{
    //allocating space for an array of type char, which is always 1 byte,
    //you must allocate memory according to the array type
    //for instance malloc(sizeof(Char_t) * 100 * 20);
    char (*fileList)[20] = malloc(100 * 20);

    strcpy(fileList[0], "name1");
    strcpy(fileList[1], "name2");

    return fileList;
}

Output in both cases:
name1 name2

A: Probably the better way is to allocate the array dynamically, because you are able to deallocate the array after it isn´t needed anymore.
To point to function-local objects from outside of the function is also considered as "bad practice", because it is f.e. not thread-safe.
In detail, allocate an array of 20 pointer to Char_t first and assign it to **fileList. Then allocate memory of 100 Char_t for each pointer.
Return fileList and assign it to a pointer to pointer to Char_t in the caller.
After that you can simply use file_list[i] to access the specific strings.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char** getAllFiles (void);

typedef char Char_t;

int main (void)
{
    Char_t** file_list = getAllFiles();

    printf("%s\n", file_list[0]);
    printf("%s", file_list[1]);

    for (int i = 0; i < 20; i++)
    {
        free(file_list[i]);     // deallocate pseudo-rows of 100 Char_t.
    }

    free(file_list);            // deallocate pointer array.

}

char** getAllFiles (void)
{
    Char_t** fileList = malloc (sizeof (*fileList) * 20);

    for (int i; i < 20; i++)
    {
        fileList[i] = malloc (sizeof (**fileList) * 100);
    }

    strcpy(fileList[0], "name1");
    strcpy(fileList[1], "name2");

    return fileList;
}

Output:
name1
name2


text:
Q: How effectively to change JSON keys At the input, the program receives a JSON.
I need to return the same JSON, but with camelCase keys.
Is there any effective way to convert all snake_case keys in JSON to camelCase keys in Go?
Snippet Code:
package main

import (
    "encoding/json"
    "fmt"
    "reflect"
    "regexp"
    "strings"
)

type CategoryList struct {
    Id   *string `json:"id"`
    Name *string `json:"name"`
}

type Data struct {
    AccessToken  *string         `json:"access_token"`
    Category     *string         `json:"category"`
    CategoryList []*CategoryList `json:"category_list"`
    Name         *string         `json:"name"`
    Id           *string         `json:"id"`
    Tasks        []*string       `json:"tasks"`
}

type Paging struct {
    Cursors *Cursors `json:"cursors"`
}

type Cursors struct {
    Before *string `json:"before"`
    After  *string `json:"after"`
}

type Categories struct {
    Data   []*Data `json:"data"`
    Paging *Paging `json:"paging"`
}

func main() {
    jsonString := `{"data":[{"access_token":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","category":"First Category","category_list":[{"id":"2301","name":"Finance App"}]},{"access_token":"ZYXWVUTSRQPONMLKJIHGFEDCBA","category":"Second Category","category_list":[{"id":"2302","name":"Medical App"}]}],"paging":{"cursors":{"before":"MTA0MjcxMzIxNjYxNTkz","after":"MTA3MTA5NDcxNDc5MTk3"}}}`

    var categories map[string]interface{}
    if err := json.Unmarshal([]byte(jsonString), &categories); err != nil {
        panic(err)
    }

    modified := fromSnakeCaseToCamelCase(reflect.ValueOf(categories))

    result, err := json.Marshal(modified.Interface().(map[string]interface{}))
    if err != nil {
        panic(err)
    }
    fmt.Println(string(result))
}

func fromSnakeCaseToCamelCase(value reflect.Value) reflect.Value {
    switch value.Kind() {
        case reflect.Array, reflect.Slice:
            for i := 0; i < value.Len(); i++ {
                nestedValue := value.Index(i)

                fromSnakeCaseToCamelCase(nestedValue)
            }
        case reflect.Map:
            for _, keyName := range value.MapKeys() {
                nestedValue := value.MapIndex(keyName)

                newKeyName := reflect.ValueOf(convertToCamelCase(keyName.Interface().(string)))
                value.SetMapIndex(newKeyName, nestedValue)

                oldKeyName := reflect.ValueOf(keyName.Interface().(string))
                value.SetMapIndex(oldKeyName, reflect.Value{})

                fromSnakeCaseToCamelCase(nestedValue)
            }
        default:
            // pass
    }
    return value
}

var link = regexp.MustCompile("(^[A-Za-z]|_[A-Za-z])")

func convertToCamelCase(str string) string {
    return link.ReplaceAllStringFunc(str, func(s string) string {
        r := strings.NewReplacer("_", "")
        return strings.ToUpper(r.Replace(s))
    })
}

A: You can unmarshal the JSON into an interface{}, which will produce a map[string]interface{} for each JSON object. Recursively traverse the structure and replace keys as necessary, then marshal it back to JSON again.

A: You could use a custom json marshalling function for your struct which could use a regex to replace snake case to camel case for the keys.
Otherwise I think a simple way would be to define two structs, one with camel and one with snake. You can unmarshal into one, concert between the two and then re-marshal and send as a json response.


text:
Q: PicklingError for ProcessPoolExecutor I have already implemented a programm, where it gets a path with hundreds of pdf-files. It than opens them and extracts informations. But this takes a while, so i wanted to implement the ProcessPoolExecutor.
import concurrent.futures
import os

def func(path):
    print(path)
    return path

path = r'C:\Users\abi52\OneDrive\Desktop\Pyprogramme\SDBS'
listPaths= os.listdir(path)
listPathsFinal = []

if __name__ == '__main__':
    for PDF in listPaths:
        if 'pdf' in PDF or 'PDF' in PDF:
            listPathsFinal.append(r'%s\%s' %(path,PDF))

    with concurrent.futures.ProcessPoolExecutor() as ex:
        result = ex.map(func,listPathsFinal)

    print(list(result))

func should just show if the paths are given to the function. But when i list the result it shows a Pickling error. There are already similar questions asked but for the most part they describe functions which are not top level, e.g. function in a class. But this minimalistic function should be top level, so i don't understand the error. I am relatively new to programming so i would appreciate your help.
listPathsFinal = ['C:\\Users\\abi52\\OneDrive\\Desktop\\Pyprogramme\\SDBS\\MSDS_Merck_Chloroform für die Flüssigkeitschromatographie LiChrosolv®_10.05.2021.PDF', 'C:\\Users\\abi52\\OneDrive\\Desktop\\Pyprogramme\\SDBS\\MSDS_Merck_Kaliumnitrat zur Analyse EMSURE_23.09.2021.PDF', 'C:\\Users\\abi52\\OneDrive\\Desktop\\Pyprogramme\\SDBS\\MSDS_Sigma Aldrich_Ethanol_03.04.2020.pdf', 'C:\\Users\\abi52\\OneDrive\\Desktop\\Pyprogramme\\SDBS\\MSDS_Thermo Fisher_Wash Solution 1 Concentrate_11.06.2019.pdf', 'C:\\Users\\abi52\\OneDrive\\Desktop\\Pyprogramme\\SDBS\\TestSDS_CRC Industries_FLUX SK10_29.06.2017.PDF']

The error message:
concurrent.futures.process._RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Users\abi52\AppData\Local\Programs\Python\Python39\lib\multiprocessing\queues.py", line 245, in _feed
    obj = _ForkingPickler.dumps(obj)
  File "C:\Users\abi52\AppData\Local\Programs\Python\Python39\lib\multiprocessing\reduction.py", line 51, in dumps
    cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function func at 0x000002336ED5CAF0>: attribute lookup func on __main__ failed
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "C:\Users\abi52\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\core\interactiveshell.py", line 3441, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-35-a724536b8d79>", line 1, in <module>
    runfile('C:/Users/abi52/AppData/Roaming/JetBrains/PyCharm2021.3/scratches/scratch.py', wdir='C:/Users/abi52/AppData/Roaming/JetBrains/PyCharm2021.3/scratches')
  File "C:\Program Files\JetBrains\PyCharm 2021.3.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2021.3.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/abi52/AppData/Roaming/JetBrains/PyCharm2021.3/scratches/scratch.py", line 22, in <module>
    print(list(result))
  File "C:\Users\abi52\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\process.py", line 559, in _chain_from_iterable_of_lists
    for element in iterable:
  File "C:\Users\abi52\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\_base.py", line 608, in result_iterator
    yield fs.pop().result()
  File "C:\Users\abi52\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\_base.py", line 438, in result
    return self.__get_result()
  File "C:\Users\abi52\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\_base.py", line 390, in __get_result
    raise self._exception
  File "C:\Users\abi52\AppData\Local\Programs\Python\Python39\lib\multiprocessing\queues.py", line 245, in _feed
    obj = _ForkingPickler.dumps(obj)
  File "C:\Users\abi52\AppData\Local\Programs\Python\Python39\lib\multiprocessing\reduction.py", line 51, in dumps
    cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function func at 0x000002336ED5CAF0>: attribute lookup func on __main__ failed


text:
Q: Hierarchical Linear Mixture Model I have implemented a stan hierarchical model with level 1 within groups to be a linear model and level 2  within subjects Gaussian mixture model. It means the slope obtained from level 1 is used by level model GMM to cluster. When I run the model it has a convergence problem.

WARNING:pystan:Maximum (flat) parameter count (1000) exceeded:
  skipping diagnostic tests for n_eff and Rhat. To run all diagnostics call pystan.check_hmc_diagnostics(fit)
  WARNING:pystan:2 of 500 iterations ended with a divergence (0.4 %).
  WARNING:pystan:Try running with adapt_delta larger than 0.8 to remove the divergences.
  WARNING:pystan:Chain 1: E-BFMI = 0.0611
  WARNING:pystan:E-BFMI below 0.2 indicates you may need to reparameterize your model

Any comments on improving the model?
 multi_level_model = """

data {
  int<lower=0> N; // No of observations
  int J; // No of subjects
  int<lower=1,upper=J> RID[N];
  vector[N] x;  // Cognitive measure
}

parameters{
  real a;
  vector[J] b;
  real mu_b;
  real<lower=0,upper=2> sigma_b;

 # Gaussian Parameters for level 2

  ordered[2] mu;
  real<lower=0> sigma[2];
  real<lower=0, upper=1> theta;

}
transformed parameters {
  vector[N] y_hat;
  for(i in 1:N)
    y_hat[i] <- a + x[i] * b[RID[i]];

}
model {

  sigma_b ~ normal(0, 1);
  b ~ normal (mu_b, sigma_b);

  a ~ normal (0, 1);

  sigma ~ normal(0, 1);
  mu ~ normal(0, 1);
  theta ~ beta(5, 5);

  for (n in 1:J)
   target += log_mix(theta,
                     normal_lpdf(b[n] | mu[1], sigma[1]),
                     normal_lpdf(b[n] | mu[2], sigma[2]));

}
   """


text:
Q: Get element value from XML with XPath I have XML file like this:
<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents- xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 UBL-Invoice-2.1.xsd">
<cac:AccountingSupplierParty>
<cac:Party>
  <cac:PartyIdentification>
    <cbc:ID schemeID="schema1">123231123</cbc:ID>
  </cac:PartyIdentification>
  <cac:PartyIdentification>
    <cbc:ID schemeID="schema2">2323232323</cbc:ID>
  </cac:PartyIdentification>
  <cac:PartyIdentification>
    <cbc:ID schemeID="schema3">4442424</cbc:ID>
  </cac:PartyIdentification>
  <cac:PostalAddress>
    <cbc:CityName>İstanbul</cbc:CityName>
    <cac:Country>
      <cbc:Name>Turkey</cbc:Name>
    </cac:Country>
  </cac:PostalAddress>
</cac:Party>
</cac:AccountingSupplierParty>
</Invoice>

I want to access schemeID="schema=2" value. I try XPath and document.getElementsByTagName. I can access elements with document.getElementsByTagName, since  is multiple I can't access the element I want. When I try to with XPath, I can't access any elements from XML.
Here is my XPath implementation:
try {
    String decoded = new
    String(DatatypeConverter.parseBase64Binary(binaryXmlData));
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(decoded));
    Document doc = db.parse(is);
    String expression = "/Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID@[schemaID='schema2']/text()";
    String schema2 = (String) xPath.compile(expression).evaluate(doc, XPathConstants.STRING);
    System.out.println(schema2);
    //schema2 is null

    //Above this code block returns correct value
    NodeList nl = doc.getElementsByTagName("cbc:CityName");
    System.out.println(nl.item(0).getTextContent());

} catch () {

}

binaryXmlData is source of my XML. First, I convert base64binary data to xml. Am I doing to convertion wrong or my xpath implementation is wrong ?

A: There are many problems with your code and your XML, including:

*

*Your XML is not well-formed.  The closing quote of the cbc
namespace prefix is missing.

*Your Java code never defines a NamespaceContext.

See also How does XPath deal with XML namespaces?


text:
Q: Checkbox looks different in IE and Chrome Checkbox looks different in IE and Firefox. Need to look it consistent like Firefox. I have tried giving the css below but in IE it still doesnt show shadow inside checkbox like in FF
{ background-color: #FAFAFA;
border: 1px solid #CACECE;
border-radius: 3px 3px 3px 3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05), 0 -15px 10px -12px rgba(0, 0, 0, 0.05) inset;}

Any inputs?
Thanks.


text:
Q: Groovy not showing parameters I am using Pipeline Remote Loader Plugin to load .groovy based file form git repo in my Jenkinsfile.
Everything works fine except parameters which is not showing when I trigger the CI job
My code for parameters looks like:
parameters {
  choice(choices: 'greeting\nsilence', description: 'This is test',name: 'REQUESTED_ACTION')
}

I expect params.REQUESTED_ACTION has the value of whatever use choose but it is null because the choices never displayed.

A: For those who may face this, The solution was to wrap everything in properties so the code becomes:
 properties([
    parameters([choice(choices: 'env1\env2', name: 'envName', description: 'The target environment')])
])


text:
Q: Do lambda expressions use reflection? To be sure that I understand could someone confirm that lambda expressions use reflection?

A: They can, but they are not required to. If they are compiled to a delegate, then no reflection is necessary: however, if they are compiled to ab expression tree, then an expression tree is absolutely reflection-based. Some parts of expression trees can be assembled directly from metadata tokens (ldtoken) - in particular methods (including operators and getters/setters, and types) - but some other parts cannot . This includes properties (PropertyInfo cannot be loaded by token) - so the IL for a compiled lambda can explicitly include GetProperty etc.
But however it is loaded (token or reflection), an expression tree is expressed in terms of reflection (MemberInfo, etc). This might later be compiled, or might be analysed by a provider.
To help performance, the expression compiler may cache some or all of the expression tree, and re-use it.

A: Lambda expressions are turned by the compiler into either anonymous functions or expression trees. Since reflection can only be performed at runtime it doesn't come into the picture at all when considering what the compiler does with them in either case.
At runtime, lambda expressions might result in reflection being used under very specific circumstances:
For anonymous functions: if you write an anonymous function that explicitly reflects on something then the lambda will perform that reflection when invoked. This is of course the same as if you were reflecting from within a "proper" method.
For expression trees (i.e. values of type Expression<TDelegate> for some TDelegate): using them at runtime when working with an IQueryable might result in reflection being used by the query provider. For example, assume that you do:
var user = new User { Id = 42 };
var posts = Queryable.Posts.Where(p => p.UserId == user.Id);

When posts is about to be materialized the query provider sees that it must find those posts with a UserId equal to the Id of the variable user. Since that id has a specific known value at runtime, the query provider needs to fish it out of user. One way it might decide to do that is through reflection.

A: A lambda expressions is just compiler syntax sugar for creating delegates.  No reflection used here.


text:
Q: how do I use WooCommerce from C# to post a record So I have a worpress site with woo commerce. I am in the process of writing a C# WebApi rest app to interact with the wordpress site. So far I can catch things like new product creation, order creation from woo using webhooks.
Now I'm trying to go the other way and in this case post a new product into wordpress from my api.
I have installed the latest version of WooCommerce.Net from Nuget (V4.0.30319).
So for test purposes I've created a product :
var wooProduct = new WooCommerceNET.WooCommerce.v3.Product
            {
                name = "test product",
                type = "simple",
                regular_price = 23.99m,
                description = "test product to see if I can create a product using rest APi",
                short_description = "this is a short desc",
                shipping_required = true,
                stock_quantity = 20
            };
            wooProduct.categories = new List<ProductCategoryLine>();
            wooProduct.categories.Add(new ProductCategoryLine { id = 1 });

Then to send it I have:
 var fullEndPoint = string.Concat(site, "/wp-json/wc/v3/", endpoint);

                var serializedData = JsonConvert.SerializeObject(postdata);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullEndPoint);
                request.Method = "POST";
                request.ContentType = "application/json";
                request.Headers.Add("consumer_key", woosecret);
                string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1")
                                           .GetBytes(username + ":" + password));
                request.Headers.Add("Authorization", "Basic " + encoded);
                using (StreamWriter swJSONPayload = new StreamWriter(request.GetRequestStream()))
                {
                    swJSONPayload.Write(serializedData);
                    swJSONPayload.Close();
                }

but nothing get's across and I dont receive any error's. The Documentation says that the

WooCommerceNET.RestAPI

is deprecated and all examples do not show how to send from C#. If anyone can point me in the right direction I'd be very grateful.
Update: I added Basic Authorisation where the username and password are a valid user set up on wordpress/woo. I now receive a 401 unauthorized error, but dont know what else I need to give to allow this to go through.
Update 2: I didn't have basic authentication enabled in IIS. Now that I've done that I receive an error suggesting that IIS could not verify the identity of the username and password provided. These details are configured in wordpress and isn't system wide. I'm running all of this on a windows 10 developer machine at the moment, so there is no Active Directory either.


text:
Q: Why does UIScrollView resize back up when moving to another textfield - iOS iPhone This probably isn't an easy one to answer....
I have 8 text fields on screen which sit in a scrollView. When I select the first field, the keyboard appears and the scrollView shrinks. I can then scroll up and down.
When I select another text field, I can't scroll anymore.
I've checked the scrollView height using textFieldDidBeginEditing and it definitely grows back up.
I've also registered for all 4 of the keyboard notifications but none of them are triggered during the move to the new text field.
Any pointers would be much appreciated :)
- (void)viewDidLoad
{
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification
                                           object:self.view.window];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillHide:)
                                             name:UIKeyboardWillHideNotification
                                           object:self.view.window];

keyboardIsShown = NO;

//Additional Code

}

- (void)viewDidUnload {

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillShowNotification
                                              object:nil];

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillHideNotification
                                              object:nil];

}

- (void)keyboardWillHide:(NSNotification *)n
{

NSDictionary* userInfo = [n userInfo];

CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

CGRect viewFrame = self.scrollView.frame;

viewFrame.size.height += (keyboardSize.height - self.toolBar.frame.size.height);

[self.scrollView setFrame:viewFrame];

keyboardIsShown = NO;
}

- (void)keyboardWillShow:(NSNotification *)n
{
if (keyboardIsShown) {
    return;
}

NSDictionary* userInfo = [n userInfo];

CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

CGRect viewFrame = self.scrollView.frame;

viewFrame.size.height -= (keyboardSize.height - self.toolBar.frame.size.height);

scrollViewHeight = viewFrame.size.height;

[self.scrollView setFrame:viewFrame];

keyboardIsShown = YES;
}

For moving between the text fields:
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
[[self saveButton] setEnabled:YES];

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == self.label1) {
    [self.label2 becomeFirstResponder];
} else if (textField == self.label2) {
    [self.label3 becomeFirstResponder];
} else if (textField == self.label3) {
    [self.label4 becomeFirstResponder];
} else if (textField == self.label4) {
    [self.label5 becomeFirstResponder];
} else if (textField == self.label5) {
    [self.label6 becomeFirstResponder];
} else if (textField == self.label6) {
    [self.label7 becomeFirstResponder];
} else if (textField == self.label7) {
    [self.label8 becomeFirstResponder];
} else if (textField == self.label8) {
    [textField resignFirstResponder];
}
return YES;
}

A: After lots of digging I found the following code, which I've now tweaked and tested:
- (void)viewDidLoad
{
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillBeHidden:)
                                             name:UIKeyboardWillHideNotification
                                           object:nil];

keyboardIsShown = NO;

//Additional code
}

- (void)viewDidUnload {

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardDidShowNotification
                                              object:nil];

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIKeyboardWillHideNotification
                                              object:nil];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, (kbSize.height -    self.toolBar.frame.size.height), 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;

// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= (kbSize.height + (self.toolBar.frame.size.height*2));
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
    CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
    [self.scrollView setContentOffset:scrollPoint animated:YES];
}
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}

A: In this kind of tasks I'm using BSKeyboardControls
There is good example project and Usage description


text:
Q: How to deep link to specific screen in react-native expo I am creating a link URL with the following code:
Linking.makeUrl('lobby/', {
  roomId: params.roomId
})

which outputs the following: exp://192.168.0.31:19000/--/lobby/?roomId=1585512451
This works fine locally but only seems to open to the Home page of my app.
I have defined the screens in My app.js
const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={HomeScreen}
        />
        <Stack.Screen
          name="Lobby"
          component={LobbyScreen}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Do I need to redirect to the lobby screen with some sort of even listener or should the path passed into makeUrl map to a screen?

A: Yes you need to listen for the url events. See the section in the Expo documentation on deep linking. https://docs.expo.io/versions/latest/workflow/linking/#handling-links-into-your-app
Note there are additional configuration options you will need in the expo configuration for this to work on different devices. See their documentation for all instructions in that regard.
Quoted from the link provided
Handling links into your app
There are two ways to handle URLs that open your app.

1. If the app is already open, the app is foregrounded and a Linking event is fired
You can handle these events with Linking.addEventListener('url', callback).

2. If the app is not already open, it is opened and the url is passed in as the initialURL
You can handle these events with Linking.getInitialURL -- it returns a Promise that resolves to the url, if there is one.

From their example code:
let redirectUrl = Linking.makeUrl('path/into/app', { hello: 'world', goodbye: 'now' });
Then you need to handle the URL using an event handler
_handleUrl = url => {
  this.setState({ url });
  let { path, queryParams } = Linking.parse(url);
  alert(`Linked to app with path: ${path} and data: ${JSON.stringify(queryParams)}`);
};

Because the behavior is different if your app is opened and the link is clicked vs the app being closed you need 2 different entry points for handling a link.
Inside you HomeScreen component you could put something like this:
    componentDidMount() {
        // handle an initial url on app opening
        Linking.getInitialURL().then(urlRedirect)
    }

And somewhere in your app, maybe in the app.js place a handler for new urls from inside the app.
function urlRedirect(url) {
    if(!url) return;
    // parse and redirect to new url
    let { path, queryParams } = Linking.parse(url);
    console.log(`Linked to app with path: ${path} and data: ${JSON.stringify(queryParams)}`);
    this.navigation.replace(path, queryParams);
}

// listen for new url events coming from Expo
Linking.addEventListener('url', event => {
    urlRedirect(event.url);
});


text:
Q: Does series of average of positive numbers converge? Given: sequence of $\{a_n\}$ (where $a_n$ is a positive number) and number $p \in \mathbb{N}$ ($p > 1$) such as series $\sum^\infty_{n=1} a_n^p$ converges. Let
$$b_n = \frac{a_1 + a_2 + \dots + a_n}{n}$$.
Prove: series $\sum^\infty_{n=1} b^p_n$ converges and the statement $\sum^\infty_{n=1} b^p_n \leq \frac{p}{p-1} \sum^\infty_{n=1} a^p_n$ is true.

I think that series $\sum^\infty_{n=1} a_n^p$ converges only if in sequence $\{a_n\}$ there's only a finite quantity of numbers that are $\geq 1$. But what to do next? Is this idea right?


text:
Q: Android....Not getting JSON respone from darksky weather API using Okhttp I am writing code to build a simple weather app using Darksky API
Following is my java code file.
In which I am using okHttp 3.5.0 and asynchronously calling the darksky API and writing response on the log.
MainActivity.java
package treehouse.com.stormy;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;

import javax.xml.datatype.Duration;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    public static final String TAG=MainActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        double latitude=37.8267;
        double longitude=-122.4233;
        String apiKey="Here you would insert your key and I have ofcourse mine";
        String forecastURL="https://api.darksky.net/forecast/" + apiKey + "/" + latitude + "," + longitude;

      OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder().url(forecastURL).build();
        Call call=client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {
                    if(response.isSuccessful()) {
                        Log.v(TAG, response.body().string());
                    }
                } catch (IOException e) {

                    Log.e(TAG,"Exception caught: ",e);
                }
            }
        });

    }
}

Activity Output

Gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "treehouse.com.stormy"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.squareup.okio:okio:1.6.0'
    compile project(':okhttp-3.5.0')
}
repositories {
    mavenCentral()

}

Detailed Logcat
Logcat
**My activity is crashing  on the emulator but  it is correctly calling the API and I have checked the API console usage before and after running the code?
API usage before running the code

API usage after running the code

A: You are using an older version of Okio library which is not compatible with your version of OkHttp, causing the crash when trying to call a nonexistent method. I would advise using the latest version of Okio, but the OkHttp maven library already has the dependency, too.
Just remove the compile 'com.squareup.okio:okio:1.6.0' line from your gradle file.


text:
Q: ESP32 I2C along with analogue read not working. How to fix it? First of all I am new to electronics. I am using ESP32 dev kit and trying to communicate with an i2c sensor and an analogue sensor.
I am able to communicate both devices.
I am using freertos Task to gather output running on parallel threads on two cores of the ESP32.
I noticed that as the I2C communication begins the noise in the analogue signal increase to every high level. I am completely puzzled why this is happening. Could it be ghosting, or something that I don't know about?
I need your guidance on how to resolve this issue.
Please note if the I2C device is not running then the analogue values are read perfectly.

A: I had similar issue when I used BLE and analogread together.
Try the following function if you use arduino-core.
Use adc2_config_channel_atten function ifyou are usung esp-idf
int new_analogRead(int pin){
  int value = 0;
  int8_t channel = digitalPinToAnalogChannel(pin);
  if(channel < 0){
      return 0;//not adc pin
  }
  if(channel > 7){    //ADC2
    adc2_config_channel_atten(adc2_channel_t(channel-10),ADC_ATTEN_11db);//11dB attenuation (ADC_ATTEN_11db) gives full-scale voltage 3.9V
    adc2_get_raw(adc2_channel_t(channel-10), ADC_WIDTH_BIT_10, &value);
    //used chanel-10 based on gpioMUX in esp32-hal-gpio
    return value;
  } else {//ADC1- not required
      // while (GET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DONE_SAR) == 0); //wait for conversion
      // value = GET_PERI_REG_BITS2(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DATA_SAR, SENS_MEAS1_DATA_SAR_S);
      return 0;
  }
}


text:
Q: shortest distance between road and lake with PostGIS I have a country-wide dataset with lakes (polygons) and streets (lines). For each lake I want to know the shortest distance to the closest street. (I do not necessarily need the closest street itself ... )

I use this query for it:
SELECT
  *,
  (SELECT
      ST_Distance(lake.geom, street.geom)
    FROM
      street
    ORDER BY
      lake.geom <-> street.geom
    LIMIT
      1
  ) AS distance_closest_street
FROM
  lake

This query works quite fast on regional level, but takes forever on country level.  I have the usual "gist"-index on the geometry columns.
Do you have ideas how this query could become faster?
Edit:
I use PostgreSQL 9.5.7 and PostGIS 2.3.2

A: You don't mention what version of PostgreSQL/PostGIS you are using.  The KNN nearest neighbor operators have improved greatly over recent years
https://postgis.net/docs/geometry_distance_knn.html
So I believe you are just looking for the nearest neighbor road to each lake.
SELECT
 a.lake_id
,a.nearest_street_id
,ST_Distance(
    ST_Transform(a.geom,4326)::geography
   ,ST_Transform(b.geom,4326)::geography
) / 1000 AS distance_km
FROM (
   SELECT
    a.lake_id
   ,a.geom
   ,(
      SELECT
      bb.street_id
      FROM
      street bb
      ORDER BY
      bb.geom <-> aa.geom
      LIMIT 1
    ) AS nearest_street_id
   FROM
   lake aa
) a
JOIN
street b
ON
a.nearest_street_id = b.street_id;

This will work with 9.5 and greater and PostGIS 2.2.  You can do similar things with earlier KNN versions - using <#> after 9.1 but its more work to batch and then inspect the batch for the nearest.
Note in cases where the distance is exactly the same, you just get whichever one comes up first in the limit.
Edit:  Note you can try the lateral trick as well though in my testing I get very similar performance results
SELECT
 a.lake_id
,b.nearest_street_id
,ST_Distance(
    ST_Transform(a.geom,4326)::geography
   ,ST_Transform(b.geom,4326)::geography
) / 1000 AS distance_km
FROM
lake a
CROSS JOIN LATERAL (
   SELECT
    bb.street_id AS nearest_street_id
   ,bb.geom
   FROM
   street bb
   ORDER BY
   bb.geom <-> a.geom
   LIMIT 1
) b

Cheers,
Paul

A: I'm not an expert in postgis, but I have an idea. You can create another field of lakes with st_buffer (10km, 20km, etc) and indexed. Then use st_intersects with streets, I believe the search will be faster. This way you'll be using the gist index indeed.


text:
Q: .NET Framework FxCop rule CA1401 PInvokesShouldNotBeVisible rule - why does this rule exist? This rule indicates that P/Invokes should not be made public.  My question is why?  A caller can trivially create their own declaration within their own assembly to make the exact same call.  A caller could just write a C library to call the API.  What benefit, security or otherwise, is gained by making these declarations internal?

A: Well, in the .NET security model, it's possible for your assembly to have permission to do P/Invokes, but for your caller not to have.  (AllowPartiallyTrustedCallersAttribute, which permits code running as partially trusted to call into an assembly that is fully trusted, exists to enable this.)
Which is, essentially, what you want when the library you are writing exists to provide safe access, or limited access, to some system facility that you don't want sandboxed applications of one type or another to have arbitrary access to.
On another note, it's politeness as well as security. P/Invokes are de facto unsafe, inasmuch as calling them badly can result in all kinds of interesting ways to crash that you generally don't run into in the comfortable .NET world.  Wrapping some error-checking and general safety code around them, along with such things as mangling input data into the Win32 API (or whatever's) format, translating its error codes into the appropriate .NET exceptions, etc., etc., is just plain courtesy to your library's future users, IMO.


text:
Q: Recommended way to Install Magento 2 on shared hosting, Composer or archives The Install Guide recommends installing the software using archives (not Composer) for a shared hosting environment.
However, from Magento documentation:

Everyone who uses the Magento software must install Composer to update components and Magento. If you install Magento using an archive, you don't need Composer to install Magento, but you do need Composer for updates.

And from this article:

Attention: Because Composer relies on third-party code, we do not recommend Composer for use on production sites.

Then what is the "best" way to install Magento 2?

A: I'm not speaking for Magento but it doesn't seem like a good idea in general to install updates on a production site. In addition, we recommend you use the pub folder as your root in production so as to prevent running the Setup Wizard.

A: For shared hosting where you can't do a source code clone or checkout and can't run composer. I would upload the archive from Magento direct or your own local dev machine if you have one. Then ensure that you have the server Web root pointed to the pub folder. This stops access to the setup wizard and other non protected directories.

A: You should use Bitnami : https://google.bitnami.com
It has a launcher and your magento will be in the cloud. It is amazing and very cost-efficient.


text:
Q: Protobuf helloworld compile error I checked out the protobuf repository, built with a custom prefix and installed, then copy&pasted the Person example from Google and compiled with protoc. That was OK.
But when I include Person.pb.h in my CPP file, I get:
/home/name/usr/include/google/protobuf/repeated_field.h:53:47: fatal error:
google/protobuf/stubs/type_traits.h: No such file or directory

That file was not installed. Is it a bug?


text:
Q: python manage.py migrate doesn't work on anaconda I am new to django; I am trying to finish my first project and I was able to start project but it fails migration. Here is the error code:

Traceback (most recent call last):
File "manage.py", line 10, in
<module> execute_from_command_line(sys.argv)
 File "C:\Anaconda\lib\site-packages\django\core\management\__init__.py",

line 338, in
execute_from_command_line utility.execute()

File
  "C:\Anaconda\lib\site-packages\django\core\management__init__.py",
  line 312, in execute django.setup()
File "C:\Anaconda\lib\site-packages\django__init__.py", line 18, in
  setup apps.populate(settings.INSTALLED_APPS)
File
  "C:\Anaconda\lib\site-packages\django\django\apps\registry.py", line
  85, in populate app_config = AppConfig.create(entry)     File
  "C:\Anaconda\lib\site-packages\django\django\apps\config.py", line
  127, in create "'%s' isn't a subclass of AppConfig." % entry)
  django.core.exceptions.ImproperlyConfigured:
  'django.contrib.admin.apps.AdminConfig' isn't a subclass of
  AppConfig.

I even tried
python manage.py makemigrations

but same error.
I am using Python 2.7.9 |Anaconda 2.2.0 (64-bit)| and django==1.8
I should mention in order to start the project I had to use
python admin-py.exe startproject djangotutorial

because
python admin-py.py startproject djangotutorial

didn't work
I really appreciate any insight

A: I'm fairly sure you made your project incorrectly. To start a project you use django-admin startproject djangotutorial and then you navigate to the folder. If the command doesn't work, then your django installation has a problem. Only after that can you use python manage.py makemigrations.


text:
Q: Async AJAX call with lookup data using ko observableArray? I have an observableArray of options that gets bound to the following:
<select data-bind="options: lookupData.options, optionsText: 'DisplayName', optionsValue: 'Id', value: optionId" />

When I first apply bindings, the options() observable array is empty - an async AJAX call is sent to retrieve these options.
Most of the time, this works perfectly.  But if I display the view very quickly, before the AJAX call returns, the dropdown displays with a default option selected, but the options become available.  The selected option isn't updated though.
In other words - if I have 'Blue' as the currently selected option, but the select markup is displayed before the AJAX call completes, 'Blue' doesn't get selected after the observableArray of options is populated.
Am I missing some syntax to make this work?
Code:
   // getLookupData()
   var lookupData = {};
   lookupData.colors = ko.observableArray();
   $.ajax({
            type: "POST",
            url: getAllergyRelationshipListUrl.url,
            async: true,
            data: new Object(),
            dataType: "json",
            contentType: "application/json"
        }).done(function(data, textStatus, jqXhr) {
            lookupData.colors(data.Data);
        });

   return lookupData;

   // colorVm
   if (vm.colorLookupData == null) {
      vm.colorLookupData = getLookupData();
   }

   ko.applyBindings(vm);

A: It's a known problem on knockout select. Before your ajax finishes, the value does not exist in options, the options binding enforced your value to be one of options.
This is solved in knockout since version 3.1 with introduction of valueAllowUnset.
Update your binding to:
<select data-bind="valueAllowUnset: true, options: lookupData.options, optionsText: 'DisplayName', optionsValue: 'Id', value: optionId" />

You can read here http://knockoutjs.com/documentation/value-binding.html#using-valueallowunset-with-select-elements


text:
Q: Difference between display inline and block on svg elements I understand the difference when it comes to divs.
But in svg:
<svg>
    <rect display="block" id="svg_3" height="57" width="52" y="20" x="41" stroke-width="5" stroke="#000000" fill="#FF0000"/>

     <rect display="inline" id="svg_3" height="57" width="52" y="20" x="120" stroke-width="5" stroke="#000000" fill="#0000BB"/>
</svg>

Seems to produce the same result... ('none' hides the element tho)
Here's the jsfiddle:
https://jsfiddle.net/foreyez/3c7va377/
what's the difference, and what's the default value, inline or block?

A: I searched for this because I have an svg in a page where the height of the surrounding element is 5px more than the actual height of the svg.
As far as I can see it does make a difference if you use display="none", display="block" or display="inline".
Just as an image there is space below a svg. Because they are, by default, inline-block elements (inline in some browsers). As such, they sit alongside text: the space that's visible under an svg is there for descenders on letters like 'p' and 'q'.
This can be seen by placing a svg within a div. If the svg is 24px. high, the div will have a height of (for instance) 29 px.
display="block" will prevent the svg to reserve that space, so the div wherein the svg is placed will have the same height.

A: In my practice, when I use <svg> tag -- browser (Google Chrome Version 80.0.3987.100 (Official Build) (64-bit)) interpret it as inline element by default. And it behaves as a standart inline element. If complines display: block css-property for it -- it behave as standart block element
If we make some research and fall into computed tab in the dev tools on any svg-child element then we'll see that it has the display inline property. Even if we'll set svg display: block the svg-child elements stay inline elements by default

A: Per the SVG specification

A value of display: none indicates that the given element and its children shall not be rendered directly (i.e., those elements are not present in the rendering tree). Any value other than none or inherit indicates that the given element shall be rendered by the SVG user agent.

So everything except none is treated exactly the same.
SVG is not HTML, it has no concept of reflow (i.e. changes in the position of one element do not affect other elements apart from tspan and tref in text).


text:
Q: How to register implementation of abc.MutableMapping as a dict subclass? I would like my SpreadSheet class below to be considered a dict subclass by the isinstance() built-in, but when I try to register it as such, an AttributeError exception is thrown (also shown below).
What is a (or the) way to do something like this?
Note: My question is similar to Is it possible to be a virtual subclass of a built in type?, but its accepted answer doesn't address the titular question asked (so please don't vote to close this as a duplicate).
The primary motivation for wanting to do this is to allow an instance of the class to be passed to json.dump() and be treated just like a Python dict. This is needed because — for reasons I don't understand — the JSONEncoder class uses isinstance(value, dict), rather than isinstance(value, Mapping).
from collections.abc import MutableMapping

class SpreadSheet(MutableMapping):
    def __init__(self, tools=None, **kwargs):
        self._cells = {}
        self._tools = {'__builtins__': None}
        if tools is not None:
            self._tools.update(tools)  # Add caller supplied functions.

    def clear(self):
        return self._cells.clear()

    def __contains__(self, k):
        return k in self._cells

    def __setitem__(self, key, formula):
        self._cells[key] = formula

    def __getitem__(self, key ):
        return eval(self._cells[key], self._tools, self)

    def __len__(self):
        return len(self._cells)

    def __iter__(self):
        return iter(self._cells)

    def __delitem__(self, k):
        del self._cells[k]

    def getformula(self, key):
        return self._cells[key]

type(dict).register(SpreadSheet)  # Register class as dict subclass.

ss = SpreadSheet()
print(f'isinstance(ss, dict): {isinstance(ss, dict)}')  # Result should be True.

Exception:
Traceback (most recent call last):
  File "spreadsheet.py", line 35, in <module>
    type(dict).register(SpreadSheet)  # Register class as dict subclass.
AttributeError: type object 'type' has no attribute 'register'

Chosen Solution
As the accepted answer to Is it possible to be a virtual subclass of a built in type? says, it's impossible as primitive types are essentially immutable.
However it is possible to make json.dump() treat a Mapping just like a dict by patching the module as shown in the second approach presented in @jsbueno's answer. The implementation shown below patches the encoder in a slightly different, simpler way that gives equivalent results. I especially liked a bonus feature it has which is that it also prevents the C optimized version from being used (which silently fails).
from collections.abc import Mapping, MutableMapping
from functools import partial
import json

class SpreadSheet(MutableMapping):
    def __init__(self, tools=None, **kwargs):
        self._cells = {}
        self._tools = {'__builtins__': None}  # Prevent eval() from supplying.
        if tools is not None:
            self._tools.update(tools)  # Add any caller-supplied functions.

    def clear(self):
        return self._cells.clear()

    def __contains__(self, key):
        return key in self._cells

    def __setitem__(self, key, formula):
        self._cells[key] = formula

    def __getitem__(self, key):
        return eval(self._cells[key], self._tools, self)

    def __len__(self):
        return len(self._cells)

    def __iter__(self):
        return iter(self._cells)

    def __delitem__(self, key):
        del self._cells[key]

    def getformula(self, key):
        """ Return raw un-evaluated contents of cell. """
        return self._cells[key]

    def update(self, *args, **kwargs):
        for k, v in dict(*args, **kwargs).iteritems():
            self[k] = v

# Monkey-path json module

# Changes check for isinstance(obj, dict) to isinstance(obj, Mapping)
# https://github.com/python/cpython/blob/3.8/Lib/json/encoder.py#L321
# This changes the default value of the function's dict= keyword to be
# a Mapping instead of a dict. The isinstance() call uses whatever it's
# set to.
_new__make_iterencode = partial(json.encoder._make_iterencode, dict=Mapping)

json.encoder._make_iterencode = _new__make_iterencode
json.encoder.c_make_encoder = None  # Disables use of C version of make encoder

if __name__ == '__main__':

    import json
    from math import cos, sin, pi, tan

    # A small set of safe built-ins.
    tools = dict(len=len, sin=sin, cos=cos, pi=pi, tan=tan)

    ss = SpreadSheet(tools)
    ss['a1'] = '5'
    ss['a2'] = 'a1*6'
    ss['a3'] = 'a2*7'
    ss['b1'] = 'sin(pi/4)'

    print()
    print('isinstance(SpreadSheet(tools), dict) -> {}'.format(isinstance(ss, dict)))
    print()
    print('Static Contents via getformula():')
    print(json.dumps({k: ss.getformula(k) for k in ss.keys()}, indent=4))
    print()
    print('Dynamic Contents via __getitem__():')
    print("  ss['a1'] -> {!r}".format(ss['a1']))
    print("  ss['a2'] -> {!r}".format(ss['a2']))
    print("  ss['a3'] -> {!r}".format(ss['a3']))
    print("  ss['b1'] -> {!r}".format(ss['b1']))
    print()
    print("via json.dumps(ss, indent=4):")
    print(json.dumps(ss, indent=4))
    print()
    print("via json.dumps(ss):")  # Works, too.
    print(json.dumps(ss))  # -> {}
    print()
    print('dict(**ss): {}'.format(dict(**ss)))  # Gets dynamic contents.

A: So, first things first, the "obvious way to do it", is to have a Json Encoder with a default method that would create a dict out of a CustomDict class while serializing:
Given
from collections.abc import MutableMapping
import json

class IdentaDict(MutableMapping):
    __getitem__ = lambda s, i: i
    __setitem__ = lambda s, i, v: None
    __delitem__ = lambda s, i: None
    __len__ = lambda s: 1
    __iter__ = lambda s: iter(['test_value'])

def default(obj):
    if isinstance(obj, MutableMapping):
            return dict(obj)
    raise TypeError()

print(json.dumps(IdentaDict, default=default)

will just work.
second
If for some reason, this is not desirable (maybe creating a dict out
of the CustomDict is not feasible, or would be too expensive), it is possible
to monkeypatch the machinery of Python's json.encoder, so that it uses
the appropriate call to isinstance:

from collections.abc import MutableMapping
from functools import partial
from unittest.mock import patch

import json

class IdentaDict(MutableMapping):
   ...

a = IdentaDict()

new_iterencoder = partial(
    json.encoder._make_iterencode,
    isinstance=lambda obj, cls: isinstance(obj, MutableMapping if cls == dict else cls)
)

with patch("json.encoder.c_make_encoder", None), patch("json.encoder._make_iterencode", new_iterencoder):
    print(json.dumps(a))

(Note that while at it, I also disabled the native C encoder, so that the
"pass indent to force Python encoder" hack is not needed. One never knows
when an eager Python volunteer will implement indent in the
C Json serializer and break that)
Also, the "mock.patch" thing is only needed if one plays mr. RightGuy and
is worried about restoring the default behavior. Otherwise, just overriding both
members of json.encoder in the application setup will make the changes
proccess wide, and working for all json.dump[s] call, no changes needed to the calls - which might be more convenient.
third
Now, answering the actual question: what is possible is to have a mechanism that will create an actual subclass of "dict", but implementing all the methods needed by dict. Instead of re-doing the work done by collections.abc.MutableClass,
it should be ok to just copy over both user methods and generated methods to the dict class:
import json
from abc import ABCMeta
from collections.abc import MutableMapping

class RealBase(ABCMeta):
    def __new__(mcls, name, bases, namespace, *, realbase=dict, **kwargs):
        abc_cls = super().__new__(mcls, name, bases, namespace, **kwargs)
        for attr_name in dir(abc_cls):
            attr = getattr(abc_cls, attr_name)
            if getattr(attr, "__module__", None) == "collections.abc" and attr_name not in namespace:
                namespace[attr_name] = attr
        return type.__new__(mcls, name, (realbase,), namespace)

class IdentaDict(MutableMapping, metaclass=RealBase):
    __getitem__ = lambda s, i: i
    __setitem__ = lambda s, i, v: None
    __delitem__ = lambda s, i: None
    __len__ = lambda s: 1
    __iter__ = lambda s: iter(['test_value'])

This will make the class work as expected, and return True to isinstance(IdentaClass(), dict). However the C Json Encoder will then try
to use native dict API's to get its values: so json.dump(...) will not raise,
but will fail unless the Python Json encoder is forced. Maybe this is why the instance check in json.encoder is for a strict "dict":
a = IdentaDict()

In [76]: a = IdentaDict()

In [77]: a
Out[77]: {'test_value': 'test_value'}

In [78]: isinstance(a, dict)
Out[78]: True

In [79]: len(a)
Out[79]: 1

In [80]: json.dumps(a)
Out[80]: '{}'

In [81]: print(json.dumps(a, indent=4))
{
    "test_value": "test_value"
}

(Another side-effect of this metaclass is that as the value returned by __new__ is not an instance of ABCMeta, the metaclass __init__ won't be called. But people coding with multiple metaclass composition would have to be aware of such issues. This would be easily work-aroundable by explicitly calling mcls.__init__ at the end of __new__)

A: I think I found a way to do it, based on a modified version of the suggestion in this answer to the question How to "perfectly" override a dict?.
Disclaimer: As the answer's author states, its a "monstrosity", so I probably would never actually use it in production code.
Here's the result:
from __future__ import print_function
try:
    from collections.abc import Mapping, MutableMapping  # Python 3
except ImportError:
    from collections import Mapping, MutableMapping  # Python 2

class SpreadSheet(MutableMapping):
    def __init__(self, tools=None, **kwargs):
        self.__class__ = dict  # see https://stackoverflow.com/a/47361653/355230

        self._cells = {}
        self._tools = {'__builtins__': None}
        if tools is not None:
            self._tools.update(tools)  # Add caller supplied functions.

    @classmethod
    def __class__(cls):  # see https://stackoverflow.com/a/47361653/355230
        return dict

    def clear(self):
        return self._cells.clear()

    def __contains__(self, key):
        return key in self._cells

    def __setitem__(self, key, formula):
        self._cells[key] = formula

    def __getitem__(self, key):
        return eval(self._cells[key], self._tools, self)

    def __len__(self):
        return len(self._cells)

    def __iter__(self):
        return iter(self._cells)

    def __delitem__(self, key):
        del self._cells[key]

    def getformula(self, key):
        """ Return raw un-evaluated contents of cell. """
        return self._cells[key]

    def update(self, *args, **kwargs):
        for k, v in dict(*args, **kwargs).iteritems():
            self[k] = v

#    # Doesn't work.
#    type(dict).register(SpreadSheet)  # Register class as dict subclass.

if __name__ == '__main__':

    import json
    from math import cos, sin, pi, tan

    # A small set of safe built-ins.
    tools = dict(len=len, sin=sin, cos=cos, pi=pi, tan=tan)

    ss = SpreadSheet(tools)
    ss['a1'] = '5'
    ss['a2'] = 'a1*6'
    ss['a3'] = 'a2*7'
    ss['b1'] = 'sin(pi/4)'

    print()
    print('isinstance(SpreadSheet(tools), dict) -> {}'.format(isinstance(ss, dict)))
    print()
    print('Static Contents via getformula():')
    print(json.dumps({k: ss.getformula(k) for k in ss.keys()}, indent=4))
    print()
    print('Dynamic Contents via __getitem__():')
    print("  ss['a1'] -> {!r}".format(ss['a1']))
    print("  ss['a2'] -> {!r}".format(ss['a2']))
    print("  ss['a3'] -> {!r}".format(ss['a3']))
    print("  ss['b1'] -> {!r}".format(ss['b1']))
    print()
    print("via json.dumps(ss, indent=4):")
    print(json.dumps(ss, indent=4))

Output:
isinstance(SpreadSheet(tools), dict) -> True

Static Contents via getformula():
{
    "a1": "5",
    "a2": "a1*6",
    "a3": "a2*7",
    "b1": "sin(pi/4)"
}

Dynamic Contents via __getitem__():
  ss['a1'] -> 5
  ss['a2'] -> 30
  ss['a3'] -> 210
  ss['b1'] -> 0.7071067811865475

via json.dumps(ss, indent=4):
{
    "a1": 5,
    "a2": 30,
    "a3": 210,
    "b1": 0.7071067811865475
}

Note: I got the idea for this class from an old ActiveState recipe by Raymond Hettinger.

A: You can do something like:
import json

def json_default(obj):
    if isinstance(obj, SpreadSheet):
        return obj._cells
    raise TypeError

cheet = SpreadSheet()
cheet['a'] = 5
cheet['b'] = 23
cheet['c'] = -4

print(json.dumps(cheet, default=json_default))

Output:
{"a": 5, "b": 23, "c": -4}

The key is the function json_default that tells the json decoder how to serialize your class!


text:
Q: Visual Studio C# Xamarin - Android networking broadcast issue I'm using Visual Studio 2019 to develop a cross-plaftorm project in C# Xamarin (Android, iOS, UWP).
I'm new to Android and cannot find the root cause of an issue... the UWP app on windows works like a charm.
I'm using the UdpClient's class as a server - binded to IPAddress.Any on a certain AppPort (e.g. 44444), also EnableBroadcast is true and ExclusiveAddressUse is false.
The client sends a broadcast message to 255.255.255.255 which the server should receive and process.
The issue is that this case is inconsistent, either:

*

*The Android phone is getting the broadcast and everything works.

-or-

*mUdpServer.Receive(...) blocks forever and I don't know the root cause (mUdpServer is UdpClient).

I suspect 2 options, either some kind of race on permission handling or some OS network related issue.
Permissions related facts:

*

*I'm requesting permissions on runtime a few lines before initializing the server binding.

*My requested permissions are CHANGE_NETWORK_STATUS, ACCESS_NETWORK_STATUS and INTERNET.

*The permissions seems to always granted immediately.

Network related facts:

*

*Wireshark on the client proves the broadcast was sent.

*PCs in the same network sees that broadcast.

*Installed PCAP Remote app on my Android device, cannot see relevant packets and cannot tell if that app is reliable.

So these are my questions:

*

*Any reliable pcap recorder app for Android?

*Are there any methods to see a log of my app on the phone? (using log4net - doesn't show logs on debug mode)

*Does C# have a way of enforcing usage in a specific network interface (e.g. Wifi)?


text:
Q: How to exclude files by name in a ClearCase find command? Using the ClearCase find command, how do I find all files in a directory that do not have the name pom.xml?
I'd like to pass other selection options to the ClearCase find command so I'd prefer not to execute another command.
I am using a RedHat linux version of ClearCase.  I have tried "cleartool find ! -name pom.xml -print" and that does not work.
PS: I do not use ClearCase by choice, it's mandated on my project.  This is one of the reasons I hate it. I've read the man pages several times and see no clear way to do this that works!

A: ClearCase wildcards doesn't have inversion (AFAIR) but you can use grep for this -
cleartool ls -short -nxname | grep -v pom.xml

A: There is another solution which might work for you. Try
ccapply task

A: You seem to forget the -exec option of the cleartool find command.
It actually does allow you to execute other commands than cleartool ones, including system ones (like a sh or DOS script).
I know you would "prefer not to execute another command", but if that other system script is part of the exec option of a find command... it can be argued it is still one command ;)
So create a simple script like:
(Unix 'print.sh')
#!/bin/sh
if [ $1 != $2 ] ; then
  echo $1
fi

(windows 'print.bat')
@echo off
if not "%1"=="%2" echo "%1"

Put that script either in your search directory, or add the script path to your %PATH% or $PATH environment.
And finally, use the find command (with all the other options regarding date filtering, branch filtering and so on)
(Unix)
cleartool find . -nrec -type f -exec './print.sh $CLEARCASE_PN ./pom.xml'

(windows)
cleartool find . -nrec -type f -exec "print.bat %CLEARCASE_PN% .\pom.xml"

And here you go: "all files in a directory that do not have the name pom.xml".
Note: the '-type f' option of the find command allows you to restrict the search to file names only (not directory names).


text:
Q: Simple QThread example won't link properly I want to use QThreadSynchronizer in my class, like so
#ifndef _MULTIWATCHER
#define _MULTIWATCHER

#include <QThread>
#include <QFutureSynchronizer>

#include "globals.h"

class MultiWatcher : public QThread
{
    Q_OBJECT

public:

signals:
    void allDone();

public:
    void run() override;
    QFutureSynchronizer<FocusResult> _sync;
};

#endif

However, when I try to build this I get the following linking errors
1>C:\Qt\5.7\msvc2015_64\include\QtCore/qvector.h(134): error C2182: 'at':
illegal use of type 'void'
1>C:\Qt\5.7\msvc2015_64\include\QtCore/qvector.h(135): error C2182: '[]':
illegal use of type 'void'
1>C:\Qt\5.7\msvc2015_64\include\QtCore/qvector.h(136): error C2182: '[]':
illegal use of type 'void'

etc ...

Actually I get the same errors if I comment out the entire class (its also the same if QThreadSynchronizer  is replaced by QFuture) and just try to include the two include files, as if QThread and QFuture/QThreadSynchronizer are incompatible with each other. So the following also doesn't link!
#ifndef _MULTIWATCHER
#define _MULTIWATCHER

#include <QThread>
#include <QFuture>

#endif

Any ideas?

A: The problem was solved by changing the "Common Language RunTime Support" option from "Common Language RunTime Support /clr" to "No Common Language RunTime Support" for the moc_multiwatcher.cpp file that QT generates. These files are in "Generated Files"->Debug section of the Solution Browser, the clr setting for this file can be accessed by right clicking on it and going to properties. I hope this is useful for other people having strange linking errors in their c++/clr/QT visual studio projects.


text:
Q: elasticsearch completion suggest on multifield I'm trying to get suggestions from a multifield. I can't find examples like this, so maybe it's not the best idea, but I'm interested in your opinion.
mapping:

POST /authors
    {
       "mappings": {
          "author": {
             "properties": {
                "name": {
                   "type": "multi_field",
                   "fields": {
                      "name": {
                         "type": "string",
                         "index": "analyzed"
                      },
                      "ac": {
                         "type": "completion",
                         "index_analyzer": "simple",
                         "search_analyzer": "simple",
                         "payloads": true
                      }
                   }
                }
             }
          }
       }
    }

data:

POST /authors/author/1
    {
       "name": "Fyodor Dostoevsky"
    }

query:

POST /authors/_suggest

    {
       "authorsAutocomplete": {
          "text": "fyodor",
          "completion": {
             "field": "name.ac"
          }
       }
    }

Requirements are:

*

*get query works with text "fyodor" and also with "dostoevsky", this example works only with "fyodor"

*be enable to filter suggestions

any ideas how can I achieve these?

A: Firstly, the suggesters don't work well in multi-fields, so you could want to put it outside.
Secondly, to make you query work with both the name and firstname, you have to choose the outputs/inputs in when indexing the data.
Example of working code for SENSE:
POST authors

PUT authors/_mapping/author
{
    "properties" : {
        "name" : { "type" : "string" },
        "suggest" : { "type" : "completion"}
    }
}

POST authors/author/1
{
    "name": "Fyodor Dostoevsky",
    "suggest": {
        "input": ["Dostoevsky", "Fyodor"],
        "output": "Fyodor Dostoevsky"
    }
}

POST authors/_suggest
{
    "authorsAutocomplete": {
        "text": "d",
        "completion": {
            "field": "suggest"
        }
    }
}

DELETE authors

Result:
{
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "authorsAutocomplete": [
        {
            "text": "d",
            "offset": 0,
            "length": 1,
            "options": [
                {
                    "text": "Fyodor Dostoevsky",
                    "score": 1
                }
            ]
        }
    ]
}

Filters are not available for suggestions. To implement some kind of filtering, you can look at this blog post about the use of context in suggestions.


text:
Q: Pegar valor de um campo hidden fora do laço php Colegas
Tenho um código em php que traz do banco o valor do produto.
<?php
...
while($jmMostrar = mysqli_fetch_object($sqlMostrar)){
      $mostrar = "<input type='hidden' id='produtos' name='valorProduto' value='".$jmMostrar->ValorProduto."'>";
}

Cada $jmMostrar->ValorProduto traz um valor diferenciado. Como eu faria para pegar esses valores com jquery? Tentei dessa forma, mas ele só me traz o primeiro valor:
$('.value-plus').on('click', function(){
var qtdCarrinho = $("#qtdCarrinho").val();

A: Pode-se pegar assim:
//NOME-DO-CAMPO-HIDDEN
$("input[name='valorProduto']").each(function(){
    if($(this).val() !== undefined){
      alert($(this).val());
    }
});


text:
Q: Problem with dropdown action on Bootstrap v4 I have this sample page that I can't get the down down to work.
I have loaded jQuery, then Bootstrap, then popper (put popper before breaks things)
<!DOCTYPE html>

    <title>Bootstrap try out</title>

    <link href="//netdna.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">

<%-- these 4 lines dont work
<link href="//netdna.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">

--%>

i'm not sure what nature of screwedness is going on and its too late to go figure.  However with the new sources the pages start to work - very weird


text:
Q: Fonts required for mPDF I need few fonts files for mpdf.

*

*Arial

*Verdana

*Times New Roman

*Courier New

*Tamoha

*Goergia

*Trebuchet MS

If anybody have please share with me

A: For 4.x, here is an explanation how to convert TrueType fonts into MPDF's format.
There is also a Beta for mpdf 5 that can read TrueType Fonts directly.
As symcbean says, be aware of possible licensing issues. These fonts come for free with every Windows installation, but they are not necessarily free to distribute.

A: For non-Microsoft systems, these fonts are available via the build package here.
The licensing of the fonts is a complex and somewhat sordid story - but since the initial release preadtes UCITA (which has limited applicability anyway) you can still legitimately download and use the software under the original Microsoft EULA
C.


text:
Q: Is there a way of displaying 'Related searches' when using Google Custom Search API I am using the Google Custom Search API to display google search results on my website, however, I would like to display 'Related Searches' like the ones shown at the bottom of a normal google search.
Is this possible? And if so, how do you do it?
Thanks in advance

A: I know relatedQueries.enabled can be used in "get" format see the example for returned results as shown below, all from this link
https://developers.google.com/shopping-search/v1/reference-content-module-related-queries
GET https://www.googleapis.com/shopping/search/v1/public/products?country=US&q=shoes&relatedQueries.enabled=true&key=key

{
 "kind": "shopping#products",
 ...
 "relatedQueries": [
  "jordan shoes",
  "nike shoes",
  "dc shoes",
  "puma shoes"
 ]
 ...
 "items": [
  ...
 ]
}


text:
Q: Effective way to regexp match pandas and strip inside df? Hoping someone on here is kind enough to at least point me in the right direction. Overall, I'm trying to match regex for each row and produce the below output (in 'desired example output').
To elaborate, data is being matched from a 'Device Pool' column from a rather large CSV (all settings from a phone). I need to:

*

*input only the regexp match in the Device Pool column/row and still have it corresponding to the Directory Number 1 data. I may add other columns later

*Also strip the D in the regexp as well, as it is only useful for the
initial lookup.

Example input data(humongous file with lots of columns):
... ,Device Pool,CSS,forward 1,Directory Number 1, ...
YART01-432-D098-00-1,CSS-bobville-1,12223041234,12228675309
BART-1435-C512-00-1,CSS-willis-3,12223041234,12228215486
HOMER-1435-A134-00-1,CSS-willis-2,12223041238,12228212345
VAR05-1435-D099-00-1,CSS-willis-2,12223041897,12228215486
POA01-4-D100-00-1,CSS-hmbrgr-chz,12223043151,12228843454
...

Tried a few different approaches to no avail. with findall, I'd have to add the other columns back I guess (doesn't seem very efficient).  It was pulling the data but not the other associated columns pertaining to the row. I since dropped that direction. Surely there is a cleaner way, that might even drop the need to filter first. This is where I'm at:
df1 = pd.read.csv(some_file.csv)
dff1 = df1.filter(items=['Device Pool', 'Directory Number 1']))
df2 = dff1.loc[d1.iloc[:,0].str.contains('[D][0-9][0-9][0-9]', regex=True)]
dff2 = # stuck here

current example output:
Device Pool Directory Number 1
YART01-432-D098-00-1 12228675309
VAR05-1435-D099-00-1 12228215486
POA01-4-D100-00-1 12228843454
...

desired example output:
Device Pool Directory Number 1
098 12228675309
099 12228215486
100 12228843454

...

I'll be using these trimmed numbers to reference an address code csv, then pulling coordinates from geo location code, to then map. Pretty fun project really.

A: You can use
df['Device Pool'] = df['Device Pool'].str.replace(r'.*-D(\d+).*', r'\1', regex=True)

Or, with Series.str.extract:
df['Device Pool'] = df['Device Pool'].str.extract(r'-D(\d+)', expand=False)

See a Pandas test:
import pandas as pd
df = pd.DataFrame({'Device Pool':['YART01-432-D098-00-1', 'VAR05-1435-D099-00-1', 'POA01-4-D100-00-1'], 'Directory Number 1':['12228675309', '12228215486', '12228843454']})
df['Device Pool'].str.replace(r'.*-D(\d+).*', r'\1', regex=True)
>>> df
  Device Pool Directory Number 1
0         098        12228675309
1         099        12228215486
2         100        12228843454

The .*-D(\d+).* regex matches

*

*.*  - any zero or more chars other than line break chars as many as possible

*-D - a -D string

*(\d+) - Group 1: one or more digits

*.* - the rest of the line.