Multipule ajax calls in a loop not returning in the same order as called

Question: Bellow is the code that gets a list from the database and then requests more data for each list item and draws a google chart for each item. everthing is working fine apart from the ajax calls for more data are not returning in the same order as the original list. the lists have different counts depending of how they are called but over twenty charts are draw. The database is large and suspect this is the main reason for the ajax request not returning in the same order.
How can I alter my code to stop another ajax call before the previous has returned
function getList(fueltype, Date1) {
    document.getElementById('charts').innerHTML = "";
    var sd = new Date(Date1);
    var y =  sd.getFullYear();
    var m = sd.getMonth();
    var d = sd.getDate();
    var ed = new Date(y,m,d+1,0,0,0,0);
    var startDate = formatDate(sd);
    var fuelsearch = '';
    var dbFile = '';
    var endDate = formatDate(ed);
    switch(fueltype){
      case 'Coal':
        fuelsearch = 'COAL';
        dbFile = 'getJSONdata.php';
        break;
      case 'CCGT':
        fuelsearch = 'CCGT';
        dbFile = 'getJSONdata.php';
        break;
      case 'Nuclear':
        fuelsearch = 'NUCLEAR';
        dbFile = 'getJSONdata.php';
        break;
      case 'OCGT':
        fuelsearch = 'OCGT';
        dbFile = 'getJSONdata.php';
        break;
      case 'Other':
        fuelsearch = 'OTHER';
        dbFile = 'getJSONdata.php';
        break;
      case 'Pump Storage':
        fuelsearch = 'PS';
        dbFile = 'getJSONdataWithMIL.php';
        break;
      case 'Wind':
        fuelsearch = 'WIND';
        dbFile = 'getJSONdata.php';
        break;
      case 'Non Pump Storage Hydro':
        fuelsearch = 'NPSHYD';
        dbFile = 'getJSONdata.php';
        break;
      default:
    }

    $.ajax({
      url:  "getBmuList.php",
      dataType: 'json',
      data: {
        fuel: fuelsearch
      }
    }).done(function (listData) {

      // draw chart for each id
      listData.forEach(function (itemId) {
        //console.log(itemId);
        drawChart(itemId,startDate,endDate,dbFile);
      });

    }).fail(function (jq, text, errMsg) {
      console.log(text + ': ' + errMsg);
    });
 }

 // This function takes a bmu and gets data in JSON format and draws a google chart
function drawChart(itemId,startDate,endDate,dbFile) {
     var bmu = itemId.itemID;
      console.log(bmu);
  $.ajax({
    url: dbFile,
    dataType: 'json',
    data: {
      Id: bmu,
      date1: startDate,
      date2: endDate
      }
  }).done(function (jsonData) {
     console.log(bmu);
    var sd = new Date(startDate);
    var y =  sd.getFullYear();
    var m = sd.getMonth();
    var d = sd.getDate();
    //console.log(sd);
    //console.log(new Date(y,m,d,0,0,0));
    var data = new google.visualization.DataTable(jsonData);
    var options = {
      title: bmu,
      width: 495,
      height: 300,
      series: {
        0: { lineWidth: 1, pointSize: 1.1 },
        1: { lineWidth: 1, pointSize: 1.1},
        2: { lineWidth: 1, pointSize: 1.1},
        3: { lineWidth: 1, pointSize: 1.1}},
      hAxis: {
        textStyle:{fontSize: 10},
        format: 'HH:mm',
        minValue: new Date(y,m,d,0,0,0),
        maxValue: new Date(y,m,d+1,0,0,0),

        viewWindow:{
          min: new Date(y,m,d,0,0,0),
          max: new Date(y,m,d+1,0,0,0)
          },

      },
      vAxis: {
        textStyle:{fontSize: 10},
      },
      chartArea: {backgroundColor: '#fffff0'},
    };

    // create new div for chart
    var div = document.createElement("div");
    div.style.width = "500px";
    div.style.height = "330px";
    div.style.float = "left";
    div.style.border  =  "thin solid #DCDCDC";
    div.id = itemId.itemID + "_div";
    container = document.getElementById('charts').appendChild(div);

    var chart = new google.visualization.ScatterChart(container);
    chart.draw(data, options);
    //google.visualization.events.addListener(chart, 'click', selectHandler);

  }).fail(function (jq, text, errMsg) {
    console.log(text + ': ' + errMsg);
  });

}

Comment: You should take a look at [`Promises`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
Comment: *How can I alter my code to `stop` another ajax call before the previous has returned*, do you mean `start` or `stop`?
Comment: https://developers.google.com/web/fundamentals/primers/promises
Comment: asynchronous calls are not synchronous so if order matters than you need to rethink your approach.
Answer: Ajax is asynchronous by nature so all request are triggered in sequence, but responses are attended as soon as they come back.
jQuery $.ajax() function has an async option you can set to false making it to become synchronous (returning data instead of passing to success callback or throwing instead of calling error one in case of error).
But this option is deprecated and will be removed soon so it is not a good idea to rely on that.
So you need to use some truly async pattern. And, in my opinion, promises are the best (they may be not supported in very old browsers but there are polyfills to support them if you need it.
That being said, your drawChart() function has a not so good pattern in it having that it does not do just what its name says (drawing a chart) but also asynchronously requesting the data so it will be a very good idea to separate those behaviours.

Of course, you could simply make it to return a promise and chain all calls in a waterfall style so each request + drawing starts after previous finished. But if (as I think to understand) none of those requests alter the results of the others (you just are asking for rendering order) the only difference will be that your code will be much more slow than actulally needed.

...so your new drawChart() function will be just the anonymous function you provided as .done() callback in its inner $.ajax() call.
Next step will be to modify .done() callback of the $.ajax() call inside of getList() function this way:
$.ajax({
    ...
}).done(function(listData){
    Promise.all(
       listData.map(function(itemId) {
           return new Promise(function(resolve, reject) {
               // Code removed from your original drawChart() function
               var bmu = itemId.itemID;
               console.log(bmu);
               $.ajax({
                  ...
               })
               .done(resolve)
               .fail(reject);
           });
       })
    )
    .then(function(listDataArr){
        // Here all (concurrent) requests finished.
        // ...and their results are in right order in listDataArr.
        listDataArr.map(drawChart);
    })
    .catch(reject);
}).fail(...);

Hope it helps.
It's not as best as possible approach but I tried to do it as similar as possible to your code to make easier to understand what are minimal required changes.
Edit: On the other hand, I figure out you could to not exactly require render them in order and it could be enought to place them in that order even being rendered in random order.
If that's true, you have another simpler strategy that doesn't require the use of promises at all and, apart of needing less changes to your code, it is sligtly faster and, in my oppinion, provides better user experience:
It consists on simply create and place the containers (synchronously) for each chart before start requesting their data and rendering them.
For example:
var charts = $("#charts");
var containers = listData.map(function(itemId){
    return $("
</div")
        .addClass(itemId+"_div")
        .appendTo(charts);
});
// Rendering process here.

You can use your original implementation with the only difference of addressing divs like below instead of creating new one each time:
var div = $("div."+itemId+".div);

…even, it would be better using containers array (or sligtly rewritting below code to produce an "itemId: container" object). But I leave it to your choice.
Comment: Been working through this but stuggling to get the chart data to the drawChart function from listDataArr.map(drawChart);. I need to get the json data into DataTable of the new function drawChart
Comment: I did'nt tested anything: I just tried to show some guidelines to help you in solving your problem. It could contain errors from myself or maybe you need to fix other issues too. If you continue struggling on that, edit your question to add your updated approach so we could analyze what is happening…
Comment: …on the other hand, casually I just edited my answes adding an "edit" section with a maybe not as polite, but simpler (in the meaning that it requires less changes to your original aproach) and, (in my oppinion) better user experience because it continue rendering things as soon as possible, but in the right position. Maybe you culd be iterested on trying it instead…
Comment: …also, answering your comment, `listDataArr.map(drawChart)` calls `drawChart()` for each *listDataArr* item passing that item as first parameter and it's position in the array as second (even function could not expect it). Remember that in my proposition, `drawChart()` is the unnamed function you pased as `.done()` callback of the `$.axax()` call inside the original `drawChart()` function that just expect single parameter. Also note, if you need to do somthing else, you always can call anothes (even inlina and/or unnamed) function that, lastly, calls `drawChart()` inside it.
Comment: Ah! Ok. I'm glad to know
Answer: Add async: false to your ajax call.
From the jQuery docs like so,
$.ajax({
    url: 'url'
    success: function (result) {
        // Do Stuff
    },
    async: false
});

Please not the the use of async: false is being deprecated. You are going to get some warnings in the browsers. If you don't want these warnings I suggest you re-evaluate your approach.
Also,
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
In your case, it would look like this.
 $.ajax({
url: dbFile,
dataType: 'json',
data: {
    Id: bmu,
    date1: startDate,
    date2: endDate },
async: false
}).done(function (jsonData) {
  // Do Stuff
});

Comment: Why the down vote? I think it's a useful answer to not only OP, but others looking for an answer.
Comment: It's not helpful if downvote and not leave a reason. One upvote for you.
Answer: You can only achieve this by having ajax call one after the other in each other callbacks.
Or
Add async: false property in the ajax call


Call a C++ DLL from C KMDF (Kernel Mode Driver Framework)

Question: I want to call a C++ DLL from a C KMDF, I made this code
C++ Code
dll.h
<code>    extern "C" {
        __declspec(dllexport) void MyFunction();
    }
</code>
dll.cpp
<code>    void MyFunction()
    {
        std::cout << "Hello from MyFunction in C++ MyLibrary.dll" << std::endl;
    }
</code>
c Code
Source.c
<code>#include <ntddk.h>
#include <wdf.h>

#define CALL_DLL CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_WRITE_DATA)

NTSTATUS GetModuleBaseAddress(PUNICODE_STRING ModuleName, PVOID* ModuleBase)
{
    NTSTATUS status = STATUS_SUCCESS;
    PVOID systemModuleInfo = NULL;

    // Query system information to obtain module information
    ULONG systemModuleInfoSize = 0;
    status = ZwQuerySystemInformation(SystemModuleInformation, &systemModuleInfo, systemModuleInfoSize, &systemModuleInfoSize);

    if (status == STATUS_INFO_LENGTH_MISMATCH)
    {
        // Allocate memory for the module information
        systemModuleInfo = ExAllocatePool(NonPagedPool, systemModuleInfoSize);
        if (systemModuleInfo)
        {
            // Retrieve the module information
            status = ZwQuerySystemInformation(SystemModuleInformation, systemModuleInfo, systemModuleInfoSize, &systemModuleInfoSize);
            if (NT_SUCCESS(status))
            {
                // Iterate through the module list
                PSYSTEM_MODULE_INFORMATION moduleInfo = (PSYSTEM_MODULE_INFORMATION)systemModuleInfo;
                ULONG moduleCount = systemModuleInfoSize / sizeof(SYSTEM_MODULE_INFORMATION);

                for (ULONG i = 0; i < moduleCount; i++)
                {
                    UNICODE_STRING moduleName;
                    RtlInitUnicodeString(&moduleName, moduleInfo[i].ImageName);

                    if (RtlEqualUnicodeString(&moduleName, ModuleName, TRUE))
                    {
                        *ModuleBase = moduleInfo[i].Base;
                        status = STATUS_SUCCESS;
                        break;
                    }
                }

                if (NT_SUCCESS(status))
                {
                    // Module found
                    status = STATUS_SUCCESS;
                }
                else
                {
                    // Module not found
                    status = STATUS_NOT_FOUND;
                }
            }

            // Free the allocated memory
            ExFreePool(systemModuleInfo);
        }
        else
        {
            status = STATUS_INSUFFICIENT_RESOURCES;
        }
    }
    else
    {
        status = STATUS_UNSUCCESSFUL;
    }

    return status;
}

NTSTATUS LoadDllAndCallFunction(PUNICODE_STRING DllPath, PUNICODE_STRING ModuleName, PUNICODE_STRING FunctionName)
{
    NTSTATUS status = STATUS_SUCCESS;
    PVOID dllBase = NULL;
    HANDLE fileHandle = NULL;

    // Open the DLL file
    OBJECT_ATTRIBUTES objectAttributes;
    InitializeObjectAttributes(&objectAttributes, DllPath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
    IO_STATUS_BLOCK ioStatus;
    status = ZwCreateFile(&fileHandle, GENERIC_READ, &objectAttributes, &ioStatus, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0);
    if (!NT_SUCCESS(status))
    {
        // Handle the error when opening the file
        return status;
    }

    // Load the DLL
    status = PsLoadImage(DllPath, NULL, NULL, 0, &dllBase);
    if (!NT_SUCCESS(status))
    {
        // Handle the error when loading the DLL
        ZwClose(fileHandle);
        return status;
    }

    // Get the base address of the module
    PVOID moduleBase = NULL;
    status = GetModuleBaseAddress(ModuleName, &moduleBase);
    if (!NT_SUCCESS(status))
    {
        // Handle the error when getting the module base address
        PsUnloadImage(dllBase);
        ZwClose(fileHandle);
        return status;
    }

    // Get the function address
    PVOID functionAddress = NULL;
    status = LdrGetProcedureAddress(moduleBase, FunctionName, 0, &functionAddress);
    if (!NT_SUCCESS(status))
    {
        // Handle the error when getting the function address
        PsUnloadImage(dllBase);
        ZwClose(fileHandle);
        return status;
    }

    // Call the function
    typedef VOID(*FunctionPtr)();
    FunctionPtr function = (FunctionPtr)functionAddress;
    function();

    // Unload the DLL
    status = PsUnloadImage(dllBase);
    if (!NT_SUCCESS(status))
    {
        // Handle the error when unloading the DLL
    }

    ZwClose(fileHandle);

    return status;
}

//VOID DriverUnload(IN PDRIVER_OBJECT DriverObject)
//{
//    UNREFERENCED_PARAMETER(DriverObject);
//    // Unload any resources
//}

void initDevice()
{
    KdPrint(("KMD - The DEVICE must be INIT \r\n"));
    //UNREFERENCED_PARAMETER(RegistryPath);

    //DriverObject->DriverUnload = DriverUnload;

    UNICODE_STRING dllPath;
    RtlInitUnicodeString(&dllPath, L"C:\\path\\MyLibrary.dll");  // Path to the user DLL

    UNICODE_STRING moduleName;
    RtlInitUnicodeString(&moduleName, L"MyLibrary.dll"); // Name of the module to load

    UNICODE_STRING functionName;
    RtlInitUnicodeString(&functionName, L"MyFunction"); // Name of the function to call

    NTSTATUS status = LoadDllAndCallFunction(&dllPath, &moduleName, &functionName);
    if (!NT_SUCCESS(status))
    {
        // Handle the error
        return;
    }

    return STATUS_SUCCESS;
}

NTSTATUS DispatchDevCTL(PDEVICE_OBJECT DeviceObject_local, PIRP Irp)
{
    UNREFERENCED_PARAMETER(DeviceObject_local);

    PIO_STACK_LOCATION irpsp = IoGetCurrentIrpStackLocation(Irp);
    NTSTATUS status = STATUS_SUCCESS;
    ULONG returnLength = 0;
    PVOID buffer = Irp->AssociatedIrp.SystemBuffer;
    ULONG inLength = irpsp->Parameters.DeviceIoControl.InputBufferLength;
    ULONG outLength = irpsp->Parameters.DeviceIoControl.OutputBufferLength;
    WCHAR* demo = L"Sample returned from driver";

    HANDLE threadHandle;

    UNREFERENCED_PARAMETER(outLength);
    UNREFERENCED_PARAMETER(inLength);

    switch (irpsp->Parameters.DeviceIoControl.IoControlCode)
    {
    case CALL_DLL:
         status = PsCreateSystemThread(&threadHandle, THREAD_ALL_ACCESS, NULL, NULL, NULL, initDevice, NULL);
        if (!NT_SUCCESS(status))
        {
            // Handle the error
            return status;
        }

        // Close the thread handle
        ZwClose(threadHandle);

        // Complete the IRP
        Irp->IoStatus.Information = 0;
        Irp->IoStatus.Status = status;
        IoCompleteRequest(Irp, IO_NO_INCREMENT);
        break;
    default:
        status = STATUS_INVALID_PARAMETER;
        break;
    }

    Irp->IoStatus.Status = status;
    Irp->IoStatus.Information = returnLength;
    IoCompleteRequest(Irp, IO_NO_INCREMENT);

    return status;
}

NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{
    NTSTATUS status;
    int i;

    //The UNREFERENCED_PARAMETER is used to indicate to the compiler that the parameter is not being used intentionality in the code and skip the warning (C4100)

    UNREFERENCED_PARAMETER(DriverObject);
    UNREFERENCED_PARAMETER(RegistryPath);

    //KdPrint(("Hello World \r\n"));

    DriverObject->DriverUnload = Unload;

    status = IoCreateDevice(DriverObject, 0, &DeviceName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &DeviceObject);

    if (!NT_SUCCESS(status))
    {
        KdPrint(("KMD - Creating device failed \r\n"));
        return status;
    }

    status = IoCreateSymbolicLink(&SymLinkName, &DeviceName);

    if (!NT_SUCCESS(status))
    {
        KdPrint(("KMD - Creating symbolic link failed \r\n"));

        IoDeleteDevice(DeviceObject);

        return status;
    }

    for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++)
    {
        DriverObject->MajorFunction[i] = DispatchPassThru;
    }

    DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchDevCTL;
    //DriverObject->MajorFunction[IRP_MJ_WRITE] = DispatchCustom1;

    KdPrint(("KMD - Driver Loaded \r\n"));

    return status;
}
</code>
I'm using VS2019, with this Project configuration

When I build the project, those errors are shown:

'ZwQuerySystemInformation' undefined; assuming extern returning int
'PsLoadImage' undefined; assuming extern returning int
'PsUnloadImage' undefined; assuming extern returning int
'LdrGetProcedureAddress' undefined; assuming extern returning int

What am I making wrong? or exist another way to call a DLL from a Driver?
Answer: this error seems to mean you are missing an include file.
'ZwQuerySystemInformation' undefined; assuming extern returning int
i suggest you find the *.h file that has that name in it and include it.
the same suggestion applies to the other errors.


Integrating $\int_0^1 \frac{1}{\sqrt{1-y^4}}dy$

Question: What do I need to manipulate to show that
$$\int_0^1 \frac{1}{\sqrt{1-y^4}}dy=\frac 1  4 \int_0^1 t^{-3/4}(1-t)^{-1/2}dt$$
Comment: you are missing some constant... Just make a substitution $t=y^4$
Comment: @leshik sorry, thanks, i missed $1/4$
Answer: Put $t=y^4.$ What then is $dt$ in terms of $y$ and $dy$? Solve that equation for $dy$ and substitute $y=t^{1/4}$ to finish.
Why did I make that choice? Well, $$\frac1{\sqrt{1-y^4}}=(1-y^4)^{-1/2},$$ so it was a fair guess that that substitution might work, and it did.
Comment: Glad we don't have to compute that integral....
Comment: That integral's just $$\frac14B\left(\frac14\;,\;\frac12\right)\;,\;B=\text{the Beta function}$$


"TypeError: expected string or bytes-like object" while reading csv file in python with nltk

Question: I'm doing pre-processing on this csv file but it didn't proceed - I got an error of "TypeError: expected string or bytes-like object":

import pandas as pd
import numpy as np
import string
import nltk

dataset =pd.read_csv('blogtext.csv')

seq=dataset.iloc[:,6]

the output would be a 7 column ofblogtext.csv file but I'm getting an error.
Comment: post a snapshot of the csv you are trying to read
Comment: kindly check it in description.
Answer: The "pandas.DataFrame.iloc" is Purely integer-location based indexing for selection by position, .iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array.
For example ,
import pandas as pd

mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
{'a': 100, 'b': 200, 'c': 300, 'd': 400},
{'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]

df = pd.DataFrame(mydict)

print(df.iloc[0])

'''
Output:
a    1
b    2
c    3
d    4
'''

df.iloc[[0]]

'''
Output
   a  b  c  d
0  1  2  3  4
'''

df.iloc[[0, 1]]

'''
Output
     a    b    c    d
0    1    2    3    4
1  100  200  300  400
'''

df.iloc[:3]

'''
Output
      a     b     c     d
0     1     2     3     4
1   100   200   300   400
2  1000  2000  3000  4000
'''

Answer: I guess you have float values in your dataset.
You need to convert these float values to string values.


How can I automate my crop harvest?

Question: Is there any easier way to collect the fruit of my settlement crops without individually collecting the food myself? For instance, the extra purified water goes straight to the workshop.
Comment: Personally I wish I could just set up a plot of land for a type of crop and let the settlers deal with planting as well. That way we could also have irrigation and fertilizer playing a part as well
Comment: I'm not 100% sure, but I believe that crop harvest is already automated. Every time I return to Sanctuary, I can cook lots of Vegetable Starch, even though I'm pretty sure I only found at best 1 or 2 Tato and Corn each.
Comment: @Nolonar Were you actually out of the vegetables when you left last time? Perhaps you're running out of water, and can then make more when you come back due to more water.
Comment: @DCShannon. Yes, I'm usually out of Corn or Tato, since my farms mostly grow Mutfruits (of which I have over 100 by now). I have plenty of Purified Water too. Whenever I return to Sanctuary, I have about 10 or so Corn and Tato. It's possible that my crop only lands in my workshop inventory because I have a Scavenger Station, though.
Comment: @Nolonar That's interesting. That doesn't jive with my experiences. I guess it needs more testing.
Comment: From what I understand, the food that is automatically generated goes first to the settlers, then if there's any remaining it'll get deposited in the workshop.  What you need to do is A) have a balance of all the craftable foods growing in all settlements, B) harvest it manually (In my experience they regrow every time you fast travel), or C) do both.
Answer: Summary
There is some automatic harvesting, but it's inconsistent and less efficient than doing it manually.
Some crops, including Corn and Mutfruit, will be automatically collected and placed in your workshop. However, you can collect more crops from a single manual harvest of your plants than will show up in your workbench, and some crops, such as Tato, don't seem to be collected automatically.
It seems that you can do both, though. Going forward, lacking more tests, I will be keeping extra crops on a follower, and pulling any extra crops out of my workshop, in addition to manually harvesting.

Notes on Tests
I think my tests may have been messed up by supply lines, and the fact that other settlements were relying on my test farm for food. A better, future test would be with one settlement not connected to others. If anyone conducts such a test before I get to it, please let me know.
I had about a dozen each of Tato, Mutfruit, and Corn planted in Sanctuary, near the default cooking station position. I completely cleared my workshop of any crops of any type, then slept for one hour at a time, checking the workshop after each hour, for three days. I found no plants in the workshop.
I then left town and came back the next day. I found four each of corn and mutfruit in my workshop, and zero tatos. Four is a lot less than a dozen. Other times I came back I found more or less, but never as many as there were crops planted. The fluctuating amount could have been impacted by fluctuating food needs in my other settlements.
It didn't seem to matter whether I had picked the crops myself recently or not, but once again I'm concerned that my supply lines may have been contaminating my test results.
If the supply lines are responsible for crops showing up or not, I'm surprised that it was my tatos that weren't being picked, as most of the other settlements have tatos planted. Maybe the tatos in their workshops were interfering, counting as crops in the workshop?
Clearly, more, better tests are needed to figure out all the parameters, but I've done enough to determine that at least some automatic harvesting occurs, but that it is not very efficient compared to picking the plants yourself. On the upside, it seems you can do both.
Answer: There is no "automated" method of harvesting planted crops for replanting or to consume yourself.
You don't need to collect the food in order for your settlers to eat it.
Answer: Normally the settlers harvest the crop for you, but they also need to eat. If you have 5 settlers and 10 corn, they return zero to the workshop. They return the rest after they eat what they need. If you harvest yourself and use the production, they have nothing to eat and the colony satisfaction get down.
All settlers, including these connected to network eat first the tato. If you have 5 settlers in order to get tato production, you need a minimum of 11 tato plants.
Also Sanctuary seem bugged for unknow reason, and seem periodically need to be harvested manually.
It seem also that you have a food cap in workshop, after a certain amount of harvest, settlers stop storing food in workshop. You need to remove the food from the workshop and store them in another container.
Comment: I'm skeptical of your claim of settlers "eating". Obviously, just like with water, you're only eligible to harvest the excess but I doubt the settlers "eat" any of that.
Answer: Set up a Scavenging Station and assign a worker to it in each of the settlements you wish to collect excess scrap/food/water! You can find it under the resources > miscellaneous tab in workshop mode.
Comment: The scavenging station produces random resource.  This doesn't actually collect from your harvests.  See [this question](http://gaming.stackexchange.com/questions/242790/what-does-a-scavenging-station-do-and-how-do-i-use-it)

How can I automate my crop harvest?


Disable drag of JFrame

Question: I want to ask how to make frame can not drag when the application is running?
And then how to disable maximize, minimize button (title bar)?
I'm using JFrame.
Comment: This description sounds more like a tool-tip.  What is the benefit to the end user of breaking a frame like that?
Comment: You can't (really).  These are look and feel/platform specific operations.  You could use a `JDialog` instead, as this typically only has a close button.  You could also try overriding the `setBounds` method of the frame and make sure that it always at a specific location
Answer: Just add the below line it removes the window decorations like close maximise and minimise(titlebar). This itself disables the dragging only with mouse events.
frame.setUndecorated(true);

Comment: *"This itself disables the dragging"*  But it does not prevent the window being moved.  Alt+space on Windows pops a menu that allows me to reposition the undecorated window using arrow keys.
Answer: You can use a JWindow instead of a JFrame.  There is no title bar, so the user won't be able to move it.
setResizable(false);
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);

Comment: *"..the user won't be able to move it."*  I can.  Alt+space on Windows pops a menu that allows me to reposition the window using arrow keys.
Comment: Gnome allows to move windows by `Alt+mouse_drag` at any part of the window.

Disable drag of JFrame


How can a Microsoft Edge content script be debugged?

Question: Microsoft has some decent documentation on debugging Content Scripts for an Edge Extension and the top of the page even includes a Channel 9 video on the subject.
Unfortunately, the techniques no longer seem to work, as even when following the debug instructions and using the the sample Text Swap extension, the extension and content script never show up in the debugger.

As you can see from the screenshot, the content script has run (and changed the font on the page) but it and the extension itself are nowhere to be seen in the debugger.
Anyone figured out how to get the content script to show up in the debugger?
Update: Please note this question, asked in 2017, was about a version of Edge that was not based on Chromium; the issue does not directly apply to versions of Edge built since 2020.
Comment: Can you post the Windows 10 version you are using when experiencing this issue?
Comment: @zaphodtx --  yes, I'm using version 1709.
Answer: You can see below screenshot. I have the css under "extension" folder" and js under "no domain" folder. I hope you have the manifest file correct. Looks like your console have errors. you can check check it and correct if necessary.
enter link description here
Comment: As I mentioned in the question, this is the sample Text Swap extension as-is. Also note that the case is still open in Microsoft's bug tracking system.
Answer: It appears that the debugger is not consistent in loading the extensions.  The script is running, however, the debugger does not always show the extension and the content script.
This is what I have done to ensure visibility of the content script:

Close all open Edge windows.
Launch Edge
Wait for prompt about extensions from unknown sources being turned
off and select 'Turn on anyway.'
Navigate to the URL to debug.  In this case it is:
https://developer.microsoft.com/en-us/
Open the debugger (F12)
Right click on the Extension's Icon on the top right of the browser,
to the right of the address bar.
Select 'Manage' and then 'Reload extension.'
Refresh the page.
Comment: See the comments and video in the referenced bug case -- this list of steps does not always resolve the problem.
Answer: I was having the same issue. The solution which helped in my case is so obvious that it's nearly embarrassing...:
I mistakenly alsways pressed F12 in any arbitrary tab. That brought up the developer tools for the site that was opened in that particular tab. Just as Ken describes his issue.
Now what helps to get the developer tools for the extension to be debugged, is following the instructions listed in the docs here:https://learn.microsoft.com/en-us/microsoft-edge/extensions/guides/debugging-extensions#background-script-debugging
You simply have to click the Background page link. Then you'll be able to debug your extension.
Comment: There is not always a background page/script -- as is the case with the referenced sample text_swap extension.
Comment: The references you mention work consistently in the latest Insider Fast and Skip Ahead Windows 10 releases.  @Ken is talking about some issues in the current public releases, I.e. the documented method do not always work properly.
Answer: This was a bug that has been fixed in an upcoming version, see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/13829248/ for details.


What's best way to show multiple related buttons?

Question: I am making a webapp that enable users to borrow/lend books with their neighbors. Design needs various options like 'borrow', 'can-lend', 'add to wish-list' and 'read' for every book. The issues is:

Showing multiple buttons for each option on UI may take too much of UI space. However if UX is better in this case, it's worth going for it?
Showing most important option by default as button title and showing other options on hover over (or on click on Mobile) doesn't provide the best UX as user may not even realize that there are other options underneath this button.

What can be other options to display multiple related buttons? Thanks.
Comment: I thought this question is worth deliberating so I added to UX SE. If this question is too much specific to my app, please let me know I'll take this down asap.
Answer: Why not use drop-box?
Like this:

It will show the default option yet affording that other options exist and show them when clicked.

download bmml source – Wireframes created with Balsamiq Mockups
Comment: Drop downs should be the last resort for UI: https://storify.com/lukew/drop-downs-are-the-ui-of-last-resort
Answer: We went ahead with Obvious Always Wins principle. This is how it looks now on desktop:

and on mobile:
Answer: The purpose of those words are not very clear.
'Read' -> Does it mean 'I have read this' or 'Read this book now':
'Borrow' -> Does it mean 'I want to borrow this book' or 'I can borrow this book'.
Sure user can figure that out in a few seconds, but he should not need to.
Option 1)
Consider grouping buttons and actions to two groups, in slightly different locations.
Have main actions visible.
[Lend now]
[ Add to wishlist ]
Place the secondary actions related to already owning this book somewhere else.
[ I own this and can lend ]
[ I have read this: rating ]
Option 2)
Just use different visual priotity, main action as a button, others as a links.
[Can lend]
Borrow
Read
Add to Wishlist
Option 3)
Combination of the two above.
Comment: Option 2 seems interesting. I'll design to evaluate if that can be a good solution. Thanks.
Answer: Like you said, if the user doesn't see options in the UI, they may never know about it. It looks to me, based on your screenshot, that you've got some room underneath the image to display some options.
If you only have one visible option, include a down-arrow of some sort next to it. That way you can prompt the user there are additional options.
And like Jkarttunen said, try re-wording the options to make them more explicit.
Answer: I think you can clarify this with icons instead of words and save a lot of space.
For Borrow I would use something like an arrow pointing into a door, or downwards.
For available for lending I would use the opposite of the borrow icon. Greyed out if not available.
For read I would use a checkmark. Greyed out by default, green or other logical color if checked.
And finally for the wishlist, simply a note/list icon.
Comment: Why would icons be a more usable solution when [icons are meaningless](http://www.nngroup.com/articles/icon-usability/) without prior experience? Placing arbitrary icons that can have multiple meanings do not improve the interface's ability to communicate purpose.
Comment: I agree that icons are meaningless without prior experience. However, if you use icons that resemble ones many people are are familiar with, I have found that users tend to click them rather than words. It all depends on the choise of icons, and yes maybe the proposed ones are not ideal.
Answer: I think the real question is what context is this book in I don't think the screenshot provided tells enough of the story. Also, what priority is the actions of the book compared to the actual details to the right of it? What problem(s) and goal(s) do these book specific actions solve?
Pseudo Problem:
People can't find book actions.
Goals:
Increase overall book actions visibility and raise the borrow metric by 10% upon feature release.
Pseudo Solution:
Place the book above the rest of the details and pull all of the actions from the drop down and make them front facing. After they are front facing sort the buttons left to right based on what ever priority they fall under. Icons inside the buttons wouldn't hurt either to further drive their separation and visibility.


Why does shared_ptr not delete its memory?

Question: int main(){

    int* iptr;
    {
    std::shared_ptr<int> sptr = std::make_shared<int>(12);
    iptr = sptr.get();
    }

    std::cout << *iptr;

    return 0;
}

Output
12

I was expecting that the content to which iptr points, would have been deleted, at the end of inner curly braces. But output shows 12. Do I miss something?
Comment: *"was expecting that the content to which iptr points, would have been deleted"* They were deleted. Accessing a deleted object causes undefined behavior. Anything can happen, including this. More practically speaking, deleting an object from the heap makes the memory it has occupied available for reuse. The memory itself is still there though, and isn't zeroed (because there's no reason to do so), and might not be reused *immediately*.
Comment: Don't expect when you free an object that accessing its location will lead to a crash or that it's contents will be changed by the deletion. It is undefined behavior to look at such memory. Anything can happen. In practice `c++` has a you don't pay for what you don't need principle. This means that `c++` won't waste cycles filling deleted memory with 0 or random garbage because it does not matter, It is UB to use such a pointer and look at the memory that was deleted. Any program that looks at such memory is considered malformed and broken by the language.
Answer:
Why does shared_ptr not delete its memory?

shared_ptr does delete the memory that it owns when it is the last owner.

I was expecting that the content to which iptr points, would have been deleted, at the end of inner curly braces.

You were expecting correctly.

But output shows 12. Do I miss something?

You're missing that accessing through invalid pointers results in undefined behaviour.
Answer: As properly pointed by eerorika, you are seeing undefined behavior here. Particularly, a dangling pointer. I.e. a pointer that points to a location with a deleted memory. Not only you can get arbitrary results, but your program might behave in a completely unexpected way.
I would strongly recommend using sanitizers to avoid such problems. Here is the output of the code compiled with -fsanitize=address (https://gcc.godbolt.org/z/Po3r9cvq7):
=================================================================
==1==ERROR: AddressSanitizer: heap-use-after-free on address 0x603000000020 at pc 0x000000401439 bp 0x7fff630ed360 sp 0x7fff630ed358
READ of size 4 at 0x603000000020 thread T0
    #0 0x401438 in main /app/example.cpp:12
    #1 0x7fdd09b5b0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
    #2 0x40121d in _start (/app/output.s+0x40121d)

As you can see, it points out that you are trying to access a deleted memory. It also provides call stacks for operations that allocated and released the memory, which is very handy.


Is it possible to summon a Minecraft item with a custom amount of usage?

Question: I am making a map in Minecraft, and I want to have a really OP bow, however, I want it to only have about 5 or 10 uses. I know how to use the /give command to give custom items to a player. I want the item to be a bow with Power 4 and Punch 7, but with only about 5 uses. I know how to do the power 4 and punch 7 part by using the command /give @p bow 1 0 {ench:{[id:48,lvl:4],[id:49,lvl:7]}}.
Is there a tag that allows you to set how many uses the item has?
Comment: Possible duplicate of [How can I give myself a damaged item on 1.13?](https://gaming.stackexchange.com/questions/338339/how-can-i-give-myself-a-damaged-item-on-1-13) (closing older question as duplicate of newer one because this question has an outdated answer)
Answer: /give @p bow 1 380

Will give you a bow with 5/6 durability remaining (Forget how Minecraft handles durability internally.) Combines with your enchantments, you get:
/give @p bow 1 380 {ench:{[id:48,lvl:4],[id:49,lvl:7]}}


Detecting 2 touches in same time

Question: everyone! I need to detect 2 touches on different image views in same time. So I need to start timer when user touch both image views in same time. And stop timer when touches is end. The image views are moving on screen. There are no problems when I use one image view. Have you any ideas?
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    NSSet *allTouches = [event allTouches];
    for (UITouch *touch in allTouches)
    for (UITouch *touch2 in allTouches)

    {
        CGPoint location = [touch locationInView:touch.view];
        CGPoint location2 = [touch2 locationInView:touch2.view];

        if ([touchArea2.layer.presentationLayer hitTest:location2]) {
             touchArea2.image = [UIImage imageNamed:@"TouchAreaTouched"];
        }
        if ([touchArea.layer.presentationLayer hitTest:location]) {
           touchArea.image = [UIImage imageNamed:@"TouchAreaTouched"];

            timerTouch = 10;
            touchTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(randomVoid) userInfo:nil repeats:YES];
        } else if (![touchArea.layer.presentationLayer hitTest:location]){
            [touchTimer invalidate];
            touchTimer = nil;
        } }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    NSSet *allTouches = [event allTouches];
    for (UITouch *touch in allTouches)
        for (UITouch *touch2 in allTouches)   {

            CGPoint location = [touch locationInView:touch.view];
            CGPoint location2 = [touch2 locationInView:touch2.view];

            if (![touchArea.layer.presentationLayer hitTest:location]){
                touchArea2.image = [UIImage imageNamed:@"TouchArea"];
                touchArea.image = [UIImage imageNamed:@"TouchArea"];
                [touchTimer invalidate];
                touchTimer = nil;
            }
        }

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    touchArea.image = [UIImage imageNamed:@"TouchArea"];
    [touchTimer invalidate];
}

Thanks for any help))
Comment: "two touches at the same time" - is one second delay "the same time"? What about 100ms? What about 1 minute?
Answer: You may want to have a look at UIGestureRecognizerDelegate and then the method:
gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:

Answer: Try this :
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  UITouch *touch = [touches anyObject];
      if ([touch view] == firstimage    ) { // Do Something}
      if ([touch view] == secondimage    ) { // Do Something}
 }

Answer: I thought about this problem a lot and I find the way how to do that.
Here is my code:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    NSSet *allTouches = [event allTouches];
    for (UITouch *touch in allTouches)
        for (UITouch *touch2 in allTouches)

    {
        CGPoint location = [touch locationInView:touch.view];
        CGPoint location2 = [touch2 locationInView:touch2.view];

        if ([touchArea2.layer.presentationLayer hitTest:location]) {
            touchArea2.image = [UIImage imageNamed:@"TouchAreaTouched"];

        }

        if ([touchArea.layer.presentationLayer hitTest:location]) {
           touchArea.image = [UIImage imageNamed:@"TouchAreaTouched"];
            if ([touchArea2.layer.presentationLayer hitTest:location2]) {
                touchArea2.image = [UIImage imageNamed:@"TouchAreaTouched"];
                            timerTouch = 10;
            touchTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(randomVoid) userInfo:nil repeats:YES];
            } }}
    }

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    NSSet *allTouches = [event allTouches];
    for (UITouch *touch in allTouches)

          {
            CGPoint location = [touch locationInView:touch.view];
              if (![touchArea.layer.presentationLayer hitTest:location]&&![touchArea2.layer.presentationLayer hitTest:location]) {
                  touchArea.image = [UIImage imageNamed:@"TouchArea"];
                  touchArea2.image = [UIImage imageNamed:@"TouchArea"];
                  [touchTimer invalidate];
              }

                 }
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    touchArea.image = [UIImage imageNamed:@"TouchArea"];
    touchArea2.image = [UIImage imageNamed:@"TouchArea"];

    [touchTimer invalidate];
}

Answer:  UIView * view = [[UIView alloc] init];
    UITapGestureRecognizer * tap = nil;
    tap.numberOfTouchesRequired = 2;
    tap.delegate = self;
    [view addGestureRecognizer:tap];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{

}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

then you recognizer the location of two touches,and decide what you do ;
Comment: I tried that, but image views are animated. That's why I choose to use
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
Comment: I am sorry than cannot help you ,then I think that when you use touch with event ,why do not use a clear view that is the supper view of the two imageView ,then you use recognizer the two touch by location;hope can help you

Detecting 2 touches in same time


Printing goes to queue only

Question: My 12.04 machine sees the printer, a Canon BJC-1000.  Print request of any kind including test pages will be sent to queue and kept there.  I can purge them but not make it print.  Is there a compatibility problem?
Answer:
Goto Page preview
Select print from printer icon

After that It will be ok and you will can print again from the main Print option

Printing goes to queue only


Strange behavior from decrypt EVP envelope_open()

Question: I have a simple program that encrypts files in a directory. I can iterate through and everything works perfectly. This is using pub/priv key pair. When decrypting one file at a time, it works as it should. However, if there are multiple files in a directory, or even if I put the filenames in a vector and fopen them for reading/writing respectively, it ONLY decrypts the LAST file in the vector/directory. How is this even possible? It fails on everyone of them on OpenFinal(). Here is the function and heart of the program. Everything else is solid. As stated, it works as a standalone program if I just decrypt one file manually or if there is just ONE file in the directory or vector.
Any help would be appreciated. This makes no sense at all. It seems like an implementation issue on their end.
void handleErrors(void)
{
    // perror("Error: ");
    ERR_print_errors_fp(stderr);
    abort();
}

int envelope_open(EVP_PKEY *priv_key, unsigned char *ciphertext,
                  int ciphertext_len, unsigned char *encrypted_key,
                  int encrypted_key_len, unsigned char *iv,
                  unsigned char **plaintext, int *plaintext_len)
{
    EVP_CIPHER_CTX *ctx;
    int len = 0, ret = 0;
    unsigned char *tmpptxt = NULL;

    if((ctx = EVP_CIPHER_CTX_new()) == NULL)
        return 0;

    if ((tmpptxt = (unsigned char*)malloc(ciphertext_len)) == NULL)
    {
        printf("tmptxt error!\n");
        handleErrors();
    }

    if(EVP_OpenInit(ctx, EVP_aes_256_cbc(), encrypted_key, encrypted_key_len,
                    iv, priv_key) != 1)
    {
        printf("OpenInit error\n");
        handleErrors();
    }

    if(EVP_OpenUpdate(ctx, tmpptxt, &len, ciphertext, ciphertext_len) != 1)
            {
        printf("OpenUpdate error\n");
        handleErrors();
    }
    *plaintext_len = len;

    if(EVP_OpenFinal(ctx, tmpptxt + len, &len) != 1)
            {
        printf("OpenFinal error\n");
                handleErrors();
    }
    *plaintext_len += len;

    *plaintext = tmpptxt;
    tmpptxt = NULL;
    ret = 1;
 err:
    EVP_CIPHER_CTX_free(ctx);
    free(tmpptxt);

    return ret;
}

Comment: This isn't an "implementation issue on their end"; it's *your* issue on *your* end. Ex: `*plaintext = tmpptxt;` stores the output buffer pointer, but you then fall past the `err:` label into `free(tmpptxt);` which dangles that pointer. The code back in `main` dereferencing that address, therefore, invokes *undefined behavior*. I have a lot more comments, but without a proper [mcve] it's near-impossible to guarantee their validity. Best of luck.
Comment: no, sorry that has nothing to do with it. Nothing calls err so it is never invoked. it was a label i was using before I started using handleErrors. I just forgot to remove that but i just removed that label now and of course it is still producing the same behavior.
Comment: The label had nothing to do with it, but you're right about the miss-pick regardless,  the setting of `tmpptxt = NULL;` is what prevents the dangle (since you're just `free`'ing a `NULL` afterward which is perfectly fine, so my bad on that, admittedly). Wish I could run your code, but can't, as it isn't a proper [mcve]. A debugger is really your only option at this point.
Comment: the rest of the code just sets up the keys, writes them to a file, reads them in to pass off to envelope_open(). it also reads in the encrypted_key and iv from text files created from the encrypt program so to keep things simple, i didn't post it and i dont think it is necessary but i know people might want to hang me for that. i can tell you that when there is only one file in the directory, it works, but more than one file, it only decrypts the last one. my iterator has nothing to do with it either because i am even using a vector this time which has all the files as the full path.
Comment: Yeah, I saw the 'vector', and the iterator `t`, which makes code like `const char *filename = t[i].c_str();` (or anything using `t[i]`) bogus regardless, since `std::vector::iterator` doesn't provide an overload of `operator[]`. People will want [mcve] s because they no longer have to guess whether the code posted is the code failing, nor do they have to guess what lays within the confines of mystery for the things you didn't provide. They won't 'hang' you for it; but they will be much more likely to not bother *trying* to answer the post.
Comment: i may post the entire code but the user will need to generate a new set of pub/priv keys and include the private portion of bob in this one. they will also need the encrypt program as well. however, i guarantee you my `t[i]` absolutely does work, i am able  to iterate through the entire vector and operate on each iteration. but also that does not matter because i've also written it without any vector, by using my Recursive function on the fly and it still fails
Comment: here is the error i am receiving: `88140000:error:1C800064:Provider routines:ossl_cipher_unpadblock:bad decrypt:providers\implementations\ciphers\ciphercommon_block.c:124:` based on this site https://gitlab.symas.net/symas-public/openssl/-/blob/1ed3249f253e4490a813279e2eb253c8e5cfaabb/providers/implementations/ciphers/ciphercommon_block.c
Answer: I was overwriting the key and iv returned from envelope_seal(). I looked over the fact it was unique. Each file must have this key and iv along with the private key and passphrase on the key to be able to decrypt a file. So this is definitely secure ... until someone cracks AES 256 of course.


How do I construct a zend controller for a command line process

Question: I have a command line process that needs to use code in one of my controllers. When I try to construct the controller, I get an error:
<code>Catchable fatal error: Argument 1 passed to Zend_Controller_Action::__construct() must be an instance of Zend_Controller_Request_Abstract, none given,
</code>
I assume the controller wants the request so it can do routing etc. How do I call the action for the controller from the command line?
Answer: I moved the code I needed for my controller into the model. I suppose it was in the wrong place anyhow as it didn't talk to a view.


ModelForms and Multiple Datasbase - error in form.is_valid()

Question:
Hi,
I just have multiple database in my django website.. each user use a different database, setted in UserProfile.
My problem is:
How can I set the modelForm to use the specific database?
I got these error:  table XX doesn't exists. because django is try to use my auth db.. I try tu use router, but all samples I found in internet, doesn't use database name from UserProfile.
Here is my Form:
class ClienteForm(ModelForm):
   class Meta:
        model = Pessoa

   def __init__(self, *args, **kwargs):
        vUserProfile = kwargs.pop('vUserProfile', None)
        super(ClienteForm, self).__init__(*args, **kwargs)

Here my traceback:
Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/cadastro/pessoa/novo/

Django Version: 1.5.1
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django_evolution',
 'debug_toolbar',
 'pagination',
 'bootstrap_toolkit',
 'web_core')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'pagination.middleware.PaginationMiddleware')

Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/fellipeh/PycharmProjects/webconflex/cadastros/views.py" in EditaPessoa
  47.             if formPessoa.is_valid():
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in is_valid
  126.         return self.is_bound and not bool(self.errors)
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in _get_errors
  117.             self.full_clean()
File "/Library/Python/2.7/site-packages/django/forms/forms.py" in full_clean
  274.         self._post_clean()
File "/Library/Python/2.7/site-packages/django/forms/models.py" in _post_clean
  344.             self.validate_unique()
File "/Library/Python/2.7/site-packages/django/forms/models.py" in validate_unique
  353.             self.instance.validate_unique(exclude=exclude)
File "/Library/Python/2.7/site-packages/django/db/models/base.py" in validate_unique
  731.         errors = self._perform_unique_checks(unique_checks)
File "/Library/Python/2.7/site-packages/django/db/models/base.py" in _perform_unique_checks
  826.             if qs.exists():
File "/Library/Python/2.7/site-packages/django/db/models/query.py" in exists
  596.             return self.query.has_results(using=self.db)
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py" in has_results
  442.         return bool(compiler.execute_sql(SINGLE))
File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  840.         cursor.execute(sql, params)
File "/Library/Python/2.7/site-packages/django/db/backends/util.py" in execute
  41.             return self.cursor.execute(sql, params)
File "/Library/Python/2.7/site-packages/firebird/base.py" in execute
  158.             six.reraise(utils.DatabaseError, utils.DatabaseError(*self.error_info(e, query, params)), sys.exc_info()[2])
File "/Library/Python/2.7/site-packages/firebird/base.py" in execute
  150.             return self.cursor.execute(q, params)
File "/Library/Python/2.7/site-packages/fdb/fbcore.py" in execute
  3322.                                     PreparedStatement(operation, self, True))
File "/Library/Python/2.7/site-packages/fdb/fbcore.py" in __init__
  1934.                 "Error while preparing SQL statement:")

Exception Type: DatabaseError at /cadastro/pessoa/novo/
Exception Value: ('Error while preparing SQL statement:\n- SQLCODE: -204\n- Dynamic SQL Error\n- SQL error code = -204\n- Table unknown\n- PESSOA\n- At line 1, column 41', u'-204 -- SELECT FIRST 1 (1) AS "A" FROM "PESSOA" WHERE "PESSOA"."IDPESSOA" = -1')

Here is my Pessoa model:
class Pessoa(models.Model):
    idsys_point_cliente = models.CharField(max_length=28, primary_key=True)
    idpessoa = models.IntegerField(verbose_name=u'Código', primary_key=True, default=-1)
    data_cadastro = models.DateTimeField(u'Data/Hora Cadastro', default=datetime.now, blank=True, editable=False)
    data_atualizacao = models.DateTimeField(verbose_name=u'Data/Hora da Última Atualização', default=datetime.now,
                                        blank=True)
    status = models.CharField(verbose_name=u'Status',
                          max_length=1,
                          default='A',
                          choices=Ativo_Inativo_CHOICE)
    razao_social = models.CharField(u'Razão Social *', max_length=70, null=False)
    nome_fantasia = models.CharField(u'Nome Fantasia', max_length=70, blank=True, null=True)
    endereco = models.CharField(u'Endereço *', max_length=150, null=False)
    numero = models.CharField(u'Número *', max_length=30, null=False)
    bairro = models.CharField(u'Bairro *', max_length=40, null=False)
    complemento = models.CharField(u'Complemento', max_length=30, blank=True, null=True)
    idcidade = models.ForeignKey('web_core.Cidade', verbose_name="Cidade *",
                             db_column='idcidade', null=False, blank=False)
    email = models.EmailField(u'E-Mail', max_length=100, blank=True, null=True)
    fisico_juridico = models.CharField('Tipo Cadastro *',
                                   max_length=1,
                                   default='F',
                                   choices=FIS_JUR_CHOICE)
    fis_cpf = models.CharField(u'CPF', max_length=14, null=True, blank=True)
    jur_cnpj = models.CharField(u'CNPJ', max_length=18, null=True, blank=True)
    telefone1 = models.CharField(u'Telefone', max_length=14)
    idrepresentante = models.IntegerField(u'Representante', null=True, blank=True, editable=False)

    class Meta:
        ordering = ['razao_social']
        managed = False
        db_table = 'pessoa'

    def __unicode__(self):
        return self.razao_social

Comment: The key is to use custom auth backend, that will recieve user data and decide, what database will you use. You can find example here: https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#writing-an-authentication-backend
Comment: can you send example? How can i use custom auth backend to set is_valid?
Comment: Oh sorry for misunderstanding. Auth backend is user authentication. It is next step if you will use authentication. May be you need to describe validation process in your custom user model.
Comment: could you post your `Pessoa` model code? the error is that table is missing.
Comment: @Hieu Nguyen : I edited my post, and added Pessoa model.. @m9_psy : I don`t have custom model validation,I just add 3 new fields to the UserProfile, only thins.
Comment: @Hieu Nguyen : the problem is.. table Pessoa doesn't exists in default database, only in my other databse, but .is_valid try to get this table in default database.. my question is: how can I force .is_valid get data from other database?
Comment: I think the source of all your problems is: `each user use a different database` - why do you have this?
Answer: Reply my own question...
The only way to get this right is make one middleware to get database name and work with locals, like this:
File: middleware.py
from threading import local
from django.contrib.sessions.models import Session
from django.contrib.auth.models import User
from web_core.models import UserProfile

my_local_global = local()

class CustomerMiddleware(object):
    def process_request(self, request):
        my_local_global.database_name = get_database_name(request)

def get_database_name(request):
    session_key = request.session.session_key
    try:
        session = Session.objects.get(session_key=session_key)
        uid = session.get_decoded().get('_auth_user_id')
        user = User.objects.get(pk=uid)

        profile = UserProfile.objects.get(pk=uid)

        if profile:
            return profile.dbname
        else:
            return None
    except:
        return None

after this, add middleware.py in your settings.py:
MIDDLEWARE_CLASSES = (
(..)
    'middleware.CustomerMiddleware',
)

to finish, make one more file to get db router:
File: authrouter:
class PadraoRouter(object):
    def db_for_read(self, model, **hints):
        from middleware import my_local_global
        return my_local_global.database_name

    def db_for_write(self, model, **hints):
        from middleware import my_local_global
        return my_local_global.database_name

    def allow_relation(self, obj1, obj2, **hints):
        return None

    def allow_syncdb(self, db, model):
        return True

class AuthRouter(object):
    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'auth':
            return 'auth_db'
        if model._meta.app_label == 'sessions':
            return 'auth_db'
        if model._meta.app_label == 'web_core':
            return 'auth_db'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == 'auth':
            return 'auth_db'
        if model._meta.app_label == 'sessions':
            return 'auth_db'
        if model._meta.app_label == 'web_core':
            return 'auth_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if obj1._meta.app_label == 'auth' or\
           obj2._meta.app_label == 'auth':
            return True
        if obj1._meta.app_label == 'sessions' or\
           obj2._meta.app_label == 'sessions':
            return True
        if obj1._meta.app_label == 'web_core' or\
           obj2._meta.app_label == 'web_core':
            return True
        return None

    def allow_syncdb(self, db, model):
        if db == 'auth_db':
            return model._meta.app_label == 'auth'
        elif model._meta.app_label == 'auth':
            return False
        return None

NOTE: I need to put import in each def, because Django 1.5.1 has a bug, if you put import into top of file.. cycle imports..
after this, change again your settings.py to add the router:
DATABASE_ROUTERS = ['authrouter.AuthRouter',
                    'authrouter.PadraoRouter']

Remember
I make this way, because I have one database, only for auth.. each user can access a different database, depending what is save in dbname field.
If you have other solution, please let's me know!
Thanks to everybody.


Incorrect syntax near the keyword 'table'

Question: I am receiving this error. What I am doing is trying to take data from one table and one db and place it into another db and table. The tables are not exactly the same. I am using a FETCH cursor, so I fetch the first row from db1 table and then place each column value into declared variables. Then I run the insert statement into db2 table and fetch the next value. It all seems to be working properly because it runs through fine but at the end I get this error,
Incorrect syntax near the keyword 'table'.
The whole transaction statement is in a TRY/CATCH with an error handling expression in the CATCH block. Other than that I don't know what causes this. Please help.
Here is the code
  BEGIN

  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  BEGIN TRY
    BEGIN TRANSACTION

    --TURN OFF ITENDITY COLUMNS
    SET IDENTITY_INSERT [DB].[dbo].[TEST] ON

    --TURN OFF ALL CONSTRAINTS
    ALTER TABLE [DB].[dbo].[TEST] NOCHECK CONSTRAINT ALL

    -- Insert statements for procedure here
    DECLARE  @ID int,
             @DT datetime,
             @PID varchar(10),
             @AREA varchar(20)

    DECLARE FETCH_TEST CURSOR FOR

    SELECT [ID]
      ,[Date]
      ,[PID]
      ,[Area]

    FROM [OLDDB].[dbo].[TEST] as db1

    OPEN FETCH_TEST;

    FETCH NEXT FROM FETCH_TEST INTO @ID,
             @DT,
             @PID,
             @AREA

    WHILE @@FETCH_STATUS = 0
      BEGIN

             --INSTER VALUES INTO THE TABLE
            INSERT INTO [DB].[dbo].[TEST]
                       ([ID]
                       ,[DT]
                       ,[PID]
                       ,[AREA])
                  VALUES
                    (@ID,
                     @DT,
                     @PID,
                     @AREA)

          FETCH NEXT FROM FETCH_TEST INTO
             @ID,
             @DT,
             @PID,
             @AREA,

     END;

    CLOSE FETCH_TEST;
    DEALLOCATE FETCH_TEST;

    -- If we reach here, success!
    COMMIT

  END TRY
  BEGIN CATCH
    -- Whoops, there was an error
    IF @@TRANCOUNT > 0
      ROLLBACK

     -- Raise an error with the details of the exception
     DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
     SELECT @ErrMsg = ERROR_MESSAGE(),
            @ErrSeverity = ERROR_SEVERITY()

     RAISERROR(@ErrMsg, @ErrSeverity, 1)
  END CATCH

  --TURN OFF ITENDITY COLUMNS
  SET IDENTITY_INSERT [DB].[dbo].[TEST] OFF

  --TURN ON ALL CONSTRAINTS
  ALTER TABLE [DB].[dbo].[TEST] CHECK CONSTRAINT ALL

END

Comment: Post the code with the invalid syntax.
Comment: It's obvious that your problem is that you have no code: no SP and no DDL. If you had it, you'd have posted it, so you obviously don't have it.
Comment: You should post the code you're having trouble with
Comment: the code you posted looks correct, I don't see any errors.....WHERE IS THE CODE!!!!
Comment: I think that a Try/Catch block can help you with exceptions... but not with syntax errors.

...Also take in consideration the Matthew's hint.
Comment: I see no one said it, WHERE IS THE CODE?????????????
Comment: @Itay: @SQLMenace said it 2.5 minutes before you. You must have been looking at the code, and not seen it.
Comment: Sorry for not posting the code I thought I copied it in there, any help would be appreciated
Answer: First thing is that @TRAIN_ID is never declared in your code
Must declare the scalar variable "@TRAIN_ID".
second is that you do NOT need a cursor, what is wrong with a SET based operation instead? It will perform much better!! Replace the cursor part with this
INSERT INTO [DB].[dbo].[TEST]
                       ([ID]
                       ,[DT]
                       ,[PID]
                       ,[AREA])

SELECT [ID]
      ,[Date]
      ,[PID]
      ,[Area]
FROM [OLDDB].[dbo].[TEST] as db1

you also have an extra comma here
 FETCH NEXT FROM FETCH_TEST INTO
             @ID,
             @DT,
             @PID,
             @AREA,

should be
 FETCH NEXT FROM FETCH_TEST INTO
             @ID,
             @DT,
             @PID,
             @AREA

But like I said you don't need a cursor for this
Comment: I edited the code with the @TRAIN_ID see above. It still give the error.

Second, that would work but I need to do some logic on each row but I first just watned to make sure that it was working properly aka, fetching the row and inserting it first. But I am still recieving the error.
Comment: Dan, the logic can easily be put into the set-based solution as well. Cursors should almost never be used for inserts as they are extremly bad for performance.
Answer: And by the way, you don't need a cursor for this.
INSERT INTO [DB].[dbo].[TEST]
                     ([ID]
                     ,[DT]
                     ,[PID]
                     ,[AREA])
SELECT    [ID]
  ,[Date]
  ,[PID]
 ,[Area]
FROM [OLDDB].[dbo].[TEST]

This does the same job and is faster.
Answer: The keyword table is not useful in either selecting from one table or inserting into another. Wherever you have written it, it doesn't belong there.
Answer: Try to replace the 'Table' (Table Name) in the queries with '[Table]'. Since Table is already a reserved keyword, there are chances the visual studio may not allow you to establish a connection to such table names.


If Dlookup doesn't meet criteria in several tables then display error. Microsoft Access

Question: Ok I could use some advice please as I am not frequently used to VBA.
I have a form and within that form, I have a subform that is built by a make table. I am in no need to change this.
I however would like to add a sanity check before pressing the upload button that updates SQL server. Where I am getting stuck is on a IIf(Dlookup) function; I am trying to look into a local table and if three fields in the local table match the fields and criteria I have on my subform then check to see if 5 columns within my subform add up to one other field in my subform.
For an example; In the Local table there are the three fields as: "UNIT", "TYPE", "Center"
"Unit" Criteria is as follows: 1212, 1213, 1214 and so on
"TYPE" Criteria is as follows: Shop, Outside, Innerbank
"Center" Criteria is as follows: Electrical shop, machine shop, outside shop.
*** What I need to do is match those fields from the table mentioned above which is called "Ledgend" to the subform on my form and if that Unit, Type, and Center are all present within a row on my subform then calculate(SUM) 5 fields on my subform and if it matches the field called Total on my subform then leave it as is but if it does not then highlight the rows that are different and throw an error msg
If DLookup("Unit", [dbo_TableName]) = "Unit", FORM![SUBFORM_NAME]!Unit & "TYPE", [dbo_TableName]) = "TYPE", FORM![SUBFORM_NAME]!TYPE, & _
    "Center", [dbo_TableName]) = "Center", FORM![SUBFORM_NAME]!Center Then
    subform Sum(Dis + ABS + Center + SS + WRK)
Else
    MsgBox ("Error")
End If

Answer: Sum() is not used to add fields, it is used to aggregate records. Syntax for DLookup is completely wrong. Reference to subform makes no sense. Sounds like you need a nested If Then. Following assumes code is behind subform.
If Not IsNull(DLookup("ID", "Ledgend", "Unit & Type & Center'" = Me!Unit & Me!TYPE & Me!Center & "'")) Then
    If Me!Total <> Dis + ABS + Center + SS + WRK Then
        MsgBox "Error"
        'code here to set BackColor property of each control
        Exit Sub
    End If
Else
    Exit Sub
End If

BTW, Ledgend is a misspelling of Legend.
Could use Conditional Formatting rule to manage setting Backcolor property.
Comment: June7 Could you perhaps translate this to EXCEL. Perform a vlookup based on certain field names then check throughout the end of the worksheet check the values in those cells and if they do not equal FieldNameX then highlight yellow
Comment: If you have a new requirement then should create a new question.
Comment: https://stackoverflow.com/questions/60043441/formatting-an-export-file-from-access-to-excel-with-conditional-formatting?noredirect=1#comment106190737_60043441


Customers using the New Order option when they should use Reorder

Question: I have a form for customers to place orders through a form (An Ecommerce solution is coming, but in the meantime we are using this). There is one <select> drop down that was giving us issues. Reorder is for referencing an old order, and just changing the customized text on the product (such as names on a nametag). New Order means they specify every option (size, magnet backing, font, so on). Because of technical reasons, I am unable to populate the form with the data of previous orders.
New Order or Reorder?
    New Order
    Reorder

We find by looking at the forms we receive and the feedback we get from customers, that a lot of customers are using the New Order option when they should use Reorder. Customers doing the opposite (using Reorder when they should use New Order) has not been an issue.
After seeing this, I made the following changes. I placed Reorder first (since most orders are reorder) and added some descriptive text.
Reorder or New Order?
    Reorder (You can make changes from a previous order)
    New Order (This is an entirely new order)

Looks like this now

The issue is still happening however. When a customer complains that the form is too long, we contact them, explain they should be using Reorder, which they say makes sense, then they start using it correctly. There must be a UI/UX tweak to prevent the issue in the first place. I've asked what language they would use, but the responses have been all over the place with no common theme.
The user demographics are usually older, not tech savvy, and business oriented.
How can I prevent customers from using New Order when they really want to use Reorder?
Comment: To me, "make changes" would mean *modifying* an order that has been placed but not received yet. They would be Re-ordering the order, changing it, not Again Ordering the same thing only different. It is hard to say "*do what you did before, almost but with the changes that you want for this time.*" It just isn't a word in our language. Ask them what they would call it. Probably they have no idea. Then you throw out your plan and come up with something... "Completely Different"
Comment: If I wanted to make a new order with a few small changes and I was presented with a free text field to *describe the changes in prose*, I would grumpily go fill out the "New Order" form because I'd be terrified someone would screw up my prose description. As made apparent by everyone's answers and comments, it's also definitely not the kind of behavior we expect from your description; your users are probably startled by it. I think the "Reorder" form is itself more of a problem than the interface you're asking about. Do you have any data on whether try it and then abandon it?
Comment: "New Order" and "Re-order" are bad choice of words. "Re-order" means "make an order that I already made, again". There is no implied connotation of "but make just a few adjustments", as you seem to want. If I am a customer and I want to make a similar but slightly different order, of course I want a new order.
Comment: It's entirely plausible that browser auto-complete is a faster re-order than your re-order pathway.
Comment: @Hamsteriffic I'm well aware. The difficult part is finding a better choice of words.
Comment: @Goose: I think I do. Punch new order, then the first character of each item in the order form and let auto-complete take care of it.
Comment: So, reorder consists of having data from some previous order blindly inserted into your database with whatever modifications you make, without being able to see what data is being reused, just able to see the changes?  I wouldn't want to press that button.  Unless I had prepared for it when I created the first order, I would be highly likely to get it wrong.
Comment: @Yakk, It's even goofier than that. There's no database, just an email that gets sent to order entry. Our focus is currently on the eCommerce solution to replace this, but in the meantime we also want to improve this form, which is the focus of the question. To your point though, some customers have said that they prefer filling out all the fields each time they order, but most do not. Before the form was created, many of these customers faxed their orders in.
Comment: Part of the reason I point that out is that maybe it doesn't even make sense to invest in trying to improve this form if users aren't going to user the actual "Reorder" form anyway.
Comment: @jpmc26 we're already saving several hours a week and feedback from customers have been very positive, even from those using New Order when they should use Reorder. I wouldn't jump to pessimistic attitudes so easy.
Comment: You could check if they have past orders and just ask them when placing a new order: "Do you want to start with a copy of a past order?"
Comment: @Joshua I don't think you understand. Reorder (not a perfect word for this) means you specify the old order ID and then specify what you want to change on the order (names, options).
Comment: @Joshua They don't refill out the form on reorder. They only fill out 2 fields. Previous order id, and changes. Only field that can be autofilled is previous order id. Even then, they have to choose to reorder before they even get to that field.
Answer: Speak like your customers
It's helpful to be more conversational — especially with older customers who tend to miss implied meaning in an interface. They aren't typically put off by a little extra text for the sake of clarity. This does not always hold true with younger markets.
Get into your customer's state of mind ...

"Reorder" means "place the same order again".
  But I want to make changes from last time.
  I know what reorder means.
  "New Order" it is ✔

Obviously, I'm not your customer. I'm guessing here, but you get the idea.
What if you framed the decision differently? What if you were more conversational?

download bmml source – Wireframes created with Balsamiq Mockups

In response to @PeterL's excellent point …
Some other, possibly clearer, button language for "re-order":
Customize a previous order
Copy and revise previous order
Copy and revise from order history
And some "new order" language options to go along with those:
Start a blank order
Order new items
Order something new
Comment: I'd still suggest not using "re-order" on the button itself. Maybe "customize previous order" or something. This goes to your point of speaking like your customers, and I think you want to do it on the button itself since that's what they're most likely to read.
Comment: @plain you're absolutely right. There is a website with the same "problem" OP mention and I think I never clicked "re-order" because I have no idea what it will do (and I do not want to waste my _valuable_ time exploring this feature)
Comment: @jitendragarg I mised your answer (left the mock window up for a while I was doing other things). Looks like we came to the same basic conclusion
Comment: @jitendragarg and plainclothes, Both answers hit some of the same points, but the suggestion in this answer to take a conversation tone to reframe the question makes sense and is very actionable. I'll implement this approach today, thank you both!
Comment: An alternative "re-order" text could be something like "Create/Start a new order based on a previous order" - to me, it's a little simpler to interpret than the "Copy and revise [...]" variants.
Comment: that is a neat solution. Very orientating
Comment: Those mockups are great. Better way to explain than I could.
Comment: I revised the button language to address @PeterL's point. In the examples I chose, there is an added benefit for the OP's scenario: The "re-order" option presents a larger button which will tend to draw the customer, which is a win since re-orders account for the majority of use cases.
Answer: Why this is happening
In a word (because, well, there is a word that's causing it—or rather three together): jargon.
It may not seem like it… both words involved are common language words. But that is actually exacerbating the issue, not helping it.
You are using the word "re-order" to mean something that is a common way to use it on the supply side of your industry. However, clearly the people using the service do not understand it to mean the same thing you do.
Now, you don't perceive it as jargon, but that's because you are familiar with your own terminology within this context. The issue, however, is not what you think "re-order" means, but rather what your customers do, and particularly what they think it means in contextual relation to "new order."
"New order" in this context is equally problematic, because it stands as a binary, blocking/exclusive choice when its own wording seems to be obviously something the customer is engaging in. They are making a new order, from their perspective, even if it is one that shares similarities/common basis to an older order. The presence of this wording likely means it will always have a higher selection rate than whatever it is being placed in opposition to, even when the other option does match the customer's underlying intent as understood in your perspective.
How to fix it
Stop trying to explain the words. Stop referring to things based on your perspective or the supply/service side context. Stop trying to mold the customer into your perspective.
Instead, change your own language entirely. You need to shift your perspective from how the ordering fulfillment process looks to you, to that of someone placing an order. How do they describe their intent for different "types" of orders? To them, are they even different "types" the way you see/categorize them? How can you, in turn, capture and address that?
While you can "train" repeat users at least (to varying extents), people tend to skip explanations. The longer the explanation, the more likely it is to be skipped. Particularly, people take shortcuts. That is to say, if you give them a word that they believe they know the meaning of, they are far less likely to read any text that seems to be explaining it.
If naming the option "re-order" is causing problems, stop calling it that entirely. You may also need to stop putting "new order" as a binary option in this context, because, from the customer perspective, of course it's a "new order." Don't expect to be able to explain around this. Re-ordering the explanation to be in front of the option may help, but ultimately it's masking the underlying issue and will likely have a lower success rate than addressing it more directly.
It's sometimes hard to remember from the context of designing a service that something which is every day and central to you or the operators of the service is often merely a minute or two out of a month for the person using it. In other words, it's given no weight as something needing to be remembered/integrated into that person's schema: trying to effectively train (because that's what this becomes) someone who is not actively using your service continually is an exercise in futility for everyone involved and merely serves to create friction between you and the people using the service.
You're going to need to both ask questions and test
I can't give you a specific answer on what is going to be best suited to the people using your service, just ideas on how to go about finding some. I carried forward a print ordering service with minimal form changes (as a requirement) and most of the people using it have no issue with the wording you are using. But they are also mostly heavy repeat users of the service, who probably spend at least an hour a month if not an hour a week, in some cases, placing orders. The few who are not heavy users are often only placing new orders (usually one offs), so it works well.
Talk to your customers. How would they refer to the process of placing an order based on an old order?
Change the flow!
One way I would approach this, personally, would be to try out something where you always are placing "a new order" and instead at the start of the ordering process you have the option to (with no directly opposing options):

"import from a previous order" (I consider the wording here to be important in distinguishing what is happening)
"Use order templating for faster orders!" (sometimes, using unfamiliar phrasing that seems to clearly connotate a contextually specific meaning and makes someone new ask "what's that?" is actually helpful, because it changes their context from one where they presume an understanding of what you are saying to one where they are open to your explanation… but remember, gaining an understanding of this is of far less significance to them than you, and they may still instead just skip it)
"Reload with changes" (However they conceive of what they are doing when going through this process, that is what you need to match)

Examples would be a page in the order flow that offers the central screen choice to:

"Yes! Import from an older order so I can quickly modify a new copy of it"

With a "normal flow" continuation option (e.g. bottom right hand corner)

"No, this order isn't like any of my previous ones"

Not as directly opposed binary elements in a drop down or radial options, but rather as effectively forking flow buttons, with the only exclusion aspect being a natural one following flow choices rather than more direct diametric opposition of an exclusive control (separating them in terms of space will help here, as will having one be an action item in the main selection area and the other being in the normal flow continuation area, due to how it changes their related contexts to each other).
Or alternatively, as an "add-on" to the current order, early in the order process, a checkbox/similar control not placed in opposition to any other options. Or a button that takes you to the selection view for the previous order to select for "importing"/"re-ordering." (you'll presumably need a new view for this, so that there is enough information to help someone select: personally I have no idea what I ordered on a given date/order number from a given company, I need to see the order details at least to some quick summary extent).
Given that you will need to somehow display an order selection from previous orders, I'm personally in favor of an action button of some kind, as it's a strong cue for the flow response or spawning a related modal (however you approach this).
Part of the problem with your current flow is that it creates an element of confusion by how it places an exclusionary binary choice between something that they obviously want to do (place a new order, in their understanding thereof) and something that they also want to do but don't necessarily realize (re-use an older order, with modifications… while placing a new order). Even changing the language won't entirely fix this problem: you need to remove the binary exclusion aspect of this in terms of it being opposed to starting a "new order." Make your "re-ordering" something that instead can be layered on top of a current "new order."
Even if the difference is essentially non-existent from a software logic side, it's crucial in how it guides an understanding and matches the flow to the intent and perspective of the customer based on their context.
Helpers
Can you programmatically spot when an order looks a lot like a previous order? Even if it's "too late" by the time you can spot this to make the current order faster, that doesn't mean you can't still offer input the next time they're ordering that highlights the "import/re-order/whatever" option. Or sends them an email about a "new feature to streamline your orders!" (which they're likely to miss, ignore, have end up in spam, or ultimately forget by the time they order again, but you can certainly try—I recommend focusing on things you can do within the service's flow, though)
Note that it doesn't matter if the feature isn't "new" in an absolute sense or from your context. The point is that it is new to them. Context and perspective.
Test
See if you can recruit a group of your customers for targeted testing and related feedback, if you can set up a separate instance or otherwise create an A/B style setup with your service by giving your test group a specific, different link to use. Do not discuss what you are changing before hand. Once they have placed some orders with the new format, you should be able to see if it made a difference.
Ideally, if you can shadow some of these customers while they place an order, it would be even more beneficial to getting an actual idea of their process and related thinking.
You'll never get everyone. People are different, they approach processes differently, and trying to design for everyone often creates more problems than it solves. Don't worry about edge cases, in terms of this design aspect. Capture them through support or direct outreach, instead. But you should be able to make a better experience for most of the people using your service, so long as you can approach it from their perspective instead of yours, and then design something that intuitively works with how they are approaching the task they are trying to complete via your service.
Comment: Honestly the issue you discussed with maxathousand could easily be another reason people aren't using the option. What kind of tracking/analytics do you have embedded? Can you tell when people pick one option and then back up the process and use the other? I would consider at least exporting and then generating some kind of previous order summary into a table with dates and PO numbers (and tied per user), if you can do a CSV/etc export from the old system. Or do your customers usually have their own order logs on hand?
Comment: I appreciate the very long answer. I think you spent far more time reiterating the problem than you needed too. You gave far too broad an answer. Also, the other answers covered most of your points much more concisely and with more narrow actionable advice. I'll update my question to explain that I am unable to populate the form, as I explained to maxathousand.
Comment: Assertions to the contrary notwithstanding, this answer is quite nice, and *"If naming the option ... is causing problems, **stop calling it that entirely**"* is going in a frame on my office wall.
Answer: The label text is not your problem. Users are telling you how they expect to interact with your site.
Perhaps this behavior indicates that you're asking the user if they would like to reorder a previous item too early in their process. It might be that the user is thinking "Okay, I need more of these, so I'll log on and make a new order for them," then proceeding to do just that--begin a new order.
Instead, maybe provide them one option: "New Order", then provide them the option to "Pre-populate from Previous Order". This way, it allows the user to continue doing what they've been doing, as well as provide them with the ability to copy from a previous order.
Comment: So where does the "Reorder (You can make changes from a previous order)" option get its values from? What does that do?
Comment: You could provide that same behavior still, but just have that one step later in the process. I'll update my answer with a mockup.
Comment: That's a great answer, **However** I am not able to populate previous data. I don't have order data from previous submitted forms stored in a relational database. It has no memory so to speak. I could work on building it, but it would delay the eCommerce solution. I'm looking for a solution that doesn't require significant back end changes.
Comment: It asks for a previous po number, order id, or ticket number. Then it provides a text box to specify what changes they want. The order information exists in a legacy and proprietary system that makes it infeasible to programmatically connect the information to the form.
Comment: @Goose Actually, I don't have time right now, but I was going to suggest that once they move to a new order form, near the top, show a button for "Populate form with previous order" or something similar. Clicking that would open a modal that would provide the lookup options that you mention. If the order is found, the modal closes and the form gets populated.
Comment: Not sure if I've explained correctly. I don't have the data available in this system, so I am unable to populate any fields. The form has no way to know what backing name tag order id 12345 had.
Comment: @Goose Ah, I think I understand. So reordering doesn't show the user all of their previous form data, but rather just prompts them to customize one or two fields and submit again? In this case, you might keep the dropdown as it is, but provide a link at the top of the "new order" page that says something like "Instead, Reorder From Previous Order (you can make changes before submitting)" or whatever terminology you'd like to redirect them back to that function. Essentially, you'd be trying to make their mistake more easily recoverable while also providing more visibility to this feature.
Answer: I think your current system might cause some confusion. As you say, users learn that they can reorder, as soon as you explain the reorder option. Which means your options are not descriptive enough.
I will try two things. One is to get rid of drop down, and instead use buttons. Buttons are one click, while drop down needs two. Second will be to rename the options. Your user base might be considering "Reorder" as equivalent to "Order same thing again". Next time, when you contact any user, ask them what they think reorder option was for. That should give you full insight on why user is missing the option.
Also, I will consider if user is even using the "New order" option, or if they are starting from scratch like they did the first time. If they do use your dropdown, it is just description that need to change. If they don't use the dropdown at all, you should improve visibility of the options. One idea is to move the buttons closer to eyesight when the page loads (closer to the center of the page or the last page's navigation button that brought user to this page). Another idea will be to create some contrast from other options in the page.
If I am unable to explain it properly, do let me know. I will try to add some examples to help.
Edit:
For the dropdown issue, consider this link. https://baymard.com/blog/drop-down-usability
Idea is if you have fixed number of options and very limited options, buttons or radio buttons are better than dropdown. Especially in your case where it is compulsory, it is unnecessary hassle for the user. It is not going to help your case directly, but will provide your options some extra visibility.
Comment: Great answer. Customers think Reorder is for exactly the same, we're aware of this, that's why the new language explains that changes are allowed, but still seems insufficient, perhaps because users aren't bothering reading the text inside the (). We have asked customers what language makes sense, but the answers have been all over the place. By the way, the dropdown is required, it can't be left blank, not sure if you were clear on that or not. Customers definitely need the New Order option sometimes.
Comment: I meant, you can convert the dropdown to two buttons instead. Create two sections with more information, and add the buttons. That should give your options higher visibility over similar dropdowns. These are bigger actions than say selecting the color of the product.
Comment: Hmmm, I'm not sure why having the choice be more visible helps. It's a required field already. I am not convinced that making the choice more visible will cause them to make the right choice more often.
Comment: Sorry, I didn't mean that it will directly help with usage rate. It is just going to make your options easier to use and more visible. Plus, only 2 options in a dropdown list is not considered a great experience. Let me find more articles on this matter. Will edit this comment again.
Comment: Oh no, I agree that it may make more sense to have buttons than a 2 option drop down, and I may implement that change. No need to persuade me of that.
Answer: If you get a high volume of Reorders then prompt for that first and up front.

Want to speed things up? Why not drop in an Order Number from last time you shopped with us!
If you haven't got an existing order number or if you just want to order something completely different please continue to place a new order.
Answer: It looks to me that you're just missing a very simple solution:

New Order
Reorder
Similar Order

The "Similar Order" is what you currently call "Reorder". "Reorder" itself is almost the same flow - you'll still offer to change the fields, but the default is just to skip that and submit the order directly.
Answer: it might be as simple as having one option 'Order' and on that page a drop down to copy a previous order details which you can edit or not.
this approach is good if the main use case is ordering something from scratch.
Comment: Per the question "I am unable to populate the form with the data of previous orders."
Answer: Often, users are best served by not asking questions at all, but providing sensible defaults. Assuming that re-ordering is a common enough use case, I would do the following:

Remove the question re-order / new order question completely.
Pre-fill the order form with the values that were entered in the previous order (if it doesn't make sense to re-use certain values, leave those out)
Display a highly visible message above the form, saying something like:
We pre-filled the choices you made last time. You can also start with an empty form.
Where "start with an empty form" is a button that clears the form.
Comment: Per the question "I am unable to populate the form with the data of previous orders."
Comment: Ah, sorry, I missed that.