text:
Q: Сохранение и загрузка в двусвязном списке Пытаюсь сделать сохранение в файл и выгрузку из файла двусвязного списка. Оно сохраняет данные, но если открыть файл, то там только китайские иероглифы, а если выгрузить в ОП, а потом попробовать напечатать данные из ОП, то программы падает. Подскажите, в чем может быть проблема.
    #include <stdlib.h>
    #include <stdio.h>
    #include <locale.h>
    #include <string.h>
    #include <windows.h>
    #include <conio.h>
    #include <malloc.h>
    #include <time.h>
    #define MAX 20

    FILE *baza;

    typedef struct inform
    {
            char *name;
            char *group;
            char *form;
            char *doza;
            char *day1;
            char *month1;
            char *year1;
            char *day2;
            char *month2;
            char *year2;
            char *price;

    } INF;

    typedef struct list_elem
    {
            INF inf;
            struct list_elem *next, *prev;
    } APTEKA;

    APTEKA *head, *tail;

    void InputData(INF* pinf);
    void InsertEl(INF data);
    void AddEl(APTEKA* pnew, APTEKA* pold);
    void PrintList(void);
    void Save(void);
    void Load(INF* pinf);

    int main()
    {
        SetConsoleCP (1251);
        SetConsoleOutputCP (1251);
        setlocale(LC_ALL, "Rus");

        INF input;
        char n[MAX];

        while(1)
        {
            printf("|---------------------------------------------------------------------------------------------|\n");
            puts("\nСписок доступных команд"
            "\n 0  || Выход из программы"
            "\n 1  || Добавить элемент;"
            "\n 10 || Сохранить данные;"
            "\n 11 || Загрузить данные;");
            printf("|---------------------------------------------------------------------------------------------|\n");

            printf("Введите номер команды: ");
            scanf("%s",n);

            switch(atoi(n))
            {
                //Добавление
                case 1:

                    InputData(&input);
                    InsertEl(input);
                    break;

                //Вывод всех данных
                case 4:
                    PrintList();
                    break;

                case 10:
                    Save();
                    break;
                case 11:
                    Load(&input);
                    break;
                //Выход из программы
                case 0:
                    exit(1);
                default:
                    break;
            }
        }

     return 0;
    }

    void InputData(INF* pinf)
    {

        char buf[MAX];
        float buf1;

        printf("Введите название:");
        fflush(stdin); gets(buf);
        pinf->name=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->name, buf);

        printf("Введите группу:");
        fflush(stdin); gets(buf);
        pinf->group=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->group, buf);

        printf("Введите форму:");
        fflush(stdin); gets(buf);
        pinf->form=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->form, buf);

        printf("Введите дозу:");
        fflush(stdin); gets(buf);
        pinf->doza=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->doza, buf);

        buf1=atoi(pinf->doza);

               printf("Введите день выпуска:");
        fflush(stdin); gets(buf);
        pinf->day1=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->day1, buf);

        printf("Введите месяц выпуска:");
        fflush(stdin); gets(buf);
        pinf->month1=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->month1, buf);

        printf("Введите год выпуска:");
        fflush(stdin); gets(buf);
        pinf->year1=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->year1, buf);

        printf("Введите день конца срока годности:");
        fflush(stdin); gets(buf);
        pinf->day2=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->day2, buf);

        printf("Введите месяц срока годности:");
        fflush(stdin); gets(buf);
        pinf->month2=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->month2, buf);

        printf("Введите год срока годности:");
        fflush(stdin); gets(buf);
        pinf->year2=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->year2, buf);

        printf("Введите цену:");
        fflush(stdin); gets(buf);
        pinf->price=(char*)malloc(strlen(buf)+1);
        strcpy(pinf->price, buf);

        system("cls");
        puts("\nПрепарат успешно добавлен.");

    }
    void InsertEl(INF data)
    {
        APTEKA *pel, *pins;

        pel = (APTEKA*)malloc(sizeof(APTEKA));
        pel->inf=data;

        if(head == NULL)
        {
            pel->next = pel->prev=NULL;
            head = tail = pel;
            return;
        }
        pins = head;

        while(pins!=NULL)
            pins=pins->next;
        AddEl(pel, pins);
    }
    void AddEl(APTEKA* pnew, APTEKA* pold)
    {
          if(pold == head)
        {
            head->prev=pnew;
            pnew->next=head;
            pnew->prev=NULL;
            head=pnew;
            return;
        }

        if(pold!=NULL)
        {
            pnew->next=pold;
            pnew->prev=pold->prev;
            pold->prev->next=pnew;
            pold->prev=pnew;
        }else{
            tail->next=pnew;
            pnew->prev=tail;
            pnew->next=NULL;
            tail=pnew;
        }

    }
    void PrintList(void)
    {

       APTEKA* pel = head;

       /* Вывод таблицы */
        /* вывод заголовков */
        printf("|---------------------------------------------------------------------------------------------|\n");
        printf("|Препараты Аптеки                                                                             |\n");
        printf("|---------------------------------------------------------------------------------------------|\n");
        printf("| Название    |     Группа    |   Форма   |  Доза  |  Дата выпуска  |  Срок годности |  Цена  |\n");
        printf("|-------------|---------------|-----------|--------|----------------|----------------|--------|\n");
        while (pel!=NULL)
       {

        /* вывод строк фактических данных */
        printf("|%13s|%15s|%11s|%8s|    %2s.%2s.%4s  |   %2s.%2s.%4s   |%8s|\n", pel->inf.name, pel->inf.group, pel->inf.form, pel->inf.doza, pel->inf.day1, pel->inf.month1, pel->inf.year1,pel->inf.day2, pel->inf.month2, pel->inf.year2, pel->inf.price);
        printf("|-------------|---------------|-----------|--------|----------------|----------------|--------|\n");

           pel=pel->next;
       }
       printf("|                                                                                |\n");
       printf("|---------------------------------------------------------------------------------------------|\n");
    }
void Save()
{
    APTEKA* pel=head;

    if( (baza = fopen("D:\\baza.txt", "a")) == NULL)
    {
        puts("\nОшибка сохранения");
        exit(1);
    }

    while(pel!=NULL)
    {
        fwrite(&pel->inf, sizeof (pel->inf), 1, baza);
        pel=pel->next;
    }
    fclose(baza);

}

    void Load(INF* pinf)
    {

        INF input;

        if( (baza = fopen("D:\\baza.txt", "r")) == NULL)
        {
            puts("\nОшибка чтения");
            exit(1);
        }

        while(fread(&pinf, sizeof (pinf), 1, baza) == 1)
        {
            fread(&pinf, sizeof (pinf), 1, baza);
            InsertEl(input);
        }
        fclose(baza);
    }

Заранее спасибо.

A: Опять...
Вы записываете и читаете вот таким способом -
fread(&pinf, sizeof (pinf), 1, baza)

адреса в полях структуры INF, а не строки.
Примерно так - жена говорит собраться в отпуск и в машину в багажник сложить, ну, там, матрас надувной, палатку, мангал и шампуры - ну, в общем, барахло. Вы в багажник кладете бумажки с надписями "Матрас - на антресолях", "Палатка - на балконе" и т.д. Так вот сохраняете в файл...
По приезду на место читает - вынимаете из бумажника бумажки с надписями, где что лежит. Но хуже того, что шкаф теперь совсем другой, балкон тоже, так что втык от жены - это примерно и есть результат вот такого хранения и попытку раскрыть палатку, которой нет...
Update
Примерный набросок, как бы писал-читал я. Набросок - надо дописать проверки и т.п.
void writeStr(const char * s, FILE * f)
{
    int l = strlen(s);
    fwrite(&l,sizeof(int),1,f);
    fwrite(s,l,1,f);
}

char* readStr(FILE * f)
{
    int l;
    fread(&l,sizeof(int),1,f);
    char * s = malloc(l+1);
    fread(s,l,1,f);
    s[l] = 0;
    return s;
}

Потом запись в файл структуры выглядит как
void writeInf(INF*i,FILE*f)
{
    writeStr(i->name,f);
    writeStr(i->group,f);
    ...
}

Ну, и чтение:
INF* readInf(FILE*f)
{
    INF * i = malloc(sizeof(INF));
    i->name  = readStr(f);
    i->group = readStr(f);
    ...
    return i;
}

Примерно так...


text:
Q: send an email based on smtp.gmail.com from magento I don't have any mail servers.
So how to configure the mail settings(settings->configuration->advanced->system->Mail sending settings) in magento admin panel using smtp.gmail.com
and how to send an email based on that settings ?

A: There is no way to configure magento to use something else for sending mails than the builtin mail(), but ASchroder implemented something for this:
Magento SMTP Pro Extension

redpajama_set_name: RedPajamaStackExchange


text:
Q: React websockets disappear on refresh So I have a websocket connection that is open and I notice once I refresh the page the websocket messages disappears. I've read online that this is supposed to happen. What is a good way to persist these messages so that they do not disappear. Right now I have the websocket messages in a react state. I've seen some say localstorage or cookies, but I don't think that is scalable as their can be thousands of messages in minutes that could overload the browser storage? Below I am using react-use-websocket package and I get the last message and store that inside a state array. That is the wrong approach I need a longer storage solution.
const { lastJsonMessage, lastMessage, sendMessage, readyState, getWebSocket } = useWebSocket(resultUrl, {
    //Will attempt to reconnect on all close events, such as server shutting down
    shouldReconnect: () => true,
    reconnectAttempts: 10,
    reconnectInterval: 3000
  });

  useEffect(() => {
    const val = lastJsonMessage ? JSON.parse(lastJsonMessage as unknown as string) : {};
    if (val !== null && Object.keys(val).length > 0) {
      setMessageHistory((prev) => prev.concat(val));
    }
  }, [lastJsonMessage, setMessageHistory]);

  // Get Video assets after finishing;
  useEffect(() => {
    messageHistory.forEach((msg) => {
      const { type } = msg;
      if (type === 'video.live_stream.recording' || type === 'video.live_stream.active') {
        const localPlaybackId = msg.data?.playback_ids[0];
        setPlaybackId(localPlaybackId);
      }
      setVideoType(type);
    });
  }, [messageHistory, videoType]);

  const connectionStatus = {
    [ReadyState.CONNECTING]: 'Connecting',
    [ReadyState.OPEN]: 'Open',
    [ReadyState.CLOSING]: 'Closing',
    [ReadyState.CLOSED]: 'Closed',
    [ReadyState.UNINSTANTIATED]: 'Uninstantiated'
  }[readyState];

  if (liveStreamId) {
    sendMessage(liveStreamId);
  }

  messageHistory.filter((msg) => {
    msg.data.id === liveStreamId;
  });

A: in this case, usually when the app is loaded you should do a GET request to the server in order to load all the last messages. Also since you are talking about "thousands of messages" you should implement a lazy loading aka paginator or infinite-scroll


text:
Q: Peak power pulse in parallel MOSFETs I have a circuit like the one shown below. To make the schematic easier to read, I only show 2 FETs in parallel. I actually have 8 identical FETs in parallel. The HT0440 is a high-side N-channel FET driver. It's controlled by a digital signal from an MCU.

simulate this circuit – Schematic created using CircuitLab
Power is not switched on and off rapidly in this application, but I am still concerned about the instantaneous heating in the FETs when power is turned off. Particularly when RLoad is small and the current is high prior to being switched off. I probed the source pins of the FETs during a switch-off event and observed this curve:

It takes about 250ms for the FETs to fully turn off. RLoad in this case was 10 Ohm. I did some calculations in a spreadsheet and came up with this curve for power-vs-time in the MOSFETs during the switch-off event:

Integrating under the curve, I get about 17Ws (Watt-seconds). That's the total accumulated power loss among all 8 MOSFETs. There's a graph in the MOSFET's datasheet that shows the maximum single pulse power dissipation as a function of pulse width.

Now, I know that MOSFETs in parallel will work "nicely" with each other to share the total current because of their PTC nature. However, I don't know if it's safe to assume they will continue to work nicely together during a switch-off event. In other words, as the gate pins are being driven low, is there some property of MOSFETs that would cause one single MOSFET to end up taking the brunt of the switching power dissipation? Or will they all share the total power dissipation equally?

A:
In other words, as the gate pins are being driven low, is there some
  property of MOSFETs that would cause one single MOSFET to end up
  taking the brunt of the switching power dissipation? Or will they all
  share the total power dissipation equally?

Your suspicions are correct. The normally nice side of MOSFETs sharing current only applies when the gate source voltage is above a certain threshold called the zero-temperature-coefficient (ZTC) threshold. For the MOSFET you have chosen it is about 6.7 volts: -

Basically I took figure 5 and extended the curves to the ZTC threshold. At gate voltages lower than this a MOSFET will warm to destruction if not prevented in some way. Take for example the situation at 25 degC and the instant application of a gate voltage of 5 volts. Current will be about 40 amps and this will cause the junction temperature to rise rapidly and, within a few milli seconds it will have warmed to 150 degC and now will be taking about 140 amps. The junction will rapidly rise past the 175 degC limit and reach destruction temperature (about 650 degC) in a few more milliseconds.
Not all of the silicon die will warm this way. In modern HEXFETs there are a gazillion parallel small MOSFETs and the most vulnerable are those closest to the centre and farthest away from the "cooler" edge. You wil get hot-spotting and the central 10% of the die will take all this current and destruct unless there are limits to the current flow.
This can happen in less than 10 ms and you wouldn't even notice hardly the slightest external change in temperature on the case. In other words, heat sinks DO NOT prevent this happening.
So hot-spotting can happen in a group of MOSFETs and it can also happen in an individual MOSFET. Some MOSFETs are designed for operating in this area and IXYS make quite a few. The front page of the data sheet will tell you. If it says that the MOSFET is for switching applications then it is likely to be vulnerable; if it says it is for linear applications than it is likely suitable and, if you look at a suitable device's equivalent of figure 5 you will see that the curves are much tighter leading to very little extra drain current as the device warms.
Go google "thermal instability in MOSFETs" and please consider a MOSFET driver that can turn off the gate voltage in less than 1 ms. Those MOSFETs have a gate-source capacitance of 15 nF and 8 of them makes a total capacitance of over 100 nF. It may even be necessary to use several gate drivers.

A: The driver has a fall time of 2ms driving 600pF to 10 volts, a charge of 6 nC. You've attached 8 MOSFETs with a worst-case gate charge of 273nC each, for a total of 2.2 μC. So you can expect it to take worst case 370 times longer than the rated fall time: 740 ms.

Worst case you need to assume one FET has a threshold voltage of 2.0V and the rest are 4.0V. So this one will turn off last and be in linear mode while the others are off. About half the gate charge is below the threshold voltage, so this will be for about 370ms.

A: From the datasheet, I got:

The flat part of that curve is where the FET really turns on and off. The exact turn-on threshold varies from FET to FET, and the FETs "drink up" a bunch of current at their turn on voltage. So, if the HT0440LG drives at a max current of 2 mA, and the FET needs 40 nC to turn on, that takes 20 us, so each FET stalls out the voltage rise and fall for 20 us. This means that, worst case, the FETs will turn off one at a time in order of their Vgs threshold. The only good part is they turn on in the opposite order.
Individual gate resistors on each FET can help equalize the distribution a lot. You also should have an active current sink on your driver, like a push/pull transistor setup, which will increase the current going in and out of the gates, and decrease the turn on/off times.
You want to turn on and off as quickly as possible, and 250 ms is very, very slow. A slow turn off, as mentioned in the comments, means the FET is operating in linear mode where the resistance is somewhere between 1 mOhm and inifinity, so the current is going through a much larger resistance. The resistive heating will heat the FETs up briefly, and cycling their temperature will speed up their failure.


text:
Q: Colour cells with a date more than 20 years ago? I have a nominal roll with the birth dates of individuals. I need to create a program that will highlight the cells of birthdays that are more than 27 years ago in red, as 27 is the age limit. Could somebody help me with this? I know it's possible with conditional formatting function on Excel but I want to do it with vba so I can filter many different categories at once.

A: For formatting condition, you may use the following:
   'for whole column A, if cell value is greater than 27
    With Range("A:A").FormatConditions.Add(xlCellValue, xlGreater, "=27")

      'color interior with red and black for font
      .Interior.Color = RGB(255, 0, 0)
      .Font.Color = RGB(0, 0, 0)
    End With

For the birth year, you may use the following function:
    '=YearDiff(B1) <- enter this on cells as a formula with birthday parameter (from B1 on this example)
    Function YearDiff(pDate As Date) As Long
      YearDiff = DateDiff("yyyy", pDate, Now())
    End Function

Next time, please exert effort to post your code so that we may see where you got stuck.


text:
Q: EmguCV - Face Recognition - 'Object reference not set' exception when using training set from Microsoft Access Database I've been developing a face recognition application using EmguCV (C#). I got the whole thing working okay if I store the face images (training set) in simple windows folder. But, after I tried to migrate the face images to be stored in a Microsoft Access database, an 'object reference not set to an instance of an object' exception message often occurs (not always, but most of the time) when the application tries to recognize a face from the video feed.
Funny thing is, the recognition actually still works okay if the exception happens to not occur.
Here is the snippet of the code of my program, using windows folder and database:
Reading the stored images from a Windows Folder
private void FaceRecognition_Load(object sender, EventArgs e)
    {
        //if capture is not created, create it now
        if (capture == null)
        {
            try
            {
                capture = new Capture();
            }
            catch (NullReferenceException excpt)
            {
                MessageBox.Show(excpt.Message);
            }
        }

        if (capture != null)
        {
            if (captureInProgress)
            {
                Application.Idle -= ProcessFrame;
            }
            else
            {
                Application.Idle += ProcessFrame;
            }

            captureInProgress = !captureInProgress;
        }

        #endregion
        {
            // adjust path to find your xml at loading
            haar = new HaarCascade("haarcascade_frontalface_default.xml");

            try
            {
                //Load of previus trainned faces and labels for each image
                string Labelsinfo = File.ReadAllText(Application.StartupPath + "\\TrainedFaces\\TrainedLabels.txt");
                string[] Labels = Labelsinfo.Split('%');
                NumLabels = Convert.ToInt16(Labels[0]);
                ContTrain = NumLabels;
                string LoadFaces;

                for (int tf = 1; tf < NumLabels + 1; tf++)
                {
                    LoadFaces = "face" + tf + ".bmp";
                    trainingImages.Add(new Image<Gray, byte>(Application.StartupPath + "\\TrainedFaces\\" + LoadFaces));
                    labels.Add(Labels[tf]);
                }

            }
            catch (Exception error)
            {
                //MessageBox.Show(e.ToString());
                MessageBox.Show("Nothing in binary database, please add at least a face(Simply train the prototype with the Add Face Button).", "Triained faces load", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
    }

Reading the stored images from a Microsoft Access Database
private void connectToDatabase()
    {
        DBConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=FacesDatabase.mdb";
        DBConnection.Open();
        dataAdapter = new OleDbDataAdapter("Select * from TrainingSet1", DBConnection);
        dataAdapter.Fill(localDataTable);

        if (localDataTable.Rows.Count != 0)
        {
            numOfRows = localDataTable.Rows.Count;
        }
    }

private void FaceRecognition_Load(object sender, EventArgs e)
    {
        //if capture is not created, create it now
        if (capture == null)
        {
            try
            {
                capture = new Capture();
            }
            catch (NullReferenceException excpt)
            {
                MessageBox.Show(excpt.Message);
            }
        }

        if (capture != null)
        {
            if (captureInProgress)
            {
                Application.Idle -= ProcessFrame;
            }
            else
            {
                Application.Idle += ProcessFrame;
            }

            captureInProgress = !captureInProgress;
        }

        #endregion
        {
            // adjust path to find your xml at loading
            haar = new HaarCascade("haarcascade_frontalface_default.xml");

            connectToDatabase();

            Bitmap bmpImage;

            for (int i = 0; i < numOfRows; i++)
            {
                byte[] fetchedBytes = (byte[])localDataTable.Rows[i]["FaceImage"];
                MemoryStream stream = new MemoryStream(fetchedBytes);
                bmpImage = new Bitmap(stream);
                trainingImages.Add(new Emgu.CV.Image<Gray, Byte>(bmpImage));

                String faceName = (String)localDataTable.Rows[i]["Name"];
                labels.Add(faceName);
            }
       }
   }

The face recognition function that causes the exception (exactly the same both when using windows folder and Access database):
private void ProcessFrame(object sender, EventArgs arg)
    {
        Image<Bgr, Byte> ImageFrame = capture.QueryFrame();

        Image<Gray, byte> grayframe = ImageFrame.Convert<Gray, byte>();

        MinNeighbors = int.Parse(comboBoxMinNeighbors.Text);
        WindowsSize = int.Parse(textBoxWinSiz.Text);
        ScaleIncreaseRate = Double.Parse(comboBoxMinNeighbors.Text);

        var faces = grayframe.DetectHaarCascade(haar, ScaleIncreaseRate, MinNeighbors,
                                        HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
                                        new Size(WindowsSize, WindowsSize))[0];

        if (faces.Length > 0)
        {
            Bitmap BmpInput = grayframe.ToBitmap();

            Graphics FaceCanvas;

            foreach (var face in faces)
            {
                t = t + 1;
                result = ImageFrame.Copy(face.rect).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);

                ImageFrame.Draw(face.rect, new Bgr(Color.Red), 2);

                ExtractedFace = new Bitmap(face.rect.Width, face.rect.Height);

                FaceCanvas = Graphics.FromImage(ExtractedFace);

                FaceCanvas.DrawImage(BmpInput, 0, 0, face.rect, GraphicsUnit.Pixel);

                ImageFrame.Draw(face.rect, new Bgr(Color.Red), 2);

                if (trainingImages.ToArray().Length != 0)
                {

                    MCvTermCriteria termCrit = new MCvTermCriteria(ContTrain, 0.001);

                    EigenObjectRecognizer recognizer = new EigenObjectRecognizer(
                        trainingImages.ToArray(),
                        labels.ToArray(),
                        3000,
                        ref termCrit);
                    try
                    {
                        name = recognizer.Recognize(result).Label;
                    }
                    catch (Exception error)
                    {
                        MessageBox.Show(error.ToString());
                    }

                    ImageFrame.Draw(name, ref font, new Point(face.rect.X - 2, face.rect.Y - 2), new Bgr(Color.LightGreen));
                }

            }
        }
        CamImageBox.Image = ImageFrame;
    }

Here is the screenshot of the exception message:
http://i.imgur.com/DvAhABK.jpg
Line 146 where the exception occurs is this line of the ProcessFrame function:
name = recognizer.Recognize(result).Label;

I tried searching for similar problems in the internet, and found these:
'Object reference not set to instance of an object' error when trying to upload image to database
Object reference not set to an instance of an object #5
C# Error 'Object Reference Not Set To An Instance Of An Object'
C#, "Object reference not set to an instance of an object." error
Most of them suggests to check if any of the involved variable is null. I've checked the involved variable, and indeed the exception occurs when the recognizer.Recognize(result) statement returns null.
So my question is, why does that statement often return null when I use training images from the database, while it never returns null when I use training images from windows folder?

A: Check your fetchedBytes array to see if you are consistently getting just a stream of bytes representing a BMP image (starting with 0x42 0x4D), or if there may be "other stuff" in there, too.
Depending on how the BMP data was inserted into the Access database it may contain an OLE "wrapper". For example, an 8x8 24-bit BMP image of pure red is saved by MSPAINT.EXE like this

If I copy that file and paste it into a Bound Object Frame in an Access form then Access wraps the BMP data in some "OLE stuff" before writing it to the table. Later, if I try to retrieve the BMP image via code, using something like this...
Sub oleDumpTest()
    Dim rst As ADODB.Recordset, ads As ADODB.Stream
    Set rst = New ADODB.Recordset
    rst.Open "SELECT * FROM TrainingSet1 WHERE ID = 1", Application.CurrentProject.Connection
    Set ads = New ADODB.Stream
    ads.Type = adTypeBinary
    ads.Open
    ads.Write rst("FaceImage").Value
    rst.Close
    Set rst = Nothing
    ads.SaveToFile "C:\Users\Gord\Pictures\oleDump_red."
    ads.Close
    Set ads = Nothing
End Sub

...then the resulting file also contains the OLE "wrapper"...

...and obviously is not a valid stand-alone BMP file. If I rename that file to give it a .bmp extension and try to open it in Paint, I get

So maybe (some of) the [FaceImage] objects in your database are not raw BMP data, and perhaps the other software is rejecting them (or simply not able to understand them).
Edit
Another possible issue is that when you get the images from files in a folder you hand the Image object a string containing the file path...
trainingImages.Add(new Image<Gray, byte>(Application.StartupPath + "\\TrainedFaces\\" + LoadFaces));

...but when you try to retrieve the images from the database you hand the same object a Bitmap object
MemoryStream stream = new MemoryStream(fetchedBytes);
bmpImage = new Bitmap(stream);
trainingImages.Add(new Emgu.CV.Image<Gray, Byte>(bmpImage));

I have no way of knowing whether the Emgu.CV.Image object might behave differently depending on the type of object it is given, but a quick+dirty workaround might be to write bmpImage to a temporary file, hand trainingImages.Add the path to that file, and then delete the file.

A: Finally made it!! just one more day of coding helped me to got the problem solved:
public void ProcessRequest(HttpContext context)
{
    _httpContext = context;
    var imageid = context.Request.QueryString["Image"];
    if (imageid == null || imageid == "")
    {
        imageid = "1";
    }

    using (WebClient wc = new WebClient())
    {
        // Handler retrieves the image from database and load it on the stream
        using (Stream s = wc.OpenRead("http://mypageurl/Image.ashx?Image=" + imageid))
        {
            using (Bitmap bmp = new Bitmap(s))
            {
                AddFace(bmp);
            }
        }
    }

}

public void AddFace(Bitmap image)
{
    var faceImage = DetectFace(image);
    if (faceImage != null)
    {
        var stream = new MemoryStream();
        faceImage.Save(stream, ImageFormat.Bmp);
        stream.Position = 0;
        byte[] data = new byte[stream.Length];
        stream.Read(data, 0, (int)stream.Length);

        _httpContext.Response.Clear();
        _httpContext.Response.ContentType = "image/jpeg";
        _httpContext.Response.BinaryWrite(data);
    }
}

private Bitmap DetectFace(Bitmap faceImage)
{
    var image = new Image<Bgr, byte>(faceImage);
    var gray = image.Convert<Gray, Byte>();
    string filePath = HttpContext.Current.Server.MapPath("haarcascade_frontalface_default.xml");
    var face = new HaarCascade(filePath);
    MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(face, 1.1, 10, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
    Image<Gray, byte> result = null;

    foreach (MCvAvgComp f in facesDetected[0])
    {
        //draw the face detected in the 0th (gray) channel with blue color
        image.Draw(f.rect, new Bgr(Color.Blue), 2);
        result = image.Copy(f.rect).Convert<Gray, byte>();
        break;
    }

    if (result != null)
    {
        result = result.Resize(200, 200, INTER.CV_INTER_CUBIC);
        return result.Bitmap;
    }

   return null;
}

public bool IsReusable
{
    get { return false; }
}

A: I couldnt make it work from reading a direct Stream from the the Database where the images are located but your workaround, saving the images to a local folder, worked for me, thx a lot for sharing.Here's my demo page where you load files from DB: http://www.edatasoluciones.com/FaceDetection/FaceDataBase


text:
Q: Unity3D frame rate dropped after importing Blender model I am making a 3D game with Unity for Android. In the game there is a main character and up to around 10 opponents possibly on the screen at the same time, all using the same model (prefabs for "opponents" differ only in one material for other colors).
The model was designed using MakeHuman and Blender.
On PC (since rendering is a lot faster) there are no problems, but when testing it on an Android device, the rendering time drops the frame rate to around 25-30 FPS when there are 3-4 or more bodies on the screen, creating a really "laggy" feeling (I am expecting a frame rate of about 60 FPS).

Before importing the Blender model I used placeholder spheres and there was no such behavior. Since this is the first time I am using Blender and such 3D models, I am not sure whether my model is within the expected sizes for a mobile game. My current model consists of: 5,956 Verts, 10,456 Faces, 10,819 Tris with a file size of around 6.5 MB (it was generated even larger by MakeHuman at first, but I managed to compress it and optimize it significantly, but still without major effects).
I attempted different solutions, including merging all meshes in the model into one, turning off shadows, using as least materials as possible, etc. All attempts were with no or very limited improvement.
Any ideas are welcome. Cheers!

A:
My current model consists of: 5,956 Verts, 10,456 Faces, 10,819 Tris
  with a file size of around 6.5 MB

Sounds like way too much to me.
Also, keep in mind that if you're doing anything such collision calculations, every extra complexity takes exponentially more time

A: for a mobile game I would suggest you to remesh the model (even though its not a nice work, but the results are much better than the decimate-modifyer for example) an than bake normalmaps for it from the high-res model.


text:
Q: TypeError: in typeassert in Julia 1.6.3 I am new to Julia. I am working on a Julia package which the writer is not available.
This is the part of the code where I have a problem with:
function find_partition(model::Model, ms)
    ps = Dict{Z3Expr,Vector{Int}}()
    for (i, m) in enumerate(ms)
        mval = Z3.eval(model, m, false)
        println(ps)
        println(mval)
        println(typeof(mval))
        if haskey(ps, mval)
            push!(ps[mval], i)
        else
            push!(ps, mval=>Int[i])
        end
    end
    values(ps)
end

Here is the output:
Dict{Z3.Expr, Vector{Int64}}()
1.0
Z3.ExprAllocated
ERROR: TypeError: in typeassert, expected UInt64, got a value of type UInt32
Stacktrace:
  [1] hashindex(key::Z3.ExprAllocated, sz::Int64)
    @ Base ./dict.jl:169
  [2] ht_keyindex(h::Dict{Z3.Expr, Vector{Int64}}, key::Z3.ExprAllocated)
    @ Base ./dict.jl:284
  [3] haskey(h::Dict{Z3.Expr, Vector{Int64}}, key::Z3.ExprAllocated)
    @ Base ./dict.jl:550
  [4] find_partition(model::Z3.ModelAllocated, ms::Vector{Z3.ExprAllocated})
    @ Absynth.NLSat ~/Desktop/faoc/Absynth/src/nlsat/cfinitesolver.jl:101

I tried following it and found out that somewhere inside dict.jl in Julia, there are such lines
sz = length(h.keys)
...
index = hashindex(key, sz)

And this is the hashindex written somewhere in dict.jl:
hashindex(key, sz) = (((hash(key)::UInt % Int) & (sz-1)) + 1)::Int

It seems that the version of Z3 used in this package is not compatible with the current version of Julia. I am not sure if this package was working in the beginning at all.
Is there any quick fix to this? Like rewriting this part of the code:
if haskey(ps, mval)
     push!(ps[mval], i)
else
     push!(ps, mval=>Int[i])

in a way that this won't happen? I tried writing like merge!(ps,Dict(mval=>Int[i])) but it's eventually reaching this hashindex function again.
If I install the older versions of Julia, would it be possible to solve this issue or the problem is somewhere else?


text:
Q: simple Java Regex read between two So I have a source page in text and I know it contains a link that is formatted like this
img src="http://someurl   and ends with -t1
I am trying to extract whatever is between img src and -t1 . It doesn't have to be perfect . I  can work with "http... or src="http... or so on . I just want to trim the source code to around that URL . I am reading about Regex but just can't seem to figure the logic . Anyone Can help ?
    File workfile = new File("page.txt");
    BufferedReader br = new BufferedReader(new FileReader(workfile));
    String line;
    while ((line = br.readLine()) != null) {
        //System.out.println(line);

        //Pattern p = Pattern.compile("src"+"t1");  ???
        //Matcher m = p.matcher("t1");              ???

    }
    br.close();

Edit : Solved by Using :
String url = line.split("<img src=")[1].split("-t1")[0];
System.out.println(url);

Thanks goes to all reply's .

A: String url = <your url eg... img src='http://someurl and ends with -t1'>

String whatYouWant = url.split("img src")[1].split("-t1")[0];

whatYouWant is the required string by you

A: Pattern pattern = Pattern.compile("img src(.+?)-t1");
Matcher matcher = pattern.matcher("img src=\"http://someurl-t1");
matcher.find();
System.out.println(matcher.group(1)); // Prints String I want to extract

A: If all your urls are similar to your example you can do some thing like this.
    String src="img src=\"http://someurl and ends with -t1\"";
    String[] url=src.split("img src");
    String[] str=url[1].split("-t1");
    System.out.println(str[0]);


text:
Q: Trying to find the top 5 and bottom 5 of this variable? Okay, so I'm trying to find the top 5 counties for the variable "total_used". I was trying different stuff with the top_five data set compared to the bottom_five data set. My problem is that I'm trying to just print out the top/bottom five counties. But I keep getting repeats of counties, and I don't want repeats, I want 5 different ones. I don't know how to change it so that I don't get any repeats but also, I don't know how to get it to churn out 5 different ones.
top_five <- arrange(dataset, total_used) %>%
  select(County, na.rm = TRUE)

print(top_five)

bottom_five <- arrange(dataset, desc(total_used)) %>%
  count = n(5) %>%
  select(County)

print(bottom_five)

A: As Akrun said, difficult to know without an example, some ideas though
dataset <- tibble(County= c("C1","C1", "C2","C2"),
              total_used= c(1,5,6,4))

dataset %>%
  group_by(County) %>%
  filter(total_used == max(total_used)) %>%
  head(5)

dataset %>%
  group_by(County) %>%
  filter(total_used == min(total_used)) %>%
  head(5)

dataset %>%
  arrange(total_used) %>%
  group_by(County) %>%
  slice_tail()


text:
Q: How To Disable AutoFill For Combobox using c#? I have added combo boxes/Auto Complete Textbox to display several lists but after clicking the Drop_down it is auto filled with google services which in turns hide the combo_box list. I have added code(Custom view, Custom Renderers and other necessary classes) of XfX.Control Nuget Package. Provided is the link from where I have downloaded the NuGet package:
https://www.nuget.org/packages/Xfx.Controls
Besides this when I change the Auto Fill services of my phone to None from Google the list appears as it is. This is how the combobox looks like.its hiding defined list.


text:
Q: Relay Triggering with Transducer Signal I wish to design a circuit that will be operating via a signal from a battery voltage transducer. The transducer will provide a signal range from 0-5V. I am actually confused with interfacing the eternal transducer with a comparator. I am also using a POT to set the threshold.
I know basic comparator circuit design using resistors etc but don't know how to interface it with the external transducer. I am attaching a rough schematic I drew.
Kindly have a look and guide me.
Regards!
..


text:
Q: A formula that outputs numbers in sequence despite skipping cells Can one output 1, 2, 3, etc. but have 2 empty cells between each number?
This doesn't necessarily start in B.
The empty cells can remain empty without a formula.
Required output:

A
B
C
D
E
F
G
H
I
J
K
L

1

2

3

4

A: With Office 365 we can use SEQUENCE:
 =IF(MOD(SEQUENCE(,4*3,0),3)=0,INT(SEQUENCE(,4*3,1,1/3)),"")

Put that in the first cell desired.  You can change the 4s to the total number desired. And it will spill across.

A: =TEXTJOIN(",",TRUE,A1:H1)

A: Pick some cell, say C7, and enter 1.
In D7 enter:
=IF(MOD(COLUMNS($A:B),3)=1,1+MAX($C$7:C7),"")

and copy across.


text:
Q: Restarting Apache hangs SSH session I have a script which will do a lot of prep work (generate config files, minimize and gzip Javascript and CSS files, etc) and then restart apache which is installed in a non-standard location). But after the script is run, when I try to exit out of my ssh session it just hangs indefinitely.
I've read the recommendation that I should redirect the IO for the actual call to the httpd binary with something like this:
sudo /path/to/httpd -f /path/to/config < /dev/null >& /dev/null

And this works and my ssh session no longer hangs after the script is done. But the problem is that now I've lost any errors that are spit out to STDERR if something goes wrong when it's started. This just seems really odd to me because I have another system with a similar (but not exact) setup that doesn't hang. And from reading the recommendation that suggests this workaround it says that daemons (like apache) should already be taking care of this. So what am I missing? Any pointers on how I can track this down or how I can fix it?

A: Firstly, you seem to have the ampersand in the wrong place. Instead of
/path/to/httpd -f /path/to/config < /dev/null >& /dev/null

I would expect
/path/to/httpd -f /path/to/config < /dev/null > /dev/null &

EDIT - actually, command >& file is a short form of command > file 2>&1. I've never used the short form, so I misunderstood the intent of that construct.
But I wouldn't do this. Redirecting STDIN and STDOUt to /dev/null is wrong. Omitting STDERR is also wrong. Doing this to program which puts itself into daemon mode is wrong. If you really had to do this I'd do something like
nohup /path/to/httpd -f /path/to/config >/tmp/httpd.out 2>/tmp/httpd.err &

But wait, Apache can be restarted by sending it signals using the apachectl script. You can signal Apache to gracefully reload it's configuration without dropping existing connections or you can signal it to restart afresh. If all you are doing is changing it's config, just do a graceful reload. I'd also use apachectl to do a configtest.
If Apache is in a non-standard location, you should still be able to use apachectl.
If you can't use apachectl you can send SIGUSR1 (reload) or SIGHUP (restart) signals to the main httpd process.
If apache isn't running, the best way to start it is by using the /etc/init.d/apache start script
If apachectl and the startup scripts don't work because you've relocated programs, I'd edit those scripts, there are variables that say which directories the executables are in.


text:
Q: connection string based on ms access version present in PC I have developed a windows application.
My development environment is win7, office2007, C#, VS2010, Winforms.
My application stores data in MS Access.
Is there any way with which i can create a connection string based on MS Access version present in PC?

A: Solution 1: You can get the Ms-Access version from widows Registry and apply the respective connection string.


text:
Q: Why isn't this glFT model loaded through A-Frame displaying on an iPhone browser? This example displays the model in Chrome on a computer. However, this example does not show anything when it is loaded from either Chrome or Safari on an iPhone 5 (iOS 9.3.1). Does this happen to you too? Why is this happening?
Edit: It works in Safari on an iPhone 6 (iOS 10.2.1), but I still wonder why.
Edit 2: It works in Safari, Firefox and Chrome on an iPhone 5 now; the iOS has been updated to iOS 10.3.2.

A: Please provide any console logs as the information is so vague I can only speculate.
According to this thread, loading a glTF model in threeJS on iOS is highly limited by the number of the model bones.  If You manage to get the logs working, and You get the WebGLRenderer: too many bones issue, it means You will need to change the model.
Also note, that according to the documentation, the support of iOS browsers is highly limited, so results may vary from what You get on Your desktop browser.
.


text:
Q: Angular App not compiling I am trying to create a simple Angular app and I am trying to use ngrx so I can use states. I was initially in my app folder and ran the command yarn add @ngrx/store.
Whenever I try to import the StoreModule using import { StoreModule } from '@ngrx/store' at the top of my app.module.ts file I receive a compilation error (listed below).
ERROR in node_modules/@ngrx/store/src/actions_subject.d.ts(2,10): error TS2305: Module '"...AngularProjects/ngrx-tut/node_modules/rxjs/BehaviorSubject"' has no exported member 'BehaviorSubject'.
node_modules/@ngrx/store/src/reducer_manager.d.ts(2,10): error TS2305: Module '".../AngularProjects/ngrx-tut/node_modules/rxjs/BehaviorSubject"' has no exported member 'BehaviorSubject'.
node_modules/@ngrx/store/src/reducer_manager.d.ts(3,10): error TS2305: Module '".../AngularProjects/ngrx-tut/node_modules/rxjs/Observable"' has no exported member 'Observable'.
node_modules/@ngrx/store/src/scanned_actions_subject.d.ts(2,10): error TS2305: Module '".../AngularProjects/ngrx-tut/node_modules/rxjs/Subject"' has no exported member 'Subject'.
node_modules/@ngrx/store/src/state.d.ts(2,10): error TS2305: Module '".../AngularProjects/ngrx-tut/node_modules/rxjs/BehaviorSubject"' has no exported member 'BehaviorSubject'.
node_modules/@ngrx/store/src/state.d.ts(3,10): error TS2305: Module '".../AngularProjects/ngrx-tut/node_modules/rxjs/Observable"' has no exported member 'Observable'.
node_modules/@ngrx/store/src/store.d.ts(2,10): error TS2305: Module '".../AngularProjects/ngrx-tut/node_modules/rxjs/Observer"' has no exported member 'Observer'.
node_modules/@ngrx/store/src/store.d.ts(3,10): error TS2305: Module '".../AngularProjects/ngrx-tut/node_modules/rxjs/Observable"' has no exported member 'Observable'.
node_modules/@ngrx/store/src/store.d.ts(4,10): error TS2305: Module '".../AngularProjects/ngrx-tut/node_modules/rxjs/Operator"' has no exported member 'Operator'.
node_modules/rxjs/BehaviorSubject.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/BehaviorSubject'.
node_modules/rxjs/Observable.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observable'.
node_modules/rxjs/Observer.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Observer'.
node_modules/rxjs/Operator.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Operator'.
node_modules/rxjs/Subject.d.ts(1,15): error TS2307: Cannot find module 'rxjs-compat/Subject'.

I am able to import { Action } from '@ngrx/store' on a different file and I don't have receive any errors.
I appreciate any help and/or comments!
EDIT:
I included import { Observable } from 'rxjs'; but I am still getting these errors.

A: Here were my dependencies at the beginning of this question:
Angular - 6.0.2 | rxjs - 6.1.0 | @ngrx/store - 1.X

My issue was that my @ngrx/store was on 1.X and everything else I had was on 6.X. I updated @ngrx/store to v6.0.0-beta.3 and it works now.

I initially installed @ngrx/store using the yarn command. Does that mean that using yarn will give everyone a v1.x verison by default? I hope not..

Anyways, thanks everyone for your help!


text:
Q: C# GraphQLRequest : Variable $max is used by but not declared I'm trying to send a GraphQL Request using This GraphQL Library.
When I attempt to send the GraphQLRequest with some variables attached I get the following error,Variable $max is used by but not declared.
GraphQLRequest graphqlRequest = new GraphQLRequest
{
    Query = "query {boards(limit: $max) {items(limit: $max) {id}}}",
    Variables = new
    {
        max = "1"
    }
};

GraphQLResponse<string> graphQLResponse = await _graphqlClient.SendQueryAsync<string>(graphqlRequest);

Changing max from a string to an int had no change.
If I try and send the same request hardcoded without the Variables attached, the request is successful.
query {boards(limit: 1) {items(limit: 1) {id}}}
Update
I updated the query with the help of gunr2171's answer, however unfortunately the sdk is still throwing errors.
GraphQLRequest graphqlRequest = new GraphQLRequest
{
    Query = "query($max: Int) {boards(limit: $max) {items(limit: $max) {id}}}",
    Variables = new
    {
        max = 1
    }
};

System.AggregateException: 'One or more errors occurred. (Unexpected character encountered while parsing value: {. Path 'data', line 1, position 9.)'
I tried changing $max: Int to $max: String as well as max = 1 to max = "1"but the request isnt sucessful.
Variable max of type Int was provided invalid value or Type mismatch on variable $max and argument limit (String / Int) depending on the combination.

Update
Changing the response type from string to the proper object response has solved the problem. eg
GraphQLResponse<string> graphQLResponse = await _graphqlClient.SendQueryAsync<string>(graphqlRequest);

to
GraphQLResponse<AuthorizationResponse> graphQLResponse = await _graphqlClient.SendQueryAsync<AuthorizationResponse>(graphqlRequest);

For some one reason or another when using Variables it didnt like the string response type.Thank you gunr2171 for their help, and pointing me in the right direction

A: You need to define the variable in the top level query before you can use it inside the query body.
query($max: Int) {
  boards(limit: $max) {
    items(limit: $max) {
      id
    }
  }
}

New line characters added for readability. You can collapse this to one line for your actual code.
The difference here is the ($max: Int) after query. That let's the graphql engine know that some variables will be used and what their type is. I'm assuming for your example that the variable is an integer.

Also, when you submit your variables, make sure you keep the data as an integer.
Variables = new
{
   max = 1 // don't quote this
}

You've got three places where the types need to line up correctly.

*

*The Variables property of the GraphQLRequest

*The declaration of the variable in query()

*The expected type for the arguments you are using.

Double check that the limit arguments of BOTH boards() and items() is an Int, and not for some reason another data type (like String).


text:
Q: presto SQL - Filter records if date column format is not matching yyyy-MM-dd I need to get all the records from a table that has a date not matching with the format yyyy-MM-dd.
Here,  column ID is unique bigint column. start_date is of varchar datatype.
Sample input:

Expected output:

Thanks

A: Use regexp_like:
select id, start_date
  from mytable
 where NOT regexp_like(start_date, '\d{4}-\d{2}-\d{2}')

This will work for '11-12-200' and 'None'.
If you want to include NULL values as well, add additional condition:
 where (NOT regexp_like(start_date, '\d{4}-\d{2}-\d{2}'))
    OR start_date is null

More strict date regexp is '^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$'
This will restrict month to 01 .. 12 and day to 01 .. 31 and will not allow other characters before and after date( ^ and $ anchors are used).
One more simple and powerful method
is to use try_cast(col as date) - it will return NULL if not possible to cast:
where try_cast(start_date as date) is not null

This will also restrict wrong dates like Feb 30 (2000-02-30)


text:
Q: step doubling Runge Kutta implementation stuck shrinking stepsize to machine precision I need to integrate a system of ODES using an adaptive RK4 method with stepsize control via step doubling techniques.
The problem is that the program continues forever shrinking the stepsize down to machine precision while not advancing time.
the idea is to step the solution once by a single step and also by two successive half steps, compare the result as their difference and store it in eps. So eps is a measure of the error. Now I want to determine the next step stepsize according to whether eps is greater to a specified accuracy eps0 (as described in the book "Numerical Recipes")
RK4Step(double t, double* Y, double *Yout, void (*RHSFunc)(double, double *, double *),double h) steps the solution vector Y by h and puts the result into Yout using the function RHSFunc.
#define NEQ 4 //problem dimension

int main(int argc, char* argv[])
{
  ofstream frames("./frames.dat");
  ofstream graphs("./graphs.dat");

  double Y[4]  = {2.0, 2.0, 1.0, 0.0}; //initial conditions for solution vector
  double finaltime = 100;  //end of integration
  double eps0   =  10e-5;  //error to compare with eps

  double t = 0.0;
  double step = 0.01;
  while(t < finaltime)
  {
    double eps = 0.0;
    double Y1[4], Y2[4]; //Y1 will store   half step solution
                         //Y2 will store double step solution
    double dt = step;    //cache current stepsize
    for(;;)
    {
      //make a step starting from state stored in Y and
      //put solution into Y1. Then from Y1 make another half step
      //and store into Y1.
      RK4Step(t,     Y,  Y1, RHS,   step);  //two half steps
      RK4Step(t+step,Y1, Y1, RHS,   step);
      RK4Step(t,     Y,  Y2, RHS, 2*step);  //one long step

      //compute eps as maximum of differences between Y1 and Y2
      //(an alternative would be quadrature sums)
      for(int i=0; i<NEQ; i++)
        eps=max(eps, fabs( (Y1[i]-Y2[i])/15.0 ) );

      //if error is within tolerance we grow stepsize
      //and advance time
      if(eps < eps0)
      {
        //stepsize is accepted, grow stepsize
        //save solution from Y1 into Y,
        //advance time by the previous (cached) stepsize
        Y[0] = Y1[0]; Y[1] = Y1[1];
        Y[2] = Y1[2]; Y[3] = Y1[3];
        step = 0.9*step*pow(eps0/eps, 0.20); //(0.9 is the safety factor)
        t+=dt;
        break;
      }
      //if the error is too big we shrink stepsize
      step = 0.9*step*pow(eps0/eps, 0.25);
    }

  }

  frames.close();
  graphs.close();
  return 0;

}

A: You never reset eps in the inner loop. This could be the direct cause of your problem. While the actual error reduces with ever decreasing step sizes, the maximum in eps stays constant, and above eps0. This results in a constant reducing factor in the step size update, without any chance to break the loop.

Another "wrong thing" is that the error estimate and tolerance are incompatible. The error tolerance eps0 is an error density or unit-step error. To bring your error estimate eps into that format you need to divide eps by step. Or put another way, currently you are forcing the actual step error to be close to 0.5*eps0, so that the global error is 0.5*eps0 times the number of steps taken, with the number of steps loosely proportional to eps0^0.2. In the version using the unit-step error, the local error is forced to be "dynamically" close to 0.5*eps0*step, so that the global error is about 5*eps0 times the length of the integration interval. I'd say that the second variant is more in line with intuition about the expected behavior.
This is not a critical error, but may lead to sub-optimal step sizes and an actual global error that deviates non-trivially from the desired error tolerance.

You also have a coding inconsistency as in the propagation of the state and declaration of state vectors you have hard-coded 4 components in the state vector, while in the error computation you have a loop over a variable number NEQ of equations and components. As you are using C++, you could use a state vector class that handles all dimension-dependent loops internally. (If done too far, frequent allocation of instances with a short life span could be an efficiency issue.)


text:
Q: Como descobrir o HTML gerado pela linha echo $OUTPUT->course_content_header(); Estou modificando um tema do moodle, porem eu não consigo encontrar alguns arquivos HTML ou pelo menos entender como eles são criados via backend, tenho o seguinte código:
<?php
            echo $OUTPUT->course_content_header();
            echo $OUTPUT->main_content();
            echo $OUTPUT->course_content_footer();
?>

Eu preciso adicionar um elemento dentro do html que uma dessas linhas de código gera, como faço para descobrir no moodle como ele gera esse html e como adicionar esse componente aonde eu quero.

Quero adicionar um componente HTML dentro do bloco Visão Geral dos Cursos, logo acima do texto Nenhuma informação disponível sobre o curso

A: Digite o seguinte código: var_dump($OUTPUT->course_content_header()); die; para ver a saída da coleção $OUTPUT.
Segue conteúdo do método citado:
public function course_content_header($onlyifnotcalledbefore = false) {
        global $CFG;
        if ($this->page->course->id == SITEID) {
            // return immediately and do not include /course/lib.php if not necessary
            return '';
        }
        static $functioncalled = false;
        if ($functioncalled && $onlyifnotcalledbefore) {
            // we have already output the content header
            return '';
        }
        require_once($CFG->dirroot.'/course/lib.php');
        $functioncalled = true;
        $courseformat = course_get_format($this->page->course);
        if (($obj = $courseformat->course_content_header()) !== null) {
            return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
        }
        return '';
    }


text:
Q: Toggle button with value from sessionStorage I have a small toggle button, and I store value (true or false) to sessionStorage, and on page load, if the value exists in sessionStorage I take it and show toggle button depending on value, also, depending on this value I show different content on my angularjs page.
Problem is, I store a value to sessionStorage, and on again I call this value but my toggle button and my ng-if statement do not get this. Here is my code bellow.
Question is, how, and why I can't get this to the ng-if statement? (in my fiddle I use ng-show because ng-if not working in this example)
working fiddle

var app = angular.module("ap", []);

app.controller("con", function($scope) {
  if (sessionStorage.getItem("modePreview")) {
    $scope.basicMode = sessionStorage.getItem("modePreview");
  } else {
    $scope.basicMode = true;
  }
  $scope.sendModeValueToStorage = function() {
    sessionStorage.setItem(
      "modePreview",
      ($scope.basicMode = !$scope.basicMode)
    );
  };

});
.activeSwitch,
.inactiveSwitch {
  font-size: 26px;
  cursor: pointer;
}

i.activeSwitch {
  color: #e4e4e471;
}

i.inactiveSwitch {
  color: #e4e4e471;
}

.fontStyleUserControlPannel {
  font-size: 18px;
  font-weight: 600;
}

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

  Advanced mode  Basic mod

      Basic mode

      Advanced mode

A: A few issues:
First, in your fiddle, you're using AngularJS version 1.1.1. ng-if did not exist in AngularJS prior to version 1.1.5. So you'll want to update your AngularJS version to use ng-if.
Secondly, sessionStorage can only accept string values. So if you want to store a JS object in sessionStorage, you have to JSON.stringify() the object to store it, and use JSON.parse() when retrieving it.
Finally, your conditional block always sets $scope.basicMode to true:
if (sessionStorage.getItem("modePreview")) { // if modePreview is true
  $scope.basicMode = sessionStorage.getItem("modePreview"); // set basicMode to true
} else { // otherwise, still set basicMode to true?
  $scope.basicMode = true;
}

I think you want the else statement to be $scope.basicMode = false, right?
Updated Working Fiddle: https://jsfiddle.net/zx02f1yv/


text:
Q: Is there a language in which `print, "hello, world!"` is a valid Hello World program? My Code Jam T-shirt has the following snippet of code on the front.
print, "hello, world!"

Here is an image of it (taken from the Hash Code Twitter, not my T-shirt):

This is not a correct Hello World program in any language that I know. It is almost Python 2, but not quite. Apparently it runs in Javascript, but it doesn't give any output. I have asked several people, and none of them know.
Is there any programming language in which this is a valid Hello, world program?

A: This could be Basic, which uses the comma as a "zone" delimiter. So it basically (hah) effects a 15 space indent before "hello world!".
See http://www.dartmouth.edu/basicfifty/commands.html, "PRINT Statements".
Although of course, it could also be something else entirely =D

A: It looks like early algol or similar language, comma after print indicates omitted first parameter (which was device name or punch device id usually). Not all implementations allowed to omit it, but such omission was inherited by 80s-90s interpreter languages.
Algol 60 didn't had standard I/O, but some versions had output in form of PRINT <device>, <some tags>, <data>


text:
Q: Is there an efficient way to convert from Bundle to ContentValues? The Bundle and ContentValues classes seem to have pretty similar functionality.
Is there an efficient way of converting from one to another (and vice-versa) without having to loop through the classes, calling get and put subsequently on each element?

A: I've scanned the Android source code and both Classes use a Map to hold the underlying data. Specifically, Bundle uses a Map and ContentValues uses a HashMap.
However, Bundle permits any parcelable objects to be loaded, while ContentValues' implementation accepts the primitive type classes (Integer, String, Double etc.) and byte arrays.
So it looks like in principle, ContentValues is a special case of Bundle, so converting  from ContentValues to Bundle might have been possible if the internals were accessible, but the reverse is problematic, since a Bundle can hold objects not strictly compatible with ContentValues.
Any comments on this are welcome.


text:
Q: Hadoop: Getting error when i load file from source (i.e my PC) to HDFS Im trying to copy a file from source to hdfs
Query: Hadoop fs -copyFromLocal (Local path) (source path)
e.g Hadoop fs -copyFromLocal C:\users\Desktop  (source path)
as well e.g Hadoop fs -copyFromLocal C:\users\Desktop  URI
but geting error
-copyFromLocal: Can not create a Path from a null string
Usage: hadoop fs [generic options] -copyFromLocal [-f] [-p] (localsrc) ... (dst)

A: try hadoop dfs -copyFromLocal file_to_be_copied hdfs://namenode:/path_to_location
fs command is being depreciated.
Note: you do not have to mention the actual HDFS path. You could also do something like
hadoop dfs -copyFromLocal file_to_be_copied /path_to_location_within_hdfs

A: *

*You are not specifying the path of file.

*Make sure hdfs path that you specified exists.

*Finally try escaping the forward slash like:
Hadoop fs -copyFromLocal C:\\users\\Desktop\myfile.txt URI

Or use
    Hadoop fs -copyFromLocal C:/users/Desktop/myfile.txt URI

A: Unfortunately, I am unable to comment below your reply.
The easiest way to to get the path is to go under the UI and click on "Browse the filesystem". Another option would be to hdfs dfs -ls /  or hdfs dfs -lsr /
ls will list the dir/files in your root dir.
lsr will recursively read through all the sub directories in your root dir.

A: HDFS is just like other file systems. The path begins with / as root. The period (.) denotes current directory. I am on Linux platform. Hope the examples below would help.
name@host: ~/oracle/sql$ hdfs dfs -ls /
Found 5 items
drwxr-xr-x   - myname supergroup          0 2014-09-05 03:06 /directory
drwxr-xr-x   - myname supergroup          0 2014-05-10 03:34 /in
drwxr-xr-x   - myname supergroup          0 2014-10-16 22:50 /system
drwxrwx---   - myname supergroup          0 2014-08-18 08:44 /tmp
drwxr-xr-x   - myname supergroup          0 2014-08-18 08:41 /user
name@host: ~/oracle/sql$ hdfs dfs -copyFromLocal foo.sql /
name@host: ~/oracle/sql$ hdfs dfs -ls /
Found 6 items
drwxr-xr-x   - myname supergroup          0 2014-09-05 03:06 /directory
-rw-r--r--   3 myname supergroup         90 2015-03-24 05:33 /foo.sql
drwxr-xr-x   - myname supergroup          0 2014-05-10 03:34 /in
drwxr-xr-x   - myname supergroup          0 2014-10-16 22:50 /system
drwxrwx---   - myname supergroup          0 2014-08-18 08:44 /tmp
drwxr-xr-x   - myname supergroup          0 2014-08-18 08:41 /user

name@name: ~/oracle/sql$ hdfs dfs -copyFromLocal foo.sql /user/myname/
name@name: ~/oracle/sql$ hdfs dfs -ls /user/myname/foo.sql
-rw-r--r--   3 myname supergroup         90 2015-03-24 05:41       /user/myname/foo.sql
name@host: ~/oracle/sql$


text:
Q: Scrapy - Add data to json file without using items I have this crawler which takes a list of websites (input: txt file) and returns json files with the name of each websites and append data to the file.
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.crawler import CrawlerProcess
from scrapy import Request
from urllib.parse import urlparse
import tldextract
import json
import os

class LkSpider(CrawlSpider):
    name = 'multi_spider'

    # read csv with just url per line
    with open('sample.txt') as file:
        start_urls = [line.strip() for line in file]
        allowed_domains = ["".join(urlparse(x).netloc.split("/")[-1]) for x in start_urls]

    rules = (
    Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

    def parse_item(self, response):

        # get the domain for the file name
        domain = tldextract.extract(response.request.url)[1]
        path = urlparse(response.request.url)[2].replace("/", "")

        filename = response.url + '.json'
        data = {
        'domain':domain,
        'path':path,

        }
        with open(filename, 'a',encoding='UTF-8') as f:
            json.dump(data, f, ensure_ascii=False, incident=4)

# main driver
if __name__ == "_main_":
    process = CrawlerProcess()
    process.crawl(LkSpider)
    process.start()

My issue my json returns for one websites 'example.json':
 {"url":"https://example.com","path":"/product"}{"url":"https://example.com","path":"/product"}
and I'd like the same file in this format json, without using items from scrapy :
[ {"url":"https://example.com","path":"/product"},{"url":"https://example.com","path":"/product"}]


text:
Q: Apache2 + mod_fcgid + php stopped working after upgrade from Debian squeeze to wheezy I've updated my server from Debian squeeze to Debian wheezy. On this server are several apache2 vhost which running php via mod_fcgid (I'm also using mod_suexec but this shouldn't be the problem). After the update all my php-sites are not working anymore, apache2 delivers php Source-Code if I request a site running php. All my log files

*

*apache2/error.log

*apache2/access.log

*apache2/suexec.log

*and the vhosts error/access logs

didn't come up with any errors, not even warnings. All neccesarry modules are installed and loaded. I searched for a possible solution for hours now, without any effort. Here is a sample vhost file ("sensitive" data is replaced, user/group and domain):
<VirtualHost *:80>
    ServerName example.com
    SuexecUserGroup john-doe john-doe
    AddHandler fcgid-script .php
    DocumentRoot "/var/www/example.com/data"
    DirectoryIndex index.php index.html

    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory "/var/www/example.com/data">
        Options Indexes MultiViews FollowSymLinks +ExecCGI
        FCGIWrapper /var/www/example.com/php-fcgi/php-fcgi-starter .php
        Order allow,deny
        allow from all
        AllowOverride All
    </Directory>
    ErrorLog /var/www/example.com/logs/error.log
    LogLevel warn
    CustomLog /var/www/example.com/logs/access.log combined
    ServerSignature Off
</VirtualHost>

Any ideas anyone? I asked this question on serverfault.com too, hope this is alright.

A: Now I stumbled upon the solution by myself. The problem is caused by an update of mod_fcgid which changed the directives used in the vhost configs. The changes could be seen here (this is what I stumbled upon).
The directive
FCGIWrapper /var/www/example.com/php-fcgi/php-fcgi-starter .php

has to be changed to
FcgidWrapper /var/www/example.com/php-fcgi/php-fcgi-starter .php

The documentation says

"All directives have been renamed in order to use a common prefix "Fcgid". Underscores in directive names have been eliminated in favor of CamelCase. The old directive names will still work but are deprecated. To fix your configuration you can use the sed script build/fixconf.sed."

but it seems like the old directive names didn't work anymore for now. The changes have done the trick for me, maybe this will help someone else.


text:
Q: Android - Give toolbar to each fragment I want to create 3 fragment like below images:
Fragment with toolbar&statusbar
Transparent toolbar&statusbar
Transparent toolbar not statusbar
The layout of fragment is below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fragment_root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorYellow"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:elevation="4dp"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"/>

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar"
        android:id="@+id/fragment_container_layout">
    </FrameLayout>

</RelativeLayout>

My themes are below:
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    <style name="MyTranparentTheme" parent="AppTheme">
        <item name="windowActionBarOverlay">true</item>
        <item name="android:windowTranslucentStatus">true</item>
    </style> </resources>

I set theme of application in AndroidManifest.xml:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

Fragment constructor signature is here:
new BlankFragment(isTranslucentHeaderbar, isTranslucentStatusbar)

How can I create these fragments?
I create non-translucent toolbar&statusbar is here:

But I couldn't create fragment with translucent toolbar. My onCreateView code is below:
View view = inflater.inflate(R.layout.fragment_sensor_light, container, false);

Toolbar toolbar = view.findViewById(R.id.toolbar);

toolbar.setTitle("Fragment toolbar");
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getContext(), R.color.translucentColor)));
return view;

If I set theme as MyTransparentTheme in manifest file, ss is below:


text:
Q: How to unlink a framework on program start I am developing for iPhone OS 3.1.3 and I need to use Dropbox API.
The problem is the Dropbox API requires at least iOS 4.2. Ok.
I decided to save the possibility of using the program under 3.1.3, but if it is 4.2 and higher, there will be Dropbox functionality.
To use Dropbox framework I needed to link another frameworks:

*

*Security.framework

*QuartzCore.framework

I have done this.
When I link Dropbox.framework to my project, the program works great on iPhone Simulator, but it cannot be started on my iPhone 3.1.3. There is an error in Output:

dyld: Symbol not found: _kSecAttrAccessible
  Referenced from: /var/mobile/Applications/C1FC10E5-0A36-4DEB-BD27-5028C205C89D/Bus Time.app/Bus Time
  Expected in: /System/Library/Frameworks/Security.framework/Security
 in /var/mobile/Applications/C1FC10E5-0A36-4DEB-BD27-5028C205C89D/Bus Time.app/Bus Time

So the question is:
Can I detect the iOS version on the program start and unlink the framework?
Or could you offer an another way to use dropbox for 3.1.3?
Thank you for your answers. I appreciate it.

A: *

*Select the Security framework in your file list.

*Expand the right sidebar (View > Utilities > Show Utilities).

*Under 'Target Membership' change 'Required' to 'Optional.'

A: You cannot programmatically unlink a framework at runtime.
You can programmatically link a framework at runtime, e.g. by using the NSBundle APIs, or dlopen, or various other ways. If you do so, you have to then manually load the ObjC objects and/or C symbols you want.
Alternatively, you can weak-link the framework, which makes the runtime do most of the work for you. If it's there, it will be loaded in at startup, and all of its ObjC objects and C symbols will be available to you. Otherwise, all of its ObjC objects and C symbols will be null. So, all you have to do is check for null to decide whether to run the code that needs that framework.


text:
Q: Expressing a Non Negative Integer as Sums of Two Squares I'm writing a code in C that returns the number of times a non negative integer can be expressed as sums of perfect squares of two non negative integers.
R(n) is the number of couples (x,y) such that x² + y² = n where x, y, n are all
non negative integers.

How can I mathematically compute R(n)?
What is a very fast algorithm I can use to compute R(n)?

A: Let $n$ have the prime power factorization
$$n=2^e p_1^{a_1}\cdots p_k^{a_k}q_1^{b_1}\cdots q_l^{b_l},$$
where the $p_i$ are distinct primes of the form $4t+1$, and the $q_i$ are distinct primes of the form $4t+3$.
If one or more of the $b_i$ is odd, then $n$ has no representations as a sum of two squares. If all the $b_i$ are even, then the number $N(n)$ of representations is given by
$$N(n)=4(a_1+1)(a_2+1)\cdots (a_k+1).$$
However, this counts all representations, including the ones that use negative integers. It also considers $0^2+5^2$ as different from $5^2+0^2$.
If we don't want negatives, and order doesn't matter, things are more complicated. If $8$ divides $N(n)$, then the number of essentially distinct representations is equal to
$$\frac{N(n)}{8}.$$
If $N(n)$ is not divisible by $8$, it is of the form $4q+4$. Then the number of representations is
$$\frac{N(n)+4}{8}.$$
Remark: Let $D_1$ be the number of positive divisors of $n$ of the form $4t+1$, and $D_3$ the number of positive divisors of $n$ of the form $4t+3$. It is a nice result of Jacobi that
$$N(n)=4(D_1-D_3).$$
Unfortunately, I do not see how this can be used to give a more efficient algorithm for computing $N(n)$.

A: This was getting a bit long for a comment, but I wanted to add an alternate perspective that is more computationally oriented.
If you are dealing with just 16-bit integers, a lookup table will be quite fast, occupying at most 64KB of storage (which fits into contemporary caches) and constructible in linear time by just iterating over all pairs $0 \le x \le y \le 256$.
1ms is a fairly tight bar for a computation.  How much slower your runs getting?  Consider that memory allocation/deallocation can have an impact at this timescale.
For 100 numbers in 1ms you could probably budget less than 10000 operations for each input.  If you are searching primes all the way to 2^16, that already is too slow: make sure to only sieve out primes up to $\sqrt{n}$, which only needs about 50 primes.
Finally, one can speed up the average-case time by avoiding factoring in cases where it is obvious that $R(n)=0$.  Half the time, $n$ will be equal to a power of $2$ times a number that is $3 \pmod 4$, which forces $R(n)=0$.  Adding this very inexpensive test (which could be implemented with bit operations) could give you twice the overall speed if your inputs are random.  One can likewise detect the presence of an odd $b_i$ (defined as in André Nicolas's answer) while factoring and cut the loop short.


text:
Q: nextjs production error 500 when a middlware is used I'm building a profile page for users of my app (nextjs 12) and when I add authentication middleware it works fine locally but when deployed to the production server (apache shared hosting with nodejs v 14 installed) it throws error 500
my node version installed locally is v16.16.0 could that affect this issue?
any suggestions?
profile.tsx:

const ProfileEditor = () => {
  const dispatch = useDispatch();
  const {
    profile,
    profileLogin,
    user
  } = useSelector((state: RootState) => state.Auth);

  useEffect(() => {
    dispatch(FetchProfileAsync());
  }, []);

  const [preview, setPreview] = useState < string > ();

  const handleFormSubmit = async(values: any, e: any) => {
    dispatch(UpdateProfileAsync(values as any));
  };

  let initialValues = {
    image: profile ? .image ? .full_path,
    first_name: profile ? .first_name,
    last_name: profile ? .last_name,
    email: profile ? .email,
    phone: profile ? .phone,
  };

  const FILE_SIZE = 160 * 1024;
  const SUPPORTED_FORMATS = ['image/jpg', 'image/png'];

  const checkoutSchema = yup.object().shape({
    image: yup.mixed().required('A file is required'),
    //  .test('fileSize', 'File too large', (value) => value && value.size <= FILE_SIZE)
    //  .test('fileFormat', 'Unsupported Format', (value) => value && SUPPORTED_FORMATS.includes(value.type)),
    first_name: yup.string().required('required'),
    last_name: yup.string().required('required'),
    email: yup.string().email('invalid email').required('required'),
    phone: yup.string().required('required'),
  });

  return ( <
    CustomerDashboardLayout >
    <
    DashboardPageHeader icon = {
      Person
    }
    title = 'Edit Profile'
    navigation = { < CustomerDashboardNavigation / >
    }
    />

    <
    Card1 >
    <
    Formik enableReinitialize initialValues = {
      initialValues
    }
    validationSchema = {
      checkoutSchema
    }
    onSubmit = {
      (values: any, e: any) => handleFormSubmit(values, e)
    } >
    {
      ({
        values,
        errors,
        touched,
        handleChange,
        handleBlur,
        handleSubmit,
        setFieldValue
      }) => ( <
        form onSubmit = {
          handleSubmit
        } >
        <
        FlexBox alignItems = 'flex-end'
        mb = {
          3
        } >
        <
        Avatar src = {
          preview ? ? user ? .image ? .full_path
        }
        sx = {
          {
            height: 64,
            width: 64
          }
        }
        alt = 'user image' / >

        { /* <img src={user?.image?.full_path} height={100} width={100} alt='fdss' /> */ }

        <
        Box ml = {-2.5
        } >
        <
        label htmlFor = 'profile-image' >
        <
        Button component = 'span'
        color = 'secondary'
        sx = {
          {
            bgcolor: 'grey.300',
            height: 'auto',
            p: '8px',
            borderRadius: '50%',
          }
        } >
        <
        CameraEnhance fontSize = 'small' / >
        <
        /Button> <
        /label> <
        /Box> <
        Box display = 'none' >
        <
        input name = 'image'
        onChange = {
          (newFile: any) => {
            setFieldValue('image', newFile.currentTarget.files[0]);
            FileToBase64(newFile.currentTarget.files[0] as any).then((res) => setPreview(res));
          }
        }
        id = 'profile-image'
        accept = 'image/*'
        type = 'file' /
        >
        <
        /Box> <
        /FlexBox>

        <
        Box mb = {
          4
        } >
        <
        Grid container spacing = {
          3
        } >
        <
        Grid item md = {
          6
        }
        xs = {
          12
        } >
        <
        ETextField mb = {
          1.5
        }
        name = 'first_name'
        label = 'First Name'
        placeholder = 'First Name'
        variant = 'outlined'
        size = 'small'
        fullWidth onBlur = {
          handleBlur
        }
        onChange = {
          handleChange
        }
        value = {
          values.first_name || ''
        }
        error = {!!touched.first_name && !!errors.first_name
        }
        helperText = {
          touched.first_name && errors.first_name
        }
        /> <
        /Grid> <
        Grid item md = {
          6
        }
        xs = {
          12
        } >
        <
        ETextField mb = {
          1.5
        }
        name = 'last_name'
        label = 'Last Name'
        placeholder = 'Last Name'
        variant = 'outlined'
        size = 'small'
        fullWidth onBlur = {
          handleBlur
        }
        onChange = {
          handleChange
        }
        value = {
          values.last_name || ''
        }
        error = {!!touched.last_name && !!errors.last_name
        }
        helperText = {
          touched.last_name && errors.last_name
        }
        /> <
        /Grid> <
        Grid item md = {
          6
        }
        xs = {
          12
        } >
        <
        ETextField mb = {
          1.5
        }
        name = 'email'
        label = 'Email'
        placeholder = 'exmple@mail.com'
        variant = 'outlined'
        size = 'small'
        type = 'email'
        fullWidth onBlur = {
          handleBlur
        }
        onChange = {
          handleChange
        }
        value = {
          values.email || ''
        }
        error = {!!touched.email && !!errors.email
        }
        helperText = {
          touched.email && errors.email
        }
        /> <
        /Grid> <
        Grid item md = {
          6
        }
        xs = {
          12
        } >
        <
        ETextField mb = {
          1.5
        }
        name = 'phone'
        label = 'Phone'
        placeholder = '09********'
        variant = 'outlined'
        size = 'small'
        fullWidth onBlur = {
          handleBlur
        }
        onChange = {
          handleChange
        }
        value = {
          values.phone || ''
        }
        error = {!!touched.phone && !!errors.phone
        }
        helperText = {
          touched.phone && errors.phone
        }
        /> <
        /Grid> <
        /Grid> <
        /Box>

        <
        ELoadingButton type = 'submit'
        variant = 'contained'
        loading = {
          profileLogin === 'loading'
        }
        buttonText = 'Save Changes'
        loadingPosition = 'start'
        fullWidth = {
          true
        }
        color = 'primary' /
        >
        <
        /form>
      )
    } <
    /Formik> <
    /Card1> <
    /CustomerDashboardLayout>
  );
};

export default ProfileEditor;

middlware.tsx

// eslint-disable-next-line @next/next/no-server-import-in-page
import { NextResponse } from 'next/server';
// eslint-disable-next-line @next/next/no-server-import-in-page
import type { NextRequest } from 'next/server';
import { KEY_TOKEN_COOKIE } from 'src/constants';

const middleware = (request: NextRequest, response: NextResponse) => {
    const token = request?.cookies[KEY_TOKEN_COOKIE];
    if (!token) return NextResponse.rewrite(new URL('/error/auth', request.url));
};

export default middleware;


text:
Q: How to calculate days between two dates in PHP? I need to calculate days between a date I get from the database and the current date.
$upload_date = mysql_query("SELECT Date FROM Setting WHERE ID = $row[ID]");
$current_date = date("Y-m-d");

How do I do it?

A: select datediff(curdate(),'2011-03-01');

A: If you want to do it in PHP, then use the DateTime class:
$current = new DateTime($current_date);
$db_date = new DateTime($upload_date);
$days = $current->diff($db_date)->days;

Or the oldschool way:
$days = round((strtotime($current) - strtotime($db_date)) /24 /60 /60);

A: form http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff
SELECT DATEDIFF( CURDATE(), Date ) FROM ....

and I would not use Date as field name, consider to change this name

A: Use SELECT DATEDIFF('new_date', 'old_date');
mysql> SELECT DATEDIFF('2006-04-01','2006-04-01');
+-------------------------------------+
| DATEDIFF('2006-04-01','2006-04-01') |
+-------------------------------------+
|                                   0 |
+-------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATEDIFF('2006-04-01','2007-04-01');
+-------------------------------------+
| DATEDIFF('2006-04-01','2007-04-01') |
+-------------------------------------+
|                                -365 |
+-------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATEDIFF('2006-04-01','2005-04-01');
+-------------------------------------+
| DATEDIFF('2006-04-01','2005-04-01') |
+-------------------------------------+
|                                 365 |
+-------------------------------------+
1 row in set (0.00 sec)

DATEDIFF(expr,expr2)
DATEDIFF() returns the number of days between the start date
expr and the end date expr2. expr and expr2 are date or
date-and-time expressions. Only the date parts of the values
are used in the calculation.
mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30');
    -> 1
mysql> SELECT DATEDIFF('1997-11-30 23:59:59','1997-12-31');
    -> -31

A: You can use this format http://php.net/manual/en/function.date.php and it will do it for you

A: you can do this in a simple way as below,
$current_date = date("Y-m-d");          // Current date
$db_date = date("Y-m-d");               // Date from your database
$diff = abs(strtotime($current_date) - strtotime($db_date));
$total_days = floor ($diff /  (60*60*24));


text:
Q: Web scraping HTML table with certain text in Python I am trying to web scrape a HTML table using python. There are many tables in the HTML page, but i want to scrape a certain table only. I am using beautiful soup to do this web scraping.
My code looks like this:
page = get("http://uobgoldprice.com/history/2018/September/10/")
html = BeautifulSoup(page.content, 'html.parser')

for p in html.select('tr'):
    if p.text == "ARGOR CAST BAR":
        print (p.text)

I would like only the table that reads "Rate as at Monday, 10 September 2018".
How do I go about doing that?

A: You need to find the elements that contains the text and the parent that is a table:
import re
import requests
from bs4 import BeautifulSoup

page = requests.get("http://uobgoldprice.com/history/2018/September/10/")
html = BeautifulSoup(page.content, 'html.parser')

element = html.find(text=re.compile('Rate as at Monday, 10 September 2018'))
print(element.findParent('table'))

A: from collections import defaultdict

import requests
from bs4 import BeautifulSoup

def get_page_html(url):
    r = requests.get(url)
    r.raise_for_status()
    return r.text

def parse_last_table(html):
    prev_key = None
    result = defaultdict(list)
    soup = BeautifulSoup(html, 'lxml')

    last_table = soup.find_all('table')[-1]
    for row in last_table.find_all('tr')[2:]:
        try:
            description, currency, unit, bank_sells, bank_buys = (
                col.text.strip() for col in row.find_all('td')
            )
        except ValueError:
            continue  # blank/empty row

        description = description or prev_key
        result[description].append({
            'currency': currency,
            'unit': unit,
            'bank_sells': bank_sells,
            'bank_buys': bank_buys
        })
        prev_key = description
    return result

Output:
>>> url = 'http://uobgoldprice.com/history/2018/September/10/'
>>> page_html = get_page_html(url)
>>> result = parse_last_table(page_html)
>>> import json; print(json.dumps(result, indent=2))
{
  "ARGOR CAST BAR": [
    {
      "currency": "SGD",
      "unit": "100 GM",
      "bank_sells": "5,369.00 (+4.00)",
      "bank_buys": "5,291.00 (+3.00)"
    }
  ],
  "CAST BARS": [
    {
      "currency": "SGD",
      "unit": "1 KILOBAR",
      "bank_sells": "53,201.00 (+36.00)",
      "bank_buys": "52,933.00 (+36.00)"
    }
  ],
  "GOLD CERTIFICATE": [
    {
      "currency": "SGD",
      "unit": "1 KILOCERT",
      "bank_sells": "53,201.00 (+36.00)",
      "bank_buys": "52,933.00 (+36.00)"
    }
  ],
  "GOLD SAVINGS A/C": [
    {
      "currency": "SGD",
      "unit": "1 GM",
      "bank_sells": "53.20 (+0.04)",
      "bank_buys": "52.94 (+0.04)"
    }
  ],
  "GOLD BULLION COINS": [
    {
      "currency": "SGD",
      "unit": "1/20 OZ(GNC,SLC &GML)",
      "bank_sells": "131.00",
      "bank_buys": "81.00"
    },
    {
      "currency": "SGD",
      "unit": "1/10 OZ",
      "bank_sells": "211.00 (+1.00)",
      "bank_buys": "163.00"
    },
    {
      "currency": "SGD",
      "unit": "1/4 OZ",
      "bank_sells": "465.00",
      "bank_buys": "410.00"
    },
    {
      "currency": "SGD",
      "unit": "1/2 OZ",
      "bank_sells": "904.00 (+1.00)",
      "bank_buys": "822.00 (+1.00)"
    },
    {
      "currency": "SGD",
      "unit": "1 OZ",
      "bank_sells": "1,726.00 (+1.00)",
      "bank_buys": "1,645.00 (+1.00)"
    }
  ],
  "PAMP GOLD BARS": [
    {
      "currency": "SGD",
      "unit": "1/2 OZ",
      "bank_sells": "876.00",
      "bank_buys": "821.00 (+1.00)"
    },
    {
      "currency": "SGD",
      "unit": "1 GM",
      "bank_sells": "82.00",
      "bank_buys": "50.00"
    },
    {
      "currency": "SGD",
      "unit": "1 OZ",
      "bank_sells": "1,711.00 (+1.00)",
      "bank_buys": "1,644.00 (+1.00)"
    },
    {
      "currency": "SGD",
      "unit": "2.5 GM",
      "bank_sells": "182.00",
      "bank_buys": "130.00"
    },
    {
      "currency": "SGD",
      "unit": "5 GM",
      "bank_sells": "322.00",
      "bank_buys": "262.00"
    },
    {
      "currency": "SGD",
      "unit": "10 GM",
      "bank_sells": "597.00 (+1.00)",
      "bank_buys": "527.00 (+1.00)"
    },
    {
      "currency": "SGD",
      "unit": "20 GM",
      "bank_sells": "1,132.00 (+1.00)",
      "bank_buys": "1,056.00 (+1.00)"
    },
    {
      "currency": "SGD",
      "unit": "50 GM",
      "bank_sells": "2,746.00 (+2.00)",
      "bank_buys": "2,644.00 (+2.00)"
    },
    {
      "currency": "SGD",
      "unit": "100 GM",
      "bank_sells": "5,414.00 (+3.00)",
      "bank_buys": "5,291.00 (+3.00)"
    }
  ],
  "SILVER PASSBOOK ACCOUNT": [
    {
      "currency": "SGD",
      "unit": "1 OZ",
      "bank_sells": "19.86 (+0.09)",
      "bank_buys": "19.30 (+0.09)"
    }
  ]
}

A: I believe this code will help you.
If you want complete running project visit html to pdf Web scraping
import logging
import math
import json
from flask import jsonify, abort, make_response
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import pydf

from constants import Constants
from response import Response

class SeleniumCrawler(object):

    def get_page(self, url):
        response = Response()
        try:

            # Initilized the chrome driver
            print("Initilized the chrome driver")
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument('--window-size=1420,1080')
            chrome_options.add_argument('--headless')
            chrome_options.add_argument('--disable-gpu')
            browser = webdriver.Chrome(chrome_options=chrome_options)

            # browser url
            browser.get(url)
            delay = 10000

            # wait till specific classes appears
            print("wait till specific classes appears")
            WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.CLASS_NAME, 'kbn-table')))
            body = browser.find_element_by_class_name("kbn-table").get_attribute('innerHTML')

            # calculate number of pages exists and loop them
            print("calculate number of pages exists and loop them")
            pages = (str(browser.find_element_by_class_name("kuiToolBarText").text).split(" ")[2]).replace(",","")
            pages = math.ceil(int(pages) / 50) - 1

            print("pages found {}".format(pages))
            for page in range(1, pages):

browser.execute_script("document.getElementsByClassName('kuiButton')[1].click()")
               chunk = browser.find_element_by_class_name("kbn-table").get_attribute('innerHTML').replace("<tbody>", "")
               body += chunk`enter code here`

            # apply table tags and generate pdf
            print("apply table tags and generate pdf")
            pdf = pydf.generate_pdf("<table>" + body + "</table>")
            with open('out.pdf', 'wb') as f:
                f.write(pdf)

            return json.loads(json.dumps((response.get_response(Constants.SUCCESS, Constants.SUCCESS))))
        except Exception as e:
            logging.exception(e)

            return abort(make_response(jsonify(response.get_response(Constants.SERVER_ERROR, Constants.SERVER_ERROR)), response.get_code(Constants.SERVER_ERROR)))


text:
Q: How to assign domain name to a machine inside LAN with dynamic IP on gateway? I'm stuck for a while on this question : I got several raspberry pis on my LAN, all with DHCP IP addresses served by MAC address resolution.
I use them over several protocols : SSH, TCP.
My ISP provide dynamic address, but I have a dynamic DNS system allowing me to resolve home.mydomain.com to the router without problem. I got full access to my DNS zone.
How to make mi raspberrys fully accessible by domain names (i.e module1.home.devgiants.fr) over internet, without having to set NAT for all protocols ? I read stuff around dnsmasq but all of them talked about local resolution. How can I have both internet and local resolution? I got an openWRT router on my LAN, so it would play local DNS server role if needed.

A: If the hints you have provided in your question are anything to go by, you can't do this "for the general Internet" - The assumption here is that you only have a single "real world" IP address - as implied by your advice that you have a dynamic IP address and the naming implying a home network connection.
You can, however, get this working for yourself or a select group of people.
At issue - it would appear to be confusing 2 totally separate systems - NAT - which allows you to share a single IP address between multiple devices and DNS, which, among other things, allows you to translate a host name to an IP address (but has nothing to do with NAT).
So long as you have a single IP address, you can't directly expose all of your devices to the wider Internet using a router without using NAT to map services on each device to a different port.
You can partially solve your problem by setting up an OpenVPN server on your router (or equivalent).    The remote systems will need VPN clients which connect to your VPN server.  If you are using OpenVPN the server needs to either be configured as a TAP device or as a TUN device which injects a route for your LAN (the latter gives you better control)
You can easily then handle the DNS by simply adding the internal IP addresses of each PI to the zone file for devgiants.com (no need to mess arround with dnsmasq) -  Even though the record you are pointing to is an internal/non-routed IP address, the DNS server does not care and will provide an answer anyway.   Because you have a VPN, your server will be able to find the internal IP address.


text:
Q: Bootstrap select searchable select within another dropdown Please see this fiddle. If you put the bootstrap select library inside another dropdown it doesn't display the select contents.
https://jsfiddle.net/75cndb4a/1/
Click link above.

Is there some css or js I can add that will make it display within a dropdown?

A: Html structure is changed and updated in the below fiddle.
Check thisUpdate Fiddle


text:
Q: Nginx no reconoce a php 7 He instalado Nginx, MySQL y PHP 7, pero cuando hago la prueba de phpinfo() solo me descarga el archivo y no lo despliega en el navegador, seguí los pasos de instalación de este link: https://www.digitalocean.com/community/tutorials/como-instalar-linux-nginx-mysql-php-lemp-stack-in-ubuntu-16-04-es
No se cual pueda ser el error.


text:
Q: Does the Realta Nua PC Releases still have the route branch in the Fate Route i know that the Realta Nua PC version was released as 3 games and there is now a patch for all 3 (i'm waiting abit before i get it just to allow the bugs to get ironed out) however one thing got to me,
in the Original PC version you had to complete the Fate Route in order to trigger the flag at the end to allow for the possibility of accessing the Unlimited Blade Works Route (which doesn't lead to Shirou creating a Geis with Rin and thus a Dead End) and it was the same with Heaven's Feel, you needed to trigger a flag from completing one Unlimited Blade Works Route in order to access an option to gain an extra affection point with Sakura in order to access the Heaven's Feel Route (all of this is based off Mirror Moon's Flowchart provided with the patch install), and ofcause -Last Episode- was only ever unlocked unless all 5 endings had been seen (needed a separate patch to add it though)
however, from what i have seen, all 3 routes are separate games with separate .exe files, so i am wondering, does the Realta Nua PC Releases still have the route branch in the Fate Route

A: Each game is each route with all possible bad ending self contained, this means rather than having to play Fate and Unlimited Blade Works before playing Heaven's Feel one can just play Heaven's Feel without ever seeing Fate's ending.
Since they are self contained, Rin's Prologue of the first 3 days before Archer is attacked by Saber after they chase Lancer to the Emiya Compound and the portion of the Fate Route which is common to all 3 is included, also the Unlimited Blade Works Bad End one can obtain in Fate before getting it's completion Flag is also included in Fate.
However, -Last Episode- and the Tiger Dojo Completion Ceremony requires all 3 games and it seems data is shared between them, a sneaky tactic by TYPE-MOON to get people to buy all 3 (Tiger Dojo Completion Ceremony is one thing but -Last Episode- is like the proper conclusion to Fate)

A: Yes, they still have the route branch but they change some scenes and improve the quality of CGs... Realta Nua also adds the canon epilogue written by Nasu "last episode"
Last episode was written by Nasu as a final epilogue once the game is finished.
"Last episode" can happen in different timelines/routes but it is sure to happen after Fate's true ending. The reason is that it is done as an epilogue for such ending (it actually says epilogue).
Nasu has made epilogues for all 3 true endings. In the original game he did Heaven's Feel true ending epilogue. After some time he did Fate's true ending epilogue "last episode" and recently he's made UBW's true ending epilogue (an 11 page script that was handed to Ufotable in order to make the epilogue episode). All 3 epilogues are sure to happen after each true ending.
"Last episode" can also happen in other timelines though.