text:
Q: Разобраться в работе класса C# Нашел C# класс, для работы с SQLite3 DB.
Не могу понять, как сформировать запрос,который получит нужные данные из таблицы DB.
Далее пишу код (datalog) - это путь до файла DB , перед этим нужно , как я полагаю , сформировать запрос и подставить его в код. На SQLite библиотеке это легко сделать, но здесь я так и не разобрался, писал много чего , все безрезультатно.
      for (int rowNum = 0; rowNum < sqlHandler.GetRowCount(); ++rowNum)
    {
        //Здесь будет код который выводит полученные значения

    }

Вот сам C# класс
namespace Program
{
    internal class SqlHandler
    {
        private readonly byte[] _sqlDataTypeSize = new byte[10] {0,1,2,3,4,6,8,8,0,0};
        private readonly ulong _dbEncoding;
        private readonly byte[] _fileBytes;
        private readonly ulong _pageSize;
        private string[] _fieldNames;
        private SqliteMasterEntry[] _masterTableEntries;
        private TableEntry[] _tableEntries;
        public SqlHandler(string fileName)
        {
            _fileBytes = File.ReadAllBytes(fileName);
            _pageSize = ConvertToULong(16, 2);
            _dbEncoding = ConvertToULong(56, 4);
            ReadMasterTable(100L);
        }

        public string GetValue(int field, int rowNum)
        {
            try
            {
                if (rowNum >= _tableEntries.Length)
                    return null;
                return field >= _tableEntries[rowNum].Content.Length ? null : _tableEntries[rowNum].Content[field];
            }
            catch
            {

            }
        }

        public int GetRowCount() => _tableEntries.Length;

        private bool ReadTableFromOffset(ulong offset)
        {
            try
            {
                if (_fileBytes[offset] == 13)
                {
                    int num2 = 0;
                    if (_tableEntries != null)
                    {
                        num2 = _tableEntries.Length;
                        Array.Resize(ref _tableEntries, _tableEntries.Length + (ushort)(ConvertToULong((int)offset + 3, 2) - 1UL) + 1);
                    }
                    else
                        _tableEntries = new TableEntry[((ushort)(ConvertToULong((int)offset + 3, 2) - 1UL) + 1)];
                    for (ushort index1 = 0; index1 <= (ushort)(ConvertToULong((int)offset + 3, 2) - 1UL); ++index1)
                    {
                        ulong num3 = ConvertToULong((int)offset + 8 + index1 * 2, 2);
                        if ((long)offset != 100L)
                        {
                            num3 += offset;
                        }
                        int endIdx1 = Gvl((int)num3);
                        Cvl((int)num3, endIdx1);
                        int endIdx2 = Gvl((int)((long)num3 + (endIdx1 - (long)num3) + 1L));
                        Cvl((int)((long)num3 + (endIdx1 - (long)num3) + 1L), endIdx2);
                        ulong num4 = num3 + (ulong)(endIdx2 - (long)num3 + 1L);
                        RecordHeaderField[] array = null;
                        int index2 = 0;
                        while ((long)num4 - Gvl((int)num4) + 1L < Cvl((int)num4, Gvl((int)num4)))
                        {
                            Array.Resize(ref array, index2 + 1);
                            int endIdx4 = Gvl((int)num4);
                            int startIdx = endIdx4 + 1;
                            endIdx4 = Gvl(startIdx);
                            array[index2].Type = Cvl(startIdx, endIdx4);
                            array[index2].Size = array[index2].Type <= 9L ? _sqlDataTypeSize[array[index2].Type] : (!IsOdd(array[index2].Type) ? (array[index2].Type - 12L) / 2L : (array[index2].Type - 13L) / 2L);
                            long num6 = (long)num4 - Gvl((int)num4) + 1L;
                            num6 = (long)num4 - Gvl((int)num4) + 1L + (endIdx4 - startIdx) + 1L;
                            ++index2;
                        }
                        if (array != null)
                        {
                            _tableEntries[num2 + index1].Content = new string[array.Length];
                            int num7 = 0;
                            for (int index3 = 0; index3 <= array.Length - 1; ++index3)
                            {
                                if (array[index3].Type > 9L)
                                {
                                    if (!IsOdd(array[index3].Type))
                                    {
                                        if ((long)_dbEncoding == 1L)
                                            _tableEntries[num2 + index1].Content[index3] = Encoding.Default.GetString(_fileBytes, (int)((long)num4 + Cvl((int)num4, Gvl((int)num4)) + num7), (int)array[index3].Size);
                                        else if ((long)_dbEncoding == 2L)
                                            _tableEntries[num2 + index1].Content[index3] = Encoding.Unicode.GetString(_fileBytes, (int)((long)num4 + Cvl((int)num4, Gvl((int)num4)) + num7), (int)array[index3].Size);
                                        else if ((long)_dbEncoding == 3L)
                                            _tableEntries[num2 + index1].Content[index3] = Encoding.BigEndianUnicode.GetString(_fileBytes, (int)((long)num4 + Cvl((int)num4, Gvl((int)num4)) + num7), (int)array[index3].Size);
                                    }
                                    else
                                        _tableEntries[num2 + index1].Content[index3] = Encoding.Default.GetString(_fileBytes, (int)((long)num4 + Cvl((int)num4, Gvl((int)num4)) + num7), (int)array[index3].Size);
                                }
                                else
                                    _tableEntries[num2 + index1].Content[index3] = Convert.ToString(ConvertToULong((int)((long)num4 + Cvl((int)num4, Gvl((int)num4)) + num7), (int)array[index3].Size));
                                num7 += (int)array[index3].Size;
                            }
                        }
                    }
                }
                else if (_fileBytes[offset] == 5)
                {
                    for (ushort index = 0; index <= (ushort)(ConvertToULong((int)((long)offset + 3L), 2) - 1UL); ++index)
                    {
                        ushort num2 = (ushort)ConvertToULong((int)offset + 12 + index * 2, 2);
                        ReadTableFromOffset((ConvertToULong((int)((long)offset + num2), 4) - 1UL) * _pageSize);
                    }
                    ReadTableFromOffset((ConvertToULong((int)((long)offset + 8L), 4) - 1UL) * _pageSize);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void ReadMasterTable(long offset)
        {
            try
            {
                switch (_fileBytes[offset])
                {
                    case 5:
                        for (int index = 0; index <= (ushort)(ConvertToULong((int)offset + 3, 2) - 1UL); ++index)
                        {
                            if (offset == 100L)
                                ReadMasterTable(((long)ConvertToULong((ushort)ConvertToULong((int)offset + 12 + index * 2, 2), 4) - 1L) * (long)_pageSize);
                            else
                                ReadMasterTable(((long)ConvertToULong((int)(offset + (ushort)ConvertToULong((int)offset + 12 + index * 2, 2)), 4) - 1L) * (long)_pageSize);
                        }
                        ReadMasterTable(((long)ConvertToULong((int)offset + 8, 4) - 1L) * (long)_pageSize);
                        break;
                    case 13:
                        ulong num3 = ConvertToULong((int)offset + 3, 2) - 1UL;
                        int num4 = 0;
                        if (_masterTableEntries != null)
                        {
                            num4 = _masterTableEntries.Length;
                            Array.Resize(ref _masterTableEntries, _masterTableEntries.Length + (int)num3 + 1);
                        }
                        else
                            _masterTableEntries = new SqliteMasterEntry[checked((ulong)unchecked((long)num3 + 1L))];
                        for (ulong index1 = 0; index1 <= num3; ++index1)
                        {
                            ulong num2 = ConvertToULong((int)offset + 8 + (int)index1 * 2, 2);
                            if (offset != 100L)
                                num2 += (ulong)offset;
                            Cvl(startIdx: (int)num2, endIdx: Gvl((int)num2));
                            int endIdx2 = Gvl((int)((long)num2 + (Gvl((int)num2) - (long)num2) + 1L));
                            Cvl((int)((long)num2 + (Gvl((int)num2) - (long)num2) + 1L), endIdx2);
                            int endIdx3 = Gvl((int)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)));
                            int endIdx4 = endIdx3;
                            long[] numArray = new long[5];
                            for (int index2 = 0; index2 <= 4; ++index2)
                            {
                                int startIdx = endIdx4 + 1;
                                endIdx4 = Gvl(startIdx);
                                numArray[index2] = Cvl(startIdx, endIdx4);
                                numArray[index2] = numArray[index2] <= 9L ? _sqlDataTypeSize[numArray[index2]] : (!IsOdd(numArray[index2]) ? (numArray[index2] - 12L) / 2L : (numArray[index2] - 13L) / 2L);
                            }
                            if ((long)_dbEncoding == 1L)
                                _masterTableEntries[num4 + (int)index1].ItemName = Encoding.Default.GetString(_fileBytes, (int)((long)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)) + Cvl((int)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)), endIdx3) + numArray[0]), (int)numArray[1]);
                            else if ((long)_dbEncoding == 2L)
                                _masterTableEntries[num4 + (int)index1].ItemName = Encoding.Unicode.GetString(_fileBytes, (int)((long)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)) + Cvl((int)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)), endIdx3) + numArray[0]), (int)numArray[1]);
                            else if ((long)_dbEncoding == 3L)
                                _masterTableEntries[num4 + (int)index1].ItemName = Encoding.BigEndianUnicode.GetString(_fileBytes, (int)((long)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)) + Cvl((int)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)), endIdx3) + numArray[0]), (int)numArray[1]);
                            _masterTableEntries[num4 + (int)index1].RootNum = (long)ConvertToULong((int)((long)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)) + Cvl((int)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)), endIdx3) + numArray[0] + numArray[1] + numArray[2]), (int)numArray[3]);
                            if ((long)_dbEncoding == 1L)
                                _masterTableEntries[num4 + (int)index1].SqlStatement = Encoding.Default.GetString(_fileBytes, (int)((long)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)) + Cvl((int)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)), endIdx3) + numArray[0] + numArray[1] + numArray[2] + numArray[3]), (int)numArray[4]);
                            else if ((long)_dbEncoding == 2L)
                                _masterTableEntries[num4 + (int)index1].SqlStatement = Encoding.Unicode.GetString(_fileBytes, (int)((long)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)) + Cvl((int)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)), endIdx3) + numArray[0] + numArray[1] + numArray[2] + numArray[3]), (int)numArray[4]);
                            else if ((long)_dbEncoding == 3L)
                                _masterTableEntries[num4 + (int)index1].SqlStatement = Encoding.BigEndianUnicode.GetString(_fileBytes, (int)((long)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)) + Cvl((int)(num2 + (ulong)(endIdx2 - (long)num2 + 1L)), endIdx3) + numArray[0] + numArray[1] + numArray[2] + numArray[3]), (int)numArray[4]);
                        }
                        break;
                }
            }
            catch
            {
            }
        }

        public bool ReadTable(string tableName)
        {
            try
            {
                int index1 = -1;
                for (int index2 = 0; index2 <= _masterTableEntries.Length; ++index2)
                {
                    if (string.Compare(_masterTableEntries[index2].ItemName.ToLower(), tableName.ToLower(), StringComparison.Ordinal) == 0)
                    {
                        index1 = index2;
                        break;
                    }
                }
                if (index1 == -1)
                    return false;
                string[] strArray = _masterTableEntries[index1].SqlStatement.Substring(_masterTableEntries[index1].SqlStatement.IndexOf("(", StringComparison.Ordinal) + 1).Split(',');
                for (int index2 = 0; index2 <= strArray.Length - 1; ++index2)
                {
                    strArray[index2] = strArray[index2].TrimStart();
                    int length = strArray[index2].IndexOf(' ');
                    if (length > 0)
                        strArray[index2] = strArray[index2].Substring(0, length);
                    if (strArray[index2].IndexOf("UNIQUE", StringComparison.Ordinal) != 0)
                    {
                        Array.Resize<string>(ref _fieldNames, index2 + 1);
                        _fieldNames[index2] = strArray[index2];
                    }
                }
                return ReadTableFromOffset((ulong)(_masterTableEntries[index1].RootNum - 1L) * _pageSize);
            }
            catch
            {
                return false;
            }
        }

        private ulong ConvertToULong(int startIndex, int size)
        {
            try
            {
                if (size > 8 | size == 0)
                    return 0;
                ulong num = 0;
                for (int index = 0; index <= size - 1; ++index)
                    num = num << 8 | _fileBytes[startIndex + index];
                return num;
            }
            catch
            {
                return 0;
            }
        }

        private int Gvl(int startIdx)
        {
            try
            {
                if (startIdx > _fileBytes.Length)
                    return 0;
                for (int index = startIdx; index <= startIdx + 8; ++index)
                {
                    if (index > _fileBytes.Length - 1)
                        return 0;
                    if ((_fileBytes[index] & 128) != 128)
                        return index;
                }
                return startIdx + 8;
            }
            catch
            {
                return 0;
            }
        }

        private long Cvl(int startIdx, int endIdx)
        {
            try
            {
                ++endIdx;
                byte[] numArray = new byte[8];
                int num1 = endIdx - startIdx;
                bool flag = false;
                if (num1 == 0 | num1 > 9)
                    return 0;
                if (num1 == 1)
                {
                    numArray[0] = (byte)(_fileBytes[startIdx] & (uint)sbyte.MaxValue);
                    return BitConverter.ToInt64(numArray, 0);
                }
                if (num1 == 9)
                    flag = true;
                int num2 = 1;
                int num3 = 7;
                int index1 = 0;
                if (flag)
                {
                    numArray[0] = _fileBytes[endIdx - 1];
                    --endIdx;
                    index1 = 1;
                }
                int index2 = endIdx - 1;
                while (index2 >= startIdx)
                {
                    if (index2 - 1 >= startIdx)
                    {
                        numArray[index1] = (byte)(_fileBytes[index2] >> num2 - 1 & byte.MaxValue >> num2 | _fileBytes[index2 - 1] << num3);
                        ++num2;
                        ++index1;
                        --num3;
                    }
                    else if (!flag)
                        numArray[index1] = (byte)(_fileBytes[index2] >> num2 - 1 & byte.MaxValue >> num2);
                    index2 += -1;
                }
                return BitConverter.ToInt64(numArray, 0);
            }
            catch
            {
                return 0;
            }
        }

        private static bool IsOdd(long value)
        {
            return (value & 1L) == 1L;
        }

        private struct RecordHeaderField
        {
            public long Size;
            public long Type;
        }

        private struct TableEntry
        {
            public string[] Content;
        }

        private struct SqliteMasterEntry
        {
            public string ItemName;
            public long RootNum;
            public string SqlStatement;
        }
    }
}

A: Этот класс на низком уровне (байты, смещения, чтения из файла) считывает таблицу из базы SQLite, складывает её в массив и позволяет из этого массива получать значения конкретных полей. Никакого SQL в нём не предусмотрено, но можно что-то делать со значениями колонок, если Вы знаете их номера:
for (int rowNum = 0; rowNum < sql.GetRowCount(); ++rowNum)
{
     Console.WriteLine(sql.GetValue(0,i));
     Console.WriteLine(sql.GetValue(1,i));
     //И так далее

}


text:
Q: MySQL UPDATE query - dealing with empty inputs This is my first UPDATE query, I have checked using jQuery for any empty fields. I want the user to input at least one field and then update the field(s). Doing a query with all the $_POST names might generate empty or undefined input fields in my database which doesn't work.. here is my query:
$first = $_POST['first'];
$last = $_POST['last'];
$birth = $_POST['birth'];
$bio = $_POST['bio'];

$UID = $_SESSION['id'];

$query = "UPDATE `user` SET `firstname`=$first,`lastname`=$last,`birthday`=$birth,`biography`=$bio WHERE `user_id` = '$UID'";
$result = mysql_query($query) or die($result . "

" . mysql_error());

The error:
syntax to use near 'birthday=,biography= WHERE user_id = '11'' at line 1
I don't want to go through nested if's to check whether has a value or not. Thanks.

A: NOTE: Use mysql_real_escape_string() to prevent from sql injection.
if( !empty($first) &&
    !empty($last) &&
    !empty($birth) &&
    !empty($bio) ){

$query = "UPDATE `user`
             SET
               `firstname`='$first',
               `lastname`='$last',
               `birthday`='$birth',
               `biography`='$bio'
           WHERE `user_id` = '$UID'";
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to mantain aspect ratios after overlay in geopandas? I'm trying to overlay some cities on top of a map.

import pandas as pd
import geopandas as gdp
import matplotlib.pyplot as plt
from shapely.geometry import box

destinations = ["Oslo", "Bergen", "Trondheim", "Tromsø", "Nordkapp", "Bodø", "Lofoten"]
world = gdp.read_file(gdp.datasets.get_path('naturalearth_lowres'))
norway = world[world.name=="Norway"]
norway =gdp.clip(norway, box(0, 0, 60,75)) # removing Svalbard
cities = world = gdp.read_file(gdp.datasets.get_path('naturalearth_cities'))
df = pd.read_csv("norway_cities.csv", sep=";")
norway_cities = gdp.GeoDataFrame(df, geometry=gdp.points_from_xy(df.lng, df.lat))

ax = norway.plot(color='white', edgecolor='black')
ax = cities[cities.name=="Stockholm"].plot(ax=ax, color='red')
ax = norway_cities[norway_cities.city.isin(destinations)].plot(ax=ax, color='blue')
plt.show()

Proportions are mantained when I plot Stockholm coordinates:

Things get distorted when I plot the rest:

Data are coming from different sources but the scale seems to be the same:

Changing the figure size does not affect the results, how do I keep the same aspect ratio of the first picture?

A: When constructing norway_cities you have not defined the CRS.
norway_cities = gdp.GeoDataFrame(
    df, geometry=gdp.points_from_xy(df.lng, df.lat), crs="epsg:4386"
)

full code

*

*get cities from a web page as I do not have access to your CSV

import pandas as pd
import geopandas as gdp
import matplotlib.pyplot as plt
from shapely.geometry import box
import requests, io

destinations = ["Oslo", "Bergen", "Trondheim", "Tromsø", "Nordkapp", "Bodø", "Lofoten"]
world = gdp.read_file(gdp.datasets.get_path("naturalearth_lowres"))
norway = world[world.name == "Norway"]
norway = gdp.clip(norway, box(0, 0, 60, 75))  # removing Svalbard
cities = world = gdp.read_file(gdp.datasets.get_path("naturalearth_cities"))
# df = pd.read_csv("norway_cities.csv", sep=";")
df = pd.read_csv(
    io.StringIO(
        requests.get("https://simplemaps.com/static/data/country-cities/no/no.csv").text
    )
)
norway_cities = gdp.GeoDataFrame(
    df, geometry=gdp.points_from_xy(df.lng, df.lat), crs="epsg:4386"
)

ax = norway.plot(color="white", edgecolor="black")
ax = cities[cities.name == "Stockholm"].plot(ax=ax, color="red")
ax = norway_cities[norway_cities.city.isin(destinations)].plot(ax=ax, color="blue")
plt.show()


text:
Q: Use "WHERE CURRENT OF" clause to update only the specific row on which the CURSOR is positioned in SQL I have the following cursor in SQL:
DECLARE @Script varchar(max)

DECLARE @getScript CURSOR

SET @getScript = CURSOR FOR

SELECT [Script]
FROM ScriptTable

OPEN @getScript
FETCH NEXT
FROM @getScript INTO @Script

WHILE @@FETCH_STATUS = 0
BEGIN
    BEGIN TRY
        EXEC(@Script) --Working part.  This executes the query stored in the Script column.
                      --For example INSERT INTO zTest VALUES(VAL1, VAL2, etc etc..)

        UPDATE ScriptTable
        SET DateDone = GETDATE(), IsDone = 1, Err = NULL
        FETCH NEXT
        FROM @getScript INTO @Script
    END TRY
    BEGIN CATCH
        DECLARE @Err varchar(max)
        SET @Err = ERROR_MESSAGE()

        UPDATE ScriptTable
        SET DateDone = GETDATE(), Err = @Err

    END CATCH
END

CLOSE @getScript
DEALLOCATE @getScript

Q1:
Currently, I am getting the values inserted into the "zTest" table specified in my comments when I execute EXEC(@Script).
However, the second part where the "Update ScriptTable" is, updates all the rows in my Script Table.  I know I need to specify the ID for the appropriate row that the cursor is moving through.  Question is, how can I do that?  I wan't to only update the appropriate row, move to the next then update that one.
Q2:
My next question is, in the CATCH block, I think I am creating an infinite loop as soon as there is an error in one of the queries in the Script Column of the ScriptTable as when I look at results, it just keeps going and going.  I don't want to BREAK; the procedure as I want to write an error to the Err column and continue with the next rows till it reaches the end of @Script, then stop.
IDENT_CURRENT, Scope_Identity etc doesn't work because I haven't inserted anything into the Scripts Table.
Please help.

A: Regarding Q1, you have to have a primary key in order to use the cursor for updating (though there are workarounds).
In general you'll want syntax something like this:
update ScriptTable
 SET DateDone = GETDATE(), IsDone = 1, Err = NULL
where ID of @getScript

Regarding Q2, it make sense that it's an infinite loop. When you use the TRY and CATCH clauses  and it fails it doesn't execute any of the syntax in the TRY "area".
Therefor the FETCH NEXT gets skipped, and in the next loop the same error happens again.
Try to make sure there is always a FETCH NEXT in the loop.
Hope this helps you out a bit.

A: Here is my final code if anyone is interested:
DECLARE @Script varchar(max)

        DECLARE @getScript CURSOR

        SET @getScript = CURSOR FOR

        SELECT [Script]
        FROM ScriptControl

        OPEN @getScript
        FETCH NEXT
        FROM @getScript INTO @Script

        DECLARE @Counter int = 1
        WHILE @@FETCH_STATUS = 0
        BEGIN
            BEGIN TRY
                EXEC(@Script)

                    UPDATE ScriptControl
                    SET DateDone = GETDATE(), IsDone = 1, Error = NULL WHERE ID = @Counter

                FETCH NEXT
                FROM @getScript INTO @Script

                SET @Counter = (@Counter + 1)
            END TRY
            BEGIN CATCH
                DECLARE @Err varchar(max)
                SET @Err = ERROR_MESSAGE()

                UPDATE ScriptControl
                SET CSC_EOD_DateDone = NULL, CSC_EOD_Err = @Err, CSC_EOD_IsDone = 0 WHERE CURRENT OF @getScript

                FETCH NEXT
                FROM @getScript INTO @Script

                SET @Counter = (@Counter + 1)
            END CATCH
        END

        CLOSE @getScript
        DEALLOCATE @getScript

A: This:
DECLARE @ScriptControlId INT, @Script VARCHAR(MAX)

DECLARE @getScript CURSOR
SET @getScript = CURSOR FOR
SELECT [ID], [Script]
FROM ScriptControl

OPEN @getScript
FETCH NEXT
FROM @getScript INTO @ScriptControlId, @Script

WHILE @@FETCH_STATUS = 0
BEGIN
    BEGIN TRY
        EXEC(@Script)

        UPDATE ScriptControl
        SET DateDone = GETDATE(), IsDone = 1, Error = NULL
        WHERE ID = @ScriptControlId

        FETCH NEXT FROM @getScript INTO @ScriptControlId, @Script
    END TRY
    BEGIN CATCH
        DECLARE @Err VARCHAR(MAX) = ERROR_MESSAGE()

        UPDATE ScriptControl
        SET DateDone = NULL, Error = @Err, IsDone = 0
        WHERE CURRENT OF @getScript

        FETCH NEXT FROM @getScript INTO @ScriptControlId, @Script
    END CATCH
END

CLOSE @getScript
DEALLOCATE @getScript

Or this:
DECLARE @Script VARCHAR(MAX)

DECLARE @getScript CURSOR
SET @getScript = CURSOR FOR
SELECT [Script]
FROM ScriptControl

OPEN @getScript
FETCH NEXT
FROM @getScript INTO @Script

WHILE @@FETCH_STATUS = 0
BEGIN
    BEGIN TRY
        EXEC(@Script)

        UPDATE ScriptControl
        SET DateDone = GETDATE(), IsDone = 1, Error = NULL
        WHERE CURRENT OF @getScript

        FETCH NEXT FROM @getScript INTO @Script
    END TRY
    BEGIN CATCH
        DECLARE @Err VARCHAR(MAX) = ERROR_MESSAGE()

        UPDATE ScriptControl
        SET DateDone = NULL, Error = @Err, IsDone = 0
        WHERE CURRENT OF @getScript

        FETCH NEXT FROM @getScript INTO @Script
    END CATCH
END

CLOSE @getScript
DEALLOCATE @getScript


text:
Q: reuse redux reducers and actions Lets say I have a section reducer to hold the section's data
const initialState = {
  data: [],
  section: ''
};

const sectionReducer = function(state = initialState, action) {
  switch(action.type) {
    case types.IMPORT_DATA_SUCCESS:
      return Object.assign(
        {},
        state,
        {
          section: action.section,
          data: action.data
        }
      );
  }
  return state;
}

And I need couple sections with the same data structure and actions. Then how can I do it like this
import { combineReducers } from 'redux';
import sectionReducer from './sectionReducer';

const reducers = combineReducers({
  sectionA: sectionReducer,
  sectionB: sectionReducer
});

export default reducers;

The action is as simple as
import sectionAData from '../data/sectionAData';
...
export const importDataSuccess = (section, data) => {
  return {
    type: types.IMPORT_DATA_SUCCESS,
    section: section,
    data
  }
}

export const loadData = (section) => {
  const dataSet = (() => {
    switch(section) {
      case "SECTIONA":
        return sectionAData
        break;
      case "SECTIONB":
        return sectionBData
        break;
    }
  })()
  return (dispatch) => {
    dispatch(importDataSuccess(section, dataSet))
  }
}

The problem with above approach is everytime I call this.props.dispatch(loadData("SECTIONA")) on componentA and this.props.dispatch(loadData("SECTIONB")) on componentB I get sectionBData on both state tree sectionA and sectionB. Even when sectionA is first dispatched, the sectionB already populated with sectionA data even though it has not been dispatched.
What is  the proper way to reuse the reducer and action for such case? Or do I have to create action and reducer for each section even though they are the same?
======= UPDATE =====
Reducer
const initialState = {
  data: []
};
const sectionReducer = function(state = initialState, action) {
  switch(action.type) {
    case types.IMPORT_DATA:
      if ( action.section ) {
        return state.data.push({ section: action.section, data: action.data });
      }
    break;
  }
  return state;
}
...
const reducers = combineReducers({
  sections: sectionReducer
});
export default reducers;

Action
export const importData= (section, data) => {
  return {
    type: types.IMPORT_DATA,
    section,
    data
  }
}
export const loadData = (section) => {
  const dataSet = (() => {
    switch(section) {
      case "SECTIONA":
        return sectionAData
        break;
      case "SECTIONB":
        return sectionBData
        break;
    }
  })()
  return (dispatch) => {
    dispatch(importData(section, dataSet))
  }
}

The component
class SectionWrapper extends Component {
  componentDidMount() {
    this.props.dispatch(loadData(this.props.const))
  }
  render() {
    return (
      <div>
        <Section
          title={this.props.title}
          id={this.props.id}
          data={this.props.data} />
      </div>
    )
  }
}
const mapStateToProps = function(store, ownProps) {
  const section = store.sections.find( (item) => { return item.section === ownProps.const; })
  const data = section.data
  return {
    data
  };
}
SectionWrapper.propTypes = {
  title: PropTypes.string.isRequired,
  id: PropTypes.string.isRequired,
  const: PropTypes.string.isRequired
}
export default connect(mapStateToProps)(SectionWrapper);

Store
const createStoreWithMiddleware  = compose(
  applyMiddleware(
    thunkMiddleware,
    createLogger()
  ),
  window.devToolsExtension ? window.devToolsExtension() : f => f
)

const store = createStore(
  reducers,
  createStoreWithMiddleware
);

export default store;

A: Right now, when sectionReducer receives an action of type IMPORT_DATA_SUCCESS, It replaces the entire state with the data received... so there could be only one section and data in the state., Which is obviously what you don't want.
What you can do is, In your sectionReducer
const initialState = {
  data: [],
};

const sectionReducer = function(state = initialState, action) {

  switch(action.type) {
    case types.IMPORT_DATA_SUCCESS:
      // action contains { type, section, data }
      // added if statement to make sure data is not empty.
      if ( action.section && action.data ) {
        state.data.push({ section: action.section, data: action.data });
        return Object.assign( {}, state );
      }
      return state;

    case types.UPDATE_IMPORTED_DATA:
      // action contains { section, data }
      let index = state.data.findIndex( item => { return item.section === action.section; });
      state.data[index] = { section: action.section, data: action.data }
      return state;

    default:
     return state;

  }

}

Using this method you can store n number of sections and also update them very easily.
And when you want to access the data of specific section, you can do
let findSectionByName = ( sections, section_name ) => {
  return sections.find( (item) => { return item.section === section_name; })
}
let section = findSectionByName( state.sections, 'SECTIONA' );

You will also have to change
const reducers = combineReducers({
  sectionA: sectionReducer,
  sectionB: sectionReducer
});

to
const reducers = combineReducers({
  sections: sectionReducer,
});


text:
Q: In R, how to remove everything before the last slash I have a dataset say
x <- c('test/test/my', 'et/tom/cat', 'set/eat/is', 'sk / handsome')

I'd like to remove everything before (including) the last slash, the result should look like
my cat is handsome

I googled this code which gives me everything before the last slash
gsub('(.*)/\\w+', '\\1', x)
[1] "test/test" "et/tom"    "set/eat"   "sk / tie"

How can I change this code,  so that the other part of the string after the last slash can be shown?
Thanks

A: Using strsplit
> sapply(strsplit(x, "/\\s*"), tail, 1)
   [1] "my"       "cat"      "is"       "handsome"

Another way for gsub
> gsub("(.*/\\s*(.*$))", "\\2", x) # without 'unwanted' spaces
[1] "my"       "cat"      "is"       "handsome"

Using str_extract from stringr package
> library(stringr)
> str_extract(x, "\\w+$") # without 'unwanted' spaces
[1] "my"       "cat"      "is"       "handsome"

A: You can basically just move where the parentheses are in the regex you already found:
gsub('.*/ ?(\\w+)', '\\1', x)

A: You could use
x <- c('test/test/my', 'et/tom/cat', 'set/eat/is', 'sk / handsome')
gsub('^(?:[^/]*/)*\\s*(.*)', '\\1', x)

Which yields
[1] "my"       "cat"      "is"       "handsome"

To have it in one sentence, you could paste it:
(paste0(gsub('^(?:[^/]*/)*\\s*(.*)', '\\1', x), collapse = " "))

The pattern here is:

^            # start of the string
(?:[^/]*/)*  # not a slash, followed by a slash, 0+ times
\\s*         # whitespaces, eventually
(.*)         # capture the rest of the string

This is replaced by \\1, hence the content of the first captured group.

A: You can use basename:
paste(trimws(basename(x)),collapse=" ")
# [1] "my cat is handsome"


text:
Q: Cannot mount SD using FatFS on STM32 I'm trying to write to a MicroSD-Card using STM32F405 chip.
The pins are connected correctly and each pin on the MicroSD-Card slot can be written to by using HAL_GPIO_WritePin. (Messured with ossciloscope) I'm using CubeMX to generate the init code for TrueStudio, so hopefully everything is ok there as well. But when I run the following code, f_mount returns FR_DISK_ERR. The MicroSD-Card can be written to and read from. If I use a different Device number, i.e. "1:", I get FR_INVALID_DRIVE
So my question is: what could cause FR_DISK_ERR except a faulty MicroSD-Card?
Here is my code so far:
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_SDIO_SD_Init();
  MX_FATFS_Init();

  /* USER CODE BEGIN WHILE */
  FATFS fileSystem;
  FIL testFile;
  uint8_t testBuffer[16] = "SD write success";
  UINT testBytes;
  FRESULT res;

  while((res = f_mount(&fileSystem, SD_MOUNT_PATH, 1)) != FR_OK){
      printf("%d", res); //used to debug res, only for TrueStudio Debugger
  }

    uint8_t path[13] = "testfile.txt";
    path[12] = '\0';

    res = f_open(&testFile, (char*)path, FA_WRITE | FA_CREATE_ALWAYS);

    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_6, GPIO_PIN_RESET);
    res = f_write(&testFile, testBuffer, 16, &testBytes);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, GPIO_PIN_RESET);

    res = f_close(&testFile);
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_RESET);

}

in MX_FATFS_Init() FATFS_LinkDriver(&SD_Driver, SD_Path) is called and returns 0.

A: Without the SD_MOUNT_PATH macro, does the f_mount call look like this:
f_mount(&fileSystem, "0:", 1) ?'
Are you saying that f_open, f_write return FR_OK even if f_mount fails?!
FR_DISK_ERR usually means disk_read() or disk_write() failed. Try giving 100ms or 1 sec delay before using f_mount() and between between fatfs function calls.


text:
Q: Customize Dropdown Select with CSS I'm trying to get my dropdown button to look like this one:
https://www.progressive.com/auto/
And can't workout how to get the arrow looking like that on the form field. Can anyone help or suggest where to start?
Just to confirm I am only looking for the button itself, not what happens after it is clicked.
jsfiddle:
https://jsfiddle.net/6e4px6La/1/
    <label class="select-label">
            <select id="Type" class="size-select" name="customer_type">
<option value="" disabled selected>Please Select</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
            </select>
          </label>

CSS:
select {
background-color: #fff;
border-color: #979797;
border-style: solid;
border-width: 1px;
width: 250px;
margin-left: 10px;
height: 50px;
}

Thanks in advance!

A: You need to add the following code to your CSS
.selectParent select {
border-color: #979797;
border-style: solid;
border-width: 1px;
width: 250px;
margin-left: 10px;
height: 50px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
background: url("IMAGE_URL") no-repeat 235px center #fff;
}

Replace the IMAGE_URL with the source of the image you want to put as the dropdown arrow.
Here is the JSFiddle with an example for the same


text:
Q: How to escape json character (Double quote, Comma ) in php I am doing php project using  php excel.. I have already created php class for read excel sheet. That class return  simple json string .. That json string i will use for  show data table in web page. But that json string can't include any json character . Therefore user can not input some json character in excel sheet . Otherwise so many errors create when encoding json string .
What is the best way prevent this problem?
have some good way to read excel sheet (Using library)?

A: Slash should be added after the quotations (escaping it)
<?php
$str = "Is your name O'Reilly?";

// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>

Here you are an approach suitable for JSON.
function json_string_encode($str) {
    $callback = function($match) {
        if ($match[0] === '\\') {
            return $match[0];
        } else {
            $printable = array('"' => '"', '\\' => '\\', "\b" => 'b', "\f" => 'f', "\n" => 'n', "\r" => 'r', "\t" => 't');
            return isset($printable[$match[0]])
                   ? '\\'.$printable[$match[0]]
                   : '\\u'.strtoupper(current(unpack('H*', mb_convert_encoding($match[0], 'UCS-2BE', 'UTF-8'))));
        }
    };
    return '"' . preg_replace_callback('/\\.|[^\x{20}-\x{21}\x{23}-\x{5B}\x{5D}-\x{10FFFF}/u', $callback, $str) . '"';
}


text:
Q: How to configure PHPUnit to test the whole vendor folder in a ZF2 application? I'm developing a Zend Framework 2 application with a common folder structure, so that the folder /vendor contains all (project external) libraries. Setting up the unit testing environment I would like to be able to run all vendor tests. The folders structures are different depending on the library. Some packages have no tests at all.
A possible solution would be to create a test suite "vendor" and manually define there the paths to every single test folder, e.g.:
phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit ...>
    <testsuites>
        <testsuite name="vendor">
            <directory>../vendor/lib-foo/path/to/tests</directory>
            <directory>../vendor/package-bar/path/to/tests</directory>
            ...
        </testsuite>
        ...
    </testsuites>
    ...
</phpunit>

I don't like this solution. First of all because then I'd have to handle every package manually.
Another solution would be to define /vendor as test folder:
phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit ...>
    <testsuites>
        <testsuite name="vendor">
            <directory>../vendor</directory>
            ...
        </testsuite>
        ...
    </testsuites>
    ...
</phpunit>

Well, but then PHPUnit has to scan a lot of folders, that it doesn't need, and the tests will need much more time.
Is there a better solution, that would make possible to automate the process and avoid much manual configuration?

A: It would probably be difficult to run all PHPUnit vendor test suites with a single test run. One issue is that each of the different test suites might ship its own configuration file or even require a custom bootstrap configuration file. You cannot cover that when running all test suites with a single command.
I'd probably use some shell magic for this. Note that this example relies on the presence of a phpunit.xml(.dist) file in each of your 3rd party packages (for most libraries that's a reasonable assumption). You could even integrate this into your continuous integration process to test this continuously:
for FILE in $(find . -name 'phpunit.xml*') ; do
    sh -c 'cd '$(dirname $FILE)' && composer install'
    vendor/bin/phpunit -c $FILE
done


text:
Q: Zend framework 2 load php file with constants I have a file called Message.php in module/Cms/language directory. This file contain constants like below
<?php
define("APPLICATION_TITLE","Test Application");
?>

When module is running I would like to use such constant anywhere in the module scope. I understand I can load this by modifying config_glob_paths in application.config.php
But I am looking for a way where this file will be loaded only for the module specified. Can I have some configuration in module.config.php for this. Appreciate your guidance.

A: To define the contants when the module CMS loads use the Module::onBootstrap() method.
class Module
{
    public function onBootstrap(Event $e)
    {
       include_once( __DIR__  . '/language/English.php');
    }
}

More information about the bootstrap event is documented here.
Optionally the Module class can implement the Zend\ModuleManager\Listener\OnBootstrapListener. Which is documented here.


text:
Q: retrieve matrix from ANN using sci-kit learn USing python 3.5, I do the following
from sklearn.neural_network import MLPRegressor
import pandas as pd

from sklearn import datasets
from sklearn.decomposition import PCA
# import some data to play with
iris = datasets.load_iris()
X = iris.data[0:100, :2]  # we only take the first two features.
Y = iris.target[0:100]

X = StandardScaler().fit_transform(X)

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.15)
reg = MLPRegressor(hidden_layer_sizes=(10,),
                           solver="lbfgs", #solver="lbfgs",
                           max_iter = 10000,
                           activation = 'relu')
reg.fit(X_train,y_train)

i can get the matrix using reg.coefs_[0] but when I multiply it by a test case, I don't get 0 or 1
what I'm trying to do is train an ANN based on lab data, and then implement it as matrix multiplication on a piece of hardware.  The hardware can do basic arithmetic, so I need to deconstruct my ANN into a matrix, and then program matrix multiplication as iterated multiplication/addition

A: The short, "specific to this question" answer is
np.dot((np.dot(X_test[0],reg.coefs_[0]) +reg.intercepts_[0] ),reg.coefs_[1]) + reg.intercepts_[1]

The long answer is as follows (even longer version here: https://www.mohammadathar.com/blog/2017/2/15/a-different-look-at-neural-networks )
A perceptron neural net can be modeled like this:
What that really means, is "multiply input values by a weight, and add.  then add in a bias value.  Then activate.  Then multiply by weights, and add.  Then activate.  And repeat!"
As matrix math, it looks like this

So the reg.coefs_ is the matrix coefficients (per layer) and the reg.intercepts_ is the activation values (again, per layer)


text:
Q: protected internal class working within class but not working outside I was trying few things and would like to know why this is happening so.
Say, I have a class called A in namespace n and I was trying to create protected internal class B.
namespace n
{
   public class A
   {
      public A()
      {
      }
   }
   protected internal class B //throwing error
   {
   }
}

But when i try like this (B as a sub class of A), its not throwing error and its built success. Could you explain me why it is so?
namespace n
{
   public class A
   {
      public A()
      {
      }
      protected internal class B // its not throwing error
      {
      }
   }
}

Am i missing anything theoretically? Its quite a bit confusing.

A: A class can't be protected except when it is inside another class.
The protected keyword is only valid for members of a class. In your second example, class B happens to be that member.
Think about it:
protected means: Derived classes can access this member.
As there is no such concept as derived namespaces, the protected keyword doesn't make sense for members of a namespace.

A: Look at the error.

Elements defined in a namespace cannot be explicitly declared as
  private, protected, or protected internal

Only internal or public members are allowed outside the class.
Your second case is defining the class B as member of class A that is why you are not getting the error.
You may see Access Modifiers C#

Classes and structs that are declared directly within a namespace (in
  other words, that are not nested within other classes or structs) can
  be either public or internal. Internal is the default if no access
  modifier is specified.

A: protected declares visiblity level for derived types.
In your first case you declare class inside namespace. There is no any polymophic support for namespaces, so there is no any sence of using protected classes in namespace
In second case, instead, you use it inside other classe (class A), which make it visible for all children of A class.


text:
Q: difference between queries I'm building queries in HQL with join, and i've stack over one thing:
my query looks like:
From HistoryPerPhraseEntity as history left join history.linkAddressByLinkId where history.serviceId = :serviceId

and the query was fine, but when i was trying to throw response into my DataBase object and try to get values like this:
historyPhrase.get(0).getPhraseId()

i've got:
[Ljava.lang.Object; cannot be cast to com.rasp.lta.domain.HistoryPerPhraseEntity

but after change into this:
Select history From HistoryPerPhraseEntity as history left join history.linkAddressByLinkId where history.serviceId = :serviceId

everything is ok.
Could anybody answer why i need "Select from" in this query?
Thanks

A: Because without explicit SELECT Hibernate cannot figure out that only instances HistoryPerPhraseEntity should be returned. It returns also joined entities.
That's why it returns List of Object arrays. First index of array contains HistoryPerPhraseEntity and type of object in second index is same as type of element in linkAddressByLinkId collection.
If you for some reason want to access only HistoryPerPhraseEntity's returned by first query, that can be done by casting each element of returned list to Object[] and casting Object[0] to HistoryPerPhraseEntity
Better to use SELECT though.


text:
Q: Restricting outlook search to a specific TO list Is it possible to restrict search in outlook to only a specific TO list?
Example:
When I type in the search criteria
TO:(Bob AND Jean)

it finds all emails where both Bob and Jean are in the TO list, apart from other people.
I want to find all emails that were sent ONLY to Bob and Jean. Exclude emails where there are other people in the TO list.
System Info:
Microsoft Outlook, Microsoft Office Professional Plau 2013
Windows 8.1

A: What you want is too granular. It can not be done. The Sent To field looks for e-mails in the the TO or CC. It will look for any e-mails where Bob or Jean are in the TO or CC. You can perform a search based on the message header, but you'd need many variations of Bob and Jean that it would not be very practical. You can filter e-mails sent only TO you, but not sent TO other specific people.


text:
Q: Apache is guessing the extension When i go to /index/test i get /index.php/test. I would like to be able to mod rewrite from /index/page1 to /index.php?page=1 but even without any .htaccess file i get the index file without the variale.
It seems that my server is set to guess the extension and get the file if it exists. Is a Mac os X Server 10.6 with standard configuration (apache2).
Any ideas?

A: I found that multiviews was set by default in /etc/apache2/sites/0001_any_80_[mydomain].conf
Just change +MultiViews to -MultiViews in:
Options All -Includes -ExecCGI -Indexes +MultiViews

A: There is an extension called mod_spelling that could also be the culprit


text:
Q: Ordered triple condition Compute the number of ordered triples $(a,b,c)$ of positive integers such that
$$a2^b + b2^c + c2^a = 2000.$$
I tried to make some bijection but no luck.
I have tried setting some variables to see if stars and bars (or balls and urns) works, as well as casework counting.

A: On investigation numerically, there are no positive integer triples $(a,b,c)$ for which the function $ f(a,b,c) := a2^b + b2^c + c2^a$ fulfils the condition
$$  f(a,b,c) = 2\cdot 10^k $$
for any value of $k\in \mathbb N$ up to $600$.
Allowing $a,b,c$ to also be zero (but forbidding any of $2^a, 2^b, 2^c$ to be greater than the target value) gives us effectively one solution in that space, $f(1,4,0) = 20$, so also $(4,0,1)$ and $(0,1,4)$.
The closest approach to the original problem (where $k=3$) is $f(5,8,6)=1984$

I might have become a little obsessed with the form $a2^b + b2^c + c2^a$ ...
Anyway the original format above has no solutions out to $2\cdot 10^{10000}$.
I also had a quick look at variations in the form $a2^b + b2^c + c2^a = N^k$ (just for fun) and

*

*$4\cdot 2^5 +5\cdot 2^3 +3\cdot 2^4 = 6^3$  (quite pretty, all low numbers)

*$13\cdot 2^{17}+ 17\cdot 2^{14} + 14\cdot 2^{13} = 8^7$, weirdly

*$3\cdot 2^9 +  9\cdot 2^7 +  7\cdot 2^3 = 14^3$ and

*$2\cdot 2^7 + 7\cdot 2^3 + 3\cdot 2^2 = 18^2$


text:
Q: Convert to list a object with anonymous type I need convert to list a object with anonymous type because when i databind the gridview i get
"The data source does not support server-side data paging"
or How i can solve this?
object o =  HttpRuntime.Cache[key];

if(o is ICollection)
{
    //Sort Object
    o = ((IQueryable)this.DataSource).AsQueryable().OrderBy(SortExpresion);

    DataSource = o;

    DataBind();

}

data returned from cache are ok, the problem is that i extended the gridview control and the data type of datasource is always different, and i need sort this anonymous data stored in cache and use in the gridview

A: Reason is IQueryable does not support paging. You need to convert it to a more concrete type like List<T> or as REA_ANDREW suggested, PagedDataSource.
Example:
o = ((IQueryable)this.DataSource).AsQueryable().OrderBy(SortExpresion).ToList();

A: Set the datasource of a PagedDataSource class and then assign this object as the datasource of your gridview.  Otherwise, create an object datasource and bind that to your gridview.
Andrew


text:
Q: Functor Connected Component and Indescrete functor i have the next doubts about the following functors:
1)
$Ind: Set\rightarrow Cat$
Which  $Ind(A)$ is the category whose objects are elements of $A$, i mean
$Obj(Ind(A))=A$, And $Hom_{Ind(A)}(x,y)=\{x\rightarrow y\}$, in other words, there is an unique morphism of $x$ to $y$.
My question is: is that assignment correct?, because the only thing i am doing  is putting an arrow between each element of $A$
2)$Comp: Cat\rightarrow Set$
Which  $Comp(C)$ is the set of connected component of $C$.
What does that mean? Because i have been looking for the definition of connected component of one category and i have not had any luck.
Thank you for everything.

A: 1) Yes it is correct.
2) A pair of objects $A$ and $B$ in a category $\mathbb{C}$ are connected if there exists for some $n$ objects $X_1$, ... , $X_n$ in $\mathbb{C}$ such that $X_1=A$ and $X_n=$B and the set $\hom(X_i,X_{i+1})\cup \hom(X_{i+1},X_i)$ is non-empty for each $i\in \{1,..,n-1\}$.
A connected component $\mathbb{S}$ of a category $\mathbb{C}$ is a maximal subset of the objects of $\mathbb{S} \subseteq \mathbb{C}_0$ whose elements are pairwise connected (i.e. for each $A$ and $B$ in $\mathbb{S}$, $A$ and $B$ are connected in $\mathbb{C}$).

A: As pointed out by Nex 2) is correct, but note that the functor $Comp$ is more commonly denoted by $\pi_0$.
Moreover, 1) is correct too. Indeed, since the name $Ind$ stands for "indiscrete", hence is an hint that you are looking for a category with only one connected component.
In addition, you can note that there is also an (obvious) functor between $\mathbf{Set}$ and $\mathbf{Cat}$, usually called the free functor $\mathbf{F}$, that maps a set to a discrete category. This free functor is "the" right adjoint to the functor $\pi_0$ (aka $Comp$). For any set $A$, the category $\mathbf{F}(A)$ has as many connected components as there are objects in $A$.


text:
Q: Python - Label won't hide when using get_forget() I'm trying to learn how to show and hide widgets when certain fields are selected, I found some code on here however i'm having a little trouble getting it to work how i'd like so wondering if I am missing something.
I am trying to get it so when the 1st radio button is selected one label appears but when the other is selected the first label disappears but the second label appears, and the other way around.
Any help is greatly appreciated!
import os
import tkinter as tk
from tkinter import ttk
from tkinter import *

class NewSoftware:
    def __init__(self,master):
        self.master = master
        lab1 = ttk.Label(master, text = "Hello", font = ("Calibri" ,10))
        lab1.grid(column = 1, row = 2)

    def combo_input(self):
        print ("do something")

class UpdateSoftware:
    def __init__(self,master):
        self.master = master
        lab2 = ttk.Label(master, text = "Bye", font = ("Calibri" ,10))
        lab2.grid(column = 2, row = 2)

    def combo_input(self):
        print ("do something")

#Show / hide
def print_selection():
        if var.get() == 1:
            print ("add new software")
            NewSoftware(frame1)

            try:
                lab2.grid_forget()
            except:
                pass;

        if var.get() == 2:
            print ("update software")
            UpdateSoftware(frame1)
            try:
                lab1.grid_forget()
            except:
                pass;

#--- GUI ---
root = tk.Tk()
root.geometry('490x410')
root.title("Software")

var = tk.IntVar()

TAB_CONTROL = ttk.Notebook(root)

#--- TAB 1 ---
TAB1 = ttk.Frame(TAB_CONTROL)
TAB_CONTROL.add(TAB1, text = 'Add/Update Software')

frame1 = Frame(TAB1)
frame1.pack(fill='both')

lab1 = Label(frame1, text = "Add/Update Software", font = ("Calibri" ,10))
lab1.grid(column = 1, row = 0)

c1 = Radiobutton(frame1, text='Add New Software',variable=var, value=1, command = print_selection)
c1.grid(column =1, row = 1, sticky = 'W')

c2 = tk.Radiobutton(frame1, text='Update Software',variable=var, value=2, command = print_selection)
c2.grid(column =2, row = 1, sticky = 'W')

#--- TAB 2 ---
TAB2 = ttk.Frame(TAB_CONTROL)
TAB_CONTROL.add(TAB2, text = 'Past Version Checker')
TAB_CONTROL.pack(expand = 0, fill = "both")

frame2 = Frame(TAB2)
frame2.pack(fill='both')

lab1 = Label(frame2, text = "Past Version Checker", font = ("Calibri" ,11 ,"bold"))
lab1.grid(column = 1, row = 0)

root.mainloop()


text:
Q: How to use Vector and Comparable Interface I did
public class Employee implements Comparable <Object> {
    public int compareTo (Object other ){

i did the implementation well (it works fine) and calles it from other class:
import java.util.Vector;

public class Firm {

    private Vector <Employee> employees = new Vector<Employee>();

and using in the same class (Firm) Comperator Vector in function :
public void SortVector(Vector <Comparable> vector) {

and calls it with:
SortEmployeesBy(this.employees); ////Error is here

and in this line the compiler said:

The method SortVector(Vector) in the type Firm is not applicable for the arguments (Vector)"

Note: i required to use only vector and need to use SortVector several times so that i need to use the comparator because i have many vector and other classes like Employee, customer, Artist... tha each has own implementation for Comparable
why is that, and how to fix it?

A: Try any one
public void SortEmployeesBy(Vector<? extends Comparable<Object>> vector) {..}
public void SortEmployeesBy(Vector<Employee> vector) {...}

instead of using
public void SortEmployeesBy(Vector<Comparable> vector) {...}

--EDIT--
You can try with Firm class making it parametrized as shown below to make it more generic.
class Firm<T extends Comparable<Object>> {

    private Vector<T> employees = new Vector<T>();

    public void SortEmployeesBy(Vector<T> vector) {...}
}

Firm<Employee> f = new Firm<Employee>();


text:
Q: how to update the action of form in javascript Can Anybody tell what is missing. I am trying to update the action at run time using javascript ?
I tried a lot but nothing working .
something is gone wrong.

                <form method="get" name="edit_form" id="edit_form_id" action="MeritorEditShipToCmd" >
                <input type="hidden" value="<%=request.getParameter("memberid")%>" name="memberid" />
                <input type="hidden" value="editLocation" name="action" />
                <input type="hidden" value="<%=request.getParameter("shipid")%>" name="shipid" />
                <input type="hidden" value="<%=request.getParameter("addrId")%>" name="addrId" />
                <input type="hidden" value="<%=request.getParameter("userType")%>" name="userType" />

                            <input type="button" name="save" value="Add/Save Location" onclick="saveLocation()"/>

</form>

I dont know wht is going wrong?
 thaxs for the reply.but when I m using the above mentioned help

 <% String userType = request.getParameter("userType");
   System.out.println(userType);
   String action = null;
   if(userType.equals("EXP")){
   action = "MeritorEditExpIpTtmAddDelCmd";
   System.out.println(userType+"hello"+action);}
   else if(userType.equals("WD")){
   System.out.println(userType+"hello");
   action = "MeritorEditShipToCmd";
   System.out.println(userType+"hello"+action);}%>

        <form method="get" name="edit_form" id="edit_form_id" action=<%action    %      >>

m getting the action as string.but this action is not going to reach my cmdimpl file.
Need Help

A: Simple way to do this:
<form id="frm" action="#">
</form>

See a working demo: http://jsfiddle.net/PCKUx/1/
Make sure you are getting form after DOM is ready, so I put the script after the form.

A: It seems to me that the action is purely based on a server-side variable, so there's no need at all to be doing this client-side.
<%
var userType = request.getParameter("userType");
var action = String.Empty;
if(userType == "EXP")
   action = "MeritorEditExpIpTtmAddDelCmd";
else if(userType == "WD"
   action = "MeritorEditShipToCmd";
%>

<form method="get" name="edit_form" id="edit_form_id"
     action="<%= action %>" >


text:
Q: PHP: 404 header not working on HTTPS site - returns blank page instead of default not found page I have a wildcard certificate for, lets call it *.example.com and I've set up a virtual host for *.example.com in the Apache (for both HTTPS and non-HTTPS traffic).
Been messing around with some 404 response headers, but I seem to have a problem, so I made a simple test case:
In the virtaul host I rewrite all traffic to index.php:
RewriteRule .* /index.php [QSA]

And in index.php I return a 404 header:
header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
exit();

I don't do anything else but that, so no ErrorDocument set or similar.
Dump of headers returned by the server (user file_get_contents("https://test.example.com"); and print_r($http_response_header); from another PHP file:
Array
(
    [0] => HTTP/1.0 404 Not Found
    [1] => Date: Mon, 08 Oct 2012 12:41:28 GMT
    [2] => Server: Apache/2.2.16 (Debian)
    [3] => X-Powered-By: PHP/5.3.3-7+squeeze14
    [4] => Vary: Accept-Encoding
    [5] => Content-Length: 57
    [6] => Connection: close
    [7] => Content-Type: text/html
)

If I then enter the HTTP site on any subdomain/any path the browser will correctly show the default not found page, but if I use HTTPS the browser will instead show a blank page (except in IE which will correctly(?) show the not found page).
header("Status: 404 Not Found"); does not work either.
This can't be right can it? Is there something I'm missing here - some kind of limitations on 404 headers and wildcard certificates maybe?
Update by request of Hakre
Headers dumped from headers_list():
Array
(
    [0] => X-Powered-By: PHP/5.3.3-7+squeeze14
)

It seems that the server completely ignores adding my 404 header, regardless of using any of these ways of writing the header:
header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
header("HTTP/1.0 404 Not Found");
header("HTTP/1.1 404 Not Found");

Other headers such as header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); works properly.

A: This is wrong:
header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");

Even if you are using HTTPS, you should return:
header("HTTP/1.1 404 Not Found");


text:
Q: Using a random point in two actions Sorry I'm new to this.
Right now I'm trying to create an endless randomly moving sprite that rotates to its direction. However I can't figure out how to use the random location generated from randomPoint on the rotateAction. Basically the bug randomly rotates instead of using the point it's going to. Is there a way I can use the same random point twice?
-(void)moveRandom:(CCSprite*)roach
{

    CGPoint randomPoint = ccp(arc4random()%480, arc4random()%320);
    NSLog(@"%@", NSStringFromCGPoint(randomPoint));

    int minDuration = 2.0;
    int maxDuration = 4.0;
    int rangeDuration = maxDuration - minDuration;
    int randomDuration = (arc4random() % rangeDuration) + minDuration;

    float dY = roach.position.y - randomPoint.y;
    float dX = roach.position.x - randomPoint.x;
    float offset = dX<0 ? 90.0f : -90.0f;
    float angle = CC_RADIANS_TO_DEGREES(atan2f(dY, dX)) + offset;

    [roach runAction:
     [CCActionSequence actions:
      [CCActionRotateTo actionWithDuration:0.001 angle:angle],
      [CCActionMoveTo actionWithDuration:randomDuration position: randomPoint],
      [CCActionCallBlock actionWithBlock:^{
         [self performSelector:@selector(moveRandom:) withObject:roach afterDelay:0.5];
     }],
      nil]
     ];

A: Some things that stand out: It looks like you're trying to get the angle in the wrong direction. The conditional offset is not needed. radians to degrees should be negated .. I'm guessing you want:
float dY = randomPoint.y - roach.position.y;
float dX = randomPoint.x - roach.position.x;
float angle = -CC_RADIANS_TO_DEGREES(atan2f(dY, dX));


text:
Q: Modified soul command \hl will not accept \boldsymbol In Cool Text Highlighting in LaTeX, Gumbo offered, in a comment to Caramdir's answer, \hlc, a modification of soul's \hl to allow choosing the highlighting color on the fly. \hlc accepts $2$ as argument but will not accept \boldsymbol{$2$}, complaining that Argument of \boldsymbol has an extra }. When I register the command \boldsymbol with soul,  see the documentation of soul "Adding font commands" (page 15), nothing at all happens.
Here is a MWE:
\documentclass[11pt]{book}
\usepackage{xcolor}
\usepackage{bm}
\usepackage{soul}
\soulregister{\boldsymbol}{1}
\newcommand{\hlc}[2][yellow]{\sethlcolor{#1}\hl{#2}}
\begin{document}
A. \boldsymbol{$2$}

B. \hlc[yellow]{$2$}

C. \hlc[yellow]{\textbf{Two}}

%D. \hlc[yellow]{\boldsymbol{$2$}}

\end{document}

A: I have no issue if I use the correct syntax:
\documentclass[11pt]{book}
\usepackage{xcolor}
\usepackage{bm}
\usepackage{soul}

\newcommand{\hlc}[2][yellow]{\sethlcolor{#1}\hl{#2}}

\begin{document}
A. $\boldsymbol{2}$

B. \hlc[yellow]{$2$}

C. \hlc[yellow]{\textbf{Two}}

D. \hlc[red]{$\boldsymbol{2}$}

E. \hlc{$\boldsymbol{2}$}

\end{document}


text:
Q: Issue while comparing hashes of array in perl I am pretty new to Perl and need to accomplish a task quickly. Any help is appreciated!
I have two hash of arrays as follows:
Hash 1
-------
abc.txt: ['0744','0']
xyz.txt: ['0744','0']

Hash 2
-------
abc.txt: ['0766','0']
x.txt: ['0744','0']

I have to compare these 2 hashes print 3 things:
1. Files Added in Hash2
2. Files Missing in Hash2
3. Files(keys) which are present in both hashes but there attributes(values) are different.
print "-------------------------ADDED FILES--------------------------------";
foreach (keys %hash2){
    print "added $_\n" unless exists $hash1{$_};
}

print "-------------------------MISSING FILES--------------------------------";
foreach (keys %hash1){
    print "Missing $_\n" unless exists $hash2{$_};
}

print "-------------------------Different permissions--------------------------------";

foreach my $key2 ( keys %hash2 ) {
    unless ( exists $hash1{$key2} ) { next; };
    if (join(",", sort @{ $hash1{$_}})
      eq join(",", sort @{ $hash2{$_}}) ){
      }
      else{
          print "value is different";
      }
}

Issue is when keys are same.This for each loop doesn't work well.I want to print like this:

FileName: File Attributes Before  : File Attributes after
  abc.txt: '0744','0': 0766','0'

Please help

A: Your code didn't work, because you defined my $key2 in your foreach-loop, which leaves $_ as an empty value.
Also you don't need to join the hashes. Try the smartmatch operator on array values, its more efficient since you only need to do the join, when you want to have an output.
foreach my $key2 ( keys %hash2 ) {
    unless ( exists $hash1{$key2} ) { next; };
    unless ( $hash1{$key2} ~~ $hash2{ $key2 } )
    {
        print "$key2: ".join(",", @{ $hash1{$key2}}).": ".join(",", @{ $hash2{$key2}})."\n"
    }
}

A: Change
foreach my $key2 ( keys %hash2 ) {
    unless ( exists $hash1{$key2} ) { next; };
    if (join(",", sort @{ $hash1{$_}})
      eq join(",", sort @{ $hash2{$_}}) ){
      }
      else{
          print "value is different";
      }
}

to
foreach my $key2 ( keys %hash2 ) {
    next unless ( exists $hash1{$key2} );
    my $val1 = join(",", sort @{ $hash1{$key2} });
    my $val2 = join(",", sort @{ $hash2{$key2} });
    if ($val1 eq $val2) {
        # values are same
    }
    else {
        print "$key2 $val1 $val2\n";
    }
}

and try again.


text:
Q: Can JARs be uploaded successfully to AWS Elastic Beanstalk from the AWS web UI? I'm trying to build a basic Spring Boot Java web app and deploy it to AWS Elastic Beanstalk (EB). Most tutorials I've read suggest uploading a JAR when creating an application, however, I'm unable to successfully deploy a JAR using the AWS web UI. When I try, the state of the environment is set as 'Severe' and the environment web link returns a 502 Bad Gateway response.
In order to make sure it wasn't some issue with the code, I downloaded the Java sample app from AWS (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/samples/corretto.zip), fixed the jetty inconsistency in the pom.xml file (the plugin didn't match the dependency), set the JDK version to be the same as what I created the environment to be (Corretto 11), then ran the following command to create the JAR:
mvn package
When I upload the created JAR onto the EB environment, the deployment fails. If, however, I simply upload the downloaded zip file (with the corrected pom and correct JDK set), the deployment works.
The following AWS page talks about how to create a source bundle to upload and only mentions being able to upload ZIP and WAR files, not JARs:
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/applications-sourcebundle.html
My question is then, is it possible to upload JAR files to Elastic Beanstalk via the EB web UI, or do I need to stick with WAR and ZIP files? This will help me when navigating the various Spring Boot / Elastic Beanstalk tutorials out there. It's proving quite difficult to get any Spring Boot web app to actually work on Elastic Beanstalk. Any advice would be much appreciated.

A: It is very possible to upload a JAR to Elastic Beanstalk using the AWS Management Console. Furthermore, then once deployed, the app shows Green:

If you get RED, means you have not set something correctly.
See this basic Spring BOOT app example to follow this process.
Creating your first AWS Java web application


text:
Q: OnClick for navigation drawer header Image not working I created an android navigation drawer and I want a header Image to be clickable. I checked many resource but not able to make it work.
@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);

        View headerView = navigationView.getHeaderView(0);
        ImageView profileView = headerView.findViewById(R.id.imageView);
        profileView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Header is clicked", Toast.LENGTH_SHORT).show();
                Log.e("Header", "Header is clicked");
            }
        });
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
}

and nav_header_main.xml file contains the ImageView(imageView) inside the LinearView
Here I am not getting the toast or any Logs from inside the OnClickListener.
Thanks.
updated activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.drawerlayout.widget.DrawerLayout>


text:
Q: How should I make up for the lack of static initializers in PHP? I'm thinking about putting every class into a separate file and doing the static initialization outside of the class definition.
The problem with this is the fact that the initialization will happen before the said class is actually needed (it will happen when the file which contains the class is included for the first time). It's a problem, because it may happen that the class won't be used at all, hence the initialization is unnecessary. And I think the practice of including the used files not in the beginning of your code is simply a dirty technique.
If anybody has a viable solution to this problem, I would greatly appreciate it.

A: Take a look at code like this. It uses a singleton instance of the database yet you can still create instances of the class:
class DB
{
    private static $_db;

    public static function pdo()
    {
        if (is_null(self::$_db))
        {
            self::$_db=new PDO('pgsql:host=localhost;
                                port=5432;
                                dbname=testdb;
                                user=postgres;
                                password=abc123');
            self::$_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }

        return self::$_db;
    }

public static function factory()
{
    return new self;
}

private function __construct() {}

When you want an instance of the DB, you do DB::factory(). DB uses self::pdo() to return the singleton to access the database.

A: The singleton answer has a problem here... if you use the static methods before an instance of the class is created... then the static initializer has not run... so you might say that one can run the initializer in every static method... that is true but what about just getting and setting static variables... I suppose one could also use __get and __set magic functions for this... there is just a problem with the language in that it does not support static intialization... here is the way it can be done...
in file Hi.php:
class Hi{
public static $v = "0";
}

Hi::$v= "2";
// end of Hi.php file

simple use a .php file per class... and do the static initialization outside of the
class definition...

A: You might look up for __autoload when a class is not found it is called and supposed to include the file contains that class. You can put static initializers in that function.

A: Use singleton pattern instead of static calls:
<?php
class Foo {

   protected static $_instance;

   /**
   * @return Foo
   */
   public static function getInstance() {
        return (null === self::$_instance)?
            self::$_instance :
            self::$_instance = new Foo();
   }

   protected function __construct() {
        // initialize here
   }
}

A: This is the way I do this. The only cost is testing the $doneinit static member each time you construct.
class Foo {
   private static $doneinit=false;

   private static init() {
      // do static initialisation here

      self::$doneinit=true;
   }

   public function __construct() {
      if (!self::$doneinit) self::init();

      // go on to do the rest of construction
   }
}

Simple, and it keeps everything within the class.


text:
Q: Python Elasticsearch Not Accepting Body of Data I'm basically trying to index data from a dataframe coming from a csv file.
I created an indices successfully.
es.indices.create(index='hash_test', ignore=400)

And added a baseline indexes with the columns and sample data contained in my dataframe
       es.index(index="hash_test", doc_type="hash-test", id=rand_id, body={
         'FILENAME': '6.js',
         'HASH': 'b4d44ed618112e41cb7e8f33bb19a414',
         'DATE': '2018-11-15'})

Which ran fine.
Below is how I want to parse my dataframe into the proper format and iterate through the rows and index the data into Elasticsearch similar to the above.
def index_data(data_path, chunksize, index_name, doc_type):
    f = open(data_path)
    csvfile = pd.read_csv(f, iterator=True, chunksize=chunksize,sep="£",encoding="utf-8-sig",index_col=0,engine="python")
    dictionary = {'Â':''}
    es = Elasticsearch('http://*.*.*.*:9200/')

    for i,df in enumerate(csvfile):
        rand_id = uuid.uuid4();
        df.replace(dictionary, regex=True, inplace=True)
        df.columns = df.columns.str.replace('Â', '')
        records=df.where(pd.notnull(df),None).T.to_dict()
        list_records=[records[it] for it in records]
        json_data = str(''.join(str(v) for v in list_records))
        try:
            es.index(index_name, doc_type, rand_id, json_data)
        except:
            print("error!")
            pass

I had to do some parsing of the dataframe as a weird character was in every row and column (Â).
When I print the values I want to index
print(index_name, doc_type, rand_id, json_data)

I get exactly what I want
hash_test hash-test 51eacee2-e2b1-4886-82f5-1373ec59c640 {'FILENAME': '6.js', 'HASH': 'b4d44ed618112e41cb7e8f33bb19a414', 'DATE': '2018-11-15'}

However I get the following error when I run it;
RequestError: RequestError(400, 'mapper_parsing_exception', 'failed to parse')

Which is attempting to PUT the following data:
{"_index":"hash_test","_type":"hash-test","_id":"{'FILENAME': '8.js', 'HASH': 'b4d44ed618112e41cb7e8f33bb19a414', 'DATE': '2018-11-15'}","found":false}

It completely ignores the rand_id parameter completely, and when I do the following:
es.index(index_name, doc_type, json_data, rand_id)

It ignores the json_data paramter.....
{"_index":"hash_test","_type":"hash-test","_id":"93eadd1b-6859-474b-9750-b618b800b4d5","found":false}

I don't understand the differences in the output I'm getting, and I'm stumped as to how the body is ending up in the _id field when I specified the id parameter.
Cheers in advance for any help.

A: So, not surprisingly,  i was over complicating what I needed to do by creating a clean JSON string from my dataframe. Instead of using a dictionary and then using a list (which I imagine is the source of my errors), I learned it's much easier to just use the to_json function in pandas.
The below code clears this up and indexes my dataframe into my Elasticsearch instance.
def index_data(data_path, chunksize, index_name, doc_type):
    f = open(data_path)
    csvfile = pd.read_csv(f, iterator=True, chunksize=chunksize,sep="£",encoding="utf-8-sig",index_col=0,engine="python")
    es = Elasticsearch('http://*.*.*.*:9200/')

    for i,df in enumerate(csvfile):
        rand_id = uuid.uuid4(); #create a random id
        data=df.to_json(orient='records', lines=True)
        try:
            es.index(index=index_name,doc_type=doc_type,id=rand_id,body=data)
        except TransportError as e:
            print(e.info)


text:
Q: XMPP based live-chat system in Django I need to implement an XMPP based live-chat system in Django. After a lot of scourging and ideas from a colleague, we came up with this.

Method using a bot:

*

*When a visitor visits the site. The visitor's XMPP client which in this case is Strophe.JS begins an XMPP-over-BOSH connection to the XMPP server and connects to a room called <visitor_id>@conference.demo.com. Currently there is no one else in the room.

*The visitor makes an analytics request with a custom visitor id to Django

*The Django view, stores the visitor id in a table called ActiveUsers. This table contains a new field as well called status. It sets the status to INACTIVE.

*This model dispatches a signal on the save method.

*This signal gets picked up by a bot which connects to the XMPP server and joins the room <visitor_id>@conference.demo.com. Now we have the user and the bot in the room.

*The site support people are logged into their web interface.

*They have JS code that keeps long-polling the Django site to check the ActiveUsers. It fetches the rows from the table and displays it. (I've thought of using django-pubsub for this)

*When the visitor types a message, it goes via XMPP-over-BOSH to the XMPP server, the jabber bot in the room see this message and updates the status of the record in the ActiveUsers table to ACTIVE.

*As said: The site support people have JS which keeps polling this table. It begins blinking the ow to show that the user is now chatting.

*The support personnel can now double-click that row which on doing so begins an XMPP-over-BOSH connection to the visitor's room. It knows that the room is <visitor_id>@conference.demo.com.

*The bot seeing that the support person has joined the room, updates ActiveUsers record to show CHATTING. This ensures that no more than support personnel can be in the room i.e. room occupied.

*The bot logs the messages to a Django table

*When the both sees that both users have left the room, it deletes the record.

ejabberd or openfire will be XMPP server.
Apache is the web server which runs mod_wsgi for serving Django and mod_proxy for proxying the XMPP-over-BOSh requests to the XMPP server.
Does this sound like a good of doing this? Any suggestions? I'm worried about the load on the Django system.
(It's long. Sorry 'bout that.)

Method using Presence Stanzas:
On the client side, i'm using Strophe JS library which supports presence and I had add callback methods. I'm flexible with using ejabberd or openfire as my XMPP server. The are many visitors on the XMPP server — some from site A and some from site B but they are all connected to the same XMPP server. When the visitor visits the site, they are connected to the XMPP server as <visitor_id>_<site_id>@demo.com and each one gets logged into a room called <visitor_id>@conference.demo.com. The sales/support personnel are also connected to the XMPP sever as <supportsale_id>_<site_id>@demo.com. They are not connected to any chat room though. They don't have any of the visitors on their roster.
A good way of showing that a user has connected to the site would be to pass a presence stanza to the sales/support people. Only visitors and sale/support personnel from the same site communicate with each other and that's why I have the <site_id> in the username to show which site that person belongs to.
It seems that you can't subscribe to presence stanzas for a user if you don't have him on your roster. (Quite logical). Is is possible to automatically add every new user of a site connecting to the system to the roster of the sales/support people of that site? Wouldn't this then automatically signal a presence to the sales/support people? How can I implement this — any help?

A: I wrote exactly this. It's called Seshat and uses a "broker" bot between the website and a Jabber server (I use ejabberd). It's in beta right now mainly because it hasn't been extensively tested outside my company.
Note: while the README specifically mentions the Pyramid web framework, the core system would work just as well with a Django, TurboGears, or command line system. It's just that I only package example code showing how to integrate it with Pyramid.
Seshat is being actively developed. If you have any feature requests, let me know. :-)

A: I think that it's better to use presence stanzas to "signal" any (in)activity. What you need to store in database is only the persistent data you need for further analysis. Otherwise, I think you'll have great time coding the application :).
EDIT:
function onConnect(status) {
  if (status == Strophe.Status.CONNECTED) {
    var joined = false;
    var participants = {};
    $('#events').html('<text class="textmainleft">XMPP connection established. Ready to rock n roll!</text>');
    connection.send($pres().c('priority').t('-1'));
    connection.addHandler(notifyUser, null, 'message', 'groupchat', null, null);
    connection.send($pres({to: 'groupchatroom@conference.demo.com/' + nickname}).c('x', {xmlns: 'http://jabber.org/protocol/muc'}));
  } else if (status == Strophe.Status.AUTHFAIL) {
    $(location).attr('href', AUTHFAIL_URL);
  } else if (status == Strophe.Status.CONNFAIL) {
    $(location).attr('href', AUTHFAIL_URL);
  }
}

$(document).ready(function () {
  connection = new Strophe.Connection(BOSH_SERVICE);
  connection.connect(jid, password, onConnect);
});

notifyUser is another function (just link onConnect) that would handle the received message stanzas.

A: I'm not sure you need to use MUCs to implement this.  Your bot could maintain its own pubsub node which it is subscribed to.  When a new user begins to type it could send a notification to the pubsub node, which the bot would then see.  From there, the bot could notify a support person via XMPP, thus eliminating the need to long poll the database table.  Then the support person could start a standard one to one chat session with the end user.  In addition, their presence could be set to 'na' in order to show that they are in a session with a user.


text:
Q: Update postgres json value by other attribute I'm using PostgreSQL 9.6 and
I got the following table:
Cars
ID          Name        Data
 1           abc        {"color":"red","wheels":4,"my-value":false}
 2           def        {"color":"blue","wheels":8}
 3           xyz        {"color":"yellow","my-value":true}

I want to extend the Data JSON object by adding another boolean attribute called "new-attr" which should get the exact value of "my-value" of the JSON field.
for example, if "my-value" in ID 1 is false, then "new-attr" will be false.
And if not set, do not add it at all (as in number 2).
I tried the following but it didn't help:
UPDATE cars SET data=jsonb_set(data,'{new-attr}',data->'my-value')

I expect to get the following JSON :
 ID          Name        Data
1           abc        {"color":"red","wheels":4,"my-value":false,"new-attr":false} // same value
2           def        {"color":"blue","wheels":8} // no change
3           xyz        {"color":"yellow","my-value":true,"new-attr":true} // same value true

Any suggestions ?

A: The concatenation operator || will do that:
update the_table
  set data = data || jsonb_build_object('new-attr', data -> 'my-value')
where data ? 'my-value'; --<< only update rows that contain the key

The ? operator tests if the key is present in the JSON value.

If your column is defined as json (rather than jsonb which it should be), you probably need to cast it, to make the || operator work properly: data::jsonb || ...

A: You could keep your current UPDATE statement, but add WHERE data ? 'my-value' to it to avoid updating rows which have nothing you want to update.
When v13 is released, you could use the new jsonb_set_lax function:
UPDATE cars SET data=jsonb_set_lax(
    data,
    '{new-attr}',
    data->'my-value',
    true,
    'return_target');

But it seems like more work for you and more work for the server and harder to read than just adding a WHERE clause.


text:
Q: DataCompare on table without UniqueKey I was looking to use VS2010's data comparison tool but found out that it will not perform the comparison on a table without a unique key.  Is there a workaround for this while still using VS2010's data compare tool or another solution?
The end result I'm hoping to get is the delta of two tables that have the same schema but are in different databases.  Thanks.

A: One of the best tools you can spend your money on: http://www.red-gate.com/products/sql-development/sql-data-compare/


text:
Q: Optimal way to display data with different ranges I have an application which I pull data from an FPGA & display it for the engineers. Good application ... until you start displaying data which are extremely different in ranges...
say:  a signal perturbating around +4000 and another around zero (both with small peak-peak).
At the moment the only real workaround is to "export to csv" and then view in Excel but I would like to improve the application so that this isn't needed
Option 1 is a more dynamic pointer that will give you readings of ALL visible plots for the present x
Option 2. Multiple Y axis. This is where it gets a bit ... tight with respect to UI area.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import numpy as np

t = np.arange(0,1,0.00001)
data = [5000*np.sin(t*2*np.pi*10),
10*np.sin(t*2*np.pi*20),
20*np.sin(t*2*np.pi*30),
np.sin(t*2*np.pi*40)+5000,
np.sin(t*2*np.pi*50)-5000,
np.sin(t*2*np.pi*60),
np.sin(t*2*np.pi*70),
]

fig = plt.figure()
host = host_subplot(111, axes_class=AA.Axes)

axis_list = [None]*7
for i in range(len(axis_list)):
    axis_list[i] = host.twinx()
    new_axis = axis_list[i].get_grid_helper().new_fixed_axis
    axis_list[i].axis['right'] = new_axis(loc='right',
                                                axes=axis_list[i],
                                                offset=(60*i,0))
    axis_list[i].axis['right'].toggle(all=True)
    axis_list[i].plot(t,data[i])

plt.show()

for i in data:
    plt.plot(t,i)
plt.show()

This code snippet doesn't contain any figure resize to ensure all 7 y-axis are visible BUT ignoring that, you can see it is quite large...
Any advice with respect to multi-Y or a better solution to displaying no more than 7 datasets?


text:
Q: Cannot read property value of null I have been learning javascript for 6 months, but I really don't know whats wrong with this .... code?
<script>
var search_file_val = document.getElementById('search_textbox').value;
var XHR = new XMLHttpRequest();
var params = "search_val="+search_file_val;
function search_file()
{
    XHR.open('POST','http://www.bt-mail.sk/somescript.php',true);
    XHR.send(params);
}
</script>

Google chrome is telling me this .
 Uncaught TypeError: Cannot read property 'value' of null
I'm sure the Id of element is right.
edit:
the html
<input type="text" class="cool_input_box" id="search_textbox" onkeyup="search_file()">

edit: no2
removed

A: Try:
<script>
document.addEventListener("DOMContentLoaded", function() {
  var search_file_val = document.getElementById('search_textbox').value;
  var XHR = new XMLHttpRequest();
  var params = "search_val="+search_file_val;
  function search_file()
  {
      XHR.open('POST','http://www.bt-mail.sk/somescript.php',true);
      XHR.send(params);
  }
});
</script>

Although, you should really not be getting the value unless you have requested to search for the file like:
<script>
  function search_file()
  {
    var search_file_val = document.getElementById('search_textbox').value;
    var XHR = new XMLHttpRequest();
    var params = "search_val="+search_file_val;
    XHR.open('POST','http://www.bt-mail.sk/somescript.php',true);
    XHR.send(params);
  }
</script>


text:
Q: how to get value by name from dictionary in python I have a csv file with column of company names and i need to find domain names of it and store it in the same csv file beside the company names
code i have used so far
import pandas as pd
import clearbit
import json
clearbit.key = 'your secret key'
df = pd.read_csv("/home/vipul/Desktop/new.csv", sep=',', encoding="utf-8")

saved_column = df['Company']
i=0
for data in saved_column:

    n = saved_column[i]
    i = i+1
    domain = clearbit.NameToDomain.find(name=n)
    print(domain)
    l = json.loads(domain)
    print(l['domain'])

This code here gives domain names logo and name in json but how to take only domain
But this gives error
l = json.loads(domain)
 print(l['domain'])
error:
TypeError: the JSON object must be str, not 'NameToDomain'

The csv file looks like this

Company
Accenture
AND Digital
Accenture
Kite Consulting Group
Capgemini

expected output

Company                 Domain
Accenture              accenture.com
AND Digital            and.digital
Accenture              accenture.com
Kite Consulting Group  None
Capgemini              capgemini.com

The json looks like
Name: Company, dtype: object
{'name': 'Accenture', 'logo': 'https://logo.clearbit.com/accenture.com', 'domain': 'accenture.com'}
{'name': 'AND Digital', 'logo': 'https://logo.clearbit.com/and.digital', 'domain': 'and.digital'}
{'name': 'Accenture', 'logo': 'https://logo.clearbit.com/accenture.com', 'domain': 'accenture.com'}
None
{'name': 'Capgemini', 'logo': 'https://logo.clearbit.com/capgemini.com', 'domain': 'capgemini.com'}

A: According to the documentation, clearbit.NameToDomain.find(name=n) returns a dictionary, so you can access the values of it just like with any other python dictionary.  You don't care that it came from json, that's handled for you.  (also this question has nothing to do with csv).
Two other points:

*

*Publishing your authentication key to clearbit is probably a bad idea

*Publishing names and job titles of people in your csv file is probably a bad idea too, unless you've made all this data up.

A: Based on the question, there are two things:

*

*Extracting domain from the data returned by clearbit

*Working with Pandas

*

*Clearbit API returns a dictionary. You may simply do:

like this:
data = clearbit.NameToDomain.find(name=n)
print(data) # Dictionary
print(data['domain']) # Domain value

*For working with Pandas, you don't loop on the data

Use apply
import pandas as pd
from urllib.parse import urlparse

def parse_url(x):
    return 'unknown' if pd.isnull(x) else urlparse(x)[1]

df = pd.read_csv("./new.csv")
df['domain'] = df['Profile URL'].apply(parse_url)
df_new = df.loc[:, ['Company', 'domain']]

Edit:
Parser for clearbit could be implemented like (I have not tried this code, but it should work):
import clearbit
def parse_url(x):
    return 'unknown' if pd.isnull(x)

    data = clearbit.NameToDomain.find(name=x)
    return data.get('domain', 'Default value')

This code imports data from the CSV provided. You may instead call the clearbit API in the parse_url method and return appropriate value.
This solution works on Python3. Please take it as a starting point and not as a copy-paste solution.

A: As it is a dictionary we can assign some default value to it and store in the csv file and later removing it does the job :)
The edited code
import pandas as pd
import clearbit
import json
clearbit.key = 'your key'
df = pd.read_csv("/home/vipul/Desktop/new.csv", sep=',', encoding="utf-8")
saved_column = df['Company'].dropna()
i=0
res = []
for data in saved_column:
    n = saved_column.get(i)
    print(n)
    i = i+1
    data = clearbit.NameToDomain.find(name=n)
    if data != None:
        res.append(data['domain'])
    else:
        res.append('domain.com')
print(res)
df['Domain'] = res
df.to_csv("/home/vipul/Desktop/new.csv",index = False, skipinitialspace=False)

print("File saved to desktop as new.csv")


text:
Q: Is it possible to improve code performance by using reserve() before moving a vector with a bigger size into a vector with a smaller capacity? sorry in advance if this question is quite incomplete, unclear or a duplicate (it's my first one here). While studying move semantics and working on a small project for my OOP course I stumbled upon a question that I can't answer myself. As far as I know std::move() works by converting l-values into r values, but let's suppose we were moving a vector with a lot of elements into a second vector that has a capacity of 1. Could I use reserve() to avoid
 a lot of automatic memory re-allocations of the second vector or would using reserve() have no effect due to std::move() moving r-values into the second vector? A simple realization of my question can be found below.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
    std::vector<int> first (1000000);
    std::vector<int> second (1);
    std::fill(first.begin(),first.end(),7);
    second.reserve(1000000);//is this needed??
    second=std::move(first);
    return 0;
}

A: No, that is not needed, and is almost certainly premature optimization.
A vector really can be represented by 3 pointers (or two pointers and an offset, or one pointer and two offsets... but those aren't so common, so for the rest of my explanation I'll imagine vectors are represented by three pointers).

*

*One pointer points to the start of the memory it manages.

*One pointer points to one-past-the-end of the items that have been inserted in it.

*One pointer points to one-past-the-end of the memory it manages.

A move constructor std::vector<int> a = std::move(b); could be implemented by just taking those three pointers from b, setting them to some easy-to-make value (nullptr as a sentinel value meaning "I'm empty", for example) and then everything would be done.
In fact, this is how gcc does it (and most standard library implementations... but I had the gcc source handy). See here.
So your reserve call is at best optimized by the compiler into a no-op, and at worst, is causing an unnecessary memory allocation. No good!

A: Please take a look at this post: STL vector: Moving all elements of a vector
std::move() is an O(1) solution. When you use ith on vectors, the moved vector is now empty, and the new one has all elements of moved one.
The reserve() methods will do not anything in this case (but in other cases it's very useful).
You can use std::swap() method, which is also a method that doesn't need using the reserve() method.


text:
Q: TypeError: interaction.options.getString is not a function discord.js v14 error I'm making a discord bot and am using discord v14.3.0.
I call const faction = interaction.options.getString(`${date}-faction`)
with let date = Date.now() above it. I am calling this in a module with async execute(interaction) {} and call that module in bot.js like this:
// if interaction is from bot
if (!interaction.isCommand()) return;

const slashCom = client.slashCommands.get(interaction.commandName);

if (!slashCom) return;

try {
    await slashCom.execute(client, interaction);
 } catch(e) {
    console.error(e);
    await interaction.reply({ content: 'There was an error while executing this
 command!', ephemeral: true });
 }

inside a client on interaction create.
The application command data is this:
    data: new SlashCommandBuilder()
    .setName('faction')
    .setDescription('Choose a faction to join.')
    .addStringOption(option =>
        option.setName(`${date}-faction`)
            .setDescription('The faction you want to join. (BurningShadows, WaterLight, or JadeDawn.)')
            .setRequired(true)
            .addChoices({
                name: "BurningShadows", value: "BurningShadows" },
                { name: "WaterLight", value: "WaterLight" },
                { name: "JadeDawn", value: "JadeDawn" })
    ),

I have tried the other article on this but I did not find anything that solved my problem. What console.log(interaction.options) prints out is this:
{
intents: 46687,
 closeTimeout: 5000,
 waitGuildTimeout: 15000,
 shardCount: 1,
 makeCache: [Function (anonymous)],
 partials: [],
  failIfNotExists: true,
  presence: { status: 'online', user: { id: null } },
  sweepers: { threads: { interval: 3600, lifetime: 14400 } },
 ws: {
 large_threshold: 50,
  compress: false,
  properties: { os: 'darwin', browser: 'discord.js', device: 'discord.js' },
  version: 10,
  presence: { activities: [], afk: false, since: null, status: 'online' }
 },
 rest: {
 agent: [Getter],
 api: 'https://discord.com/api',
 authPrefix: 'Bot',
 cdn: 'https://cdn.discordapp.com',
 headers: {},
 invalidRequestWarningInterval: 0,
 globalRequestsPerSecond: 50,
 offset: 50,
 rejectOnRateLimit: null,
 retries: 3,
 timeout: 15000,
 userAgentAppendix: 'Node.js v16.17.0',
 version: '10',
 hashSweepInterval: 14400000,
 hashLifetime: 86400000,
 handlerSweepInterval: 3600000
 },
 jsonTransformer: [Function: toSnakeCase],
 shards: [ 0 ]
  }

Any help is greatly appreciated!

A: The option name is set to the current date when it is created, then you try to get it using Date.now() which will have a different value by that time.
Original
I had this issue before but fixed it by changing getString() to just get().


text:
Q: Xampp not starting on mac by simple pressing start I have installed xaamp on mac min..if i start it from clicking start in manage-os x its not starting apache or mysql server..
but if writing this code in terminal
sudo /Applications/XAMPP/xamppfiles/bin/apachectl start
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start

I tried by changing ports of config file but didn't work.