text:
Q: How to find out, which screen is HEAD-0, HEAD-1, etc.? If I want to use the name of my primary screen (HDMI-0, found out via xrandr) within another command, the device is never found.
Instead I have to use the name HEAD-0. From what I've already read I assume this is probably a nVidia-thing, but I don't understand how it works, why it's done and most importantly:
How can I find out, which of my screens has which HEAD-name?

A: Not sure if it's the correct answer, but you can query connected displays via nvidia-settings --query dpys.
If I understand it correctly, HEAD-x is mapped to a display of the output of nvidia-settings in the order they appear. For example: HEAD-0 is the first connected display, HEAD-3 the fourth, etc.


text:
Q: Find the radius of the circle Consider this question: There are two Circles one with center C and other with center O, if the both the circles externally touch each other at one point and are tangent to the x axis, find out the radius of the circle that is tangent to both of them and also to the x axis. [given radius of big circle R1 and small circle R2]

Now I know there is a way to do using pure geometry(idk what it's called), but I want the solution to be using cartesian geometry
My attempt:
I took circle $S_1$ as $(y-R_1)^2 + x^2 - (R_1)^2 = 0$
$S_2$ as $(y-R_2)^2 + (x-2\sqrt{R1R2})^2 - (R_2)^2 = 0$
then since $S_3$ is tangent to Y axis. ($S_3$ is tangent to $y = 0$ at ($b,0$))
$\implies (x-b)^2 + y^2 + \lambda y = 0 \\
$
then I tried equating sum of radii and distance of cordinates by -
$(\lvert - \frac{\lambda}{2}\rvert + R_1)^2 = (b)^2 + (\lvert - \frac{\lambda}{2}\rvert - R_1)^2 \\
$
$(\lvert - \frac{\lambda}{2}\rvert + R_2)^2 = (b-2\sqrt{R1R2})^2 + (\lvert - \frac{\lambda}{2}\rvert - R_2)^2 \\
$
Then finding $\lambda$ and final radius becomes $\lvert \frac{\lambda}{2}\rvert $  But It's too messy, can someone post a more elegant solution to this using cartesian geometry only. Thanks!!

A: If $DG=r$, the same way ad you got the position of the circle with radius $R_2$ you can write $$AG^2=(R_1+r)^2-(R_1-r)^2=4R_1r\\GF^2=(R_2+r)^2-(R_2-r)^2=4R_2r$$
You also know that $$AF^2=(R_1+R_2)^2-(R_1-R_2)^2=4R_1R_2$$
So $$\sqrt{R_1R_2}=\sqrt r\left(\sqrt{R_1}+\sqrt{R_2}\right)$$
Therefore $$r=\frac{R_1R_2}{\left(\sqrt{R_1}+\sqrt{R_2}\right)^2}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: is it possible to use JPA repository and Ignite repository simultaneously? I want to use JPA repository and Ignite repository to CRUD the data.
Also, I want to connect the Ignite in-memory database with RDB (like mysql, mariaDB, postgresql, ..).
Is it possible to use JPA repository and Ignite repository simultaneously?
If it is possible, I hope to know how to make them.
Iginte respository means, Interface IgniteRepository.
For example,
@RepositoryConfig(cacheName = "DogCache")
public interface DogRepository extends IgniteRepository < Dog, Long > {
 List < Dog > getDogByName(String name);
 Dog getDogById(Long id);
}

A: Yes, it should work.
The important thing is cache name (in your case DogCache). Once you know Ignite cache name you can access it via any API, such as JPA, Spring Data, Cache API, SQL (if indexing is configured for that cache), REST, etc, etc.
If both JPA and Spring Data are configured to use the same cache, and they use same POJOs to access it, they should work together.
Of course, if either of those has things like 2nd level cache, they may go out of sync, but it will happen outside of Apache Ignite's zone of responsibility.
Please see blog post about Ignite JPA to understand how cache name maps to Repository.


text:
Q: If $f(0)=f(1)=f(2)=0$, $\forall x, \exists c, f(x)=\frac{1}{6}x(x-1)(x-2)f'''(c)$
Let $f:[0,2]\to \mathbb R$ be a $C^3$ function such that $f(0)=f(1)=f(2)=0$
Prove that $\forall x\in[0,2], \exists c\in[0,2], f(x)=\frac{1}{6}x(x-1)(x-2)f'''(c)$

This problem got me stuck. I guess one has to use the mean value theorem at some point.
Using Rolle, there exists $0<\xi_1<\eta<\xi_2$ such that $f'(\xi_1)=f'(\xi_2)=0$ and $f''(\eta)=0$.

A: Let $a \in [0, 2]$. We want to show that there exists a
$c\in[0,2]$ (depending on $a$) such that
$$ f(a)=a(a-1)(a-2) \, \frac{f'''(c)}{3!} \, .\tag 1$$
For $a = 0, 1, 2$ we can choose any $c$, so we assume $a \ne 0, 1, 2$
in the following. (The idea is to compare $f$ with a cubic polynomial
which interpolates $f$ at $0, 1, 2$ and at $a$.)
Define the function $g:[0,2]\to \mathbb R$ by
$$
g(x) = a(a-1)(a-2) \, f(x) - x(x-1)(x-2) \, f(a) \, .
$$
Then
$$
g'''(x) = a(a-1)(a-2) \, f'''(x) - 3! \, f(a) \tag 2
$$
and
$$
g(0) = g(1) = g(2) = g(a) = 0 \, .
$$
Repeated application of Rolle's theorem shows that there is
a $c\in[0,2]$ such that
$$
 g'''(c) = 0 \, .
$$
Now $(1)$ follows from setting  $x = c$ in $(2)$.


text:
Q: json.decoder.JSONDecodeError: Extra data: line 1 column 13 (char 12) I am running the following code, it is supposed to convert a JSON file containing hydrated tweets to CSV format.
import pandas as pd
import json

#Json file name
with open('climate.jsonl') as f:
    lines = f.read().splitlines()
print('jline opened')
df_inter = pd.DataFrame(lines)
df_inter.columns = ['json_element']

print('df_inter.columns')

df_inter['json_element'].apply(json.loads)

print('df_inter')

Twitter_Dataset = pd.json_normalize(df_inter['json_element'].apply(json.loads))

#Output CSV file
Twitter_Dataset.to_csv('Sandy_tweets_unfiltered.csv')
print('Unfiltered tweets have successfuly saved as CSV')

I have ran the same code on a few hydrated tweets dataset before and it executed with no problems. But, now I am getting  the following error:
Traceback (most recent call last):
  File "2-Json_to_CSV.py", line 15, in <module>
    df_inter['json_element'].apply(json.loads)
  File "/share/apps/miniconda3/installed_1/envs/sgupta5/lib/python3.7/site-packages/pandas/core/series.py", line 4200, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas/_libs/lib.pyx", line 2402, in pandas._libs.lib.map_infer
  File "/share/apps/miniconda3/installed_1/envs/sgupta5/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/share/apps/miniconda3/installed_1/envs/sgupta5/lib/python3.7/json/decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 13 (char 12)
srun: error: compute-20-9: task 0: Exited with exit code 1

A: You can get lines just withreadlines, no need for splitlines but if you are looking
to split the content in each link you can use line_content.split().
Note: You will have to remember to pass json.loads before  you can read the file.
#Json file name
with open('climate.jsonl') as f:
    line_content = [json.loads(line) for line in f.readlines()]


text:
Q: Line through a given point Could someone give a proof of "The line through a given point and parallel to a given line can be drawn".
I would be able to do this myself but I am so confused on the wording. As in what are we given initially? A point and a line or just a point?

A: You're given a line and a point, and you wish to draw a line through that given point parallel to the line that you were given.
This is known as Playfair's Axiom and is equivalent to the parallel postulate (also known as Euclid's fifth postulate). We can prove that these two are equivalent, but you cannot prove one by itself (many attempts in the past to prove just the parallel postulate have been made however).


text:
Q: Do I understand textureGather and textureQueryLod correctly? There is a piece of code in OpenGL SuperBible, 7th edition, Chapter 11, topic sparsetexture:
uniform sampler2D uCommittedLodTexture;
uniform sampler2D uSparseColorTexture;
vec4 sampleFromSparse(vec2 uv){
    vec4 availLod = textureGather(uCommittedLodTexture,uv);
    vec2 desireLod = textureQueryLod(uSparseColorTexture,uv);
    float maxAvailLod = max(max(availLod .x,availLod .y),max(availLod .z,availLod .w));
    float finalLod = max(desireLod.x,max(desireLod.y,maxAvailLod));
    return textureLod(uSparseColorTexture,uv,lod);// here I think it should be finalLod not lod
}

I cannot really get how does it work.
textureGather is a function that can return the four texels which would be used to do bilinear interpolation. The third parameter default value is zero which is x component of those chosen four texels.
But what is the functionality of textureQueryLod? Spec explains that:

The mipmap array(s) that would be accessed is returned in the x component of the return value. The computed level-of-detail relative to the base level is returned in the y component of the return value.

Does it mean that the x value of result is the mipmap level used at the point uv? How about the y component? Is it the offset from the base level of mipmap?
textureLod returns the texel in the specified mipmap level.
I don't know whether I understand these functions correctly and this piece of code is confusing. Could someone explain a little?

A: In the following line,
vec2 desireLod = textureQueryLod(uSparseColorTexture,uv);

desireLod.x is func(level-of-details) that shows how finally array(s) of map maps will be accessed, while desireLod.y is an computed "raw" level-of-details.
Pseudocode for the the result calculation for textureQueryLod can be found in the GLSL specification 8.9.1. Texture Query Functions.
The specification says about the computed level-of-details:

The level-of-detail (equation 3.18 of the
OpenGL Specification) is obtained after any level-of-detail bias, but prior to clamping to
[TEXTURE_MIN_LOD, TEXTURE_MAX_LOD].

while desireLod.x will be clamped by [TEXTURE_MIN_LOD, TEXTURE_MAX_LOD] and maxAccessibleLevel after the processing.


text:
Q: Cannot read property 'src' of null I'm trying to zoom images when I click on it. I use thymleaf as engine to display my images

This is the modal

  ×

This is the JS function that I use
function zoom(e) {
    var modal = document.querySelector("#img-zoom-modal");
    var img = document.querySelector('#img_' + e.target.id);
    var modalImg = document.querySelector('#modalImg');
    var captionText = document.querySelector('#img-zoom-caption');

    modal.style.display = "block";
    modalImg.src = img.src;    // THIS LINE RETURN ERROR  img is null
    captionText.innerHTML = img.alt;
    // Get the  element that closes the modal
    var span = document.getElementsByClassName("img-zoom-close")[0];

    modal.onclick = function() {
        modal.style.display = "none";
    }
    span.onclick = function() {
        modal.style.display = "none";
    }
}

When I click more times on different images I get this error:
Uncaught TypeError: Cannot read property 'src' of null in the line above modalImg.src = img.src
I'm inspired by this tutorial https://www.w3schools.com/howto/howto_css_modal_images.asp
Do you have any idea why I get this error ?


text:
Q: Manually typing in text in JavaFX Spinner is not updating the value (unless user presses ENTER) It seems that the Spinner control does not update a manually typed-in value until the user explicitly presses enter. So, they could type in a value (not press enter) exit the control, and submit the form, and the value displayed in the spinner is NOT the value of the Spinner, it is the old value.
My idea was to add a listener to the lost focus event, but I can't see a way to gain access to the typed-in value?
spinner.focusedProperty().addListener((observable, oldValue, newValue) ->
{
    //if focus lost
    if(!newValue)
    {
        //somehow get the text the user typed in?
    }
});

This is odd behavior, it seems to go against the convention of a GUI spinner control.

A: This is standard behavior for the control according to the documentation:

The editable property is used to specify whether user input is able to
  be typed into the Spinner editor. If editable is true, user input will
  be received once the user types and presses the Enter key. At this
  point the input is passed to the SpinnerValueFactory converter
  StringConverter.fromString(String) method. The returned value from
  this call (of type T) is then sent to the
  SpinnerValueFactory.setValue(Object) method. If the value is valid, it
  will remain as the value. If it is invalid, the value factory will
  need to react accordingly and back out this change.

Perhaps you could use a keyboard event to listen to and call the edit commit on the control as you go.

A: Unfortunately, Spinner doesn't behave as expected: in most OS, it should commit the edited value on focus lost. Even more unfortunate, it doesn't provide any configuration option to easily make it behave as expected.
So we have to manually commit the value in a listener to the focusedProperty. On the bright side, Spinner already has code doing so - it's private, though, we have to c&p it
/**
 * c&p from Spinner
 */
private <T> void commitEditorText(Spinner<T> spinner) {
    if (!spinner.isEditable()) return;
    String text = spinner.getEditor().getText();
    SpinnerValueFactory<T> valueFactory = spinner.getValueFactory();
    if (valueFactory != null) {
        StringConverter<T> converter = valueFactory.getConverter();
        if (converter != null) {
            T value = converter.fromString(text);
            valueFactory.setValue(value);
        }
    }
}

// useage in client code
spinner.focusedProperty().addListener((s, ov, nv) -> {
    if (nv) return;
    //intuitive method on textField, has no effect, though
    //spinner.getEditor().commitValue();
    commitEditorText(spinner);
});

Note that there's a method
textField.commitValue()

which I would have expected to ... well ... commit the value, which has no effect. It's (final!) implemented to update the value of the textFormatter if available. Doesn't work in the Spinner, even if you use a textFormatter for validation. Might be some internal listener missing or the spinner not yet updated to the relatively new api - didn't dig, though.

Update
While playing around a bit more with TextFormatter I noticed that a formatter guarantees to commit on focusLost:

The value is updated when the control loses its focus or it is commited (TextField only)

Which indeed works as documented such that we could add a listener to the formatter's valueProperty to get notified whenever the value is committed:
TextField field = new TextField();
TextFormatter fieldFormatter = new TextFormatter(
      TextFormatter.IDENTITY_STRING_CONVERTER, "initial");
field.setTextFormatter(fieldFormatter);
fieldFormatter.valueProperty().addListener((s, ov, nv) -> {
    // do stuff that needs to be done on commit
} );

Triggers for a commit:

*

*user hits ENTER

*control looses focus

*field.setText is called programmatically (this is undocumented behaviour!)

Coming back to the spinner: we can use this commit-on-focusLost behaviour of a formatter's value to force a commit on the spinnerFactory's value. Something like
// normal setup of spinner
SpinnerValueFactory factory = new IntegerSpinnerValueFactory(0, 10000, 0);
spinner.setValueFactory(factory);
spinner.setEditable(true);
// hook in a formatter with the same properties as the factory
TextFormatter formatter = new TextFormatter(factory.getConverter(), factory.getValue());
spinner.getEditor().setTextFormatter(formatter);
// bidi-bind the values
factory.valueProperty().bindBidirectional(formatter.valueProperty());

Note that editing (either typing or programmatically replacing/appending/pasting text) does not trigger a commit - so this cannot be used if commit-on-text-change is needed.

A: @kleopatra headed to a right direction, but the copy-paste solution feels awkward and the TextFormatter-based one did not work for me at all. So here's a shorter one, which forces Spinner to call it's private commitEditorText() as desired:

spinner.focusedProperty().addListener((observable, oldValue, newValue) -> {
  if (!newValue) {
    spinner.increment(0); // won't change value, but will commit editor
  }
});

A: Here is an improved variant of Sergio's solution.
The initialize method will attach Sergio's code to all Spinners in the controller.
public void initialize(URL location, ResourceBundle resources) {
    for (Field field : getClass().getDeclaredFields()) {
        try {
            Object obj = field.get(this);
            if (obj != null && obj instanceof Spinner)
                ((Spinner) obj).focusedProperty().addListener((observable, oldValue, newValue) -> {
                    if (!newValue) {
                        ((Spinner) obj).increment(0);
                    }
                });
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

A: Using a listener should work.  You can get access to the typed in value through the spinner's editor:
spinner.getEditor().getText();

A: I use an alternate approach - update it live while typing. This is my current implementation:
getEditor().textProperty().addListener { _, _, nv ->
    // let the user clear the field without complaining
    if(nv.isNotEmpty()) {
        Double newValue = getValue()
        try {
            newValue = getValueFactory().getConverter().fromString(nv)
        } catch (Exception e) { /* user typed an illegal character */ }
        getValueFactory().setValue(newValue)
    }

A: I used this approach
public class SpinnerFocusListener<T> implements ChangeListener<Boolean> {
   private Spinner<T> spinner;

   public SpinnerFocusListener(Spinner<T> spinner) {
       super();
       this.spinner = spinner;
       this.spinner.getEditor().focusedProperty().addListener(this);
   }

   @Override
   public void changed(ObservableValue<? extends Boolean> observable,
                           Boolean oldValue, Boolean newValue) {
        StringConverter<T>converter=spinner.getValueFactory().getConverter();
        TextField editor=spinner.getEditor();
        String text=editor.getText();
        try {
            T value=converter.fromString(text);
            spinner.getValueFactory().setValue(value);
        }catch(Throwable ex) {
            editor.setText(converter.toString(spinner.getValue()));
        }
    }
}


text:
Q: NSMutableURLRequest returns null on real device, while returning image on simulator I was testing my app that I've been working on for past 2 months. Basically it requests for JSON, that contains info about items. One field of JSON file is image_url. When I want to display this image, I need to download it from another server, that needs additional credentials.
So it goes like this-> In my cellForRowAtIndexPath I'm doing
NSDictionary *aucdict = [jsonAukResults objectAtIndex:indexPath.row];

NSURL *imageURL = [NSURL URLWithString:[aucdict objectForKey:@"img_url"]];

NSString *authPString = [[[NSString stringWithFormat:@"login:password"]dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString *verifPString = [NSString stringWithFormat:@"Image %@",authPString];
NSMutableURLRequest *Prequest = [[NSMutableURLRequest alloc] initWithURL:imageURL];
[Prequest setValue:verifPString forHTTPHeaderField:@"Authorization"];

NSError *error = nil;
NSURLResponse *resp = nil;
NSData *picresult = [NSURLConnection sendSynchronousRequest:Prequest returningResponse:&resp error:&error];

UIImage *imageLoad = [[UIImage alloc] initWithData:picresult];

Now, I just obscured credentials (they are not login:password :)).
My problem is, that right now, I get 3 items. All 3 have image on same server. I can get two of them with this code no problem. However third one is problematic, I always get (NULL) imageLoad. On my simulator, everything works fine, I get all 3 pictures. On real device I get error.
I tried to NSURLConnection with error and response so I could debug better. This is what I got in my error.
Printing description of error:

Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be "server name" which could put your confidential information at risk." UserInfo=0x1e5a3080 {NSErrorFailingURLStringKey=pictureLink.jpg, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSErrorFailingURLKey=pictureLink.jpg, NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be "server name" which could put your confidential information at risk., NSUnderlyingError=0x1e5a30e0 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be "server name" which could put your confidential information at risk.", NSURLErrorFailingURLPeerTrustErrorKey=}

I dont use SSL so Im really confused as what could cause this error.
Btw, everything worked fine until now (this is my initial screen, so it's been done for good month and a half). Now I started to do graphics and this problem popped up :(

A: My friend told me to try add "?" symbol at the end of URL. I don't understand why, but suddenly it works! Can anyone make it clear why it works? :) Thanks
NSMutableString *modURL = [NSMutableString stringWithString:[aucdict objectForKey:@"img_url"]];
    [modURL appendFormat:@"?"];
    NSURL *imageURL = [NSURL URLWithString:modURL];


text:
Q: Are system calls on Windows inherently slower than Linux? My understanding of system calls is that in Linux the system call mechanism (int 0x80 or whatever) is documented and guaranteed to be stable across different kernel versions. Using this information, the system calls are implemented directly in the CRT library, so that when I call e.g. printf("a"); this involves a single function call to the CRT, where the system call is set up and activated. In theory this can be improved further by statically compiling the CRT (not common on Linux, but a possibility) so that even the single function call may be inlined.
On the other hand, Windows does not document or even guarantee consistency of the system call mechanism. The only way to make a system call on Windows is to call into ntdll.dll (or maybe some other *.dll) which is done from the CRT, so there are two function calls involved. If the CRT is used statically and the function gets inlined (slightly more common on Windows than Linux) we still have the single function call into ntdll.dll that we can't get rid of.
So it seems to me that theoretically system calls on Windows will be inherently slower since they always have to do one function call more than their Linux equivalents. Is this understanding (and my explanation above) true?
Note: I am asking this purely theoretically. I understand that when doing a system call (which I think always involves 2 context switches - one in each direction) the cost of an extra function call is probably completely negligible.

A: On IA-32 there are two ways to make a system call:

*

*using int/iret instructions

*using sysenter/sysexit instructions

Pure int/iret based system call takes 211 CPU cycles (and even much more on modern processors). Sysenter/sysexit takes 46 CPU ticks. As you can see execution of only a pair of instructions used for system call introduces significant overhead. But any system call implementation involves some work on the kernel side (setup of kernel context, dispatching of the call and its arguments etc.). More or less realistic highly optimized system call will take ~250 and ~100 CPU cycles for int/iret and sysenter/sysexit based system calls respectively. In Linux and Windows it will take ~500 ticks.
In the same time, function call (based on call/ret) have a cost of 2-4 tics + 1 for each argument.
As you can see, overhead introduced by function call is negligible in comparision to the system call cost.
On other hand, if you embed raw system calls in your application, you will make it highly hardware dependent. For example, what if your application with embedded sysenter/sysexit based raw system call will be executed on old PC without these instructions support? In addition your application will be sensitive for system call call convention used by OS.
Such libraries like ntdll.dll and glibc are commonly used, because they provide well-known and hardware independent interface for the system services and hides details of the communication with kernel behind the scene.
Linux and Windows have approximately the same cost of system calls if use the same way of crossing the user/kernel space border (difference will be negligible). Both trying to use fastest way possible on each particular machine. All modern Windows versions starting at least from Windows XP are prepared for sysenter/sysexit. Some old and/or specific versions of Linux can still use int/iret based calls. x64 versions of OSes relies to syscall/sysret instructions which works like the sysenter/sysexit and available as part of AMD64 instructions set.


text:
Q: erraneous text in a LaTeX tabular array created using custom macros I have a tabular array that is based on David Carlisle's answer to
Generating LaTeX tabular code during compilation. I have modified the code so that columns and rows are defined in different \newcommand command definitions (practically lists). \regionlist contains brain regions {ABC,DEF,GHI} and \contrastlist contains 'contrasts' or activities {SLEEP,RUN,SPEAK}. These are defined in g_loc_contrast_tabular_def.tex. The data for the cells is defined in g_loc_contrast_def.tex using \def macro definitions, one for each data cell of the tabular array, excluding the top row and the left-most column.
So this particular array contains data on localized neural activity in different situations, the situations are on rows, brain regions on columns, and the data are defined by macros such as \def\locBABCcontrastSLEEP{both ABCs during sleep}. These definitions work fine.
I have added code to replace row headers with their descriptions that are defined in g_loc_contrast_def.tex using \def macros (\contrastdescSLEEP, \contrastdescRUN, \contrastdescSPEAK), but I have not been able to get the visual output right. On the leftmost column, I want "deep sleep" on the 1st data row (2nd row), "running marathon" on the 2nd data row (3rd row), and "speaking" (all with bold, without quotes), but I get LEEP deep sleep SSLEEP", "UN running marathon RRUN" and "PEAK speaking SSPEAK" (without quotes). The strings RUN, SLEEP and SPEAK are used in macro names, and when I finally found out a way to get the description in the array by using \textbf{\newcommand\contrastdesc#1{\csname contrastdesc#1\endcsname}
\contrastdesc#1}%, the first letter of the #1 string, that holds the row-code (SLEEP, RUN or SPEAK), was moved to the right side of the description string together with complete row-code string. So I'm trying to find out what is wrong with my LaTeX code to get the output right.
I'm total beginner in LaTeX macros, so it might be just some basic mistake. I have tried to find a solution and to understand LaTeX macro system, but I think I understand still only a tiny bit of it.
The code compiles without problems by using latexmk --pdf main.tex.
\documentclass[12pt]{article}

\usepackage[american]{babel}
\usepackage{graphicx}

\begin{filecontents}{g_loc_contrast_tabular_def}
\newcommand\regionlist{ABC,DEF,GHI}
\newcommand\contrastlist{SLEEP,RUN,SPEAK}

% listheadings.
\def\listheadings{%
\expandafter\xlistheadings\regionlist,\relax,}

% xlistheadings.
\def\xlistheadings#1,{%
\ifx\relax#1%
\expandafter\\\hline
\else
&\textbf{#1}%
\expandafter\xlistheadings
\fi}

% listbody.
\def\listbody{%
\expandafter\xlistbody\contrastlist,\relax,}

% xlistbody.
\def\xlistbody#1,{%
\ifx\relax#1%
\else
\textbf{\newcommand\contrastdesc#1{\csname contrastdesc#1\endcsname}
\contrastdesc#1}%
\gdef\thisrow{#1}
\expandafter\xlistdata\regionlist,\relax,%
\expandafter\hline
\expandafter\xlistbody
\fi}

% xlistdata.
\def\xlistdata#1,{%
\ifx\relax#1%
\expandafter\\
\else
&\csname locB#1contrast\thisrow\endcsname
\expandafter\xlistdata
\fi}

% preamble.
\def\preamble{\expandafter\xpreamble\regionlist,\relax,}
\def\xpreamble#1,{%
\ifx\relax#1%
\else
c%
\expandafter\xpreamble
\fi}

% tablestart.
\def\tablestart{%
\edef\temp{\noexpand\begin{tabular}{c\preamble}\noexpand\hline}%
    \temp}
\end{filecontents}

\begin{filecontents}{g_loc_contrast_def}
\def\locBABCcontrastSLEEP{ both ABCs during sleeping }
\def\locBABCcontrastRUN{ both ABCs during running }
\def\locBABCcontrastSPEAK{ both ABCs during speaking }

\def\locBDEFcontrastSLEEP{ both DEFs during sleeping }
\def\locBDEFcontrastRUN{ both DEFs during running }
\def\locBDEFcontrastSPEAK{ both DEFs during speaking }

\def\locBGHIcontrastSLEEP{ both GHIs during sleeping }
\def\locBGHIcontrastRUN{ both GHIs during running }
\def\locBGHIcontrastSPEAK{ both GHIs during speaking }

\def\contrastdescSLEEP{ deep sleep }
\def\contrastdescRUN{ running marathon }
\def\contrastdescSPEAK{ speaking }
\end{filecontents}

\begin{filecontents}{g_loc_contrast_tabular}
\tiny
\begin{table}
\scalebox{0.7}{
\tablestart
\listheadings
\listbody
\end{tabular}
} % end scalebox
\caption{Caption goes here.}
\begin{enumerate}
    \item Item number one.
    \item Item number two.
\end{enumerate}
\end{table}
\normalsize
\end{filecontents}

\input{g_loc_contrast_tabular_def}
\input{g_loc_contrast_def}

\begin{document}

\input{g_loc_contrast_tabular}

\end{document}

A: I think you just want
\def\xlistbody#1,{%
\ifx\relax#1%
\else
\textbf{\csname contrastdesc#1\endcsname}%
\gdef\thisrow{#1}
\expandafter\xlistdata\regionlist,\relax,%
\expandafter\hline
\expandafter\xlistbody
\fi}


text:
Q: Multithreading using CURL increasing cpu usage I have following instances

*

*mysql : 1 instance (8gb RAM)

*nginx : 4 instances

I am assigning jobs to 4 nginx instances from mysql instance using curl POST request. In this case mysql cpu usage is got increased.
I dont want any cpu load to mysql. Mysql should not wait for response from nginxes.
Mysql Script to assign jobs :
$query =  "SELECT id from tablename where is_active = '1'";
$result = mysql_query($query);
$total_jobs = mysql_num_rows($result);
if($total_jobs > 0)
{
    $counter = 0;
    while ($row = mysql_fetch_array($result)) {

        // Assign next job
        // Update job_last_pulled_at_for_processing for picked ids
        $now = date("Y-m-d H:i:s");

        $job_id_url = urlencode($row['id']);
        $passwd_comm = urlencode(base64_encode("abc"));
        $data_part="job_id=".$job_id_url."&passwd_comm=".$passwd_comm;

        $ssh_cmd ="curl -k POST --silent --max-time 3 --data '".$data_part."' http://".$nginx_instance.":8080/admin-alert.php > /dev/null &";
        echo "\nExecuting => CURL\n";
        exec($ssh_cmd);

        $counter++;
        sleep(5);
        if($counter>=12)  {
            GOTO ENDCASE; // If more 12 jobs every min then all of them will not get calculated every min.
        }
    }
} else {
    echo "\nNo Job Eligible to assign";
}

Nginx script to execute job:
$input_data = $_POST;
$job_id = urldecode($input_data['job_id']);
$passwd_post = base64_decode(urldecode($input_data['passwd_comm']));

if($passwd_post != "abc"){
        echo " Wrong Params "; exit;
}

if(!empty($job_id)) {
        exec("php /var/www/cron_files/update_master_value_cron.php ".$job_id." > /dev/null & ");
}
echo " Completed "; exit;

If I send wrong password (abcxyz) from CURL request mysql cpu not increasing. But for correct password ie. to complete jobs at nginx, then Mysql cpu increases to 100%.
Why Mysql cpu increasing if jobs executed by nginxes ?


text:
Q: Unbind property from model MVC I have model which directly update my DB.
But some properties I do not want to update in my DB table then how can I mark those properties to not to go in DB table?
my model is as below:
public class Blog
{
       public int id {get;set;}
       public int newid {get;set;} // which i want to unbind/exclude
}

A: Assuming that you are using Entity Framework (which by the way you should have specified in your question because ASP.NET MVC doesn't know what a database means. I remind you that ASP.NET MVC is a web framework, not an ORM), you could decorate the property with the [NotMapped] attribute:
public class Blog
{
    public int id { get; set; }

    [NotMapped]
    public int newid { get; set; }
}

Obviously if you are using some other data access technology to query your database you should check the documentation of it to know how to ignore some properties from being mapped.

A: protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}


text:
Q: Distribution of the maximum of $n$ uniform random variables If $U_1,\dots, U_n$ are independent uniform random variables with range $\{1,\dots,N\}$, what can be said about the distribution of $Z=\max U_i$?  I am interested in the case where $n$ is large and $N\geq n$.
In particular, I am interested in tail bounds for $Z$.  That is how tightly concentrated it is around its mean $\mathbb{E}(Z)$.

A: It has not been explicitly stated that the $U_i$ are independent. We assume they are.
Let $1\le z\le N$. The probability that $Z\le z$ is the probability all the $U_i$ are $\le z$. This is $\left(\frac{z}{N}\right)^n$. So the expressions for (left and right) tail probabilities are quite simple.
The distribution function of $Z$ readily follows. We have $Z=z$ iff $Z\le z$ and it is not the case that $Z\le z-1$. This has probability  $\left(\frac{z}{N}\right)^n-\left(\frac{z-1}{N}\right)^n$.
Added: In comments, we are asked about asymptotic estimates for mean and variance. Let $F(z)=(z/N)^n$. Then the mean is
$$1(F(1)-F(0))+2(F(2)-F(1))+3(F(3)-F(2))+\cdots +N(F(N)-F(N-1)).$$
There is a lot of cancellation. Since $F(0)=0$, we find that
$$E[Z] = - F(1) - \dots -F(N-1) + NF(N)$$
And recalling the expression for $F(z)$ we find:
$$E[Z] = N - (\frac{N-1}{N})^n - \dots - (\frac{1}{N})^n$$
Which converged to $N$ as n goes towards infinity, showing that $max(U_i)$ is an unbiased estimator for N
You will notice that unlike its continuous counterpart where $X \sim unif[0 , \theta]$, $max(X_i)$ is not unbiased, and you can find that $\frac{n+1}{n}[max(X_i)]$ is unbiased for a sample size of n. Indeed, intuitively this makes sense, given that in the continuous case, $max(X_i)$ does not reach $\theta$ with probability 1, hence needs a nudge upwards. In the discrete case, $max(U_i)$ reaches N with probability 1, hence will not need some nudge to reach the value it is attempting to estimate.

A: If you are interested in results for large $n$ but with $n\le N,$ I would first consider the variable $Z/N.$ This converges in distribution as $N\to \infty.$ Because: Let $X_n$ be the maximum of $n$ iid Uniform$(0,1)$  so $P(X_n \le x)=x^n.$ Then $P(Z/N\le x)=P(Z\le Nx)=\left(\lfloor Nx   \rfloor /N   \right)^u\to x^n.$
Now that we are in the Uniform(0,1) case, it is easy to compute the mean and standard deviation of $X_n:$
$$ \mu_n=\frac n{n+1}, \sigma_n=\frac 1{n+1}\sqrt\frac n{n+2}.$$
Now we can show $(X_n-\mu_n)/\sigma_n$ converges in distribution:
$$P[(X_n-\mu_n)/\sigma_n \le x] =(x\sigma_n+\mu_n)^n =\left( 1+\frac {x\sqrt {(n/(n+2)} -1}{n+1}   \right)^n\to e^{x-1}$$
as $n\to \infty$ for $x \le 1.$  So for an asymptotic result, consider the probability that $X_n$ is between $\mu_n-\sigma_n$ and $\mu_n+\sigma_n$ This can be approximated for any $n$ sufficiently large as $e^{1-1} - e^{-1-1}=0.86 $
We can also use other sequences of norming constants. Since $X_n \le 1$ and converges to it and $\sigma_n \sim 1/n$ we can try
 $n(X_n-1).$ It is easy to show this converges to $e^x    $ for $x  \le 0. $
The study of the distribution of the max of iid r.v. is called Extreme Value Theory. It models extreme events like a 100-year flood. It is also used in Reliability Theory since the lifetime of $n$ components connected in parallel is given by the max.

A: $$F_Z(x)=P(\max U_i\leq x)=P(U_1,\ldots,U_N\leq x)=F_U(U_1\leq x)\cdots F_U(U_N\leq x)=F_U(x)^n$$
where for the last two steps I assumed i.i.d. for the $U_i$'s, and the discrete Uniform CDF given by
$$
  F_U(x; 1,N)= \begin{cases}
  0 & \text{, }x < 1 \\[8pt]
  \frac{ x} {N} & \text{, }1 \le x < N \\[8pt]
  1 & \text{, }x \ge N
  \end{cases}
$$
, $x\in\mathbb{N}$.

A: André, the formula you give for the expectation of $Z$ is wrong. I agree on $E(Z)$ being given by
$$
1(F(1)−F(0))+2(F(2)−F(1))+3(F(3)−F(2))+\cdots+N(F(N)−F(N−1))
$$
But cancellations do not yield the ratio
$$
E(Z)=\frac{1^n+2^n+3^n+\cdots+N^n}{N^n}
$$
Instead, the correct expression is
$$
E(Z) = N- \frac{1^n+2^n+\cdots+(N-1)^n}{N^n}
$$
Obviously, those two expressions are not the same


text:
Q: Implementing facenet in keras
Here I am trying to implement open face in keras.
but i am confused about that how to do triplet embedding (As Image in above link)
I know about triplet selection and convolution neural network
can someone help to figure out:
1> model structure for triplet training
2> triplet loss function

A: The model can be anything, but generally it's a convolutional net. The triplet loss is computed on one of the late dense layer outputs, according to the formula you linked. Basically, if d(A, B) is the euclidean distance between outputs A and B (treated as vectors), then take max(0, d(A, P)^2 - d(A, N)^2 + alpha)


text:
Q: get the value sent by ajax I have:
  <form method="POST" name="f">
    <input type="file" name="FileUpload" id="FileUpload" />
  </form>

I'm sent the file using ajax,using the uplaod.file method:
document.getElementById('FileUpload').onchange = function() {

        file = this.files[0];
        ajax = new XMLHttpRequest;
        ajax.file = file;

        //etc..

         ajax.open('post','Default.aspx', true);
         ajax.setRequestHeader('foo','baa');

         ajax.send(file);

}
Request.Forms["FileUplaod"] // don't works

How I get the value (the file) sent by ajax in my asp.net application?
I tried sent by http headers(is not pratice good,I know) but there problem with long length.
Thanks in advance.

A: try this form attribute :
form action="some/action" method="POST" enctype="multipart/form-data"


text:
Q: including RTF inserted images to be sent in an email as HTML I am using this code to insert images into an RTF box:
Public Sub InsertPicture()
        'Use the code 'InsertPicture()' to show the dialog and insert a picture
        Try
            Dim GetPicture As New OpenFileDialog
            GetPicture.Filter = "PNGs (*.png), Bitmaps (*.bmp), GIFs (*.gif), JPEGs (*.jpg)|*.bmp;*.gif;*.jpg;*.png|PNGs (*.png)|*.png|Bitmaps (*.bmp)|*.bmp|GIFs (*.gif)|*.gif|JPEGs (*.jpg)|*.jpg"
            GetPicture.FilterIndex = 1
            GetPicture.InitialDirectory = "C:\"
            If GetPicture.ShowDialog = Windows.Forms.DialogResult.OK Then
                Dim SelectedPicture As String = GetPicture.FileName
                Dim Picture As Bitmap = New Bitmap(SelectedPicture)
                Dim cboard As Object = Clipboard.GetData(System.Windows.Forms.DataFormats.Text)
                Clipboard.SetImage(Picture)
                Dim PictureFormat As DataFormats.Format = DataFormats.GetFormat(DataFormats.Bitmap)
                If RichTextBoxPrintCtrl1.CanPaste(PictureFormat) Then
                    RichTextBoxPrintCtrl1.Paste(PictureFormat)
                End If
                Clipboard.Clear()
                Clipboard.SetText(cboard)
            End If
        Catch ex As Exception
        End Try
    End Sub

It works okay and inserts/shows the image fine, however the images are not showing when converting the RTF to HTML and sending as a HTML email.
im guessing its because its not inserting the images as attachments, how can i do this for each image inserted into the RTF box?


text:
Q: ng-dirty is not working as expected I am having tough time in understanding why my element shows ng-dirty after updating the model.
I have a collection of bridges which need to be rendered on UI.  On each tab click, I am changing the index and rendering the data.

*

*If my first tab data has changed and moved to second tab why are input elements still dirty on second tab. (Function -  $scope.changeIndex)

*After executing calculate, the model gets updated but still the input elements are still dirty
UI

    Length:
    <input type="text" class="currencyLabel-editable" ng-model="bridgeModel.bridges[currentIndex].length" />

    Width:
    <input type="text" class="currencyLabel-editable" ng-model="bridgeModel.bridges[currentIndex].width" />

     Skew:
    <input type="text" class="currencyLabel-editable" ng-model="bridgeModel.bridges[currentIndex].skew" />

Controller
(function () {

var bridgeCtrl = function ($scope, $bootstrapBridgeData, $crudService,$log) {

    $scope.bridgeModel = $bootstrapBridgeData.bridgeModel;

    var onCalculateComplete = function (data) {
        $scope.bridgeModel.bridges[$scope.currentIndex] = angular.copy(angular.fromJson(data));

    }

    var onCalculateError = function (reason){
        $scope.error = "Unable to perform calculation";
        $log.error(reason);
    }

    var onError = function (reason) {
        $scope.error = "Unable to fetch data";
    }

    //function to null the values which needs to be re-computed
    var removeCalculatedValues = function () {

        $scope.bridgeModel.bridges[$scope.currentIndex].foundation_PreBoringCalculated = null;
        $scope.bridgeModel.bridges[$scope.currentIndex].foundation_DrilledShaftsCalculated = null;

    }

    //function to compute the bridge values
    $scope.calculate = function (url) {

        if (!preValidation()) {
            return false;
        }

        removeCalculatedValues();

        $crudService.postAndGetData(url, $scope.bridgeModel.bridges[$scope.currentIndex])
                     .then(onCalculateComplete, onCalculateError)

    }

    //function to select the bridge and change the index of the bridge
    $scope.changeIndex = function (bridgeName,index) {
         $scope.selectedBridge = bridgeName;
         $scope.currentIndex = index;
    }

    $scope.save = function (index, url) {

        $scope.currentIndex = index;
        crudService.postAndGetData(url, $scope.bridges[index])
                   .then(onUserComplete, onError);

    }

    //$scope.enableSave = function isFormDirty() {

    //    if ($(".ng-dirty").length) {
    //        return false;
    //    }
    //    else { return true; }
    //}

    //Behaviour Changes

    //function which changes the css
    $scope.isBridgeSelected = function (bridge) {
        return $scope.selectedBridge === bridge;
    }

    var preValidation = function () {

        if ($(".ng-invalid").length) {
            alert("Please correct the errors.")
            return false;
        }
        else { return true;}
    }

}

//Get the module and add a controller to it
var module = angular.module("bridgeModule");
module.controller("bridgeCtrl", bridgeCtrl);

}());

A: From the documentation

ng-dirty is set if the form is dirty.

This is a check for whether the form itself has been interacted with in any way.  It doesn't care what the underlying object binding is.  So this is the expected behavior, since you are using the same form but changing the ng-model behind the scenes.

A: Dunno if this is the problem or not, but the line $scope.$setPristine; is not doing anything.  It should be: $scope.$setPristine();


text:
Q: Can't close PCL visualizer I am writing a program to record and store pointclouds. Part of the programs function to observe the recorded clouds, for this I use the PCL visualizer. The problem is that if I close the visualizers window the window just stops, but won't close. I tried calling the close() method, but nothing. I read that this was a problem before VTK 8.0, but I use 8.1 and the problem is still there. I also use PCL 1.9.1 and Ubuntu 18.04.
Anyone has a solution for this? Thanks in advance.

A: You can try wasStopped() instead of close();
After creating your viewer object:
while (!viewer.wasStopped ())
       {
        viewer.spinOnce ();
      }


text:
Q: How does a robust http server handle requests? I have written many http(s) servers in Node.js and just take for granted that I can receive many requests and all IO operations are async. However, now I would like to try and implement an HTTP server in C, like this one, but I'm wondering what it would look like to be robust.
Specifically, what I mean is, I don't want to see a full fledged HTTP framework in C because they are quite large and complicated. But I just would like to understand how to maximize the number of requests and handle the requests efficiently on one server.
Is it just as simple as a while (1) loop to look for incoming socket connections and then parse the HTTP request and server a response in one fell swoop? (Assuming we don't have any async resources we are fetching in this simplified example)?
Or are there more tricks you need to do somewhere within this, such as creating a queue of incoming requests before processing them, then partially process them in a round robin sort of fashion until they are individually done. Or something along those lines. Wondering if one could outline what needs to be done to maximize performance/throughput.

A: Maximizing throughput requires the use of async techniques, which C is very bad at. The issue with a while-loop that accepts and handles new connections is that we can only process one request at a time, and that processing this request is typically IO-bound: speed is dependent on the connection to the client, and even on the client itself. If we don't receive the next TCP packet, the entire loop is blocked until the connection times out!
So what servers in C typically do is fork() immediately after accepting a request, or passing the accepted file handle to a pre-forked pool of workers (see: Apache), or using threads instead of processes. Now, the number of requests that can be in flight is limited by the number of worker threads/processes. There is considerable overhead with this approach, limiting how far it can scale. There is context-switching overhead from juggling all those processes, and there is a memory overhead of at least a few KB for each worker. Most of the workers will always be idle, because they are waiting for some IO operation (read or write) to complete.
A scalable server will therefore have to use event-driven, non-blocking techniques. To a small degree, this can be managed with select() or poll() in POSIX. More practical are non-portable APIs like epoll() in Linux or kqueue() in FreeBSD (which are all predated by IOCP in Windows NT). You wouldn't use those directly, but use an event loop library like libuv or libevent.
Nginx uses precisely such event driven IO facilities to efficiently multiplex connections. Node.JS combines the V8 JavaScript engine with libuv and is probably one of the most accessible platforms to write async servers. However, we are now also seeing systems programming languages getting good abstractions for async operations. Async/await syntax was pioneered in .NET languages, and is also available in Rust and C++20. This allows for much less overhead per in-flight request, and makes it comparatively easy to integrate an event loop, without having to manually encode a state machine.


text:
Q: Drawing an arc backwards? I am porting some of the Slick Graphics class to work with AWT, but I've run into a problem. Slick, being run on OpenGL, draws arcs clockwise. AWT defines them as being drawn counter-clockwise, like in math. I'm wondering how I can draw Slick's arc counter-clockwise, so that it matches AWT.
An image of what I'd expect:

An image of what I get:

A: This is the function to draw an arc in Slick2D:
public void drawArc(float x1,
                    float y1,
                    float width,
                    float height,
                    float start,
                    float end)

Since it appears that Slick draws these arcs clock-wise (0 - 360 degrees) then you can do some simple arithmetic to get the effect that you wish.

A and B are your original angles that you wish to draw the arc in between like 0 and 90 degrees. drawArc(0,0,1,1,A,B) will render an arc from A to B, but we want an arc from C to D which is the same arc as A to B but counter-clock wise. Since you already know the values of A and B (like 0 and 90) you can get the values for C and D with the following:
C = 360 - B
D = 360 - A
So now we can just use drawArc(0,0,1,1,C,D).
Test it with values:
A = 0
B = 90
C = 360 - 90 = 270
D = 360 - 0  = 360
This will plot an arc from 270 to 360 which is the same as an arc from 0 to 90 counter-clock wise.


text:
Q: How to call function instead of screen inside Drawer on React Navigation? I Used "react-navigation": "^4.0.10", "react-navigation-drawer": "^2.3.2",
and implement a drawer and inside them, I added my item, one of them is "Call us" and it should open a phone so I used for it Linking and I don't know if that's a good way to invoke a function instead of Screen as default in RN-drawer
so I do that's But after click to this item my app crashed and stop to work!! so how can I achieve this?
const DrawerNavigator = createDrawerNavigator({
 ...
 CallUsDrawer: {
      screen: () => Linking.openURL(`tel:0597093830`),
      navigationOptions: {
        drawerLabel: 'call us',
        drawerIcon: () => <Icon name="ios-call" size={28} color="#1E558E" />,
      },
    },
 ...
});

A: This is a wrong approach. You should create a contentcomponent for the createDrawerNavigator and there should be a <Button> or something for "call us". and in onPress of that component wright the logic  Linking.openURL(tel:0597093830)
plese check,
https://reactnavigation.org/docs/en/drawer-navigator.html#providing-a-custom-contentcomponent
Sample
const drawerNavigator = createDrawerNavigator(
  {
   ... screens here
  },
  {
    contentComponent: MenuScreen,
    drawerWidth: 300
  }
);

where MenuScreen is a Componet

A: Use DrawerItem instead of Drawer.Screen. Complete Docs here. Example available in this Snack


text:
Q: Do React unique key warnings appear in production (in Next, specifically)? I'm getting a React duplicate key warning in development. Grepping for all of my maps and manually reviewing them hasn't led me anywhere. So, I started reversing commits to find the offender, but ended up way back without finding it, and I was pretty sure this wasn't happening a few days ago. So, I went and looked at what was in production, and I'm not seeing the errors there. So I checked out the production build, and am seeing the errors. So I'm wondering, does either React normally by itself, or something in the way NextJS builds static pages, suppress the warning in production?
NB: the actual warning is being generated for a 3rd-party component, the React DatoCMS <StructredText> component. If Next/React isn't suppressing the warning, then my suspicion will be something broke in an update to the DatoCMS API, and I'll reach out to them. If it is or may be suppressing the warning, then ... I'll keep digging.


text:
Q: Java substitute for function pointers I'm looking to create a Sigma method. Coming from C I could use a function pointer, but I'm not certain of a similar construct of C. It seems that I could use Lambdas, though I'm unfamiliar of how they work outside of Scheme. If anyone could help me modify the code below it would be greatly appreciated.
public static int Sigma( int n , function f(int)) {
     int sum = 0;
     for(int i = 0; i < n; i++)
          sum = sum + f(i);
     return sum;
}

A: You can use functional classes/interfaces from the java.util.function package in Java 8+. Like IntUnaryOperator.
public static int Sigma(int n, IntUnaryOperator f){
     int sum = 0;
     for(int i = 0; i < n; i++)
          sum = sum + f(i);
     return sum;
}

An even shorter version would use IntStream (same package)
public static int Sigma(int n, IntUnaryOperator f){
     return IntStream.range(0, n).map(f).sum();
}

A: Assuming I understand your intent, you could pass a Function<Integer, Integer> and then perform a range, map and sum like
public static int Sigma(int n, Function<Integer, Integer> f) {
    return IntStream.range(0, n).map(f::apply).sum();
}


text:
Q: SqlConnection не реагирует на password Имеется база данных на Sql Server 2012.
В базе данных имеется пользователь TestUser, созданный таким образом:
CREATE LOGIN TestUser
    WITH PASSWORD = '123';
USE Банк;
GO
CREATE USER TestUser FOR LOGIN TestUser;
GO

Я подключаюсь к базе через приложение на C#, используя SqlConnection.
String ConnectionString = "Data Source=Computer;Initial Catalog=Банк;Persist Security Info=False;Integrated Security=SSPI;User ID=TestUser;Password=123;";
SqlConnection con = new SqlConnection();
con.ConnectionString = ConnectionString;
con.Open();

Проблема в том что даже если пароль неверный то соединение все равно будет установлено и можно отправлять запросы. Подскажите как это исправить.

A: Попробуйте убрать "Integrated Security=SSPI". Кажется это логинит через системный логин и соосно игнорит юзера и пароль. То есть вы входите не как TestUser.


text:
Q: unable to import file into Aws documentdb - error: connection() : x509: certificate signed by unknown authority when I am trying to import the data from ec2 to documentdb with below two commands, getting the same error
mongoimport --ssl --host="@hostname:27017" --collection=test   --db=admin     --file=restaurant.json --numInsertionWorkers 4     --username=Tester --password=xxxxxx --sslCAFile rds-combined-ca-bundle.pem

mongorestore  --host @hostname:27017 --ssl --sslCAFile rds-combined-ca-bundle.pem --username Test --password xxxxxxx dump

error connecting to host: could not connect to server: server
selection error: server selection timeout, current topology: { Type:
Single, Servers: [{ Addr:
dev-gba-documentdb.cprffppj2tqu.ap-south-1.docdb.amazonaws.com:27025,
Type: Unknown, State: Connected, Average RTT: 0, Last error:
connection() : x509: certificate signed by unknown authority }, ] }

I tried with both commands mongoimport ,mongorestore , error not resolved, i am expecting to way out from this error or migrate the data to documentdb


text:
Q: Can you undo changes to your visual selection? Say you're selecting a large region of text using a & i, but you make a mistake and accidentally select too much (say you accidentally type at and select the entire tag you are working in, losing your selections inside the tag).
Is there any way to undo a change in visual selection?

A: The extent of the selection is stored in the '<,'> marks when you leave or operate on the selection.
Therefore, to "save" the selection, you'd have to leave and re-enter the selection: <Esc>gv. Then, if you accidentally select something undesired, you could restore the previous selection (within visual mode!) with ```>o`<``.


text:
Q: Grails custom environments and web-apps I'm asking to learn here so I might need a reality check so please, all input is welcome!
Let me describe the situation at hand here.
I have a Grails-project called, let's say - Forrest.
The idea is to give Forrest to different users, which may have different types of databases and branding (css and images), the delivery is then to be done by running say:
grails -Dgrails.env=user1 war

Forrest is to be given different environments in for example DataSource.groovy:
environments{
    user1{
        prop = 'user1'
    }
    user2{
        prop = 'user2'
    }
}

This is done so that customers can specify where they have their databases etc (not the idea way of doing it since it'll end up in a code repo and I don't know how configuration can be done by the user once they have the war-file).
What's also important is that I'm able to specify what environment uses what css-files and images. For exmaple, user1 might want green text whereas user2 wants blue text.
Any input on how I can control what is givem to whom or shall I reconsider?

A: The best approach to this would be to externalize the configuration so that you can just hand them the WAR and they can place a configuration file (Groovy file) in the path to the application. No custom build process, no changes in the code, etc. Easy and clean.
Check out grails-app/conf/config.groovy for

grails.config.locations


text:
Q: How to count two relation at the same time without subquery Assume table A has on to many relation with both table B and table C. I want to achieve the A.id,count(B.id),count(C.id) results. How can I get that without using subquery?

A: You can achieve this by using the distinct keyword within your count() function. Example:
select
  A.id,
  count(distinct B.id),
  count(distinct C.id)
from A
  left outer join B on B.A_id = A.id
  left outer join C on C.A_id = A.id
  group by A.id;

Reference: MySQL docs on count(distinct).


text:
Q: Select three columns (A,B,C) and return rows where (B,C) are distinct and A is at max value because there are multiple occurrences of (B,C) pairs Working in Hive, I have a table with three columns A(INT), B(STRING) and C(STRING). B & C columns have repeat paired values (ie row 1 & row 10 may have identical strings in columns B & C). I'm trying to return the full rows (ie A,B,C) of distinct B,C pairs where the A column is at it's max value among all occurrences of distinct B,C pairs. All help is appreciated.
Example of input table
Col1 Col2 Col3
----------------
1111, str1, str2
2222, str1, str2
3333, str3, str4
4444, str5, str6
5555, str3, str4
6666, str5, str6

Example of output from query
Col1 Col2 Col3
----------------
2222, str1, str2
5555, str3, str4
6666, str5, str6

A: If you want just the three columns in result:
select max(a) a, b, c
from your_table
group by b, c;

If you have more columns to select, you can use window function row_number for this:
select *
from (
    select t.*,
        row_number() over (
            partition by b, c
            order by a desc nulls last
            ) rn
    from your_table t
    ) t
where rn = 1;


text:
Q: mPDF Output blocks response I am  writing a PHP file that receives post data (via a React Native App) and create a PDF file using mPDF. At the end of that file I want to be able to download the file, or see it in the browser or upload it on the server. In addition to that I do a json_encode($array) to be able to retrieve the name of the file and its path on the server.
$result = array('generatedPDF' => $file,'path' => $path);
echo json_encode($result);

$mpdf->Output('report.pdf','D'); // For Download
// $mpdf->Output($filename,'F'); // For Upload
// $mpdf->Output(); // For Browser

return json_encode($result);

The download and the display on the browser both work (I have an error 500 for the upload...) but in the debugging tool, I have nothing in the response (in Network).
If I delete the Output lines, I have the a response
{"generatedPDF":"report.pdf","path":"\/folder\/folder\/report.pdf"}

Is it possible to have both a working Output method and a response ?

A: An HTTP request can return only one resource. So it's impossible to return both a PDF and a JSON at the same time.
You should get the JSON first and issue a second request to retrieve the PDF.


text:
Q: how to hide a particular paragraph tag in layout in particular view p in rails? In my application I have a layout for all view pages ending with 'Happily, CSE team'. Now we have a view for destruction of user in that we want to display 'sadly, CSE team'. I know there is option, 'content_for tag' , I am having more than 20 views so no use of that tag.
In the user_destruction_mail view i want to display sadly cse team instead of  Sincerely, The Happy CSE team.
template.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css"
<title><%= content_for?(:page_title) ? yield(:page_title) : 'Mailer_View' %></title>

                  <%= yield %>

                    Sincerely,

                    The Happy CSE team

view/intimation_mailers/user_destruction_mail.html.erb

Ciao,

The Sadly CSE team


text:
Q: C# DataGridView date time formatting of a column I have datagridview which fills data from database, there are columns where I have date and time in them "MMddyyyy" and "hhmmss" format, what I want to do is when the datagridview loads, I want to change this format to some other format say, dd-MM-yy for date and for time hh-mm-ss. I was wondering if some one can guide me how to do it.
I have not been able to do this by gridview.columns[x].defaultcellstyle.format="dd-MM-yy"
with the above I get no error but nothing is changed on the gridview ...
Thanks
Note:I dont have the option to change the column length in the database as well..:-(
there are no syntax problems

A: Microsoft suggest you intercept the CellFormatting event (where DATED is the column you want to reformat):
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // If the column is the DATED column, check the
    // value.
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "DATED")
    {
        ShortFormDateFormat(e);
    }
}

private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting)
{
    if (formatting.Value != null)
    {
        try
        {
            DateTime theDate = DateTime.Parse(formatting.Value.ToString());
            String dateString = theDate.ToString("dd-MM-yy");
            formatting.Value = dateString;
            formatting.FormattingApplied = true;
        }
        catch (FormatException)
        {
            // Set to false in case there are other handlers interested trying to
            // format this DataGridViewCellFormattingEventArgs instance.
            formatting.FormattingApplied = false;
        }
    }
}

A: The sintax in DataGridView formating is a little different then in DateTime, but you can get the same result. In my example i have a Time collumn, that by default shows HH:mm:ss and I want to show only hours and minutes:
 yourDataGridView.Columns["Time"].DefaultCellStyle.Format = @"hh\:mm";


text:
Q: uploading image to server php to python I am converting my code from php to python and want to find the equivalent
in python. My android application sends a base64 encrypted image and folder name. The script should decode it and save it to my server.
The php is
<?php
    // Get image string posted from Android App
    $base=$_REQUEST['image'];
    // Get file name posted from Android App
    $filename = $_REQUEST['filename'];
    // Decode Image
    $binary=base64_decode($base);
    header('Content-Type: bitmap; charset=utf-8');
    // Images will be saved under 'www/img/uplodedimages' folder
    $file = fopen('/home1/test/public_html/img/'.$filename.'.jpg', 'wb');
    if($file != true)
    {
    echo'Error uploading image';
    }
    else{
     // Create File
    fwrite($file, $binary);
    fclose($file);
    echo 'Image upload successful';
    }
?>

My attempt to convert to python is bellow
#! /usr/bin/python
import cgi
import base64
import json

print "Content-type: text/html\r\n\r\n"

d = {}
arguments = cgi.FieldStorage()
base = arguments.getvalue('image')
filename = arguments.getvalue('filename')

binary = base.b64decode('base64')
file = open('/home1/test/public_html/img/%s.jpg', 'wb') % filename
if file != True:
    d['success'] = 0
    d['message'] = 'Error uploading image'
    print json.dumps(d)
else:
    file.write(file, binary)
    file.close()
    d['success'] = 1
    d['message'] = 'Upload Successful'
    print json.dumps(d)

I have never used I/O With python so I am new with it. When running the output is blank.

A: This should work
#! /usr/bin/python
import cgi
import base64
import simplejson

print "Content-type: text/html\r\n\r\n"

d = {}
arguments = cgi.FieldStorage()
data = arguments.getvalue('image')
filename = arguments.getvalue('filename')

binary = base64.b64decode(data)
file = open('/home1/test/public_html/img/%s.jpg' % filename, 'wb')

if file != True:
    d['success'] = 0
    d['message'] = 'Error uploading image'
    print simplejson.dumps(d)
else:
    file.write(file, binary)
    file.close()
    d['success'] = 1
    d['message'] = 'Upload Successful'
    print simplejson.dumps(d)


text:
Q: Logstash Load Error - Java I need help figuring out how to solve this error. I'm running elastic search 5.6.2 and log stash 5.6.1 (and tried 5.6.3 and 6.0.0) and JDK 1.8 but I'm getting an error when trying to run log stash.  This is on OSX 10.12.6
Java HotSpot(TM) 64-Bit Server VM warning: Option UseParNewGC was deprecated in version 9.0 and will likely be removed in a future release.
Java HotSpot(TM) 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by jnr.posix.JavaLibCHelper to method sun.nio.ch.SelChImpl.getFD()
WARNING: Please consider reporting this to the maintainers of jnr.posix.JavaLibCHelper
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
io/console on JRuby shells out to stty for most operations
LoadError: load error: jopenssl/load --     java.lang.ExceptionInInitializerError: null
  require at org/jruby/RubyKernel.java:1040
   (root) at /Users/perkinsl/logstash-5.6.1/vendor/jruby/lib/ruby/shared/openssl.rb:1
  require at org/jruby/RubyKernel.java:1040
   (root) at /Users/perkinsl/logstash-5.6.1/logstash-core/lib/logstash/patches/stronger_openssl_defaults.rb:1
  require at org/jruby/RubyKernel.java:1040
   (root) at /Users/perkinsl/logstash-5.6.1/logstash-core/lib/logstash/patches/stronger_openssl_defaults.rb:2
  require at org/jruby/RubyKernel.java:1040
   (root) at /Users/perkinsl/logstash-5.6.1/logstash-core/lib/logstash/patches.rb:1
  require at org/jruby/RubyKernel.java:1040
   (root) at /Users/perkinsl/logstash-5.6.1/logstash-core/lib/logstash/patches.rb:5
  require at org/jruby/RubyKernel.java:1040
   (root) at /Users/perkinsl/logstash-5.6.1/lib/bootstrap/environment.rb:70

I've tried running a config test but it doesn't get that far.

A: A complete uninstall/re-install of the JDK and setting Java_Home seems to have done the trick.


text:
Q: How to Handle pop ups in selenium Webdriver I want to handle pop up that coming after submitting the data on a page, pop up like OK And Cancel . (in Java )
Please check attached image
Note: i tried Alert and this #8244723
Thanks   pop up like attached image

A: You can use following one line code when that pop will arise:
driver.switchTo().alert().accept();


text:
Q: how to edit a line having IPv4 address using sed command I need to modify an ntp configuration file by adding some options to the line containing Ip addresses.
I have been trying it for so long using sed command, but no able to modify the line unless i don't know the IP addresses.
Let say, i have few lines as,
server 172.0.0.1
server 10.0.0.1
I need to add iburst option after the ip address.
I have tried command like.. sed -e 's/(\d{1,3}\.\d{1.3}\.\d{1,3}\.\d{1,3})/ \1 iburst/g' ntp_file
or sed -e 's/^server +\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/server \1\.\2\.\3\ iburst/g' ntp_file
but its not modifying the line. Any kind of suggestions would be really appriciated.

A: The regex you have used as  POSIX BRE cannot match the expected strings due to \d shorthand class that sed does not support, the misused dot inside a range quantifier and incorrect escaping of grouping and range quantifier delimiters.
You may use
sed -E -i 's/[0-9]{1,3}(\.[0-9]{1,3}){3}/ & iburst/g' ntp_file

The POSIX ERE (enabled with the -E option) expression means to match

*

*[0-9]{1,3} - one to three digits

*(\.[0-9]{1,3}){3} - three occurrences of a dot and one to three digits

The replacement pattern is  & iburst where & stands for the whole match.
The g flag replaces all occurrences.


text:
Q: Add A UITableView Cell After Another One Essentially I have a tableview with two types of cells. One is a cell that contains a number that is being pulled from an array. The second cell is just supposed to act as a spacing cell but can contain information. However, I've only seen solutions that have the second cell come after the first if it its row is equal to 0 or if it is sectioned off.
The array of numbers is [1,2,3,4,5,6,7] and the first cell type pulls from it to display each number
I'm trying to get something that looks like this:
celltypeone: 1
celltypetwo
celltypeone: 2
celltypetwo
celltypeone: 3
celltypetwo
celltypeone: 4
celltypetwo
... and so on.
I thought about trying to get the space cell to come after every next cell but I didn't think that made sense.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let index = indexPath.row

    if index >= 0 {

    let cell = tableView.dequeueReusableCell(withIdentifier: "productsblock", for: indexPath ) as! DetailTBCell

        return cell

    }
    else {

          let spacecell = tableView.dequeueReusableCell(withIdentifier: "spacingcell", for: indexPath ) as! DetailSpaceTBCell

        return spacecell

}

}
This prints all the numbers from the array and displays them but the second cell does not show at all.
I'm unsure of what to do or how to get it to work.

A: if (index % 2) == 0 | try if index number is double put the first tableCell else put the other one
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let index = indexPath.row

    if (index % 2) == 0 {

    let cell = tableView.dequeueReusableCell(withIdentifier: "productsblock", for: indexPath ) as! DetailTBCell

        return cell

    }
    else {

          let spacecell = tableView.dequeueReusableCell(withIdentifier: "spacingcell", for: indexPath ) as! DetailSpaceTBCell

        return spacecell

}

A: If you notice your product cell needs to be shown at even position and the spacing cell at odd position.
`index >= 0 ` needs to replaced with `index % 2 == 0 `

Moreover in order to fetch data from product array you will be needing to divide the index by 2.
let products = [1,2,3,4,5,6,7]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let index = indexPath.row

if index % 2 == 0 {

let cell = tableView.dequeueReusableCell(withIdentifier: "productsblock", for: indexPath ) as! DetailTBCell

    // Fetching data from array products defined above
    let data = products[index / 2]
    return cell

}
else {

      let spacecell = tableView.dequeueReusableCell(withIdentifier: "spacingcell", for: indexPath ) as! DetailSpaceTBCell

    return spacecell

}


text:
Q: How can a line skip a column in an aligned environment? I'm trying to align an equation block with eight terms in the following layout:
A....... B..............
C.....   D....    E......
F......  G......  H...

I've tried just leaving out the third column in the first line, but that pushes the third column far right:
\begin{gather}
\begin{aligned}
&\text{A.......} &&\text{B..............} \\
&\text{C.....}   &&\text{D....}    &&\text{E......} \\
&\text{F......}  &&\text{G......}  &&\text{H...}
\end{aligned}
\end{gather}

If this were a table, I would merge the second and third cells of the first row using \multicolumn.
How can I position E and H before the end of B?

A: Depending on the width of B..., you can set it inside a \mathrlap:

\documentclass{article}

\usepackage{mathtools}

\begin{document}

\begin{gather}
  \begin{aligned}
    &\text{A.......} && \mathrlap{\text{B..............}} \\
    &\text{C.....}   && \text{D....}    && \text{E......} \\
    &\text{F......}  && \text{G......}  && \text{H...}
  \end{aligned}
\end{gather}

\end{document}

A: Why not use aray? With it is siple (as you noted in question):
\documentclass{article}
\usepackage{amsmath}
\usepackage{makecell}

\begin{document}
    \begin{equation}
    \begin{equation}
    \setcellgapes{3pt}
    \makegapedcells\bigotimes
\begin{array}{lll}
\gamma^2 = \alpha^2 + \beta^2
                &\multicolumn{2}{l}{\displaystyle
                \sin{x}= \sum_{i=0}^{\infty}\frac{(-1)^i}{(2i+1)!}x^{2i+1}
                                    }                       \\
\text{C.....}   &\text{D....}    &\text{E......}            \\
\text{F......}  &\text{G......}  &\text{H...}
\end{array}
    \end{equation}
\end{document}


text:
Q: List comparison failure with Vampire Numbers This code checks whether or not a combination of numbers produces a vampire number but returns an incorrect True if x = 2947051 and y = 8469153.
def vampire_test(x, y):
    vamp = (list(str(x) + str(y)))
    prod = x*y
    vamp_check = list(str(prod))

    print vamp, vamp_check

    if '-' in vamp and '-' not in vamp_check:
        return False
    else:
        check = cmp(vamp.sort(),vamp_check.sort())
        if check == 0 and len(vamp) == len(vamp_check):
            return True
        else:
            return False

What's the issue and how can I improve the code I've already written?

A: There is a logic problem.  This line:
check = cmp(vamp.sort(),vamp_check.sort())

Will do check = 0 every time, because the .sort() method of list sorts in place and returns None.


text:
Q: Monads with Java 8 In the interests of helping to understand what a monad is, can someone provide an example using java ? Are they possible ?
Lambda expressions are possible using java if you download the pre-release lambda compatible JDK8   from here http://jdk8.java.net/lambda/
An example of a lambda using this JDK is shown below, can someone provide a comparably simple monad ?
public interface TransformService {
        int[] transform(List<Integer> inputs);
    }
    public static void main(String ars[]) {
        TransformService transformService = (inputs) -> {
            int[] ints = new int[inputs.size()];
            int i = 0;
            for (Integer element : inputs) {
                ints[i] = element;
            }
            return ints;
        };

        List<Integer> inputs = new ArrayList<Integer>(5) {{
            add(10);
            add(10);
        }};
        int[] results = transformService.transform(inputs);
    }

A: Just FYI:
The proposed JDK8 Optional class does satisfy the three Monad laws. Here's a gist demonstrating that.
All it takes be a Monad is to provide two functions which conform to three laws.
The two functions:

*

*Place a value into monadic context

*

*Haskell's Maybe: return / Just

*Scala's Option: Some

*Functional Java's Option: Option.some

*JDK8's Optional: Optional.of

*Apply a function in monadic context

*

*Haskell's Maybe: >>= (aka bind)

*Scala's Option: flatMap

*Functional Java's Option: flatMap

*JDK8's Optional: flatMap
Please see the above gist for a java demonstration of the three laws.
NOTE: One of the key things to understand is the signature of the function to apply in monadic context: it takes the raw value type, and returns the monadic type.
In other words, if you have an instance of Optional<Integer>, the functions you can pass to its flatMap method will have the signature (Integer) -> Optional<U>, where U is a value type which does not have to be Integer, for example String:
Optional<Integer> maybeInteger = Optional.of(1);

// Function that takes Integer and returns Optional<Integer>
Optional<Integer> maybePlusOne = maybeInteger.flatMap(n -> Optional.of(n + 1));

// Function that takes Integer and returns Optional<String>
Optional<String> maybeString = maybePlusOne.flatMap(n -> Optional.of(n.toString));

You don't need any sort of Monad Interface to code this way, or to think this way. In Scala, you don't code to a Monad Interface (unless you are using Scalaz library...). It appears that JDK8 will empower Java folks to use this style of chained monadic computations as well.
Hope this is helpful!
Update: Blogged about this here.

A:
Here's the thing about monads which is hard to grasp: monads are a
  pattern, not a specific type. Monads are a shape, they are an abstract
  interface (not in the Java sense) more than they are a concrete data
  structure. As a result, any example-driven tutorial is doomed to
  incompleteness and failure.
  [...]
  The only way to understand monads is to see them for what they are: a mathematical construct.

Monads are not metaphors by Daniel Spiewak

Monads in Java SE 8
List monad
interface Person {
    List<Person> parents();

    default List<Person> greatGrandParents1() {
        List<Person> list = new ArrayList<>();
        for (Person p : parents()) {
            for (Person gp : p.parents()) {
                for (Person ggp : p.parents()) {

                    list.add(ggp);
                }
            }
        }
        return list;
    }

    // <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
    default List<Person> greatGrandParents2() {
        return Stream.of(parents())
                .flatMap(p -> Stream.of(p.parents()))
                .flatMap(gp -> Stream.of(gp.parents()))
                .collect(toList());
    }
}

Maybe monad
interface Person {
    String firstName();
    String middleName();
    String lastName();

    default String fullName1() {
        String fName = firstName();
        if (fName != null) {
            String mName = middleName();
            if (mName != null) {
                String lName = lastName();
                if (lName != null) {
                    return fName + " " + mName + " " + lName;
                }
            }
        }
        return null;
    }

    // <U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper)
    default Optional<String> fullName2() {
        return Optional.ofNullable(firstName())
                .flatMap(fName -> Optional.ofNullable(middleName())
                .flatMap(mName -> Optional.ofNullable(lastName())
                .flatMap(lName -> Optional.of(fName + " " + mName + " " + lName))));
    }
}

Monad is a generic pattern for nested control flow encapsulation.
I.e. a way to create reusable components from nested imperative idioms.

Important to understand that a monad is not just a generic wrapper class with a flat map operation.
For example, ArrayList with a flatMap method won't be a monad.
Because monad laws prohibit side effects.
Monad is a formalism. It describes the structure, regardless of content or meaning.
People struggle with relating to meaningless (abstract) things.
So they come up with metaphors which are not monads.
See also:
conversation between Erik Meijer and Gilad Bracha.

A: Java 8 will have lambdas; monads are a whole different story. They are hard enough to explain in functional programming (as evidenced by the large number of tutorials on the subject in Haskell and Scala).
Monads are a typical feature of statically typed functional languages. To describe them in OO-speak, you could imagine a Monad interface. Classes that implement Monad would then be called 'monadic', provided that in implementing Monad the implementation obeys what are known as the 'monad laws'. The language then provides some syntactic sugar that makes working with instances of the Monad class interesting.
Now Iterable in Java has nothing to do with monads, but as a example of a type that the Java compiler treats specially (the foreach syntax that came with Java 5), consider this:
Iterable<Something> things = getThings(..);
for (Something s: things) {  /* do something with s */ }

So while we could have used Iterable's Iterator methods (hasNext and company) in an old-style for loop, Java grants us this syntactic sugar as a special case.
So just as classes that implement Iterable and Iterator must obey the Iterator laws (Example: hasNext must return false if there is no next element) to be useful in foreach  syntax - there would exist several monadic classes that would be useful with a corresponding do notation (as it is called in Haskell) or Scala's for notation.
So -

*

*What are good examples of monadic classes?

*What would syntactic sugar for dealing with them look like?

In Java 8, I don't know - I am aware of the lambda notation but I am not aware of other special syntactic sugar, so I'll have to give you an example in another language.
Monads often serve as container classes (Lists are an example). Java already has java.util.List which is obviously not monadic, but here is Scala's:
val nums = List(1, 2, 3, 4)
val strs = List("hello", "hola")
val result = for { // Iterate both lists, return a resulting list that contains
                   // pairs of (Int, String) s.t the string size is same as the num.
  n <- nums
  s <- strs if n == s.length
} yield (n, s)
// result will be List((4, "hola"))
// A list of exactly one element, the pair (4, "hola")

Which is (roughly) syntactic sugar for:
val nums = List(1, 2, 3, 4)
val strs = List("hello", "hola")
val results =
nums.flatMap( n =>
  strs.filter(s => s.size == n).   // same as the 'if'
       map(s => (n, s))            // Same as the 'yield'
)
// flatMap takes a lambda as an argument, as do filter and map
//

This shows a feature of Scala where monads are exploited to provide list comprehensions.
So a List in Scala is a monad, because it obeys Scala's monad laws, which stipulate that all monad implementations must have conforming flatMap, map and filter methods (if you are interested in the laws, the "Monads are Elephants" blog entry has the best description I've found so far). And, as you can see, lambdas (and HoF) are absolutely necessary but not sufficient to make this kind of thing useful in a practical way.
There's a bunch of useful monads besides the container-ish ones as well. They have all kinds of applications. My favorite must be the Option monad in Scala (the Maybe monad in Haskell), which is a wrapper type which brings about null safety: the Scala API page for the Option monad has a very simple example usage: http://www.scala-lang.org/api/current/scala/Option.html
In Haskell, monads are useful in representing IO, as a way of working around the fact that non-monadic Haskell code has indeterminate order of execution.
Having lambdas is a first small step into the functional programming world; monads
require both the monad convention and a large enough set of usable monadic types, as well as syntactic sugar to make working with them fun and useful.
Since Scala is arguably the language closest to Java that also allows (monadic) Functional Programming, do look at this Monad tutorial for Scala if you are (still) interested:
http://james-iry.blogspot.jp/2007/09/monads-are-elephants-part-1.html
A cursory googling shows that there is at least one attempt to do this in Java: https://github.com/RichardWarburton/Monads-in-Java -
Sadly, explaining monads in Java (even with lambdas) is as hard as explaining full-blown Object oriented  programming in ANSI C (instead of C++ or Java).

A: the only way to understand monads is by writing a bunch of combinator libraries, noticing the resulting duplication, and then discovering for yourself that monads let you factor out this duplication. In discovering this, everyone builds some intuition for what a monad is… but this intuition isn't the sort of thing that you can communicate to someone else directly – it seems everyone has to go through the same experience of generalizing to monads from some concrete examples of combinator libraries. however
here i found some materials to learn Mondas.
hope to be useful for you too.
codecommit
james-iry.blogspot
debasishg.blogspot

A: This blog post gives a step-by-step example of how you might implement a Monad type (interface) in Java and then use it to define the Maybe monad, as a practical application.
This post explains that there is one monad built into the Java language, emphasising the point that monads are more common than many programmers may think and that coders often inadvertently reinvent them.

A: Even though monads can be implemented in Java, any computation involving them is doomed to become a messy mix of generics and curly braces.
I'd say that Java is definitely not the language to use in order to illustrate their working or to study their meaning and essence. For this purpose it is far better to use JavaScript or to pay some extra price and learn Haskell.
Anyway, I am signaling you that I just implemented a state monad using the new Java 8 lambdas. It's definitely a pet project, but it works on a non-trivial test case.
You may find it presented at my blog, but I'll give you some details here.
A state monad is basically a function from a state to a pair (state,content). You usually give the state a generic type S and the content a generic type A.
Because Java does not have pairs we have to model them using a specific class, let's call it Scp (state-content pair), which in this case will have generic type Scp<S,A> and a constructor new Scp<S,A>(S state,A content). After doing that we can say that the monadic function will have type
java.util.function.Function<S,Scp<S,A>>

which is a @FunctionalInterface. That's to say that its one and only implementation method can be invoked without naming it, passing a lambda expression with the right type.
The class StateMonad<S,A> is mainly a wrapper around the function. Its constructor may be invoked e.g. with
new StateMonad<Integer, String>(n -> new Scp<Integer, String>(n + 1, "value"));

The state monad stores the function as an instance variable. It is then necessary to provide a public method to access it and feed it the state. I decided to call it s2scp ("state to state-content pair").
To complete the definition of the monad you have to provide a unit (aka return) and a bind (aka flatMap) method. Personally I prefer to specify unit as static, whereas bind is an instance member.
In the case of the state monad, unit gotta be the following:
public static <S, A> StateMonad<S, A> unit(A a) {
    return new StateMonad<S, A>((S s) -> new Scp<S, A>(s, a));
}

while bind (as instance member) is:
public <B> StateMonad<S, B> bind(final Function<A, StateMonad<S, B>> famb) {
    return new StateMonad<S, B>((S s) -> {
        Scp<S, A> currentPair = this.s2scp(s);
        return famb(currentPair.content).s2scp(currentPair.state);
    });
}

You notice that bind must introduce a generic type B, because it is the mechanism that allows the chaining of heterogeneous state monads and gives this and any other monad the remarkable capability to move the computation from type to type.
I'd stop here with the Java code. The complex stuff is in the GitHub project. Compared to previous Java versions, lambdas remove a lot of curly braces, but the syntax is still pretty convoluted.
Just as an aside, I'm showing how similar state monad code may be written in other mainstream languages. In the case of Scala, bind (which in that case must be called flatMap) reads like
def flatMap[A, B](famb: A => State[S, B]) = new State[S, B]((s: S) => {
  val (ss: S, aa: A) = this.s2scp(s)
  famb(aa).s2scp(ss)
})

whereas the bind in JavaScript is my favorite; 100% functional, lean and mean but -of course- typeless:
var bind = function(famb){
    return state(function(s) {
        var a = this(s);
        return famb(a.value)(a.state);
    });
};

<shameless>
I am cutting a few corners here, but if you are interested in the details you will find them on my WP blog.</shameless>

A: Despite all controversy about Optional satisfying, or not, the Monad laws, I usually like to look at Stream, Optional and CompletableFuture in the same way. In truth, all them provide a flatMap() and that is all I care and let me embrace the "the tasteful composition of side effects" (cited by Erik Meijer). So we may have corresponding Stream, Optional and CompletableFuture in the following way:

Regarding Monads, I usually simplify it only thinking on flatMap()(from "Principles of Reactive Programming" course by Erik Meijer):

A: A diagram for the "Optional" Monad in Java.
Your task: Perform operations on the "Actuals" (left side) transforming elements of type T union null to type U union null using the function in the light blue box (the light blue box function). Just one box is shown here, but there may be a chain of the light blue boxes (thus proceeding from type U union null to type V _union null to type W union null etc.)
Practically, this will cause you to worry about null values appearing in the function application chain. Ugly!
Solution: Wrap your T into an Optional<T> using the light green box functions, moving to the "Optionals" (right side). Here, transform elements of type Optional<T> to type Optional<U> using the red box function. Mirroring the application of functions to the "Actuals", there may be several red box functions to be be chained (thus proceeding from type Optional<U> to Optional<V> then to Optional<W> etc.). In the end, move back from the "Optionals" to the "Actuals" through one of the dark green box functions.
No worrying about null values anymore. Implementationwise, there will always be an Optional<U>, which may or may not be empty. You can chain the calls to to the red box functions without null checks.
The key point: The red box functions are not implemented individually and directly. Instead, they are obtained from the blue box functions (whichever have been implemented and are available, generally the light blue ones) by using either the map or the flatMap higher-order functions.
The grey boxes provide additional support functionality.
Simples.

A: I like to think of monads in slighlty more mathematical (but still informal) fashion. After that I will explain the relationship to one of Java 8's monads CompletableFuture.
First of all, a monad M is a functor. That is, it transforms a type into another type: If X is a type (e.g. String) then we have another type M<X> (e.g. List<String>). Moreover, if we have a transformation/function X -> Y of types, we should get a function M<X> -> M<Y>.
But there is more data to such a monad. We have a so-called unit which is a function X -> M<X> for each type X. In other words, each object of X can be wrapped in a natural way into the monad.
The most characteristic data of a monad, however, is it's product: a function M<M<X>> -> M<X> for each type X.
All of these data should satisfy some axioms like functoriality, associativity, unit laws, but I won't go into detail here and it also doesn't matter for practical usage.
We can now deduce another operation for monads, which is often used as an equivalent definition for monads, the binding operation: A value/object in M<X> can be bound with a function X -> M<Y> to yield another value in M<Y>. How do we achieve this? Well, first we apply functoriality to the function to obtain a function M<X> -> M<M<Y>>. Next we apply the monadic product to the target to obtain a function M<X> -> M<Y>. Now we can plug in the value of M<X> to obtain a value in M<Y> as desired. This binding operation is used to chain several monadic operations together.
Now lets come to the CompletableFuture example, i.e. CompletableFuture = M. Think of an object of CompletableFuture<MyData> as some computation that's performed asynchronously and which yields an object of MyData as a result some time in the future. What are the monadic operations here?

*

*functoriality is realized with the method thenApply: first the computation is performed and as soon as the result is available, the function which is given to thenApply is applied to transform the result into another type

*the monadic unit is realized with the method completedFuture: as the documentation tells, the resulting computation is already finished and yields the given value at once

*the monadic product is not realized by a function, but the binding operation below is equivalent to it (together with functoriality) and its semantic meaning is simply the following: given a computation of type CompletableFuture<CompletableFuture<MyData>> that computation asynchronously yields another computation in CompletableFuture<MyData> which in turn yields some value in MyData later on, so performing both computations on after the other yields one computation in total

*the resulting binding operation is realized by the method thenCompose
As you see, computations can now be wrapped up in a special context, namely asynchronicity. The general monadic structures enable us to chain such computations in the given context. CompletableFuture is for example used in the Lagom framework to easily construct highly asynchronous request handlers which are transparently backed up by efficient thread pools (instead of handling each request by a dedicated thread).

A: Haskell monads is an interface which specify rules to convert "datatype that is wrapped in another datatype" to another  "datatype that is wrapped in another or same datatype"; the conversion steps is specified by a function you define with a format.
The function format takes a datatype and return "datatype that is wrapped in another datatype". You can specify operations/ calculations during conversion e.g. multiply or lookup something.
It is so difficult to understand because of the nested abstraction. It is so abstracted so that you can reuse the rules to convert datatype in a datatype without custom programming to unwrap the first " datatype that is wrapped in another datatype" before putting the data to your specified function; Optional with some datatype is an example of "datatype in a datatype".
The specified function is any lambda confirming the format.
You don't need to fully understand it; you will write your own reusable interface to solve similar problem. Monad is just exist because some mathematicians already hit and resolve that problem, and create monad for you to reuse. But due to its abstraction, it is difficult to learn and reuse in the first place.
In other words, e.g. Optional is a wrapper class, but some data is wrapped , some not, some function take wrapped data type but some don't, return type can be of type wrapped or not. To chain calling mixture of function which may wrap or not in parameter/return types, you either do your own custom wrap/unwrap or reuse pattern of functor / applicative / monad to deal with all those wrapped/unwrapped combinations of chained function call. Every time u try to put optional to a method that only accept plain value and return optional, the steps are what monad does.


text:
Q: Is it possible to provide a decendent class as a formal parameter in an overriden function and still compile What is the best way to provide a mechanism in which a base class can have a function with a class parameter and a decendant class can override the function with a parameter that is a decendant of the base classes parameter. Confused, let me construct what I am would like to implement below:
Base class
public class BaseReportController
{
    private ActionResult InternalRenderReport(BaseReportModel model)
    {
        ReportExecution execution = this.GetReportExecution(model);
        execution.AddRequiredParameter("DatabaseName", aTargetDatabase);
        execution.AddRequiredParameter("DatabaseServerName", aTargetServer);
        //Send execution into ssrs wrappers to return a report payload
    }

    public virtual ReportExecution GetReportExecution(BaseReportModel model)
    {
        return null;
    }
}

Extended class
public class ExtendedReportController:BaseReportController
{
    public override ReportExecution GetReportExecution(ExtendedFromBaseReportModel model)
    {
        ReportExecution exec = new ReportExecution();
        exec.AddOptionalParameter("SomeID1", model.SomeID1);
        exec.AddOptionalParameter("SomeID2", model.SomeID2);
        return exec;
    }
}

Is there something like an anonymous parameter that would allow me to define ExtendedFromBaseReportModel as the formal parameter in the overridden method and still compile?

A: Use your base class and cast it to derived type inside your method.
public class ExtendedReportController:BaseReportController
{
    public override ReportExecution GetReportExecution(BaseReportModel model)
    {
        var castedModel = (ExtendedFromBaseReportModel) model;
        ReportExecution exec = new ReportExecution();
        exec.AddOptionalParameter("SomeID1", castedModel.SomeID1);
        exec.AddOptionalParameter("SomeID2", castedModel.SomeID2);
        return exec;
    }
}


text:
Q: havin issues inserting data into mysql using vb.net. it's keeps telling me connection already open please i need help, anytime i i try inputting my data in my mysql it's keeps telling that my connection is already open.....pls help..below are my codes
Imports MySql.Data.MySqlClient

Dim str As String = "server=localhost; uid=root; pwd=ksaufcacye; database=dbprofile"
Dim con As New MySqlConnection(str)

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        load()
    End Sub

Sub load()
        Dim query As String = "select * from profile"
        Dim adpt As New MySqlDataAdapter(query, con)
        Dim ds As New DataSet()
        adpt.Fill(ds, "Emp")
        DataGridView1.DataSource = ds.Tables(0)
        con.Close()
        TextBox1.Clear()
        TextBox2.Clear()
        TextBox3.Clear()
        TextBox4.Clear()
End Sub

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        Dim row As DataGridViewRow = DataGridView1.CurrentRow
        Try
            TextBox1.Text = row.Cells(0).Value.ToString()
            TextBox2.Text = row.Cells(1).Value.ToString()
            TextBox3.Text = row.Cells(2).Value.ToString()
            TextBox4.Text = row.Cells(3).Value.ToString()
        Catch ex As Exception

        End Try
End Sub

    Private Sub btnInput_Click(sender As Object, e As EventArgs) Handles btnInput.Click
        Dim cmd As MySqlCommand
        con.Open()
        Try
            cmd = con.CreateCommand
            cmd.CommandText = "insert into profile(id,name,email,website)values(@id,@name,@email,@website);"
            cmd.Parameters.AddWithValue("@id", TextBox1.Text)
            cmd.Parameters.AddWithValue("@name", TextBox2.Text)
            cmd.Parameters.AddWithValue("@email", TextBox3.Text)
            cmd.Parameters.AddWithValue("@website", TextBox4.Text)
            cmd.ExecuteNonQuery()
            con.close
            load()
        Catch ex As Exception

        End Try
End sub