text:
Q: How do I parse a nested JSON array of object with a custom Gson deserializer? Good day all. I am having a bit of trouble understanding this. I have a JSON that looks like this:
  {
      "data": [
        {
          "id": "43",
          "type": "position",
          "attributes": {
            "address-id": "1",
            "employer-id": "11"
          }
        }
      ],
      "included": [
        {
          "id": "1",
          "type": "address",
          "attributes": {
            "line-1": "21 london london",
            "line-2": "",
            "line-3": "",
            "locality": "",
            "region": "London",
            "post-code": "",
            "country": "UK",
            "latitude": "",
            "longitude": ""
          }
        },
        {
          "id": "11",
          "type": "employer",
          "attributes": {
            "title": "Mr",
            "first-name": "S",
            "last-name": "T"
          }
        }
      ]
    }

And my Retrofit call is:
 @GET("/api/positions")
 Single<PositionResponse> getPosition();

And my PositionResponse class:
public class PositionResponse {

        @SerializedName("data")
        @Expose
        private List<DataResponse> data;
        @SerializedName("included")
        @Expose
        private List<IncludedModel> included;

        public List<DataResponse> getData() {
            return data;
        }

        public void setData(List<DataResponse> data) {
            this.data = data;
        }

        public List<IncludedModel> getIncluded() {
            return included;
        }

        public void setIncluded(List<IncludedModel> included) {
            this.included = included;
        }

        }
    }

Now imagine it has a lot more data. How can I create a custom TypeAdapter or JsonDeserializer for parsing the List<IncludedModel>? For some reason, I can create a custom JsonDeserializer or TypeAdapter for Object, but when it comes to a List, I don't seem to be able to get that to work.
My TypeAdapter is as follows:
  public class IncludedTypeAdapter extends TypeAdapter<ArrayList<IncludedModel>> {

        @Override
        public void write(JsonWriter out, ArrayList<IncludedModel> value) throws IOException {

        }

        @Override
        public ArrayList<IncludedModel> read(JsonReader in) throws IOException {
            ArrayList<IncludedModel> list = new ArrayList<>();
            IncludedModel model = new IncludedModel();
            Gson gson = new Gson();
            in.beginArray();
            String id = null;
            //in.beginObject();
            while(in.hasNext()){
                JsonToken nextToken = in.peek();

                if(JsonToken.BEGIN_OBJECT.equals(nextToken)){
                    in.beginObject();

                } else if(JsonToken.NAME.equals(nextToken)){

                    if(JsonToken.NAME.name().equals("id")){
                        id = in.nextString();
                        model.setId(id);

                    } else if(JsonToken.NAME.name().equals("type")){
                        String type = in.nextString();
                        model.setMytype(type);

                        switch (type) {
                            case BaseModelType.Employer:
                                EmployerResponse employer = gson.fromJson(in, EmployerResponse.class);
                                model.setEmployer(employer);
                                break;
                        }
                    }
                }
            }
            list.add(model);

            return list;
        }

And i register to my Gson:
  GsonBuilder gsonBuilder = new GsonBuilder();
      gsonBuilder.registerTypeAdapter(IncludeModel.class, new IncludedTypeAdapter());
     //gsonBuilder.registerTypeAdapter(new IncludedTypeAdapter());
      gsonBuilder.serializeNulls();
      Gson gson = gsonBuilder.create();

      return gson;

Which I register on retrofit through GsonConverterFactory.
I am getting:

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 6292 path $.included[0]

which I suspect is because my Retrofit response is <PositionResponse> which is a JsonObject.
To summarize my question: how do I deserialize the List<IncludeModel> object with my own custom type adapter bearing in mind the response type from my Retrofit service is PositionResponse? Many thanks for your patients and answers.

A: It's easy if you're using JSON tree models using JsonDeserializer. Pure type adapters are somewhat an overkill (as well as RuntimeTypeAdapterFactory is, I think, since it's still tree-oriented), and in the most simple case for your JSON document you could use something like this (you can find a similar approach in my yesterday answer having some more explanations, but you case slightly differs).
I'm assuming you would like to have mappings like these:
abstract class Element {

    final String id = null;

    private Element() {
    }

    static final class Address
            extends Element {

        @SerializedName("line-1") final String line1 = null;
        @SerializedName("line-2") final String line2 = null;
        @SerializedName("line-3") final String line3 = null;
        @SerializedName("locality") final String locality = null;
        @SerializedName("region") final String region = null;
        @SerializedName("post-code") final String postCode = null;
        @SerializedName("country") final String country = null;
        @SerializedName("latitude") final String latitude = null;
        @SerializedName("longitude") final String longitude = null;

        private Address() {
        }

        @Override
        public String toString() {
            return country + " " + region;
        }

    }

    static final class Employer
            extends Element {

        @SerializedName("title") final String title = null;
        @SerializedName("first-name") final String firstName = null;
        @SerializedName("last-name") final String lastName = null;

        private Employer() {
        }

        @Override
        public String toString() {
            return title + ' ' + firstName + ' ' + lastName;
        }

    }

    static final class Position
            extends Element {

        @SerializedName("address-id") final String addressId = null;
        @SerializedName("employer-id") final String employerId = null;

        private Position() {
        }

        @Override
        public String toString() {
            return '(' + addressId + ';' + employerId + ')';
        }

    }

}

All you have to do is just:

*

*determine the expected object type;

*"align" the JSON tree (if it fits your needs sure);

*just delegate the deserialization work to Gson via the deserialization context (your example does not do it well: you're instantiating Gson once again losing the original configuration; you redo all Gson can do out of box: lists and POJO by reflection; JsonToken are much better if checked via switch (by the way enums are singletons and it's perfectly legal to compare them using reference equality ==), etc).

So, it can be implemented by something like this:
final class ElementJsonDeserializer
        implements JsonDeserializer<Element> {

    private static final JsonDeserializer<Element> elementJsonDeserializer = new ElementJsonDeserializer();

    private ElementJsonDeserializer() {
    }

    static JsonDeserializer<Element> getElementJsonDeserializer() {
        return elementJsonDeserializer;
    }

    @Override
    public Element deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context)
            throws JsonParseException {
        final JsonObject jsonObject = jsonElement.getAsJsonObject();
        final String typeCode = jsonObject.getAsJsonPrimitive("type").getAsString();
        final Class<? extends Element> clazz;
        switch ( typeCode ) {
        case "address":
            clazz = Element.Address.class;
            break;
        case "employer":
            clazz = Element.Employer.class;
            break;
        case "position":
            clazz = Element.Position.class;
            break;
        default:
            throw new JsonParseException("Unrecognized type: " + typeCode);
        }
        reattach(jsonObject, "attributes");
        return context.deserialize(jsonElement, clazz);
    }

    private static void reattach(final JsonObject parent, final String property) {
        final JsonObject child = parent.getAsJsonObject(property);
        parent.remove(property); // remove after we're sure it's a JSON object
        copyTo(parent, child);
    }

    private static void copyTo(final JsonObject to, final JsonObject from) {
        for ( final Entry<String, JsonElement> e : from.entrySet() ) {
            to.add(e.getKey(), e.getValue());
        }
    }

}

Of course, you can refactor the above to extract a strategy to implement the strategy design pattern to reuse it. Put it all together:
final class Response {

    final List<Element> data = null;
    final List<Element> included = null;

}

(The above one looks like a Map<String, List<Element>> but you decide).
private static final Gson gson = new GsonBuilder()
        .registerTypeAdapter(Element.class, getElementJsonDeserializer())
        .create();

public static void main(final String... args)
        throws IOException {
    try ( final JsonReader jsonReader = getPackageResourceJsonReader(Q43811168.class, "data.json") ) {
        final Response response = gson.fromJson(jsonReader, Response.class);
        dump(response.data);
        dump(response.included);
    }
}

private static void dump(final Iterable<Element> elements) {
    for ( final Element e : elements ) {
        System.out.print(e.getClass().getSimpleName());
        System.out.print(" #");
        System.out.print(e.id);
        System.out.print(": ");
        System.out.println(e);
    }
}

Output:

Position #43: (1;11)
  Address #1: UK London
  Employer #11: Mr S T


text:
Q: prevent absolute file path in Content-Disposition "filename" I have a simple HTML Form
<form id="uploadForm" method="post" action="/cgi-bin/test.cgi" enctype="multipart/form-data">
   <input type="submit" name="add_something" value="add">
   <input size="50" type="file" name="myFile" accept="application/zip">
</form>

In addition I do some web page localization on server side by checking user browser locale or searching for a self set language session cookie.
If I upload a file with

*

*Iron 18.0.1050.0

*Opera 11.64.1403

*Firefox 3.6.27

*Firefox 12.0

*Google Chrome 19.0.1084.52

*SeaMonkey 2.9.1

all works fine. But If I upload a file with

*

*IE 9.0.8112.16421

*Maxton 3.3.8.3000

the localization fails. I detected the issue inside the HTTP request:
Opera 11
Content-Disposition: form-data; name="myFile"; filename="ziptest.zip"
Content-Type: application/zip

and IE 9
Content-Disposition: form-data; name="myFile"; filename="C:\Documents and Settings\m1krsch\Documents\Now Some Spaces\ziptest.zip"
Content-Type: application/x-zip-compressed

If I remove the spaces from the path all works fine in IE and Maxton.
Neighter can I exchange the used cgicc library because it is fixed part of the project nor can I force a user to use a path without spaces. How can I circumvent this issue? Is there a way to force IE/Maxton to use the filename instead of the abolute filepath? Or can I set a specific parameter in cgi/env to prevent transmission of abolute filepath?
[EDIT]
I found out that this is a security issue in IE and Maxton. The security zone model of IE allows by default to "Include local directory path when uploading files". I can disallow this behaviour only by changing the client configuration but I am still searching for an application-based solution.
[/EDIT]

A: Try replacing the spaces with '%20':
"C:\Documents%20and%20Settings\m1krsch\Documents\Now%20Some%20Spaces\ziptest.zip"

A: I found a stupid error in my localization code. I am using RapidXML for this and encapsulate the whole localization code and RapidXML headers in one class. Unfortunately I did not read the documentation very careful. The data inside vector<char> object - which is holding the XML document data - is not copied into the XML document object xml_document<> by using the parse() method as expected. This looks like procedural C code to me and is in my opinion bad OOD. The documentation says:

3.1 Lifetime Of Source Text
In-situ parsing requires that source text lives at least as long as the document object.

The problem vanished when I corrected my code to get a global vector<char> object inside my localization class.
Nevertheless I am perplexed why mostly all other browsers have no problem with my old code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding typedefs for function pointers in C I have always been a bit stumped when I read other peoples' code which had typedefs for pointers to functions with arguments. I recall that it took me a while to get around to such a definition while trying to understand a numerical algorithm written in C a while ago. So, could you share your tips and thoughts on how to write good typedefs for pointers to functions (Do's and Do not's), as to why are they useful and how to understand others' work? Thanks!

A: A function pointer is like any other pointer, but it points to the address of a function instead of the address of data (on heap or stack). Like any pointer, it needs to be typed correctly. Functions are defined by their return value and the types of parameters they accept. So in order to fully describe a function, you must include its return value and the type of each parameter is accepts.
When you typedef such a definition, you give it a 'friendly name' which makes it easier to create and reference pointers using that definition.
So for example assume you have a function:
float doMultiplication (float num1, float num2 ) {
    return num1 * num2; }

then the following typedef:
typedef float(*pt2Func)(float, float);

can be used to point to this doMulitplication function. It is simply defining a pointer to a function which returns a float and takes two parameters, each of type float. This definition has the friendly name pt2Func. Note that pt2Func can point to ANY function which returns a float and takes in 2 floats.
So you can create a pointer which points to the doMultiplication function as follows:
pt2Func *myFnPtr = &doMultiplication;

and you can invoke the function using this pointer as follows:
float result = (*myFnPtr)(2.0, 5.1);

This makes good reading: http://www.newty.de/fpt/index.html

A: This is the simplest example of function pointers and function pointer arrays that I wrote as an exercise.
    typedef double (*pf)(double x);  /*this defines a type pf */

    double f1(double x) { return(x+x);}
    double f2(double x) { return(x*x);}

    pf pa[] = {f1, f2};

    main()
    {
        pf p;

        p = pa[0];
        printf("%f\n", p(3.0));
        p = pa[1];
        printf("%f\n", p(3.0));
    }

A: cdecl is a great tool for deciphering weird syntax like function pointer declarations.  You can use it to generate them as well.
As far as tips for making complicated declarations easier to parse for future maintenance (by yourself or others), I recommend making typedefs of small chunks and using those small pieces as building blocks for larger and more complicated expressions.  For example:
typedef int (*FUNC_TYPE_1)(void);
typedef double (*FUNC_TYPE_2)(void);
typedef FUNC_TYPE_1 (*FUNC_TYPE_3)(FUNC_TYPE_2);

rather than:
typedef int (*(*FUNC_TYPE_3)(double (*)(void)))(void);

cdecl can help you out with this stuff:
cdecl> explain int (*FUNC_TYPE_1)(void)
declare FUNC_TYPE_1 as pointer to function (void) returning int
cdecl> explain double (*FUNC_TYPE_2)(void)
declare FUNC_TYPE_2 as pointer to function (void) returning double
cdecl> declare FUNC_TYPE_3 as pointer to function (pointer to function (void) returning double) returning pointer to function (void) returning int
int (*(*FUNC_TYPE_3)(double (*)(void )))(void )

And is (in fact) exactly how I generated that crazy mess above.

A: A very easy way to understand typedef of function pointer:
int add(int a, int b)
{
    return (a+b);
}

typedef int (*add_integer)(int, int); //declaration of function pointer

int main()
{
    add_integer addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
    int c = addition(11, 11);   //calling function via new variable
    printf("%d",c);
    return 0;
}

A: Consider the signal() function from the C standard:
extern void (*signal(int, void(*)(int)))(int);

Perfectly obscurely obvious - it's a function that takes two arguments, an integer and a pointer to a function that takes an integer as an argument and returns nothing, and it (signal()) returns a pointer to a function that takes an integer as an argument and returns nothing.
If you write:
typedef void (*SignalHandler)(int signum);

then you can instead declare signal() as:
extern  SignalHandler signal(int signum, SignalHandler handler);

This means the same thing, but is usually regarded as somewhat easier to read.  It is clearer that the function takes an int and a SignalHandler and returns a SignalHandler.
It takes a bit of getting used to, though.  The one thing you can't do, though is write a signal handler function using the SignalHandler typedef in the function definition.
I'm still of the old-school that prefers to invoke a function pointer as:
(*functionpointer)(arg1, arg2, ...);

Modern syntax uses just:
functionpointer(arg1, arg2, ...);

I can see why that works - I just prefer to know that I need to look for where the variable is initialized rather than for a function called functionpointer.

Sam commented:

I have seen this explanation before. And then, as is the case now, I think what I didn't get was the connection between the two statements:
    extern void (*signal(int, void()(int)))(int);  /*and*/

    typedef void (*SignalHandler)(int signum);
    extern SignalHandler signal(int signum, SignalHandler handler);

Or, what I want to ask is, what is the underlying concept that one can use to come up with the second version you have? What is the fundamental that connects "SignalHandler" and the first typedef? I think what needs to be explained here is what is typedef is actually doing here.

Let's try again.  The first of these is lifted straight from the C standard - I retyped it, and checked that I had the parentheses right (not until I corrected it - it is a tough cookie to remember).
First of all, remember that typedef introduces an alias for a type.  So, the alias is SignalHandler, and its type is:

a pointer to a function that takes an integer as an argument and returns nothing.

The 'returns nothing' part is spelled void; the argument that is an integer is (I trust) self-explanatory.  The following notation is simply (or not) how C spells pointer to function taking arguments as specified and returning the given type:
type (*function)(argtypes);

After creating the signal handler type, I can use it to declare variables and so on.  For example:
static void alarm_catcher(int signum)
{
    fprintf(stderr, "%s() called (%d)\n", __func__, signum);
}

static void signal_catcher(int signum)
{
    fprintf(stderr, "%s() called (%d) - exiting\n", __func__, signum);
    exit(1);
}

static struct Handlers
{
    int              signum;
    SignalHandler    handler;
} handler[] =
{
    { SIGALRM,   alarm_catcher  },
    { SIGINT,    signal_catcher },
    { SIGQUIT,   signal_catcher },
};

int main(void)
{
    size_t num_handlers = sizeof(handler) / sizeof(handler[0]);
    size_t i;

    for (i = 0; i < num_handlers; i++)
    {
        SignalHandler old_handler = signal(handler[i].signum, SIG_IGN);
        if (old_handler != SIG_IGN)
            old_handler = signal(handler[i].signum, handler[i].handler);
        assert(old_handler == SIG_IGN);
    }

    ...continue with ordinary processing...

    return(EXIT_SUCCESS);
}

Please note How to avoid using printf() in a signal handler?
So, what have we done here - apart from omit 4 standard headers that would be needed to make the code compile cleanly?
The first two functions are functions that take a single integer and return nothing.  One of them actually doesn't return at all thanks to the exit(1); but the other does return after printing a message.  Be aware that the C standard does not permit you to do very much inside a signal handler; POSIX is a bit more generous in what is allowed, but officially does not sanction calling fprintf().  I also print out the signal number that was received.  In the alarm_handler() function, the value will always be SIGALRM as that is the only signal that it is a handler for, but signal_handler() might get SIGINT or SIGQUIT as the signal number because the same function is used for both.
Then I create an array of structures, where each element identifies a signal number and the handler to be installed for that signal.  I've chosen to worry about 3 signals; I'd often worry about SIGHUP, SIGPIPE and SIGTERM too and about whether they are defined (#ifdef conditional compilation), but that just complicates things.  I'd also probably use POSIX sigaction() instead of signal(), but that is another issue; let's stick with what we started with.
The main() function iterates over the list of handlers to be installed.  For each handler, it first calls signal() to find out whether the process is currently ignoring the signal, and while doing so, installs SIG_IGN as the handler, which ensures that the signal stays ignored.  If the signal was not previously being ignored, it then calls signal() again, this time to install the preferred signal handler.  (The other value is presumably SIG_DFL, the default signal handler for the signal.)  Because the first call to 'signal()' set the handler to SIG_IGN and signal() returns the previous error handler, the value of old after the if statement must be SIG_IGN - hence the assertion.  (Well, it could be SIG_ERR if something went dramatically wrong - but then I'd learn about that from the assert firing.)
The program then does its stuff and exits normally.
Note that the name of a function can be regarded as a pointer to a function of the appropriate type.  When you do not apply the function-call parentheses - as in the initializers, for example - the function name becomes a function pointer.  This is also why it is reasonable to invoke functions via the pointertofunction(arg1, arg2) notation; when you see alarm_handler(1), you can consider that alarm_handler is a pointer to the function and therefore alarm_handler(1) is an invocation of a function via a function pointer.
So, thus far, I've shown that a SignalHandler variable is relatively straight-forward to use, as long as you have some of the right type of value to assign to it - which is what the two signal handler functions provide.
Now we get back to the question - how do the two declarations for signal() relate to each other.
Let's review the second declaration:
 extern SignalHandler signal(int signum, SignalHandler handler);

If we changed the function name and the type like this:
 extern double function(int num1, double num2);

you would have no problem interpreting this as a function that takes an int and a double as arguments and returns a double value (would you? maybe you'd better not 'fess up if that is problematic - but maybe you should be cautious about asking questions as hard as this one if it is a problem).
Now, instead of being a double, the signal() function takes a SignalHandler as its second argument, and it returns one as its result.
The mechanics by which that can also be treated as:
extern void (*signal(int signum, void(*handler)(int signum)))(int signum);

are tricky to explain - so I'll probably screw it up.  This time I've given the parameters names - though the names aren't critical.
In general, in C, the declaration mechanism is such that if you write:
type var;

then when you write var it represents a value of the given type.  For example:
int     i;            // i is an int
int    *ip;           // *ip is an int, so ip is a pointer to an integer
int     abs(int val); // abs(-1) is an int, so abs is a (pointer to a)
                      // function returning an int and taking an int argument

In the standard, typedef is treated as a storage class in the grammar, rather like static and extern are storage classes.
typedef void (*SignalHandler)(int signum);

means that when you see a variable of type SignalHandler (say alarm_handler) invoked as:
(*alarm_handler)(-1);

the result has type void - there is no result.  And (*alarm_handler)(-1); is an invocation of alarm_handler() with argument -1.
So, if we declared:
extern SignalHandler alt_signal(void);

it means that:
(*alt_signal)();

represents a void value.  And therefore:
extern void (*alt_signal(void))(int signum);

is equivalent.  Now, signal() is more complex because it not only returns a SignalHandler, it also accepts both an int and a SignalHandler as arguments:
extern void (*signal(int signum, SignalHandler handler))(int signum);

extern void (*signal(int signum, void (*handler)(int signum)))(int signum);

If that still confuses you, I'm not sure how to help - it is still at some levels mysterious to me, but I've grown used to how it works and can therefore tell you that if you stick with it for another 25 years or so, it will become second nature to you (and maybe even a bit quicker if you are clever).

A: int add(int a, int b)
{
  return (a+b);
}
int minus(int a, int b)
{
  return (a-b);
}

typedef int (*math_func)(int, int); //declaration of function pointer

int main()
{
  math_func addition = add;  //typedef assigns a new variable i.e. "addition" to original function "add"
  math_func substract = minus; //typedef assigns a new variable i.e. "substract" to original function "minus"

  int c = addition(11, 11);   //calling function via new variable
  printf("%d\n",c);
  c = substract(11, 5);   //calling function via new variable
  printf("%d",c);
  return 0;
}

Output of this is :
22
6
Note that, same math_func definer has been used for the declaring both the function.
Same approach of typedef may be used for extern struct.(using sturuct in other file.)

A: Use typedef's to define more complicated types i.e function pointers
I will take the example of defining a state-machine in C
    typedef  int (*action_handler_t)(void *ctx, void *data);

now we have defined a type called action_handler that takes two pointers and returns a int
define your state-machine
    typedef struct
    {
      state_t curr_state;   /* Enum for the Current state */
      event_t event;  /* Enum for the event */
      state_t next_state;   /* Enum for the next state */
      action_handler_t event_handler; /* Function-pointer to the action */

     }state_element;

The function pointer to the action looks like a simple type and typedef primarily serves this purpose.
All my event handlers now should adhere to the type defined by action_handler
    int handle_event_a(void *fsm_ctx, void *in_msg );

    int handle_event_b(void *fsm_ctx, void *in_msg );

References:
Expert C programming by Linden

A: What about a macro? I've seen that with a typedef, I cannot cast something to a function pointer. So I made this small macro for it, which is able to do everything I've needed so far (no idea of things it can't be used on - I think it's basically a typedef, but with an optional parameter to make it usable on casts):
#define funcptr_t(sym_name) void (*sym_name)(void)

// Declare a function pointer-returning function, and declare a function pointer variable.
funcptr_t (randomFunction(funcptr_t (func_ptr_variable)));
// Cast a variable to a function pointer
(funcptr_t()) some_variable;

PS: I made this for generic usage, not sure if it could be modified for specific-functions use.


text:
Q: Can you create mutilple columns of data from one controller in VisualForce? I am trying to create a VF page with multiple columns of data from one controller.
Here is the  page so far:. What I need is for each of the Management Types to have it's own column and show all of the status and accounts. I understand I would need 8 columns for each category, and then tow columns under each category to show status and company name. I just cannot figure out if it is even possible. Also, is there a way to make the link on the company name so that it takes you to another vf page showing data for that particular account id, rather than the account page?
Controller:
    public class SortingController{
 // The list of all our accounts has a custom getter to sort immediately
public List<Account> accounts { get {
return sortList(accounts);
} set; }
// The string containing the column to filter by
public String sortBy { get; set; }
// The string containing the direction (ASC, DESC)
public String sortDir { get; set; }
// In the constructor we just define an initial list of accounts
public SortingController()
{
accounts = [Select Id,Name, Overall_Status__c,Account_Management_Type__c from Account where Account_Type_Bucket__c='Customer' order by Account_Management_Type__c] ;
}
public PageReference empty() { return null; }
// The sorting function works on all SObjects sorting on all fields
private List<SObject> sortList(List<SObject> cleanList)
{
// return the clean list if we don't have a sort field defined
if (sortBy == null) { return cleanList; }
// create an empty result List
List<SObject> resultList = new List<SObject>();
// and an object map which will be sorted
Map<Object, List<SObject>> objectMap = new Map<Object, List<SObject>>();
// now loop through the clean list and create the object map
for (SObject item : cleanList) {
if (objectMap.get(item.get(sortBy)) == null) {
objectMap.put(item.get(sortBy), new List<SObject>());
}
objectMap.get(item.get(sortBy)).add(item);
}
// get all the keys from the object map and sort them
List<Object> keys = new List<Object>(objectMap.keySet());
keys.sort();
// now create a result list by adding all objects from the object map
// in the sorted order
for(Object key : keys) {
resultList.addAll(objectMap.get(key));
}
// clear the clean list
cleanList.clear();
// depending on the direction add the items in the correct sorting to the clean list
if (sortDir == 'ASC') {
for (SObject item : resultList) {
cleanList.add(item);
}
} else {
for (Integer i = resultList.size()-1; i >= 0; i--) {
cleanList.add(resultList[i]);
}
}
// return the clean and now sorted list
return cleanList;
}

}

VF Page
<apex:page controller="SortingController">
    <apex:sectionHeader title="Accounts" subtitle="Any Employee, Any Customer, Any Time" />
    <apex:form >
        <apex:pageBlock title="Customer Accounts">
            <apex:pageBlockTable value="{!accounts}" var="account" width="50%">
                <apex:column width="5%">
                    <apex:facet name="header" >
                        <apex:commandLink action="{!empty}">
                            <apex:outputText value="{!$ObjectType.Account.Fields.Account_Management_Type__c.Label}" />
                            <apex:outputText escape="false" rendered="{!sortBy=='Account_Management_Type__c'&&sortDir=='ASC'}">

                            </apex:outputText>
                            <apex:outputText escape="false" rendered="{!sortBy=='Account_Management_Type__c'&&sortDir=='DESC'}">

                            </apex:outputText>
                            <apex:param value="Overall_Status__c" name="column" assignTo="{!sortBy}" />
                            <apex:param value="{!IF(sortDir=='ASC'&&sortBy=='Account_Management_Type__c', 'DESC', 'ASC')}" name="direction" assignTo="{!sortDir}" />
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputLink value="/{!account.Id}" >
                        <apex:outputText value="{!account.Account_Management_Type__c}"/>
                    </apex:outputLink>
                </apex:column>
                <apex:column width="1%">
                    <apex:facet name="header" >
                        <apex:commandLink action="{!empty}">
                            <apex:outputText value="{!$ObjectType.Account.Fields.Overall_Status__c.Label}" />
                            <apex:outputText escape="false" rendered="{!sortBy=='Overall_Status__c'&&sortDir=='ASC'}">

                            </apex:outputText>
                            <apex:outputText escape="false" rendered="{!sortBy=='Overall_Status__c'&&sortDir=='DESC'}">

                            </apex:outputText>
                            <apex:param value="Overall_Status__c" name="column" assignTo="{!sortBy}" />
                            <apex:param value="{!IF(sortDir=='ASC'&&sortBy=='Overall_Status__c', 'DESC', 'ASC')}" name="direction" assignTo="{!sortDir}" />
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputLink value="/{!account.Id}" >
                        <apex:outputText value="{!account.Overall_Status__c}" escape="false"/>
                    </apex:outputLink>
                </apex:column>
               <apex:column width="30%">
                   <apex:facet name="header" >
                       <apex:commandLink action="{!empty}">
                           <apex:outputText value="{!$ObjectType.Account.Fields.Name.Label}" />
                           <apex:outputText escape="false" rendered="{!sortBy=='Name'&&sortDir=='ASC'}">

                           </apex:outputText>
                           <apex:outputText escape="false" rendered="{!sortBy=='Name'&&sortDir=='DESC'}">

                           </apex:outputText>
                           <apex:param value="Name" name="column" assignTo="{!sortBy}" />
                           <apex:param value="{!IF(sortDir=='ASC'&&sortBy=='Name', 'DESC', 'ASC')}" name="direction" assignTo="{!sortDir}" />
                       </apex:commandLink>
                   </apex:facet>
                   <apex:outputLink value="/{!account.Id}" >
                        <apex:outputText value="{!account.Name}" />
                   </apex:outputLink>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
   </apex:form>
</apex:page>

A: You already have a Map<object, List<sObject>> concept in your code. So you could reuse it or build a similar Map<String, List<sObject>> where the key will be Account_Management_Type__c. This would be much easier if this field would be a lookup and not a picklist or whatever it seems to be (you could use subqueries). Anyway - you could "bucket" them per Management Type and store in some helper variable list of types.
Code below shouldn't be a part of your end solution, it's just to demnostrate an idea.
Map<String, List<sObject>> accsBucketedByType = new Map<String, List<sObject>>{
'Key (WIG)' => new List<sObject>(), // assuming you've filled them in your loop
'Active Project' => new List<sObject>(),
'Active Opportunity > $50K' => new List<sObject>(),
'Partner-Managed' => new List<sObject>(),
'TAM-Managed' => new List<sObject>(),
'TSE-Managed' => new List<sObject>(),
'Inactive' => new List<sObject>()
};

You can get all keys of such map with keySet() but you might not like the order they're in and decide to sort them just to be safe.
Set<String> keys = accsBucketedByType.keyset();
System.debug(keys);
List<String> keysAlphabetically = new List<String>();
keysAlphabetically.addAll(keys);
keysAlphabetically.sort();
System.debug(keysAlphabetically);

Finally - Visualforce supports map[key] syntax to access items in maps. So you could have an <apex:repeat> walking on keysAlphabetically variable and within it you could get to the map and list of sobjects to display in the table.

As for your second question: you already have
<apex:outputLink value="/{!account.Id}" >
    <apex:outputText value="{!account.Name}" />
</apex:outputLink>

What you're after is pretty similar, 2 possible ways are
<apex:outputLink value="/apex/somePage?id={!account.Id}" >
    <apex:outputText value="{!account.Name}" />
</apex:outputLink>

or
<apex:outputLink value="/apex/somePage" >
    <apex:param name="id" value="{!account.Id}" />
    <apex:outputText value="{!account.Name}" />
</apex:outputLink>


text:
Q: how to get the record on the basis of certain coditions in sql i need to fetch the record with some condtions from two table
SELECT `tbui`.`user_id`,    `tbui`.`first_name`,`tbui`.`last_name`,`tbui`.`education_level`,`tbui`.`sex`,`tbui`.`country_of_origin`,`tbui`.`city`,`tbui`.`state`,`tbui`.`country`,`tbui`.`occupation`,`tbui`.`about`,TIMESTAMPDIFF(YEAR,`tbui`.`age`,CURDATE()) as age
FROM `tb_preference_dropdown` as `tbpda`
     RIGHT JOIN `tb_user_answers` as `tbua` ON `tbpda`.`question_id` = `tbua`.`question_id`
     RIGHT JOIN `tb_preference_questions` as `tbpa` ON `tbpa`.`user_id` = `tbpda`.`user_id`
     RIGHT JOIN `tb_user_info` as `tbui` ON `tbui`.`user_id` = `tbua`.`user_id`
WHERE `tbpda`.`user_id` = 113
     AND TIMESTAMPDIFF(YEAR,`tbui`.`age`,CURDATE()) >=`tbpa`.`min_age_required` AND TIMESTAMPDIFF(YEAR,`tbui`.`age`,CURDATE()) <= `tbpa`.`max_age_required`
     AND `tbui`.`country_of_origin` = `tbpa`.`country_of_origin`
     AND `tbua`.`user_id` != 113
     AND `tbui`.`sex` != 'Female'
     HAVING SUM(IF(tbpda.question_id = 1,IF(tbpda.answer_id !=0,IF(tbua.question_id =tbpda.question_id AND `tbua`.`answer_id` = tbpda.answer_id,tbua.user_id,''),true),'')) > 0

all the things working perfectly except:
HAVING SUM(IF(tbpda.question_id = 1,IF(tbpda.answer_id !=0,IF(tbua.question_id =tbpda.question_id AND `tbua`.`answer_id` = tbpda.answer_id,tbua.user_id,''),true),'')) > 0

i am getting the records which even don't match with the above condition

A: You are missing GROUP BY clause, re-write the query


text:
Q: What does Θ(deg(u)) mean? I have never heard this before, or maybe I have heard it in other terms?
The context is that for adjacency lists, the time to list all vertices adjacent to u is Θ(deg(u)).
 Similarly, the time to determine whether (u,v)∈ E is O(deg(u)).
If the implementation of the adjacency list is an array, then I assume it would be constant time to find u in the array.
 If all adjacent vertices are linked to u, then I believe it would take O(n) time to list or find all vertices, where n is the number of adjacent vertices.
 Is that essentially what Θ(deg(u)) means?

A: Θ(deg(u)) = Big-Theta of the degree of u = the time is tightly-bounded (bounded from above and below) by the degree of vertices. In the case of an adjacency-list representation of the graph, the degree of a vertex u is |adj[u]| the size of the list for u.
Thus, to iterate over the adjacent vertices of u by an adjacency list is tightly-bound to the number of vertices adjacent to u (algorithmic facts sound redundant sometimes, don't they?).
The difference between Big-O and Big-Theta is that Big-O is an upper bound, whereas Big-Theta states a tight bound from above and below. That is, the same expression serves as a bound, but with a different coefficient m and x0. See the family of Bachmann-Landau notations on wikipedia.

A: I'm pretty sure deg(u) means "the degree of u", i.e. the number of edges that contain u. In an adjacency list representation, that number will also be the size of the adjacency list for u, so iterating it requires Θ(|list|), which is Θ(deg(u)).


text:
Q: Is passing a controller in a construtor always a bad practice? I occasionally instantiate a class from my view controller by passing in the view controller instance itself so that the objects that I create can invoke methods of the controller to update the view.
Is that always, often, or never a bad practice?
Concretely:
ViewController.h has
-(void)updateButtonValue:(NSString*)value;

MyObject.h has
-(id)initWithViewController:(ViewController*)aViewController;

I instantiate that class from my view controller with:
[[MyObject alloc] initWithViewController:self];

thus allowing that MyObject instance to update a button value in my view by a simple call like:
MyObject.m
[self.viewController updateButtonValue:@"example"];

It does not seem ideal since I am passing to MyObject much more (the view controller itself) than it should need, but it is certainly quick and functional.  If there is a cleaner approach, such as relying on protocols, that is also succinct, a brief code sample would be much appreciated.

A: It is always bad practice to pass a class-typed pointer in, as you are tightly coupling your objects together (each object needs to know the class of the other, they might as well be a single object). This is what the delegate pattern is for. It minimises the info MyObject needs (minimally, nothing more than a pointer type id - preferably, a protocol specified by MyObject to offer it some behavioural guarantees)
So to translate your example
MyObject.h
replace...
-(id)initWithViewController:(ViewController*)aViewController;

with...
-(id) init;

(which you can dispense with if you have no further reason to override)
and...
@property (nonatomic, weak) id delegate;

Instantiation in myViewController (which does need to #include MyObject) ...
MyObject* object = [[MyObject alloc] init];

Followed by
object.delegate = self;

(Note that object gets a pointer to myViewController without needing to know anything else about it)
Now you can do this from inside object:
 [self.delegate updateButtonValue:@"example"];

However ... you will want to ensure that your delegate can receive the message updateButtonValue:
To do this, you declare a protocol in MyObject.h with the signature of this method
@protocol MyObjectDelegate

  - (void) updateButtonValue:(NSString*)string;

@end

And in your viewController, declare that you conform to this protocol using <> in the interface line
@interface ViewController <MyObjectDelegate>

(this is no big deal, ViewController already has to #include MyObject to alloc/init it, so needs no more info to do this)
And expand your property declaration thus:
@property (nonatomic, weak) id <MyObjectDelegate> delegate

Now you have given the compiler enough information for it to ensure that you can only pass conformant messages around. The brilliant thing here is that MyObject can confidently pass messages to MyViewController without needing to know anything about MyViewController other than that it is reached via the delegate pointer.


text: Q: EMTYFILE flag location During execution of a DBCC SHRINKFILE ('file_name' , EMPTYFILE) command is there any kind of flag in a DMV, DBCC or other monitoring tool that reflects that no data should be written to 'file_name'?


text:
Q: Issue with Apex Charts rendering twice with Vue 3 I am using Apex Charts with Vue 3. When the chart renders (draws), its rendering twice. The weird thing is, the second chart is removed from the DOM as soon as I resize or move the browser window. I've also double checked my Vue components to make sure I am not importing this chart component twice.
<template>

<apexchart
  width="500"
  height="400"
  type="bar"
  :options="chartOptions"
  :series="series">
</apexchart>

</template>

<script>

import VueApexCharts from "vue3-apexcharts";

export default {
    name: 'ChartExample',
    components: {
        apexchart: VueApexCharts
    },
    data() {
        return {
            chartOptions: {
                chart: {
                    id: "vuechart-example",
                },
                xaxis: {
                    // categories loaded here
                },
            },
            series: [
                // data loaded here
            ],
        };
    },
    mounted() {
        this.series = [
            {
            name: 'precip',
            data: [1,2,3,4,5],
            }
        ];
        this.chartOptions.xaxis = {
            categories: [1,2,3,4,5],
        }
    }
}

</script>

I'm passing in the data in the mounted hook because I plan on passing in dynamic data. When I add static data directly in the chart options (i.e. not passed in from the mounted hook), the chart is rendered once and works correctly. Any help would be appreciated.

A: After doing some research I've found this is a known bug in apex charts with Vue3.
https://github.com/apexcharts/vue3-apexcharts/issues/3
The only solution that worked for me is this.
mounted() {
    this.$nextTick(() => {
        window.dispatchEvent(new Event('resize'));
    });
}

A: Well the solution that is present above nextTick() it works but it's not feasible and it's a bad solution.
I have implemented a solution which is better than nextTick().
Just add a key attribute ":key='Series.length'" to your component i.e
      `<chart
          width="100%"
          :options="GraphOptions"
          :series="Series.length > 0 ? Series : []"
          :key="Series.length"
          @mounted="ChartLoaded = true"
        ></chart>`

Issue will be resolved


text:
Q: How do I show that the set of natural number N has the same size as NxN? How do I show that the set of natural numbers $\mathbb{N}$ has the same size as $\mathbb{N}\times\mathbb{N}$?
I know that for two sets to have the same size, there must be an injection from the set $\mathbb{N}$ to the set $\mathbb{N}\times\mathbb{N}$ and there must be and injection from the set $\mathbb{N}\times\mathbb{N}$ to the set $\mathbb{N}$.
But I have no idea on how to prove this.

A: Take any $n\in\Bbb N$.
One can find $n_1$ and $n_2$ such that $ n = 2^{n_1}n_2$.
Essentially,it extracts the odd and even part of $n$.
So, $n_1$ and $n_2$ are unique.
Hence by this one can find a bijection from $\Bbb N$ to $\Bbb N \times (\Bbb N\setminus 2\Bbb N)$
$\Bbb N\setminus 2\Bbb N$ is the set of all odd integers.
Now, since $\Bbb N$ is equinumerous to $\Bbb N\setminus 2\Bbb N$.(Argue)
So, $\Bbb N$ and $\Bbb N\times\Bbb N$ are equinumerous.

A: The maps $(m,n)\mapsto 2^m\cdot 3^n$ and $n\mapsto (n,0)$ are injections. Now we may apply the Schröder–Bernstein theorem.

A: You can do this in many ways. Here is one:
First get all pairs of numbers with sum 0, then with sum 1, then sum 2, etc.:
So:
(0,0), (0,1), (1,0), (0,2), (1,1), (2,0), (0,3), (1,2), (2,1), (3,0), etc.
Notice that for every sum $i$, there are only finitely many ($i+1$ to be exact) pairs $(m,n)$ that have that sum, meaning that for every number $i$, you will get to all the pairs with sum $i$, and since every pair of numbers $(m,n)$ has a finite sum $i$, it is bound to appear somewhere on this list.
And now that you have a list, you have a one to one mapping:
1<->(0,0)
2<->(0,1)
3<->(1,0)
4<->(0,2)
etc.

A: What you can also do is find a bijection between the two sets.
Consider the function:$$f: \mathbb{N} \rightarrow \mathbb{N} \times \mathbb{N}$$
$$f(x)\begin{cases}
      (\frac{m+n-1}{2}+n):if\ m+n-1 \ is \ odd\\
      ({\frac{m+n-1}{2}}+m)  : if\ m+n-1 \ is \ even \\
        \end{cases}$$
Try to make a graph, and check that is indeed a bijection.
(if you are unsure about the bijection rule, if $f$ is a bijection, then $f^{-1}$ exists, and it is also a bijection, so you have two injections you required)


text:
Q: HttpHandler not rewriting I am writing a simple HttpHandler for URL rewriting, but I'm hitting a brick wall.
I have created a HttpHandler class that's really simple just to test things:
public class HttpHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.RewritePath("default.aspx", false);
        //Rewriter.Rewrite(context);
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

I then have the following verb in the web.config:
<httpHandlers>
  <add verb="*" path="*" type="Tizma.CMS.Runtime.HttpHandler"/>
</httpHandlers>

I basically want all incoming URL's to go through this rewritter. When I run this, ProcessRequest fires, but the RewritePath never gets to default.aspx.
Please bare in mind this is just a test and eventually default.aspx will be passed a query string along the lines of ?pageid=2 I just wanted to figure out how httphandlers worked first.
What am I doing wrong?

A: By using a HttpHandler, you're overriding the whole Web Forms mechanism for handling requests (System.Web.UI.Page implements IHttpHandler).  In your machine-level web.config file, you'll find
<add path="*.aspx" verb="*" type="System.Web.UI.PageHandlerFactory" validate="true"/>

Rewriting the URL to default.aspx won't achieve much, because your web.config overrides that default handler mapping and says that your HttpHandler should be called to handle all URLs, including default.aspx.
You want a HttpModule, most likely handling the BeginRequest event. A HttpModule can handle individual events through the request lifecycle without overriding all of the standard behaviour.

A: Andy - you can't call RewritePath() in a handler - it's way to late for that at that time. By the time you hit your handler the request has already routed to completion and RewritePath() doesn't do anything.
RewritePath must be called very early in the request cycle (like BeginRequest or anything before the CacheModule kicks in) to be effective so you most likely need an HttpModule and hook the appropriate early pipeline event.

A: You can try "http://urlrewriter.net/". It has what you require as an out of the box solution.
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

A: What do you expect to see?  RewritePath changes the path internally without showing a different URL to the user.  If default.aspx is called, then it's working.


text:
Q: making a list of dates and stock prices into a dictionary using date as a key and converting prices into floats-python I am creating a program where the user enters a file name. The file apple.dat has all the dates and stock prices apple. Right now I have all the data into one list. I need some help getting the list into a dictionary and using date (keep as string) as the key and making the stock prices into float values.
apple.dat file
Date,Open,High,Low,Close,Adj Close,Volume
2020-01-02,74.059998,75.150002,73.797501,75.087502,74.333511,135480400
2020-01-03,74.287498,75.144997,74.125000,74.357498,73.610840,146322800

output I get
['2020-01-02,74.059998,75.150002,73.797501,75.087502,74.333511,135480400\n', '2020-01-03,74.287498,75.144997,74.125000,74.357498,73.610840,146322800\n'...]

code
def createdict(file_name):
  with open('apple.dat','r') as f:
    lines = f.readlines()[1:]
  return lines

def main():
  print("Welcome to the Stock Price Program")
  print()
  file_name=input("Enter the data file name: ")

  list=createdict(file_name)
  print(list)

A: Try to adapt this solution for your problem.
import csv

def dict_date(file):
    dict1={}
    with open(file,'r') as file:
        for i in csv.DictReader(file):
            date=i.get('Date')
            i.pop('Date')
            row=i
            dict1[date]=row
    return dict1
file='t.csv'
res=dict_date(file)
print(res)
# {'2020-01-02': {'Open': '74.059998', 'High': '75.150002', 'Low': '73.797501', 'Close': '75.087502', 'Adj Close': '74.333511', 'Volume': '135480400'}, '2020-01-03': {'Open': '74.287498', 'High': '75.144997', 'Low': '74.125000', 'Close': '74.357498', 'Adj Close': '73.610840', 'Volume': '146322800'}}

A: Here's an approach using the csv library (specifically the DictReader constructor). It makes the solution simpler to address the fieldnames by name rather than addressing them by column number.
import csv

apl_stk = list()

with open('apple.dat', 'r') as f:
    reader = csv.DictReader(f)

    for dictionary in reader:
        apl_stk.append(dictionary)

def avg(L, field):
    return sum(map(lambda x: float(x[field]), L)) / len(L)

def minimum(L, field):
    return min(map(lambda x: float(x[field]), L))

print(f"Avg. high: {avg(apl_stk, 'High'):.6f}")
print('minimum open:', minimum(apl_stk, 'Open'))

For your sample input data, this prints:
Avg. high: 75.147500
minimum open: 74.059998


text:
Q: Drag & Drop using Dropzone and Seaside I'm struggling a little with the dropzone implementation for dragging/dropping files. I am developing on a Smalltalk platform with Seaside on the front end. Currently, I am able to upload a file but unable to see the success icon as well as the progress bar appear at the time of upload. When I inspect elements on the web, I do see that the divs representing the success/progress are present. I do see the file size and file name appear just as the file gets dropped in. Can someone point out what I'm missing? My code is as follows:
| serverURL url |

serverURL := RepWebSettings portalSettingsWebServerURL ifNil: [self session requestContext request uri serverURL].
url := serverURL ,
        html context actionUrl printString ,
         '&' , (html callbacks store: (Seaside.WAValueCallback on: [self uploadFileDroppedFiles])).

html div class: 'layoutBorder'; with: [
    html div id: 'draganddropupload'; class: 'dropzone';
        with: [
            html div class: 'dz-message'; with: [
                html image url: RepWebFileLibrary / #draganddropPng]]].

html script: ('
    $(document).ready(function () {
        Dropzone.autoDiscover = false;
        Dropzone.uploadMultiple = true;
        Dropzone.createImageThumbnails = false;
        $("#draganddropupload").dropzone({
            url: "%1",
            success: function (file, response) {
                document.location.reload(true);
            }
        });
    });' bindWith: url).

A: When you run your example with Chrome's Developer Tools opened to the 'Console' tab what javascript errors do you see?  Seems like Dropzone manages the progress bar and checkmark.
From looking at their simple example:
https://github.com/enyo/dropzone/blob/gh-pages/examples/simple.html
The only difference between what you've got and what they've got is that they're using a 'form' tag with the 'dropzone' class and you're using a 'div' tag.
So, it may be that Dropzone expects to operate in a 'form' and without any other inputs in that form.  So if it were me I'd change that div tag in your seaside code to a form, and make sure the new form wasn't nested inside another form on the page.


text:
Q: Should unit of work create repository? Our "unit of work" class has a method which takes a class type and creates a repository:
public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
        {
            var repoItem = _repositoryList.FirstOrDefault(cv => cv.GetType().IsGenericType && cv.GetType().GetGenericArguments()[0] == typeof(TEntity));
            if (repoItem == null)
            {
                repoItem = new Repository<TEntity, object>(Context);
                _repositoryList.Add(repoItem);
            }
            return repoItem as IRepository<TEntity>;
        }

For me, it looks very strange because the unit of work is not DI.
I tried to explain it to my team, but they always say "all examples of unit of work contain concrete classes, or properties/methods which can create and return repositories."
But my opinion about a "unit of work" is, it should know only what repositories exist, and when I call Savechanges, it should save the entities in all these repositories.
Now our services contructors takes only UnitOfWork, but my opinion is, it should take also the repository interfaces. Because UnitOfWork shouldn't be a God class which can do anything.
Do you have some good explanation why it is wrong\right?

A: The immediate problem I see here that it becomes hard to unit test the "UnitOfWork" with mock repositories. What if the line
    repoItem = new Repository<TEntity, object>(Context);

needs to be replaced by  ... new MockRepository for a meaningful test?
So in case UnitOfWork just needs one or two, maybe 3 repos, you could try to inject them in the UnitOfWork constructor. If it needs more, but the repos can be instantiated beforehand, then you could also try to inject the filled _repositoryList beforehand, without extending it in UnitOfWork.
However, if your UnitOfWork is really so complex it requires to utilize lots of different repo classes, and creating the repos should be done only "on demand" (as shown in your example), then I would try the following: create a new class RepositoryFactory which encapsulates _repositoryList, refactor GetRepository to this new class, and inject an object of type IRepositoryFactory into the UnitOfWork. That gives you the necessary separation of reponsibilities, and will allow to inject a MockRepositoryFactory for a unit test.


text:
Q: Pesquisar em um form e trazer o retorno para o form que chamou no meu projeto da faculdade estou fazendo o cadastro de produtos ta tudo certinho o meu problema é carregar o fornecedor no cadastro de produto.
criei um form frmCadastroProduto e um Form frmCadastroFornrcedor no cadastro de produto quando clico em pesquisar o fornecedor abre uma tela de pesquisa e não consigo trazer de volta o fornecedor que selecionei alguém poderia me dar uma força.  Windows Form 4 camadas
segue a baixo
Cadastro de Produto

código
  private void pctLocalizaFornecedor_Click(object sender, EventArgs e)
    {
        frmPesquisarFornecedor pesqFornec = new frmPesquisarFornecedor(this);

        pesqFornec.Show();

    }

Pesquisar Fornecedor

Código   o que esta comentado foi o que tentei mais não deu certo
   public partial class frmPesquisarFornecedor : Form
{

 //   private int CodFornec;
    //private Form codFornecedor;

    frmCadastroPecas codFornecedor;

    public frmPesquisarFornecedor()
    {
        InitializeComponent();
    }

    public frmPesquisarFornecedor(frmCadastroPecas fm1)
    {
        InitializeComponent();

        codFornecedor = fm1;
        //tbxTextBoxFormB.Text = instanciaDoForm1.tbxTextBoxFormA.Text.ToString();

    }

    //public frmPesquisarFornecedor(int codFornec)
    //{
    //    InitializeComponent();

    //    CodFornec = codFornec;

    //}

    private void frmPesquisarFornecedor_Load(object sender, EventArgs e)
    {
        CarregaGrid();

    }

    #region Carregar o Grid Fornecedor
    private void CarregaGrid()
    {
        try
        {
            IList<FornecedorDTO> listaFornecDTO = new List<FornecedorDTO>();

            listaFornecDTO = new FornecedorModel().CargaFornecedor();// Cria uma estancia do Objeto UsuarioModel
            dgvFornecedor.AutoGenerateColumns = false;// Não vai gerar colunas automaticamente
            dgvFornecedor.DataSource = listaFornecDTO;// carrega o meu grid DataSource ListaUsuarioDTO

        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message);
        }
    }

    #endregion

    private void frmPesquisarFornecedor_FormClosed(object sender, FormClosedEventArgs e)
    {
        frmCadastroPecas obj = new frmCadastroPecas();

      //  obj.codForn = Convert.ToInt32(txtCodigoFornec.Text);
    }

    private void dgvFornecedor_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        int sel = dgvFornecedor.CurrentRow.Index;

        txtCodigoFornec.Text = Convert.ToString(dgvFornecedor["Codigo", sel].Value);
        txtRazaoSocial.Text = Convert.ToString(dgvFornecedor["NomeRazao", sel].Value);
        txtNomeFantasia.Text = Convert.ToString(dgvFornecedor["NomeFantasia", sel].Value);

    }

    private void btnOk_Click(object sender, EventArgs e)
    {
        //PesqFornecDTO objFornec = new PesqFornecDTO();

        //objFornec.Codigo = Convert.ToInt32(txtCodigoFornec.Text);

        //frmCadastroPecas obj = new frmCadastroPecas();
        //obj.codForn = Convert.ToInt32(txtCodigoFornec.Text);

       frmCadastroPecas obj = new frmCadastroPecas();

      //  obj.codForn = Convert.ToInt32(txtCodigoFornec.Text);

    }

}

}
Classe FornecedorDTO
public class FornecedorDTO:PessoaDTO
{
    private int codigo;
    private Double vlMinCompra;
    private String telefone2;
    private String contato;
    private int ramal;
    private String userConectado;

    #region Getters e Setters
    public int Codigo
    {
        get { return codigo; }
        set { codigo = value; }
    }

    public String Telefone2
    {
        get { return telefone2; }
        set { telefone2 = value; }
    }
    public String Contato
    {
        get { return contato; }
        set { contato = value; }
    }

    public Double VlMinCompra
    {
        get { return vlMinCompra; }
        set { vlMinCompra = value; }
    }

    public int Ramal
    {
        get { return ramal; }
        set { ramal = value; }
    }

    public String UserConectado
    {
        get { return userConectado; }
        set { userConectado = value; }
    }

na tela de pesquisa esta certo

na tela de peça não esta entrabndo no IF if (retorno == DialogResult.OK)

pq. será ?

A: Opá beleza! Tente algo parecido com isso:
//--- frmPesquisarFornecedor ---
// crie propriedades publicas para retorná-las para frmCadastroDeProduto
public int RetornoCodigo {get;set;}
public string RetornoRazaoSocial {get;set;}
// é assim por diante...

//--- frmPesquisarFornecedor ---
private void btnOk_Click(object sender,EventArgs e)
{
    this.RetornoCodigo = this.txtCodFornecedorPesquisa.text; // <-- ex: pegando diretamente do textbox
    this.RetornoRazaoSocial = Convert.ToString(dgvFornecedor["NomeRazao", sel].Value); // <-- pegando da grid
    this.DialogResult = DialogResult.OK; // <-- tem que retornar [OK], para passar no if
    this.Close();
}

//--- frmCadastroDeProduto ---
private void pctLocalizaFornecedor_Click(object sender, EventArgs e)
{
    using (var form = new frmPesquisarFornecedor())
    {
        var retorno = form.ShowDialog(); // <-- aqui está a magia :D
        if (retorno == DialogResult.OK)
        {
            // os valores vinham como retorno do form assim que ele for fechado
            int codigo = form.RetornoCodigo;
            string razaoSocial = form.RetornoRazaoSocial;

            // assim facilmente pode atribuir á um controle ex:
            this.txtCodigoFornecedor.Text = codigo;
        }
    }
}


text:
Q: Ruby how to assign a model association to multiple model objects I have looked around at questions and have only found what to do if I want to assign an object to multiple models (polymorphic). Basically, I have two models (Day and Schedule) that I want to connect with an association. The problem is that I want to have several Days be able to have a single Schedule:
(day1.schedule == schedule1, day2.schedule == schedule1)
I was using a polymorphic association (I thought it was what I was trying to do), and it was working, but I discovered that it was assigning Day information to imageable for Schedule every time I assigned the Schedule to a Day:
(schedule1.imageable == day2, schedule1.imageable_id == day2.id, schedule.imageable_type == Day)
It's unnecessary information (that will be incorrect if the Day no longer exists) that I don't want Schedule to save, but if I remove as: :imageable, it breaks and I can't .
I basically need a one-way association, and I haven't been able to figure out how to set one up. I want Days to save Schedules, but Schedules to not save anything about Days. Is there an association or am I going to be forced to use the Schedule id instead?
class Day < ApplicationRecord**

    has_one :schedule, as: :imageable

    validates :day, presence: true

    def after_initialize( args = {} )
        @day = args[:day]
        @schedule = args[:schedule]
    end
end

There's nothing in my Schedule class that has anything to do with Day. It's automatically creating an imageable_id and imageable_type method (although I did have to create columns for it in my db)

A: If I understand you correctly, you just need Schedule has_many :days :
class Schedule < ApplicationRecord
  has_many :days
end

class Day < ApplicationRecord
  belongs_to :schedule
end

This way, Schedule won't save anything about days : the information about the relationship will be saved in the schedule_id column of the days table.
Here's the corresponding documentation.


text:
Q: How to get related model's field's value in django I am trying to get user's gender who is in room between start_date and end_date range here is models.py
 class Profile(models.Model):
    MALE = 'M'
    FEMALE = 'F'
    GENDER_CHOICES = (
        (MALE, u'ere'),
        (FEMALE, u'eme')
    )

    FOOD_TYPE = (
        ('Veg', 'Vegeterian'),
        ('Green', 'Green')
    )
    user = models.OneToOneField(User, related_name="profile", null=True)
    firstname = models.CharField(max_length=50, null=True)
    lastname = models.CharField(max_length=50, null=True)
    phone1 = models.CharField(max_length=50, null=True)
    phone2 = models.CharField(max_length=50, null=True, blank=True)
    birthdate = models.DateField(blank=True, null=True)
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True)
    emd_number = models.CharField(max_length=10, null=True)
    special_situation = models.IntegerField(choices=SITUATION_CHOICES, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    email = models.EmailField(blank=True, null=True)
    city = models.CharField(max_length=20, blank=True)
    food_type = models.CharField(max_length=50, choices=FOOD_TYPE, blank=True)

    def __unicode__(self):
        return self.user.username

class Room(models.Model):
    number = models.CharField(max_length=8, null=True)
    category = models.ForeignKey(RoomCategory, related_name="rooms")
    beds = models.PositiveIntegerField(null=True)
    description = models.TextField(blank=True)
    size = models.CharField(max_length=2, blank=True)

    def __unicode__(self):
        return self.number

class Reservation(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    transport_type = models.CharField(max_length=8, blank=True)
    start_date = models.DateField(null=True)
    end_date = models.DateField(null=True)
    total_days = models.PositiveIntegerField(null=True, blank=True)
    arrival_date = models.DateField(null=True, blank=True)
    user = models.ForeignKey(User, related_name="customers")
    room = models.ForeignKey(Room, related_name="reservations")
    total_payment = models.PositiveIntegerField(null=True, blank=True)
    total_paid = models.PositiveIntegerField(null=True, blank=True)

currently i get the rooms by this query below:
queryset = Room.objects.all()
if start_date && end_date:
    queryset = queryset.exclude(reservations__start_date__range=[start_date, end_date], reservations__end_date__range=[start_date, end_date])

how to get user's gender who is in room between dates

A: You can check like,
for reservetion in Reservation.objects.filter(room__in=queryset):
     print reservation.user.gender

A: @Adaikalaraj how to append user gender in get_queryset method?
class RoomList(ListAPIView):
    """ Listing all room """
    serializer_class = RoomSerializer

    def get_queryset(self):
        queryset = Room.objects.all()
        start_date = self.request.query_params.get('start_date', None) #date string
        end_date = self.request.query_params.get('end_date', None)  #date string
        if start_date and end_date:
            queryset = queryset.exclude(reservations__start_date__range=[start_date, end_date], reservations__end_date__range=[start_date, end_date])
        return queryset


text:
Q: Make UITableView tableHeaderView clear, with all other cells white My UITableView spans the the size of the iPhone view, with a tableHeaderView holding additional content. Wanting the header to be clear and the rest of the table white, I set the background colour of the table to clear, and inside the view delegate method -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath I set the cell's background to white.
This takes care of the cells with content, but there's now another problem: data for my table doesn't extend to the bottom, so there are a number of cell spaces that are clear.
I'm just looking for a clear tableHeaderView and white cells. Am I approaching this wrong? Setting the table background to white and the headerView to clear doesn't solve it.

A: Here is a work around which seems to at least work well enough:

*

*Set the background colour of the UITableView to clear.

*Set the background colour of cells to white in delegate method - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

*Return a UIView with clear background as the header view.

*Return a UIView with white background as the footer view and dynamically adjust its height with respect to the number of cells you have. That is, tableView.frame.size.height - (rowHeight * numberOfRows + headerHeight)

A: I have another idea that I tried today and works. I made my tableView's background colour as [UIColor clearColor] and I put a scroll view behind the header view. My solution is to make sure that the scroll view that I have behind my table header view has clipsToBounds set as YES.


text:
Q: Antiquated appellations for marks of punctuation I was in the mood for A room with a view last night, and I came across the expression "note of interrogation" for "question mark," which I found quite pleasing.  It seems "note of exclamation" has also been used for "exclamation mark."  As far as I know, these are no longer in vulgar usage.  For instance, these terms are not even mentioned on the Wikipedia entries for these marks.

Did the punctuation marks now called period/full stop, comma and quotation marks/inverted commas commonly go by other names that have since fallen out of fashion? (let us say, go by names that are not listed in the first part of their Wikipedia entries)

Note: I would also be interested in antiquated terms for other punctuation marks, but will not make that part of the question proper.  I presume there is none for semicolon (at least in English), since that appears to have come to us straight from Greek.

A: A few possibilities found in the Oxford English Dictionary:
Interstinctive point: Not a particular mark, but rather an obsolete synonym for punctuation mark. The OED's sole attestation is from 1696.
Interpunction: Again, not a particular piece of punctuation, but a synonym for punctuation itself. Attested from the early 1600s to late 1800s.
Punctum: A full stop/period until the 19th century (still used in medicine and possibly some other specialized fields with other definitions).
Subdistinction: Used for both a comma and semi-colon (and apparently sometimes for both as a class) in the 16th and 17th centuries.
Also, apparently full point was originally used where today we would use full stop; this one is attested all the way to 1995, however, and the use of point for various punctuation marks (exclamation point, most notably) is still current, so I don't know whether it meets your criteria for obsolescence.
So, if you were in the mood for anachronism, you could tell someone

Your interpunction is atrocious! You don't know your puncta from your subdistinctions, and very often you leave out interstinctive points altogether!

A: Because the discussion of early punctuation mark nomenclature in Vivian Salmon,  "Orthography and Punctuation," in Roger Lass, ed., The Cambridge History of the English Language, volume 3: 1476–1776 (1999) is so interesting, I've decided to supplement my comment above by quoting from it at greater length.
Salmon offers these comments about the nomenclature devised by John Hart, in one of the earliest English-language discussions of punctuation:

By this time [1561], however, John Hart had set out his views in his 1551 manuscript, 'The opening of the unreasonable writing of our Inglish toung', where he remarked that the function of 'distinction or pointing' (1955[1551]: 157) is to teach us 'how to rest and stay, how to understand what is added and is not neadful to the sentence, and what some translater or new writer of a worke, doth ad more then the authour at first wrate, also what sentence is asking and what is wondring'. There are seven marks listed by Hart in his chapter on pointing, including comma (or incisum), colon (a 'joint'), period ('point'), question mark (the asker'), and exclamation mark (the 'wonderer') but not the semicolon; he discusses the function of comma, colon and period in terms which are both rhetorical, marking pause, and syntactic, marking of word groups.

It thus appears that sharp observers from Hart forward have recognized punctuation as partaking of a duality of purpose that combines rhetoric and syntax; it reminds me of discussions of light that treat it as both particle and wave. Salmon continues:

Hart describes the function of round brackets (the 'clozer') as 'to put souch a sentence in a writing as mough be left out, and the rest of the matter remaine a good sentence' (160) while 'notes', or square brackets, are used for marking 'translations, commentaries or expositions'. He then adds to the list of seven punctuation marks (in an unnumbered chapter 13) the apostrophe or 'tourner', with a somewhat laboured illustration of its use in marking omissions (161–2). He ends this chapter with a reminder that 'great' or capital letters should be used at the beginning of every sentence, whether after the 'full point', the 'wonderer' or the 'asker', ... In chapter 10 on 'thaccents' he discusses the hyphen, which he calls the 'joiner', and the dieresis, or, as he calls it, the 'sondrer' (153, 155). ... In his first published treatise, An Orthographie, Hart repeats his comments on punctuation in more succinct form (1569: fo. 45 v.); but now he uses the terms 'interrogatiue' and 'admiratiue' rather than 'asker' and 'wonderer', proposing that these punctuation marks should be used before rather than after, the sentence 'bicause their tunes do differ from our other maner of pronunciation at the beginning of the sentence'.

In a later section on "the printed word" (that is, on punctuation for printing press use), Salmon resumes her discussion of early punctuation terminology:

When printing made individual reading more widely practised, the three marks indicating pauses, comma, colon, and period, were still apparently regarded as having the same function; this belief is clearly indicated by the name given to these pauses in another early grammar (Clement 1587: 25) who named them the vnderpause, the middle pause and the perfect pause. ...
... The next addition to the printers' regular stock of punctuation marks was the semicolon, used with increasing frequency in English texts after about 1580, although its nomenclature remained doubtful for many decades. Jonson (1640) called the actual mark a sub-distinction, apparently meaning a pause shorter than that of a comma. Daines (1640) described it as a comma-colon, Brooksbank (1654) named it a hemi-colon and Lewis (1672) a sub-colon.

Finally, in a discussion of late seventeenth-century and early eighteenth-century punctuation, Salmon has this note:

[John] Jones also gives unusually full directions for the use of 'turned double commas', the punctuation for which he uses the modern term Quotation Mark (1701: 143–4), explaining that " must be used at the beginning of every line, though not apparently at the end of the quotation. ...
In 1661, nearly all the punctuation marks in common use now were known, but there were some differences in form and function. Quotation marks are used by the end of the period to enclose short passages, with 'turned' or 'reversed' commas (Watts 1721: 43) at the beginning and raised commas at the end.

To sum up, Vivian Salmon gives the following alternative or earlier names for modern punctuation marks, as used by various writers on orthography and punctuation between 1561 and 1771 (not all of these names are mentioned in the excerpts I've quoted above):

*

*period: point, full point, perfect pause

*comma: incisum, vnderpause

*colon: joint, middle pause

*semicolon: sub-distinction, comma-colon, hemi-colon, sub-colon

*hyphen: joiner

*dieresis: sondrer

*question mark: asker, interrogatiue, note of interrogation

*exclamation point wonderer, admiratiue, note of admiration

*apostrophe: tourner

*quotation marks: double commas, inverted commas, turned commas, turned double commas, reversed commas

*round brackets: clozer

*square brackets: notes, crotchets


text:
Q: Android: How is the row id assigned to a ListView I want to show different message when tapping on a listview item, could anyone help me understand how I can explicitly bind a specific column (e.x., room_id) to the list view so that the id in the onItemClick takes the room_id.
listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,long id) {

        }
    });

Any help will be greatly appreciated!

A: in list view, you have to pass list of objects as it's arguments.
listview = (ListView) findViewById(android.R.id.list);
adapter = new YourCustomeAdapter(this, rowItems);
listview.setAdapter(adapter);

Here rowItems is your list of objects.
in the setOnItemClickListener method, you will obtain each object of the rowItem list by using the position.

A: I think this is related to your adapter (that you pass to listView.setAdapter() )
You have to implement these methods (of your adapter) correctly.
    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

And you will be able to get current id directly OR your object (and its id if its a property)
listView.setOnItemClickListener(new OnItemClickListener() {
   @Override public void onItemClick(AdapterView parent, View view, int position,long id)     {
       ListView lv = (ListView) parent;
       YOUR_OBJECT yourItem = (YOUR_OBJECT) parent.getSelectedItem();
    }
});

A: listView.setOnItemClickListener(new OnItemClickListener() {
 @Override
   public void   onItemClick(AdapterView parent, View view, int position,long id) {

  }
});

In my cases,int position and long id both gives the same value ie. if first item in list view is clicked, the value of position and id in OnItemClick() is 0 which ultimately gives you the index of the column room_id. So you can explicitly bind the specific column (e.x., room_id) to the list view so that the id in the onItemClick() takes the room_id.


text:
Q: JS DynamoDB to React Prop This will be a simple async issue for some but i've struggled with this for a while.
How can I send the output data object from a DynamoDB document client get as a prop? I'm having scope / context issues which I usually wouldn't.
var docClient = new AWS.DynamoDB.DocumentClient()

//not how i'm actually doing it but i've tried so many ways.
render(){
function myJect(stuff){
    var x;
    docClient.get(params, function(err, data){
        x = data.Item.title;
        stuff(x);
    });
  }
function myExt (c){
    this.setState({
        fish: c
    });
}
myJect(MyExt);

return (
  <div>
    <List pug={this.state.fish} />
  </div>


text:
Q: liferay 5.2 ldap login method check users in only specifics group I used liferay 5.2 and I can integrate ldap correctly with  liferay and I activated ldap in login.
and I arrived to import only users from ldap wich exists in my groups using this configuration :

my problem now is when I try to login in liferay
it checks user if exist or not in all locations in ldap
I want in login state to check user if exist or not only in my specifics group which is exist in my configuration.
meaning in login state  check user only in :
testGroup1 and testGroup2  and not in all locations in ldap


text:
Q: What's the most convenient way to analyze a sentence phrases and structure using NLTK or SpaCy?
What's the most convenient way to analyze a sentence phrases and structure using NLTK or SpaCy?
The main goal is to get a well organized and clean data in order to apply some inferential statistics on it.
Here is a simple example of what I need, as shown in the tree above:

*NP which is a Noun Phrase

*VP, a Verb Phrase

*ADJP, Adjective Phrase

*-, a coordinating conjunction, implying that it is a compound sentence

*PP, a Prepositional Phrase

A: The most convenient way is to use dependency parsing from spacy. https://spacy.io/usage/linguistic-features#dependency-parse
From its output you can extract whatever information you need.
It is important to memorize that no parser will ever have perfect accuracy, so best choose a large model to guarantee good quality.


text:
Q: Multiple Foreground Colours In ControlTemplate I have a Style for an Expander. I want the Foreground property of the Header to be different from the Content.
<Style TargetType="Expander">
  <Setter Property="Foreground" Value="Red"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="Expander">
        <StackPanel>
          <ContentControl Content="{TemplateBinding Header}" Foreground="{TemplateBinding Foreground}"/>
          <ContentControl Content="{TemplateBinding Content}" Foreground="Blue" TextBlock.Foreground="Blue"/>
        </StackPanel>
       </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

<Expander>
  <Expander.Header>
    <TextBlock Text="Header"/>
  </Expander.Header>
  <Expander.Content>
    <TextBlock Text="Content"/>
  </Expander.Content>
</Expander>

However, once the Style is applied, both the Header and the Content come back as Red i.e. the Expander style Foreground colour.
How can I get the Expander style to contain multiple Foreground colours.

A: First, in template is better to use the ContentPresenter, instead of ContentControl, which is a common practice. Quote reply Nir (Question: What's the difference between ContentControl and ContentPresenter?):

ContentControl is a base class for controls that contain other elements and have a Content-property (for example, Button).
  ContentPresenter is used inside control templates to display content.
  ContentControl, when used directly (it's supposed to be used as a base class), has a control template that uses ContentPresenter to display it's content.
Inside ControlTemplate use ContentPresenter;
Outside of ControlTemplate (including DataTemplate and outside templates) try not to use any of them, if you need to, you must prefer ContentPresenter;
Subclass ContentControl if you are creating a custom "lookless" control that host content and you can't get the same result by changing an existing control's template (that should be extremely rare).

Second, the type of construction:
<Expander Header="MyHeader">
    <Expander.Content>
        <TextBlock Text="Content"/>
    </Expander.Content>
</Expander>

You automatically overwrites your the template (style), so the color is the same everywhere, because Red is set, taken from the Style setter.
So, a slightly modified example:
<Style TargetType="{x:Type Expander}">
    <Setter Property="Foreground" Value="Red"/>

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Expander}">
                <StackPanel>
                    <Border BorderThickness="{TemplateBinding BorderThickness}" TextBlock.Foreground="{TemplateBinding Foreground}">
                        <ContentPresenter Content="{TemplateBinding Header}" />
                    </Border>

                    <Border Name="Content" BorderThickness="{TemplateBinding BorderThickness}" TextBlock.Foreground="Blue">
                        <ContentPresenter Content="{TemplateBinding Content}" />
                    </Border>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Grid>
    <!-- Work -->
    <Expander Header="MyHeader" Content="MyContent" />

    <!-- Not work -->
    <!--<Expander Header="MyHeader">
        <Expander.Content>
            <TextBlock Text="Content"/>
        </Expander.Content>
    </Expander>-->
</Grid>

To study the work style, you can take a predefined style (such as MSDN), and change it from there.
Note: It is better to design a universal template to the content, because if you set the content other than TextBlock, color for TextBlock will be useless. Perhaps it is better to set the color in style for the TextBlock.


text:
Q: Continuity of normalized displacement vector for a smooth closed curve I am currently working on chapter 3.12 of "Differential Equations and Dynamical Systems" by Lawrence Perko. I am stuck on the continuity of the function $g$ in Theorem 3. My work (up to the prove of continuity based on Perko with slightly different notation) so far:
Suppose that $f\in C^1(E)$ where $E$ is an open subset of $\mathbb{R}^2$ and that $E$ contains a cycle $\Gamma$ of the system $\dot{x}=f(x) \quad(1)$.
At any point $x\in\Gamma$, define the unit vector $u(x)=f(x)/|f(x)|$. We can assume that $\Gamma$ lies in the first quadrant and is tangent to the $x$-axis in some point $(x_0,0),x_0>0$ (otherwise translate and rotate the axis). Let $\gamma(t)=(x(t),y(t))$ be the solution of $(1)$ through the point $(x_0,0)$ at time $t=0$. We can assume that $\Gamma$ is positively oriented and that the period of $\Gamma$ is equal to $1$, so
\begin{align*}\Gamma=\{\gamma(t)=(x(t),y(t))\in\mathbb{R}^2~|~0\leq t\leq 1\}.\end{align*}
Let $T=\{(s,t)\in\mathbb{R}^2~|~0\leq s\leq t\leq 1\}$, then for $(s,t)\in T$ we define the vector field $g$ by
\begin{align*}&g(s,s)=u(\gamma(s)), & 0\leq s\leq 1 \\ &g(0,1)=-u(\gamma(0)), & \\ &g(s,t)=\frac{\gamma(t)-\gamma(s)}{|\gamma(t)-\gamma(s)|}, & 0\leq s < t \leq 1\end{align*}
Now Perko states, that $g$ is continuous on $T$ and $g\neq 0$ for on $T$.
It is clear that $g$ is continuous on $\tilde{T}:=T\setminus\{(s,t)\in T~|~s=t \vee (s,t)=(0,1)\}$. Let $(s_n,t_n)\rightarrow (s,s),0\leq s\leq 1$. One can show that
\begin{align*}g(s_n,t_n)=\frac{\gamma(t_n)-\gamma(s_n)}{|\gamma(t_n)-\gamma(s_n)|}=\frac{\frac{\gamma(t_n)-\gamma(s_n)}{t_n-s_n}}{\frac{|\gamma(t_n)-\gamma(s_n)|}{t_n-s_n}}\stackrel{s_n<t_n}{=}\frac{\frac{\gamma(t_n)-\gamma(s_n)}{t_n-s_n}}{\left|\frac{\gamma(t_n)-\gamma(s_n)}{t_n-s_n}\right|}\stackrel{n\to\infty}{\rightarrow} \frac{\dot{\gamma(s)}}{|\dot{\gamma(s)}|}\stackrel{\dot{\gamma}=f(\gamma)}{=}u(\gamma(s)).\end{align*}
I now have problems to prove the continuity of $g$ in $(0,1)$. I have uploaded a pdf with figures of the problem (is it possible to attach it directly to this post?), just by "looking" one would say that $g(s,t)\rightarrow -u(\gamma(0))$ as $(s,t)\rightarrow (0,1)$, but I don't find a way to really prove it. Any input would be appreciated!

A: The best way to avoid complications at endpoints is to not have endpoints. The function $\gamma$ is continuously differentiable and $1$-periodic on all of $\mathbb{R}$. Let $\tilde t = t-1$. As $t\to 1$,
$$\frac{\gamma(t)-\gamma(s)}{|\gamma(t)-\gamma(s)|} =
\frac{\gamma(\tilde t)-\gamma(s)}{|\gamma(\tilde t)-\gamma(s)|} \to -\gamma'(0)$$
because both $\tilde t$ and $s$ converge to $0$ in such a way that $\tilde t<s$.
The details are exactly as in your computation, except for the reversed inequality between $s_n$ and $t_n$.


text:
Q: Fetch session details I want to get the session id & csfrtoken from the url: https://www.screener.in/api/company/6596449/quick_ratios/
below is the screenshot of the values.

Also, I tried the below code in vba, but not getting response. please guide, Note the account is a dummy account only to fetch the details.
Sub test()
 Dim user As String
 Dim pwd As String
 Dim path As String
 user = "rajesh2.gade@gmail.com"
 pwd = "Rain@123"
 path = "https://www.screener.in/api/company/6596449/quick_ratios/"
 Debug.Print httpGET(path, user, pwd)
End Sub

Public Function httpGET(fn As String, _
        Optional authUser As String = vbNullString, _
        Optional authPass As String = vbNullString) As String
    pHtml = fn
    Dim oHttp As Object
    Set oHttp = CreateObject("Microsoft.XMLHTTP")
    Call oHttp.Open("GET", pHtml, False)
    If (authUser <> vbNullString) Then
    ' need to do basic authentication
    ' acknowledgement to http://pastie.org/1192157
        oHttp.setRequestHeader "Content-Type", "application/json"
        oHttp.setRequestHeader "Accept", "application/json"
        oHttp.setRequestHeader "Authorization", "Basic " + _
            EncodeBase64(authUser + ":" + authPass)
    End If
    Call oHttp.send("")
    Debug.Print oHttp.getAllResponseHeaders
    httpGET = oHttp.responseText
    Set oHttp = Nothing
End Function

Function EncodeBase64(text As String) As String

  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As MSXML2.DOMDocument60
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument60
  Set objNode = objXML.createElement("b64")

  objNode.DataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = Application.Clean(objNode.text)

  Set objNode = Nothing
  Set objXML = Nothing
End Function

A: You don't need the value of sessionid to login to that site. Csrftoken is necessary, though. However, the following is how you can log in to that site and access the content available in there.
Sub ScrapeAfterLogin()
    Const Url$ = "https://www.screener.in/api/company/6596449/quick_ratios/"
    Const Link$ = "https://www.screener.in/login/"
    Dim Html As HTMLDocument, sParams As String
    Dim oHttp As Object, sToken$

    Set Html = New HTMLDocument
    Set oHttp = CreateObject("MSXML2.serverXMLHTTP")

    With oHttp
        .Open "GET", Url, True
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
        .send
        While .readyState < 4: DoEvents: Wend
        Html.body.innerHTML = .responseText
        sToken = Html.querySelector("input[name='csrfmiddlewaretoken']").getAttribute("value")
        sParams = "csrfmiddlewaretoken=" & sToken & "&next=%2Fapi%2Fcompany%2F6596449%2Fquick_ratios%2F&username=rajesh2.gade%40gmail.com&password=Rain%40123"

        .Open "POST", Link, True
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
        .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        .setRequestHeader "Referer", "https://www.screener.in/login/"
        .setRequestHeader "Origin", "https://www.screener.in"
        .send (sParams)
        While .readyState < 4: DoEvents: Wend
        MsgBox .responseText
    End With
End Sub

To get the session id, you have to create a session, reuse the same session throughout all the requests and then find that session id in the cookies. I don't know how to reuse the same session in vba. However, the following is a python version of achieving the same.
import requests
from bs4 import BeautifulSoup

start_url = 'https://www.screener.in/api/company/6596449/quick_ratios/'
login_url = 'https://www.screener.in/login/'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
}

params = {
    'csrfmiddlewaretoken': '',
    'next': '/api/company/6596449/quick_ratios/',
    'username': 'rajesh2.gade@gmail.com',
    'password': 'Rain@123',
}

with requests.Session() as s:
    s.headers.update(headers)
    res = s.get(start_url)
    soup = BeautifulSoup(res.text,"lxml")
    params['csrfmiddlewaretoken'] = soup.select_one("input[name='csrfmiddlewaretoken']")['value']
    s.headers['Origin'] = 'https://www.screener.in'
    s.headers['Referer'] = 'https://www.screener.in/login/'
    resp = s.post(login_url,data=params)
    print(s.cookies.items())

Output:
[('csrftoken', 'y64L6KeQfJiDvTMcsRQNlLCGYtfEVj82'), ('sessionid', 'e06akkv5yodjag6nf9tqrz5hex9wx99w')]


text:
Q: React Hooks useEffect won't use the correct state <Button
    onClick={() => {
        console.log('addedNodes', addedNodes)
        let credentials = //something...
        let nodes = [...addedNodes]
        console.log(addedNodes)
        setCurrentForm(
            {
                ...currentForm,
                credentials: credentials,
                nodes: [...addedNodes],
            }
        )
    }}
</Button>

I have a button that updates the currentForm state using another state addedNodes.
Whenever the currentForm gets updated, I console.log the currentForm using useEffect.
useEffect(() => {
        console.log('currentForm ,,,,,, ', currentForm)
        console.log('addedNodes ,,,,,, ', addedNodes)
    }, [currentForm]);

This prints out the CORRECT updated state.
However, when I try to add an API request using that state, it goes back to the state before it got updated.
For example, when I update my useEffect to
useEffect(() => {
        console.log('currentForm,,,,,, ', currentForm)
        console.log('addedNodes ,,,,,, ', addedNodes)
        console.log('RUNNING POST')
        setLoadingStatus('loading')

        let body = {
            form: currentForm,
        }

        intializeForms()
        let options = {
            headers: header,
            method: 'post',
            mode: 'cors',
            body: JSON.stringify(body),
        }
        console.log('options.body', options.body)

        const urls = ['...'];
        const fetchJson = url => fetch(url, options).then(res => res.json());
        Promise.all(urls.map(fetchJson))
            .then(([result]) => {
               ...
            })
            .catch(err => {
                setLoadingStatus('none')
                console.log(err)
            });

    }, [currentForm]);

The console.log('options.body', options.body) prints out the old currentForm.
This is very weird to be because console.log(currentForm) prints the expected state, but when I actually use it for an API call, it goes back to the original form.
I assume that it is because this useEffect gets called everytime the state gets updated, but not really sure.
Any help, please?

A: Problematic code fragment

    let body = {
        form: currentForm,
    }
    intializeForms()
    // later bad body.form content

form gets a reference to currentFrom object then currentFrom is overwritten in intializeForms() ... this way JSON.stringify(body) operates on bad data.
Why Kaca992's solution didn't worked?

let body = {
    form: {...currentForm},
  }

It should create a fresh object from currentForm' element/properties.
Probably it worked for some part of currentForm, f.e. for nodes as they was properly (in immutable way - by new instance) assigned/passed:
 nodes: [...addedNodes],

Probably other currentForm elements are a copies of always the same object references, mutated on changes, not replaced with new instances.
Solution:
In this case it's enough to call intializeForms() just after currentForm "consuming" (stringify) - let options = block.
Other good place for form reset (intializeForms() call) can be Promise.all(... resolving function (.then part).

A: What does initializeForms do? If currentForms is a reference type maybe you reset the value? Try setting the body like this:
    let body = {
        form: {...currentForm},
    }


text:
Q: Unexpected sql operation order in Rails controller action We have an action that returns a dynamic list of user emails that are due for a monthly newsletter. The action takes an optional mark_as_sent parameter, which if present will update the user records to show they were sent an email today.
But even though the update operation happens after the users have been selected, the action always returns an empty list when mark_as_sent is true.
The two operations are not part of the same transaction, so I don't understand why the first one seems to be taking effect before the second?
  def monthly_email_list

    last_month = DateTime.current-1.month
    # Grab all users who havent received a monthly follow up email in a month or more:
    @users = User.where("monthly_email_sent < '#{last_month}' AND on_mailing_list = 't'").select("email","id")

    if params[:mark_as_sent]
      count = User.where("monthly_email_sent < '#{last_month}'").select("email","id").update_all(:monthly_email_sent => DateTime.current)
    end

  end

A: Rails lazy-loads data from first query, and executes second one immediately. Try to force the first query:
@users = User.where("monthly_email_sent < '#{last_month}' AND on_mailing_list = 't'").select("email","id").to_a