text:
Q: Complex values for a supposed real integral I have an integral for which I have checked that it is supposed to be real but there some values of zm which gives a complex value.
First I checked the validity range of func1 and func2,
ContourPlot[func1[z, zm, 9.30685, -15.5, 10], {z, 0, 9.30685}, {zm, 2, 14}, Frame -> True, FrameLabel -> {"z", "zm"}, LabelStyle -> Directive[FontFamily -> "Arial", FontSize -> 20], ImageSize -> Large, PlotLegends -> Automatic] // AbsoluteTiming
ContourPlot[func2[z, zm, 9.30685, 10], {z, 9.30685, 14}, {zm, 2, 14}, Frame -> True, FrameLabel -> {"z", "zm"}, LabelStyle -> Directive[FontFamily -> "Arial", FontSize -> 20], ImageSize -> Large, PlotLegends -> Automatic] // AbsoluteTiming

Below you will see that zm~13.12... and zl=9.30685 so based on the contour plot, the function should be real numbers for the range specified.
Now here is my code,
d = 3;
ag = 20;
pg = 20;
wp = 100;
f[z_, zh_] := 1 - (z/zh)^(d + 1);
func1[z_?NumericQ, zm_?NumericQ, zl_?NumericQ, \[Sigma]_?NumericQ, zh_?NumericQ] := Rationalize[FullSimplify[zm^d/(z^d Sqrt[f[z, zh] zm^(2 d) - f[zm, zh] z^(2 d)]) - zl^d/(z^d Sqrt[f[z, zh] (zl^(2 d) - (f[zl, zh] z^(2 d))/(f[zl, zh] + \[Sigma]^2))])], 0]
func2[z_?NumericQ, zm_?NumericQ, zl_?NumericQ, zh_?NumericQ] := Rationalize[FullSimplify[zm^d/(z^d Sqrt[f[z, zh] zm^(2 d) - f[zm, zh] z^(2 d)])], 0]
Sdiff1[zm_?NumericQ, zl_?NumericQ, \[Sigma]_?NumericQ, zh_?NumericQ] := NIntegrate[func1[z, zm, zl, \[Sigma], zh], {z, 10^-6, zl}, AccuracyGoal -> ag, PrecisionGoal -> pg, WorkingPrecision -> wp] - 1/zl^(d - 1)
Sdiff2[zm_?NumericQ, zl_?NumericQ, zh_?NumericQ] := NIntegrate[func2[z, zm, zl, zh], {z, zl, zm}, AccuracyGoal -> ag, PrecisionGoal -> pg, WorkingPrecision -> wp]
Sdiff[zm_?NumericQ, zl_?NumericQ, \[Sigma]_?NumericQ, zh_?NumericQ] := Sdiff1[zm, zl, \[Sigma], zh] + Sdiff2[zm, zl, zh]

I want to find the root of Sdiff[zm,zl,\[Sigma],zh]=0, so
Plot[Sdiff[zm, 0.930685, -1.55, 1], {zm, 1.31, 1.314}, PlotStyle -> {Blue, Thickness[0.005]}, ImageSize -> Large] // AbsoluteTiming
Plot[Sdiff[zm, 9.30685, -15.5, 10], {zm, 13.1, 13.14}, PlotStyle -> {Blue, Thickness[0.005]}, ImageSize -> Large] // AbsoluteTiming

I have plotted Sdiff[zm,zl,\[Sigma],zh] for different values, i.e. scale everything by factors of 10 (In this case I showed two different cases, zh=1 and zh=10). As you can see there are complex values at some points which is very weird. This will affect how I find the root using FindRoot, for example
In[311]:= Sdiff[1.3122, 0.930685, -1.55, 1]

During evaluation of In[311]:= NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in z near {z} = {1.10524401558531152310428738847291229469593603918764874985616942995484548973267025261496827751468857732080682244020164489570106785806413041234318401687*10^-6}. NIntegrate obtained -0.0953680951680931834745123674416812697318528782917380282484631277114279966108197976780600049228239456971990308722276004495808778188013233959933376197893 and 5.85518219686336069826959647527731082173980350941567052572749792113897389621195362705030451018833409494062810446414117340960083869273350500071564734243`150.*^-6 for the integral and error estimates.

During evaluation of In[311]:= NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small.

During evaluation of In[311]:= NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in z near {z} = {1.31219999996483775815022710925413900325446196741877373671252134559465310956494433552531673372086271474655712701563166561726401758962888297501592615831}. NIntegrate obtained 1.20335539716039122886908985026362661137726264579696310786318485276473000853231349656943135755073685036993548318482112178431183944472080815293312408373-2.98666309015455056925534269794783240056722422689357295577995834953594171518743926959095013943264159192680423190751058648637852902332826307958023336608*10^-8 I and 9.852591478099224742584715514655146848865875888877501022195950834394971266735884212697416425973180150042925051691217796179500572518840194547309207848`150.*^-8 for the integral and error estimates.

Out[311]= -0.0465144 - 2.98666*10^-8 I

In[316]:=
FindRoot[Sdiff[zm, 0.930685, -1.55, 1] == 0, {zm,
   1.313}] // AbsoluteTiming

During evaluation of In[316]:= NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in z near {z} = {1.43628442733304049176237159421375406043675406787164837826181212170174294734144693316126775482870488514544158898529087874593892511596377848099164854596*10^-6}. NIntegrate obtained -0.0953677430126576890317804757035965852145657587652392085970936658759314126174898801398971900787493739043444088160327727805498519290223977816445364470503 and 2.89397313756015414359427380459096848107793820089910650435934688803685220569080408374145792659908259535152922600074117123194677145733427270103524166053`150.*^-6 for the integral and error estimates.

During evaluation of In[316]:= NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in z near {z} = {1.31299999996476393815843577120175756096583203717702249833126334557685736161243282560190392580959562320605806579767154678758445722585164366254519505445}. NIntegrate obtained 1.24209549585833258515400729015185658085179856431970135575634837182003541211813883750840953454444322107739595395976933113881528509394769347545102038392-1.11260715736832754271226365950881587154788934169698566310114610778037210620400003096207658071042571105498101884905957622359883099514289681467968087977*10^-7 I and 9.11306124954966805954714643395838397126221015795969449969272935181145135202368019974986545127461924277936248514998091680891708387436445255181327286198`150.*^-8 for the integral and error estimates.

During evaluation of In[316]:= NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in z near {z} = {1.43628442733304049176237159421375406043675406787164837826181212170174294734144693316126775482870488514544158898529087874593892511596377848099164854596*10^-6}. NIntegrate obtained -0.0953677430126576890317804757035965852145657587652392085970936658759314126174898801398971900787493739043444088160327727805498519290223977816445364470503 and 2.89397313756015414359427380459096848107793820089910650435934688803685220569080408374145792659908259535152922600074117123194677145733427270103524166053`150.*^-6 for the integral and error estimates.

During evaluation of In[316]:= General::stop: Further output of NIntegrate::ncvb will be suppressed during this calculation.

During evaluation of In[316]:= NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small.

During evaluation of In[316]:= NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small.

During evaluation of In[316]:= NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small.

During evaluation of In[316]:= General::stop: Further output of NIntegrate::slwcon will be suppressed during this calculation.

During evaluation of In[316]:= NIntegrate::inumri: The integrand func2[z,1.31311 -8.39439*10^-6 I,0.930685,1] has evaluated to Overflow, Indeterminate, or Infinity for all sampling points in the region with boundaries {{1.313106823851375892786563781555742025375366210937500000000000000000000000000000000000000000000000000-8.39438812464856821027488209541189689844031818211078643798828125000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*10^-6 I,1.31310682385137589278656378154532196282846108303459917393652031300261052080212042327483089465064104398127251947970448226866065749184806172138611881869-8.39438812464856821027488209518317028336138899066660076766073388076349356073810504462990043049957127732694718006373758881957959364026202385510465424045*10^-6 I}}.

During evaluation of In[316]:= NIntegrate::inumri: The integrand func2[z,1.31311 -8.43138*10^-6 I,0.930685,1] has evaluated to Overflow, Indeterminate, or Infinity for all sampling points in the region with boundaries {{1.313106794078247929746794397942721843719482421875000000000000000000000000000000000000000000000000000-8.43138406127335189024427086756929838884389027953147888183593750000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*10^-6 I,1.31310679407824792974679439793230178198382245897726121707531775353358197619357632018964367708580121668400692114874349854204266096059225964967595336693-8.43138406127335189024427086733956372466951666984520735049820226690615498627879851667470323522444300010977212779156432486485196065538859756075619294786*10^-6 I}}.

During evaluation of In[316]:= NIntegrate::inumri: The integrand func2[z,1.31311 -8.43138*10^-6 I,0.930685,1] has evaluated to Overflow, Indeterminate, or Infinity for all sampling points in the region with boundaries {{1.313106794096682072847670497139915823936462402343750000000000000000000000000000000000000000000000000-8.43137899897577064174235966786952189977455418556928634643554687500000000000000000000000000000000000000000000000000000000000000000000000000000000000000*10^-6 I,1.31310679409668207284767049712949576220030015397972888398459406527352356028334368642572578628765041006633065497395603175327088345565398183827797449243-8.43137899897577064174235966763978737353545031654624029810073943077125217704951179703277710408782099359913267973633997017398860967033749757892941962606*10^-6 I}}.

During evaluation of In[316]:= General::stop: Further output of NIntegrate::inumri will be suppressed during this calculation.

During evaluation of In[316]:= FindRoot::lstol: The line search decreased the step size to within tolerance specified by AccuracyGoal and PrecisionGoal but was unable to find a sufficient decrease in the merit function. You may need more than MachinePrecision digits of working precision to meet these tolerances.

Out[316]= {18.7782, {zm -> 1.31311 - 8.43138*10^-6 I}}

It spits out complex values, which I do not know why.
Also, I still do not understand how AccuracyGoal, PrecisionGoal, and WorkingPrecision play any role in these situations after reading through many other questions here in MSE. There some who said to make the numbers exact and use Rationalize & FullSimplify, use higher WorkingPrecision, etc. None of it solved the issue.

A: Clear["Global`*"]

d = 3;
ag = 20;
pg = 20;
wp = 100;
f[z_, zh_] := 1 - (z/zh)^(d + 1);

Rationalize function inputs prior to the calculation rather than rationalizing the end result of an inexact calculation. For performance reasons eliminate simplification except that which occurs naturally from the use of exact numbers. Use Module to localize the temporary variables.
func1[z_?NumericQ, zm_?NumericQ, zl_?NumericQ, σ_?NumericQ,
   zh_?NumericQ] :=
  Module[{zr, zmr, zlr, σr, zhr},
   {zr, zmr, zlr, σr, zhr} =
    Rationalize[{z, zm, zl, σ, zh}, 0];
   zmr^d/(zr^d Sqrt[f[zr, zhr] zmr^(2 d) - f[zmr, zhr] zr^(2 d)]) -
    zlr^d/(zr^d Sqrt[
        f[zr,
          zhr] (zlr^(2 d) - (f[zlr, zhr] zr^(2 d))/(f[zlr,
               zhr] + σr^2))])];

func2[z_?NumericQ, zm_?NumericQ, zl_?NumericQ, zh_?NumericQ] :=
  Module[{zr, zmr, zlr, zhr},
   {zr, zmr, zlr, zhr} = Rationalize[{z, zm, zl, zh}, 0];
   zmr^d/(zr^d Sqrt[f[zr, zhr] zmr^(2 d) - f[zmr, zhr] zr^(2 d)])];

Sdiff1[zm_?NumericQ, zl_?NumericQ, σ_?NumericQ, zh_?NumericQ] :=
 Module[{zlr = Rationalize[zl, 0]},
  NIntegrate[func1[z, zm, zlr, σ, zh], {z, 10^-6, zlr},
    AccuracyGoal -> ag, PrecisionGoal -> pg, WorkingPrecision -> wp] -
   1/zlr^(d - 1)]

Sdiff2[zm_?NumericQ, zl_?NumericQ, zh_?NumericQ] :=
 Module[{zlr, zmr},
  {zlr, zmr} = Rationalize[{zl, zm}, 0];
  NIntegrate[func2[z, zmr, zlr, zh], {z, zlr, zmr}, AccuracyGoal -> ag,
   PrecisionGoal -> pg, WorkingPrecision -> wp]]

Sdiff[zm_?NumericQ, zl_?NumericQ, σ_?NumericQ, zh_?NumericQ] :=
 Sdiff1[zm, zl, σ, zh] + Sdiff2[zm, zl, zh]

Test case,
Sdiff[1.3122, 0.930685, -1.55, 1] // AbsoluteTiming

(* {7.41299, \
-0.046510430706799189085784355939930933139694434574566957872349257327957297540\
0788205351038711701552046} *)

However, if the values of {ag, pg, wp} are only trying to avoid complex-valued results,
{ag = 10, pg = 10, wp = 20};

Sdiff[1.3122, 0.930685, -1.55, 1] // AbsoluteTiming

(* {1.18131, -0.04651043070679918730} *)

Plots
Plot[Sdiff[zm, 0.930685, -1.55, 1], {zm, 1.31, 1.314},
  PlotStyle -> {Blue, Thickness[0.005]},
  ImageSize -> Medium] // AbsoluteTiming

Plot[Sdiff[zm, 9.30685, -15.5, 10], {zm, 13.1, 13.14},
  PlotStyle -> {Blue, Thickness[0.005]},
  ImageSize -> Medium] // AbsoluteTiming


text:
Q: XPath: handling invalid second parameter of contains() function I have kind of invalid xpath expression where second parameter is not a string:
//ng-messages/span[contains(., fieldName)]

This expression still returns some of span's. I'm curious how xpath handles this invalid second parameter.

A: The predicate in expression span[contains(., fieldName)] checks if the current span element contains the value of string(fieldName), where fieldName is child of the span.
The predicate will evaluates to true if fieldName exists whatever its content, because fieldName is part of the span. And it is also evaluates to true when the span doesn't have child fieldName, because string(fieldName) will then returns an empty string and the expression contains('whatever', '') is always evaluates to true.

A: See XPath 1.0, §3.2 Function Calls:

A FunctionCall expression is evaluated by using the FunctionName to identify a function in the expression evaluation context function library, evaluating each of the Arguments, converting each argument to the type required by the function, and finally calling the function, passing it the converted arguments.
An argument is converted to type string as if by calling the string function. (...)

contains() is defined like this:

Function: boolean contains(string, string)
The contains function returns true if the first argument string contains the second argument string, and otherwise returns false.

And finally, the string() function has all cases defined depending on the input: node-set, number, boolean. If it's something else:

An object of a type other than the four basic types is converted to a string in a way that is dependent on that type.

At first sight, I don't know how your XPath engine will convert  fieldName.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Return type for python's search and match in re module? Documenting return types for methods and I have:
@classmethod
def rightFileType(cls, fileName):
    """Check if the filetype (extension) is correct for subclass.
    :type fileName: str | unicode
    :rtype: _sre.SRE_Match | None # here ?
    """
    return cls.file_extension.search(fileName)

It does not feel right to use a private module but the docs refer to a re.MatchObject class that I can't seem to locate in re - pycharm can't resolve that symbol. So here is re.MatchObject in python's re module - or what should I use for return type here ?

A: I think you would like to return a bool type.
Then:
if cls.file_extesion.search(fileName):
    return True
return False

But, I don't know why you use regex here, you can check the filename with endswith method of str.


text:
Q: Segmentation fault assigning function result I am trying to write memory allocation interface. Seg fault occures exactly when returning new_buf_addr from myalloc function to main and assigning it to variable temp, checked within gdb. Return value is not a pointer to a local value, so i guess this is not the issue. I tried to return other types, but it has the same result
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

void* HEAD = NULL;
void* NULLPTR = (void*)10;
std::size_t ATTRS_SIZE = 2*sizeof(NULL) + sizeof(std::size_t) + sizeof(char);

// BUFFER STRUCT
// |--prev--|--next--|--size--|--flag--|–––––––––––data–––––––––––|
// |---8b---|---8b---|---8b---|---1b---|
// |---------------25b-----------------|––––––––size - 25b––––––––|
// flag:
// 0 - busy
// 1 - free

// add metadata
void init_buf(void *buf, std::size_t size, void *prev, void *next, char free_flag ){
    printf("%d\n", sizeof(prev) );
    memcpy(buf, prev, sizeof(prev));
    memcpy(buf + sizeof(NULL), next, sizeof(next));
    memcpy(buf + 2*sizeof(NULL), &size, sizeof(std::size_t));
    memcpy(buf + 2*sizeof(NULL) + sizeof(std::size_t), &free_flag, sizeof(char));
}

// setups buffer where memory will be allocated
void mysetup(void *buf, std::size_t size)
{
    HEAD = buf;
    init_buf(buf, size, &NULLPTR, &NULLPTR, 1);
}

void* myalloc(std::size_t size)
{
    void* buf = HEAD;
    while (true) {
        // getting buf attrs
        void* prev;
        void* next;
        std::size_t* buf_size;
        char free_flag;

        printf("%d %d %d\n", sizeof(buf), sizeof(void*), sizeof(prev));
        // memcpy(prev, buf, sizeof(void*));
        prev = buf;
        // memcpy(next, buf + sizeof(NULL), sizeof(void*));
        next = buf + sizeof(NULL);
        memcpy(buf_size, buf + 2*sizeof(NULL) , sizeof(std::size_t));
        memcpy(&free_flag, buf + 2*sizeof(NULL) + sizeof(std::size_t), sizeof(char));

        // check if buf is free and big enough to allocate
        if (size < *buf_size && free_flag){
            void* new_buf_addr = buf + *buf_size - ATTRS_SIZE - size;

            // point buf's next to new buf
            memcpy(next, new_buf_addr, sizeof(new_buf_addr));
            init_buf(new_buf_addr, size, buf, &NULLPTR, 0);

            new_buf_addr = new_buf_addr + ATTRS_SIZE;
            return new_buf_addr;
        }
        // going to next buf
        else {
            if (next == &NULLPTR) {
                printf("%s\n", "Can't allocate memory");
                return NULL;
            }
            else {
                buf = next;
            }
        }
    }
}

void myfree(void *p)
{
    while (true){
        void *left_neighbor;
        memcpy(left_neighbor, p - ATTRS_SIZE, sizeof(void*));
        void *right_neighbor;
        memcpy(right_neighbor, p - ATTRS_SIZE + sizeof(void*), sizeof(void*));
        std::size_t* size;
        memcpy(size, p - ATTRS_SIZE + 2 * sizeof(void*) , sizeof(std::size_t));
        char* free_flag;
        memcpy(free_flag, p - sizeof(char), sizeof(char));

        bool is_right = false;
        if (right_neighbor != &NULLPTR) {
            bool right_is_free = *((char*)(right_neighbor + ATTRS_SIZE - sizeof(char))) == 1;
            if (right_is_free) {
                is_right = true;
            }
        }

        bool is_left = false;
        if (left_neighbor != &NULLPTR) {
            bool left_is_free = *((char*)(right_neighbor + ATTRS_SIZE - sizeof(char))) == 1;
            if (left_is_free) {
                is_left = true;
            }
        }

        if (is_right) {
            memcpy(size, p - ATTRS_SIZE + 2 * sizeof(void*) , sizeof(std::size_t));
            void* right_next;
            std::size_t* right_size;
            memcpy(right_next,  right_neighbor + sizeof(void*), sizeof(void*));
            memcpy(right_size,  right_neighbor + 2 * sizeof(void*), sizeof(std::size_t));

            // set p->next to right_neighbor's next
            memcpy(right_neighbor, right_next, sizeof(void*));
            // adding right_neighbor->size to p->size
            *size = *size + *right_size;
        }
        else if (is_left){
            memcpy(left_neighbor +  sizeof(void*), right_neighbor, sizeof(void*));

            std::size_t* new_size;
            // set left_neighbor->next to p->next
            memcpy(new_size, left_neighbor +  2 * sizeof(void*), sizeof(std::size_t));
            //adding p->size to left_neighbor->size
            *new_size = *new_size + *size;
            // pointig p to data to keep cycle alive
            p = left_neighbor + ATTRS_SIZE;
        }
        else {
            // Just in case if is 0 set it to 1
            char flag = 1;
            memcpy(p - sizeof(char), &flag, sizeof(char));
            return;
        }
    }
}

int main() {
    void* ret[10];
    std::size_t buf_size = 100*1024;
    void* buf = malloc(buf_size);
    mysetup(buf, buf_size);
    std::size_t block_size = 16;
    int i = 0;
    while(1) {
        void* temp = myalloc(block_size);
        ret[i] = temp;
        if(ret[i] == NULL) break;
        i++;
    }
    for(int j = 0; j < i; j++) {
        std::size_t rnd = (rand()/(double)RAND_MAX*(i-1));
        void* swp = ret[rnd];
        ret[rnd] = ret[j];
        ret[j] = swp;
    }
    for(int j = 0; j < i; j++) {
        myfree(ret[j]);
    }
    return 0;
}

A: Ok, looking at the sparse comments, the "8b" suggests "8 bytes" which looks like a pointer size you're planning to get from sizeof(NULL). And std::size_t means you're compiling C++.
In C++, NULL is not a pointer. sizeof(NULL) can be smaller or larger than sizeof(void*). I expect that on your system, #define NULL 0 and sizeof(NULL)==4. Not 8 bytes.

A: The problem was that void* prev and void* next should be void**, because prev and next are pointers to the begining of another buffers, which are also pointers


text:
Q: How to use pyomo along with gurobi feasRelax? In gurobipy we can use
m = Model()
m.feasRelax(1, False, False, True)
m.optimize()

to compute the feasibility relaxation.
Is there a way to do this in pyomo with gurobi?


text:
Q: In Apache Karaf, how can a KAR file instruct Karaf to install features? I have a KAR file which I produced for Apache Karaf.
Now to get my KAR to run in Karaf 2.4.1 I must manually type into Karaf console the following to allow declarative services to work.
features:install scr

Is there a way for my KAR file to instruct Karaf to install this scr automatically?
The point is that I would like to be able to deploy a KAR by just dropping it into Karaf deploy folder without having to do any manual command.

A: A KAR contains a features XML file, correct? Add the scr feature into your features XML file as a dependent feature. See the section on Dependent Features in Karaf Provisioning.


text:
Q: java.util.logging (JDK 19) - Why isn't the logging written to disk immediately? I have a small java program that uses logging.

import java.util.logging.*;

public class Main {

    static Logger  logger = Logger.getLogger(Main.class.getName());

    static   {

         try {

            System.setProperty(
"java.util.logging.SimpleFormatter.format",

                               "[%1$tF %1$tT] [%4$-7s] %5$s %n");

            FileHandler fileHandler = new FileHandler("java_%u.log");
            fileHandler.setFormatter(new SimpleFormatter());

            logger.addHandler(fileHandler);

        } catch (Exception e) {

             logger.severe(e.getMessage());

          }

          logger.info("Static done");

    }

    public static void main(String[] args) {

       logger.info("Main started");

       for(int i=0;i<10;i++){

         logger.info("Sleeping "+ i);

         try {

            Thread.sleep(3000);

         } catch (InterruptedException e) {

            throw new RuntimeException(e);

         }

       }

    }

}

It doesn't matter whether you use it from a development environment (Intellij 2022.2.3)
or directly as a jar file from the command line.
How logging works is generally clear to me. It's the Java version (jdk 19) that's giving me problems? Why is the logging only written to disk after the program has terminated?

A:
Why is the logging only written to disk after the program has terminated?

On shutdown the FileHandler is closed by the LogManager which issues a sync to disk. Normal publish of the FileHandler will only issue a flush and not a sync.  I think in your test program you are not filling the native buffers to make it sync to disk.  I would assume you are going to have to exceed 8K of log data before data is written to disk.
The other possibility is that the contents are written to disk but the way you are observing the log file can't see them.  This can happen if you are view this file over a network share from another machine.

A: This is peculiar.
I have a copy of the Java 19 source code in front of me, and the JUL code for a FileHandler calls flush after each log record.  And I think I can see where it calls flush on the handler's Writer.
When I run your example, the log file seems to be written to each time an event is logged.  Immediately ... as far as I can tell.
(I ran the code with Java 11 and Java 17.)


text:
Q: JQuery each loop looping through one line of code x amount of times before even looking at the rest I have a loop in Jquery:
var fadeTime=500;
css_id=0;
$.each(my_array, function (i, d_U) {
css_id++;
an_v=d_U[1];
an_d=d_U[4];

do_c_function("id_344",true,true);

$("#box_"+css_id).fadeIn(fadeTime,function(){

   //this stuff will happen once the fadein is complete

   $("#box_"+css_id).animate({top: '-50px'},fadeTime,function(){

       //this stuff will happen once the animate is complete

       alert("#box_"+css_id);//for debugging

    });//end of animation

  });//end of fadein

});//end of each loop

Now as you've probably noticed, I'm trying to make the loop animate different divs each time using the css_id variable and ++; (add 1) to it each time the loop runs.
Thing is, css_id reaches a high value before any of the code below has even been executed once. So when its time to animate, Jquery will try to animate #box_210 when its supposed to animate #box_1.
Is there any way to make it only execute the css_id++; line once, then the animate lines get executed, and only then again with the css_id++; line...and so on.
I've tried to put the css_id++; line in a call back with both the animations but that seems to not work as well.
Thanks

A: Your animate callback function is forming a closure over css_id and therefore storing a live reference to css_id, not merely the value this variable holds at the moment the animation loop is created.
Since all parameters are passed by value in JavaScript, you can use jQuery's data function to break the closure, and take a snapshot of the css_id value at that time.
    $("#box_"+css_id).data("css_id", css_id).fadeIn(fadeTime,function(){
       var local_css_id = $(this).data("css_id");
       $("#box_"+ local_css_id).animate({top: '-50px'},fadeTime,function(){

           //this stuff will happen once the animate is complete

           alert("#box_" + local_css_id);//for debugging
        });//end of animation
      });//end of fadein
    });//end of each loop

A: The problem is the scope of css_id.  The easiest way to fix it would be to call a function within your loop.  Each call to the function will get its own parameter in the scope of the function which will not change as the variable is incremented.
Something like this:
function doTheAnimation(css_id) {
    $("#box_" + css_id).fadeIn(fadeTime, function() {

        //this stuff will happen once the fadein is complete
        $("#box_" + css_id).animate({
            top: '-50px'
        }, fadeTime, function() {

            //this stuff will happen once the animate is complete
            alert("#box_" + css_id); //for debugging
        }); //end of animation
    }); //end of fadein
}

var fadeTime = 500;
css_id = 0;
$.each(my_array, function(i, d_U) {
    css_id++;
    an_v = d_U[1];
    an_d = d_U[4];

    do_c_function("id_344", true, true);

    doTheAnimation(css_id);

}); //end of each loop

Here is a fiddle to illustrate the difference.
http://jsfiddle.net/kmGWa/

A: If you want each animation to go in sequence (the next one starting after the previous one is done), you can code it like this where each one is done in a local function and the final completion function invokes the local function again to do the next one:
function doFades() {
    var fadeTime=500;
    css_id=0;
    var i = 0;
    function doOneFade() {
        if (i < my_array.length) {
            var d_U = my_array[i++];
            css_id++;
            an_v=d_U[1];
            an_d=d_U[4];

            do_c_function("id_344",true,true);

            $("#box_"+css_id).fadeIn(fadeTime,function(){

               //this stuff will happen once the fadein is complete

               $("#box_"+css_id).animate({top: '-50px'},fadeTime,function(){

                   //this stuff will happen once the animate is complete

                   alert("#box_"+css_id);//for debugging
                   doOneFade();

               });//end of animation

           });//end of fadein
       }
   }
   doOneFade();
}


text:
Q: Delphi Xe2 with Firemonkey : Can you have a non-client area that is painted in a style other than the default Windows nonclient paint style? Here is a sample of a delphi application I am making using firemonkey + Delphi XE2.
As you can see, you can use the visual style "stylebook" in Firemonkey to customize the appearance of most things inside the window frame. However the outside of the window frame is drawn using whatever style Windows decides.  Now if I was using VCL instead of Firemonkey, I could apply "VCL Styles" and "skin" the whole VCL application in a dark color scheme.
My guess is that this is NOT YET posssible with Delphi XE2 + Firemonkey. Can anyone show how to do this?

At designtime, the "preview" of your form shows a nice black border. But when I run my app, the Windows XP "Luna" theme border (the blue parts in the picture below) looks atrocious.  Ironically, the VCL is prettier (in XE2 with styles) than Firemonkey...

A: You can create a VCL Forms application as usual, with styles if you like, at runtime load your Firemonkey form and set your VCL form as its parent:
uses
  FMX.Platform.Win, FMX.Forms,
  Unit2;

procedure TForm1.FormCreate(Sender: TObject);
var
  Form2: TForm2;
begin
  Form2 := TForm2.Create(nil);
  Form2.BorderStyle := FMX.Forms.TFmxFormBorderStyle.bsNone;
  Form2.SetBounds(0, 0, ClientWidth, ClientHeight);
  Winapi.Windows.SetParent(FmxHandleToHWND(Form2.Handle), Handle);
  Form2.Show;
end;

In the following screenshot, Form1 is the VCL application main form (with Carbon style) and the dark-grey area with the button is the embedded Firemonkey form:

Note that I'm not handling resizing of the parent window - it should resize the emebedded form, too, emulating alClient alignment.
It seems there are many potential problems with this approach - I think there's a reason why the IDE doesn't let you easily mix Firemonkey forms with VCL forms - it warns about possible "compilation errors or unexpected behavior."

A: Firemonkey is cross platform.  By and large you cannot do anything that is platform dependent within the FMX framework itself.  You can however make calls to the underlying platform (be it windows, OSX or iOS) to access platform specific functionality.  This should be done within conditionally compiled code.
eg.
{$IF DCC}
  something;
{$ENDIF}

{$IF FPC}
  somethingelse;
{$ENDIF}

Looking at it from another viewpoint, it may be possible for you do do all of your FMX work on a TRectangle (for example), then use AddObject (or assign its parent), to a VCL form.

A: If you change the forms BorderStyle to bsNone, you can add whatever chrome you want. You will, of course, need to manually handle maximise, minimise, close, resize etc actions.


text:
Q: SFML sf::Text::setFillColor is broken or am I doing something wrong? The code I've written displays the sf::Drawable objects only for the top state of the state stack. Rendering works fine for everything, except the sf::Text type, that does not change the color of the text when button.getText().setFillColor(sf::Color:Red) is called. However, when I construct a button with a red text, whenever I try to set another color to that button, I only get a white text, no matter what color I request.
Here's where I change the color of a button:
void GameState_MainMenu::handleRealTimeInput()
{
    for each (TextButton button in mButtons)
    {
        if (button.isSpriteClicked())
        {
            button.getText().setFillColor(sf::Color::Red);
            button.triggerAction();
            sf::Clock wait;
            sf::Time timer = sf::Time::Zero;
            timer = sf::seconds(0.15f);
            while (wait.getElapsedTime() < timer)
            {

            }
            wait.restart();
        }
    }
}

and this is my Game::render() method:
void Game::render()
{
    GameState *currentState = getActiveState();
    if (currentState != nullptr)
    {
        mWindow.clear();
        currentState->draw();
    }
    mWindow.display();
}

Lastly, this is the draw method of the MainMenu state:
void GameState_MainMenu::draw()
{
    game->mWindow.draw(game->mBackground);
    game->mWindow.draw(mSelector.mSprite);
    for each (TextButton button in mButtons)
    {
        game->mWindow.draw(button.getText());
    }
}

A: It's probably because you have a while loop in the GameState_MainMenu::handleRealTimeInput that the program is getting stuck in.
You can try to use threads, though that way could get pretty messy. I suggest revising your code.

A: Okay, so I figured out this had something to do with c++'s for each instruction. As soon as I switched to the classic array-like traversal, my buttons started changing colors. I'm not saying this is THE solution, just that it worked for me. If anyone has the same problem, you might want to check that.


text:
Q:  not working on iPhone Mobile Safari Supposedly in HTML5 in Safari, you can define your input type as "search" and when the user starts typing, an X button will show up to allow them to clear, much like the Google search bar in Safari. On my website, this works on desktop Safari but it doesn't work in Mobile Safari.
    <input id="termsField" type="search" autocorrect="off" placeholder="Type something here">

//This is the code for the X button I have to use now since HTML5 doesn't work
<INPUT type="image" name="Clear" alt="Clear" src="clearX.png" height="22" width="22"
        onClick="clearText(this)">

At first I thought it's because I have a Jquery autocomplete function on the #termsField but again if it works in Desktop Safari that wouldn't be the case. Does anyone have any idea why this might be happening?
Also, it doesn't work either on my iPhone or in the iPhone Simulator in XCode so it's not an issue specifically with my iPhone.

A: That works in (Desktop) Safari, but not on the iPhone (Mobile Safari). You can mimic the functionality via some clever javascript.

A: you need to make the type="search" attribute the first one in the tag - ie
<input type="search" id="termsField" autocorrect="off"
       placeholder="Type something here" />

This bug has since been resolved for iphones but android browsers still need the search attribute first, otherwise it will be rendered as a standard input field.


text:
Q: tabstackengine repeat the endnotes many times When I use an \endnote command from enotez package inside a tabstackengine package's table, the endnote apear as if I call it many times.
The MWE
\documentclass{article}
\usepackage{enotez}
\usepackage{tabstackengine}

\begin{document}

\tabbedCenterstack{
foo \endnote{bar} & baz
}

\printendnotes

\end{document}

The rendering

As you see, the note appear in the Notes section tree times when I call it just once. I think its because \tabbedCenterstack process tree tree times, then the note is tree times loaded.
Finaly
So how can I avoid to get tree times the endnote?

A: Here is the approach of saving the end note in a temp box first and passing that to the stack.  While I have upgraded stackengine to avoid setting the content (internally) more than once, I will have to re-examine tabstackengine.  It may not be possible to eliminate the multiple passes, based on the technique used to align all the content.
In any event, this temporary box approach should work.
\documentclass{article}
\usepackage{enotez}
\usepackage{tabstackengine}

\begin{document}

\sbox4{\endnote{bar}}
\tabbedCenterstack{
foo\copy4 & baz
}

\printendnotes

\end{document}

If you are worried about using temporary boxes, or if there is more than one endnote in the stack, you can use \savestack, which itself creates a unique named box for storing its contents.
\documentclass{article}
\usepackage{enotez}
\usepackage{tabstackengine}
\begin{document}

\savestack\tmpA{\endnote{bar}}
\savestack\tmpB{\endnote{barr}}
\tabbedCenterstack{
foo\tmpA & baz\tmpB
}

\printendnotes
\end{document}

UPDATE: I can confirm that tabstackengine itself is setting cell content thrice, as part of its technique of measuring and aligning the content.  I can easily get that down to twice (and will update the package); however, it will be tough to eliminate the two typesets...once for measuring and the other for final typeset.


text:
Q: Insert multiple data if not exists or update data (php/mysql) I want to insert multiple data to mysql.
My PHP code which is Array input field:
pag1.php
  <form method="post" action="page2.php">
     <input type="text" name="option_id[]" size="1">
     <input type="text" name="store_id[]" size="1">
     <button type="submit" name="action" value="add" >Add</button>
  </form>

page2.php
<?php
if(isset($_POST['action'])){

for ($i=0; $i < count($_POST['option_id']); $i++ ) {
$option_id = $_POST['option_id'][$i];
$store_id = $_POST['store_id'][$i];
// check if option id is exists or not
         $result = mysql_query ("SELECT * FROM temp_cart WHERE option_id='$option_id' AND store_id='$store_id' ") or die (mysql_error());

         if (mysql_num_rows($result) == 0){
                     //insert query
                 }
                 else {
                     //update query
                 }
        }
}
?>

For loop is not work.
Your help would be very much appreciated.


text:
Q: Can I use IIF in th update query I have an access query which I am trying to convert to SQL but getting Msg 102...
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near 'r'.
can I know what's wrong in this ?
UPDATE r
SET r.Estimate_date_collected = (IIf([LAB].[nationality]='MD',
                                    DateAdd("m",-1,[lab].[Date Received]),
                                    DateAdd("m",-2,[lab].[Date Received])))
From temp as r INNER JOIN temp1 as l
ON r.[ID #] = l.[ID #]
WHERE ((((r.Estimate_date_collected) Is Null)) AND ((r.[Date Coll't]) Is Null))) ;


text:
Q: How to get an element in *ngFor in Angular dynamically without using Js id selector I have a component that has a bootstrap dropdown, I want to focus on the current week that is set on the dropdown span
I can do it with plain javascript by setting ids, and then using Jquery .focus() method to focus on it, But wanted to know if there is any angular 7/ 7+ way to do it using ViewChildren etc.
<button class="btn dropdown-toggle"
        (click)="focusOnWeek(currentWeek)"
        type="button" data-toggle="dropdown">
  Week {{currentWeek}} // currentWeek = 5 need to focus on week 5  tag on click of this span
</button>

//weekList = [1,2,3,4,5,6,7,8,9,10]>
    <a class="dropdown-item"
      Week {{week}}

On Click of Button the Currentweek is focused.

A: You can use ViewChildren to find the anchor element that you want to focus. First, you set a template reference variable (e.g. #anchor) on the anchor elements:

    Week {{week}}

In the code, you get a reference to the anchor elements with ViewChildren:
@ViewChildren("anchor") anchorList: QueryList<ElementRef>;

and you set the focus on the anchor that corresponds to the specified week:
focusOnWeek(week) {
  const weekIndex = this.weekList.indexOf(week);
  const elementRef = this.anchorList.find((item, index) => index === weekIndex);
  elementRef.nativeElement.focus();
}

See this stackblitz for a demo.

If the menu is not immediately visible when the click is made, you can monitor the creation of the menu items with the QueryList.changes event. When you detect that the items are visible, you can then set the focus with currentWeek.
ngAfterViewInit() {
  this.anchorList.changes.subscribe(() => {
    if (this.anchorList.length > 0) {
      const weekIndex = this.weekList.indexOf(this.currentWeek);
      const elementRef = this.anchorList.find((item, index) => index === weekIndex);
      elementRef.nativeElement.focus();
    }
  });
}

See this stackblitz for a demo.

A: Please add following code in html file

          Week {{week}}

add following class in css file
.focus{
   background-color: red;
}

Make sure you have change detection implemented in focusOnWeek() function.


text:
Q: Create custom Web Chat for Microsoft Bot Framework Is there a guide on how to create my own Web Chat (I don't want to be using/customizing the one that is in react). I would like to make it from scratch using Blazor or Angular, but I haven't found a good guide on how to do that.

A: No guides that I am aware of.
It also depends on what you mean. If you are wanting to build the tool that would implement something like Web Chat, then I'd recommend installing different tools to use while referencing their respective SDKs.

*

*BotFramework-WebChat is impressive but it is also quite sophisticated in its build and features.

*Botkit's Web Client, while presently deprecated, would serve as a different perspective to tackling the same problem.

*Botkit's botbuilder-adapter-web offers a different method by communicating via webhooks and websocket with a site.

Regardless, you will need to have a method for capturing the incoming messages as well as posting messages back. This means you will need to utilize the BotFramework-DirectLineJS SDK which is what BotFramework-WebChat relies on. You will then need to consider how you will want to handle the different activity types and messages that could be sent by the bot or user. For instance, how to handle:

*

*Messages:

*

*Simple text messages

*Messages with attachments: cards, adaptive cards, images, audio/speech, etc.

*Events

*ConversationUpdates, including membersAdded

*Traces

*Typing

There are accessibility considerations, as well, for the hearing- and sight-impaired, etc., plus a host of other things to think of.
Here is a custom chat I created some time ago. It does the absolute basic and is not pretty. In it I call a local token server I run for getting a valid Directline token.
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" href="favicon.ico" type="image/x-icon" />
  <title>Custom Chat Using Direct Line</title>

Custom Chat Using Direct Line

    <input type="text" class="input-box" name="input-box" value="Hi">
    <button type="button" class="input-button">Send</button>


text:
Q: Finding the value of $f(x)\times f(-x)$ I'm having trouble understanding the intuition needed to solve this problem. If  $f(0)=3$ and $f(x)\times f'(-x)=f(-x)\times f'(x)$ for all $ x $. Then how can we find the value of $f(x)\times f(-x)$.
Can someone please explain to me what the answer would be to this problem?

A: $$(f(x)f(-x))'=f'(x)f(-x)-f(x)f'(-x)=0\Rightarrow f(x)f(-x)=C$$
So $f(0)=3$ implies $C=9$

A: $$f(x) \cdot f'(-x)=f(-x) \cdot f'(x) \\ \Rightarrow \frac{f'(-x)}{f(-x)}=\frac{f'(x)}{f(x)} \\ \Rightarrow -\ln f(-x)=\ln f(x)+c \\ \Rightarrow \ln f(-x)+\ln f(x) =C \\ \Rightarrow \ln (f(-x) \cdot f(x))=C \\ \Rightarrow f(-x) \cdot f(x)=M, \text{ where } M=e^C $$
We have that $f(0)=3$ so setting $x=0$ at the above relation we get $$f(0) \cdot f(0)=M \Rightarrow M=9$$
Therefore, $$f(-x) \cdot f(x)=9$$


text:
Q: Unable to start pouchdb with directory option I have installed PouchDB on a AWS EC2 instance as shown below:
sudo npm install -g pouchdb-server --ignore-scripts

I started the server as shown below:
pouchdb-server -o aws-private-ip --dir /home/ubuntu/db

But, this is the result:
/usr/lib/node_modules/pouchdb-server/node_modules/bindings/bindings.js:96
  throw err
  ^

Error: Could not locate the bindings file. Tried:
 → /usr/lib/node_modules/pouchdb-server/node_modules/leveldown/build/leveldown.node
 → /usr/lib/node_modules/pouchdb-server/node_modules/leveldown/build/Debug/leveldown.node
 → /usr/lib/node_modules/pouchdb-server/node_modules/leveldown/build/Release/leveldown.node
 → /usr/lib/node_modules/pouchdb-server/node_modules/leveldown/out/Debug/leveldown.node
 → /usr/lib/node_modules/pouchdb-server/node_modules/leveldown/Debug/leveldown.node
 → /usr/lib/node_modules/pouchdb-server/node_modules/leveldown/out/Release/leveldown.node
 → /usr/lib/node_modules/pouchdb-server/node_modules/leveldown/Release/leveldown.node
 → /usr/lib/node_modules/pouchdb-server/node_modules/leveldown/build/default/leveldown.node
 → /usr/lib/node_modules/pouchdb-server/node_modules/leveldown/compiled/8.11.2/linux/x64/leveldown.node
    at bindings (/usr/lib/node_modules/pouchdb-server/node_modules/bindings/bindings.js:93:9)
    at Object.<anonymous> (/usr/lib/node_modules/pouchdb-server/node_modules/leveldown/leveldown.js:4:46)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/usr/lib/node_modules/pouchdb-server/node_modules/level/level.js:1:106)

Can you please suggest how to get the instance started?


text:
Q: NodeJS async.parallel inside another async.parallel In node.js, I want to have one foreach async.parallel inside another. However I got "callback was already called" error (look at the comment on my code). I want the callback to the outer only called after the inner finished. How can I do that?
async = require("async");

var asyncTasks = [];
var items = [];
/* push elements to items */

items.forEach(function(item){
  var asyncTasks2 = [];
  var items2 = [];
  asyncTasks.push(function(callback2){
    item.someAsyncCall(function(){
       /* push elements to items2 */
       items2.forEach(function(item2){
          item2.someAsyncCall(function(){
            callback2();
          })
       }
       asyncTasks2.push(function(callback2){
         setTimeout(function(){
           callback2();
         }, 100000);
       });
       async.parallel(asyncTasks2, function(){
          // All tasks are done now
          doSomethingOnceAllAreDone();
          callback(); // callback was already called
        });
    });
  });
});

asyncTasks.push(function(callback){
  setTimeout(function(){
    callback();
  }, 100000);
});

async.parallel(asyncTasks, function(){
  // All tasks are done now
  doSomethingOnceAllAreDone();
});

A: use bluebird promise
var Promise = require('bluebird');
var items = [];
return Promise.map(items, function(item){
    var items2 = [];
    return Promise.map(items2, function(item2){
        return item2.someAsyncCall();
    })
    .then(function(){
        return doSomethingOnceItems2AreDone();
    });
})
.then(function(){
    return doSomethingOnceItems1AreDone();
});


text:
Q: firebase tells me that the command "eslint." is either misspelled or could not be found Every time I enter the command in Visaul studio "firebase deploy --only functions".
VisualSTD shows me this error message
"The command "eslint." is either misspelled or
could not be found."
I want to connect firebase to my app and I get this error every time. I do not know what is wrong have already included all other functions with
{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint.",
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "12"
  },
  "main": "index.js",
  "dependencies": {
    "nodemailer": "6.4.17",
    "firebase-admin": "^9.2.0",
    "firebase-functions": "^3.11.0"
  },
  "devDependencies": {
    "eslint": "^7.6.0",
    "eslint-config-google": "^0.14.0",
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

and this is what I get in the Console
The command "eslint." is either misspelled or
could not be found.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint.`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\samo1\AppData\Roaming\npm-cache\_logs\2021-01-28T15_12_42_887Z-debug.log
events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: spawn npm --prefix "%RESOURCE_DIR%" run lint ENOENT
    at notFoundError (C:\Users\samo1\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:6:26)
    at verifyENOENT (C:\Users\samo1\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:40:16)
    at ChildProcess.cp.emit (C:\Users\samo1\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:27:25)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12)
Emitted 'error' event on ChildProcess instance at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12) {
  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'spawn npm --prefix "%RESOURCE_DIR%" run lint',
  path: 'npm --prefix "%RESOURCE_DIR%" run lint',
  spawnargs: []
}

A: Try to install eslint-cli globally first
npm -g i eslint-cli

Then in your project folder
npm i eslint --save-dev


text:
Q: SecKeychainItemExport get private key data, but convert to OpenSSL EVP_PKEY error I use SecKeychainItemExport to get the raw data of public key and private key. The code:
CFDataRef key_data = NULL;
ret = SecKeychainItemExport(key_ref, kSecFormatBSAFE, 0, NULL, &key_data);

and the public key convert is ok:
 d2i_RSA_PUBKEY_bio(public_key_bio, &rsa1_ptr);
 EVP_PKEY_set1_RSA(evp_public_key_ptr, rsa1_ptr);

but the private key's convert is fail:
 d2i_RSA_PrivateKey_bio(private_key_bio, &rsa2_ptr);

the ERR_print_errors_fp(stdout) dump the err:
16586:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1315:
16586:error:0D06C03A:asn1 encoding routines:ASN1_D2I_EX_PRIMITIVE:nested asn1 error:tasn_dec.c:827:
16586:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:747:Field=n, Type=RSA
16586:error:0D09A00D:asn1 encoding routines:d2i_PrivateKey:ASN1 lib:d2i_pr.c:99:

i use openssl asn1parse, is print out the info of the privatekey.der file:
OpenSSL> asn1parse -inform DER -in privatekey.der
    0:d=0  hl=4 l= 630 cons: SEQUENCE
    4:d=1  hl=2 l=   1 prim: INTEGER           :00
    7:d=1  hl=2 l=  13 cons: SEQUENCE
    9:d=2  hl=2 l=   9 prim: OBJECT            :rsaEncryption
   20:d=2  hl=2 l=   0 prim: NULL
   22:d=1  hl=4 l= 608 prim: OCTET STRING      [HEX DUMP]:3082025C02010002818100A75F05604B1E303CC8174081D8BF2BD96826E1224327464EE274E07568F8D226A5FE03DBBE6830BB1FB7B48F0DAFF3B9E4A9DDD14783CCA11310B0FBE5CFC5A71C5DD9725A5340EA0A8347346B3B2D5E5041EA69E18179242A26F2238F2922DE3C0D7627710C923F954448D6E886A077CC0BE653387ADDA6D28E1EA4C6336C6902030100010281804681A8EA1FBADFE73B0350916295660B77ECA8FA9DFF7586D5AF16BF5F3132964566F48925750ED245524625DD463A0E1D5DD1ABCFCC9DEF5CF0B31DEA79D4711AF6A2466DD3594F214C7B7075580728F027040C0840B464FD2141F907D4837C23AFBDE9408AA53F6949B0F8FC98477FB224136D8917915297D3C348BC63AD61024100D41418FA9B2B8851D70ED3FCBFC6DAE08EBE78E7E89109D65D72BA7CDF61557BE1409E39C2999890878EB7CAA88D22E140FE442761D7E31AB0A9561F8366E3D3024100CA08A56B35883D353805484B780ACB65E039980DC3B50BEC16ADD89A8111A7FD9FC0BCB1D4D6C511F370559A8D68808E383B5A0D4ED65D304900A58A15F3D553024100CA891701DE46C8BD3FE10D5A87DBE51427BE87C1123DD163438359CDFF96F90881AA3071810326CC80692FE4FEEB2AB06C5D67C1249404736CDB8B40354181B902402F6FF04747FE8140A9B2B3D2E490C4495B68AA8730D8A5BFFD633C64AAC1968C3AA26AABE6A9B7040C00E858ADB347DC1CDFF2B90535D813AA50788DFFB18CF9024051651FEA85A8DC1BCE7B4774A38989ACAF118E26CD25CC7098A887E982DF112439B4A896EDF948E2E886BF7642198F87D792D2D3692B2005EE72D4BB0CB73786

and the openssl generated key parse info is:
OpenSSL> asn1parse -inform DER -in openssl.privatekey.der
    0:d=0  hl=4 l= 604 cons: SEQUENCE
    4:d=1  hl=2 l=   1 prim: INTEGER           :00
    7:d=1  hl=3 l= 129 prim: INTEGER           :BFEC6EF278EAA85FFAB7641348A3BB2B448D88DAA83D91375F95C5C3DFAFDCA13C771A4C86A5A56718FCB1A3F5EDF28CCD0193809C43F5D95E7F944E95A50BF1F31FD01E969C82E21ED20BD4DD9AA683A3E09F7AF2E6C501BD7A448AA21E0245C9E02F925AEF073D39481AAAD1440DD024ED6ADC57303AC3BD26003C51747E23
  139:d=1  hl=2 l=   1 prim: INTEGER           :03
  142:d=1  hl=3 l= 128 prim: INTEGER           :7FF2F4A1A5F1C59551CF980CDB17D21CD85E5B3C70290B7A3FB92E82951FE86B7DA4BC33046E6E44BB532117F9494C5DDE010D00682D4E90E9AA62DF0E6E07F579E5B2F78EEC1B6A8EB6EECD498131976261571707CDEDE4AAAB69B98356F4F39A274A3D0ED6B8DB374296D7895E6B144AB63AA6A467A13787A2F24F08D866DB
  273:d=1  hl=2 l=  65 prim: INTEGER           :ECBF357666549510226D953FAFBE0E8CCDC88D0C73644FA8C9D8B7F0DCB9FD092BD7EFD707839BFC497935874882154F7890310474F71A938C316FB4EF2A84DD
  340:d=1  hl=2 l=  65 prim: INTEGER           :CF880E34D9E5C4B2265210613F9ACD93C2860FCBF3CD9081F3A06E03806195CF36CD505FBD2955F81CEB02E03AB457E23C4BE1DDEB9DAE5CE5802510D5055EFF
  407:d=1  hl=2 l=  65 prim: INTEGER           :9DD4CE4EEEE30E0AC19E637FCA7EB45DDE85B35DA242DFC5DBE5CFF5E87BFE061D3A9FE4AFAD12A830FB7904DB01638A506020ADA34F670D0820F5234A1C5893
  474:d=1  hl=2 l=  65 prim: INTEGER           :8A5AB4233BEE83216EE16040D511DE6281AEB532A2890B014D159EAD00410E8A2488E03FD370E3FABDF201EAD1CD8FEC28329693F2691EE8990018B5E358E9FF
  541:d=1  hl=2 l=  65 prim: INTEGER           :EA03B3BC171D1642CA7AA4D34226CE23CE079410341393FFFEF550B31E3D9D686BDA99ABC72478FBA0D3D36C91EA3E970B9DA95A1F91519F197F71A06208549A

i changed the parameter (format) of SecKeychainItemExport, but have no effection.
is the useage of SecKeychainItemExport right?
how can i convert the private key to EVP_PKEY?

A: I just stumbled upon this exact same problem.
I had to go through the source code of PEM_write_bio_PrivateKey before I finally found the code that writes the private key in DER format like we want:

i2d_PKCS8PrivateKey_bio(private_key_bio, evp_private_key_ptr, NULL,
  NULL, 0, NULL, NULL);

In your case, you'll just have to use d2i, instead of i2d like I did:

d2i_PKCS8PrivateKey_bio(private_key_bio, &evp_private_key_ptr, NULL, NULL);


text:
Q: Modifying sphinx_bootstrap_theme method rendering I have some API Documentation which I'm mostly happy with.
I'm using the sphinx_bootstrap_theme to render my doc style.  However, I want to modify how each API method renders.
Today the docs look like this:

I want to make a small change to the bootstrap theme, such that I get an HR between every method like this:

QUESTION:
Where do I modify sphinx_bootstrap_theme such that I can customize the rendering of these methods?
I looked through the sphinx_bootstrap_theme templates, but I can't seem to find the template I have to monkey with to make this work right.
If you want to see how I've configured my docs, you can find the source tree here

A: Usually, it is a bit tricky to tweak the original code. What I personally do and so far was happy with is the overwrite the existing style by adding a custom css to implement some minor changes. The way I do it:

*

*Create a folder called css under source/_static

*Add a new css (for example: custom.css) file that includes your desired changes.

*Add the following code to your conf.py
def setup(app):
    app.add_stylesheet('css/custom.css')

*

*Save and build

For more check this


text:
Q: Inheritance - insert records just on the specialized table My base table already has some register ID = 5.
How can I add the same id on the specialized table?
Example:
BaseTable
ID INT
Name Varchar(100)

DerivedTable
ID INT
Test BIT

I insert some values on the base table
Context.BaseTable.Add(new BaseTable(){ Name = '123' });
Context.SaveChanges();

The identity is 5
Now I want to add the specialized values
Context.DerivedTable.Add(new DerivedTable(){ ID = 5, Test = 1 });
Context.SaveChanges();

It didn't work, linqpad is showing to me that sql is trying to create a new BaseTable register.
Is that any way to work around this?
Tks

A: If you have it mapped as inheritance (EDMX TPT, Code first TPT) you must not insert into base table separately (it should most probably be abstract class in your model). You must only insert to derived table and EF will handle insertion to both mapped tables:
Context.DerivedTable.Add(new DerivedTable(){ Name = "123", Test = 1 });
Context.SaveChanges();


text:
Q: How to combine a datetime column and an int column into a datetime column How to combine a datetime column and an int column into a single datetime column?
DateTime                  TimeInt
--------------------------------------
2017-09-04 00:00:00.000   1409858857

Combine both into datetime with hour, minute and second

A: I'm assuming that INT is a milliseconds which is 17 days, 7 hours, 37 minutes, 38 seconds...
declare @table table (dt datetime, i int)
insert into @table
values
('2017-09-04 00:00:00',1409858857)

select
    dt + dateadd(millisecond,1409858857,0)
from
    @table


text:
Q: Can all stages of the cumulative hierarchy beyond $V_\omega$ violate the weak partition principle? This question is a follow up of this.
Is it consistent for ALL infinite stages $V_{\alpha >  \omega}$ of the cumulative hierarchy of $\sf ZF$, to violate the weak partition principle? That is, each $V_{\alpha >  \omega}$ can be parititioned into strictly more compartments than its elements.
The connection with the prior question is that if this question is answered to the positive, then the answer to the second question in the prior question would be answered to the positive as well.


text:
Q: How to use post method when clicking hyperlink in email body using Jmail? Im using Jmail to send an email from a classic asp page.
The email contains hyperlinks for service ratings that the customer can click, for a vote.
Upon clicking this hyperlink an asp page opens in the browser with a thank you message. Currently the rating value and other info are passed as queryStrings as part of the hyperlink url to the asp page. How can i send this data as a post method instead of get from within the email?


text:
Q: How to fix data no loading in hard refresh/ cache clean refresh I want to display a particular div inside a section depending on the value of my flag. I am not able to display it as soon as I clear the cache and try to load it. This is happening for the first time only i.e. after I clear the cache and load response for the first time. Rest of the time its working fine.
tried using v-if and v-else-if, in where I had two seactions, But that gave other issues like some of my tables and columns did not load.

// .js file

processResponse: function(response){
            if(!response.data){
                return false;
            }

            if(response.data.error !== undefined){

                this.animateResults();

            } else {

                this.flag = response.data.flag

                if(this.flag){
                    $("div.scheme-lookup-component-descoped").show();
                    $("div.scheme-lookup-component-results-notdescoped").hide();
                }
                 else{
                    $("div.scheme-lookup-component-results-notdescoped").show();
                    $("div.scheme-lookup-component-descoped").hide();
                    //this.animateResults();
                }
            }

            animateResults: function() {
            const self = this;
            if(!this.resultsShown) {
                Vue.nextTick(function() {
                    $(".scheme-lookup-component-results").velocity("slideDown", {
                        duration: 500,
                        complete: function () {
                            $('.scheme-lookup-component-results__title-section').velocity('scroll', {duration:1000, easing: "ease-in-out", offset: -16});
                            customPrint.preparePageForPrint();
                            self.resultsShown = true;
                        }
                    },);
                })

# html code #

Expected result is that I should be able to view my div even after clearing the cache and loading it. As of now, I am unable to view the  result after I clean up the cache


text:
Q: In Flutter Quill,how can i get the input value like TextField onChange I want to get the input value when input is changed,just like TextField onChange. Many thanks

A: Use _controller.document.toDelta() to extract the deltas.
Use _controller.document.toPlainText() to extract plain text.

A: We can use controller for getting the changes.
_controller.document.changes.listen((event) {
});


text:
Q: LinkedIn OAuth token with Javascript SDK I was integrating LinkedIn sign-in with my web application,
Initially I was doing the implementation using JS SDK. After I realised that for iOS Mobile Devices, LinkedIn does not support JS SDK. So Currently I am using OAuth implementation.
My question is,  Is there any way to use JS SDK after getting OAuth login success and after getting the access token. My point is, I don't want to do the logic for token validation, expiration etc.
PS - Similar feature I have found in Facebook SDK, they are allowing to use Facebook JS SDK after setting the access token to SDK.
Please share your thoughts, comments, links.
Thanks in advance.

A: You are using JS SDK, which has all of the following features to work with authorization, tokens etc.
Example:
IN.User.authorize()
IN.User.logout()
IN.User.refresh()
IN.API.RAW.... etc


text:
Q: ItemsControl panel generation Does anybody know how i can determine if itemscontrol panel has been generated?
I am building a custom control that contains itemscontrol with Grid set as ites panel and cant figure out the proper way to obtain the itemscontrol panel from code behind.
Control Template
    <Style TargetType="{x:Type local:DayTimeRange}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:DayTimeRange}">

                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">

                    <ItemsControl
                                      Name="PART_ItemsControl"
                                      AlternationCount="1"
                                      IsEnabled="{Binding HasTimeRange,RelativeSource={RelativeSource AncestorType=local:DayTimeRange}}">
                        <ItemsControl.ItemContainerStyle>
                            <Style>
                                <Setter Property="Grid.Row" Value="{Binding GridRow,Mode=OneWay}" />
                                <Setter Property="Grid.Column" Value="{Binding GridColumn,Mode=OneWay}" />
                                <Setter Property="Grid.RowSpan" Value="{Binding GridRowSpan,Mode=OneWay}" />
                                <Setter Property="Grid.ColumnSpan" Value="{Binding GridColumnSpan,Mode=OneWay}" />
                            </Style>
                        </ItemsControl.ItemContainerStyle>
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <Grid x:Name="PART_Panel" IsItemsHost="True"/>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>
                    </ItemsControl>

                </Border>

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

So what would be the best way to get the actual Panel?

A: You can simply used its Loaded event and access it there. Something like:
xaml:
<Grid>
    <ItemsControl Loaded="OnItemsControlLoaded">

    </ItemsControl>
</Grid>

code-behind:
    private void OnItemsControlLoaded(object sender, RoutedEventArgs e)
    {
        var itemsControl = sender as ItemsControl;
        if (itemsControl != null)
        {
            // use here
        }
    }


text:
Q: Segmenting Image by Pixel Value I have a large image (about 12000 pixels by 10000) that I am trying to segment by pixel value. The different pixel values for every image were generated with OpenCV's cv.connectedComponentsWithStats. Every single object in the image has a different pixel value and there are about 10k objects in each image. How do I create binary arrays for each object based on different pixel values? Here's an example:
I start with this image:

Where every green colored object has a different pixel value. How do I make something like this for every single object ?

Ideally, this would take one input array with n different pixel values for each object and return n binary arrays for each object.


text:
Q: Tastypie, field from an attribute or function? For instance, I'd like to add absolute_url field when I return my model's json data.
I added the following to my model
@property
def absolute_url(self):
    return self.get_absolute_url()

then in my tastypie resource
absolute_url = fields.CharField(attribute="absolute_url", readonly=True)

class Meta:
    fields = [... 'absolute_url' .. ]

But this was not enough to make my resource to include the absolute_url data in the JSON response.
I had to use dehydrate to include the field.
The doc isn't clear about the effect of defining a field (here absolute_url CharField).

A: It turns out 'absolute_url' is rather special field in tastypie, and there's an even option for it.
include_absolute_url


text:
Q: How can I set "Login" as text for anonymous and "Logout" for authenticated users in twig and symfony2? I have a menu that all items appear for all users and I want to hide/show specific items to specific ROLE users in symfony2.
For example, I have

{{ 'menu.home'|trans }}

{{ 'menu.articles'|trans }}

{{ 'menu.categories'|trans }}

{{ 'menu.users'|trans }}

{{ 'menu.logout'|trans }}

Now Logout appears to all users, even If they are not logged in. How can I make twig check whether a user is authenticated or not and then choose

{{ 'menu.login'|trans }}
 ?

A: In Twig do following check:
{% if app.user %}

{{ 'menu.logout'|trans }}

{% else %}

{{ 'menu.login'|trans }}

{% endif %}

In case if you have different roles and you'd like to render some parts of the page dependent on user role, you can do next check:
{% if is_granted('YOUR_ROLE') %} ... {% endif %}


text:
Q: How to capture a form element and use dynamically in the post url? I'm trying to build a form which submits a URL which contains a lon/lat that has been passed over from Google Maps.  I have managed to get it so the lon/lat is passed into input fields in the form, how would I go about using these values dynamically in the post URL, i.e.:
action="search.asp?[lon][lat]

A: If you want to get the values from the form into the URL, set the method attribute to get:
<form method="search.asp" action="get">

. This will put the values of the lon and lat fields of the form in the URL. Example:
search.asp?lat=[lat value]&lon=[lon value]

For more information, read this page. Excerpt:

If the processing of a form is
  idempotent (i.e. it has no lasting
  observable effect on the state of the
  world), then the form method should be
  GET. Many database searches have no
  visible side-effects and make ideal
  applications of query forms.

A: Using javascript you can change the action attribute of the form. So, create a form..
<form name="myForm">
  <input type="hidden" name="lon" value="123" />
  <input type="hidden" name="lat" value="321" />
  ...
  <button onclick="setAction();">Submit</button>
</form>

Then in the head of the page add the setAction function..
<script type="text/javascript">
  function setAction()
  {
    var lon = document.myForm.lon.value;
    var lat = document.myForm.lat.value;

    document.myForm.action = "search.php?["+lat+"]["+lon+"]"';
    document.myForm.submit();
  }
</script>

Hope this helps, it's how I have done this in the past!

A: Try using:
<form action="search.php" method="get">
 <input type="hidden" name="lon" value="<?php echo $lon_fromGoogleMaps; ?>" />
 <input type="hidden" name="lat" value="<?php echo $lat_fromGoogleMaps; ?>" />
 <!-- The Rest of your Form... -->
 <input type="submit" value="Submit!" />
</form>

Or if you want to use the form as post:
<form action="search.php?lon=<?php echo $lon_fromGoogleMaps; ?>&lat=<?php echo $lat_fromGoogleMaps; ?>" method="post">
 <!-- The Rest of your Form... -->
 <input type="submit" value="Submit!" />
</form>

I see you tagged this as Javascript as well, and as Google Maps relies heavily on Javascript, you may have the Lon and the Lat passed as Javascript variables...
<script type="text/javascript">
 // Obviously, execute this code after the DOM has loaded...
 var formAction = document.searchForm.action;
 formAction = formAction + '?lon=' + lon_fromGoogleMaps + '&lat=' + lat_fromGoogleMaps;
 document.searchForm.action = formAction;
</script>
<form action="search.php" method="post" name="searchForm">
 <!-- The Rest of your Form... -->
 <input type="submit" value="Submit!" />
</form>


text:
Q: Oracle index specified in index hint is invalid I have 2 scenarios where I'm using the hint IGNORE_ROW_ON_DUPKEY_INDEX. The first seems to be working fine. The second scenario is failing with the error below and I'm unsure how to fix it.
ORA-38913: Index specified in the index hint is invalid

I'm testing on live SQL so our environments can be the same if you so desire.
ALTER SESSION SET NLS_DATE_FORMAT = 'MMDDYYYY HH24:MI:SS';

 create table t (
    t_pk integer not null primary key
  );

 insert /*+ IGNORE_ROW_ON_DUPKEY_INDEX (t (t_pk)) */ into t values (1);

insert /*+ IGNORE_ROW_ON_DUPKEY_INDEX (t (t_pk)) */ into t values (1);

CREATE table t1(
      seq_num INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL,
       a NUMBER,
       b  DATE,
       c NUMBER,
       d NUMBER,
       e DATE,
       f DATE,
       g DATE,
       h VARCHAR2(1),
constraint t1_pk primary key (a, b,c,d,e, f, g,h)
       );

insert /*+ignore_row_on_dupkey_index (t1 ( t1_pk)) */ INTO t1(
       a
       ,b
       ,c
       ,d
       ,e
       ,f
       ,g
       ,h
 )
VALUES
 (1,
TO_DATE('2021-08-28 00:00:00', 'YYYY-MM-DD HH24:MI:SS'),1,1,
TO_DATE('2021-08-28 13:27:00', 'YYYY-MM-DD HH24:MI:SS'),
TO_DATE('2021-08-28 13:30:00', 'YYYY-MM-DD HH24:MI:SS'),
TO_DATE('2021-08-28 13:27:20', 'YYYY-MM-DD HH24:MI:SS'), 'G');

A: Your syntax for the second case is incorrect. Valid syntax when giving a list of columns is like this:
/*+ignore_row_on_dupkey_index ( table_name ( column_1, column_2, ... )) */

or like this when naming an index:
/*+ignore_row_on_dupkey_index (table_name , index_name) */

In your first example, you named your column t1_pk, so the ( table ( column )) syntax is correct. In your second example, you named your contraint t1_pk, so you need to use the (table,index) syntax form.
See documentation here: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/Comments.html#GUID-20390275-91A7-49DC-AAD1-A1FE943A4F75


text:
Q: preserve textbox data after an Ajax request with RenderResponse call with JSF 2.0 How can I preserve the textboxes values when I perform an ajax action with immediate = true? I need to render the entire form. I want to skip the validations and update model phases when the ajax action is performed. I've tried using FacesContext.getCurrentInstance().renderResponse() at the end of the method that is invoked by the ajax actions but it doesn't work. Old values appear in the textboxes or some data is cleared in some textboxes. I don't want to update the backing bean yet.
What I want to do is to keep the information that the user is filling in the textboxes. The Ajax button that I use adds dynamically more textboxes and I set render attribute, in the ajax button, to render the entire page (I need to do a complete render). Inside the method I call with the ajax action I have "FacesContext.getCurrentInstance().renderResponse();"
the button code is:
<h:commandButton id="btnAdd" value="Add" type="button">
<f:ajax event="click" execute="@form" render=":form" listener="#{ManagedBean.add()}"/>
</h:commandButton>

And the listener action is:
public void add() {
   Person p = new Person();
   ManagedBean.getPeople().add(p);
   FacesContext.getCurrentInstance().renderResponse();
}

I have an ui:repeat to iterate in the "people" List and the code of the textbox is:
<ui:repeat value="#{ManagedBean.people}" var="currentPerson" varStatus="i">
<h:inputText id="p" readonly="false" label="Person" value="#{currentPerson.name}"  >
</h:inputText>
</ui:repeat>

I was debbuging the JSF phases and I got:
[2/7/12 15:06:33:584 CST] 0000002f SystemOut     O START PHASE RESTORE_VIEW 1
[2/7/12 15:06:34:375 CST] 0000002f SystemOut     O END PHASE RESTORE_VIEW 1
[2/7/12 15:06:34:981 CST] 0000002f SystemOut     O START PHASE APPLY_REQUEST_VALUES 2
[2/7/12 15:06:35:553 CST] 0000002f SystemOut     O END PHASE APPLY_REQUEST_VALUES 2
[2/7/12 15:06:36:089 CST] 0000002f SystemOut     O START PHASE RENDER_RESPONSE 6
[2/7/12 15:06:44:364 CST] 0000002f SystemOut     O END PHASE RENDER_RESPONSE 6

It is there a way to pull the data from the textboxes and set it again to them in the view after the ajax call? Thanks.

A: you could use a wrapper class for the persons in people. Then you can let JSF call the setters and the original person objects wont' be touched.
MAG,
Milo van der Zee


text:
Q: Abrir una ventana dentro de otra que esta en otro archivo en tkinter python No puedo abrir una ventana dentro de otra que esta en otro archivo, por ejemplo: Quiero hacer un juego pero quiero hacer una ventana principal donde agrego un boton y cuando lo presiono, me abra la otra ventana del juego y esta ultima ventana es de otro archivo.
import tkinter as tk
from tkinter import *
import tkinter
from subprocess import call
import Fx2
#Fx2 es el nombre del segundo archivo

def opne_window():
    app.destroy()

    call(["Fx2.py"])

app = Tk()
app.title("GAME")
buttonExample = tk.Button(app,
              text="Open window",
              command=opne_window)
buttonExample.pack()

app.mainloop()

A: El siguiente código de dos archivos (application.py y fx2.py) podría servir:
# application.py
import tkinter as tk

from fx2 import Fx2

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.button = tk.Button(self)
        self.button["text"] = "Open"
        self.button["command"] = self.open
        self.button.pack()

    def open(self):
        Fx2(self.master)

root = tk.Tk()
app = Application(master=root)
app.mainloop()

# fx2.py
import tkinter as tk

class Fx2(tk.Toplevel):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.create_widgets()

    def create_widgets(self):
        self.message = tk.Message(self, text="Hello")
        self.message.pack()

Se puede ejecutar usando python3 application.py.
application.py es el archivo principal. Importa Fx2 definida en fx2.py. Define una ventana que tiene un único botón que al presionarse muestra una nueva ventana (Toplevel) definida en el segundo archivo fx2.py.
fx2.py es el archivo secundario. Define una ventana que tiene un mensaje.
Este código está basado en este ejemplo de la documentación de Tkinter.


text:
Q: How to past an array of objects to server from android? I am trying to send an array with a bunch of objects back to android?
I tried String Builder like so:
StringBuilder sb = new StringBuilder();
        sb.append("[");
        for(int i = 0; i <usersChanged.size(); i++) {
            DatabaseUser userChange = usersChanged.get(i);

                if(userChange.getIsFollowingType() == 0) {
                    String userIdStr = "{userId:" +  userChange.getUserId() + ",";
                    String followingStr = "following:" +  String.valueOf(userChange.getIsFollowingType())+ "}]";
                    sb.append(userIdStr).append(followingStr);

but I am doing something wrong here. On my server side I am using node.js and would parse the array if I send over a string no problem, but this is not sending a string version of the array? What do I need to change on my string builder? Or is there a more efficient way to send over the list of usersChanged - (which is List)
I am using retrofit if there is a way to do it easy with that.

A: Your code will send things like
[{userId: someuserid, following: someparameter}]
You need to have the double quote (" ") sent over as well.
for(int i = 0; i <usersChanged.size(); i++) {
        DatabaseUser userChange = usersChanged.get(i);

            if(userChange.getIsFollowingType() == 0) {
                String userIdStr = "{\"userId\":\"" +  userChange.getUserId() + "\",";
                String followingStr = "\"following\":\"" +  String.valueOf(userChange.getIsFollowingType())+ "\"}]";
                sb.append(userIdStr).append(followingStr);

You should also probably move the "]" to after the loop.
EDIT:
Forgot to mention this, but you can definitely use JSONArray and JSONObject to make your life easier.
JSONArray jsonArray = new JSONArray();
for(...){
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("userId", userChange.getUserId());
    jsonObject.put("following", String.valueOf(userChange.getIsFollowingType()));
    jsonArray.put(jsonObject);

}

Then send over the jsonArray.


text:
Q: Endothermic reactions and climate change I have seen some questions regarding climate change. What I want to know is would generating endothermic reactions in a mass controlled state counter balance global warming and reduce heat effect energies? Therefore by using thermal energies to complete the reaction and lowering external temperature such as photosynthesis reaction we could use up a lot of planetary thermal energy without adding mass. And why is the pole so cold but the equator hot.

A: The issue is that the greenhouse effect causes us to hold onto more energy from the sun, which is coming in at a constant rate.  To stop this with endothermic reactions, you would need to continuously find more raw materials to react.
And you would need a LOT of them.  From one of my favorite tables in the world, Orders of Magnitude (Energy):

*

*$5\cdot10^{20} \text J$ -- Total world annual energy consumption

*$150\cdot10^{20} \text J$ -- Total energy from the Sun that strikes the face of the Earth each day

*$390\cdot10^{20} \text J$ -- Estimated energy contained in the world's fossil fuel reserves as of 2010

Yes, that much energy hits the planet every day.  Even just a fraction of that would quickly swamp any endothermic reaction efforts we could muster.

A: You would need to continue to do the reaction indefinitely to offset warmer temperatures. If greenhouse gas levels stay high with constant sun and no other factors, more energy would always be being absorbed by the atmosphere than the environment could handle (warming was an initial part of the question). I am sure that any endothermic reaction would have a waste product, so eventually that waste product would start to pile up with no end in sight. Additionally, I am sure an endothermic reaction doesn't take much energy from an environment and the ones available to react that don't require energy in before we can do them (starting products are just sitting around in nature) are pretty small, and would require a lot of refining (which takes energy and produces heat) to get them in amounts to have a reaction you are looking for. Fundamentally though, yes, the heat is more of a problem than the extra CO2, that just makes plants photosynthesize a bit faster.
The poles are cold due to the light being at an angle. Imagine a beach ball being hit by light from a flashlight across the room. the middle (equator) of it will be brighter (warmer) than the poles, which are close to perpendicular. If you were standing on the beach ball as a planet, at the poles, your shadow would be long, at the equator, it would be directly beneath you.

A: Well, yes, but not because these endothermic reactions would directly absorb the heat being generated.  The earth naturally radiates heat out into space in an equilibrium with the heat being put onto it by the sun every day.  CO2 is a problem because it is building up in the atmosphere and it prevents the process of heat radiation into space.
Photosynthesis is an endothermic reaction and more photosynthesis would help solve the climate change problem, but not because it is endothermic.  There is a natural balance in nature between the combustion of hydrocarbons and photosynthesis.  Animals all combust sugars which are essentially hydrocarbons with oxygen in the cell respiration process to generate energy and this process releases CO2.  This is the chemical equation for cell respiration:
glucose + oxygen → carbon dioxide + water + usable energy
C6H12O6 + 6O2 → 6CO2 + 6H2O + 38 ATP
Plants including phytoplankton in the world's oceans conduct photosynthesis which absorbs CO2 and produces Oxygen that animals then breathe.  This is the chemical equation for photosynthesis:
6H2O + 6CO2 →(sunlight)= C6H12O6 + 6O2
The reason that climate change is occurring is that we are burning fossil fuels which is causing the build-up of CO2 in the atmosphere and prevents heat from radiating out into space.  We are releasing far more C02 than the planet can absorb naturally.


text:
Q: javascript append html to appended before I am trying to append HTML that appended before. Like first Append the key, then append another one to that key.
My goal is to create nested DOM.
Here is the sample,

let result = [
   {
      "name":"Component Murah",
      "slug":"components-component-murah-34",
      "id":34,
      "parent":1
   },
   {
      "name":"Gadget Case",
      "slug":"components-component-murah-gadget-case-35",
      "id":35,
      "parent":34
   },
   {
      "name":"Components",
      "slug":"components-1",
      "id":1,
      "parent":false
   },
];

$.each(result, function(i, field) {
  if (field['parent'] == false){
    $(`ul[class=nav-categories]`).append(
        `

            ${field['name']}

`);

  }

  $.each(result, function(i, field){
    if (field['parent'] != false){
      $(`li[class=child-${field['parent']}]`).append(
        `

            ${field['name']}

`);

    }
  });
});

First one works as well, the second one that finds parent is not working?...
Thank you!

A: I think you forgot to close the first $.each....Check this sample
 var res = [
   {
      "name":"Component Murah",
      "slug":"components-component-murah-34",
      "id":34,
      "parent":1
   },
   {
      "name":"Gadget Case",
      "slug":"components-component-murah-gadget-case-35",
      "id":35,
      "parent":34
   },
   {
      "name":"Components",
      "slug":"components-1",
      "id":1,
      "parent":false
   },
]

$.each(res, function(i, field){
   if (field['parent'] == false){
       $(`ul[class=nav-categories]`).append(
           `<li class='child-` + field['id'] + `'>
               <a href='/shop/category/` + field['slug'] + `'>
                   ` + field['name'] + `

`);
    }
});
$.each(res, function(i, field){
   if (field['parent'] != false){
       $(`li[class=child-` + field['parent'] + `]`).append(
           `<li class='child-` + field['id'] + `'>
               <a href='/shop/category/` + field['slug'] + `'>
                   ` + field['name'] + `

`);

   }
});

A: Check this sample. It has some improvements over your code (Like correct usage of back ticks)

let result = [
   {
      "name":"Component Murah",
      "slug":"components-component-murah-34",
      "id":34,
      "parent":1
   },
   {
      "name":"Gadget Case",
      "slug":"components-component-murah-gadget-case-35",
      "id":35,
      "parent":34
   },
   {
      "name":"Components",
      "slug":"components-1",
      "id":1,
      "parent":false
   },
];

$.each(result, function(i, field) {
  if (field['parent'] == false){
    $(`ul[class=nav-categories]`).append(
        `

            ${field['name']}

`);

  }
});

$.each(result, function(i, field){
  if (field['parent'] != false){
    $(`li[class=child-${field['parent']}]`).append(
      `

          ${field['name']}

`);

  }
});


text:
Q: Sending polars Dataframe via juniper GraphQL I am trying to send the Polars dataframe over juniper GraphQL, but #[juniper::graphql_object] is complaining about trail bound
the trait bound `Result<HashMap<std::string::String, polars::prelude::DataFrame>, FieldError>: IntoResolvable<'_, __S, _, ()>` is not satisfied
the following other types implement trait `IntoResolvable<'a, S, T, C>`:
  <Result<(&'a <T as GraphQLValue<S2>>::Context, T), FieldError<S1>> as IntoResolvable<'a, S2, T, C>>
  <Result<T, E> as IntoResolvable<'a, S, T, C>>
  <Result<std::option::Option<(&'a <T as GraphQLValue<S2>>::Context, T)>, FieldError<S1>> as IntoResolvable<'a, S2, std::option::Option<T>, C>>

Here is my Rust code.
use juniper::{EmptySubscription,
            FieldResult,
            RootNode,
            EmptyMutation};
use polars::prelude::DataFrame;
use std::collections::HashMap;

pub struct QueryRoot;

#[juniper::graphql_object]
impl QueryRoot {
    fn fetch_data() -> FieldResult<HashMap<String, DataFrame>> {
        // ...
        let data: HashMap<String, DataFrame> = fetch_my_data();
        Ok(data)
    }
}

pub type Schema = RootNode<'static, QueryRoot, EmptyMutation, EmptySubscription>;

pub fn create_schema() -> Schema {
    Schema::new(QueryRoot {}, EmptyMutation::new(), EmptySubscription::new())
}

I am guessing that juniper cannot recognize polar's Dataframe struct as graphqlobject. I am wondering if anyone knows how to fix this compile error. I also tried with serde_json, but no luck so far.


text:
Q: Does C# optimize code automatically in looped/lambda statements? In Javascript for example, one is strongly encouraged to place function calls outside of loops for better performance:
var id = someIdType.ToString();
someList.Where(a => a.id == id) ...

How about C#? Same case or does the compiler/runtime employ internal optimization/caching?
someList.Where(a => a.id == someIdType.ToString()) ...

Probably a noob question and has been asked before, but can't find a reference.

A: The lambda will be executed for each element of the list.. Hence the code someIdType.ToString() will execute for every element. I don't think compiler or runtime will cache it for you. (AFAIK someIdType will be captured in a closure, but not .ToString())
EDIT:
The original question was only about "Does?", but not about "Why?", but still there are several comments and other answers which attempt to answer / demonstrate "Why?".
Given so much interest around "Why?" I am editing my answer to state my version of "Why?".
i.e. if you look at C# specification, for any of the relevant scenarios, the specification talks about capturing the variable.. not capturing the expression.
That is the reason why compiler behaves the way it does.. Because its not in the specification. Why is it not in the specification, is something C# Design team can answer.. Rest is speculation, parts or all of which may or may not have merit, should the feature of capturing expressions be considered.

A: C# code:
List<string> list = new List<string>();
list.Where(a => a == typeof(String).ToString());

Lambda expression in MSIL, Debug configuration:
.method private hidebysig static bool  '<Main>b__0'(string a) cil managed
{
  .custom instance void     [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  // Code size       26 (0x1a)
  .maxstack  2
  .locals init ([0] bool CS$1$0000)
  IL_0000:  ldarg.0
  IL_0001:  ldtoken    [mscorlib]System.String
  IL_0006:  call       class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
  IL_000b:  callvirt   instance string [mscorlib]System.Object::ToString()
  IL_0010:  call       bool [mscorlib]System.String::op_Equality(string,
                                                             string)
  IL_0015:  stloc.0
  IL_0016:  br.s       IL_0018
  IL_0018:  ldloc.0
  IL_0019:  ret
} // end of method Program::'<Main>b__0'

Lambda expression in MSIL, Release configuration:
.method private hidebysig static bool  '<Main>b__0'(string a) cil managed
{
  .custom instance void     [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  // Code size       22 (0x16)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldtoken    [mscorlib]System.String
  IL_0006:  call       class [mscorlib]System.Type     [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
  IL_000b:  callvirt   instance string [mscorlib]System.Object::ToString()
  IL_0010:  call       bool [mscorlib]System.String::op_Equality(string,
                                                             string)
  IL_0015:  ret
} // end of method Program::'<Main>b__0'

Both versions call typeof(String).ToString()), this lambda is called on every iteration. No optimization on IL level, JIT compilation will not add anything here. The reason is: function may have side effects.


text:
Q: How to Run WireShark Commands in command line through C# I want to convert .pcapng files to .csv files using the below commands:
     > cd C:\Program Files\Wireshark
     > tshark -r output.pcapng -T fields -e frame.number -e eth.src -e eth.dst -e frame.len -e frame.time -e frame.time_relative -e data -E header=y -E separator=, > output.csv

In C#, I used the following code.
        string command = @"cd C:\Program Files\Wireshark & tshark -r output.pcapng -T fields -e frame.number -e eth.src -e eth.dst -e frame.len -e frame.time -e frame.time_relative -e data -E header=y -E separator=, > output.csv";
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = "CMD.exe";
        startInfo.Arguments = command;
        startInfo.Verb = "runas";
        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();

This doesnt seem to be working.

A: From cmd /?:
Starts a new instance of the Windows command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
<snip>

Try adding the /C to the start of your command string:
 string command = @"/C cd C:\ProgramFiles\Wireshark & tshark -r output.pcapng -T fields -e frame.number -e eth.src -e eth.dst -e frame.len -e frame.time -e frame.time_relative -e data -E header=y -E separator=, > output.csv";

Update:
The command below works for me. And the number of double quote characters is not a typo. It's 4 at the start of the tshark program path and 3 at the end.
cmd /k """"C:\Program Files\Wireshark\tshark""" -r output.pcapng -T fields -e frame.number -e eth.src -e eth.dst -e frame.len -e frame.time -e frame.time_relative -e data -E header=y -E separator=, > output.csv"

A: Check that path:
string command = @"cd C:\ProgramFiles\Wireshark & tshark -r output.pcapng -T fields -e frame.number -e eth.src -e eth.dst -e frame.len -e frame.time -e frame.time_relative -e data -E header=y -E separator=, > output.csv";
On my machine, Program Files has a space between the two words, and Wireshark & tshark is suspicious too.  Ampersand (especially when using shells) is interpreted differently.


text:
Q: How do I create a RSS feed? Can you help me with creating an RSS feed?

A: Any text editor should be able to do it. As for formats/etc, have a look at the Wikipedia entry and links from there:
http://en.wikipedia.org/wiki/RSS
As for code libraries, we can't help you unless you are more specific.