text:
Q: Getting kexec error when running npm install I started getting below error with node v12.22.7 and npm 6.14.15 (also tried with node v16.13.1 and npm v8.1.2)
> node-gyp rebuild

  CXX(target) Release/obj.target/kexec/src/kexec.o
../src/kexec.cc:19:11: error: no member named 'Handle' in namespace 'v8'
using v8::Handle;
      ~~~~^
../src/kexec.cc:68:27: error: no matching constructor for initialization of 'String::Utf8Value'
        String::Utf8Value str(info[0]);
                          ^   ~~~~~~~
/Users/username/Library/Caches/node-gyp/12.22.7/include/node/v8.h:3142:5: note: candidate constructor not viable: no known conversion from 'v8::Local<v8::Value>' to 'const v8::String::Utf8Value' for 1st argument
    Utf8Value(const Utf8Value&) = delete;
    ^
/Users/username/Library/Caches/node-gyp/12.22.7/include/node/v8.h:3135:5: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
    Utf8Value(Isolate* isolate, Local<v8::Value> obj);
    ^
../src/kexec.cc:78:27: error: no matching constructor for initialization of 'String::Utf8Value'
        String::Utf8Value str(info[0]);
                          ^   ~~~~~~~
/Users/username/Library/Caches/node-gyp/12.22.7/include/node/v8.h:3142:5: note: candidate constructor not viable: no known conversion from 'v8::Local<v8::Value>' to 'const v8::String::Utf8Value' for 1st argument
    Utf8Value(const Utf8Value&) = delete;
    ^
/Users/username/Library/Caches/node-gyp/12.22.7/include/node/v8.h:3135:5: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
    Utf8Value(Isolate* isolate, Local<v8::Value> obj);
    ^
../src/kexec.cc:91:75: error: no matching member function for call to 'ToString'
            String::Utf8Value arg(argv_handle->Get(Nan::New<Integer>(i))->ToString());
                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~
/Users/username/Library/Caches/node-gyp/12.22.7/include/node/v8.h:2668:44: note: candidate function not viable: requires single argument 'context', but no arguments were provided
  V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
                                           ^
/Users/username/Library/Caches/node-gyp/12.22.7/include/node/v8.h:2684:31: note: candidate function not viable: requires single argument 'isolate', but no arguments were provided
                Local<String> ToString(Isolate* isolate) const);
                              ^
../src/kexec.cc:91:48: warning: 'Get' is deprecated: Use maybe version [-Wdeprecated-declarations]
            String::Utf8Value arg(argv_handle->Get(Nan::New<Integer>(i))->ToString());
                                               ^
/Users/username/Library/Caches/node-gyp/12.22.7/include/node/v8.h:3553:3: note: 'Get' has been explicitly marked deprecated here
  V8_DEPRECATED("Use maybe version", Local<Value> Get(Local<Value> key));
  ^
/Users/username/Library/Caches/node-gyp/12.22.7/include/node/v8config.h:328:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated(message)))
                            ^
../src/kexec.cc:115:12: error: no template named 'Handle'
void init (Handle<Object> exports) {
           ^
../src/kexec.cc:116:5: error: too few arguments to function call, single argument 'context' was not specified
    EXPORT("kexec", kexec);
    ^~~~~~~~~~~~~~~~~~~~~~
../src/kexec.cc:112:51: note: expanded from macro 'EXPORT'
  Nan::New<FunctionTemplate>(symbol)->GetFunction() \
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
/Users/username/Library/Caches/node-gyp/12.22.7/include/node/v8.h:6126:46: note: 'GetFunction' declared here
  V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
                                             ^
1 warning and 6 errors generated.
make: *** [Release/obj.target/kexec/src/kexec.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/username/.nvm/versions/node/v12.22.7/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (events.js:314:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Darwin 20.6.0
gyp ERR! command "/Users/username/.nvm/versions/node/v12.22.7/bin/node" "/Users/username/.nvm/versions/node/v12.22.7/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/username/Documents/Workspace/Code/projectname/node_modules/kexec
gyp ERR! node -v v12.22.7
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
npm WARN ajv-keywords@2.1.1 requires a peer of ajv@^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN inquirer-autocomplete-prompt-ipt@2.0.0 requires a peer of inquirer@>=7 but none is installed. You must install peer dependencies yourself.
npm WARN inquirer-ordinal-prompt@1.0.0 requires a peer of inquirer@>= 7 but none is installed. You must install peer dependencies yourself.
npm WARN stylelint-config-recommended@1.0.0 requires a peer of stylelint@^8.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN stylelint-config-standard@17.0.0 requires a peer of stylelint@^8.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN zipkin-instrumentation-express@0.16.2 requires a peer of @types/express@^4.0.39 but none is installed. You must install peer dependencies yourself.
npm WARN projectname@0.0.245 No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! kexec@3.0.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the kexec@3.0.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Then I found this post
which happens to be there is no support yet available for node 7 and above versions.
So I downgraded to node v6.17.1 and npm v5.10.0 and got this error:
> kexec@3.0.0 install /Users/username/Documents/Workspace/Code/projectname/node_modules/kexec
> node-gyp rebuild

  CXX(target) Release/obj.target/kexec/src/kexec.o
clang: warning: include path for libstdc++ headers not found; pass '-stdlib=libc++' on the command line to use the libc++ standard library instead [-Wstdlibcxx-not-found]
../src/kexec.cc:1:10: fatal error: 'cstdio' file not found
#include <cstdio>
         ^~~~~~~~
1 error generated.
make: *** [Release/obj.target/kexec/src/kexec.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/username/.nvm/versions/node/v6.17.1/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:258:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:219:12)
gyp ERR! System Darwin 20.6.0
gyp ERR! command "/Users/username/.nvm/versions/node/v6.17.1/bin/node" "/Users/username/.nvm/versions/node/v6.17.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/username/Documents/Workspace/Code/projectname/node_modules/kexec
gyp ERR! node -v v6.17.1
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
npm WARN ajv-keywords@2.1.1 requires a peer of ajv@^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN inquirer-autocomplete-prompt-ipt@2.0.0 requires a peer of inquirer@>=7 but none is installed. You must install peer dependencies yourself.
npm WARN inquirer-ordinal-prompt@1.0.0 requires a peer of inquirer@>= 7 but none is installed. You must install peer dependencies yourself.
npm WARN stylelint-config-recommended@1.0.0 requires a peer of stylelint@^8.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN stylelint-config-standard@17.0.0 requires a peer of stylelint@^8.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN zipkin-instrumentation-express@0.16.2 requires a peer of @types/express@^4.0.39 but none is installed. You must install peer dependencies yourself.
npm WARN projectname@0.0.245 No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! kexec@3.0.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the kexec@3.0.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Then I check this post which mentions installing Command Lines Tools since I'm on Mac.
Though it was already installed, I uninstalled and reinstalled it with XCode Version 13.1 (13A1030d) and then ran xcode-select --install
Other things I tried were : running npm cache clean --force , deleting node-modules and package-lock.json

A: After Referring to my organization's Jenkins pipeline I found that node 10 is used.
Installing node v10.24.1 and npm v6.14.12 fixed the problem but with the below kexec warnings.
> kexec@3.0.0 install /Users/username/Documents/Workspace/Code/projectname/node_modules/kexec
> node-gyp rebuild

  CXX(target) Release/obj.target/kexec/src/kexec.o
../src/kexec.cc:68:27: warning: 'Utf8Value' is deprecated [-Wdeprecated-declarations]
        String::Utf8Value str(info[0]);
                          ^
/Users/username/Library/Caches/node-gyp/10.24.1/include/node/v8.h:2891:5: note: 'Utf8Value' has been explicitly marked deprecated here
    V8_DEPRECATED("Use Isolate version",
    ^
/Users/username/Library/Caches/node-gyp/10.24.1/include/node/v8config.h:327:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
../src/kexec.cc:78:27: warning: 'Utf8Value' is deprecated [-Wdeprecated-declarations]
        String::Utf8Value str(info[0]);
                          ^
/Users/username/Library/Caches/node-gyp/10.24.1/include/node/v8.h:2891:5: note: 'Utf8Value' has been explicitly marked deprecated here
    V8_DEPRECATED("Use Isolate version",
    ^
/Users/username/Library/Caches/node-gyp/10.24.1/include/node/v8config.h:327:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
../src/kexec.cc:91:31: warning: 'Utf8Value' is deprecated [-Wdeprecated-declarations]
            String::Utf8Value arg(argv_handle->Get(Nan::New<Integer>(i))->ToString());
                              ^
/Users/username/Library/Caches/node-gyp/10.24.1/include/node/v8.h:2891:5: note: 'Utf8Value' has been explicitly marked deprecated here
    V8_DEPRECATED("Use Isolate version",
    ^
/Users/username/Library/Caches/node-gyp/10.24.1/include/node/v8config.h:327:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
3 warnings generated.
  SOLINK_MODULE(target) Release/kexec.node
npm notice created a lockfile as package-lock.json. You should commit this file.

added 1 package from 1 contributor and audited 1286 packages in 13.916s

113 packages are looking for funding
  run `npm fund` for details

found 36 vulnerabilities (27 moderate, 9 high)
  run `npm audit fix` to fix them, or `npm audit` for details


text:
Q: I want to access .sql file format on the computer without using the internet I need to access data from the database and manipulate the data. I can do this through the internet, however I need to make it so that the data can be accessed on the computer that the program runs without having internet connection.
The current method I'm using is displayed below with the code:
Dim dbDataSet2 As New DataTable
Sqlconn = New MySqlConnection
Sqlconn.ConnectionString="server=xx.xx.xx;userid=root;password=xxxxxx;database=xxxxxx"
Dim SDA As New MySqlDataAdapter
Dim bSource As New BindingSource

Try
Sqlconn.Open()    'open connection
Dim query As String

query = "SELECT * FROM bbs_test.test"

command = New MySqlCommand(query, Sqlconn)
SDA.SelectCommand = command
SDA.Fill(dbDataSet2)
bSource.DataSource = dbDataSet2
DataGridView_array.DataSource = bSource
SDA.Update(dbDataSet2)

          Sqlconn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try

Is there a was to change this, so the file location is using a path like C: \ ......   or something similar
Also the file gets updated as well from time to time and the format of the file is .sql
Please can anyone help me
Thank You

A: You can use local IP address of lan adapter or IP address of localhost (127.0.0.1) it work without internet connection because everything is on local computer.

A: The problem is likely the server address in the connection string.  To make it connect to your local SQL Server engine, you can simply set the address to either (local) or ., for instance:
Sqlconn.ConnectionString="server=.;userid=root;password=xxxxxx;database=xxxxxx"

A: You could use a local - physical database like Access.
https://kyokasuigetsu25.wordpress.com/2011/01/16/how-to-connect-ms-access-with-vb-net-using-oledb-2/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to understand the logic of this question? Task:

Scan 2 numbers outerNumber and innerNumber. Iterate from [0, outerNumber). Inside that loop, iterate from [0, innerNumber). In the inner iteration print the sum of both the iterators.

Note:
[x, y] means all numbers from x to y including both x and y.
[x, y) means all numbers from x to y excluding y.
(x, y] means all numbers from x to y excluding x.
(x, y) means all numbers from x to y excluding both x and y.

Sample Input:
3 5
Expected Output:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6

Explanation:
outerIterator=0, innerIterator=0 → 0+0 = 0
outerIterator=0, innerIterator=1 → 0+1 = 1
outerIterator=0, innerIterator=2 → 0+2 = 2
outerIterator=0, innerIterator=3 → 0+3 = 3
outerIterator=0, innerIterator=4 → 0+4 = 4
outerIterator=1, innerIterator=0 → 1+0 = 1
outerIterator=1, innerIterator=1 → 1+1 = 2
outerIterator=1, innerIterator=2 → 1+2 = 3
outerIterator=1, innerIterator=3 → 1+3 = 4
outerIterator=1, innerIterator=4 → 1+4 = 5
outerIterator=2, innerIterator=0 → 2+0 = 2
outerIterator=2, innerIterator=1 → 2+1 = 3
outerIterator=2, innerIterator=2 → 2+2 = 4
outerIterator=2, innerIterator=3 → 2+3 = 5
outerIterator=2, innerIterator=4 → 2+4 = 6//

This is problem statement of the code and below that explanantion is given, but still I didn't understand how the output is coming.
I would be keen to learn how zeros, 1 and 2 are coming 5 times in Outeriterator and same in InnerIterator

A: Simply, it's nested loop with both outer and inner numbers as the range for both loops. You can implement it easily as:
for(out = 0; out < outerNumber; out++){
  for(in = 0; in < innerNumber; in++){
    printf("%d ",out + in);
  }
  printf("\n");
}

A: Outer is [0,3), so 0,1,2 is the amount of iterations.
Inner is [0,5), so 0,1,2,3,4 iterations.
Each value from outer requires you to run all the inner values once, so the first time for outer = 0 you will have 0,1,2,3,4 because 0 + [0,5) is 0+0, 0+1, 0+2, 0+3, 0+4.
For outer = 1 you will do the same but add 1 instead of 0.
For outer = 2, same thing 2+0,2+1,2+2,2+3,2+4.
In code should be something close to this:
for (i = 0 ; i<3 ; i++){

    for (x = 0; x<5; x++){

        printf i+x;
    }

}

Best of luck to you


text:
Q: jQuery селектор Ищу элемент с помощью селектора:
$(this).children().next().next().next().next().find('input').val();

Все работает корректно.
Но мне сильно не нравиться такая запись, наверняка есть способ написать это короче?

A: Добавьте вашему input или class или же id после чего сможете получать данные более менее нормально, например так
HTML
<input class="myInput" type="text" value="" />

JS
$('.myInput').val();


text:
Q: Struts Hibernate Mysql Tomcat based application hangs I have an application running on Apache 2.2, tomcat 6 and it uses struts framework, hibernate framework. We use Mysql at back end. We also interact with third party servers to place some requests that are requested by the user. Due to confidentiality constrains I can not tell you exactly what we do but I can assure you that we have not customized any thing and we use the most general builds availaible for Apache, tomcat etc. We use Linux platform. Lots of visitors visit our site, where they first pay using payment gateways, and then buy a product. To buy the product we again have to hit a third party site. Its a simple e-commerce kind of setup. The problem is that some times the server hangs. As in it does not responds and when we click on a link that (I know) is served by the tomcat container, it does not get loaded. Here is what i need help for:

*

*Since my hosting is on a headless linux platform, please suggest me a good debugging tool.

*We have logging in place and we print stack trace of almost all exception(if they happen), we always monitor catalina.out, but when the server hangs, we dont see any activity on catalina.out. may be this can give some one a clue.

*We have show_sql disabled for hibernate, we tried to enable it but still that was not sufficient to figure out if the application stucks on a query. We also have slow_sql log enabled but that does not show any significant queries. How can we check if my application is stuck on a query?

*If my application is not stuck on a query, how can i know where it is stuck?

*How can I get java stack dump?

*What are possible ways to resolve such a problem.

ANy suggestions are welcome. I thank you all in advance for reading my question and for the time you will devote writing an answer.

A: Facing your situation I would do a thread dump when the servlet container "hangs". A thread dump provides you a list of the stack traces for all Java threads in a given JVM.
Doing a thread dump is pretty easy:

*

*Find the Tomcat's process ID, e.g. ps -ef | grep java

*Send a SIGQUIT to the process, e.g. kill -3 tomcatProcessId
You will find the thread dump's content in TOMCAT_HOME/logs/catalina.out.


text:
Q: How to prevent button double click from server side I made disable button on javascript button click and it works in most of cases to prevent double click,but in some cases it does not work so I want to prevent double click also from server side.
protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
  {
     hfid.value="0";
  }
}
protected void frmSubmit_Click(object sender, EventArgs e)
{
   if(Convert.ToInt32(hfid.value) == 0)
   {
   // Code of insert
   // then I set hfid.value with newly created id
   }
}

 <asp:Button ID="frmSubmitInsert" runat="server" OnClick="frmSubmit_Click" OnClientClick="GRVMasterAddButton_Click(this)" Text="Add"
                                                Width="100px" Visible="false" ValidationGroup="masterGrp" />

 function GRVMasterAddButton_Click(btn)
        {

            if (window.Page_ClientValidate('masterGrp'))
            {
             document.getElementById(btn.id).disabled = true;
                __doPostBack(btn.id, '');
            }

        }

In double click scenario,two times round trip is generated.In First round trip it is ok,but in second round trip though I am setting hfid.value with newly inserted id, it shows me 0 and again duplicate record is generated.

A: You can use a Session variable in your frmSubmit_Click event handler to ensure server-side that you are not running the submit code twice:
In Form_Load event, add:
Session["isProcessingForm"] = false;

Modify frmSubmit_Click event handler as follows:
protected void frmSubmit_Click(object sender, EventArgs e)
{
   if(Session["isProcessingForm"])
   {
       return;
   }

   Session["isProcessingForm"] = true;

   if(Convert.ToInt32(hfid.value) == 0)
   {
       // Code of insert
       // then I set hfid.value with newly created id
   }

   //Once form is processed
   Session["isProcessingForm"] = false;
}

If this application runs on a web farm (multiple web servers), you'll need to persist session state. There are several ways to do so in ASP.NET WebForms. More info here: https://msdn.microsoft.com/en-us/library/ms178581.aspx and here: https://msdn.microsoft.com/en-us/library/ms178587.aspx

A: Best option is disable button in client side using javascript in very first click

A: Try the following: It should definitely work.
    protected void Page_Load(object sender, EventArgs e)
        {
                 if(!IsPostBack)
                 {
                    hfid.value="0";
                 }
            frmSubmit.Attributes.Add("onclick", "this.disabled = true; this.value = 'Loading ...'; " + ClientScript.GetPostBackEventReference(frmSubmit, null) + ";");
        }

     protected void frmSubmit_Click(object sender, EventArgs e)
        {
            //Remove following line, this is added just to test.
            System.Threading.Thread.Sleep(5000);
            if (Convert.ToInt32(hfid.Value) == 0)
            {
                // Code of insert
                // then I set hfid.value with newly created id
            }
        }

A: You can use Lock. To prevent multiple call at same time.
private object _lockObj = new object();
protected void frmSubmit_Click(object sender, EventArgs e)
{
    // Here we lock code. When someone else will try to access to this code
    // or in your case double clicked button it will wait until _lockObj
    // is set to free.
    Lock(_lockObj)
    {
        if(Convert.ToInt32(hfid.value) == 0)
        {
        // Code of insert
        // then I set hfid.value with newly created id
        }
    }
}


text:
Q: How do I insert special formatted text from VBA? This might be a very simple question with a hopefully simple reply. I have been googling for ages, and I just cannot seem to figure it out.
I need to insert some special formatted text from VBA, as the text inserted depends on 1 out of four 4 answers to a dropdown menu.
A picture of what I want to insert
As you can see on the picture, the user chose 'SM-1'. That means the below three requirements below has to be inserted in that format.
So all the balck text has to be text that is automatically inserted, and all the red text has to be inserted as FormFields that the user can write text in.
I really hope you guys can help out! Tell me if I'm not being specific enough and I will elaborate. :)


text:
Q: how to offset squares in a loop? I'm creating a sketch of the cafe wall illusion and need help coming up with a way to offset the checkerboard effect in Processing. The row below the previous one cannot be too close to the the row above it. basically I need it too look offset by half a tile each row going down but random starting points.
void setup(){
    size (500, 500);
    strokeWeight(3);
    stroke(127);
    tileSize = height/ROW_NUM;
    drawTiles();
}

void draw() {
}

void drawTiles() {
    for (int i=0; i<ROW_NUM; i++) {
        squareX = int(random(-tileSize, 0));

        int counter = 0;
        while (squareX < width) {

            if (counter%2==0) {
                fill(0);
                rect(squareX, squareY, tileSize, tileSize);
            } else {
                fill(255);
                rect(squareX, squareY, tileSize, tileSize);
            }
            squareX += tileSize;
            counter ++;
        }
        squareY += tileSize;
    }
}

A: Rather than figuring out how to move the coordinates for your rectangles, "move the coordinate system" by using translate:
final int rectSize = ...

void setup() {
    ...
    noLoop();
    strokeWeight(4);
    stroke(127);
}

In draw, rather than figuring out x/y coordinates for each rect, instead we "draw a row of tiles" starting at (0,0), and then we change what (0,0) means by using translate, by moving it down one row and either right or left by a little depending on which row we're at; we want to move right for row 1 and 2, then left for row 3 and 4, then right for 5 and 6, etc. so we want to move left if (row number/2) rounds to an even number, and right if it rounds to an odd number.
void draw() {
  int steps = 4;
  for(int row=0; row < 1 + height/rectSize; row++) {
    drawTileRow();
    int step = rectSize / steps;
    if ((row / 2) % 2 == 0) {
      step = -step;
    }
    translate(step, rectSize);
  }
}

You can then write much simpler code in the drawTileRow function, just drawing rects starting at (0,0) and ending at (width,0), although you really want to start at -rectSize, and end at width+rectSize, to compensate for the fact that the entire global coordinate system gets offset:
void drawTileRow() {
  boolean negative = false;
  for(int x=-rectSize; x<width+rectSize; x+=rectSize) {
    fill(negative ? 255 : 0);
    rect(x,0,rectSize,rectSize);
    negative = !negative;
  }
}

The result is properly trippy.


text:
Q: Any reason to prefer static_cast over a chain of implicit conversions? Suppose I have a class implementing several interfaces
class CMyClass : public IInterface1, public IInterface2 { };

and in a member function of that class I need to obtain a void* pointer to one of those interfaces (typical situation in IUnknown::QueryInterface().
The typical solution is to use a static_cast to achieve pointer adjustment:
void* pointer = static_cast<IInterface2*>( this );

and it is safe in this case if there's no known class inherited from CMyClass. But if such class exists:
class CDerivedClass : public CUnrelatedClass, public CMyClass {};

and I accidentially do
void* pointer = static_cast<CDerivedClass*>( this );

and this is actually a pointer to CMyClass instance the compiler won't catch me and the program might run into undefined behavior later - static_cast becomes unsafe.
The suggested solution is to use implicit conversion:
IInterface2* interfacePointer = this;
void* pointer = interfacePointer;

Looks like this will solve both problems - pointer adjustment and risk of invalid downcast.
Are there any problems in the second solution? What could be the reasons to prefer the first one?

A: You could use this template:
template<class T, class U> T* up_cast(U* p) { return p; }

usage:
struct B {};
struct C : B {};

int main()
{
  C c;

  void* b = up_cast<B>(&c);
}

Note that the '*' is implicit. If you prefer up_cast<B*>, adjust the template accordingly.

A: Assigning to void* is always unsafe. Whichever way you write it you can mess up - assuming that the user is trying to QI for Interface1, then neither of the following will be a warning or error:
Interface2* interfacePointer = this;
void* pointer = interfacePointer;

or
void* pointer = static_cast<Interface2*>( this );

Given the tiny risk of accidentally using a static_cast to up cast, in a file that most likely wont even have access to the definition of the derived class, I see a lot of extra effort for very little actual safety.

A: I can't see any reason in not using the latter solution other than the fact that, if somebody else is reading your code it won't communicate immediatly why you are using such a convoluted statement ("why isn't he just using a static_cast?!?"), so it would be better to comment it or make the intent very clear.

A: Your analysis looks sound to me.  The reason not to use your implicit approach are not compelling:

*

*slightly more verbose

*leaves variables hanging around

*static_cast<> is arguably more common, therefore more likely to be obvious to other developers, searched for etc.

*in many cases even the declarations of derived classes won't appear before the definition of the base class functions, so there's no potential for this type of error

A: If you are afraid of doing something by accident with the static_cast then I suggest that you wrap the casting/interface pointer obtaining into some template function, e.g. like this:
template <typename Interface, typename SourceClass>
void set_if_pointer (void * & p, SourceClass * c)
{
  Interface * ifptr = c;
  p = ifptr;
}

Alternatively, use dynamic_cast and check for the NULL pointer value.
template <typename Interface, typename SourceClass>
void set_if_pointer (void * & p, SourceClass * c)
{
  p = dynamic_cast<Interface *>(c);
}


text:
Q: How to merge a heatmap with its mirror image I have data for which I can make a heatmap in the form of a triangle.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

c = np.array([[1, np.nan, np.nan, np.nan, np.nan, np.nan],
              [-0.140898, 1, np.nan, np.nan, np.nan, np.nan],
              [0.0867051, -0.0934162, 1, np.nan, np.nan, np.nan],
              [0.117242, -0.0332325, 0.0414388, 1, np.nan, np.nan],
              [-0.120879, 0.00294446, -0.11504, -0.101007, 1, np.nan],
              [-0.696967, 0.0913504, -0.0823251, -0.0598827, 0.127752, 1]])

fig,ax = plt.subplots(1,1,sharex=True)

sns.heatmap(c,cmap='jet',
            vmin = -1,
            vmax = 1,
            ax = ax,
            annot = True,
            fmt = '.1f',
            annot_kws={"fontsize":5},
            cbar = True)

I have map looking like this:

And I would like to create a mirror image and merge it with orginal heatmap:

A: You could stack the matrix together with its mirror image. Use np.hstack([c[:, :0:-1], c]) if you only want the central column once.
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

c = np.array([[1, np.nan, np.nan, np.nan, np.nan, np.nan],
              [-0.140898, 1, np.nan, np.nan, np.nan, np.nan],
              [0.0867051, -0.0934162, 1, np.nan, np.nan, np.nan],
              [0.117242, -0.0332325, 0.0414388, 1, np.nan, np.nan],
              [-0.120879, 0.00294446, -0.11504, -0.101007, 1, np.nan],
              [-0.696967, 0.0913504, -0.0823251, -0.0598827, 0.127752, 1]])

labels = ['A', 'B', 'C', 'D', 'E', 'F']
fig, ax = plt.subplots(1, 1)
sns.heatmap(np.hstack([c[:, ::-1], c]),
            xticklabels=labels[::-1] + labels,
            yticklabels=[],
            cmap='turbo',
            vmin=-1,
            vmax=1,
            ax=ax,
            annot=True,
            fmt='.1f',
            annot_kws={"fontsize": 5},
            cbar=True)
# optionally add labels for the rows
for i, label in enumerate(labels):
    ax.text(len(labels) - i - 1.2, i + 0.5, label, ha='right', va='center')
plt.show()


text:
Q: Mysql Query to Delete Duplicate Wordpress posts? I have a lot of duplicate posts. So, how to delete them (only keep 1 post). If they have same title, they are duplicate posts. Thank you very much ! Have a nice day !

A: I'm not entirely sure you can do this with a single query in MySQL as you can't delete from tables which you reference in a sub-query. I would actually recommend doing this using wp-cli and using the WordPress API to delete the duplicate posts (which will also delete any post meta and associated term references):
global $wpdb;

$duplicate_titles = $wpdb->get_col("SELECT post_title FROM {$wpdb->posts} GROUP BY post_title HAVING COUNT(*) > 1");

foreach( $duplicate_titles as $title ) {
   $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s", $title ) );
   // Iterate over the second ID with this post title till the last
   foreach( array_slice( $post_ids, 1 ) as $post_id ) {
       wp_delete_post( $post_id, true ); // Force delete this post
   }
}

Hope this helps.

A: I know, it's an old thread but since i had a similar problem i would like to add some advises to the Answer from Bendoh (unfortunately i dont have the reputation to make a comment)
Since wordpress and some Plugins are also storing data in the post table, i would recommend to add an post_type to your querry:
global $wpdb;

$duplicate_titles = $wpdb->get_col("SELECT post_title FROM {$wpdb->posts} WHERE `post_type` = 'post' GROUP BY post_title HAVING COUNT(*) > 1");

foreach( $duplicate_titles as $title ) {
    $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s", $title ) );
    // Iterate over the second ID with this post title till the last
    foreach( array_slice( $post_ids, 1 ) as $post_id ) {
        wp_delete_post( $post_id, true ); // Force delete this post
    }
}

Depending of the source of your duplicates i would also add another field to check for duplicates, like the publication date.
global $wpdb;

$duplicate_titles = $wpdb->get_results("SELECT post_title, post_date, CONCAT(post_date, post_title) AS WHOLENAME FROM {$wpdb->posts} WHERE post_type = 'post' GROUP BY WHOLENAME HAVING COUNT(WHOLENAME) > 1");

foreach( $duplicate_titles as $title ) {

    $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s AND post_date='".$title->post_date."'", $title->post_title ) );

    foreach( array_slice( $post_ids, 1 ) as $post_id ) {
        wp_delete_post( $post_id, true ); // Force delete this post
    }

}


text:
Q: How to open forms ussing keyboard keys I would like to be able to press shift+D+A+L to open another form (form2) ussing VB.net how do i do this?

A: Set the forms KeyPreview property to true, then add code to the forms KeyDown event. Y
Then use an if statement e.g
If e.KeyCode = Keys.F1 Then
Add each key you want as a condition and since you want to use shift add this to your if;
e.modifier = keys.shift
Then create a new instance of the second form and call the showdialog function.


text:
Q: PHP / MYSQL + while repetition I'm trying to display ul>li list using PHP while loop and MYSQL.
My database 'company' has table 'news' with 2 columns ' id & content'.
The while loop works correctly it is returning two 'li' = as there are two rows in the table.
But, instate of data from the table something like this $indx." - ".$ID." ".$CONTENT." is inserted in each 'li'.
My while loop:
    $readNews_SQLselect = "SELECT  ";
    $readNews_SQLselect .= "id, content ";  // rows names
    $readNews_SQLselect .= "FROM ";
    $readNews_SQLselect .= "news ";         // table name

    $readNews_SQLselect_Query = mysql_query($readNews_SQLselect);

    $indx = 1;
    while ($row = mysql_fetch_array($readNews_SQLselect_Query, MYSQL_ASSOC)) {
        $ID = $row['id'];
        $CONTENT = $row['content'];

        echo '
$indx." - ".$ID." ".$CONTENT."
';

        $indx++;

    }

    mysql_free_result($readNews_SQLselect_Query);

I'm 99% sure is the syntax issue with echo '
$indx." - ".$ID." ".$CONTENT."
';.

A: PHP doesn't substitute variables in single quoted strings.
echo "
$indx - $ID $CONTENT
";

A: replace
'
$indx." - ".$ID." ".$CONTENT."
';

with:
'
'. $indx .' - ' . $ID .' ' . $CONTENT . '
';

EDIT 1
or with:
"
$indx - $ID $CONTENT
";


text:
Q: Как обратиться к конкретному номеру списка enumerate Python for f in enumerate(ftp.nlst(), 1):
    print(f)

На ftp сервере есть несколько файлов,они пронумеровано выводятся:
(1, 'user-2ccc659b-7f62-448e-acc0-45d227277216')
(2, 'user-deef9334-6bf4-44c3-9103-08c937e1a99e')

Как я могу обратиться к файлу 1 или 2?
Такое возможно?

A: а зачем такие сложности, что мешает обратиться напрямую?
ftp.nlst()[index - 1]

зачем ваять enumetate?
ftp_list = [i for i in ftp.nlst()]

print(ftp_list[1 - 1], ftp_list[2 - 1])


text:
Q: SOX detecting silence when reading mp3 from url I setup a nice utility to log and record scanner radio traffic and then remove silence using SOX.  To record continuously I keep calling SOX with silence detection:
function dosox() {
/usr/bin/sox -t alsa -D "plughw:2,0" $DATE.wav silence 1 0.1 2% 1 1.0 2%
 dosox
}
dosox

This works very well for ALSA sound devices.  However I now would like to get the stream from a url.  I use the URL source like:
function dosox() {
/usr/bin/sox -t mp3 $CHAN_URL $DATE.wav silence 1 1.0 2% 1 2.0 2%
 dosox
}
dosox

With the stream SOX seems to generate many audio output files quickly.  Many of these files are near duplicates. (They contain the same transmission).  I think SOX is out running the stream cache and considering this the end of the file, then terminating.  Then when SOX is called the next time it grabs the same stream which apparently can be of audio which was already streamed.
Assuming this is what is going on, I am looking for an easy way to have SOX exit on actual silence on the stream, but wait a bit when it thinks it got to the end of the stream for more audio.  Things I tried:
-Used mplayer to stream to a fifo and read that in with SOX.
-Tried to adjust the silence settings of the SOX silence effect.
Here is an example stream


text:
Q: eConnect 10.0 SLPRSNID & SALSTERR not importing in new line items The following code helps to import a sales line to an invoice:
        Dim LineItems(dtItem.Rows.Count) As taSopLineIvcInsert_ItemsTaSopLineIvcInsert
        Dim salesLine As New taSopLineIvcInsert_ItemsTaSopLineIvcInsert

        'Create Invoice Sales lines
        For Each dr In dtItem.Rows

            With salesLine
                .CUSTNMBR = dr.Item("acctno")
                .SOPNUMBE = invoiceNumber
                .SOPTYPE = 3
                .DOCID = "STD INV"
                .QUANTITY = dr.Item("Qty")
                .ITEMNMBR = dr.Item("Item")
                .ITEMDESC = dr.Item("Memo")
                .UNITPRCE = dr.Item("SalesPrice")
                .XTNDPRCE = dr.Item("Credit")
                .TAXAMNT = 0
                .UOFM = "Each"
                .SALSTERR = "GENERAL"
                .ReqShipDate = dtHdr.Rows(0).Item("InvoiceDate").ToString()
                .FUFILDAT = dr.Item("Date1").ToString()
                .ACTLSHIP = dr.Item("Date1").ToString()
                '.NONINVEN = 0
                .DOCDATE = dtHdr.Rows(0).Item("InvoiceDate").ToString()
                .SLPRSNID = "C1"
            End With

            LineItems(rowCtr) = salesLine
            rowCtr = rowCtr + 1
        Next

The fields for SLPRSNID & SALSTERR are just ignored. The invoice itself is being created with all the line items. ANY ideas from anyone with experience using this API are appreciated!

A: Since we are not integrating SOP commissions data, importing SLPRSNID & SALSTERR on line items using code like above is not supported. However, eConnect does expose pre and post stored procedures to customize business logic. The following was added in taSopHdrIvcInsertPost to implement the import:
/** Custom Business Logic */
if ((@I_vSLPRSNID <> '') and (@I_vSALSTERR <> ''))
begin
    update SOP10200
    set SLPRSNID = @I_vSLPRSNID, SALSTERR = @I_vSALSTERR
    where SOPNUMBE = @I_vSOPNUMBE and SOPTYPE = @I_vSOPTYPE
end
/** Custom Business Logic */
NOTE: with this implementation, the specific SLPRSNID & SALSTERR will have to be provided to the line items, it will not automatically post from header data, or any customer setup data in GP - your integration has to pass the values in.


text:
Q: RealBasic byte to string In RealBasic, is there a way to convert a byte to a string?

A: If you mean turn a Byte into a string representation of the byte in Binary (or hex or Octal), then:
  Dim x As Byte = 24  //For example
  Dim z, y, w As String
  y = Bin(x)      //Binary = "11000"
  z = Hex(x)      //Hexadecimal = "18"
  w = Oct(x)      //Octal = "30"

A: You could use MemoryBlock:
  Dim m As MemoryBlock
  m = NewMemoryBlock(1)
  m.Byte(0) = 65
  MsgBox(m.StringValue(0, 1)) // Displays "A"

Of course, Chr(65) does the same thing...


text:
Q: How to get rid of bias in data? I have been trying to classify a set of data into one of four classes. The data has already been generated and I have set aside 10,000 for training and 2,000 for testing. I have also generated the labels for each of the data. Let's call the classes - 0,1,2 and 3.
Now when I observe the classification, I notice that there are a lot of 0s in the training data and hence in most cases, the classifier is just learning to predict 0 no matter what the features are. (I am using random forests for classification)
Generating the data again to ensure uniformity, takes a lot of time and I prefer to avoid that. Is there anyway I can still use the data that I have?

A: Another way is to oversample: "Oversampling: you duplicate the observations of the minority class to obtain a balanced dataset." [1]
But note that oversampling of the minority class may lead to overfitting, so be sure to test that.
You also may want to check this paper: Yap, Bee Wah, et al. "An Application of Oversampling, Undersampling, Bagging and Boosting in Handling Imbalanced Datasets." [2]

A: This is usually referred to as class imbalance or skewed data not bias.
For a random forest you can use roughly balanced bagging to resample the data used to grow each tree during the bagging process.
You can also look into using a weighted or cost sensitive criteria for tree growth like weighted gini or entropy. Note that weights should be tuned using a grid search or hyperparameter optimization as it is difficult to guess good ones. IE weighting the majority class more then the minority class may produced the best balanced error somewhat counterintuitively.
Finally heilinger distance decision trees have recently been proposed as less sensitive to this sort of things.
I wrote a random forest implementation that includes a bunch of different methods for imbalanced data.


text:
Q: VBA color of visible gridlines of tables word I have more than 500 tables in Word. All of them have horizontal green borders at the top and bottom of the table, and some horizontal lines inside the table. Because of a mistake, some lines inside the same table and between tables have different green colors.
I need to unify the color of visible borders of all tables to the same green (RGB:0,128,0).
I'm very new with VBA. I have been looking at this for weeks without any success.
Here is an example of the tables in my document:

A: this should set the colour of all the borders
it does not change the visibility of any border, or the width, or any other attribute
i tested it on a couple of tables. please test this using a COPY of your document.
Sub colorBorders()

    Dim i As Integer

    Dim tabl As Table
    For Each tabl In ActiveDocument.Tables           ' iterate all the tables

        For i = 1 To tabl.Borders.Count              ' iterate all borders for each table
            tabl.Borders(i).Color = RGB(0, 128, 0)
        Next i

    Next tabl
End Sub


text:
Q: Python: Zip dict with keys I have:
list_nums = [1,18]
list_chars = ['a','d']

I want:
list_num_chars = [{'num':1, 'char':'a'},
                  {'num':18, 'char':'d'}]

Is there a more elegant solution than:
list_num_chars = [{'num':a, 'char':b} for a,b in zip(list_nums, list_chars)]

A: map(dict, map(lambda t:zip(('num','char'),t), zip(list_nums,list_chars)))

gives:
[{'char': 'a', 'num': 1}, {'char': 'd', 'num': 18}]

A: If the initial lists are very long, you might want to use itertools.izip() instead of zip() for slightly improved performance and less memory usage, but apart from this I can't think of a significantly "better" way to do it.

A: Declare a new variable which are the keys to your dict
from itertools import izip
nums  = [1,18]
chars = ['a','d']
keys  = ["num", "char"]      # include list of keys as an input

which gives a slightly more elegant solution, I think.
[dict(zip(keys,row)) for row in izip(nums,chars)]

It's definitely more elegant when there are more keys (which is why I started hunting for this solution in the first place :)
If you want, this tweak gives the same as a generator:
(dict(zip(keys,row)) for row in izip(nums,chars))


text:
Q: Is it possible to group by a list without linq I have a list containing these items.
ID     TaskId     Purposecode    UserId     Time
1      1          915            421        7.0
2      1          915            421        7.0
3      1          915            421        7.0
4      4          912            421        7.0

How can i group by without using linq?
The goal is to get this
   TaskId     Purposecode    UserId     Time
       1          915            421        21.0 (uniqeID: 1,2,3)
       4          912            421        14.0 (uniqeID: 4,5)

The reason why, i am doing this in code, is because i need the unique IDs after group by for other reasons.

A: You can take a dictionary of lists... like this (assuming "Item" is the entity with your data):
Dictionary<int, List<Item>> itemsByTask = new Dictionary<int, List<Item>>()
foreach (Item item in items) {
  List<item> groupItems;
  if (!itemsByTask.TryGetValue(item.TaskID, out groupItems)) {
    groupItems = new List<Item>();
    itemsByTask.add(item.TaskID, groupItems);
  }
  groupItems.Add(item);
}


text:
Q: Postgres: `last_value` Clarifiation I'm currently fixing up a bad postgresql migration and have just reset the pg_sequence for a few of my tables. Just to clarify specifically:
Is last_value supposed to EQUAL TO the last-highest PK for a given table? Or the should last_value be the highest value + 1? The reason I ask is because I see a few that are equivalent to the max PK, and a few that are a few higher.
I know this seems like an odd question– "why wouldn't the last_value be the last used value", but I just wanted to clarify to remove any ambiguity that last_value is not in fact the last pk+1 but equal to the last pk

A: From the pg_sequences documentation:

last_value: The last sequence value written to disk. If caching is used, this value can be greater than the last value handed out from the sequence. Null if the sequence has not been read from yet. Also, if the current user does not have USAGE or SELECT privilege on the sequence, the value is null.

Your question:

Is last_value supposed to EQUAL TO the last-highest PK for a given table?

If caching is not used, then last_value gives you the highest value of the pk. If caching is used, you might get a value slightly greater than the highest pk in the table.


text:
Q: are two threads involved when use APM BeginXX, EndXXX methods? For example, we have the following APM APIs:
public virtual IAsyncResult BeginGetResponse(AsyncCallback callback, object state);
public virtual WebResponse EndGetResponse(IAsyncResult asyncResult);

so when I call BeginGetResponse in the main thread, I outlines the sequences below, correct me if I'm wrong
1-the main thread enqueue the request work on the thread pool.
2-some times later, thread pool assign a thread to send the request.Then this thread is recycled back into thread pool.
3-Once all the data arrives, the thread pool assign a new thread to process the result, we can call EndGetResponse in this thread to get the result.
So apart from the main thread,  there are two new threads involved to get the job done, is my understanding correct? If yes, are those new threads all I/O threads, or the first one is a IO thread and the second thread is a worker thread?
Edit:
Below is the quote from my textbook:
A far more efficient approach(i.e use BeginXXX and EndXXX) would be to create a thread to request the data from the web server, give the thread back to the thread pool, and when the data arrives, obtain a thread from the pool to process the results.

A:
I outlines the sequences below, correct me if I'm wrong

Sorry, but you are wrong. :)

1-the main thread enqueue the request work on the thread pool

No. As a general rule, the only time a method of the form BeginXXX() queues something to the thread pool is the BeginInvoke() method on a delegate type.
Otherwise, the usual implementation (on Windows) is to use "I/O Completion Ports" (IOCP). This will eventually result in your callback method being executed on a thread from the IOCP thread pool, but at step #1 the only thing that happens is that the I/O operation is initiated, associating it with an I/O completion port.

2-some times later, thread pool assign a thread to send the request.Then this thread is recycled back into thread pool.

This step never happens.

3-Once all the data arrives, the thread pool assign a new thread to process the result, we can call EndGetResponse in this thread to get the result.

This step is the only step at which a thread pool thread executes code. And to be clear: the thread is in the IOCP thread pool, not the regular thread pool.
What happens is that when the original I/O operation was initiated, the underlying native Windows call associated the I/O completion port with it. The port is a feature in the native Windows API that allows Windows to wake up a thread in the thread pool automatically when the I/O operation completes. This executes some .NET code, which then in turn executes your code to finally resolve the operation.
There are exceptions, of course. There is nothing enforcing the above for classes that implement the BeginXXX()/EndXXX() pattern. But this is invariably how .NET components will implement it. And since for third-party components that implement it, they will typically not be calling the native API directly, but instead will be using some .NET IO object (typically a FileStream, Socket, or some other class that ultimately depends on one of those two classes), even they will also wind up using IOCP as the underlying implementation.
Note that there is one other prominent exception, where neither the thread pool nor IOCP is used: the BeginInvoke() methods for Winforms or WPF/Dispatcher-based code. These, of course, queue your delegate for invocation on a specific non-thread-pool thread. This is more similar to the thread-pool scenario, but technically is not that, and would still only involve a single thread in any case.

A: BeginXXX/EndXXX is just a pattern (one of) which is used to describe asynchronous execution semantic. How it actually behaves in any specific case depends on actual implementation of the pattern. Most of I/O-bound scenarios covered by .NET Framework use IOCP underneath, which implies that they don't use any additional thread to issue an I/O request to completion port, and as soon as the asynchronous I/O was primary target of the pattern usage in pre-async age we tended to think about it as something with no thread. However the scope of areas where IOCP can be applied is limited by internal file handles mechanism which covers mostly file sytem objects, sockets, named pipes and maybe couple of other objects (all of them related to the I/O scenarios). For the rest scenarios (as an asynchrony can be not only I/O-bound) an implementation can be different and using a thread as an option to initiate an asynchronous execution cannot be excluded. As for the example referred in the book, the BeginGetResponse and EnGetResponse methods of HttpWebRequest class (unless some other type is implied) are built on top of .NET streams APM API which internally uses IOCP, so they are IOCP-based and no thread is created when BeginGetResponse is invoked. So answer to the:

are two threads involved when use APM BeginXX, EndXXX methods?

comes down to two options:

*

*In general case it depends in the implementation.

*In specific case you provided as an example no thread is created for BeginGetResponse as well as any other IOCP-based implementation.


text:
Q: groups and groups  are different even after restart Hi there I'm new to Linux and I'm very confused. I tried to add my user to docker group to run the docker without sudo as follow:  https://docs.docker.com/engine/install/linux-postinstall/ and It worked (even when I closed the terminal or with my vs-code). Yesterday after I restart my computer It's looks like my user doesn't have any groups when I enter:
nitai@nitai-IdeaPad-5 ~ % id
uid=1000(nitai) gid=0(root) groups=0(root)

but when I enter my current username :
nitai@nitai-IdeaPad-5 ~ % id nitai
uid=1000(nitai) gid=0(root) groups=0(root),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),122(lpadmin),134(lxd),135(sambashare),136(docker)

It's magically finds all the groups.
I already tried to add the user again to docker group, restart the computer. I would appreciate any advice, thanks from advance.
EDIT:
If I use su nitai (login from the terminal as nitai) I could see the groups in the current terminal.


text:
Q: How to check if value is not smaller (!<=) or bigger (!>=) than value x? How to check if value is not smaller (!<=) or bigger (!>=) than value x?

A: Why dont you use number (>) to compare if its (!<=) and number (<) to compare (!>=)

A: Simple:
var value:int = 10;

if(value > 5)
{
    trace("will trace");

}// end if

if(!(value > 5))
{
    trace("will not trace");

}// end if

A: I assume that you are talking about 2 operations (other wise there is no such number).
so you should use
if(number >=x){//which means he is larger.

}else if(number<=x){//which means he is smaller.

}

A: If x and y are both numbers then x <= y || x >= y one of them has to be true (or both if x == y). Using logical not in this fashion can make things less readable but you would do it like this.
x !>= y would actually need to be !(x >= y)
x >= y is the same as !(x <= y)
x <= y is the same as !(x >= y)
Operators in AS3 from the live docs can be found at: http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/operators.html


text:
Q: how to load external js file in component with systemjs in Angular 2? I want to load test.js in   statComponent  i try with System.import in the construncor but i get this error : Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3000/systemjs
    Error: XHR error……
 import { Component, OnInit } from '@angular/core';
import { System } from 'systemjs';

@Component({
template: `
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto">
 </div>

`
})
export class StatComponent implements OnInit {
constructor() {
    System.import('./app/user/test.js').then(refToLoadedModule => {
        refToLoadedModule.someFunction();
    })
}

ngOnInit() { }
}

thi is sysytemjs.config.js
  /**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
 (function (global) {
 // map tells the System loader where to look for things
  var map = {
'app': 'dist', // 'dist',
'@angular': 'node_modules/@angular',
'rxjs': 'node_modules/rxjs',
'ng2-toasty': 'node_modules/ng2-toasty/bundles/index.umd.js'

  };
 // packages tells the System loader how to load when no filename and/or no
extension
 var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' }
 };
 var ngPackageNames = [
'common',
'compiler',
'core',
'forms',
'http',
'platform-browser',
'platform-browser-dynamic',
 'router'
 ];
  // Individual files (~300 requests):
 function packIndex(pkgName) {
 packages['@angular/' + pkgName] = { main: 'index.js', defaultExtension:
 'js' };
  }
  // Bundled (~40 requests):
 function packUmd(pkgName) {
packages['@angular/' + pkgName] = { main: '/bundles/' + pkgName + '.umd.js',
defaultExtension: 'js' };
 }
 // Most environments should use UMD; some (Karma) need the individual index
files
 var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
 var config = {
map: map,
packages: packages
 };
 System.config(config);
 })(this);


text:
Q: How can I use Regex to return a string with its matches PLUS its delimiters? For example, I want to take a weirdly formatted expression: '4.2+5 - 6'
and return this list: ['4.2', '+', '5', '-', '6]
I can return ['4.2', '5', '6'] but I don't know where to go from there.


text: Q: Flutter how to click a button on webpage? I'm using flutter html package to get document's from webpage, and I'm now wondering if I can click on button on this webpage or event enter text in input to sign in before get data from that webpage


text:
Q: Why is this char stopping my program? Does the newline character have some kind of special significance in c++? Is it a non-ASCII character?
I'm trying to build a Markov chain for each unique n-character substring within a larger piece of text. Every time I come across a new unique substring I enter it into a map whose value is a 256-element vector (one element for each character in the extended ASCII table).
There's no problem when I print out the entire contents of the file ("lines" is a vector of lines of text built using ifstream and getline):
for(int i=0; i<lines.size(); i++) cout << lines[i] << endl;

The whole text file shows up in the console. The problem happens when I try to return the newline character to a function that's expecting a char. "moveSpaces" is an integer constant that determines how many characters further ahead to move in the vector of strings on each iteration.
char GetNextChar(int row, int col){
    for (int i=0; i<MOVESPACES; i++) {
        if (col+1<lines[row].size()) {
            col+=1;
        } else {        // If you're not at the end of the line keep going
            row+=1;     // Otherwise, move to the beginning of the next row
            col=0;
        }
    }
    return lines[row].at(col);
}

I've walked through with the debugger, and when it gets to the 1st column of the 2nd line it craps out on me – no error or anything. It fails within this function, not the calling function.
The file I'm using is A Christmas Carol (first thing that came up on Project Gutenberg). For reference here are the first few lines:
STAVE I:  MARLEY'S GHOST

MARLEY was dead: to begin with. There is no doubt
whatever about that. The register of his burial was

The function breaks when it should return the first character on the second line. This doesn't happen if I get rid of the newline, or if I build the "lines" vector myself line by line in the program. Any idea what's wrong?

A: Your GetNextChar function is assuming that if you are at the last character in some line, there will be a character in the next line. What happens if there is no character in that next line? This can happen in two places: When you have hit end of file, or when the next line is the empty string.
The second line is the empty string.


text:
Q: Coordinates system used by Get Coordinates on large images I often try to crop images by selecting a few points manually with the interactive tools and copy-paste them in ImageTrim[theImage,ThePoints].
It works fine on small images and often doesn't work on large images. Here is a example that should be reproductible (Mathematica 12.1, Windows 7).
Let's say I want to crop a little bit this image :
TheImage = ExampleData[{"TestImage", "Apples"}]

I select two points on the diagonal, very near the corners :

One sees on the animation that the points are at coordinates {11,15}, and {641,425}. I copy-paste them in ImageTrim :
ImageTrim[TheImage, {{11, 15}, {641, 425}}]

result :

These are only the three apples at the bottom-right of the original image !
The question
Where does the coordinates system used by GetCoordinates comes from ?

A: I have finally understood the origin of the coordinates system used by GetCoordinates.
It turns out that the image of apples has a Option called "ImageResolution" :
TheImage = ExampleData[{"TestImage", "Apples"}];
Options[TheImage]

{ColorSpace -> "RGB", ImageResolution -> {300, 300},   Interleaving ->
True}

(This option follows the image whatever copy/paste you do with the image. )
On the other hand, the size of the image in pixels is {2700,1800} :
ImageDimensions[TheImage]

{2700, 1800}

The coordinate system used by GetCoordinate is :
72/300 {2700,1800}
One reconize the 300,2700 and 1800.
Regarding the 72, it is the standard resolution 72 dots/Inch.


text:
Q: Wait for completion of callback function in HTTP request before continuing with for loop I'm trying to run an HTTP request 3 times in node.js using the inbuilt HTTPS library, with each run having a different set of options. In order to move on to the next set of options after the completion of one execution, I"m using a for loop that increments once each run, for a total of 3 runs. However, instead of waiting for each run to finish before proceeding in the loop, it skips the first two calls completely and runs it 3 times with the third set of options. I've looked all over for an answer, anyone have any ideas/solutions?
    for(let i = 0; i < 3; i++) {
        option = i;
        console.log("Calling with option " + i)
        await http.request(options[i], res => {
            let resp = '';
            res.on('data', function(chunk) {
                resp += chunk;
            });
            res.on('end', async function () {
                let data = await JSON.parse(resp);
                if(option === 0) { //Bloxlink handler
                    console.log("Case 1: Bloxlink")
                    if(data.status === "error") {
                        returndata += "Bloxlink returned no users"
                    } else {
                        returndata += "\nBloxlink returned user with ID " + data.primaryAccount + " and username " + await noblox.getUsernameFromId(parseInt(data.primaryAccount)) + "."
                    }
                } else if(option === 1) { //RoWifi handler
                    console.log("Case 2: RoWifi")

                    if(data.success === false) {
                        returndata += "RoWifi returned no users"
                    } else {
                        returndata += "\nRoWifi returned user with ID " + data.roblox_id + " and username " + await noblox.getUsernameFromId(data.roblox_id) + "."
                    }
                } else if(option === 2) { //Eryn handler
                    console.log("Case 3: Eryn")
                    if(data.status === "error") {
                        returndata += "Eryn returned no users"
                    } else {
                        returndata += "\nEryn returned user with ID " + data.robloxId + " and username " + data.robloxUsername + "."
                    }
                }
                console.log(returndata);
            });
            res.on('error', function () {
                channel.send('One or more APIs returned an error. The operation has been terminated.')
            });
        }).end();
        channel.send("Run " + i + " finished: " + returndata);
        console.log(returndata);
    }

A: You could wrap it in a promise and then await it:
for(let i = 0; i < 3; i++) {
    option = i;
    console.log("Calling with option " + i)
    await new Promise((resolve, reject) => {
        http.request(options[i], res => {
            let resp = '';
            res.on('data', function(chunk) {
                resp += chunk;
            });
            res.on('end', async function () {
                let data = await JSON.parse(resp);
                if(option === 0) { //Bloxlink handler
                    console.log("Case 1: Bloxlink")
                    if(data.status === "error") {
                        returndata += "Bloxlink returned no users"
                    } else {
                        returndata += "\nBloxlink returned user with ID " + data.primaryAccount + " and username " + await noblox.getUsernameFromId(parseInt(data.primaryAccount)) + "."
                    }
                } else if(option === 1) { //RoWifi handler
                    console.log("Case 2: RoWifi")

                    if(data.success === false) {
                        returndata += "RoWifi returned no users"
                    } else {
                        returndata += "\nRoWifi returned user with ID " + data.roblox_id + " and username " + await noblox.getUsernameFromId(data.roblox_id) + "."
                    }
                } else if(option === 2) { //Eryn handler
                    console.log("Case 3: Eryn")
                    if(data.status === "error") {
                        returndata += "Eryn returned no users"
                    } else {
                        returndata += "\nEryn returned user with ID " + data.robloxId + " and username " + data.robloxUsername + "."
                    }
                }
                console.log(returndata);
                resolve();
            });
            res.on('error', function () {
                channel.send('One or more APIs returned an error. The operation has been terminated.')
                reject();
            });
        }).end();
    }).then(() => {
        channel.send("Run " + i + " finished: " + returndata);
        console.log(returndata);
    });
}

But a cleaner approach would be to use a promise-based request library like fetch or axios.


text:
Q: OpenID: Acceptance in non geek community for registration If we are going to develop a community website for non geeks, is it ok if we implement openid registration. How much openid is acceptable in non geek community. Anybody having any idea about this.

A: Do both - provide OpenID for those that want to use it and have a regular user account signup for those that don't. You could even go all the way and become an OpenID provider and allow users with regular accounts on your system to use them as OpenIDs on other systems.
In short, OpenID is OK as long as it's not the only option.
One small note: If you do decide to provide OpenID authentication, you need to be prepared for users locking themselves out of their accounts. You should also provide a mechanism for changing the associated OpenID.

A: I think you should just stick with the standard email address and password, it's what everybody knows and gives you the benefit of having an automatic external point of contact with the users in case you need to notify them of something.

A: You can choose both Open ID and Traditional login functionality. its becoming quite adaptable among non geeks also. You can even look for Google's friend connect for further reference.

A: We're just migrating an old site to a new (WordPress-based) platform. We're confronting this issue, we know we want to outsource the credential-management to something like OpenID, although currently FaceBook Connect is the leader in our planning. Mainly because a significant proportion of our users are already there.
We could look to do both, but if a decent proportion of your base is not already OpenIDed-up then to non-Geeks it's not compelling. Equally I do believe that the OpenID model is fundamentally A Good Thing so you could argue that teaching a little more of the world about it has some moral good associated with it.

A: I think non-geeks don't see the benefits of using OpenId and most OpenID logons do a poor job of stating what they do.
To address your concerns, if you're going to implement OID, then do a good job of explaining what it does and what benefits it has.


text:
Q: What finitely presented groups embed into $\operatorname{GL}_2$? This is a naive question but I hope that the answers will be educational. When is it the case that a finitely presented group $G$ admits a faithful $2$-dimensional complex representation, e.g. an embedding into $\text{GL}_2(\mathbb{C})$? (I am mostly interested in sufficient conditions.)
I think I can figure out the finite groups with this property (they can be conjugated into $\text{U}(2)$ and taking determinants reduces to the classification of finite subgroups of $\text{SU}(2)$ and an extension problem) as well as the f.g. abelian groups with this property (there can't be too much torsion). But already I don't know what finitely presented groups appear as, say, congruence subgroups of $\text{GL}_2(\mathcal{O}_K)$ for $K$ a number field.
What can be said if you are given, say, a nice space $X$ with fundamental group $G$? I hear that in this case linear representations of $G$ are related to vector bundles on $X$ with flat connection.

A: First, instead of subgroups of $GL(2,C)$ it suffices to consider subgroups of $SL(2, C)$. I will also restrict to subgroups which are not virtually solvable (since these should be easy to classify). Lastly, I will consider characterization of subgroups of $SL(2, C)$ "up to abstract commensuration" since the criterion is much cleaner in this setting. (Recall that two abstract groups $G_1, G_2$ are called "commensurable" if they contain isomorphic finite-index subgroups.)
Definition. Let $p$ be a prime and $c$ an integer. A $p$-congruence structure of degree $c$ for a group $\Gamma$, is a descending chain of finite-index normal subgroups of $\Gamma$:
$\Gamma=N_0\supset N_1 \supset ... \supset N_k ... $, such that:
(i) $\bigcap_{k=0}^\infty N_k= 1$;
(ii)    $N_1/N_k$ is a finite $p$-group for every $k\ge 2$;
(iii)   $d(N_i/N_j)\le c$ for all $j\ge i\ge 1$, where $d(H)$ denotes the minimal number of generators
of a group $H$.
Theorem. A finitely-generated (non-virtually solvable) group $\Gamma$ is commensurable to a
subgroup of $SL(2,C)$ if and only if $\Gamma$ admits (for some prime $p$) a $p$-congruence structure of degree $c=3$.
This theorem is an application of "A Group Theoretic Characterization of Linear Groups" by Alex Lubotzky (Journal of Algebra, 113 (1988), 207-214), combined with the classification of Lie algebras of dimension $\le 3$ over fields. Note that Lubotzky does not get a group-theoretic characterization of subgroups of $SL(n,C)$ for particular values of $n$ (even up to commensurability), however, for $n=2$ the situation is better than for the general $n$ since dimension of the Lie group is so small in this case.

A: I'm not sure whether it is worth remarking on, but if $G$ is any irreducible subgroup of ${\rm GL}(2,\mathbb{C}),$ its non-central Abelian subgroups have some very restrictive properties:
If $A$ is a non-central Abelian subgroup of $G$, then $C_{G}(A)$ is also Abelian and $[N_{G}(A):C_{G}(A)] \leq 2.$

A: If the group $G$ does not have property FA, then a necessary and sufficient
condition is that the group embeds in $\operatorname{GL}_2(\mathcal{O}_K)$, for some number
field $K$ (although there are such subgroups which do not have property FA).
This follows from Bass-Serre theory. Of course, this begs the question of classifying finitely presented subgroups of $\operatorname{GL}_2(\mathcal{O}_K)$ with property FA.
More generally, Bass-Serre theory implies that a general finitely generated
subgroup of $\operatorname{GL}_2(K)$ will have a graph of groups decomposition
into subgroups of $\operatorname{GL}_2(\mathcal{O}_K)$ for some number fields $K$.
The geometrization theorem and ending lamination theorems classify
discrete subgroups of $\operatorname{PSL}_2(\mathbb{C})$ (which up to finite-index
embed in $\operatorname{SL}_2(\mathbb{C})$), by their topological type as a 3-orbifold
and the ending lamination data.
You ask about congruence subgroups of $\operatorname{GL}_2(\mathcal{O}_K)$.
If $K=\mathbb{Q}$ or $K=\mathbb{Q}(\sqrt{-D})$, for some $D>0$,
then the group is a discrete non-uniform lattice in $\operatorname{PSL}_2(\mathbb{R})$
or $\operatorname{PSL}_2(\mathbb{C})$, and one may classify the congruence
subgroups of $\operatorname{SL}_2(\mathbb{Z})$ by a result of Tim Hsu (more
generally, I think there exists and algorithm to determine
if a finite-index subgroup of $\operatorname{GL}_2(\mathcal{O}_{\mathbb{Q}(\sqrt{-D})})$
is congruence, but I don't know if it's written down - I could describe
it for you though if you're interested). More generally, one can
determine if a discrete non-uniform arithmetic lattice in $\operatorname{PSL}_2(\mathbb{R})$
or $\operatorname{PSL}_2(\mathbb{C})$ is congruence.
Otherwise, Serre essentially showed that a finite-index subgroup of $\operatorname{GL}_2(\mathcal{O}_K)$
will have the congruence subgroup property (and thus, non-uniform
lattices in a product $(\mathbb{H}^2)^k\times (\mathbb{H}^3)^l$ will
have this property if $k+l>1$).
For examples of groups which don't have property FA, there's a paper
of Calegari and Dunfield which constructs an ascending HNN
extension subgroup of $\operatorname{SL}_2(\mathbb{C})$.
There are many necessary conditions which show that various groups
cannot embed in $\operatorname{GL}_2(\mathbb{C})$, some of which you describe.
But I think a general classification is beyond reach at this point.
As you say, if a space $X$ has a $\mathbb{C}^2$ bundle with flat
connection, then you get a representation of $G=\pi_1(X)$ into
$\operatorname{GL}_2(\mathbb{C})$. The space of such flat bundles is computable
if $G$ is finitely presented, it amounts to computing the character
variety of $G$ into $\operatorname{GL}_2(\mathbb{C})$. However, it is difficult
to tell if there is a faithful representation. If you can solve
the word problem in $G$, then in principle one can determine if
a representation is not faithful.  Also, it seems difficult to certify that
a representation is faithful, except if it is discrete. The
difficulty is to find a nice fundamental domain for the
action on a product of symmetric spaces on which the group
acts discretely (in fact, it might not exist).

A: For a finitely generated group $G$, a necessary and sufficient condition to be embeddable into $\text{GL}_2(\mathbf{C})$ is the following strengthening of being residually finite: for every finite subset $F$ of $G$ and any $m$ there exists a finite field $K$ of characteristic $>m$ and a homomorphism from $G$ to $\text{GL}_2(K)$ that is injective on $F$.
Indeed, if this condition is satisfied, write $G=\bigcup F_n$ (increasing union) and consider such homomorphisms $G\to\text{GL}_2(K_n)$ with $K_n$ of characteristic $>n$. If $K$ is an ultraproduct of the $K_n$ then it is isomorphic to a subfield of $\mathbf{C}$ and $G\to\text{GL}_2(K)$ is an injective homomorphism. For the converse, we have to know that for every finitely generated domain of characteristic zero $R$ the intersection of maximal ideals is reduced to 0 (it's indeed a Jacobson ring). It follows that $\text{GL}_2(R)$ satisfies the above property. Indeed let $F$ be a finite subset. For every non-identity element $b$ in $FF^{-1}$ pick a nonzero entry of $b-1$ and let $x$ be the product of all these nonzero entries. Take a maximal ideal $M$ not containing $m!x$. Then $R/M$ is a finite field of characteristic $>n$ in which $x$ is nonzero, so the homomorphism $\text{GL}_2(R)\to\text{GL}_2(R/M)$ is injective on $F$.
If you remove the condition "characteristic $>m$", you similarly characterize being isomorphic to a subgroup of $\text{GL}$ over an arbitrary field $K$. Also this works the same with $\text{GL}_k$ and $\text{SL}_k$, etc.

A: This is a very nice question which, as Agol says, is probably out of reach at the moment.  To say that there is a classification of the fp subgroups of $GL_2(\mathbb{C})$ would be to say that the set of presentations of those subgroups is recursively enumerable and has solvable Isomorphism Problem.  It's hard to guess which way to jump for either of these properties: the Isomorphism Problem is known to be unsolvable for finitely presented subgroups of $GL_N(\mathbb{Z})$ for some large $N$, by work of Bridson--Miller and Haglund--Wise.
There is one nice, tangential but positive, result that I know of. Oddly enough, it says that we have some sort of limited decision-theoretic understanding of which groups are not subgroups of $GL_2(\mathbb{C})$.  Apparently it was known to Mal'cev; Daniel Groves and I re-discovered it for ourselves, but then found it in Lubotzky and Segal's book.
It's well known that most nice (more precisely, Markov) classes of finitely presented groups aren't recursively recognizable, by the Adian--Rabin Theorem.  This applies to subgroups of $GL_2(\mathbb{C})$, essentially because the word problem is solvable, as Igor Belegradek pointed out above. However, in nice cases, it turns out that the word problem is the only obstruction.
More precisely, Groves, Manning and I call a class $\mathcal{C}$ of fp groups recursive modulo the word problem if $\mathcal{C}\cap\mathcal{D}$ can be recursively recognized in any class of groups $\mathcal{D}$ in which the word problem is uniformly solvable.  This holds for the trivial group, abelian groups, nilpotent groups of class at most $k$ for fixed $k$, free groups, Sela's limit groups, surface groups, 3-manifold groups...
There is some hope that this could hold for subgroups of $GL_2(\mathbb{C})$.  As I said above, it's unknown whether the class of these subgroups is recursively enumerable.  However, it is true that the complement of this class is recursively enumerable modulo the word problem.  That is, the following holds:
Theorem: Let $\mathcal{L}_n$ be the set of all finite presentations of subgroups of $GL_n(\mathbb{C})$.   There is a Turing machine that determines in finite time if a presentation $P\notin\mathcal{L}_n$, using a solution to the word problem in $P$.
The key point is that a group is in $\mathcal{L}_n$ if and only if it is fully residually $\mathcal{L}_n$, and this latter property can be reduced to the decidability of the elementary theory of $\mathbb{C}$ (Tarski).
===========
Added details:
As far as I know, the theorem above isn't written down anywhere. The proof I had in mind is essentially an application of the following theorem.
Theorem (Mal'cev): A finitely generated group $G$ is a subgroup of a group $GL_n(\mathbb{C})$ if and only if $G$ is fully residually $GL_n(\mathbb{C})$; that is, for any finite subset $X\subseteq G\smallsetminus 1$ there is a homomorphism $f:G\to GL_n(\mathbb{C})$ with $1\notin f(X)$.
This is Theorem 16.4.1 in Lubotsky and Segal's book Subgroup growth.
Proof of the first theorem. Let $G$ be the group presented by $P$.  Using the word problem, enumerate balls $B(n)$ in $G$.  If $G$ is not embeddable in $GL_n(\mathbb{C})$ then, by Mal'cev's theorem, for some $n$, every homomorphism $f:G\to GL_n(\mathbb{C})$ kills a non-trivial element of $B(n)$.  This last statement can be rephrased as a system of equations and inequations over $\mathbb{C}$ with integral coefficients, and hence solved. QED


text:
Q: smart pointer memory pool I'm working on a large, old codebase that uses memory pools to great speed advantage. The problem, though, is that allocating and deallocating memory through the memory pool is complicated. I would like to try using smart pointers, but it was suggested to me that the loss in performance would be an issue.
The solution that seems to present itself is a smart pointer implementation that continues to use the original memory pool under the hood. I can't find any smart pointer/memory pool combinations in use. Can anyone point me to an example implementation of this? Are there any gotchas/cautions I should be aware of before trying this out?

A: Smart pointers don't generally allocate memory for the object they are pointing to - rather you create the object yourself and construct a smart pointer of the desired type from the resulting raw pointer.
However the smart pointer controls the life cycle of the object after that, so it needs to know how to free the object once it is no longer referenced, according to the rules of the smart pointer you have chosen.
The default action is to use 'delete', but you can supply your own 'custom deleter' instead.
For example:
MyClass* CreateMyObject(/* whatever args you need */) {
    // Do whatever it takes to create your object in the pool
    return myObject;
}

void DeleteMyObject(MyClass *obj) {
    // Do whatever it takes to free object from pool
}

std::shared_ptr<MyClass> ptr(CreateMyObject(....), DeleteMyObject);

I am not sure if that solves your initial concerns - you still need to handle the complexities of allocating and de-allocating your objects in the pools - but you do get the life cycle management benefits of the smart pointers.
Here is at least one tutorial on the use of custom deleters.

A: Andrei Alexandrescu's Modern C++ Design has a good chapter on smart pointers. The Loki library described in the book provides templates that use policy classes to tune behavior of the smart pointers to your specific needs.
Be aware, these are a different beast than C++11's std::shared_ptr, and not compatible with those. Incorporating Loki into your codebase might not be a justifiable choice, depending on your maintenance needs. But the concepts in the book are worth exploring in any case.


text:
Q: Mori cone of homogeneous varieties Let $X$ be an homogeneous projective variety, written as the quotient $G/P$, where $G$ is a Lie group and $P$ is a parabolic subgroup of it. It seems it is well-known that the monoid of effective curves on $X$, as a submonoid of $H_2(X, \mathbb{Z})$, is generated by finitely many curves $\beta_1, \ldots, \beta_p$. Moreover the $\beta_i$ are embedded $\mathbb{P}^1$'s in $X$. For instance in the expository notes http://arxiv.org/abs/alg-geom/9608011, the authors use this fact (e.g. at the beginning of p. 37).
The question is simply: how does one prove this fact? Is there a reference for a precise proof of it (perhaps in a slightly different generality, or proving the same statement for the effective monoid inside the Chow group, instead of homology)?

A: One place this is treated is in Brion's notes, http://arxiv.org/abs/math/0410240, particularly Section 1.4, and the references in the notes at the end of that section.
A little more precisely, one shows that a divisor (line bundle) is nef iff it is globally generated, and this cone is generated by the Schubert divisors.  Using the fact that the Schubert classes form a self-dual basis for $H^*(X,{\Bbb Z})$ (as well as $A^*X$) under the intersection pairing, it follows that the "dual classes" to the Schubert divisors generate the cone of curves.  (As with many such things in $G/P$ world, the arguments for cohomology and Chow groups are exactly the same.)
By the way, it's an easy consequence of the existence of a dense open $B$-orbit that the pseudo-effective cone is generated by the complement of the open orbit --- that is, again by the Schubert divisors.  So for $G/P$, the nef and pseudo-effective cones are the same.


text:
Q: Probability to pick a sample with similar mean from a population. The average weight of a mature ear of corn is 175 grams. It's believed that the weight is normally distributed with a standard deviation of 8. From the population, the farmer selects 9 corn. The weights of selected ears are 182, 184, 166, 160, 190, 175, 174, 183 and 170 grams. (Farmer's weighting machine has precision 1 gram and gives integer results.) The sample average is 176. The farmer asks, what is the probability to obtain a sample average as large as 176 if he repeats this experiment?
I tried calculating the standard deviation of the sample
std dev = 9.63
later I considered CDF to calculate the probability as follows:
probability = CDF(176.5) - CDF(175.5)
since, the weighing machine is measuring integer values, I have considered
$175.5 \le 176 < 176.5$
Using the above considerations I am getting $probability = 0.05$ but this is too small for a number that close to the average.
Can someone suggest an alternative approach to the problem?

A: your reasoning is correct. What is wrong is that the sample mean has the following distribution
$$\overline{X}_9\sim N\left(175;\frac{8^2}{9}\right)$$
Thus
$$\mathbb{P}[175.5\leq \overline{X}_9<176.5]=\Phi\left( \frac{176.5-175}{8}\cdot3 \right)-\Phi\left( \frac{175.5-175}{8}\cdot3 \right)\approx13.87\%$$
The Sample variance is not needed.


text:
Q: How to unmarshal xml and map it to a POJO? I want to unmarshal this xml document that I am receiving from a REST call:
<ns2:hello xmlns:ns4="http://myspace.org/hello/history/1.0" xmlns:ns3="http://www.hello.com/IAP/im1_1_0" xmlns:ns2="http://www.w3.org/2005/Atom">
   <ns3:totalEntries>7</ns3:totalEntries>
   <ns2:id>123</ns2:id>
   <ns2:title type="text">Users</ns2:title>
   <ns2:updated>2017-08-22T07:51:27.270Z</ns2:updated>
   <ns2:link href="https://example.com:8080/1/rest/users" rel="self"/>
   <ns2:link href="https://example.com:8080/1/rest/users" rel="http://www.example.com/iap/im/user/create"/>
   <ns4:complete/>
   <ns2:entry>
      <ns2:id>urn:uuid:f0fd4040-04da-11e7-8f6a-8e3ecfcb7035</ns2:id>
      <ns2:title type="text">Hello</ns2:title>
      <ns2:content type="application/vnd.bosch-com.im+xml">
         <ns3:user>
            <ns3:id>f0fd4040-04da-11e7-8f6a-8e3ecfcb7035</ns3:id>
            <ns3:name>name</ns3:name>
            <ns3:firstName>Hello</ns3:firstName>
            <ns3:lastName>All</ns3:lastName>
         </ns3:user>
      </ns2:content>
   </ns2:entry>
</ns2:hello>

As you can see the XML is nested, and for this I am using JAXB for unmarshalling:
 try {
        JAXBContext jc = JAXBContext.newInstance(Feed.class);
        Unmarshaller um = jc.createUnmarshaller();
        Feed feed = (Feed) um.unmarshal(new StringReader(userEntity.getBody()));
        System.out.println(feed.getEntry().get(0).getContent().getUser().getFirstName());
    }
    catch (JAXBException e) {
        e.printStackTrace();
    }

But, I am not getting any data set into my POJO (it's null):
@XmlRootElement(namespace="http://www.w3.org/2005/Atom", name="hello")
public class Hello {
    private String id;
    private String totalEntries;
    private String title;
    private String updated;
    List<Entry> entry;
    Complete complete;
}

My POJO looks like above. Also I have created Entry and Complete POJO classes. How can I fix this?

A: The XML has 3 namespaces:
xmlns:ns4="http://myspace.org/hello/history/1.0"
xmlns:ns3="http://www.hello.com/IAP/im1_1_0"
xmlns:ns2="http://www.w3.org/2005/Atom"

You will need to  ensure that each element is in the correct namespace @XmlElement(namespace="xmlns:ns3="http://www.hello.com/IAP/im1_1_0") etc, to be able to unmarshall correctly
You may Also benefit from adding @XmlType(propOrder = { "totalEntries", ...

A: Have you tried just adding getters and setters to the class Hello ?
Your sample works with this simplified version of Hello.
@XmlRootElement(namespace = "http://www.w3.org/2005/Atom", name = "hello")
public class Hello {
  private String id;
  private String title;
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public String getTitle() {
    return title;
  }
  public void setTitle(String title) {
    this.title = title;
  }
}

And the Test class
public class Test {

  public static void main(String[] args) {
    try {
      JAXBContext jc = JAXBContext.newInstance(Feed.class);
      Unmarshaller um = jc.createUnmarshaller();
      InputStream file = new FileInputStream("path/to/file/feed.xml");
      Hello feed = (Hello) um.unmarshal(file);
      System.out.println(feed.getId());
      System.out.println(feed.getTitle());
    } catch (JAXBException | FileNotFoundException e) {
      e.printStackTrace();
    }
  }

}

Prints
123
Users


text:
Q: Getting an instance of an event aggregator each time I have to subscribe to an event? I have three events to which a WPF app must subscribe.  Is it necessary to get an instance of an event aggregator each time I have to subscribe to an event?
Here is how I am doing it now:
                IEventAggregator eventAggregator = new EventAggregator();
                eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
                eventAggregator.GetEvent<IncidentInfoReadyEvent>().Subscribe(OnIncidentInfoReady);

                eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
                eventAggregator.GetEvent<IncidentInfoReadyEvent2>().Subscribe(OnIncidentInfoReady2);

                eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
                eventAggregator.GetEvent<ArrestInfoReadyEvent>().Subscribe(OnArrestInfoReady);

Can I do it this way:
                IEventAggregator eventAggregator = new EventAggregator();
                eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
                eventAggregator.GetEvent<IncidentInfoReadyEvent>().Subscribe(OnIncidentInfoReady);
                eventAggregator.GetEvent<IncidentInfoReadyEvent2>().Subscribe(OnIncidentInfoReady2);
                eventAggregator.GetEvent<ArrestInfoReadyEvent>().Subscribe(OnArrestInfoReady);

A: You just need to do dependency injection in your class.
public class MainViewModel : ViewModelBase
{
    private readonly IEventAggregator _eventAggregator;

    public MainViewModel(IEventAggregator eventAggreator)
    {
        _eventAggregator = eventAggregator;

        _eventAggregator.GetEvent<MyEventOne>().Subscribe(() => DoSomething());
        _eventAggregator.GetEvent<MyEventTwo>().Subscribe(() => DoSomething());
        _eventAggregator.GetEvent<MyEventThree>().Subscribe(() => DoSomething());
    }
}

There is no need to take a new instance each time. But you should  register  logger in container as singleton.


text:
Q: Set textview from returned value I am creating a horizontal string which have colored bullet point between each text. The method which I've uses Spanned StringBuilder and return value as Html.fromHtml(builder.toString()). The problem is how to use that return value to set text in TextView.
public class MainActivity extends AppCompatActivity {

    TextView text;
    StringBuilder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = (TextView)findViewById(R.id.text);
        text.setText(Html.fromHtml(builder.toString()));

    }

    Spanned createSpannable(List<String> interests) {
        builder = new StringBuilder();
        int size = interests.size();
        for (int i = 0; i < size; i++) {
            builder.append(interests.get(i));
            if (i < size - 1) {
                builder.append(" &#8226 ");
            }
        }

        return Html.fromHtml(builder.toString());
    }

}

A: Try this:
public class MainActivity extends AppCompatActivity {

    TextView text;
    StringBuilder builder;
    Spanned mSpanned;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = (TextView)findViewById(R.id.text);
        mSpanned = createSpannable(YourList); //Pass your list
        text.setText(mSpanned);

    }

    Spanned createSpannable(List<String> interests) {
        builder = new StringBuilder();
        int size = interests.size();
        for (int i = 0; i < size; i++) {
            builder.append(interests.get(i));
            if (i < size - 1) {
                builder.append(" &#8226 ");
            }
        }
        return Html.fromHtml(builder.toString());
    }

}


text:
Q: Flickering video for tkinter video I am trying to make a simple play/pause application in tkinter. Basically I want to show a video and have a play/pause button underneath.
So, after some research I found this suitable post to show a video using tkinter and opencv:
to show video streaming inside frame in tkinter
When using the code, given in the accepted answer to show a video, there is no problem and I don't see any flickering. Here is the code:
# import the necessary packages
from __future__ import print_function
import tkinter as tk
from PIL import ImageTk, Image
import cv2

root = tk.Tk()
# Create a frame
app = tk.Frame(root, bg="white")
app.grid()
# Create a label in the frame
lmain = tk.Label(app)
lmain.grid()

# Capture from camera
cap = cv2.VideoCapture(r'PATH_TO_VIDEO_FILE')

# function for video streaming
frame_number = 0
def video_stream():
    global frame_number
    cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
    success, frame = cap.read()
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(1, video_stream)

    frame_number += 1

video_stream()
root.mainloop()

Now, I slightly altered the code to be able to use the grid manager and add a play button:
# import the necessary packages

from __future__ import print_function
import tkinter as tk
from PIL import ImageTk, Image

import cv2

class PhotoBoothApp:
    def __init__(self, path_to_video):
        # initialize the root window
        self.window = tk.Tk()
        self.window.title("Video_Player")
        self.videocap = cv2.VideoCapture(path_to_video)
        self.frame_number = 0

        # Initalize
        self.videocap.set(cv2.CAP_PROP_POS_FRAMES, self.frame_number)
        success, self.frame = self.videocap.read()
        cv2image = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGBA)
        self.img = Image.fromarray(cv2image)
        self.imgtk = ImageTk.PhotoImage(image=self.img)
        # Show frames
        self.picture_label = tk.Label(self.window, image=self.imgtk, relief=tk.RIDGE).grid(row=0, column=0)
        self.btn_next_image=tk.Button(self.window, text="Play", width=50, bg ="green",command=self.video_stream).grid(row=1,column=0)

        self.window.mainloop()

    def video_stream(self):

        self.videocap.set(cv2.CAP_PROP_POS_FRAMES, self.frame_number)
        sucess, frame = self.videocap.read()
        cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
        img = Image.fromarray(cv2image)
        self.imgtk = ImageTk.PhotoImage(image=img)
        self.picture_label = tk.Label(self.window, image=self.imgtk, relief=tk.RIDGE).grid(row=0, column=0)
        # Update Frame Number to display
        self.frame_number = self.frame_number + 1
        self.window.after(1, self.video_stream)

ph = PhotoBoothApp(r'PATH_TO_FILE')

The problem is that when I execute the above code, the video flickers as if tkinter need to reload something in-between frames. I have no clue why this happens.
P.S. This post here Flickering video in opencv-tkinter integration did not help me.

A: You need to make two changes: split your self.picture_label line to create a proper reference to your Label object, and then use self.picure_label.config(...) to change the image.
class PhotoBoothApp:
    def __init__(self, path_to_video):
        # initialize the root window
        ...
        self.picture_label = tk.Label(self.window, image=self.imgtk, relief=tk.RIDGE)
        self.picture_label.grid(row=0, column=0)
        ...

    def video_stream(self):
        ...
        img = Image.fromarray(cv2image)
        self.imgtk = ImageTk.PhotoImage(image=img)
        self.picture_label.config(image=self.imgtk)
        # Update Frame Number to display
        self.frame_number = self.frame_number + 1
        self.window.after(1, self.video_stream)

ph = PhotoBoothApp(r'PATH_TO_FILE')


text:
Q: jquery ui button icon change dynamically $("#slideshowadvanceconfig").button({
icons:{ primary: 'ui-icon-circle-arrow-e'} }).toggle(function () {
$(this).button("option", { icons: { primary: 'ui-icon-circle-arrow-s'} });

$(".settings").slideDown('slow'); },
function () { $(this).button("option", { icons: { primary: 'ui-icon-circle-arrow-e'} });

$(".settings").slideUp('slow');
});

Through this above code i am trying to change the icon of jquery ui button dynamically. Slideup and SlideDown works but image is not changing , can anybody tell me the problem?

A: From what I can see you are targeting the icons: value after the page is drawn, you will need to target the src value of the html image element to change it programmaticly


text:
Q: Handle file changes with i18next I'm using next.js with i18n and when I initialize my i18n.js , I'm loading the files with the translations files this way:
import { initReactI18next } from "react-i18next";
import i18n from 'i18next';
import {defaultApplicationLocale} from '../application.properties'
var en_GB = require('./locales/EN/en-GB.json')
var pt_PT = require('./locales/PT/pt-PT.json')
var fr_FR = require('./locales/PT/fr_FR.json')

  const resources = {
    en_GB: {
      translation: en_GB
    },
    pt_PT: {
      translation: pt_PT
    },
    fr_FR:{
      translation: fr_FR
    }
  };

  i18n
    .use(initReactI18next)
    .init({
      resources,
      lng: defaultApplicationLocale,
      interpolation: {
        escapeValue: false
      }
    });

export default i18n

Later I import this i18n already initialized and everything works fine.
But if I change one of the translation files (change some message from 'hi' to 'hello') it's doesn't work until I restart the whole thing. In theory i18n provides a function to reload resources i18n.reloadResources() which should reload the data from the files, but it doesn't.
What am I doing wrong ?

A: If you're using webpack, there is this HMR webpack plugin that allows reloading translation resources: https://github.com/felixmosh/i18next-hmr


text:
Q: How to post json String in android How I post json String. My json is correct but problem to post to server.
 API = public static String getaddProject= "http://10.10.10.64:10003/API/Project/Add";

Code
     for(int i=0; i<iArr.size(); i++){

    if(i==0){

        st = "{\"userId\":" + iArr.get(i) + "}";
        str += st;
    }else if(i>0 && i<iArr.size()-1){
        st = ",{\"userId\":" + iArr.get(i) + "}";
        str+=st;
    }else if(i==iArr.size()){
        st = ",{\"userId\":" + iArr.get(i) + "}]}";
        str+=st;
    }
}
String myPost = "{\"project\":{\"Name\":"+ "\""+ title + "\""
        + ",\"Description\":" + "\""+ desc + "\""
        + ",\"createdBy\":" + usrid + ""
        + ",\"startDate\":" + "\""+ startdate + "\""
        + ",\"dueDate\":" + "\""+ duedate + "\""
        + ",\"projectLeadId\":" + leadPosition + ""
        + ",\"QAId\":" + QAssurencePosition + ""
        + ",\"TotalHour\":" +"\""+ edtHour + "\""+ "},\"members\":[";
myPost += str;
myPost +="]}";
RequestPackage myPackage = new RequestPackage();
myPackage.setUri(getaddProject);
myPackage.setMethod("POST");
myPackage.setParam("posting", myPost);
new MyTask().execute(myPackage);

Toast.makeText(CreateProject.this,"Testing String: " + myPost,Toast.LENGTH_LONG ).show();

Log.d("My Post :",myPost);
 }

I get the following result:
{"data":null,"statusCode":200,"isSuccess":true,"message":"input data is required"}

message : Input data is required

And some more code from the comments:
protected String doInBackground(RequestPackage... params) {
    String content = HttpManager.getData(params[0]);
    //...
}

A: You should use a library for JSON parsing like Gson or Xml Parser.
In your Java Code you can use JSONObject api's as well, and add using typical .put methods.


text:
Q: The service threw an exception during a call to the second service within a transaction. What general solution is possible? My problem schematically is:

*

*service A beginning transaction;

*service A prepared and save any data to DB

*service A make some (HTTP-REST) request on service B

*if service B success responded (and saved data), then A commit transaction

*If service B throws any exception - service A rollback transaction

The problem is that service B just responded slowly and service A caught a timeout exception and rolled back the transaction. Service B, however, processed the data (although it did not respond in time).
When, the process is considered successful if both service A and service B have saved and processed the data.
In this case, due to the rollback of the transaction, the data of service A was not saved.
Is there a general solution to this problem? I look towards 2PC and event-based distributed transactional mechanism (such as saga pattern). Thans for any help/links/etc.

A: I generally solve this by splitting the call to Service B into a "prepare" and a "commit" phase.  This is effectively putting in-place 2PC for a service layer, inserting records in a "Pending" state, and then having a final call to "Activate" the change.
The fact of the matter is, REST over HTTP is not great for transactional consistency.  You are much better off with eventual consistency models when you are talking about potential long-running processes.  Put a message queue behind Service B, queue the update up, and have Service A poll for completion (or have a call-back).