text:
Q: Assigning a value in SQLite cursor to a variable Iam trying to find average of a column in my sqlite database.
Here is the code:
public void getAvgMileage(Prediction pd)
    {

    String [] columns = new String[]{KEY_ROW_ID, KEY_KM, KEY_FUEL_QTY, KEY_FUEL_PRICE, KEY_TOTAL_COST, KEY_MILEAGE, KEY_DATE,KEY_TANK_FULL};
    predictionCursor = ourDatabase.rawQuery("SELECT AVG(_mileage) FROM fuel_table WHERE _mileage IS NOT NULL ORDER BY _id DESC LIMIT 5", null);
                predictionCursor.moveToFirst();
                if(predictionCursor!=null && predictionCursor.getCount()>0)
                {
                    predictionCursor.moveToLast();
                   findAvgMileage = (Double.valueOf(predictionCursor.toString()));
                    pd.setpredictionMileage(findAvgMileage);
                }
}

But Iam geting a NullPointerException.
Any help??
Thank you.

A: It doesn't look like you are getting the value out of the cursor for your SQL recordset
This line:
findAvgMileage = (Double.valueOf(predictionCursor.toString()));

looks like it's trying to take a double value of the tostring() of the actual cursor - which I don't think is going to usable or at least not parseable to Double. The return of Cursor.toString() may well be a null value.
replace the line with the following:
findAvgMileage = predictionCursor.getDouble(0);

This new line will fetch out the value in the first column of the current position of the curosr which in your SQL should be the average value you want.


text:
Q: Python do action without pop up response I've been trying to write a python program to automatically shut down my computer. The Notification Messagebox module uses tkinter code like in TutorialPoint. The pop up will show Yes / No options.
with the current code, only if i press "No" button, the system will shutdown.
So instead, it should automatically start the shutdown process without me clicking anything. At the sametime, if i click "Yes", then the shutdown process should stop.
This is the code. How do i accomplish this?
import MessageBox
def PopUp(Title, Msg, Type='Info'):
    Title = str(Title)
    Msg = str(Msg)

    root = tk.Tk()
    root.withdraw()
    if Type == "Question":
        response = MessageBox.askquestion(Title, Msg)
        print("question", response)
        return response
    elif Type == "TryAgain":
        response = MessageBox.askretrycancel(Title, Msg)
        print("try again", response)
        return response
    else:
        print("Incorrect Type selected.")
        response = MessageBox.showinfo(Title, Msg)
        print("info", response)
        return response

def main():
    CurrentTime = int(time.strftime('%H'))
    if CurrentTime > 22 or CurrentTime < 5:
        msg = ("The Time is %s hours. Abort Automatic Shutdown?" % CurrentTime)
        resp1 = Notification.PopUp("Auto Shut Down", msg, Type="Question")
        print('Response from Notification is %s' % resp1)

        if resp1 == 'no':
            closeApps()
            shutDown()
        else:
            print('ShutDown abortered by user.')

if __name__ == '__main__':
    main()

A: For the closeApps(), you could use psutil module,
import psutil
for process in psutil.process_iter():
    if process.name()=="Application.exe":
        process.kill()

The psutil.process_iter() gives a list of all running processes.
Note: Replace "Application.exe" with the name of the application to close.
As for shutDown(), you simply have to use os to give terminal commands:
import os
os.system("shutdown /s")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does the first asterick in pointcut expression stand for "any return type" or "any access modifier"? Please consider this pointcut expression:
@Before("execution(* org.mycompany.service.*.get*())")

I understand that an advice annotated by the expression above will execute for all methods who belong to a class in the package org.mycompany.service and whose names start with "get". My question is: what does the first asterick stand for? Is it a wildcard for access modifier or for return type?

A: From the reference documentation
The format of an execution expression follows:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern) throws-pattern?)

All parts except the returning type pattern (ret-type-pattern in the
preceding snippet), the name pattern, and the parameters pattern are
optional

So in the given code , first * represents ret-type-pattern


text:
Q: Browser displaying PHP code I am running XAMPP in order to use PHP on my local computer. I put all of my scripts inside of the htdocs folder (the default location). Everything used to work great until recently. For example, if I click on an HTML file in htdocs, the file opens up in a browser(like it should). But, if I click submit on a form with an action set to "some-script.php" It goes to the php page and displays the php code. Now, if I type into my browser "localhost/some-html.html" then it works? Why is that? What could I be doing wrong??

A: When you access it by typing "localhost/some-html.html" into the address bar you use XAMPP's server and PHP engine to access the page, when you simply double click the file in the folder you are just opening the file with the default program (which happens to be your browser)

A: define a base url variable like $baseurl = "http://localhost/foldername/" and use this variable in your action like action = "example.php".


text:
Q: Inspecting the E-mail traffic of a Windows Server 2008 R2 I have seen that the IP address of my mail server has added to blocked IP address list on http://psbl.org. I am using this server for personal use. So, it is not that much of an issue that I am, as a non IT pro, handling the server.
I suspect that someone obtained the password of one of the e-mail addresses or my server got infected by a spamware. I am trying to find out if there is any sign of a spamware inside the server by using SysInternals' tools but I haven't seen anything unusual (or I don't know where and what to look).
Is there any way I can inspect the SMTP traffic of my mail server to see usual e-mails going out from my server? First, I thought that Wireshark would be a suitable tool but I am not that experienced with that tool as well.
Also, which approach should I follow to be sure that my server doesn't have a spamware?
I am on Windows Server 2008 R2.

A: Check out what your server looks like to the outside world here: http://www.mxtoolbox.com/
Run the SMTP diagnostics to make sure you aren't an open relay, which is a common mistake, and will get you on a blacklist within 15 minutes of setting up a new mail serve, since spammers are constantly scanning for open relays. Do you have any type of perimeter defense in front of this box, or is is just connected to the internet?
If you are using Exchange, look at the queue in ESM. If you are an open relay, it will be FULL.


text:
Q: How do you get the namespace of a component? I'm trying to write CSS stylesheet dynamically but Flex 4 requires that you declare the namespace in the Style markup.
If I have a Spark Button or MX Button class or class instance how would I get the namespace of that button?
So far I've tried this:
var className:Object = getQualifiedClassName(myButton);
var ButtonClass:Object = ApplicationDomain.currentDomain.getDefinition(className);
var button:Object = new ButtonClass();

With that information I can write this:
<fx:Style>

    myButton {
        color: red;
    }

</fx:Style>

I need to create this:
<fx:Style>
    @namespace s "library://ns.adobe.com/flex/spark";
    @namespace mx "library://ns.adobe.com/flex/mx";

    s|Button {
        color: red;
    }

</fx:Style>

I would like to be able to get this information at runtime but design time may be acceptable as well.

A: It's the same format as the namespace in the MXML code.  I.e., if you have components in com.xyzzy.components, the MXML namespace is something like
xmlns:components="com.xyzzy.components.*"

And the CSS namespace would be like
@namespace components "com.xyzzy.components.*";
components|myButton {...}

A: It looks like I can't get it at runtime but I can get it XML files from the SDK directory and create a table of classes and their namespace.
In $FlashBuilder/sdks/4.6.0/frameworks/flex-config.xml there is a node called namespaces that contain the URI of the namespace and then a reference to the XML file that contains a list of classes in that namespace.
  <!-- Specify a URI to associate with a manifest of components for use as MXML -->
  <!-- elements.                                                                -->
     <namespace>
        <uri>http://ns.adobe.com/mxml/2009</uri>
        <manifest>mxml-2009-manifest.xml</manifest>
     </namespace>
     <namespace>
        <uri>library://ns.adobe.com/flex/spark</uri>
        <manifest>spark-manifest.xml</manifest>
     </namespace>
     <namespace>
        <uri>library://ns.adobe.com/flex/mx</uri>
        <manifest>mx-manifest.xml</manifest>
     </namespace>
     <namespace>
        <uri>http://www.adobe.com/2006/mxml</uri>
        <manifest>mxml-manifest.xml</manifest>
     </namespace>
     <namespace>
        <uri>http://flex.apache.org/ns</uri>
        <manifest>apache-manifest.xml</manifest>
     </namespace>
     <namespace>
        <uri>http://flex.apache.org/experimental/ns</uri>
        <manifest>experimental-manifest.xml</manifest>
     </namespace>
  </namespaces>

I can use that information and the MXML document to add the necessary namespace to each node.


text:
Q: Can we use AWS S3 sdk to connect MinIO(running locally) programatically? If yes, how? I am trying to connect my local MinIO instance running in docker. I have written a simple Go program to do the work. See following:
package main

import (
    "bytes"
    "context"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-sdk-go/service/s3/s3manager"
    "log"
)

func main() {

    endpoint := "localhost:9000"
    accessKeyID := "1mVyDeEcrRU7qQ7h"
    secretAccessKey := "vNi9SNfcHNxfRDETSvkeFLO210mzu7ee"
    useSSL := false

    awsSession := session.Must(session.NewSession(&aws.Config{
        Region: aws.String("ap-south-1"),
        Credentials: credentials.NewStaticCredentialsFromCreds(credentials.Value{
            AccessKeyID:     accessKeyID,
            SecretAccessKey: secretAccessKey,
            SessionToken:    "",
        }),
        Endpoint:   aws.String(endpoint),
        DisableSSL: aws.Bool(!useSSL),
    }))

    ctx := context.Background()

    file, err := downloadFileFromS3(ctx, awsSession, "mybucket", "data.txt")
    if err != nil {
        log.Fatal(err)
    }

    reader := bytes.NewReader(file)
    println(reader)
}

func downloadFileFromS3(ctx context.Context, sess *session.Session, bucketName string, fileName string) ([]byte, error) {
    downloader := s3manager.NewDownloader(sess)

    buff := &aws.WriteAtBuffer{}
    _, err := downloader.DownloadWithContext(ctx, buff,
        &s3.GetObjectInput{
            Bucket: aws.String(bucketName),
            Key:    aws.String(fileName),
        })
    if err != nil {
        return nil, err
    }

    return buff.Bytes(), nil
}

But this fails to do the job. Check error below:
GOROOT=/usr/local/go #gosetup
GOPATH=/Users/kuldeep/go #gosetup
/usr/local/go/bin/go build -o /private/var/folders/29/zkqqp9_d0fscymp5ph4rscl40000gp/T/GoLand/___2go_build_minio_client_example minio-client-example #gosetup
/private/var/folders/29/zkqqp9_d0fscymp5ph4rscl40000gp/T/GoLand/___2go_build_minio_client_example
2023/01/16 22:37:52 RequestError: send request failed
caused by: Get "http://mybucket.localhost:9000/data.txt": dial tcp: lookup mybucket.localhost: no such host

Process finished with the exit code 1

What should I do to make it work?


text:
Q: In Rails should i generate a model to contain simple plain list? I'm currently building a web-page with Ruby on Rails. Im creating A data model that works as follows: Project has many Milestones and milestone has many goals
Example:
Project.milestones.goals

So I generated a model for Project and a model for milestones but generating a model for list of goals seems like big and unnecessary.
Should I generate a model for goals or is there something else that would fit more for this purpose?

A: It all comes down to this question: Goals need to be persisted on your database?
If the answer is yes, then you must create a model that inherits from ActiveRecord::Base, and if the answer is no, you could create a model, that don't have the need for persistence methods of ActiveRecord, but acts like an Enum, having static values and stuff.


text:
Q: Force https on Hash fragmented url with htaccess? I have website which developed by MVC js (EmberJS) so the all the routes is hash fragmented routes (eg. #/home), my problem now is that i am trying to force https with htaccess to all website but when i do that i always lose the fragmented part of the url.
How can i achieve that without losing the ash fragment part?
<IfModule mod_rewrite.c>
  RewriteCond %{HTTP:X-Forwarded-Ssl} !on
  RewriteRule (.*) https://example.dk [NE,L,R]
</IfModule>

Please help

A: I use the following rule - which just testing now does not remove the hash;
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{SERVER_NAME}/$1 [R,L]


text:
Q: Unknown error in a C++ program void change_degree(vector<int> &nodes, map<int, vector<int> > &edges, int vertex){
    map<int, vector<int> >::iterator ite;
    ite = edges.find(vertex);
    vector<int> temp = (*ite).second;
    vector<int>::iterator it;
    for(it = temp.begin(); it != temp.end(); it++){
        cout << *it;
        if(nodes[*it + 1] > 1)
            nodes[*it + 1]++;
    }
}

This function is producing error
*** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0x09c930e0 ***

Can someone tell me why is it coming and what it means?
Thanks in advance.

A: Well, one issue I see is that you're not checking to see if vertex was actually found in edges. You are probably dereferencing memory you don't own.
void change_degree(vector<int> &nodes, map<int, vector<int> > &edges, int vertex){
    map<int, vector<int> >::iterator ite = edges.find(vertex);
    if (ite != edges.end()) {  // <-- this is what you're missing
        vector<int> temp = (*ite).second;  // <-- this is probably where you're dying
        vector<int>::iterator it;
        for(it = temp.begin(); it != temp.end(); it++){
            cout << *it;
            if(nodes[*it + 1] > 1)  // <-- you could also be crashing here
                nodes[*it + 1]++;
        }
    }
}

Next time, try running your app through GDB, and check your stack trace.
Edit: another possibility is that you're indexing into nodes incorrectly. Check that nodes[*it + 1] is valid.


text:
Q: trouble with declaring a delegate i have two views with view1 calling view2. i need to pass data from view2 back to view1. so i am attempting to set up a delegate. here's what i got in view controller 2:
.h file

@protocol addEventDelegate <NSObject>

-(void) setAddedEventFlag:(BOOL) hasAddedEvent;

@end

@interface AddEventViewController : UIViewController <UITextFieldDelegate, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDelegate>

@property (weak, nonatomic) id delegate;  //changed from strong to weak

i then @synthesize delegate in the .m file
when try to include the addEventDelegate for the first view controller, xcode can not find it:
.h file

#import "AddEventViewController.h"

@interface FieldReportViewController : UIViewController <UITextFieldDelegate,
UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDelegate, addEventDelegate>

i get the error: "Cannot find protocol declaration for 'addEventDelegate'".
what is wrong?
EDIT:

//code

ERRORS:

A: *

*Make sure your spelling is correct.

*Make sure that AddEventViewController.h/.m are added to the project.

Other than that, what you have is fine.
Edit
Something else I would suggest is to rename your delegate, perhaps there is a naming conflict.  Although I haven't seen any issues with 'add' and 'set', but I've seen issues in the past when prefixing with, say, 'new'.
Also, clean your project, and rebuild and see if that helps.
There could be a situation if you have multiple targets in your project, and possibly only added AddEventViewController.h/m to one of them, and you are building/debugging a different target.

A: Here's the correct way to define a protocol
@protocol addEventDelegate; // forward declaration for delegate property

@interface AddEventViewController : UIViewController <UITextFieldDelegate, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDelegate>
{
    id <addEventDelegate> *delegate
}

@property (weak, nonatomic) id <addEventDelegate> *delegate;

@end // interface

@protocol addEventDelegate <NSObject>
// @optional // if you want to make it optional
    -(void) setAddedEventFlag:(BOOL) hasAddedEvent;
@end // protocol

A: Solved the issue. i had an #import loop. I was #importing all my classes in my .h files. i changed to @Class in .h file and moved the #import's to the .m files and works like a charm now.

A: You can import addEventDelegate in FieldReportViewController.m file
@interface FieldReportViewController ()<AddEventDelegate>
@end

This one is working in my app


text:
Q: Runing php on server side issue Please forgive the simplicity of this question. The answer will be obvious to many of you. But since I'm completely new to php and JSON, and I can't find a concrete answer on Google, I need to ask.
I have the following:

*

*Client side Android app

*mySQL database on server

*JSON in between

The question is very simple. Where on the server do I put the php file? Any directory? A specific location? I just need a simple working answer. Not concerned about security or anything fancy at this stage. Please help.
Also, does anyone know of a very simple tutorial that talks about php, json, and working on the server side for someone like me who's completely new to it?

A: Your server must be available with a one of the given folders

*

*public_html

*www

*htdocs

if any of the folder you can see in your server then this is the place where you need to place your php files
basic Introductory Tutorial for PHP with examples
tizag.com
Basic Introductory Tutorial For JSON
JSON
JSON with PHP

A: As long as the php file is accessible by http you are fine.  So pretty much anywhere.
here is a tutorial.  http://www.itnewb.com/tutorial/Introduction-to-JSON-and-PHP

A: To run your php script you will need an http server on your server that handles php script.
For example you can use the apache web server with mod_php. You then can put your php file in the server default web folder or configure another one.


text:
Q: Play mp4 video using GStreamer on Google Coral Dev Board Mini I'm trying to play a video file on a Google Coral Dev Board Mini using GStreamer.
I am using the file "drop.avi" from here: https://www.engr.colostate.edu/me/facil/dynamics/avis.htm
I can successfully play this file using the following command:
gst-launch-1.0 playbin uri=file:///home/mendel/coral/google-coral/example-object-tracker/gstreamer/drop.avi

I now want to try playing an mp4 file.
I have converted the avi file using the following command from here:
ffmpeg -i drop.avi -an -vf "scale=960:540,format=yuv420p" -colorspace bt470bg -color_range tv -color_primaries smpte170m -color_trc bt709 -vcodec libx264 -brand mp42 -c:v libx264 -profile:v baseline drop.mp4

and get the following:
$ mediainfo drop.mp4
General
Complete name                            : drop.mp4
Format                                   : MPEG-4
Format profile                           : Base Media / Version 2
Codec ID                                 : mp42 (isom/iso2/avc1/mp41)
File size                                : 1.82 MiB
Duration                                 : 6 s 67 ms
Overall bit rate                         : 2 511 kb/s
Writing application                      : Lavf58.20.100

Video
ID                                       : 1
Format                                   : AVC
Format/Info                              : Advanced Video Codec
Format profile                           : Baseline@L3.1
Format settings                          : 3 Ref Frames
Format settings, CABAC                   : No
Format settings, ReFrames                : 3 frames
Codec ID                                 : avc1
Codec ID/Info                            : Advanced Video Coding
Duration                                 : 6 s 67 ms
Bit rate                                 : 2 509 kb/s
Width                                    : 960 pixels
Height                                   : 540 pixels
Display aspect ratio                     : 16:9
Frame rate mode                          : Constant
Frame rate                               : 30.000 FPS
Color space                              : YUV
Chroma subsampling                       : 4:2:0
Bit depth                                : 8 bits
Scan type                                : Progressive
Bits/(Pixel*Frame)                       : 0.161
Stream size                              : 1.81 MiB (100%)
Writing library                          : x264 core 155 r2917 0a84d98
Encoding settings                        : cabac=0 / ref=3 / deblock=1:0:0 / analyse=0x1:0x111 / me=hex / subme=7 / psy=1 / psy_rd=1.00:0.00 / mixed_ref=1 / me_range=16 / chroma_me=1 / trellis=1 / 8x8dct=0 / cqm=0 / deadzone=21,11 / fast_pskip=1 / chroma_qp_offset=-2 / threads=6 / lookahead_threads=1 / sliced_threads=0 / nr=0 / decimate=1 / interlaced=0 / bluray_compat=0 / constrained_intra=0 / bframes=0 / weightp=0 / keyint=250 / keyint_min=25 / scenecut=40 / intra_refresh=0 / rc_lookahead=40 / rc=crf / mbtree=1 / crf=23.0 / qcomp=0.60 / qpmin=0 / qpmax=69 / qpstep=4 / ip_ratio=1.40 / aq=1:1.00
Color range                              : Limited
Color primaries                          : BT.601 NTSC
Transfer characteristics                 : BT.709
Matrix coefficients                      : BT.470 System B/G
Codec configuration box                  : avcC

But when I try to play this I get an error:
$ gst-launch-1.0 playbin uri=file:///home/mendel/coral/google-coral/example-object-tracker/gstreamer/drop.mp4
Setting pipeline to PAUSED ...
Pipeline is PREROLLING ...
Got context from element 'sink': gst.gl.GLDisplay=context, gst.gl.GLDisplay=(GstGLDisplay)"\(GstGLDisplayWayland\)\ gldisplaywayland0";
Got context from element 'playsink': gst.gl.GLDisplay=context, gst.gl.GLDisplay=(GstGLDisplay)"\(GstGLDisplayWayland\)\ gldisplaywayland0";
WARNING: from element /GstPlayBin:playbin0/GstURIDecodeBin:uridecodebin0/GstDecodeBin:decodebin0/GstCapsFilter:capsfilter0: not negotiated
Additional debug info:
gstbasetransform.c(1415): gst_base_transform_reconfigure (): /GstPlayBin:playbin0/GstURIDecodeBin:uridecodebin0/GstDecodeBin:decodebin0/GstCapsFilter:capsfilter0:
not negotiated
ERROR: from element /GstPlayBin:playbin0/GstURIDecodeBin:uridecodebin0/GstDecodeBin:decodebin0/GstQTDemux:qtdemux0: Internal data stream error.
Additional debug info:
qtdemux.c(6073): gst_qtdemux_loop (): /GstPlayBin:playbin0/GstURIDecodeBin:uridecodebin0/GstDecodeBin:decodebin0/GstQTDemux:qtdemux0:
streaming stopped, reason not-negotiated (-4)
ERROR: pipeline doesn't want to preroll.
Setting pipeline to NULL ...
Freeing pipeline ...

What am I doing wrong?
Edit:
The following works:
gst-launch-1.0 filesrc location=drop.mp4 ! decodebin ! autovideoconvert ! autovideosink

But this doesn't
$ gst-launch-1.0 filesrc location=drop.mp4 ! decodebin ! videoconvert ! autovideosink
Setting pipeline to PAUSED ...
Pipeline is PREROLLING ...
Got context from element 'autovideosink0': gst.gl.GLDisplay=context, gst.gl.GLDisplay=(GstGLDisplay)"\(GstGLDisplayWayland\)\ gldisplaywayland0";
WARNING: from element /GstPipeline:pipeline0/GstDecodeBin:decodebin0: Delayed linking failed.
Additional debug info:
./grammar.y(510): gst_parse_no_more_pads (): /GstPipeline:pipeline0/GstDecodeBin:decodebin0:
failed delayed linking some pad of GstDecodeBin named decodebin0 to some pad of GstVideoConvert named videoconvert0
ERROR: from element /GstPipeline:pipeline0/GstDecodeBin:decodebin0/GstQTDemux:qtdemux0: Internal data stream error.
Additional debug info:
qtdemux.c(6073): gst_qtdemux_loop (): /GstPipeline:pipeline0/GstDecodeBin:decodebin0/GstQTDemux:qtdemux0:
streaming stopped, reason not-linked (-1)
ERROR: pipeline doesn't want to preroll.
Setting pipeline to NULL ...
Freeing pipeline ...

Still quite confused - am I missing something fundamental?

A: You write you are using a Google development board. Assuming this is some embedded development board, chances are high that the decoder on that board is implemented in hardware. So most likely your final image buffer after decoding resides in GPU memory.
autovideoconvert probably selects a color converter that operates on these GPU buffers (opengl? vaapi? thats something you will find out). videoconvert on the oither hand operates on buffers from the host main memory. So before you could use that you will need to download the video buffer to the host memory - gldownload in case of OpenGL buffers for example.


text:
Q: How to get percentile of each element of list of matrices If I have a list of matrices with same dimensions, how can I get each element of list of matrices in R? For example, I have 4 matrices:
> a
           [,1]       [,2]       [,3]
[1,] -0.8761453  0.2821336 -0.8541406
[2,] -0.9649200  1.7734091 -1.2058440
[3,] -0.4250063 -0.8197162 -1.3997540
> b
           [,1]       [,2]       [,3]
[1,] -1.2096577 -0.5440074  0.6102016
[2,] -0.1299645 -0.8943189 -1.8042720
[3,]  1.0111488  0.2547343  0.2395172
> c
           [,1]       [,2]       [,3]
[1,]  0.2853833 -0.2716714  0.2330467
[2,] -0.7963095 -1.2120779  0.6909755
[3,]  0.3479346  0.1803124 -0.7400176
> d
             [,1]       [,2]       [,3]
[1,] -1.048740842 -1.0492152 -0.6889409
[2,] -0.004154795 -0.6167335 -0.8028550
[3,] -1.111915258 -2.1586534 -0.1448612

The result I want is if I want the 2nd least minimum of each element.
> res
           [,1]       [,2]       [,3]
[1,] -1.0487408 -0.5440074 -0.6889409
[2,] -0.7963095 -0.8943189 -1.2058440
[3,] -0.4250063 -0.8197162 -0.7400176

A: If we need the second minimum value, create an array by concatenating the matrixes together, specify the dimensions and use apply with the required MARGIN, sort the elements from smallest to largest and get the second element
apply(array(c(a, b, c, d), c(dim(a), 4)), c(1, 2), FUN = function(x) sort(x)[2])
#           [,1]       [,2]       [,3]
#[1,] -1.0487408 -0.5440074 -0.6889409
#[2,] -0.7963095 -0.8943189 -1.2058440
#[3,] -0.4250063 -0.8197162 -0.7400176

NOTE: Based on the OP's post, it looks like 'a', 'b', 'c', 'd' are separate matrix objects in the global environment


text:
Q: JAVA - Parsing an XML file into Map using FasterXml.Jackson I have the following XML file:
<?xml version="1.0" encoding="UTF-8"?>
<Site xmlns="bla" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  id="0" affiliations="foo" status="OPERATIONAL" color="#DB2253" updateTime="2002-12-17T09:30:47.0Z" name="GFB_0035" subject="GF">
    <location>
        <vertices Lat="41.905889" Lon="12.452019"/>
        <vertices Lat="41.905973" Lon="12.453596"/>
        <vertices Lat="41.905206" Lon="12.453707"/>
        <vertices Lat="41.905058" Lon="12.452109"/>
    </location>
</Site>

I am using FasterXml.Jackson to parse the data into a Map<String, Object>
object using the following code:
XmlMapper xmlMapper = new XmlMapper();
Map<String, Object> data = xmlMapper.readValue(new File(xmlFile), Map.class);

However, when I look at the contents of the "location" field I have only one vertex instead of four (the last one).
UPDATE:
The map object which I get looks like the one bellow:
{id=0, affiliations=foo, status=OPERATIONAL, color=#DB2253, updateTime=2002-12-17T09:30:47.0Z, name=GFB_0035, subject=GF, location={vertices={Lat=41.905058, Lon=12.452109}}}

Is there a way to get all four entries using FasterXml.Jackson?

A: According to Java Documentation -
A map cannot contain duplicate keys; each key can map to at most one value.
And thats why when you look at the contents of the "location" field you have only one vertex instead of four (the last one).
I think you should parse the XML in your own classes instead of storing it into Map
See below example -
import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class Stack {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

        String xmlFile = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<Site xmlns=\"bla\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"  id=\"0\" affiliations=\"foo\""
                + " status=\"OPERATIONAL\" color=\"#DB2253\" updateTime=\"2002-12-17T09:30:47.0Z\" name=\"GFB_0035\" "
                + "subject=\"GF\">"
                + "    <location>"
                + "        <vertices lat=\"41.905889\" lon=\"12.452019\"/>"
                + "        <vertices lat=\"41.905973\" lon=\"12.453596\"/>"
                + "        <vertices lat=\"41.905206\" lon=\"12.453707\"/>"
                + "        <vertices lat=\"41.905058\" lon=\"12.452109\"/>"
                + "    </location>"
                + "</Site>";

        XmlMapper mapper = new XmlMapper();
        SiteData site = mapper.readValue(xmlFile, SiteData.class);
        System.out.println(site);
    }

}

SiteData.java
import com.fasterxml.jackson.xml.annotate.JacksonXmlProperty;
import com.fasterxml.jackson.xml.annotate.JacksonXmlRootElement;

@JacksonXmlRootElement(localName = "Site")
public class SiteData {

    private String id;

    private String affiliations;

    private String status;

    private String color;

    private String updateTime;

    private String name;

    private String subject;

    @JacksonXmlProperty(localName = "location")
    private LocationData location;

    public String getId() {
        return id;
    }

    public void setIdValue(String id) {
        this.id = id;
    }

    public String getAffiliations() {
        return affiliations;
    }

    public void setAffiliations(String affiliations) {
        this.affiliations = affiliations;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(String updateTime) {
        this.updateTime = updateTime;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public LocationData getLocation() {
        return location;
    }

    public void setLocation(LocationData location) {
        this.location = location;
    }

    @Override
    public String toString() {
        return "Site [id=" + id + ", affiliations=" + affiliations
                + ", status=" + status + ", color=" + color + ", updateTime="
                + updateTime + ", name=" + name + ", subject=" + subject
                + ", locations=" + location + "]";
    }
}

LocationData.java
import java.util.List;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;

public class LocationData {

    @JacksonXmlElementWrapper(useWrapping=false)
    private List<VerticesData> vertices;

    public List<VerticesData> getVertices() {
        return vertices;
    }

    public void setVertices(List<VerticesData> vertices) {
        this.vertices = vertices;
    }

    @Override
    public String toString() {
        return "LocationData [vertices=" + vertices + "]";
    }

}

VerticesData.java
public class VerticesData {

    private String lat;

    private String lon;

    public String getLat() {
        return lat;
    }

    public void setLat(String lat) {
        this.lat = lat;
    }

    public String getLon() {
        return lon;
    }

    public void setLon(String lon) {
        this.lon = lon;
    }

    @Override
    public String toString() {
        return "Vertices [lat=" + lat + ", lon=" + lon + "]";
    }

}

Output:
Site [id=0, affiliations=foo, status=OPERATIONAL, color=#DB2253, updateTime=2002-12-17T09:30:47.0Z, name=GFB_0035, subject=GF, locations=LocationData [vertices=[Vertices [lat=41.905889, lon=12.452019], Vertices [lat=41.905973, lon=12.453596], Vertices [lat=41.905206, lon=12.453707], Vertices [lat=41.905058, lon=12.452109]]]]


text:
Q: Pure reducers and canvas context? I'm creating a MS Paint replica. After a week of messing around with React states, I wanted to go with Redux. The problem I think of is: How can I pair a reducer which must be pure, with a canvas context which basically has its own state (what is drawn on it)? I see two options here:

*

*Do I need to recreate canvas context every time the state changes? If so, I do think this is really redundant practice.

*Or can I just carry the context between states and use its methods to draw in reducers as I'd usually do? But this makes my reducers impure as I understand.
Thank you.

A: I'm assuming the canvas context can't be easily serialized and it's not the "source of truth" in terms of application state (rather an object created by the native browser api). Therefore I'd only use redux to have undo/time travel functionality. Your reducer would only hold a history of drawing actions. Replaying those on an empty canvas should restore the state of the app.

A: The canvas represents the UI of your application, and shouldn't be kept in the store itself.  Since a canvas retains whatever pixels have already been drawn, what you probably need to do is re-execute your drawing logic whenever the store has been updated.
There's a pair of posts out there that demonstrate how to use a Redux store to drive drawing on a canvas as the UI:

*

*A Functional Canvas Approach with Redux, Part 1

*A Functional Canvas Approach with Redux, Part 2

A: I've chosen to store ImageData (getting it via context getImageData method) in Redux store. This keeps the store serializable and immutable. I face some troubles with performance though, because getImageData and putImageData are very slow, so I need to update ImageData in my store as rarely as possible.


text:
Q: How to center the text mesh in Three.js I am currently building a tool with Three.js.
I would like to put dots with corresponding numbers (dot count).
Below code is how I implemented. (Please teach me if there are better ways)
To align two meshes, I relocated them so that the text (number) can be inside the center of the dot. However, the problem is that the position of the text is based on meshes left side, not the center. So that if the numbers gain more digits, they wouldn't align as I expected.
Is there a better way to align text mesh so that they can be on the center of the circle?
var totalDotCount = 0;
function addDotMeshToGroup(x, y) { // x,y coordinate
  ...
  // Dot
  var geometry = new THREE.CircleGeometry(0.4, 32);
  var material = new THREE.MeshBasicMaterial({color: 0xFFFF00});
  var dotMesh = new THREE.Mesh(geometry, material)

  // Number Text
  var textGeo = new THREE.TextGeometry(totalDotCount.toString(10), textParm);
  var textMesh = new THREE.Mesh(textGeo, material);

  // Relocation
  dotMesh.position.set(x, y, 0);
  textMesh.position.set(x - 0.2, y - 0.2, 0);

  totalDotCount += 1;
  ...
}

Picture 01 [Expected]

Picture 02 [Unexpected]

A: In this specific case, modelling the circle and numbers as 3d-objects is probably a bit overkill. Instead, you can create a simple plane and add the circle and number to it using a texture. Textures can be created on the fly using a canvas-element, something like this:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

canvas.width = canvas.height = 256;

// draw/fill the circle
ctx.beginPath();
ctx.arc(128, 128, 128, 0, 2 * Math.PI);
ctx.fillStyle = 'yellow';
ctx.fill();

// draw the number
ctx.fillStyle = 'black';
ctx.font = '64px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('12', 128, 128);

// create mesh with texture
const mesh = new Mesh(
  new PlaneGeometry(1,1),
  new MeshBasicMaterial({transparent: true, map: new CanvasTexture(canvas)})
);


text:
Q: Why am I getting "NOAUTH Authentication required" with Spring Boot? I have a simple redis server running with a password. I want to talk with it from my spring boot app. I look here and see there is a spring.redis.password so my application-local.yml (running with -Dspring.profiles.active=local) looks like...
spring:
  redis:
    password: ...

but when I run I get

NOAUTH Authentication required

What am I missing? I can connect via node.js like...
import redis from "redis";

const client = redis.createClient({
 password: "..."
});

Additional Code
@Bean
LettuceConnectionFactory redisConnectionFactory(){
    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
    return new LettuceConnectionFactory(config);
}

@Bean
public RedisTemplate<String, Object> redisTemplate(){
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory());
    return template;
}

also tried...
@Bean
LettuceConnectionFactory redisConnectionFactory(){
    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
    if (redisPassword != null){
        config.setPassword(redisPassword);
    }
    return new LettuceConnectionFactory(config);
}

and this works but seems overly verbose given it is a standard property.

A: If you need less verbose configuration, you can remove RedisConnectionFactory bean from your configuration code and just inject the RedisConnectionFactory bean in your redisTemplate. redisConnectionFactory will be populated with properties from application.yml:
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}

In this case, Spring injects LettuceConnectionFactory by default.
The problem was here: new RedisStandaloneConfiguration(). If you look at the code of constructor you will see that empty password is created and there is no way to set it besides calling a setter.

Old answer: You need to fetch your data from application.yml through RedisProperties class. Try this:
@Bean
RedisConnectionFactory redisConnectionFactory(RedisProperties props) {
    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();

    config.setPassword(props.getPassword());

    return new LettuceConnectionFactory(config);
}

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}

Here props contains properties from spring.redis section

A: for me, problem because version of spring and redis (2.1.4), after upgrade newer version, it work normal
Please use with:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.9.RELEASE</version>
</parent>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.3.9.RELEASE</version>
</dependency>

I use redis sentinel and my properties is:
spring.redis.database=0
spring.redis.sentinel.master=
spring.redis.sentinel.nodes=
spring.redis.sentinel.password=
spring.redis.password=
spring.redis.timeout=60000


text:
Q: How to change ProgressIndicator to an icon when reaching a certain condition with javafx I have a separate class that initializes a bunch of progress indicator for my GUI
public class ProgressIndicators {
    private ProgressIndicator firstIndicator;
    private ProgressIndicator secondIndicator;
    private ProgressIndicator thirdIndicator;

    public void initalizeIndicators() {

        //Initialize indicators and set properties

    }

}

I have another class that performs some heavy backend calculations in another class
public class HeavyCalculations {

    private boolean isFinished;

    public HeavyCalculations() {
        isFinished = false;
        doHeavyCalculations()
    }

    public doHeavyCalculations() {
        // Do Heavy Calculations that may take up to ten minutes
        isFinished = true; // Set isFinished to true once heavy calculations are done
    }

}

Once the isFinished variable is set to true, I would like to remove one of the ProgressIndicator and change it to another icon. How would I go about accomplishing this?

A: Well, you know that if it reaches that line is finished, so you are in control, without the need of sharing any flag.
public doHeavyCalculations() {
    isFinished = true;
    removeProgressIndicator();
}

Simply implement the logic you need in order to know which ProgressIndicator you want to remove, and how to remove it, inside removeProgressIndicator() method.
If the HeavyCalculations class owns an instance of ProgressIndicators, it could be implemented in that class. Or without the need of an instance, by calling a static method.
For example, using an instance and with an int id param:
public doHeavyCalculations() {
    isFinished = true;
    indicatorInstance.removeProgressIndicator(1);
}

.
public class ProgressIndicators {
   private ProgressIndicator firstIndicator;
   private ProgressIndicator secondIndicator;
   private ProgressIndicator thirdIndicator;

   public void removeProgressIndicator(int id) {
      //remove logic
   }
 }

I would suggest storing the Indicators in a List, so you could retrieve/add/remove them easily.


text:
Q: Help on clarification of a formal statement concerning algorithms running time I am reading the following in a book on algorithms (Cormen's to be specific):

That is, we are concerned with how the running time of an algorithm
  increases with the size of the input in the limit, as the size of the
  input increases without bound.

I can not understand what is the meaning of the phrase:  with the size of the input in the limit.
What is the limit refering about?
UPDATE:
Please note that at this point in the book (early fundamentals of chapter 2) there has been no formal definition or mention of Big O or other asymptotic notation except a vague reference on Theta notation
Any help?

A: Look at the formal definition of Big O notation to see a limit defined within the notation there.  While Big O is specifically about worst case complexity there are other notations for average case or best case.
Usually the idea is to get an upper bound of how bad does the algorithm run.  Is the complexity logarithmic, linear, quadratic, or exponential?  There are various examples one can give for some of those as a binary search can have logarithmic complexity as one is reducing half the options with each search assuming the initial set of data is sorted.  Quadratic would be various poor sorting algorithms like Bubble Sort.

An alternative view here is to note that "the size of the input increases without bound" is generally a way of describing a limit as a variable tends to infinity.  Limits to Infinity would be an example discussing f(x) = 1/x where as x grows without bound, the function value will approach zero.  The key is to imagine the running time of the algorithm as a function depending on the size of the input and as one changes that input, how quickly is the function growing.  Is it a straight line or a curve?  How steep is the slope at any point?  That is kind of the point behind the idea here.

A: It means that as the size of the input increases infinitely, what is the running time in relation to the input. Big O can be used to measure any factor, including memory, but is usually time.


text:
Q: 'Reversed' comparison operator in Python class Inner():

    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        if isinstance(other, Inner):
            return self.x == other.x
        else:
            raise TypeError("Incorrect type to compare")

class Outer():

    def __init__(self, y):
        self.y = Inner(y)

    def __eq__(self, other):
        if isinstance(other, Outer):
            return self.y == other.y
        elif isinstance(other, Inner):
            return self.y == other
        else:
            raise TypeError("Incorrect type to compare")

if __name__ == "__main__":

    a = Outer(1)
    b = Inner(1)

    print(a == b) # ok no problem
    print(b == a) # This will raise a type error

In the example I have inner and outer class. I have no control over what Inner implements just wanted to simulate the situation. I have only control over Outer's behavior. I want Outer instances to be able to compare to Inner instances (not just equality). With the given implementation only the first comparison works because that is calling Outer's __eq__ method allowed to be compared to Outer and Inner instances but the second one is calling Inner's __eq__ which will not allow the comparison to Outer - heck it doesn't know Outer exists why should it bother to implement it.
Is there a way to get the second type of comparison to work, with something similar like the __radd__ and such functions.
I know for instance in C++ you resolve this with inline operator definitions, but we don't have such in Python.

A: Not to put too fine a point on it: Inner.__eq__ is broken. At the very least, rather than throwing an error it should return NotImplemented, which would allow Python to try the reverse comparison:

When NotImplemented is returned, the interpreter will then try the
  reflected operation on the other type, or some other fallback,
  depending on the operator. If all attempted operations return
  NotImplemented, the interpreter will raise an appropriate exception.

Better yet it would use "duck typing", rather than insisting on a specific class (unless the class, rather than its interface, is an explicitly important part of the comparison):
def __eq__(self, other):
    try:
        return self.x == other.x
    except AttributeError:
        return NotImplemented

However, as you say you cannot control this, you will have to manually implement similar functionality, for example:
def compare(a, b):
    """'Safe' comparison between two objects."""
    try:
        return a == b
    except TypeError:
        return b == a

as there is no such thing as __req__ in Python's data model.


text:
Q: Java Webapp Performance Issues I have a Web Application, Made entirely with Java. The Webapp doesn't use any Graphical / Model Framework, instead, the webapp uses The Model-View Controller. It's made only with Servlet specification (Servlet ver. 2.4).
The webapp it's developed since 2001, and it's very complex. Initially, was built for work with Tomcat 4.x/5.x. Actually, runs on Tomcat 6.x. But, we still having memory Leaks.
In Depth, the specifications of The Webapp can resumed as:

*

*Uses Servlet v. 2.4 Specification.

*It doesn't use Any Framework

*It doesn't use JavaEE (Not EJB)

*It's based on JavaSE (With Servlets)

*Works Only on IE 6+ (Because of it's age)

Infrastructure Specification
Actually, the webapp works in three environments:
First

*

*IBM Server (I don't remember exactly the model)

*Intel Xeon 2.4 Ghz

*32GB RAM

*1TB HDD

*Tomcat (Version 6) is configured to use 8GB of RAM

Second

*

*Dell Server

*Intel Xeon 2.0Ghz

*4GB RAM

*500GB HDD

*Tomcat (Version 5.5) is configured to use 1.5GB of RAM

Third

*

*Dell Server

*Amd Opteron 1214 2.20Ghz

*4GB RAM

*320GB HDD

*Tomcat (Version 6) is Configured to use 1.5GB of RAM

Database specification
The webapp uses SQL Server 2008 R2 Express Edition as a DBMS, except for the user of the first server-specification, that uses SQL Server 2008 R2 Standard Edition. For the connection pools, the app uses Apache DBCP.
Problem
Well, it has very serious performance issues. The webapp slow down continually, and, many times Denies the Service. The only way to recover the app is restarting The Apache Tomcat Service.
During a performance Audit, i've found several programming issues (Like database connections that never closes, excesive use of Vector collection [instead of ArrayList]).
I want to know how can improve the performance for the app, which applications can help me to monitoring the Tomcat performance and the Webapp Memory usage.
All suggestions are gladly accepted.

A: You could also try stagemonitor. It is an open source performance monitoring library. It records request response times, JVM metrics, request details including a call stack (profile) of the called methods during the request and more. Because of the low overhead, you can also use it in production.
The tuning procedure would be the following.

*

*Identify slow requests with the Request Dashboard

*Analyze the stack trace of the request with the Request Detail Dashboard to find out about slow methods

*Dive into your code and try to optimize those slow methods

*You can also correlate some metrics like the throughput or number of sessions with the response time or cpu usage

*Analyze the heap with the JVM Memory Dashboard
Note: I am the developer of stagemonitor.

A: I would start with some tools that can help you profiling the application. Since you are developing webapp start with Lambda Probe and Java melody.
The first step is to determine the conditions under which the app starts to behave oddly. Ask yourself few questions:

*

*Do performance issues arise right after applications starts, or overtime?

*Do performance issues are correlated to quantity of client requests?

*What is the real performance problem - high load on the server or lack of memory (note that they are related, so check which one starts first)

*Are there any background processes which are performing some massive operations? Are they scheduled to run at some particular time period?

Try to find some clues before going deep into code. It will help you to narrow down possible causes.
As Joshua Bloch has stated in his book entitled "Effective Java" - performance issues are rarely the effect of some minor mistakes in source code (although, of course, misuse of Java constructs can lead to disaster). Usually the cause is bad system (API) architecture.
The last suggestion based on my experience - try not to think that high memory consumption is something bad. Tomcat will use as much memory as operating system and JVM will let him (not more than max settings) and just when it needs more - Tomcat will perform garbage collection. So a typical (proper!) graph of memory consumption looks like a saw. If you are dealing with memory leak, then the graph will be increasing constantly, but indefinitely. This is the most often misunderstood of memory leaks, so keep it in mind.
To be honest - we cannot help you much further. Those are just pointers, now you will have to make extensive research to figure out the cause :)

A: The general solution is to use a profiler e.g. YourKit, with a realistic workload which reproduces the problem.
What I do first is a CPU only profile, a memory only profile and finally a CPU & Memory profile on at once (I then look at the CPU profile results)
YourKit can also monitor your high level operations such a Java EE resources and JDBC connections. I haven't tried these as I don't use them. ;)
It can be a good idea to improve the efficiency even if its not the cause of the problem as it will reduce the amount of "noise" in these profiles and make your issues more obvious.
You could try increasing the amount of memory available but a suspect it will just delay the problem.

A: Ok. So I have seen huge Java applications run lesser configurations. You should try to do the following -

*

*First connect a Profiler to your application and see which part of your application takes the most time. You can use JProfiler or Eclipse MAT ( I personally prefer JProfiler). Also try to take a look at the objects taking the most memory. This will help you narrow down to the parts which you need to rewrite to improve the performance.

*Once you have taken a look at the memory leaks update your application to use 64bit JDK(assuming it already does not do so)

*Take a look at your JVM arguments and optimize them.

A: You can try the open source tool Webapp Watcher in order to identify where in the code is the performance issue.
You have first to add a filter in the webapp (as explained here) in order to record metrics, and then import the logs in the WAW Analyzer tool and follow the steps described in the doc to know where is the potential performance issue in the code.


text:
Q: N different normal distributions - probability A is largest Following on from this question, I now have a harder version I need to solve. If we have N numbers selected from N normal distributions, each with its own mean and variance, what is the probability that a particular number is the largest. So for example we choose $A,B,C$ and $D$ from distributions with means $M_a,M_b,M_c,$ and $M_d$ and variances $V_a,V_b,V_c$ and $V_d$, then what is the probability that:
$$A > \max\{B,C,D\}$$

A: Thank you Ian for pointing out my mistake (independence issues). I've got ANOTHER answer and some code for you. I tested it out properly with R via Monte Carlo simulation. I'll provide the R code and the Mathematica code. I used Mathematica to numerically evaluate the integral I derive below.
So let's say we have $N$ distributions, and each $X_i$ is distributed according to the $i^{th}$ distribution. Let's assume without loss of generality that we are interested in $P(X_1 \ge \max_i X_i)$. I'm going to be a little loose with the notation, but I think it'll be clear.
$$\begin{align}
P(X_1 \ge \max_i X_i) &= P(X_1 \ge X_2, X_1 \ge X_3, \ldots, X_1 \ge X_N)\\
&= \int_{-\infty}^\infty P(X_1 \ge X_2, X_1 \ge X_3, \ldots, X_1 \ge X_N, X_1 = x) dx\\
&= \int_{-\infty}^\infty P(X_1 \ge X_2, X_1 \ge X_3, \ldots, X_1 \ge X_N| X_1 = x) f_{X_1}(x) dx\\
&= \int_{-\infty}^\infty P(X_1 \ge X_2, X_1 \ge X_3, \ldots, X_1 \ge X_N| X_1 = x) f_{X_1}(x) dx\\
&= \int_{-\infty}^\infty P(X_1 \ge X_2|X_1)P(X_1 \ge X_3|X_1)\ldots P(X_1 \ge X_N| X_1 = x) f_{X_1}(x) dx\\
&= \int_{-\infty}^\infty f_{X_1}(x) \prod_{i=2}^N F_{X_i}(x) dx\\
\end{align}$$
where $f$ denotes the PDF and $F$ is the CDF. At this point, it's reasonable to evaluate the integral numerically.
Here is some Mathematica code to show an example of how to evaluate the above expression. Say

*

*$X_1$ ~ N(1,2)

*$X_2$ ~ N(0,1)

*$X_3$ ~ N(2,1)

*$X_4$ ~ N(1.5,3)

Then to get $P(X_1 \ge \max_i X_i)$ we just run the following in Mathematica
NIntegrate[
 CDF[NormalDistribution[0, 1], x]*CDF[NormalDistribution[2, 1], x]*
  CDF[NormalDistribution[1.5, 3], x]*
  PDF[NormalDistribution[1, 2], x], {x, -Infinity, Infinity}]

We can get answer of 0.216147.
Now let's check our answer with R. Here's code for running a Monte Carlo simulation. Note that it took me around 2 minutes to run.
x1 = rnorm(10^8, 1, 2)
x2 = rnorm(10^8, 0, 1)
x3 = rnorm(10^8, 2, 1)
x4 = rnorm(10^8, 1.5, 3)
indicators = ifelse(x1 >= pmax(x2, x3, x4), 1, 0)
mean(indicators)

I just ran it and I got 0.2161365, which is pretty close to what we expect. I tried different numbers of variables and different distributions, and it always worked. Hopefully I understood your problem correctly and this helps you.

A: If you want to do it with numerical integration, that's straightforward enough. The joint pdf is
$$f(x_1,\dots,x_N)=\prod_{i=1}^N \frac{1}{\sqrt{2 \pi \sigma_i}} e^{-\frac{(x_i-\mu_i)^2}{2\sigma_i^2}}.$$
Now supposing you want $X_1$ to be the biggest, then you just integrate over the region $x_1>x_2,x_1>x_3,\dots,x_1>x_N$. This is
$$\int_{-\infty}^\infty \int_{-\infty}^\infty \dots \int_{\max \{ x_2,\dots,x_N \}}^\infty f(x_1,\dots,x_N) dx_1 dx_2 \dots dx_N.$$
However, I will warn that if $N$ is even slightly large (say, 10), this integral will probably be faster to compute by Monte Carlo integration than by direct integration. This is a manifestation of the "curse of dimensionality". If you really want to use direct integration, one approach would be Gauss-Hermite quadrature: given the $m$ nodes $x_j$ and $m$ weights $w_j$ for one dimensional Gauss-Hermite quadrature (meaning that $\sum_{j=1}^m w_j f(y_j) \approx \int_{-\infty}^\infty \frac{1}{\sqrt{2 \pi}} f(x) e^{-x^2/2} dx$), your integral can be approximated as
$$\sum_{i_1=1}^m w_{i_1} \sum_{i_2=1}^m w_{i_2} \dots \sum_{i_N=1}^m w_{i_N} f(\mu_1+\sigma_1 x_{i_1},\mu_2+\sigma_2 x_{i_2},\dots,\mu_N+\sigma_N x_{i_N})$$
where $f(x_1,\dots,x_N)=1$ if $x_1=\max x_i$ and $0$ otherwise. Since this function is discontinuous, the convergence rate will probably be just decent, not great. Moreover, as you can see you will need $m^N$ evaluations to use this rule at all, which is large when $N$ is large even if $m$ is just $2$.

A: To ask for $p_{A} = P(A > max(B,~C,~D))$ is equivalent to ask for $P(A > B~ \land ~A > C~ \land ~A > D)$.

Edit: I think my initial answer was wrong, so I reworked on it, without being able to show a final solution yet.
$P(A > B~ \land ~A > C~ \land ~A > D) = P(A > B) \cdot P( A > C~ \land ~A > D|A > B) = P(A > B) \cdot P(A > C|A > B) \cdot P(A > D|A > B, A>C)$.

A: Let us say the $A$ we are looking for is $A_k$ and we want to see if it is largest in the set $\{A_1,\cdots,A_n\}$. My initial thought is to fix $A_k$ and then calculate the probability that none of the other $A_i$ is pairwise larger and then use complementary probability:
$$P\left(\max_i A_i\leq A_k| A_k\right) =1-\prod_{\forall i \neq k} P\left(A_i\leq A_k\right)$$
Then what would be needed is to sum or integrate over all $A_k$:
$$P\left(\max_i A_i \leq A_k\right) = \sum_{\forall A_k} P\left(\max_i A_i \leq A_k|A_k\right)\cdot P(A_k)$$
If you have a table for normal distribution function, this becomes easy, just the product of a series of table lookups ( maybe you want interpolation in between table entries ). You will need to calculate which entry of the table to check for each $A_i$ but it will be a a really nice function of its mean and variance. This will be nice to express with vectors too, in case you want to try it in a computational language like R or Matlab or Python or Octave.


text:
Q: Does VSCode have a different view in mac and in windows? I am beginner programmer and have just installed VSCode. But to way VSCode looks in the tutorials is different from the one I have.
I mean the Left most and the Topmost looks different.
So I cant flow the tutorial and almost all tutorials has the same look.
The links of the sreenshots are down below:

Is my version older or it looks like that on windows or anything else, please explain step-by-step cause I am new to this. Thanks a lot!
Sorry if it is a bad Question!

A: You installed Visual Studio which is a more powerful IDE from Microsoft. Don't confuse it with the editor Visual Studio Code.
There is an answer explaining the main differences between the environments: https://stackoverflow.com/a/33798601/10770079

Visual Studio (full version) is a "full-featured" and "convenient" development environment.
Visual Studio (free "Express" versions - only until 2017) are feature-centered and simplified versions of the full version. Feature-centered meaning that there are different versions (Visual Studio Web Developer, Visual Studio C#, etc.) depending on your goal.
Visual Studio (free Community edition - since 2015) is a simplified version of the full version and replaces the separated express editions used before 2015.
Visual Studio Code (VSCode) is a cross-platform (Linux, Mac OS, Windows) editor that can be extended with plugins to your needs.

A: You downloaded Visual Studio the IDE.
Visual Studio Code is a pseudo-IDE style text editor.
Be sure you look up specifically Visual Studio Code Download for [ insert operating system here ].


text:
Q: Input to reshape doesn't match requested shape I know others have posted similar questions already, but I couldn't find a solution that was appropriate here.
I've written a custom keras layer to average outputs from DistilBert based on a mask. That is, I have dim=[batch_size, n_tokens_out, 768] coming in, mask along n_tokens_out based on a mask that is dim=[batch_size, n_tokens_out]. The output should be dim=[batch_size, 768]. Here's the code for the layer:
class CustomPool(tf.keras.layers.Layer):
    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        super(CustomPool, self).__init__(**kwargs)

    def call(self, x, mask):
        masked = tf.cast(tf.boolean_mask(x, mask = mask, axis = 0), tf.float32)
        mn = tf.reduce_mean(masked, axis = 1, keepdims=True)
        return tf.reshape(mn, (tf.shape(x)[0], self.output_dim))

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

The model compiles without error, but as soon as the training starts I get this error:
InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument:  Input to reshape is a tensor with 967 values, but the requested shape has 12288
     [[node pooled_distilBert/CustomPooling/Reshape (defined at <ipython-input-245-a498c2817fb9>:13) ]]
     [[assert_greater_equal/Assert/AssertGuard/pivot_f/_3/_233]]
  (1) Invalid argument:  Input to reshape is a tensor with 967 values, but the requested shape has 12288
     [[node pooled_distilBert/CustomPooling/Reshape (defined at <ipython-input-245-a498c2817fb9>:13) ]]
0 successful operations.
0 derived errors ignored. [Op:__inference_train_function_211523]

Errors may have originated from an input operation.
Input Source operations connected to node pooled_distilBert/CustomPooling/Reshape:
 pooled_distilBert/CustomPooling/Mean (defined at <ipython-input-245-a498c2817fb9>:11)

Input Source operations connected to node pooled_distilBert/CustomPooling/Reshape:
 pooled_distilBert/CustomPooling/Mean (defined at <ipython-input-245-a498c2817fb9>:11)

The dimensions I get back are smaller than the expected dimensions, which is strange to me.
Here is what the model looks like (TFDistilBertModel is from the huggingface transformers library):
dbert_layer = TFDistilBertModel.from_pretrained('distilbert-base-uncased')

in_id = tf.keras.layers.Input(shape=(seq_max_length,), dtype='int32', name="input_ids")
in_mask = tf.keras.layers.Input(shape=(seq_max_length,), dtype='int32', name="input_masks")

dbert_inputs = [in_id, in_mask]
dbert_output = dbert_layer(dbert_inputs)[0]
x = CustomPool(output_dim = dbert_output.shape[2], name='CustomPooling')(dbert_output, in_mask)
dense1 = tf.keras.layers.Dense(256, activation = 'relu', name='dense256')(x)
pred = tf.keras.layers.Dense(n_classes, activation='softmax', name='MODEL_OUT')(dense1)

model = tf.keras.models.Model(inputs = dbert_inputs, outputs = pred, name='pooled_distilBert')

Any help here would be greatly appreciated as I had a look through existing questions, most end up being solved by specifying an input shape (not applicable in my case).

A: Using tf.reshape before a pooling layer
I know that my answer kinda late, but I want to share my solution to the problem. The thing is when you try to reshape a fixed size of a vector (tensor) during model training. The vector will change its input size and a fixed reshape like tf.reshape(updated_inputs, (shape = fixed_shape)) will trigger your problems, actually my problem :)) Hope it helps


text:
Q: how to calculate time for timer relay In the below circuit of Timer Relay, how I can calculate the time for C1 to be fully charged?
please don't use regulator, transistor or any other device I just want to use Resistance and want to calculate how much resistance required to charge the C1 for how much time?
If ohms law(E=IR) is suitable than what is the relation of (I) with C1?

A: Capacitor resistor charge time: -

If the applied voltage is 12V the capacitor charges to 63.2% of 12V in a time equal to capacitance in farads x resistance in ohms. In twice this time it gets another 63.2% closer to 12V i.e. 86.5%. Each duration of time equal to CR it gets another 63.2% closer. See below: -

how I can calculate the time for C1 to be fully charged?

Theoretically a capacitor never gets to 12V but, for practical purposes it gets to over 99% charge after 5 x CR.
As for the circuit in the question, it appears to be using a 555 timer chip and the relevant point at which this activates the chip is not to be confused with "fully charged". Read the data on the 555 to determine what that point in time is.

A: The circuit you've shown is that of a 555 timer wired as a monostable multivibrator and if S1 is pressed and released, pin 3 will go high as soon as S1 is made and will turn the relay ON for:
$$  \text {T} = 1.1 \times{R1}\times{C1}\ \text {seconds.}$$
However, if S1 is pressed for longer than T, and then released, U1 won't time out at all; it'll just follow S1.
So, assuming that S1 will be released before U1 times out, and that your criterion for "fully charged" is specific to your question and is how long it takes to charge up C1 through R1 until it gets to the voltage required to de-energize the relay, you have your answer.
On a more general note, if you have a circuit like this:

then the time for Vt to rise to any voltage between GND (0V) and V when S1 is made, and held made, can be determined by:
$$ \text{T} = kRC \ \text{seconds,} $$
where
$$ k = l_{n}\  \frac{V}{V - Vt} $$
and \$ l_{n}\$ is the natural logarithm.
For example, let's say we have a circuit where V is 10 volts, C is 1 microfarad, and we want to find the resistance which will cause Vt to rise from zero volts to one volt in one second.
In that case we first solve for k:
$$ k = l_{n}\  \frac{V}{V - Vt} = l_{n}\  \frac{10V}{9V} = 0.105 $$
Then, since
$$ \text{T} = kRC \ \text{seconds,} $$
we can rearrange and solve for R like this:
$$ \text{R} = \frac{T}{kC} = \frac{1s}{0.105 \times 1\cdot10^{-6}\mu F} =\ 952k\Omega $$

A: When wired in a monostable configuration, as in the question, the output of the 555 goes high when the trigger input goes low (more precisely, below 1/3 of the supply voltage); and T seconds later, when the threshold voltage reaches 2/3 of the supply voltage the output goes back to zero.  But why 1/3 V and 2/3 V? Because of the way the 555 in constructed.  (We'll deal with the time delay T later.)
Here is a block diagram of the 555 configured as a monostable:

Note the three resistors to the left of the two comparators.  Each of them are 5K, and the three in series form a voltage divider divide the supply voltage in thirds, so a voltage of 2/3V goes to the - terminal of the top comparator, and 1/3V goes to the + terminal of the bottom comparator.
A little trivia: the name of the chip -- 555 -- comes from these three 5K resistors.
The threshold input level is normally high (greater than 2/3 V) for a 555 in this configuration so the top comparator is on because the voltage on the + input (threshold) is greater then the voltage on the - input (2/3 V), keeping the RS flip-flop reset.  Transistor T1 is turned on, keeping the capacitor C discharged.
Note the in this monostable configuration, the trigger input and threshold input are tied together.
When the trigger goes low (below 1/3 V), the top comparator will turn off, and the bottom comparator will turn on since the voltage on the + terminal (1/3 V) is more then the voltage on the trigger input, and the flip-flop will be set.  This will cause the output to go high.
T1 is now turned off, so capacitor C begins to charge up through resistor R.  Once the threshold voltage reaches 2/3 V, the top comparator is turned on, causing the flip-flop to reset again, the output to go to zero, and the capacitor to discharge since T1 is turned back on.

What about the voltage levels across the middle resistor, from 1/3V to 2/3V?  If the inputs on the trigger/threshold pins fall in-between the two voltages, nothing happens.  This provides hysteresis so the flip-flop doesn't change rapidly when the inputs are near their thresholds.  In fact, sometimes the 555 is employed as a Schmitt trigger just because of the way it is constructed.
The time constant that governs how long the delay (i.e how long it takes the capacitor to charge up to 2/3 V, is
$$T=1.1\space RC \space\space seconds$$
This very similar to the standard equation for an typical RC delay, but there is an extra factor of 1.1 in the equation.  Where did the 1.1 come from?
The current through RC connected in series is:
$$i = ( \frac{V}{R} ) \space e^{-(\frac{T}{RC})}$$
The voltage change of the both edges of resistor (R) is demanded by the following formula.
$$iR = V e^{-(\frac{T}{RC})}$$
The time when the voltage of the both edges of capacitor (C) becomes 2/3 of power supply voltage (V) is time out period. That is, it is when the voltage across resistor becomes 1/3 of power supply voltage, since the resistor and capacitor are connected in series between Vcc and ground.
Replacing \$iR\$ by \$V\$, and dividing by 3 because want 1/3 of the voltage, we have:
$$\frac{V}{3} = V e^{-(\frac{T}{RC})}$$
Dividing both sides by \$V\$, then taking the natural logarithm and rearranging a little, we have::
$$T = -RC\space ln (\frac{1}{3})$$
so: $$T = 1.1\space RC$$
Actually my calculator gives -1.09861 for \$ln (\frac{1}{3})\$ but -1.1 is close enough.


text:
Q: How to combined html with c++ I am pretty new to both html and c++ with a´lot of knowledge in c#, I have just writen my first 100% own c++ program a little banking system and need a litte help on how to integrate html.
For example how would i dispaly the funds in html?
IDE Clion.
    int press;
    int newFunds;
    cout << "Available funds ";
    cout << funds;
    cout << "$ \n";
    cout << "Press 1 for Withdraw \n";
    cout << "Press 2 for Deposit \n";
    cin >> press;
    if(press == 1) {
        cout << "Amount";
        cin >> withdraw;
        funds -= withdraw;
        newFunds += withdraw;
        if(funds < 0) {
            funds += newFunds;
            cout << "Not enough funds!";
        }
        else {
            cout << "Remaining funds ", cout << funds, cout << "$ \n";
        }
    }
    else if(press == 2) {
        cout << "Amount\n";
        cin >> deposit;
        funds += deposit;
        cout << "Funds ";
        cout << funds;
        cout << "$";
    }
    if(press > 2) {
        cout << "Invalid";
    }
    return 0;
}

I welcome any suggestion!
I have tried to look up som tut but they wherent so good!

A: C++ and HTML can't connect just by creating a localhost web server. To make a "connection" between them, you'll need a C++ API to interact with the server and your C++ program. FastCGI protocol is simple and easy for beginners, but maybe not be the best option for more professional projects. Check information about FastCGI++ that's an API for C++. Here is a useful GitHub link that I recommend to start: https://github.com/eddic/fastcgipp.


text:
Q: sending variable,which is read by arduino, to php script(electronic toll collection system) I am building electronic toll colection system using arduino which rfid based;i want to send the "unique id" of the tag(read by arduino) to php script(stored on local apache server root folder).i have written the code please point out the mistakes and also have a look on the ethernet settings whether they are correct in the program..
#include <SPI.h>
#include <Ethernet.h>
EthernetServer server(80);
byte mac[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
IPAddress ip(192,168,1,4);
EthernetClient client;
int  val = 0;
char code[10];
int bytesread = 0;
void setup()
{
Ethernet.begin(mac, ip, gateway, subnet);
Serial.begin(9600);
pinMode(2,OUTPUT);
digitalWrite(2, HIGH);
}

 void loop()

{
 if(Serial.available() > 0) {
    if((val = Serial.read()) == 10) {
      bytesread = 0;
      while(bytesread<10) {
        if( Serial.available() > 0) {
          val = Serial.read();
          if((val == 10)||(val == 13)) {
            break;
          }
          code[bytesread] = val;
          bytesread++;
        }
      }
      if(bytesread == 10) {
       client.print("GET try.php?code=");
      client.print(code);

client.println(" HTTP/1.1");
client.println("Host: localhost");
client.println();
      }
      bytesread = 0;

      digitalWrite(2, LOW);
           delay(1500);
           digitalWrite(2, HIGH);                  // Activate the RFID reader
    }
  }
}
the php script:

<?php
$variable = $_GET['code']
echo  "code is  $variable ";
?>

A: you forgot to connect your EthernetClient to the server! Take a look at the Arduino documentation.
if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("GET /search?q=arduino HTTP/1.0");
    client.println();
} else {
    Serial.println("connection failed");
}

In your example you have to write:
Serial.println("connected");
client.print("GET /try?code=");
client.print(code);
client.print(" HTTP/1.0");
client.println();

EDIT: Here's a complete example:
Replace
client.print("GET try.php?code=");
client.print(code);
client.println(" HTTP/1.1");
client.println("Host: localhost");
client.println();

with
if (client.connect(serverIP, 80)) {
    Serial.println("connected");
    client.print("GET /try?code=");
    client.print(code);
    client.print(" HTTP/1.0");
    client.println();
} else {
    Serial.println("connection failed");
}

and add this to the declarations
byte serverIP[] = { 127, 0, 0, 1 }; //That's localhost. Change it to whatever you need!

A: Seems you're missing a "client.connect(...)" to connect to your PHP server before sending it an HTTP request :
http://arduino.cc/en/Reference/EthernetClient


text:
Q: Django MultiValueDictKeyError Passing input type file I am getting this error when I am trying to pass the value of the folder to another html.

I have stored the form in a database in DB Browser Sqlite. I am trying to pass the input type = file to another HTML. So that when I view the existing type = file, the file will automatically be shown.

Below is an attachment from submitclaim.html
 <form action="/newclaim/" method="post" enctype="multipart/form-data">
    <label for="receipt">Receipt:  </label> <br>
    <input id="receipt" type="file" name="receipt_field">
</form>

This is my verfiyexistingclaims.html
 <form method="POST" action="/verifyexistingclaims/{{claims.id}}" enctype="multipart/form-data">
    <label for="receipt">Receipt: </label>
    <input id="receipt" type="file" name="receipt" value={{claims.receipt}}>
</form>

This is my views.py
def financeverifyclaims(request, id):
    context = initialize_context(request)
    user = context["user"]

    # get original object
    claims = SaveClaimForm.objects.get(id=id)

    if request.method == "POST":

        # update original object

        claims.receipt = request.FILES["receipt"]

        # save it with original `ID`
        claims.save()

    return render(
        request, "Login/verifyexistingclaims.html", {"claims": claims, "user": user}
    )

Models.py
from django.db import models
from django.core.validators import FileExtensionValidator

# Create your models here.
class SaveClaimForm(models.Model):

    receipt = models.FileField(upload_to='receipts/%Y/%m/%D', validators=[FileExtensionValidator(allowed_extensions=['jpg','png'])])

A: You should provide a default value in case it does not exist, i.e.:
claims.receipt = request.FILES.get('receipt', False)


text:
Q: How to translate Tiff.ReadEncodedTile to elevation terrain matrix from height map in C#? I'm new with working with reading tiff images and I'm trying to get the elevation terrain values from a tiff map by using LibTiff. The maps I need to decode are tile organized. Below the fragment of the code I'm using currently to get these values, based on the library documentation and research on the web:
    private void getBytes()
    {
        int numBytes = bitsPerSample / 8;           //Number of bytes depending the tiff map
        int stride = numBytes * height;
        byte[] bufferTiff = new byte[stride * height];  // this is the buffer with the tiles data

        int offset = 0;

        for (int i = 0; i < tif.NumberOfTiles() - 1; i++)
        {
            int rawTileSize = (int)tif.RawTileSize(i);
            offset += tif.ReadEncodedTile(i, bufferTiff, offset, rawTileSize);

        }

        values = new double[height, width];         // this is the matrix to save the heigth values in meters

        int ptr = 0;                    // pointer for saving the each data bytes
        int m = 0;
        int n = 0;

        byte[] byteValues = new byte[numBytes];     // bytes of each height data

        for (int i = 0; i < bufferTiff.Length; i++)
        {
            byteValues[ptr] = bufferTiff[i];

            ptr++;
            if (ptr % numBytes == 0)
            {
                ptr = 0;

                    if (n == height) // tiff map Y pixels
                    {
                        n = 0;
                        m++;
                        if (m == width) // tiff map X pixels
                        {
                            m = 0;
                        }
                    }

                    values[m, n] = BitConverter.ToDouble(byteValues, 0);    // Converts each byte data to the height value in meters. If the map is 32 bps the method I use is BitConverter.ToFloat

                    if (n == height - 1 && m == width - 1)
                        break;
                    n++;

            }
        }
        SaveArrayAsCSV(values, "values.txt");
    }

    //Only to show results in a cvs file:
    public void SaveArrayAsCSV(double[,] arrayToSave, string fileName)  // source: http://stackoverflow.com/questions/8666518/how-can-i-write-a-general-array-to-csv-file
    {
        using (StreamWriter file = new StreamWriter(fileName))
        {
            WriteItemsToFile(arrayToSave, file);
        }
    }

   //Only to show results in a cvs file:
    private void WriteItemsToFile(Array items, TextWriter file)     // source: http://stackoverflow.com/questions/8666518/how-can-i-write-a-general-array-to-csv-file
    {
        int cont = 0;
        foreach (object item in items)
        {
            if (item is Array)
            {
                WriteItemsToFile(item as Array, file);
                file.Write(Environment.NewLine);
            }
            else {
                file.Write(item + " | ");
                cont++;
                if(cont == width)
                {
                    file.Write("\n");
                    cont = 0;
                }
            }
        }
    }

I've been testing two different maps (32 and 64 bits per sample) and the results are similar: At the begining, the data seems to be consistent, but there is a point in which all the other values are corrupted (even zero at the end of data results). I deduce there are some bytes that need to be ignored, but I don't know how identify them to depurate my code. The method Tiff.ReadScanline does not work for me, because the maps I need to decode are tiles organized, and this method is not for working with these kind of images (according to BitMiracle.LibTiff documentation). The method Tiff.ReadRGBATile is not valid neither, because the tiff images are not RGB. I can read these values with Matlab, but my project needs to be built in C#, so I can compare the expected results with mine. As reference (I think it could be helpful), these are some data extracted from one of the tiff files with LibTiff tag reading methods:

*

*ImageWidth: 2001

*ImageLength: 2001

*BitsPerSample: 32

*Compression: PackBits (aka Macintosh RLE)

*Photometric: MinIsBlack

*SamplesPerPixel: 1

*PlanarConfig: Contig

*TileWidth: 208

*TileLength: 208

*SampleFormat: 3

Thanks in advance by your help guys!

A: Ok, Finally I found the solution: My mistake was the parameter "count" in the function Tiff.ReadEncodedTile(tile, buffer, offset, count). The Tiff.RawTileSize(int) function, returns the compressed bytes size of the tile (different for each tile, depending of the compression algorithm), but Tiff.ReadEncodedTile returns the decompressed bytes (bigger and constant for all tiles). That's why not all the information was been saved properly, but just a part of data. Below the correct code with the terrain elevation matrix (need optimization but it works, I think it could be helpful)
 private void getBytes()
    {
        int numBytes = bitsPerSample / 8;
        int numTiles = tif.NumberOfTiles();
        int stride = numBytes * height;
        int bufferSize = tileWidth * tileHeight * numBytes * numTiles;
        int bytesSavedPerTile = tileWidth * tileHeight * numBytes; //this is the real size of the decompressed bytes
        byte[] bufferTiff = new byte[bufferSize];

        FieldValue[] value = tif.GetField(TiffTag.TILEWIDTH);
        int tilewidth = value[0].ToInt();

        value = tif.GetField(TiffTag.TILELENGTH);
        int tileHeigth = value[0].ToInt();

        int matrixSide = (int)Math.Sqrt(numTiles); // this works for a square image (for example a tiles organized tiff image)
        int bytesWidth = matrixSide * tilewidth;
        int bytesHeigth = matrixSide * tileHeigth;

        int offset = 0;

        for (int j = 0; j < numTiles; j++)
        {
            offset += tif.ReadEncodedTile(j, bufferTiff, offset, bytesSavedPerTile); //Here was the mistake. Now it works!
        }

        double[,] aux = new double[bytesHeigth, bytesWidth]; //Double for a 64 bps tiff image. This matrix will save the alldata, including the transparency (the "blank zone" I was talking before)

        terrainElevation = new double[height, width]; // Double for a 64 bps tiff image. This matrix will save only the elevation values, without transparency

        int ptr = 0;
        int m = 0;
        int n = -1;
        int contNumTile = 1;
        int contBytesPerTile = 0;
        int i = 0;
        int tileHeigthReference = tileHeigth;
        int tileWidthReference = tileWidth;
        int row = 1;
        int col = 1;

        byte[] bytesHeigthMeters = new byte[numBytes]; // Buffer to save each one elevation value to parse

        while (i < bufferTiff.Length && contNumTile < numTiles + 1)
        {
            for (contBytesPerTile = 0; contBytesPerTile < bytesSavedPerTile; contBytesPerTile++)
            {
                bytesHeigthMeters[ptr] = bufferTiff[i];
                ptr++;
                if (ptr % numBytes == 0 && ptr != 0)
                {
                    ptr = 0;
                    n++;

                    if (n == tileHeigthReference)
                    {
                        n = tileHeigthReference - tileHeigth;
                        m++;
                        if (m == tileWidthReference)
                        {
                            m = tileWidthReference - tileWidth;
                        }
                    }
                    double heigthMeters = BitConverter.ToDouble(bytesHeigthMeters, 0);

                    if (n < bytesWidth)
                    {
                        aux[m, n] = heigthMeters;
                    }
                    else
                    {
                        n = -1;
                    }

                }
                i++;
            }

            if (i % tilewidth == 0)
            {
                col++;
                if (col == matrixSide + 1)
                {
                    col = 1;
                }
            }

            if (contNumTile % matrixSide == 0)
            {
                row++;
                n = -1;
                if (row == matrixSide + 1)
                {
                    row = 1;

                }
            }

            contNumTile++;
            tileHeigthReference = tileHeight * (col);
            tileWidthReference = tileWidth * (row);

            m = tileWidth * (row - 1);

        }

        for (int x = 0; x < height; x++)
        {
            for (int y = 0; y < width; y++)
            {
                terrainElevation[x, y] = aux[x, y]; // Final result. Each position of matrix has saved each pixel terrain elevation of the map
            }
        }

    }

Regards!

A: Here is an improved code, works with non-square tiles:
int imageWidth = tiff.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
                int imageHeight = tiff.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
                int bytesPerSample = (int)tiff.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt() / 8;
                SampleFormat format = (SampleFormat)tiff.GetField(TiffTag.SAMPLEFORMAT)[0].ToInt();

                //Array to return
                float[,] decoded = new float[imageHeight, imageWidth];

                //Get decode function (I only want a float array)
                Func<byte[], int, float> decode = GetConversionFunction(format, bytesPerSample);
                if (decode == null)
                {
                    throw new ArgumentException("Unsupported TIFF format:"+format);
                }

                if(tiff.IsTiled())
                {
                    //tile dimensions in pixels - the image dimensions MAY NOT be a multiple of these dimensions
                    int tileWidth = tiff.GetField(TiffTag.TILEWIDTH)[0].ToInt();
                    int tileHeight = tiff.GetField(TiffTag.TILELENGTH)[0].ToInt();

                    //tile matrix size
                    int numTiles = tiff.NumberOfTiles();
                    int tileMatrixWidth = (int)Math.Ceiling(imageWidth / (float)tileWidth);
                    int tileMatrixHeight = (int)Math.Ceiling(imageHeight / (float)tileHeight);

                    //tile dimensions in bytes
                    int tileBytesWidth = tileWidth * bytesPerSample;
                    int tileBytesHeight = tileHeight * bytesPerSample;

                    //tile buffer
                    int tileBufferSize = tiff.TileSize();
                    byte[] tileBuffer = new byte[tileBufferSize];

                    int imageHeightMinus1 = imageHeight - 1;

                    for (int tileIndex = 0 ; tileIndex < numTiles; tileIndex++)
                    {
                        int tileX = tileIndex / tileMatrixWidth;
                        int tileY = tileIndex % tileMatrixHeight;

                        tiff.ReadTile(tileBuffer, 0, tileX*tileWidth, tileY*tileHeight, 0, 0);

                        int xImageOffset = tileX * tileWidth;
                        int yImageOffset = tileY * tileHeight;

                        for (int col = 0; col < tileWidth && xImageOffset+col < imageWidth; col++ )
                        {
                            for(int row = 0; row < tileHeight && yImageOffset+row < imageHeight; row++)
                            {
                                decoded[imageHeightMinus1-(yImageOffset+row), xImageOffset+col] = decode(tileBuffer, row * tileBytesWidth + col * bytesPerSample);

                            }
                        }
                    }
                }


text:
Q: Backreference in RegExp replace function not working Below is my code for string replacing:
var input = "player @renish Score";
var matches = input.replace(/@\w*/g,'$1 55');

The output is
player $1 55 Score

I want the output like
player @renish 55 Score

A: The $1 is called a backreference and it will be valid only if there is a valid capturing group.
Quoting MDN's Grouping and back references section,

(x)
Matches x and remembers the match. These are called capturing parentheses.
For example, /(foo)/ matches and remembers "foo" in "foo bar". The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.
  You need to introduce a capturing group, like this

console.log(input.replace(/(@\w*)/g,'$1 55'));

Now, we capture the string @\w*, and the $1 will represent the captured string.

Alternatively, as per the ECMA Script 5.1 Specification for String.prototype.replace, you can use $& to represent the matched string.

$&
The matched substring.

So, you can use the code as it is and simply change the replacement pattern to $&, like this
console.log(input.replace(/@\w*/g,'$& 55'));

A: You'll need to specify what part of your regex is your capturing group, using ():

var input = "player @renish Score";
var matches = input.replace(/(@\w*)/g,'$1 55');
alert(matches)

Otherwise, the replace will literally place "$1" into your string, because you haven't specified a capturing group.

A: You need to reference the whole match with $& , no need in capturing groups:

var input = "player @renish Score";
alert(input.replace(/@\w*/g,'$& 55'));

See MDN reference:

$&    Inserts the matched substring.

Mind that adding capturing groups should only be performed when you only need to refer to some subpattern. Additional capturing groups mean additional overhead.


text:
Q: Given the VB.net code, combine multiple queries into 1 Given this code below which returns a first recordset (rs) based on a date range with some values that are then used in the second recordset (rs2) to sum up a cost.  Further explanation is below the code:
strSQL = "SELECT job, suffix, isnull(qty_scrapped,0),isnull(qty_released,0), isnull(price,0),co_num FROM vwDashboardsQuality "
strSQL &= "        WHERE trans_date >= '" & dtpStartDate.Value & "' AND trans_date <= '" & dtpEndDate.Value & "' "

rs = conn.Execute(strSQL)

While Not rs.EOF
    strCONUM = Trim("" & rs("co_num").Value)

    strSelectString = "SELECT ISNULL(a_cost,0) FROM jobmatl WHERE job='" & rs("job").Value & "' AND suffix = " & Format(rs("suffix").Value)

     rs2 = conn.Execute(strSelectString)
     While Not rs2.EOF
         dblSumActualMaterialCost = dblSumActualMaterialCost + CDbl(rs2(0).Value)
         rs2.MoveNext()
     End While
     rs2.Close()
     rs2 = Nothing
     rs.MoveNext()
End While
rs.Close()
rs = Nothing

I want to combine the queries into a single query so I am not hitting the database through the second recordset (rs2) just to sum up something that I know can be done in a single query.
Any tips would be helpful.  Thank you in advance.

A: It looks like you're just needing to do an inner join on the two queries to get one result set.
See if this works.  If so, you can eliminate the second query and second inner loop.
 strSQL = "SELECT d.job, d.suffix, isnull(d.qty_scrapped,0), isnull(d.qty_released,0)," _
 & " isnull(d.price,0), d.co_num, ISNULL(m.a_cost,0)" _
 & " FROM vwDashboardsQuality d" _
 & " INNER JOIN jobmatl m" _
 & " ON d.job = m.job" _
 & " AND d.suffix = m.suffix" _
 & " WHERE trans_date >= '" & dtpStartDate.Value & "'" _
 & " AND trans_date <= '" & dtpEndDate.Value & "'"

You can paste this in Management Studio, replacing dates as applicable to check the results.
SELECT d.job, d.suffix, isnull(d.qty_scrapped,0), isnull(d.qty_released,0), isnull(d.price,0), d.co_num,
    ISNULL(m.a_cost,0)
FROM vwDashboardsQuality d
    INNER JOIN jobmatl m
    ON d.job = m.job
    AND d.suffix = m.suffix
WHERE trans_date >= '2015-09-29'
    AND trans_date <= '2015-09-30'

A: From your code I see that you are at the end just running a SUM on all values for jobmatl.a_cost that fulfill a condition set by the where clause. So why not doing everything on the same query? And you will save yourself all the unnecessary iterations on the result set, you are loosing previous CPU time and resources there.
Also, you are not using all other values on the first query, why getting them on the first place? I removed them from the following query.
SELECT  SUM(j.a_cost)
FROM    vwDashboardsQuality vDQ
        INNER JOIN jobmatl j
            ON vDQ.job = j.job
               AND vDQ.suffix = j.suffix
WHERE   vDQ.trans_date >= @startdate
        AND vDQ.trans_date <= @enddate;


text:
Q: Question about os.environ.get : VSCode Debug Mode V.S. directly run with python I know the module os and how to use like os.environ.get('a', 'b'). It will catch current environment variable 'a', if not exists will default to 'b'.
But today I have a small problem. This is my tiny project about the problem:
.vscode/
    launch.json
.env
runme.py

For runme.py:
import os

vv = os.environ.get('SETTINGS', 'Nothing')

print(vv)

And also the .env file is quite simple like runme.py
SETTINGS = proj.settings.local

In launch.json, follow Python debugging configurations in VS Code
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/runme.py"
        }
    ]
}

After that, press F5, I see what I expect to see in INTERNAL TERMINAL
>cd d:\tmp\tt && cmd /C "set "SETTINGS=proj.settings.local" && set "PYTHONIOENCODING=UTF-8" && set "PYTHONUNBUFFERED=1" && python c:\Users\tony\.vscode\extensions\ms-python.python-2018.7.1\pythonFiles\PythonTools\visualstudio_py_launcher.py d:\tmp\tt 62502 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput D:\tmp\tt/runme.py "
proj.settings.local

But when I just run the command in COMMAND LINE python runme.py, I saw 'Nothing' printed in COMMAND LINE. WHY?
Is that IDE(ex: VSCode) do for me? Or something I misunderstand about the os module? Please explain it to me.

A: This seems to be a problem with VS Code. It seems that the way the .env file is evaluated and applied to a terminal is not very consistent and predictable.
During my test, the .env file only gets picked up, if you use the Debug function (shortcut F5 or Ctrl+F5). This results in the content of .env getting injected into the terminal session. Until you close that terminal, the variables you have defined there will be available for any consecutive runs of your program(s), if started from that terminal. Any new terminal you open (even if it is a new terminal inside VS Code) will not have access to these variables.
If you want an environment variable available at all times in a terminal, you can set that environment variable on the OS level. Under Windows, use System Properties / Environment Variables... and put it under User variables or System variables, depending on your needs. Under Linux, put it in your shells .rc file.
Please note that you have to restart VS Code for the change to take effect.


text:
Q: Classifying groups of order 399 and finding their centers and commutator subgroups Let $G$ be a group of order $399=3\cdot 7 \cdot 19$. By Sylow Theorems, we get that there is a unique Sylow 19-subgroup. If $N$ is that subgroup and $H$ is a Sylow 7-subgroup, it's easy to show $NH$ is normal in $G$. We must examine $\varphi: \mathbb{Z}_3 \to Aut(NH) \cong \mathbb{Z}_6\times \mathbb{Z}_{18}$. Let $\mathbb{Z}_3 = \langle s \rangle$, $N = \langle a \rangle$, and $H= \langle b \rangle$. Let $\varphi(s) = \sigma$. We must examine $\sigma(a,b)$ of order 3.
We know that $\sigma(a,b) = (a^k, b^l)$ such that $k^3 \equiv 1 \mod 7$ and $l^3\equiv  1 \mod 19$. If $k=l=1$, then $G\cong \mathbb{Z}_3\times \mathbb{Z}_7\times\mathbb{Z}_{19}$ and has obvious center/commutator subgroup. If $k,l \ne 1$ , after some work, one determines that $k=2,3$ and $l=7, 11$. This gives a total of 9 groups of order 399.
At this point, they each have their own presentation, but how does one then determine the center? Simply messing around with the relations? Also, I found a document that gives the number of groups of order $n\le 2015$, and it says there only 5 groups of order 399. Any hints on how to determine which of mine are isomorphic?

A: You found nine ways to map $\Bbb Z_3\to \operatorname{Aut}(NH)$. However, any two such homomorphism that differ only by an automorphims of $\Bbb Z_3$ lead to isomorphic groups. Thus instead of $1+8=9$ you get $1+\frac 82=5$.