text:
Q: Getting invalid key values from jsonschema using python Is there an easy way to get set of all keys that failed validation of the jsonschema?
I'm using the Draft4Validator from the jsonschema package and I'm validating a json file against some config and using the iter_errors method to iterate through all of the errors. It shows me all of the errors but it would be nice if there was a way to get all of the keys that failed the validation - is this possible?
I've tried going through all of the errors and trying to dig the keys out of the output from the validator but it's getting long and tedious.
EDIT: I am trying to use ErrorTree as per this question: Get the property for each jsonschema errror
def get_errors_in_tree(error_tree):
    errors = []
    if error_tree.total_errors <= 1:
        return map(lambda ve: list(ve.instance.keys()),  error_tree.errors.values())
    for error in error_tree:
        errors.extend(get_errors_in_tree(error_tree[error]))
    return errors

But it's still not giving me ALL of the invalid keys only some of them.
Here is my schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Git Hooks Config",
"description": "Git Hooks Config",
"type" : "object",
"properties" : {
    "git_hooks_config" : {
        "type" : "object",
        "properties" : {
            "prepare_commit_msg": {
                "type" : "object",
                "properties" : {
                    "template" : { "type" : "string" }
                },
                "additionalProperties" : false
            },
            "commit_msg": {
                "type" : "object",
                "properties" : {
                    "regex" : { "type" : "string" },
                    "regex_flags" : {
                        "type" : "array",
                        "items" : {
                            "type" : "string",
                            "enum": [ "T", "TEMPLATE", "I", "IGNORECASE",
                                    "L", "LOCALE", "M", "MULTILINE",
                                    "S", "DOTALL", "U", "UNICODE", "X",
                                    "VERBOSE", "DEBUG", "A", "ASCII" ]
                        }
                    },
                    "error_message" : { "type" : "string" }
                },
                "additionalProperties" : false
            },
            "pre_push": {
                "type" : "object",
                "properties" : {
                    "validate_branch_name" : { "type" : "boolean" },
                    "branch_name_regex" : { "type" : "string" },
                    "branch_name_regex_flags" : {
                        "type" : "array",
                        "items" : {
                            "type" : "string",
                            "enum": [ "T", "TEMPLATE", "I", "IGNORECASE",
                                    "L", "LOCALE", "M", "MULTILINE",
                                    "S", "DOTALL", "U", "UNICODE", "X",
                                    "VERBOSE", "DEBUG", "A", "ASCII" ]
                        }
                    },
                    "branch_name_error_message" : { "type" : "string" }
                },
                "additionalProperties" : false
            },
            "external_git_hooks": {
                "type" : "object",
                "properties" : {
                    "prepare_commit_msg" : {
                        "type" : "object",
                        "properties" : {
                            "relative_path_to_script" : { "type" : "string" },
                            "when_to_execute" : {
                                "type" : "string",
                                "enum" : [ "before", "after" ]
                            }
                        },
                        "additionalProperties" : false
                    },
                    "commit_msg" : {
                        "type" : "object",
                        "properties" : {
                            "relative_path_to_script" : { "type" : "string" },
                            "when_to_execute" : {
                                "type" : "string",
                                "enum" : [ "before", "after" ]
                            }
                        },
                        "additionalProperties" : false
                    },
                    "pre_commit" : {
                        "type" : "object",
                        "properties" : {
                            "relative_path_to_script" : { "type" : "string" },
                            "when_to_execute" : {
                                "type" : "string",
                                "enum" : [ "before", "after" ]
                            }
                        },
                        "additionalProperties" : false
                    },
                    "pre_push" : {
                        "type" : "object",
                        "properties" : {
                            "relative_path_to_script" : { "type" : "string" },
                            "when_to_execute" : {
                                "type" : "string",
                                "enum" : [ "before", "after" ]
                            }
                        },
                        "additionalProperties" : false
                    }
                },
                "additionalProperties" : false
            }
        },
        "additionalProperties" : false
    },
    "repository_properties": {
        "type" : "object",
        "properties" : {
            "unvalidated_patterns" : {
                "type" : "array",
                "items" : { "type" : "array" }
            }
        },
        "additionalProperties" : false
    }
},
"additionalProperties" : false
}

And here is my config
{
"git_hooks_config" : {
    "prepare_commit_msg" : {
        "templadste" : "\nIssue: <JIRA_TICKET_NUMBER>"
    },
    "commit_msg" : {
        "regsex" : ".*",
        "regeax_flags" : [ "DOTALL" ],
        "errdor_message" : "The commit message does not match the supplied regex: '%s'"
    },
    "pre_push" : {
        "validate_branch_name" : true,
        "branch_name_regex" : "^(master|(feature|bugfix|release)/[\\w-]{3,80})$",
        "branch_name_regex_flags" : [ ],
        "branchd_name_error_message" : "The branch name: '%s' does not match the supplied regex: '%s'"
    },
    "external_git_hooks" : {
        "prepare_commit_msg" : {
            "when_to_execute" : "after"
        },
        "commit_msg" : {
            "when_to_execute" : "after"
        },
        "pre_commit" : {
            "when_to_execute" : "after"
        },
        "pre_push" : {
            "when_taso_execute" : "after"
        }
    }
},
"repository_properties" : {
    "unvadlidated_patterns" : [
        [ "*", "src", "test", "*" ],
        [ "*", "src", "generated", "*" ]
    ]
}
}

This is what I get from my method:
[[u'unvadlidated_patterns'], [u'regeax_flags', u'errdor_message', u'regsex'], [u'validate_branch_name', u'branchd_name_error_message', u'branch_name_regex_flags', u'branch_name_regex'], [u'templadste']]
And what I want to get is a list of the following entries:

*

*templadste

*regsex

*regeax_flags

*errdor_message

*branchd_name_error_message

*when_taso_execute

*unvadlidated_patterns

Because these are the ones with actual errors in them.


text:
Q: How to plot error bars for a mean with ggplot2 in R? I have plotted my data as a scatter bar plot and have a benchmark (Basemodel) and a theoretical value (AASHTO) that I am presenting with different colored points. I use the following code and my graph looks as follows:
library(ggplot2)
ggplot(data = plotshear, aes(x = Shear, y = LLDF)) + geom_jitter(aes(colour = Source))

# plotshear data:

      Source     Shear        LLDF
# 1   Baseline   EXT.Single   0.7627894
# 2   Samples    EXT.Single   0.7130376
# 3   Baseline   EXT.Multi    0.8521338
# 4   Samples    EXT.Multi    0.7975502
# 5   Baseline   INT.Single   0.5706947
# 6   Samples    INT.Single   0.5462812
# 7   Baseline   INT.Multi    0.7291602
# 8   Samples    INT.Multi    0.7331171
# 9   AASHTO     EXT.Multi    0.8250000
# 10  AASHTO     INT.Single   0.7200000
# 11  AASHTO     INT.Multi    0.8840000

I actually need a error bar for a mean looking like this:
current plot

plot needed

A: Here is a solution that reproduces the "plot needed" figure from your data:
library(ggplot2)

# plotshear data:
plotshear <- data.frame(Source = c(rep(c("Baseline", "Samples"), 4), rep("AASHTO", 3)),
                        Shear = c(rep("EXT.Single", 2), rep("EXT.Multi", 2), rep("INT.Single", 2),
                                  rep("INT.Multi", 3), "INT.Single", "INT.Multi"),
                        LLDF = c(0.7627894, 0.7130376, 0.8521338, 0.7975502, 0.5706947,
                                 0.5462812, 0.7291602, 0.7331171, 0.8250000, 0.7200000, 0.8840000))

#without error bars
ggplot(data = plotshear, aes(x = Shear, y = LLDF)) +
  geom_boxplot() +
  geom_jitter(aes(color = Source)) +
  stat_summary(fun.y=mean, geom="point", shape=23, size=4) +
  stat_summary(fun.y=mean, geom="line", aes(group=1))

#with error bars
ggplot(data = plotshear, aes(x = Shear, y = LLDF)) +
  geom_boxplot() +
  geom_jitter(aes(color = Source)) +
  stat_summary(fun.y=mean, geom="point", shape=23, size=4) +
  stat_summary(fun.y=mean, geom="line", aes(group=1)) +
  stat_summary(fun.data = mean_se, geom = "errorbar")

redpajama_set_name: RedPajamaStackExchange


text:
Q: How would I capture a "double-click" on a touch-screen device with JavaFX? I'm working on an application that will be released both for desktop and for mobile devices with touch screens. There is a feature which will require the user to double-click (for desktop).
How do I capture a "double-click" on a touch-screen device? Is that even possible?

A: I think you found a solution by now.
But this is how I did it,
I used the MousePressed event with the condition MouseEvent.getClickCount() == 2.


text:
Q: Pre subscript versus tensor What is the best way to typeset \sqcup with two subscripts left/right.
For sure, 1st and 2nd are wrong. But they help us to see the baseline for the indexes.
The 3rd and 4th look equal except by the space around. Also, they insert the index too low (I think).
The 5th produces almost the same but change the baseline for indexes. However it gives me an error (since \sqcup is not an operator).

Limit controls must follow a math operator. $A \sideset{_f}{_g}{\sqcup}

MWE
\documentclass[a5paper]{report}
\usepackage{mathtools}
\usepackage{tensor}

\begin{document}

$A_g  \sqcup_f B$

$A{}_g\sqcup_f B$

$A\prescript{}{g}{\sqcup}_fB$

$A\tensor[_g]{\sqcup}{_f}B$

% $A\sideset{_g}{_f}{\sqcup} B$

\end{document}

A: You should define the symbol as \mathbin:
\documentclass{article}

\newcommand{\dsqcup}[2]{% #1 presubscript, #2 postsubscript
  \mathbin{_{#1}\sqcup_{#2}}%
}

\begin{document}

$A\dsqcup{f}{f}B$

$A\dsqcup{g}{f}B$

\end{document}


text:
Q: Running brew install on mac terminal results in errors brew install hadolint on mac terminal (Monterey) gives the following output
Warning: No available formula with the name "hadolint".
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
Error: No formulae found in taps.
I have tried brew doctor but nothing seems to work


text:
Q: Groupby using 2 different functions syntax I'm using the following statement which works fine to total some columns by Team and Year in an NBA Analytics project.
nba_df =pd.DataFrame(bball_data.groupby(['Tm', 'Year'], as_index = False)['BPM_A', 'WORP', 'VORP', 'PER'].sum())

I would also like to include Average Age, but can't seem to figure out the syntax.
The following statement would work fine on its own but, only returns the average age, not the other sums:
nba_df =pd.DataFrame(bball_data.groupby(['Tm', 'Year'], as_index = False)['Age'].mean())

Basically, I need a way to combine the 2.

A: You could use agg:
nba_df = pd.DataFrame(bball_data.groupby(['Tm', 'Year'], as_index=False).agg(
    {'BPM_A': 'sum', 'WORP': 'sum', 'VORP': 'sum', 'PER': 'sum', 'Age': 'mean'}))


text:
Q: What are the dangers of unsafe user-inputted text in Django? One of my coworkers recently introduced a vulnerability to an in-development page. This allows the user to insert 30 chars of unescaped code that will be executed with the |safe filter. So html unsafe chars (<, >, ', " or &) can be freely inserted into the page template.
The vulnerability exists in a error message on a form, so it does not allow a hacker to edit what is shown to other users, only himself. I wish to show my co-worker the danger of the vulnerability with a horrific example. Also, I'm personally intrigued on a professional level on what the absolute worst case with such a vulnerability like this would be. I know in PHP (possibly older versions) this would allow the user to echo out the contents of server files. Will this vulnerability allow me to similarly show content in the settings file? The Django Devs (bless them) have wisely chosen that { will not be escaped even with the |safe filter. So it cannot be used to show context variables.
The worst I've been able to come up with on my own is insertion (and execution) of any JS file located anywhere on the web, which would be horrific if it could affect other users, but it doesn't seem that bad if the js file will only be executed for the hacker himself.

A: If the error message can be triggered through GET parameters, then you can simply craft a link that executes the JS when the victim clicks it.
ie: http://example.com?email=<script>alert(1)</script>
Otherwise, the only other way (that I can think of) to exploit this would be to use a form on another page (assuming this request is allowed).
<form name="xssForm" action="http://example.com" method="POST">
    <input type="hidden" name="email" value="<script>alert(1)</script>" />
</form>
<script>
    document.xssForm.submit();
</script>

The second option is a CSRF vulnerability, which may or may not exist on your site.
Assuming that this vulnerability only affects the attacker themselves, I think it's ok to say that there is minimal (if any) risk to this implementation, but that all output should be escaped as a standard. No need to overstate the risk of a particular vulnerability.


text:
Q: Using Flexform-FAL Image in Typo3 10.x WITH editor I wonder how to get the editor (image manipulation / crop) in Typo3 Flexform FAL image working. How to run up the FAL inside Flexform is not a big deal, but... how to get the editor? I din't found any solution, so it would be great getting some help.
the reason why I try it in flexform, is that I want ot stay on core functions without using flux and all that horrible stuff just to prevent version chaos....
here is a similar example of how I realsied it in Flexform.
How to create a file upload field in flexform of a custom extbase extension in TYPO3 10?
anyone got a solution get the editor running?
Found a solution
https://blog.wappler.systems/typo3-fal-image-in-flexform/
BUT: how can I use the cropped image in FE?


text:
Q: sails.js(v0.11) cartridge needed for openshift Current version of sails.js is v0.11.
To create application with this version of sails.js in openshift needs cartidge .
I found an older cartidge https://github.com/markschad/openshift-origin-cartridge-nodejs-sails.
Can anyone give an upgraded cartridge ?

A: recently sails have documented the way to host in openshift http://sailsjs.org/documentation/concepts/deployment/hosting as below
To deploy to OpenShift, you'll need to make some minor modifications to your configuration: Open up config/local.js in your app folder. In here, you'll need to add the following lines.
port: process.env.OPENSHIFT_NODEJS_PORT,
host: process.env.OPENSHIFT_NODEJS_IP,

You will also need to install grunt-cli with
npm i --save grunt-cli.

After doing that, create the file
    .openshift/action_hooks/pre_start_nodejs with the following contents. (source)
#!/bin/bash
export NODE_ENV=production

 if [ -f "${OPENSHIFT_REPO_DIR}"/Gruntfile.js ]; then
(cd "${OPENSHIFT_REPO_DIR}"; node_modules/grunt-cli/bin/grunt prod)
 fi

Then create the file /supervisor_opts with the following contents. This tells OpenShift's supervisor to ignore Sails' .tmp directory for the hot reload functionality. (source)
-i .tmp

You can now git add . && git commit -a -m "your message" && git push to deploy to OpenShift.


text:
Q: What does power of '+' in $\hat{\beta}_j=\operatorname {sign} (\hat{\beta^0_j})(|\hat{\beta^0_j}|-\gamma)^+$means? I encountered the following equation in a paper.
$$\hat{\beta}_j=\operatorname {sign} (\hat{\beta^0_j})(|\hat{\beta^0_j}|-\gamma)^+$$
What does the power of '+' mean? The paper can be viewed at:
http://statweb.stanford.edu/~tibs/lasso/lasso.pdf

A: Typically $\alpha^+$ means $\max \{\alpha,0\}$.

A: The notation is usually not meant to be "the power of $+$" but rather "the positive part". For a function $f(t)$, one has
$$
f^+(t)=\max\{f(t),0\}.
$$


text:
Q: What algorithm do browsers commonly use when scaling images with CSS? I am trying to get canvas to render scaled images with the same visual fidelity as CSS does.
According to my tests (done in Chrome Version 43.0.2357.130), it does not seem to be Lanczos3, even though my tests with ResampleScope indicate that it should be.
See Here:

Code used to produce these results:
"CSS":
<img src="temp.png" style="width:200px;height:200px">

"canvas drawImage":
ctxNative.drawImage(img, 0, 0, 200, 200);

"canvas transform":
ctxTransform.transform(200 / img.width, 0, 0, 200 / img.height, 0, 0);
ctxTransform.drawImage(img, 0, 0, img.width, img.height);

"bicubic" (code for bicubic at the bottom)
"bicubic #2"
"downsample alg."
"lanczos3"

A: Here is perhaps a useful links on the matter considering Firefox:
https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering
Thus, sometimes CSS does control the image resize process, but most of the time it doesn't.
According to my tests the image scaling quality varies a lot depending on the state of the browsers internal optimisations, for example, when running in CSS transformations which are considered as "accelerated" the sourcebitmap of NxN may be scaled only once to fixed size, let's say into 200x200 and after that this bitbuffer is scaled to some other dimension MxM, which loses quality since there are two passes and the result could be blurred, if the first buffer size is not big enough, which means you can not determine the result based on the source bitmap only.
This is to say that the resulting image quality may not depend on the original picture quality or size, at least if GPU transformations are used.
In other cases, if there are no restrictions based on CSS rules or the browser does not obey then, it can apply smoothing to images the way it sees best - it could first transform the image using some simple algorithm and if there is enought processor time it could apply second filtering pass to the image to make is sharper using more sophisticated algorithm if it is realistic on the current GPU / device configuration.
I'm sure you are familiar with the subject, but here is a list of possibilities on how to scale an image, so there is plenty of algorithms to choose from:
https://en.wikipedia.org/wiki/Image_scaling
To get more realistic take, you can go straight to the  Chrome's source code,
https://code.google.com/p/chromium/codesearch#chromium/src/skia/ext/image_operations.h&sq=package:chromium&type=cs&rcl=1435318317
// Quality Methods
//
// Those enumeration values express a desired quality/speed tradeoff.
// They are translated into an algorithm-specific method that depends
// on the capabilities (CPU, GPU) of the underlying platform.
// It is possible for all three methods to be mapped to the same
// algorithm on a given platform.

// Good quality resizing. Fastest resizing with acceptable visual quality.
// This is typically intended for use during interactive layouts
// where slower platforms may want to trade image quality for large
// increase in resizing performance.
//
// For example the resizing implementation may devolve to linear
// filtering if this enables GPU acceleration to be used.
//
// Note that the underlying resizing method may be determined
// on the fly based on the parameters for a given resize call.
// For example an implementation using a GPU-based linear filter
// in the common case may still use a higher-quality software-based
// filter in cases where using the GPU would actually be slower - due
// to too much latency - or impossible - due to image format or size
// constraints.
RESIZE_GOOD,

// Medium quality resizing. Close to high quality resizing (better
// than linear interpolation) with potentially some quality being
// traded-off for additional speed compared to RESIZE_BEST.
//
// This is intended, for example, for generation of large thumbnails
// (hundreds of pixels in each dimension) from large sources, where
// a linear filter would produce too many artifacts but where
// a RESIZE_HIGH might be too costly time-wise.
RESIZE_BETTER,

// High quality resizing. The algorithm is picked to favor image quality.
RESIZE_BEST,

The code has enumeration for at least following filters:
    RESIZE_BOX,
    RESIZE_HAMMING1,
    RESIZE_LANCZOS2,
    RESIZE_LANCZOS3,
I suppose you can also find the implementations of those filters in image_operations.cc
https://code.google.com/p/chromium/codesearch#chromium/src/skia/ext/image_operations.cc&sq=package:chromium&type=cs

A: I found an article about using the image-rendering CSS property to control the algorithm. In that article, the author states:

As you can see, the effect is suboptimal – the browser's default
  scaling algorithm (usually bi-linear interpolation) has applied
  anti-aliasing to the image.

(emphasis mine). It also talks about using the image-rendering CSS property to control what algorithm is used.


text:
Q: What is the safe way to replace Ubuntu 12.04 (installed in dual-boot with W7) with OpenSUSE 13.1? This question is related to:
How can I remove Ubuntu from my dual-boot and replace it with another distribution?
Laptop: DELL XPS L502X, 64-bit
Existing OS: Windows 7 + Ubuntu 12.04 (in dual-boot)
I tried to proceed with the installation DVD of OpenSUSE 13.1, at the stage where it asks "New Installation" or "Update an existing system". I do not know what to do next, I am just stuck here, I checked in both the options. The new installation seem to wipe the existing OS and the update will not install the automatic configurations (with all programs).
 I am afraid to loose windows. I do not want to install windows again because it is from the manufacturer when i bought the laptop.
Anyone can provide a step-by-sept guide, or any external link ?

A: You will need to partition your drive for another operating system. Use gparted or similar program to break hard drive into segments. Once you do that, select the particular partition when you install OpenSUSE. Please let me know if you do not understand how to partition a drive.


text:
Q: C# (.NET) WebAPI: Show more items in the call stack I've been trying to debug some reference issues between a C# WebAPI project and a separate class library. For whatever reason, I can call the class library code from a console app, but if I try to call it from a WebAPI project specifically, my application fails with FileNotFound runtime exceptions because it can't find dependencies. I'm guessing it's some weird issue with STA threads/COM but ¯\_(ツ)_/¯
When my application starts, it opens a webpage, and that webpage includes a stack trace with a list of reference exceptions. This stack trace looks like it could be super helpful as it lists in what order references weren't found, but it's really short (it only has three entries). How can I view this entire stack trace? I tried using Visual Studio's Debug > Windows > Call Stack window but it says that only native runtime code is running so it's not supported by the current debug engine.
How can I view more entiries from the stack trace displayed in a C# WebAPI browser window?


text:
Q: How can I make a list plot from three arrays, plotting values of the 2nd and 3rd arrays against the 1st? Very new to Mathematica, so pardon my ignorance.
I am trying to plot x vs y1 and x vs y2 on the same ListPlot.
Here is what the data look like:
x = {1,2,3,4}
y1 = {3,4,5,6]
y2 results from FindIteration and gives me a result like this:
y2 = {{5},{6},{8},{9}}
How can I convert y2 such so it has the same shape as x and y1?
My iteration code is
Do[y2new =
  ynew /. FindInstance[
    function1[x[[i]], ynew] == function2[x[[i]], ynew], ynew, Reals];
 y2[[i]] = ynew, {i, Length[x]}]

Is there a way to change the assignment of y2 values so the resulting array y2 has the same shape as x and y1?

A: x = {1, 2, 3, 4};
y1 = {3, 4, 5, 6};
y2 = {{5}, {6}, {8}, {9}};

To correct y2 when has been already generated, you just need to apply Flatten to y2 and then plot the transpose of x and the flattened y2.
ListPlot[
  {Transpose[{x, y1}], Transpose[{x, Flatten[y2]}]},
  PlotLegends -> SwatchLegend[{"y1", "y2"}]]

Now let's look into generating the flat form of y2 directly. You did provide definitions for the two functions for which you are giving FindInstance, so I will use these two
f1[x_, y_] := Sin[x + 2 π y]
f2[x_, y_] := Cos[x + 2 π y]

I will use Map in its operator form, /@, to generate the list y2. Doing so will make the code much simpler than your Do-loop.
N[FindInstance[f1[#, y] == f2[#, y] && 0 <= y <= 1, y]][[1, 1, 2]] & /@

x

{0.465845, 0.30669, 0.147535, 0.98838}

Note tha t I use the part specification [[1, 1, 2]] to extract the numerical values for the list of instance found by FindInstance. Were I to use the usual extraction method
y /. N[FindInstance[f1[#, y] == f2[#, y] && 0 <= y <= 1, y]] & /@ x

I would get

{{0.465845}, {0.30669}, {0.147535}, {0.98838}}

a list of the same shape as the one that you generate.

A: x = {1, 2, 3, 4}
y1 = {3, 4, 5, 6}
y2 = {{5}, {6}, {8}, {9}}
data = MapThread[{{#1, #2}, {#1, #3}} &, {x, y1, Catenate@y2}]
ListPlot[Transpose@data]


text:
Q: Execute the query on the basis of two columns This is my table on which I want to execute the query on the basis of two columns.I want to execute the query on the basis of first column values. It must pick the first column value if put in the where clause of the case statement.
id  | Service
-------------
123 | 4
124 | 4
125 | 3
126 | 6
-------------

     Select Service
    case when Service = 4 then (select size from table1 where id = {first column value})
    case when Service = 3 then (select size from table2 where id = {first column value})
    case when Service = 6 then (select size from table3 where id ={first column value})
    End as
    Size
    From Services_table

A: I think your query will work if you just replace {first column value} with id, like this:
SELECT Service,
    CASE
        WHEN Service = 4 THEN (SELECT Size FROM Sizes1 WHERE Id = Id)
        WHEN Service = 5 THEN (SELECT Size FROM Sizes2 WHERE Id = Id)
        WHEN Service = 6 THEN (SELECT Size FROM Sizes3 WHERE Id = Id)
    END AS Size
FROM Services_Table

However, JOIN's are (usually) preferable to subqueries, so you could perhaps rewrite this query:
SELECT Service,
    CASE
        WHEN Service = 4 THEN S1.Size
        WHEN Service = 5 THEN S2.Size
        WHEN Service = 6 THEN S3.Size
    END AS Size
FROM Services_Table S
LEFT JOIN Sizes1 S1 ON S.Id = S1.Id
LEFT JOIN Sizes2 S2 ON S.Id = S2.Id
LEFT JOIN Sizes3 S3 ON S.Id = S3.Id

That being said, I'd re-iterate the comment above that queries like this are usually a sign of questionable design choices and you should consider re-working your data structure.

A: I think you just want a correlated subquery.  For this to work you need appropriate qualified column names:
Select Service
       (case when Service = 4
             then (select t1.size from table1 t1 where t1.id = st.id)
             when Service = 3
             then (select t1.size from table1 t2 where t2.id = st.id)
             when Service = 6
             then (select t3.size from table1 t2 where t3.id = st.id)
        end) as Size
From Services_table st


text:
Q: What is the definition of "disjoint cycles"? I'm the one who thinks clear definition(clear with meta-language) is very important for doing mathematics.
Below, i list my definitions for cycle and orbit.

Let $X$ be a nonempty set.
Let $\langle \sigma \rangle$ be the cyclic subgroup generated by $\sigma$, where $\sigma\in S_X$.
Here, $\langle \sigma \rangle$ is a group acting on $X$ in a way that $\sigma^n . x = \sigma^n(x)$ for $x\in X$.
Then, orbit of $\sigma$ is $\langle \sigma \rangle .  x$ for $x\in X$.
(This is consistent with the definition of orbit of a group action)

And below is the definition of cycle.

Let $\sigma$ be a permutation on a set $X$.
Then, $\sigma$ is a cycle iff there exists at most one orbit of $\sigma$ whose cardinality is greater than $1$.

With these definitions, how do one defines "disjoint cycles"?
Below is what i tried to formulate:

Let $\sigma,\tau$ be cycles on $X$.
Then, $\sigma,\tau$ are disjoint iff there does not exist $x\in X$, $| \langle \sigma \rangle . x |>1$ and $| \langle \tau \rangle . x|>1$.

Is this definition fine? Or if there is a clear definition of disjoint cycles please let me know.  Thank you in advance:)

A: That formulation seems fine. What you've written is that $\sigma$ and $\tau$ are disjoint if nontrivial orbits of $\tau$ and $\sigma$ have no intersection.
Another way to think about this: let $X=\{1,\ldots,n\}$. We can express $\sigma=(i_1\,\cdots\,i_s)$ and $\tau=(j_1\,\cdots\, j_t)$, where $i_k,j_l\in X$ are numbers. Then $\sigma$ and $\tau$ are disjoint if and only if $i_k\neq j_l$ for all $k,l$.


text:
Q: PowerShell Converto-html format style I am trying to output powershell result into html file by using code below:
$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:white}"
$a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:white}"
$a = $a + "</style>"

Get-item c:\work | select-object Name,Lastwritetime,@{label="Size" ; expression={[math]::round(((Get-childitem -force "c:\work" -recurse | measure-object length -sum).sum/1Gb),1)}}
get-childitem .....| Convertto-html -head $a | Out-File -append C:\temp\backup.htm
....
....

The result of html file looks like this:

So my question is:
How to have only one Name LastTime Size row on top and how to fix the length of the form ?

A: Each time you use ConvertTo-Html, you are creating a new table. That's why the widths are not consistent.
Get all of your results for the table into a single variable, then convert it to html once. That will create a single html table, with one header, and consistent widths.


text:
Q: Frame layout getting stuck when I hide soft input (Android) I have an Android app (fullscreen, landscape), and I have two Views, one is a FrameLayout that's always visible, and one's a LinearLayout. I set the visibility on the LinearLayout to View.GONE right off the bat. When the user taps a button on the FrameLayout, I set visibility on the LinearLayout to view.VISIBLE, and use the InputMethodManager to show the soft input on an EditText in the LinearLayout. This results in both views being shifted up such that the EditText is on screen just above the keyboard. This is all fine.
The problem arises when I close the soft input. In the same callback, I set the visibility of the LinearLayout (with the EditText) to View.GONE, and what I'm seeing is the FrameLayout getting stuck on top of the screen (it doesn't shift back down). If I don't GONE-ize the LinearLayout, both Views shift back down just fine.
I can work around the issue by starting a timer to wait before setting the visibility to GONE, but I shouldn't have to do that; there should be some notification that I can receive consistently that will indicate when I can hide the LinearLayout.
Things I've tried: hideSoftInputFromWindow with a ResultReceiver (result receiver callback gets invoked pretty well immediately (i.e. before the keyboard actually disappears), view is GONEd too quickly, same problem), overriding onLayout for the LinearLayout (doesn't get invoked when the soft input moves the View up and down), overriding other View "on"s.
The other really annoying thing is this problem seems to be exclusive to my phone - an AT&T Samsung Galaxy SII Skyrocket running Android 4.0.4 (possibly with some Samsung modifications). I can't repro on a 4.0.3 simulator, nor can anyone else repro on other devices with other Android versions.
Any ideas?

A: You're going to have to write your own touch event handler. Here is an example that will slide the whole frameLayout view down when the soft input is hidden. As you can see, it is important to call the super handler and wrap our code in a test for textEdit widgets. If you want to get a look at the calculations, uncomment the debugging logger code.
    @Override
public boolean dispatchTouchEvent(MotionEvent event) {

    View v = getCurrentFocus();
    boolean ret = super.dispatchTouchEvent(event);

    if (v instanceof EditText) {
        View w = getCurrentFocus();

        int scrcoords[] = new int[2];
        w.getLocationOnScreen(scrcoords);
        float x = event.getRawX() + w.getLeft() - scrcoords[0];
        float y = event.getRawY() + w.getTop() - scrcoords[1];

        // Log.d("Activity",
        // "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]);
        if (event.getAction() == MotionEvent.ACTION_UP
                && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w
                        .getBottom())) {

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus()
                    .getWindowToken(), 0);
        }
    }

    return ret;

}


text:
Q: How do deliver marketing emails to Gmail without ending up in spam? I have a question about the email deliverability to primarily Gmail and to some extent, Yahoo and Outlook email users. It's a bit long since I'd like to lay down what I've done and tried so far, so please bear with me.
The Issue: Our marketing emails (in newsletter format, in hotel industry) using several email IaaS and PaaS are ending up in spam for Gmail users. About 10% will receive in Promotions tab.
The Providers: Here are the email IaaS and PaaS services I have been trying so far.

*

*SendGrid (we are using their email API)

*SparkPost

*Mailgun

*ElasticEmail

With each platform:
I've tried both our own dedicated IP addresses AND the platforms' shared IPs.
New domains that haven't been used to send emails
Changed contents of the email completely, including the HTML code (by designing new ones, just in case it's an issue)
DKIM, SPF and all are setup correctly for each domains we used
I've checked all the domains and IPs (both dedicated and shared) against known blacklists and spams using MXTools and such. Everything is okay.
We also checked the emails we're sending using:

*

*www.isnotspam.com

*www.mail-tester.com

Both are recommended by SendGrid. We score highly on both, and according to the analysis results from both, our emails are not considered spam.
We'd also checked our domains and all IPs (both dedicated and shared, from any platforms we mentioned above) using SenderScore. Everything is fine here too.
For dedicated IPs, we did the warm up too. But the issue is, even if we are sending just 1-10 emails for testing and warm up, they do end up in Spam. We aren't even sending to anyone unsolicited. In fact, just for testing purposes, we are sending emails to multiple email addresses owned by our internal team.
I'd talked at length with support team from SendGrid. After checking everything they could think of, they also stated that they can't find anything amiss with our configs, settings, IP and domain reputation and their own infrastucture.
So what gives? I am really out of idea. Please help!
Thanks.


text:
Q: JQuery- Make a Post Request with Authorization I have been trying to figure out way to Post json data using Blogger API 3.0. I do have a idea about GET method so I am able to hit a url an read json data but I am a bit confused about how exactly i can make following request
Adding a post

You can add a post for a blog by sending a POST request to the post collection URI with a post JSON body:

POST https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/
Authorization: /* OAuth 2.0 token here */
Content-Type: application/json

{
  "kind": "blogger#post",
  "blog": {
    "id": "8070105920543249955"
  },
  "title": "A new post",
  "content": "With exciting content..."
}
You must be authenticated to create a post.

I have bee trying to use Blogger API 3 which allows to create new post.
ref: http://code.blogger.com/2012/06/blogger-api-v3.html
Update: I am a bit curious if same thing can be done using Console Application using C# as Programming language.

A: To send post request:
var post_data = {
   "kind": "blogger#post",
   "blog": {"id": "8070105920543249955"},
   "title": "A new post",
   "content": "With exciting content..."
}

$.ajax({
    type: 'POST',
    url: 'your_request_url_here',
    dataType: 'JSON',
    data: post_data,
    complete: function(res) {
       console.log(res);
    }
})


text:
Q: Using fstreams throws an access violation after main returns The following function works fine, showing a text file line by line to stderr:
void load_text(std::string path){
  ifstream f(path);
  char linebuff[100];
  linebuff[99] = 0;
  while(!f.eof()){
    f.getline(linebuff, 99);
    std::cerr<<linebuff<<std::endl;
  }
  f.close();
}

Now, when the main function returns, it throws the following acces violation error:
Unhandled exception at 0x77e58dc9 in app.exe: 0xC0000005: Access violation writing location 0x00000014.
Oddly enough, creating an ifstream, closing it and returning also throws the error
//This also crashes when returning from main
void load_text(std::string path){
  ifstream f(path);
  f.close();
}

Any idea why this happens?
Edit:
The main function (as it is compiled), this actually works provided you create a new project, the difference with the actual program are a lot of never called, never used functions and classes
Right now I'm in the 'cannot reproduce' stage:
#include <fstream>
#include <string>
#include <iostream>

//Using SDL for plotting
#ifdef WIN32
  #pragma comment(lib, "SDL")
  #pragma comment(lib, "SDLMain")
  #pragma comment(lib, "SDL_image")
#endif

int fn(std::string path){
    std::ifstream f(path);
    char linebuff[100];
    linebuff[99] = 0;
    while(!f.eof()){
      f.getline(linebuff, 99);
      std::cerr<<linebuff<<std::endl;
    }
    f.close();
    return 0;
}

int main(int argc, char** argv){
    fn("sscce.cpp");
    return 0;
}

A: For some reason, telling the compiler to use libraries using pragmas is not he same as explicitly setting them in te configuration. By removing the pragmas and putting the .lib files on the linker options it works.
found via: http://www.gamedev.net/topic/600901-lock-file-access-violation/


text:
Q: beta coefficient in Anova with R and XLStat I'm working with the software R and XLStat. I've conducted an one-way ANOVA (my categorical variable is 3 modal (1,2,3) and my response variable is quantitative on scale 1-10).
I've conducted this ANOVA on R and XLStat and the outputs for the F fisher, p-value, coefficient estimations, t-values, std error … are exactly the same.
However, XLstat offers an extra output : the standardized coefficients (called too beta coefficients). Firstly, I was surprised, because I didn't think we could calculate beta coefficient for a categorical variable and according to the bibliography I read, it doesn't have any sense.
Anyway, I tried to find these coefficients with R, thanks to the unique formula I found : beta = estimate * sd(x)/sd(y). sd(x) being the standard deviation of the categorical variable (which is automatically transformed as numeric variable with R, in order to calculate sd(x), seems logical  ) and sd(y) being the standard deviation of my response variable.
The first beta I obtained with R is the same than in XLstat , but not the second and the third. Given that the first one is the same with R and XLStat, I suppose that Xlstat convert too the categorical variable in numeric variable (which is senseless but this is not the question).
Moreover, I conducted the anova on Statistica in order to see if XLStat did any mistake but its outputs for the beta coefficients are the same than in Xlstat …
So, my question is this one : what is the formula to obtain the beta coefficient in a one way Anova ?
Then, I would like to ask you about the relevance of these beta coefficients for a categorical variable. According to my thoughts and publications I read, it doesn't have any sense …
ps contrasts in R and Xlstat are sum(ai)=0. For beta coefficients, XLStat remove the intercept. I guess this fact could be important but I don't know somehow

A: The formula for obtaining beta coefficients from metric coefficients for an ANOVA is the same as for a linear regression. The coefficients have no sensible interpretation (for categorical variables), but standardized coefficients are useful in comparing the relative effects of IVs with different metrics.
In R, either use scale() to transform the data to z-scores before fitting the model, or use lm.beta() instead of lm().
It is not clear why you would obtain different beta coefficients with XLStat, but it could have something to do with degrees of freedom if it's not an error. This example compares the lm.beta() function in R with SAS and obtains the same coefficients.


text:
Q: How to draw pie charts with text labels inside? How to draw pie charts with text labels inside (better if it can be placed on the center position of the corresponding pie)?
To be clear, I want to create something like this, which currently I have to manually edit it in the figure window.

By default, I can only get this (i.e. text labels outside the pie chat):

Edited: My current code:
%% data
data_raw = [68 58];
data = [100-data_raw' data_raw'];

%% draw here
figure

subplot(1,2,1)
h = pie(data(1, :)); % 2D pie chart
hp = findobj(h, 'Type', 'patch');
set(hp(1),'FaceColor',[165/255 165/255 165/255]);
set(hp(2),'FaceColor',[90/255 155/255 213/255]);

subplot(1,2,2)
h2 = pie(data(2, :)); % 2D pie chart
hp2 = findobj(h2, 'Type', 'patch');
set(hp2(1),'FaceColor',[165/255 165/255 165/255]);
set(hp2(2),'FaceColor',[90/255 155/255 213/255]);

A: Following my comment it leads to:
%% data
data_raw = [68 58];
data = [100-data_raw' data_raw'];

%% draw here
figure

subplot(1,2,1)
h = pie(data(1, :)); % 2D pie chart
hp = findobj(h, 'Type', 'patch');
set(hp(1),'FaceColor',[165/255 165/255 165/255]);
set(hp(2),'FaceColor',[90/255 155/255 213/255]);

subplot(1,2,2)
h2 = pie(data(2, :)); % 2D pie chart
hp2 = findobj(h2, 'Type', 'patch');
set(hp2(1),'FaceColor',[165/255 165/255 165/255]);
set(hp2(2),'FaceColor',[90/255 155/255 213/255]);

hText = findobj(h,'Type','text');
textPositions_cell = get(hText,{'Position'}); % cell array
textPositions = cell2mat(textPositions_cell); % numeric array
textPositions = textPositions * 0.4; % scale position
set(hText,{'Position'},num2cell(textPositions,[3,2])) % set new position

hText = findobj(h2,'Type','text');
textPositions_cell = get(hText,{'Position'}); % cell array
textPositions = cell2mat(textPositions_cell); % numeric array
textPositions = textPositions * 0.4; % scale position
set(hText,{'Position'},num2cell(textPositions,[3,2])) % set new position

A: A simpler method is to multiple the positions of the current labels by one half:
%% data
data_raw = [68 58];
data = [100-data_raw' data_raw'];

%% draw here
figure

subplot(1,2,1)
h1 = pie(data(1, :)); % 2D pie chart
h1(1).FaceColor = [165/255 165/255 165/255];
h1(2).Position = 0.5*h1(2).Position;
h1(3).FaceColor = [90/255 155/255 213/255];
h1(4).Position = 0.5*h1(4).Position;

subplot(1,2,2)
h2 = pie(data(2, :)); % 2D pie chart
h2(1).FaceColor = [165/255 165/255 165/255];
h2(2).Position = 0.5*h2(2).Position;
h2(3).FaceColor = [90/255 155/255 213/255];
h2(4).Position = 0.5*h2(4).Position;

As the above code suggests, the handles comes in pairs, i.e., first a patch (piece of pie) then a text (the label). Thus, for an arbitrary number of labels, the following will work:
%% arbitrary number of slices
data = rand(1,5);
labels = {'One','Two','Three','Four','Five'};
pieHandle = pie(data,labels);

%% reposition labels
for iHandle = 2:2:2*numel(labels)
    pieHandle(iHandle).Position = 0.5*pieHandle(iHandle).Position;
end

This is the result:


text:
Q: php bind_param number of variables doesn't match number of parameters (mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement)

I made a users class to handle registration login and profile updates and it all works. However I to receive the above error when a user updates their profile. Lets go step by step.
First I have the form
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">

        First Name:
        <input type="text" name="firstName" id="firstName" value="<?php echo $_SESSION['firstName']; ?>">

        Last Name:
        <input type="text"  name="lastName" id="lastName" value="<?php echo $_SESSION['lastName']; ?>">

        Username:
        <input type="text"  name="username" id="username" value="<?php echo $_SESSION['username']; ?>">

        Email:
        <input type="email" name="email" id="email" value="<?php echo $_SESSION['email']; ?>">

        Profile Image:
        <input type="file" name="file" id="file">

        Bio:
        <textarea type="text" name="bio" id="bio"></textarea>

         <input type="submit" name="update" value="Submit Updates" class="btn black pull-left">

</form>

then I have the upload class that handles the file upload portion of things. This works fine and is used in my users class.
class Upload
{
    public function uploadImages()
    {
        if (isset($_POST['update'])) {
            if (isset($_FILES['file'])) {
                $fileName = $_FILES['file']['name'];
                $fileName = mt_rand(100000, 999999) . $fileName;
                $fileName = preg_replace('#[^a-z0-9.]#i', '', $fileName);
                $fileTmp = $_FILES['file']['tmp_name'];
                $fileType = $_FILES['file']['type'];
                $fileSize = $_FILES['file']['size'];
                $fileError = $_FILES['file']['error'];
                $extensions = array('jpg', 'jpeg', 'png', 'tif', 'tiff', 'gif', '');
                $tmp = explode('.', $fileName);
                $fileExtension = strtolower(end($tmp));

                // if (!$fileTmp) {
                //     die('No File Selected, Please try again - Try Again?');
                // }
                if ($fileSize > 2097152) {
                    die('Error, File too big - Try Again?');
                }
                if (in_array($fileExtension,$extensions) === false and $fileError === 4) {
                    move_uploaded_file($fileTmp, CURRENTROOT . '../img/upload/profiles/'.$fileName);
                    $GLOBALS['fileName'] = $fileName;
                } elseif (in_array($fileExtension,$extensions) === false) {
                    die('Acceptable file types are jpg, png, tif, and gif - Try Again?');
                } else {
                     move_uploaded_file($fileTmp, CURRENTROOT . '../img/upload/profiles/'.$fileName);
                     $GLOBALS['fileName'] = $fileName;
                 }
            }
        }
    }
}

This is the users class that handles registration, log in and profile updating. This also works sort of. It does everything its intended to do however it does return the above arrow. I'm going to leave out the rest of the class and just show the relevant method.
public function userProfileEdit()
{
    $upload = new Upload();
    $upload->uploadImages();

    $userID = $_SESSION['userID'];
    $result = $this->con->db->query('SELECT * FROM users WHERE userID="'.$userID.'"');
    $row = $result->fetch_array(MYSQLI_BOTH);

    $_SESSION['firstName'] = $row['firstName'];
    $_SESSION['lastName'] = $row['lastName'];
    $_SESSION['username'] = $row['username'];
    $_SESSION['email'] = $row['email'];
    $_SESSION['profileImage'] = $row['profileImage'];
    $_SESSION['bio'] = $row['bio'];

    if (!empty($_POST)) {
        if (isset($_POST['update'])) {
            trim($updateFirstName = $_POST['firstName']);
            trim($updateLastName = $_POST['lastName']);
            trim($updateUsername = $_POST['username']);
            trim($updateEmail = $_POST['email']);
            trim($updateProfileImage = $GLOBALS['fileName']);
            trim($updateBio = $_POST['bio']);

            $insert = $this->con->db->prepare('UPDATE users SET
                firstName="'.$updateFirstName.'",
                lastName="'.$updateLastName.'",
                username="'.$updateUsername.'",
                email="'.$updateEmail.'",
                profileImage="'.$updateProfileImage.'",
                bio="'.$updateBio.'"
                WHERE userID = '.$userID);

            $insert->bind_param('sssssss', $updateFirstName, $updateLastName, $updateUsername, $updateEmail, $updateProfileImage, $updateBio, $userID);
            if ($insert->execute()) {
                $GLOBALS['profileUpdated'] = '
Your profile has been updated.  Refresh to see changes.
';
            }
        }
    }
}

So the scripts work and the file is uploaded and the info is sent to the database. As far as I can see the number of prepared vars is the same as in the bind_param. I have tried included and excluding the $userID from the prepare and bind. Why am I getting the error? I am especially confused because even though I get the error everything works.

A: You get the error because you bind 7 params to the query, but don't use any of them. Instead you insert the variables directly into the query, which leads to the data being (insecurely) inserted into the database.
$insert = $this->con->db->prepare('UPDATE users SET
            firstName="'.$updateFirstName.'",
            lastName="'.$updateLastName.'",
            username="'.$updateUsername.'",
            email="'.$updateEmail.'",
            profileImage="'.$updateProfileImage.'",
            bio="'.$updateBio.'"
            WHERE userID = '.$userID);

should be
$insert = $this->con->db->prepare('UPDATE users SET
            firstName= ?,
            lastName= ?,
            username= ?,
            email= ?,
            profileImage= ?,
            bio= ?
            WHERE userID = ?');

read more: http://php.net/manual/en/mysqli-stmt.bind-param.php


text:
Q: Strange H_RESULT E_FAIL error with Remote Desktop Connection in C# I'm using the com component Microsoft RDP Client Control version 8 in C# to connect to terminal servers and remote desktops.
The code looks something like this:
if (rdp.Connected.ToString() == "1")
{
  rdp.Disconnect();
}
rdp.Server = userDetails.RoleMachine;
rdp.UserName = userDetails.UserName;
IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
secured.ResetPassword();
secured.ClearTextPassword = userDetails.Password;

This works the first time, to either a Remote Desktop or Terminal Services Server but fails on subsequent calls with an "H_RESULT E_FAIL" error, stack trace beneath.
How can I allow someone to reconnect to somewhere else from the same form (i.e. what do I need to clean up before changing properties and attempting a connect() ?)
at MSTSCLib.IMsRdpClient7.set_Server(String pServer)
at AxMSTSCLib.AxMsRdpClient7.set_Server(String value)
at RDP.FrmRemote.Connect() in \\..\FrmRemote.cs:line 56
at RDP.FrmRemote.Operations1_Click(Object sender, EventArgs e) in  \\...\FrmRemote.cs:line 157
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32  clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)

A: The answer turned out to be quite simple.
A call to Disconnect() is asynchronous.
I had to handle the ActiveX control's OnDisconnect event, not attempting to Connect() again until it had fired, e.g. completely disconnected.


text:
Q: Memory Leak Example -references and objects I have the below method.Suppose i call A.m1() 10,000 times from class B.
So all 10,000 MyObj  objects will be garbage collected as their scope is only within the m1() method.
There is no memory leak?
class A {
    String m1() {
        MyObj obj = new Mybj();
    }
}

And i call it below
class B {
    void m2() {
        String s = classAObj.m1();
    }
}

A: I think you have a C++ background. In Java, it's quite hard to get a memory leak because of its garbage collection system. Garbage collection can get complicated, but the basic idea is there is a program constantly running in the background looking in the heap for an unused object, and when it finds one, it deletes it. So when you exit the m1() method, there are no references to the new Mybj() object so the garbage collector deletes it.

A: The references created in the method are eventually garbage collected when they go out of scope.  But it doesn't necessary happen immediately.
Here is a demo that shows that the references are collected.  But first
some terms.

*

*hard reference - A normal reference to an object that will be around until it is garbage collected.  These are the typical instance values resulting from object creation.

*weak references - references that point to the same object as a hard reference.  When a hard reference is garbage collected, the associated weak references are also collected.

How this works.

*

*The method m1 is called n times, each time creating a weak reference of an instance of A and returning it.

*This is then added to a list.

*Once the hard references are garbage collected, the weak references that refer to the same objects will also be collected

*The weak reference will then return null when trying to retrieve its associated object.

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class GarbageCollection {

    public static void main(String[] args) {
        // get out of static context
        new GarbageCollection().start();
    }
    public void start() {

        int n = 10_000;
        List<WeakReference<A>> weak = new ArrayList<>();

Create n weak references of A by calling m1 and returning the reference.
Then it add to the List.
        for (int i = 0; i < n; i++) {
            WeakReference<A> wk = m1();
            weak.add(wk);
        }

Now iterate thru the List of weak references to see how many are null.
Zero is expected since the garbage collector has not yet run. All of those A allocations created in m1 are still lurking around in the heap.
        int count = 0;
        for (WeakReference<A> wk : weak) {
            if (wk.get() == null) {
                count++;
            }
        }

        System.out.println(count); // probably zero

Now repeat the same process but explicitly invoke the garbage collector.
        count = 0;
        System.gc();
        for (WeakReference<A> wk : weak) {
            if (wk.get() == null) {
                count++;
            }
        }

At this point, count should be non-zero (or possibly n for small values of n) to show some or all of the objects have been collected.
        System.out.println(count);
    }

    public WeakReference<A> m1() {
       A a = new A();
       return new WeakReference<>(a);
    }
}

class A {
}


text:
Q: shell scripting error logging I'm trying to setup a simple logging framework in my shell scripts. For this I'd like to define a "log" function callable as
log "LEVEL" $message

Where the message is a variable to which I have previously redirected the outputs of executed commands. My trouble is that I get errors with the following
{message=command 2>&3 1>&3 3>&-} >&3
log "INFO" $message

There's something wrong isn't there?
TIA

A: I've developed a simple multi-level logger for my shell scripts, you can take a look for use,  inspiration, or whatever you want.

A: Perhaps you want:
message=$( command 2>&1 )
log INFO "$message"

A: It's not entirely clear that your problem is related to logging (it looks like your trouble is capturing the text to log, which glenn jackman has ably suggested a solution for), but just in case, you might wish to be aware of the logger command found on most Unix systems—it provides shell scripts the ability to write the system log.  It has various levels and priorities and everything.  Very handy.

A: In addition to the $(), you need to use spaces and a semicolon with your curly braces (if you even need them):
{ command; }


text:
Q: Where is the timestamp in this script that sets the prompt? I came across this old post, which I find useful. Now, I'm trying hard, but in vain, to tell which part of it is responsible for printing the timestamp at the end of the dashes.
The following is the script for ease of reference:
# Fill with minuses
# (this is recalculated every time the prompt is shown in function prompt_command):
fill="—- "
reset_style='\[\033[00m\]'
status_style=$reset_style'\[\033[0;90m\]' # gray color; use 0;37m for lighter color
prompt_style=$reset_style
command_style=$reset_style'\[\033[1;29m\]' # bold black

# Prompt variable:
PS1="$status_style"'$fill \t\n'"$prompt_style"'${debian_chroot:+($debian_chroot)}\u@\h:\w\$'"$command_style "

# Reset color for command output
# (this one is invoked every time before a command is executed):
trap 'echo -ne "\e[0m"' DEBUG

function prompt_command {
    # create a $fill of all screen width minus the time string and a space:
    let fillsize=${COLUMNS}-9
    fill=""
    while [ "$fillsize" -gt "0" ]
    do
        fill="-${fill}" # fill with underscores to work on
        let fillsize=${fillsize}-1
    done

    # If this is an xterm set the title to user@host:dir
    case "$TERM" in
    xterm*|rxvt*)
        bname=`basename "${PWD/$HOME/~}"`
        echo -ne "\033]0;${bname}: ${USER}@${HOSTNAME}: ${PWD/$HOME/~}\007"
        ;;
    *)
        ;;
    esac
}

PROMPT_COMMAND=prompt_command

Any hint?

A: It's the \t in this line that composes the whole prompt, incorporating the variables (including fill which gives the dashes) that have been assigned:
PS1="$status_style"'$fill \t\n'"$prompt_style"'${debian_chroot:+($debian_chroot)}\u@\h:\w\$'"$command_style "

In PS1, \t is a Bash escape sequence that prints the current time.
Test:
zanna@toaster:~$ PS1="\t"
21:33:06


text:
Q: How to truncate a file in FAT32 file system without zero padding in C? I have 2TB HDD contains a single partition of FAT32 file system. While truncating a file to larger size say 100MB or 200MB using ftruncate(), it takes time of 5 to 10 seconds to do zero padding. Is there any way of file truncation that take a less time or do it without zero padding?

A: No.  Ftruncate specifically adds zeros to the end according to the GNU C library page.  It also says you could try and just use truncate, and it will try to fill it with holes instead, but this isn't supported on all machines so you might not be able to do that.
You could try and hack the file system by opening the inode and changing the value to make the File system think the file is larger, but this is a security issue.


text:
Q: Which of these these two sentences is correct?
*

*You must be thinking I am mad.

*You must think I am mad.
Although, both the sentences don't seem to be wrong and seem to convey the same meaning, I want to know which of the two is correct ?

A: You mean 'neither of the sentences seems to be wrong', which is true. The difference is that (2) could refer to a person's general opinion of the speaker (they always think he/she is mad), while (1) describes their current state of mind (I'm doing something that seems crazy, so you must be thinking right now that I am mad).


text:
Q: How do I solve this system of modular equations? How do I solve this system of modular equations?
$2=(4+6a)k_1^{-1}\bmod19 $
$11=(3+6b)k_1^{-1}\bmod19$
$8=(5+5a)k_2^{-1}\bmod19$
$6=(18+5b)k_2^{-1}\bmod19$
I want to get the values for $a, b, k_1$, and $k_2$. Note that $k^{-1}$ denotes the modular inverse (mod $19$) of $k$.
How do I solve this? Or are there infinitely many solutions?

A: Multiply all congruences by $k_1$ or $k_2$ as appropriate. This gives a linear system:
$$2k_1=4+6a\bmod19$$
$$11k_1=3+6b\bmod19$$
$$8k_2=5+5a\bmod19$$
$$6k_2=18+5b\bmod19$$
Now $19$ is a prime number, so we can solve this as if it were over $\mathbb Q$, treating all divisions as multiplications by inverses. We get the following set of solutions (modulo $19$ of course):
$$(k_1,k_2,a,b)=(5,6,1,15)+(4,4,14,1)t\qquad t\in\mathbb Z;k_1,k_2\ne0$$

A: Solving in pari/gp.
Find $k_1$:
(4+6*a)/Mod(2,19)=Mod(3, 19)*a + Mod(2, 19)
and
(3+6*b)/Mod(11,19)=Mod(4, 19)*b + Mod(2, 19)
i.e. $k_1\equiv 2+3a\equiv 2+4b \pmod{19}$
Find $k_2$:
(5+5*a)/Mod(8,19)=Mod(3, 19)*a + Mod(3, 19)
and
(18+5*b)/Mod(6,19)=Mod(4, 19)*b + Mod(3, 19)
i.e. $k_2\equiv 3+3a\equiv 3+4b \pmod{19}$
Find $a$ from $3a\equiv 4b \pmod{19}$
4*b/Mod(3,19)=Mod(14, 19)*b
i.e. $a\equiv 14b \pmod{19}$
Thus $(k_1,k_2,a,b) \equiv (2,3,0,0) + (4b,4b,14b,b) \pmod{19}$
Verify in W.Mathematica:
Solve[{2*k1==4+6*a,11*k1==3+6*b,8*k2==5+5*a,6*k2==18+5*b},{k1,k2,a,b},Modulus->19]/.C[1]->b=
{{k1 -> 2 + 4 b, k2 -> 3 + 4 b, a -> 14 b, b -> b}}


text:
Q: Android app not permitting cleartext traffic inspite of adding xml permissions I'm trying to access a development server API using nativescript-vue. I have added all the possible permissions in the android manifest, but it's giving the error: JS: Error: java.io.IOException: Cleartext HTTP traffic to url not permitted
Here is my manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

<application
        android:usesCleartextTraffic="true"
        android:name="com.tns.NativeScriptApplication"
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:cleartextTrafficPermitted="true"
        android:usesCleartextTraffic="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:theme="@style/AppTheme">

Here is the network_security_config.xml file:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
       <domain includeSubdomains="true">192.168.xxx.xxx</domain>
   </domain-config>
</network-security-config>

And here is the Nativescipt-vue code:
httpModule.request({
        url: "http://192.168.XXX.XXX:XXXX/func",
        method: "POST",
        headers: { "Content-Type": "application/json" },
        content: data
      }).then((response) => {
        const result = response.content.toJSON();
      }, (e) => {
        console.error(e);
      });

A: For those who face the same issue, tns platform remove android and tns platform add android worked for me. It started reading the updated manifest after this.

A: Go in to App_Resources -> Android -> src\main -> AndroidManifest.xml add android:usesCleartextTraffic="true" go to the application xml section then do a tns update resources cmd.


text:
Q: Unable to provide access to Key Vault for Managed instance using powershell I have a requirement to grant and remove access to TDE keys in Keyvault for Managed Instances using powershell.
As per the below documentation, Microsoft suggests to use the below code to get the objectid of the Managed instance and use it to set the policy in the key vault
https://learn.microsoft.com/en-us/powershell/module/az.sql/add-azsqlinstancekeyvaultkey?view=azps-4.4.0
$managedInstance = Get-AzSqlInstance -Name 'ContosoManagedInstanceName' -ResourceGroupName 'ContosoResourceGroup' Set-AzKeyVaultAccessPolicy -VaultName ContosoVault -ObjectId $managedInstance.Identity.PrincipalId -PermissionsToKeys get, wrapKey, unwrapKey

But the above command doesn't work for me because the identity property, which i have marked in red is empty

I checked all the MI's in our inventory and they are all empty, But I can assign permissions to the Keys in the vault easily using the Azure portal, which also shows the GUID(object id) of the Managed instance while selecting the principal. Does anyone know why the identity property is empty for Get-AzSqlInstance, is there any other way I can accomplish this using PowerShell?

A: You can assign identity to your MI with the CmdLet : Set-AzSqlInstance (See : -AssignIdentity parameter https://learn.microsoft.com/en-us/powershell/module/az.sql/set-azsqlinstance?view=azps-5.1.0)
BR.


text:
Q: Trying to call Oracle MAIL_PKG with arrays and getting PLS-00201: identifier 'MAIL_PKG.ARRAY' must be declared I need to create a simple PL/SQL program which will:
a) get a current number of active session on db from v$session
b) compare the result to average active session baseline (i collect the data on table on user1 schema by simple job running every 5 minutes)
If a > b then an email should be send to a defined recipents - I have a whole mailing package on oracle on schema1. But whenever I try to run the following code:
 declare
  SESS_COUNT NUMBER;
  SESS_AVG NUMBER;
  SUB           VARCHAR2(500);
  BODY          VARCHAR2(500);
  INSTANCE_NAME VARCHAR(200);
  HOST_NAME     VARCHAR(500);

BEGIN
 SELECT COUNT(*)
 INTO SESS_COUNT
 FROM v$session
WHERE status='ACTIVE';

SELECT ROUND(AVG(SESS_COUNT))
INTO SESS_AVG
FROM user1.SESS_ACTIVE;

IF SESS_COUNT > SESS_AVG

  THEN
   SELECT INSTANCE_NAME INTO INSTANCE_NAME FROM V$INSTANCE;
    SELECT HOST_NAME INTO HOST_NAME FROM V$INSTANCE;
    SUB  := INSTANCE_NAME || '@' || HOST_NAME ||' - MAIL_TOPIC';
    BODY := 'MAIL_BODY:'|| SESS_COUNT;
    SCHEMA1.MAIL_PKG.SEND_MAIL(INSTANCE_NAME || '_'|| HOST_NAME||'@domain1', MAIL_PKG.ARRAY('user.123@net.ca'), SUB, BODY);
  END IF;
END;

I get error:
ORA-06550: line 26, column 79:
PLS-00201: identifier 'MAIL_PKG.ARRAY' must be declared

I will be grateful for any tips - I tried to declare MAIL_PKG.ARRAYS in various ways, but nothing works.


text:
Q: How can I retrieve old data from Kafka to store in Mongodb How can i transfer old data from Kafka to MongoDB database, I had changed the topic of Kafka so because of that there was old data it did not come in MongoDB so how can I do it?
If I try to retrieve data from old topic then I get poll timeout error.

A: Unclear how you define "old".
Kafka actively removes data from topics with retention policies. If data is deleted, you can never consume it.
While it is still retained, you simply set auto.offset.reset=earliest (in Connect, you add consumer. prefix to this and put in the worker properties file, not the connector itself), and start polling. Timeout errors are separate issue, and have nothing to do with retention time of the topic. By default, any consumer or connector will set this property to latest and not see retained data


text:
Q: How to get the current region DateFormat like "dd/mm/yyyy" I'm using the System.Windows.Controls.DatePicker control. This control allows the user to select a date in the calendar, but also to write directly a date.
I'm looking to give users the information on how to write this date.
So I'm basically looking for a way to display the format of a general date (not a specific date)
I know the following:
DateTime dt = DateTime.Now;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine(dt.ToString("d")); //  Gives 7/9/2001

It looks like the DatePicker uses the "d" format, so I'm looking for a way to get the following string "dd/mm/yyyy"
On the French (canada) region, it's "yyyy-mm-dd" for example
Thanks a lot!

A: When you get a CultureInfo object, it has a DateTimeFormat property on it.  That has a ShortDatePattern property which shows the pattern it uses to format dates.
From the linked MSDN article:
public class SamplesDTFI
{
   public static void Main()
   {
      string[]  cultures = { "en-US", "ja-JP", "fr-FR" };
      DateTime date1 = new DateTime(2011, 5, 1);

      Console.WriteLine(" {0,7} {1,19} {2,10}\n", "CULTURE", "PROPERTY VALUE", "DATE");

      foreach (var culture in cultures) {
         DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture(culture).DateTimeFormat;
         Console.WriteLine(" {0,7} {1,19} {2,10}", culture,
                           dtfi.ShortDatePattern,
                           date1.ToString("d", dtfi));
      }
   }
}
// The example displays the following output:
//        CULTURE      PROPERTY VALUE       DATE
//
//          en-US            M/d/yyyy   5/1/2011
//          ja-JP          yyyy/MM/dd 2011/05/01
//          fr-FR          dd/MM/yyyy 01/05/2011

A: You use the DateTimeFormatInfo object you get from the CultureInfo.  There are some properties on the DateTimeFormatInfo that end with "Pattern".  Here is a list I generated:
Current culture: en-US

Property                             Format                                Result
--------------------                 -----------------------------         -------------
FullDateTimePattern                : dddd, MMMM dd, yyyy h:mm:ss tt      - Thursday, February 04, 2016 3:51:17 PM
LongDatePattern                    : dddd, MMMM dd, yyyy                 - Thursday, February 04, 2016
LongTimePattern                    : h:mm:ss tt                          - 3:51:17 PM
MonthDayPattern                    : MMMM dd                             - February 04
RFC1123Pattern                     : ddd, dd MMM yyyy HH':'mm':'ss 'GMT' - Thu, 04 Feb 2016 15:51:17 GMT
ShortDatePattern                   : M/d/yyyy                            - 2/4/2016
ShortTimePattern                   : h:mm tt                             - 3:51 PM
SortableDateTimePattern            : yyyy'-'MM'-'dd'T'HH':'mm':'ss       - 2016-02-04T15:51:17
UniversalSortableDateTimePattern   : yyyy'-'MM'-'dd HH':'mm':'ss'Z'      - 2016-02-04 15:51:17Z
YearMonthPattern                   : MMMM, yyyy                          - February, 2016

As you can see, your desired result "dd/mm/yyyy" isn't there.  To get it, you'll have to hardcode it.
For the curious (the following code isn't meant to answer the question), this is the code I used to generate the above table:
var culture = CultureInfo.CurrentCulture;
var fmt = culture.DateTimeFormat;
Debug.WriteLine("Current culture: " + culture.Name);
foreach (var prop in fmt.GetType().GetProperties().Where(p => p.Name.EndsWith("Pattern")))
{
    var pattern = prop.GetValue(fmt) as string;
    Debug.WriteLine("{0,-35}: {1,-35} - {2}", prop.Name, pattern, DateTime.Now.ToString(pattern));
}

A: Use Console.WriteLine(dt.ToString("dd/MM/yyyy"));


text:
Q: don't start Android application in React native Finally i could resolve by making new project.
and copy code and add library one by one.
i could clean my project.
it means i could throw unneeded libraries and something.
thank you!
i'm trying to use react-native-webview for my application.
In iOS,it works well.
In Android ,it doesn't.
And unfortunatelly,i don know the reason.
i reserched a lot.
unfortunatelly,i still have a problem.
it produced this error on Android studio.
because it doesn't produces any error by running this command.
react-native run-android

so i can't understand why it doesn't work.
so i tried to build it on android studio,then it produced this error.
2020-04-29 00:34:25.444 19491-19530/com.hiratsuka_react_native_test E/SoLoader: couldn't find DSO to load: libhermes.so
2020-04-29 00:34:25.446 19491-19530/com.hiratsuka_react_native_test E/AndroidRuntime: FATAL EXCEPTION: create_react_context
Process: com.hiratsuka_react_native_test, PID: 19491
java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so
    at com.facebook.soloader.SoLoader.doLoadLibraryBySoName(SoLoader.java:789)
    at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:639)
    at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:577)
    at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:525)
    at com.facebook.hermes.reactexecutor.HermesExecutor.<clinit>(HermesExecutor.java:20)
    at com.facebook.hermes.reactexecutor.HermesExecutorFactory.create(HermesExecutorFactory.java:27)
    at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:952)
    at java.lang.Thread.run(Thread.java:764)

my env is here.
react-native-cli: 2.0.1
react-native: 0.61.5

      {
    "name": "hiratsuka_react_native_test",
    "version": "0.0.1",
    "private": true,
    "scripts": {
      "android": "react-native run-android",
      "ios": "react-native run-ios",
      "start": "react-native start",
      "test": "jest",
      "lint": "eslint .",
      "storybook": "start-storybook -p 7007"
    },
    "dependencies": {
      "@expo/vector-icons": "^10.0.6",
      "@react-native-community/masked-view": "^0.1.7",
      "@react-navigation/bottom-tabs": "^5.2.0",
      "@react-navigation/native": "^5.0.9",
      "@react-navigation/stack": "^5.1.1",
      "@unimodules/core": "^5.0.0",
      "axios": "^0.19.2",
      "expo-asset": "^8.0.0",
      "expo-constants": "^8.0.0",
      "expo-font": "^8.0.0",
      "jest-worker": "^25.2.6",
      "react": "16.9.0",
      "react-native": "0.61.5",
      "react-native-elements": "^1.2.7",
      "react-native-fast-image": "^8.1.5",
      "react-native-gesture-handler": "^1.6.0",
      "react-native-get-random-values": "^1.4.0",
      "react-native-reanimated": "^1.7.0",
      "react-native-safe-area-context": "^0.7.3",
      "react-native-screens": "^2.2.0",
      "react-native-unimodules": "^0.8.1",
      "react-native-webview": "^9.3.0",
      "react-navigation": "^4.3.4",
      "realm": "5.0.0",
      "typescript": "^3.7.0-beta"
    },
    "devDependencies": {
      "@babel/core": "7.8.7",
      "@babel/runtime": "7.8.7",
      "@react-native-community/eslint-config": "0.0.5",
      "@storybook/addon-actions": "^5.3.17",
      "@storybook/addon-links": "^5.3.17",
      "@storybook/addons": "^5.3.17",
      "@storybook/react-native": "^5.3.17",
      "@storybook/react-native-server": "^5.3.17",
      "babel-jest": "24.9.0",
      "babel-loader": "^8.0.6",
      "eslint": "^5.0.0",
      "jest": "24.9.0",
      "metro-react-native-babel-preset": "0.56.4",
      "react-dom": "^16.9.0",
      "react-native-storybook-loader": "^1.8.1",
      "react-test-renderer": "16.9.0"
    },
    "jest": {
      "preset": "react-native"
    }
  }

i tried to clean cache,change gradle,or something.but it didn't work.
before using react-native-webview,it worked well.
please help.
app/build.gradle is here.
      apply plugin: "com.android.application"

  import com.android.build.OutputFile

  /**
   * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
   * and bundleReleaseJsAndAssets).
   * These basically call `react-native bundle` with the correct arguments during the Android build
   * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
   * bundle directly from the development server. Below you can see all the possible configurations
   * and their defaults. If you decide to add a configuration block, make sure to add it before the
   * `apply from: "../../node_modules/react-native/react.gradle"` line.
   *
   * project.ext.react = [
   *   // the name of the generated asset file containing your JS bundle
   *   bundleAssetName: "index.android.bundle",
   *
   *   // the entry file for bundle generation
   *   entryFile: "index.android.js",
   *
   *   // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
   *   bundleCommand: "ram-bundle",
   *
   *   // whether to bundle JS and assets in debug mode
   *   bundleInDebug: false,
   *
   *   // whether to bundle JS and assets in release mode
   *   bundleInRelease: true,
   *
   *   // whether to bundle JS and assets in another build variant (if configured).
   *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
   *   // The configuration property can be in the following formats
   *   //         'bundleIn${productFlavor}${buildType}'
   *   //         'bundleIn${buildType}'
   *   // bundleInFreeDebug: true,
   *   // bundleInPaidRelease: true,
   *   // bundleInBeta: true,
   *
   *   // whether to disable dev mode in custom build variants (by default only disabled in release)
   *   // for example: to disable dev mode in the staging build type (if configured)
   *   devDisabledInStaging: true,
   *   // The configuration property can be in the following formats
   *   //         'devDisabledIn${productFlavor}${buildType}'
   *   //         'devDisabledIn${buildType}'
   *
   *   // the root of your project, i.e. where "package.json" lives
   *   root: "../../",
   *
   *   // where to put the JS bundle asset in debug mode
   *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
   *
   *   // where to put the JS bundle asset in release mode
   *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
   *
   *   // where to put drawable resources / React Native assets, e.g. the ones you use via
   *   // require('./image.png')), in debug mode
   *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
   *
   *   // where to put drawable resources / React Native assets, e.g. the ones you use via
   *   // require('./image.png')), in release mode
   *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
   *
   *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
   *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
   *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
   *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
   *   // for example, you might want to remove it from here.
   *   inputExcludes: ["android/**", "ios/**"],
   *
   *   // override which node gets called and with what additional arguments
   *   nodeExecutableAndArgs: ["node"],
   *
   *   // supply additional arguments to the packager
   *   extraPackagerArgs: []
   * ]
   */

  project.ext.react = [
      entryFile: "index.js",
      root: "../../",
      enableHermes: true,  // clean and rebuild if changing
  ]

  apply from: "../../node_modules/react-native/react.gradle"

  apply from: '../../node_modules/react-native-unimodules/gradle.groovy'

  /**
   * Set this to true to create two separate APKs instead of one:
   *   - An APK that only works on ARM devices
   *   - An APK that only works on x86 devices
   * The advantage is the size of the APK is reduced by about 4MB.
   * Upload all the APKs to the Play Store and people will download
   * the correct one based on the CPU architecture of their device.
   */
  def enableSeparateBuildPerCPUArchitecture = false

  /**
   * Run Proguard to shrink the Java bytecode in release builds.
   */
  def enableProguardInReleaseBuilds = false
  def useIntlJsc = false

  /**
   * The preferred build flavor of JavaScriptCore.
   *
   * For example, to use the international variant, you can use:
   * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
   *
   * The international variant includes ICU i18n library and necessary data
   * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
   * give correct results when using with locales other than en-US.  Note that
   * this variant is about 6MiB larger per architecture than default.
   */
  def jscFlavor = 'org.webkit:android-jsc:+'

  /**
   * Whether to enable the Hermes VM.
   *
   * This should be set on project.ext.react and mirrored here.  If it is not set
   * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
   * and the benefits of using Hermes will therefore be sharply reduced.
   */
  def enableHermes = project.ext.react.get("enableHermes", false);

  android {
      compileSdkVersion rootProject.ext.compileSdkVersion

      compileOptions {
          sourceCompatibility JavaVersion.VERSION_1_8
          targetCompatibility JavaVersion.VERSION_1_8
      }

      defaultConfig {
          applicationId "com.hiratsuka_react_native_test"
          minSdkVersion rootProject.ext.minSdkVersion
          targetSdkVersion rootProject.ext.targetSdkVersion
          versionCode 1
          versionName "1.0"
      }
      splits {
          abi {
              reset()
              enable enableSeparateBuildPerCPUArchitecture
              universalApk false  // If true, also generate a universal APK
              include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
          }
      }
      signingConfigs {
          debug {
              storeFile file('debug.keystore')
              storePassword 'android'
              keyAlias 'androiddebugkey'
              keyPassword 'android'
          }
      }
      buildTypes {
          debug {
              signingConfig signingConfigs.debug
          }
          release {
              // Caution! In production, you need to generate your own keystore file.
              // see https://facebook.github.io/react-native/docs/signed-apk-android.
              signingConfig signingConfigs.debug
              minifyEnabled enableProguardInReleaseBuilds
              proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
          }
      }
      // applicationVariants are e.g. debug, release
      applicationVariants.all { variant ->
          variant.outputs.each { output ->
              // For each separate APK per architecture, set a unique version code as described here:
              // https://developer.android.com/studio/build/configure-apk-splits.html
              def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
              def abi = output.getFilter(OutputFile.ABI)
              if (abi != null) {  // null for the universal-debug, universal-release variants
                  output.versionCodeOverride =
                          versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
              }

          }
      }
  }

  dependencies {
      implementation project(':react-native-webview')
      implementation fileTree(dir: "libs", include: ["*.jar"])
      implementation "com.facebook.react:react-native:+"  // From node_modules
      addUnimodulesDependencies()
      api project(':unimodules-core')

      if (enableHermes) {
          def hermesPath = "../../node_modules/hermes-engine/android/";
          debugImplementation files(hermesPath + "hermes-debug.aar")
          releaseImplementation files(hermesPath + "hermes-release.aar")
      } else {
          implementation jscFlavor
      }

      // If your app supports Android versions before Ice Cream Sandwich (API level 14)
      implementation 'com.facebook.fresco:animated-base-support:1.3.0'

      // For animated GIF support
      implementation 'com.facebook.fresco:animated-gif:2.0.0'

      // For WebP support, including animated WebP
      implementation 'com.facebook.fresco:animated-webp:2.1.0'
      implementation 'com.facebook.fresco:webpsupport:2.0.0'

      // For WebP support, without animations
      implementation 'com.facebook.fresco:webpsupport:2.0.0'
  }

  // Run this once to be able to run the application with BUCK
  // puts all compile dependencies into folder libs for BUCK to use
  task copyDownloadableDepsToLibs(type: Copy) {
      from configurations.compile
      into 'libs'
  }

  apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

A: try adding this to your app/build.gradle
project.ext.react = [
    entryFile   : "index.js",
    enableHermes: true,  // HERE!
]


text:
Q: Conditional duplicate filtering query At Oracle I would like to filter below TABLE as

COLUMNA
COLUMNB
COLUMNC

19
AAA
PRIMARY

20
AAA
PRIMARY

8
AAA
SECONDARY

7
AAA
SECONDARY

7
AAA
PRIMARY

8
AAA
SECONDARY

9
AAA
SECONDARY

my expected output is

COLUMNA
COLUMNB
COLUMNC

19
AAA
PRIMARY

20
AAA
PRIMARY

7
AAA
PRIMARY

9
AAA
SECONDARY

Logic is Group by COLUMNA and COLUMNB (please evaluate below conditions on grouping.)

*

*if columnc candidate record (grouped by COLUMNA and COLUMNB) includes only PRIMARY take PRIMARY.

*if columnc candidate record (grouped by COLUMNA and COLUMNB) includes only SECONDARY take SECONDARY.

*if columnc candidate records (grouped by COLUMNA and COLUMNB) include PRIMARY and SECONDARY set, take PRIMARY.

*if columnc candidate records (grouped by COLUMNA and COLUMNB) include duplicate SECONDARY set skip record.

*imagine this row has 100 columns so I need to fetch row by itself. MAX MIN wont work here.

I have used couple of row_number() functions and where not exists but went into oblivion.

A: Maybe this query is what you are looking for. As I said in my comment, 8 should be also included based on your description
with your_data as (
  select 19 as columna, 'AAA' as columnb, 'PRIMARY' as columnc from dual union all
  select 20,'AAA','PRIMARY' from dual union all
  select 8 ,'AAA','SECONDARY' from dual union all
  select 7 ,'AAA','SECONDARY' from dual union all
  select 7 ,'AAA','PRIMARY' from dual union all
  select 8 ,'AAA','SECONDARY' from dual union all
  select 9 ,'AAA','SECONDARY' from dual
)
select distinct COLUMNA, COLUMNB, COLUMNC
from (
  select
    COLUMNA, COLUMNB, COLUMNC,
    count(DISTINCT COLUMNC) over (partition by COLUMNA) as x,
    count(COLUMNC) over (partition by COLUMNA) as y
  from your_data
  ) yd
where
  -- if columnc candidate rows includes only PRIMARY take PRIMARY
  (COLUMNC = 'PRIMARY' and x = 1)
  or
  -- if columnc candidate rows includes only SECONDARY take SECONDARY (just one record)
  (COLUMNC = 'SECONDARY' and x = 1 and y=1)
  or
  -- if columnc candidate rows includes PRIMARY and SECONDARY take PRIMARY
  (COLUMNC = 'PRIMARY' and x = 2)
order by 1

A: It looks like aggregation does what you want:
SELECT COLUMNA, COLUMNB, MIN(COLUMNC)
FROM t
GROUP BY COLUMNA, COLUMNB
HAVING MIN(COLUMNC) = 'PRIMARY';

Actually, based on your logic (but not the results which are inconsistent), WHERE is sufficient:
SELECT COLUMNA, COLUMNB, MIN(COLUMNC)
FROM t
WHERE COLUMNC = 'PRIMARY'
GROUP BY COLUMNA, COLUMNB;

Or for the entire row:
SELECT t.*
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY Column1, Column2 ORDER BY Column1) as seqnum
      FROM t
      WHERE COLUMNC = 'PRIMARY'
     ) t
WHERE seqnum = 1;

A: CInspired by @Jaime Drq have solution below.
Easy to understand and optimized query.
WITH TABLE_VIEW AS (
SELECT /*+ ORDERED */ COLUMNA, COLUMNB, COLUMNC, ROW_NUMBER() OVER (PARTITION BY COLUMNA, COLUMNB ORDER BY COLUMNC ASC) CANDIDATERANKING
    FROM TABLE)
    SELECT *
    FROM (
        SELECT COLUMNA, COLUMNB, COLUMNC, SUM(CANDIDATERANKING) PRIORITY
            FROM TABLE_VIEW TT
          GROUP BY COLUMNA, COLUMNB, COLUMNC)
    WHERE PRIORITY= 1;


text:
Q: Are these mispronunciations by my British English text-to-speech engine a reflection of an actual British English usage? A little context: I'm a native speaker of American English. I use Google's text-to-speech engine with the British voice, as I find the roboticness (roboticity?) of delivery to be less distracting in a less familiar accent. However, I'm occasionally left scratching my head over particular pronunciations.
Some of these are clearly based on English language formation rules--for example, for some time the proper name "Ian" was said as just a sort of swallowed /n/ sound, likely because of a system rule about words ending in -ian (such as logician or Hessian; presumably there was some other rule governing guardian and the like).
However, two of these have me stumped. "M'" (as in m'lady or m'lord, but NOT m'self) is pronounced something like "MASHna" (/ˈmæʃ-nə/), and "hon" (the short form of "honey", as in "can I get you a warm-up on your coffee, hon?") sounds to me as if it is pronounced "cur" (/kər/). The US engine does not produce these pronunciations.
I've looked these up as abbreviations, both with a general google search and in the OED online, since the TTS engine frequently defaults to words as abbreviations (for example, the common name Ed always becomes editor, and the word "no" at the end of a sentence would be read as "number").
If this were the case, I would think "honourable" would be the obvious default British pronunciation of "hon", or possibly "honorary".
For M', something relating to machines or mass seems possible, but they don't seem like the first association (the OED has six other definitions for M preceding the mathematical symbol for mass, and does not include machine at all). These also don't explain where the second syllable comes from.
So, my questions:

*

*Is there an English rule, or a British usage, that explains the
  pronunciation of m' as /ˈmæʃ-nə/ and/or

*Is there an English rule, or a British usage, that explains the
  pronunciation of hon as /kər/?

I'm willing to accept that this might just be a bug in the engine (which would be out-of-scope for ELL), but most mispronunciations are clearly the product of over-regularization rather than pure error.

Clarification of why I believe this question is on-topic here:
I thought I was clear about this, but I'm NOT interested in the mechanics of how TTS engines work, nor am I assuming that the engine's pronunciations are "correct" for any variety of English. Rather, I am interested in what over-regularizations produced by machines relying on the rules given it by English speakers can tell us about English. (Similarly, linguists have looked at the over-regularizations produced by children learning to speak a language to identify underlying structures of the language.) I am also interested in the differences between American- and British-English usage, as occasionally (incidentally) revealed by listening to a TTS engine predicated on British English input.
Clarification 2: One more piece of information that may help understand why these examples, in particular, are of interest to me: Ordinarily, if the TTS doesn't "know" a word (most "common" words were apparently entered wholesale, rather than relying on "rules"), it will either sound it out using fairly basic rules—which in the case of "hon" I would expect to produce something like hot-ending-with-an-n or con-starting-with-an-h or similar—or else it simply spells out the word, in cases where it doesn't follow normal patterns of English spelling (common with loan words and uncommon names). In these two cases (out of thousands of unique words I've listened to), neither of these strategies was employed and I have been unable to identify a logical reason. For comparison, "'ave" as in "'ave a good day, guv'nor" is pronounced "avenue" by one TTS engine, and "ah-vay" as in "Ave Maria" in another; both of these examples are clearly comprehensible based on English usage, even if a native speaker would not make that mistake.

A: *

*No, generally "m'" is vocalised as a quick 'muh' sound.

*'hon' is never pronounced /kər/. In the case of 'honey', /hʌn/ would be correct, in case of 'honourable' (hon. as an abbreviation), then /ˈɒn/ (somewhere between 'ahn', 'on') would be about right.


text:
Q: single component load in react router I need to know how to avoid all the components to get loaded when starting the application.
Below is my app.js file. There I have used react-router. But it get loaded all the components when starting the application. But the requirement is only the particular component has to get loaded in that particular route. Help me to resolve this.
import "./App.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Pages/Home";
import TollList from "./Pages/TollList";

function App() {
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />}></Route>
          <Route path="/tolllist" element={<TollList />}></Route>
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;

I tried the react-router for this

A: React creates a single page application. Look at this example of React Router V6. The URL displayed in the address bar always reflects the thing that they are viewing. When you click on the "About" link you can see that the URL changes to www.websitename.com/About. The empty "/" route is whatever you want the default route to be. If you clicked on the /tolllist route then the Home component will no longer be displayed and the tolllist will be shown instead.
React Router Docs


text:
Q: jaxb unmarshal abusable by crafted xml when using default sax parser? So in my current project I use the JAXB RI with the default Java parser from Sun's JRE (which I believe is Xerces) to unmarshal arbitrary XML.
First I use XJC to compile an XSD of the following form:
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="foobar">
...
</xs:element>
</xs:schema>

In the "good case" everything works as designed.  That is to say if I'm passed XML that conforms to this schema then JAXB correctly unmarshals it into an object tree.
The problem comes when I'm passed XML with an external DTD references, e.g.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foobar SYSTEM "http://blahblahblah/foobar.dtd">
<foobar></foobar>

Upon unmarshalling something like this, the SAX parser attempts to load the remote entity ("http://somehost/foobar.dtd") despite the fact that this snippet clearly does not conform to the schema I compiled earlier with XJC.
In order to circumvent this behavior, since I know that any conformant XML (according to the XSD I compiled) will never require the loading of a remote entity, I have to define a custom EntityResolver that short circuits the loading of all remote entities.  So instead of doing something like:
MyClass foo = (MyClass) myJAXBContext.createUnmarshaller().unmarshal(myReader);

I'm forced to do this:
XMLReader myXMLReader = mySAXParser.getXMLReader();
myXMLReader.setEntityResolver(myCustomEntityResolver);
SAXSource mySAXSource = new SAXSource(myXMLReader, new InputSource(myReader));
MyClass foo = (MyClass) myJAXBContext.createUnmarshaller().unmarshal(mySAXSource);

So my ultimate question is:
When unmarshalling with JAXB, should the loading of remote entities by the underlying SAX parser be automatically short circuited when the XML in question can be recognized as invalid without the loading of those remote entities?
Also, doesn't this seem like a security issue?  Given that JAX-WS relies on JAXB under the hood, it seems like I could pass specially crafted XML to any JAX-WS based web service and cause the WS host to load any arbitrary URL.
I'm a relative newbie to this, so there's probably something I'm missing.  Please let me know if so!

A: A well-crafted question, it deserves an answer :)
Some things to note:

*

*The JAXB runtime is not dependent on XML Schema. It uses a SAX parser to generate a stream of SAX events which it uses to bind on to the object model. This object model can be hand-written, or can be generated from a schema using XJC, but the binding and the runtime are very distinct from each other. So you may know that good XML input conforms to the schema at runtime, but JAXB does not.

*Forcing the runtime to load a remote DTD reference does not constitute a security hole. If there's a real DTD at the end of it, the worst case is that it won't validate. If it's not a real DTD, then it'll be ignored.

*DTD is considered obsolete, and so there's no direct support for it in the high level JAXB API. If you need an EntityResolver, you need to dig into the SAX API, which you have already done.

*If your class model was generated from an XML Schema, then you should consider validating against it at runtime, using SchemaFactory and Unmarshaller.setSchema(). This will instruct Xerces to validate the SAX events against the schema before being passed to JAXB. This won't stop the DTD being fetched, but it adds a layer of safety that you know the data is good.


text:
Q: Есть ли возможность для скомпилированного файла сделать врапер для управления программой? У меня есть скомпилированная программа
program
Она имеет свои методы.
getFile
last
и т. д.
Есть ли возможность запускать и управлять этим бинарным файлом не из консоли, а на Node.js запустить его и передавать ему комманды ?