text:
Q: Lebesgue measure of complement of this set This question was part of  my real analysis quiz and I need help in correctly proving it.

For each a $\in \mathbb{R}$ , let $ S_a$ ={$(x,y,z)\in {\mathbb{R}}^3 | x^2+y^2+z^2= a^2$} Let $E=\bigcup_{a\in \mathbb{R}/ \mathbb{Q}} S_a$ Then does every open set containing $E^C$ has finite Lebesgue measure ?

I can't think why measure must be finite , even intutively I think that measure must be infinite. I am looking for a rigorious argument why measure must be finite. I am not really good in Lebesgue measure but really want to learn.

A: (edit) I assume you meant to say that there is not open set contained in E, with positive measure, so I answered that question.
E is $\mathbb{R}^3$, except for the points with rational norm ( $||\mathbf{x}||\in \mathbb{Q}\Rightarrow \mathbf{x}\notin E$).
The idea here is that, $F:=\mathbb{R}^3-E$ is dense in $\mathbb{R}^3$ (and $\overline{F}=\mathbb{R}^3$)
Then, you can show that, there are no open sets in $E$, with non cero messure, since they would intersect with $F$.
Let me know if you need more details.


text:
Q: Proving that the Sample Mean is BLUE (Best Linear Unbiased Estimator) For a pupil, i, selected at random from a school, the number of years of education of their parents, $X_i$, is given by:
$$
X_{i}=\mu+\varepsilon_{i}
$$
$\varepsilon_{i} \sim i i d\left(0, \sigma^{2}\right)$. Here $\mu$ is the mean number of years of education completed by parents. For a sample of N students selected independently from the population:
(e) Is the sample mean BLUE? Either way, prove it.
Answer:
First part of proof proves conditions for linear estimator to be unbiased. The second part proves that if the estimator is unbiased, the variance of a linear estimator cannot better it.
Define linear estimator $\tilde{X}=\frac{1}{N} \sum_{i=1}^{N} w_{i} X_{i}$ with weights made up: $w_{i}=1+\delta_{i}$. The 1 here is what the sample mean weight are, so we are saying our new estimator weights differ from that of the sample mean by the amount $\delta_{i}$.
$$
\mathbb{E}(\tilde{X})=\mathbb{E}\left(\frac{1}{N} \sum_{i=1}^{N}\left(1+\delta_{i}\right) X_{i}\right)=\mu+\frac{\mu}{N} \sum_{i=1}^{N} \delta_{i}
$$
Hence we must have $\sum_{i=1}^{N} \delta_{i}=0$ for our new linear estimator to be unbiased. Now we derive variance:
$$
\operatorname{Var}(\tilde{X})=\frac{1}{N^{2}} \sum_{i=1}^{N}\left(1+\delta_{i}\right)^{2} \sigma^{2}=\frac{\sigma^{2}}{N}+\frac{\sigma^{2}}{N^{2}} \sum_{i=1}^{N}\left(2 \delta_{i}+\delta_{i}^{2}\right)=\operatorname{Var}(\bar{X})+\frac{\sigma^{2}}{N^{2}} \sum_{i=1}^{N} \delta_{i}^{2}
$$
Finally, note that for non-zero weights the expression $\sum_{i=1}^{N} \delta_{i}^{2}=\eta>0$, hence we have that the variance of the new estimator is greater than that of the sample mean. Hence this has proved that any other linear estimator apart from the sample mean has a greater sampling variance.
$$
\operatorname{Var}(\tilde{X})=\operatorname{Var}(\bar{X})+\eta
$$
Q: The expected value expression makes sense, but where does the variance expression come from and how does he get that?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to substitute the extension for a cmake list of filenames I am trying to build a c++ library from some protobuf definitions using cmake.
I added a custom command to compile the proto to c++, but I have some issues with the output part.
I need to specify which are the expected output files after protoc does its job. For this I would like to replace in my PROTO_SOURCEfile glob, the proto extension with .pb.cc and .pb.h
I basically need something like this, but for cmake.
I am building this command manually because I don't have protobuf cmake support available.
project(messages)

set(PROTO_PATH "${CMAKE_CURRENT_SOURCE_DIR}/proto_definitions")
file(GLOB PROTO_FILES "${PROTO_PATH}/*.proto")
#set(PROTO_SOURCES ???) # This needs to contain '*.pb.cc' and '*.pb.h'

add_custom_command(COMMAND protoc --cpp_out=${CMAKE_CURRENT_SOURCE_DIR}/compiled_proto ${PROTO_FILES}
               WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
               DEPENDS ${PROTO_FILES}
               OUTPUT ${PROTO_SOURCES})

add_library(${PROJECT_NAME} STATIC ${PROTO_SOURCES})

A: Use string(REGEX REPLACE) function:
# Replace .proto -> .pb.cc
string(REGEX REPLACE "[.]proto$" ".pb.cc" OUTPUT_SOURCES ${PROTO_FILES})
# Replace .proto -> .pb.h
string(REGEX REPLACE "[.]proto$" ".pb.h" OUTPUT_HEADERS ${PROTO_FILES})

add_custom_command(COMMAND protoc <...>
   OUTPUT ${OUTPUT_SOURCES} ${OUTPUT_HEADERS})

A: The accepted answer didn't work for me, as the first few elements in the list weren't properly substituted.
So I loop over the list, replace them one by one, and append each one to a list:
foreach (CXX_SRC ${LIST_OF_CXX})
    string(REGEX REPLACE "[.]cpp$" ".o" OBJ ${CXX_SRC})
    set(OBJ_FILES ${OBJ_FILES} ${OBJ})
endforeach ()
message(STATUS "Object files compiled from *.cpp: ${OBJ_FILES}")


text:
Q: Openbox pipe-menu script error This is the weirdest thing. The script works when run from the shell with no problems. When I run it as an Openbox pipe-menu I get the error "Invalid output from pipe-menu". After playing around with the script I found that it has specifically to do with printing the 5th column.
To make matters even more confusing, this only happens with the month of July. All other months will show up correctly running the script.
Here is the script as it should be. It works when executed from a terminal:
#!/bin/bash
echo "<openbox_pipe_menu>"
cal | while read i;do
echo "<item label=\"$i\"/>"
done
echo "</openbox_pipe_menu>"
echo "</openbox_pipe_menu>"

The output of the script:
$ ./date-menu.sh
<openbox_pipe_menu>
<item label="July 2014"/>
<item label="Su Mo Tu We Th Fr Sa"/>
<item label="1  2  3  4  5"/>
<item label="6  7  8  9 10 11 12"/>
<item label="13 14 15 16 17 18 19"/>
<item label="20 21 22 23 24 25 26"/>
<item label="27 28 29 30 31"/>
<item label=""/>
</openbox_pipe_menu>

Here is the simplified version that still fails when running as a pipe-menu:
#!/bin/bash
calRow () {
cal | gawk -v row=$1 '{ if (NR==row) { print $0 } }'
}
echo "<openbox_pipe_menu>"
echo "<item label=\"`calRow 5`\"/>"
echo "</openbox_pipe_menu>"

BUT...If I do the same script with any number but 5 it works like a charm:
#!/bin/bash
calRow () {
cal | gawk -v row=$1 '{ if (NR==row) { print $0 } }'
}
echo "<openbox_pipe_menu>"
echo "<item label=\"`calRow 2`\"/>"
echo "<item label=\"`calRow 3`\"/>"
echo "<item label=\"`calRow 4`\"/>"
echo "<item label=\"`calRow 6`\"/>"
echo "<item label=\"`calRow 7`\"/>"
echo "<item label=\"`calRow 8`\"/>"
echo "</openbox_pipe_menu>"

Here is the menu.xml file in case anyone wants to see it:
<?xml version="1.0" encoding="utf-8"?>
<openbox_menu xmlns="http://openbox.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://openbox.org/                 file:///usr/share/openbox/menu.xsd">
    <menu id="root-menu" label="Openbox 3">
        <item label="Terminal emulator">
            <action name="Execute">
                <execute>x-terminal-emulator</execute>
            </action>
        </item>
        <item label="Browser">
            <action name="Execute">
                <execute>x-www-browser</execute>
            </action>
        </item>
        <item label="Virtualbox">
            <action name="Execute">
                <execute>virtualbox</execute>
            </action>
        </item>
        <!-- This requires the presence of the 'menu' package to work -->
        <menu id="/Debian"/>
        <separator/>
        <item label="obmenu">
            <action name="Execute">
                <execute>obmenu</execute>
            </action>
        </item>
        <item label="ObConf">
            <action name="Execute">
                <execute>obconf</execute>
            </action>
        </item>
        <item label="Reconfigure">
            <action name="Reconfigure"/>
        </item>
        <item label="Restart">
            <action name="Restart"/>
        </item>
        <separator/>
        <menu execute="obpipes/sysinfo.sh" id="pipe-sysinfo" label="System Info"/>
        <menu execute="obpipes/date-menu.sh" id="pipe-datemenu" label="Date"/>
        <menu id="client-list-menu"/>
        <separator/>
        <item label="Exit">
            <action name="Exit"/>
        </item>
    </menu>
</openbox_menu>

A: It turns out it was the current day being highlighted causing the problem. I was able to fix it by turning highlighting off (cal -h)


text:
Q: Clustering of news articles My scenario is pretty straightforwrd: I have a bunch of news articles (~1k at the moment) for which I know that some cover the same story/topic. I now would like to group these articles based on shared story/topic, i.e., based on their similarity.
What I did so far is to apply basic NLP techniques including stopword removal and stemming. I also calculated the tf-idf vector for each article, and with this can also calculate the, e.g., cosine similarity based on these tf-idf-vectors. But now with the grouping of the articles I struggles a bit. I see two principle ways -- probably related -- to do it:
1) Machine Learning / Clustering: I already played a bit with existing clustering libraries, with more or less success; see here. On the one hand, algorithms such as k-means require the number of clusters as input, which I don't know. Other algorithms require parameters that are also not intuitive to specify (for me that is).
2) Graph algorithms: I can represent my data as a graph with the articles being the nodes and weighted adges representing the pairwise (cosine) similarity between the articles. With that, for example, I can first remove all edges that fall below a certain threshold and then might apply graph algorithms to look for strongly-connected subgraphs.
In short, I'm not sure where best to go from here -- I'm still pretty new in this area. I wonder if there some best practices for that, or some kind of guidelines which methods / algorithms can (not) be applied in certain scenarios.
(EDIT: forgot to link to related question of mine)

A: Try the class of Hierarchical Agglomerative Clustering HAC algorithms with Single and Complete linkage.
These algorithms do not need the number of clusters as input.
The basic principle is similar to growing a minimal spanning tree across a given set of data points and then stop based on a threshold criteria. A closely related class is the Divisive clustering algorithms which first builds up the minimal spanning tree and then prunes off a branch of the tree based on inter-cluster similarity ratios.

A: You can also try a canopy variation on k-means to create a relatively quick estimate for the number of clusters (k).
http://en.wikipedia.org/wiki/Canopy_clustering_algorithm
Will you be recomputing over time or do you only care about a static set of news?  I ask because your k may change a bit over time.

A: Since you can model your dataset as a graph you could apply stochastic clustering based on markov models. Here are link for resources on MCL algorithm:
Official thesis description and code base
Gephi plugin for MCL (to experiment and evaluate the method)


text:
Q: Swift Command failed due to signal: Segmentation fault I am trying to do Product->Archive in Xcode, but I get this error.

"1.    While running pass #317664 SILFunctionTransform "Constant Propagation" on SILFunction "@_TTSg5VSC29UIApplicationLaunchOptionsKeyS_s8Hashable5UIKit_P__CSo8NSObjectS2_S0_10ObjectiveC_Ps9AnyObject____TFs17_dictionaryUpCastu2_Rxs8Hashable0_S_rFGVs10Dictionaryxq__GS0_q0_q1__"."

When I try to build I have no errors, but when I try to archive the console I see this error.
I'm using Swift 3.
The full console report can be found here.

A: Hey guys I don't know if you guys solved this yet but I had the exact same problem, tried clean delete derived data and everything, was able to build but not archive and got the same error. The way I solved it was to disable Swift Complier Optimization for Release in build settings, I attached an image of what it looks like afterward.
Disable Swift Complier Optimization for Release


text:
Q: Finding Last n Groups of Rows in Dataframe I have a large dataframe (1m+ rows) that contains test data. A snapshot of "Events" was taken at various times and up to three rows were added to the dataframe per snapshot. Eg, in the extract below the first snapshot for Event At223 was taken at 18/03/2016  18:10:45, the second at 21/03/2016  10:14:28, etc.
I want to filter the dataframe so that it returns only the last n snapshots per Ref. Refs are unique whereas Events may be duplicated.
I'm new to Pandas but have tried various combinations of sort_values, groupby and tail but cannot get the desired result. Eg:
df = df.sort_values(['Ref', 'Time']).groupby(['Time', 'Ref', 'TestId']).tail(3)

Can anyone suggest how to do it? In the deisred result example below n = 3 so it shows the last three snapshots per Ref.
Extract:

Time
Ref
Event
EndTime
TestId
TestNames
Result

18/03/2016 18:10:45
1.123717985
At223
01/04/2016 16:00
28212
One

18/03/2016 18:10:45
1.123717985
At223
01/04/2016 16:00
466299
Two

18/03/2016 18:10:45
1.123717985
At223
01/04/2016 16:00
58805
Three

21/03/2016 10:14:28
1.123717985
At223
01/04/2016 16:00
28212
One

21/03/2016 10:14:28
1.123717985
At223
01/04/2016 16:00
466299
Two
4

21/03/2016 10:14:28
1.123717985
At223
01/04/2016 16:00
58805
Three

21/03/2016 12:44:34
1.123717985
At223
01/04/2016 16:00
28212
One

21/03/2016 12:44:34
1.123717985
At223
01/04/2016 16:00
466299
Two
4.5

21/03/2016 12:44:34
1.123717985
At223
01/04/2016 16:00
58805
Three

21/03/2016 13:05:16
1.123717985
At223
01/04/2016 16:00
28212
One

21/03/2016 13:05:16
1.123717985
At223
01/04/2016 16:00
466299
Two
4.5

21/03/2016 13:05:16
1.123717985
At223
01/04/2016 16:00
58805
Three

21/03/2016 13:14:22
1.123717985
At223
01/04/2016 16:00
28212
One

21/03/2016 13:14:22
1.123717985
At223
01/04/2016 16:00
466299
Two
4.5

21/03/2016 13:14:22
1.123717985
At223
01/04/2016 16:00
58805
Three

01/04/2016 10:37:43
1.123717985
At223
01/04/2016 16:00
28212
One

01/04/2016 10:37:43
1.123717985
At223
01/04/2016 16:00
466299
Two
4.5

01/04/2016 10:37:43
1.123717985
At223
01/04/2016 16:00
58805
Three

18/03/2016 18:12:12
1.123719512
Br12
03/04/2016 16:00
28214
Eight
7

18/03/2016 18:12:12
1.123719512
Br12
03/04/2016 16:00
1212772
Nine
1.58

18/03/2016 18:12:12
1.123719512
Br12
03/04/2016 16:00
58805
Ten
4.4

21/03/2016 13:03:48
1.123719512
Br12
03/04/2016 16:00
28214
Eight
7.2

21/03/2016 13:03:48
1.123719512
Br12
03/04/2016 16:00
1212772
Nine
1.58

21/03/2016 13:03:48
1.123719512
Br12
03/04/2016 16:00
58805
Ten
4.4

21/03/2016 13:19:15
1.123719512
Br12
03/04/2016 16:00
28214
Eight
7.2

21/03/2016 13:19:15
1.123719512
Br12
03/04/2016 16:00
1212772
Nine
1.58

21/03/2016 13:19:15
1.123719512
Br12
03/04/2016 16:00
58805
Ten
4.5

01/04/2016 12:48:13
1.123719512
Br12
03/04/2016 16:00
28214
Eight
7.2

01/04/2016 12:48:13
1.123719512
Br12
03/04/2016 16:00
1212772
Nine
1.59

01/04/2016 12:48:13
1.123719512
Br12
03/04/2016 16:00
58805
Ten
4.5

Desired result:

Time
Ref
Event
EndTime
TestId
TestNames
Result

21/03/2016 13:05:16
1.123717985
At223
01/04/2016 16:00
28212
One

21/03/2016 13:05:16
1.123717985
At223
01/04/2016 16:00
466299
Two
4.5

21/03/2016 13:05:16
1.123717985
At223
01/04/2016 16:00
58805
Three

21/03/2016 13:14:22
1.123717985
At223
01/04/2016 16:00
28212
One

21/03/2016 13:14:22
1.123717985
At223
01/04/2016 16:00
466299
Two
4.5

21/03/2016 13:14:22
1.123717985
At223
01/04/2016 16:00
58805
Three

01/04/2016 10:37:43
1.123717985
At223
01/04/2016 16:00
28212
One

01/04/2016 10:37:43
1.123717985
At223
01/04/2016 16:00
466299
Two
4.5

01/04/2016 10:37:43
1.123717985
At223
01/04/2016 16:00
58805
Three

21/03/2016 13:03:48
1.123719512
Br12
03/04/2016 16:00
28214
Eight
7.2

21/03/2016 13:03:48
1.123719512
Br12
03/04/2016 16:00
1212772
Nine
1.58

21/03/2016 13:03:48
1.123719512
Br12
03/04/2016 16:00
58805
Ten
4.4

21/03/2016 13:19:15
1.123719512
Br12
03/04/2016 16:00
28214
Eight
7.2

21/03/2016 13:19:15
1.123719512
Br12
03/04/2016 16:00
1212772
Nine
1.58

21/03/2016 13:19:15
1.123719512
Br12
03/04/2016 16:00
58805
Ten
4.5

01/04/2016 12:48:13
1.123719512
Br12
03/04/2016 16:00
28214
Eight
7.2

01/04/2016 12:48:13
1.123719512
Br12
03/04/2016 16:00
1212772
Nine
1.59

01/04/2016 12:48:13
1.123719512
Br12
03/04/2016 16:00
58805
Ten
4.5

A: You could loop through each unique event and grab the top n times from each. Then concatenate the results together:
n = 3
event_dfs = []
for event in df['Event'].unique():
   sub_df = df.loc[df['Event'] == event]
   max_times = sub_df['Time'].nlargest(n=n)
   event_dfs.append(sub_df.loc[sub_df['Time'].isin(max_times)])

result = pd.concat(event_dfs)

A: Factorize the date and keep the n highest values (assuming your dataframe is already sorted by Time)
# Number of snapshot you want to keep
n = 3

# Create a boolean mask
m = (df.assign(val=pd.factorize(df['Time'])[0])
       .groupby('Ref')['val']
       .transform(lambda x: x.max() - x < n))

out = df[m]

Output:
>>> out
                   Time       Ref  Event           EndTime   TestId TestNames  Result
9   21/03/2016 13:05:16  1.123718  At223  01/04/2016 16:00    28212       One     NaN
10  21/03/2016 13:05:16  1.123718  At223  01/04/2016 16:00   466299       Two    4.50
11  21/03/2016 13:05:16  1.123718  At223  01/04/2016 16:00    58805     Three     NaN
12  21/03/2016 13:14:22  1.123718  At223  01/04/2016 16:00    28212       One     NaN
13  21/03/2016 13:14:22  1.123718  At223  01/04/2016 16:00   466299       Two    4.50
14  21/03/2016 13:14:22  1.123718  At223  01/04/2016 16:00    58805     Three     NaN
15  01/04/2016 10:37:43  1.123718  At223  01/04/2016 16:00    28212       One     NaN
16  01/04/2016 10:37:43  1.123718  At223  01/04/2016 16:00   466299       Two    4.50
17  01/04/2016 10:37:43  1.123718  At223  01/04/2016 16:00    58805     Three     NaN
21  21/03/2016 13:03:48  1.123720   Br12  03/04/2016 16:00    28214     Eight    7.20
22  21/03/2016 13:03:48  1.123720   Br12  03/04/2016 16:00  1212772      Nine    1.58
23  21/03/2016 13:03:48  1.123720   Br12  03/04/2016 16:00    58805       Ten    4.40
24  21/03/2016 13:19:15  1.123720   Br12  03/04/2016 16:00    28214     Eight    7.20
25  21/03/2016 13:19:15  1.123720   Br12  03/04/2016 16:00  1212772      Nine    1.58
26  21/03/2016 13:19:15  1.123720   Br12  03/04/2016 16:00    58805       Ten    4.50
27  01/04/2016 12:48:13  1.123720   Br12  03/04/2016 16:00    28214     Eight    7.20
28  01/04/2016 12:48:13  1.123720   Br12  03/04/2016 16:00  1212772      Nine    1.59
29  01/04/2016 12:48:13  1.123720   Br12  03/04/2016 16:00    58805       Ten    4.50

A: You can use apply after groupby
And create a function that only handles dataframes with a single Ref
def extract_n_last_times(n: int):
    def extract_last_times(group: pd.DataFrame):
        times = group.sort_values("Time")["Time"].unique()
        return group[group["Time"].isin(times[-n:])]
    return extract_last_times

df.sort_values(["Ref", "Time"]).groupby("Ref", group_keys=False).apply(extract_n_last_times(n=3))


text:
Q: Get specific part of a string for each line I have a data which I want to take specific part of it
    DoseResponse_Curves/drCurve_AAATT.pdf
    DoseResponse_Curves/drCurve_AGMK1.pdf
    DoseResponse_Curves/drCurve_AGU.pdf
    DoseResponse_Curves/drCurve_ALH1L2.pdf
    DoseResponse_Curves/drCurve_ALKB1.pdf
    DoseResponse_Curves/drCurve_AS2.pdf
    DoseResponse_Curves/drCurve_ANK1.pdf
    DoseResponse_Curves/drCurve_ANKRD54.pdf

I only want to take whatever comes after the second _ and before . which means the output looks like this
AAATT
AGMK1
AGU
ALH1L2
ALKB1
AS2
ANK1
ANKRD54

Note: as we are working with gene names, they can contain characters such as c(".", "-").

A: You can do this with sub and a regular expression.
Files = c(
    'DoseResponse_Curves/drCurve_AAATT.pdf',
    'DoseResponse_Curves/drCurve_AGMK1.pdf',
    'DoseResponse_Curves/drCurve_AGU.pdf',
    'DoseResponse_Curves/drCurve_ALH1L2.pdf',
    'DoseResponse_Curves/drCurve_ALKB1.pdf',
    'DoseResponse_Curves/drCurve_AS2.pdf',
    'DoseResponse_Curves/drCurve_ANK1.pdf',
    'DoseResponse_Curves/drCurve_ANKRD54.pdf')

sub(".*?_.*?_(.*?)\\..*", "\\1", Files)
[1] "AAATT"   "AGMK1"   "AGU"     "ALH1L2"  "ALKB1"   "AS2"     "ANK1"
[8] "ANKRD54"

A: There are many ways:
# Example data with gene names with dots and dashes
Files = c('DoseResponse_Curves/drCurve_ALKB1.pdf',
          'DoseResponse_Curves/drCurve_BAC05914.1.pdf',
          'DoseResponse_Curves/drCurve_ALDH1L1-AS1.pdf',
          'DoseResponse_Curves/drCurve_AL953854.2-002.pdf')

# as parts of path are all same, we can sub with "":
gsub("DoseResponse_Curves/drCurve_|.pdf", "", Files)
# [1] "ALKB1"          "BAC05914.1"     "ALDH1L1-AS1"    "AL953854.2-002"

# Or, as we are working with path and filenames maybe:
gsub("drCurve_", "", tools::file_path_sans_ext(basename(Files)))
# [1] "ALKB1"          "BAC05914.1"     "ALDH1L1-AS1"    "AL953854.2-002"

# @G5W answer doesn't handle extra dots in gene names
sub(".*?_.*?_(.*?)\\..*", "\\1", Files)
# [1] "ALKB1"       "BAC05914"    "ALDH1L1-AS1" "AL953854"


text:
Q: Nginx 502 bad getaway in Django register and login page I've deployed a Django app with nginx and gunicorn. It's works fine except it's login form and register form.
When I submit either of forms I get "502 bad gateway" error message.
/etc/nginx/sites-available/config
server {
    listen 80;
    server_name croyal.net;
    server_name www.croyal.net;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

Could anybody give me a clue so that I can find the root of the issue?


text:
Q: Execute *nix find command using java code I am trying to execute a find command using java code.  I did the following:
sysCommand = "find . -name '*out*' > file1"

Runtime runtimeObj = Runtime.getRuntime();

try {
    Process processObj = runtimeObj.exec(sysCommand);
    processObj.waitFor();
    ...

This Linux command is executed when I use command line but fails in Java, why?

A: This question is probably a duplicate or a duplicate.

*

*Anyway, you could use File.list, providing a Filter on the type
of files you want.  You could call it recursively to get all sub-directories.  I don't love this answer.  You would think there is a simpler way.

*A friend of mine recommended Commons-Exec from Apache for running a command.  It allows you to use a time out on the command.  He recommended it because Runtime can have issues with large stdout and stderr.

A: As far as I know, it is not allowable to use any form of piping operator in Runtime.exec. If you want to move the results to a file, you will have to do that part in Java through Process.getInputStream.

A: If you are interested in doing this in Java then you will want to do something like this:
public void find(File startDirectory, FileFilter filter, List<File> matches) {
    File[] files = startDirectory.listFiles(filter);
    for (File file:files) {
        if(file.isDirectory()) {
            find(file, filter, matches);
        } else {
            matches.add(file);
        }
    }
}

Then you need but write the FileFilter to accept directories and files that match your pattern.


text:
Q: How do I modify Serilog Log Levels to match up with Log4Net? So I am in the process of swapping logging frameworks from Log4Net to Serilog where we log out to a text file.
I want the format of the text file to be exactly the same as I had previously, so users have a seamless migration.
So with the Serilog File Sink, I am able to modify the outputTemplate to suit my needs, however I am unable to get Serilogs log level to match exactly the same as in Log4Net.
I wish to have:

*

*ERROR

*INFO

*WARN

*DEBUG

*etc...

By reading the documentation for outputTemplates
https://github.com/serilog/serilog/wiki/Configuration-Basics#output-templates

For more compact level names, use a format such as {Level:u3} or {Level:w3} for three-character upper- or lowercase level names, respectively.

So I tried the following to try and get 5 letter uppercase {Level:u5} and got back:

*

*Infor

*Error

*Warni

*Debug

*etc..

Is anyone able to give me a pointer on this please?

A: After digging through the source code of Serilog, I found where the shorthand formatting for u3, w3 etc was happening and submitted a PR so that 5 character length log levels would be output as I needed.
After a polite response from Serilog maintainers, they gave me a much simpler solution of implementing my own ILogEventEnricher to add a new property to the log such as {Log4NetLevel} where the Enricher code can map Serilog Levels to be output in the exact format that Log4Net would use.
Then I can update my outputTemplate to use my new property {Log4NetLevel} as opposed to {Level:u5}
Here is a basic example
/// <summary>
/// This is used to create a new property in Logs called 'Log4NetLevel'
/// So that we can map Serilog levels to Log4Net levels - so log files stay consistent
/// </summary>
public class Log4NetLevelMapperEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        var log4NetLevel = string.Empty;

        switch (logEvent.Level)
        {
            case LogEventLevel.Debug:
                log4NetLevel = "DEBUG";
                break;

            case LogEventLevel.Error:
                log4NetLevel = "ERROR";
                break;

            case LogEventLevel.Fatal:
                log4NetLevel = "FATAL";
                break;

            case LogEventLevel.Information:
                log4NetLevel = "INFO";
                break;

            case LogEventLevel.Verbose:
                log4NetLevel = "ALL";
                break;

            case LogEventLevel.Warning:
                log4NetLevel = "WARN";
                break;
        }

        logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Log4NetLevel", log4NetLevel));
    }
}

Then I simply need to update my Serilog configuration to use my enricher, a much cleaner solution.
Thanks Serilog team!
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .Enrich.With<Log4NetLevelMapperEnricher>()
    .WriteTo.File(
        $@"{AppDomain.CurrentDomain.BaseDirectory}\App_Data\Logs\UmbracoTraceLog.{Environment.MachineName}.txt",
        rollingInterval: RollingInterval.Day,
        restrictedToMinimumLevel: LogEventLevel.Debug,
        retainedFileCountLimit: null,
        outputTemplate:
        "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} [P{ProcessId}/D{AppDomainId}/T{ThreadId}] {Log4NetLevel}  {Message:lj}{NewLine}{Exception}")
    .CreateLogger();


text:
Q: Are there 2-connected regular graphs whose maximum matching leaves 3 vertices uncovered? I'd like to use Corollary 5 of a paper by Hell & Kirkpatrick on graph packings to obtain an NP-hardness result. They want a 2-vertex-connected graph $F$ such that every matching in $F$ leaves at least 3 vertices unmatched. I would also like the graph to be $k$-regular for some $k$. I don't particularly care about the size of the graph or $k$, but smaller would be better.
Petersen's theorem implies that no such graph exists for $k =3$, but other theorems in this spirit that I've found in handbooks etc. don't seem to rule out the existence of such a graph for other $k$. I've searched through the collection of graphs from Mathematica's $\texttt{GraphData}$, but it didn't contain any examples satisfying these conditions.
Is anyone aware of reasons why such an $F$ might not exist, or else has ideas where to look for an example of one?
(I previously mentioned circulant graphs as possibilities, but they won't work because they are Hamiltonian.)

A: Take an even number $r\ge 4$.  Take $r$ copies of a 3-connected graph $G$ which has odd order and is regular of degree $r$.  Add two new vertices $x$ and $y$.  For each copy of $G$, remove one edge and join one of its former endpoints to $x$ and the other to $y$.
This gives a 2-connected $r$-regular graph whose maximum matchings miss at least $r-2$ vertices.  This type of construction is pretty standard. The Edmonds–Gallai decomposition theorem tells it all.


text:
Q: Python pandas code to pick a value from one column based on highest value of another column I have dataframe as shown below:

I need to transform the data set to something shown below.

I have tried to use groupby condition with agg as max. But it is not working as expected.
Could you please help with a python pandas code for the same?


text:
Q: Better way to create instance and run method in .NET 5 I have converted my .NET 4.5 to .NET 5, and everything seems to be about DI, which is great.
In order to load all my AutoMapper configuration files, i thought i would create an interface against them all, and then i need to execute the method, which i did like this.
// interface
public interface IAutoMapperMapping
{
    void Apply();
}

// class that implements interface
public class PageMapping : IAutoMapperMapping
{
    public void Apply()
    {
        // mappaing config here
    }
}

// load all classes
public void ConfigureServices(IServiceCollection services)
{

    // Load all mappings files and apply
    var assembly = System.Reflection.Assembly.GetExecutingAssembly();
    var types = assembly.GetTypes()
        .Where(e => typeof(IAutoMapperMapping).IsAssignableFrom(e) && !e.IsInterface)
        .ToList();

    foreach (var type in types)
    {
        var instance = (IAutoMapperMapping)Activator.CreateInstance(type);
        instance.Apply();
    }
}

Is this the best way to do this in .NET 5, or in .NET in general, or have i done something bad that i should avoid?

A: It looks like you are not actually registering any types to the ASP.NET 5 services DI container. What you are doing though is called Assembly Scanning and is a common feature of a lot of Dependency Injection containers.
The default container in ASP.NET 5 is very basic and does not include the ability to register types in the assembly using assembly scanning. If you wanted to, you could register all the types with the ASP.NET 5 services container and then rely on the container to resolve the IAutomapperMapping type, rather than using Activator.CreateInstance.
Alternatively, you can use a container like Autofac (There are many other good ones too but I like this one because it has a large community behind it and even Microsoft used it for Azure Mobile Services). You can read about Autofac Assembly Scanning and about their support for ASP.NET 5 here. However, you should note that this is all beta quality code.


text:
Q: Where can I get the source code of String class in Java I want to modify the replace() method of String class. But I can't find the code for it. Any help is appreciated.

A: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html this is Java doc URL.
http://www.docjar.com/html/api/java/lang/String.java.html you can find source code here...

A: The source code is available in the OpenJDK project.
Here is the link to the source of the String class: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/String.java


text:
Q: UIAlertView cuts off last row of message I would like to show an alert using a UIAlertView with a lot of text.
When I show this alert in the iOS simulator running iOS 4.2 it covers the navigation bar and the tab bar, however when I run the app on my iPhone running iOS 3.1.3 the alert message doesn't cover the navigation and tab bar. Furthermore, my "Okay" button cuts off the last part of the text of the UIAlertView.
How can I prevent the last line of text in the UIAlertView from being cut off on my iPhone running iOS 3.1.3 as it is on the simulator running iOS 4.2?
Thanks

A: Instead of depending on UIAlertView (which isn't meant for displaying an e-book's worth of long form text), you should create your own UIAlertView-like modal dialog with a scrollable text view so you can display everything you want the user to see.


text:
Q: Display none not working inside of media query I am trying to build a nice nav from the ground up. I have some seperators built into my nav as list items. I want these to dissapear when the screen size is smaller.
This is my HTML:

      <title>Personal Portfolio Page</title>
  <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet" type="text/css">

Who

|

Work

|

Blog

|

Contact

This is my CSS:
html {
  font-family: 'Quicksand', sans-serif;
  margin: 0;
  padding: 0;
}

body {
  margin: 0;
  padding: 0;
}

#top_nav {

}

#nav_ul {
  list-style: none;
  margin: 18.5px 20px 18.5px 20px;
  padding: 0px;
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

#nav_ul li {
  display: inline;
  margin: auto;
}

#nav_ul a {
  text-decoration: none;
  font-size: 50px;
  background-color: pink;
  margin: 0px;
  padding: 0px;
}

.nav_seperator {
  font-size: 50px;
  padding: 0;
  margin: 0;
}

@media screen and (max-width: 590px) {

  #nav_ul a{
    background-color: green;
  }

  .nav_seperator {
    display: none;
  }

}

The background color green works fine, but the separators do not disappear, any reason for this?

A: You have set your #nav_ul li to display: auto in your CSS, as #nav_ul li is a higher level of specificity than the nav_seperator it takes priority when rendered.
To combat this you should change .nav_seperator to #nav_ul .nav_seperator in your CSS and the specifier will take priority over the #nav_ul li specifier.
This:
.nav_seperator {
    display: none;
 }

Becomes this:
#nav_ul .nav_seperator {
    display: none;
}

A: Above answers will solve it, but if you can't or don't want to change your CSS for some reason try placing the separators in

 tags which should work.
E.g.

Who

|

Work

|

Blog

|

Contact


text:
Q: Is reporting on dynamic database fields an issue? For the last 30 years or so, the company I have been working for has set up static dynamic fields (the best term I can think of).
It's better described in an example. We have an employee object below:
Employee
{
    Employee Name
    Employee Number
    Address
}

Each of our clients has many employees, but may wish to save extra data - say their pets name. We do not have a field for pet's name so the choice is to either store this field for all clients, allow each client to have a different database (ugh), or allow for dynamic fields.
We took the dynamic field option, but a slight variation of it.
The question here is asking for a solution to this problem. In my opinion this is what we should have done when this decision was first made before I was born.
Our implementation below:
Employee
{
    Employee Name
    Employee Number
    Address
    FlexiField1
    FlexiField2
    ...
    FlexiField20
}

We have somewhere between 10 and 20 extra fields which are referred to internally as 'flexi fields' (flexible fields). These fields hold string values with config determining the display name (eg FlexiField3 = PetName) to the individual clients, the field type (dates will always be stored in a specified format etc) and a few other bits and pieces.
I would like to suggest to my boss that we move away from this model in favor of the answer of the question found here.
I've mentioned this before to my boss as something I didn't like, but wasn't completely sure on the alternatives. I briefly suggested a table looking something like:
CustomCustomerValues
{
    Table
    Key
    Type
    Value
}

An example entry would be {Table=Employee, Key=EmployeeNumber, Type=Integer, Value=1234}
My boss came back with 1 main point that would prevent us from pursuing this any further - reporting.
Our clients love reports. Crystal reports being the most common.
Is it possible to report nicely on dynamic fields? Currently reporting is very simple to them as it's simply "Pick fields Employee Number, Employee Name and Flexi Field 2, 3 and 4". If we had some key-value pair how would this work for reporting applications?

A: Sadly I think reporting will inevitably be more complex. If the names of the attributes are known you can add a column to your table (eg AttributeName) and join to the CustomCustomerValues table restricting by this AttributeName column. eg.
SELECT
    Employee.EmployeeName,
    Employee.EmployeeNumber,
    Employee.Address,
    CustomCustomerValues.Value as PetsName
FROM
    Employee
    LEFT JOIN CustomCustomerValues ON
        Employee.EmployeeNumber = CustomCustomerValues.Key
        AND CustomCustomerValues.Table = 'Employee'
        AND CustomCustomerValues.AttributeName = 'PetsName'

If the attribute names are unknown it will be more complex again, and you would have to employ dynamic sql.


text:
Q: Proxy-attack simulation I have a WS2008 x64 server, that has NodeJS application working on its 80 port. Server constantly receives queries from different IP-addresses that are trying to use my application as a proxy. NodeJS (working with Express module) is replying with 404 error, but fails during session initialization (using Everyauth module).
So, I've splitted the problem in two parts:

*

*I need to find the way how to simulate requests from attackers;

*Find out why these requests are processed in a wrong way (this one I will ask at another forum)
Here is a typical request from attacker:
GET http://www.baidu.com/ HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Content-Type: application/x-www-form-urlencoded
Accept: */*
Referer: http://www.baidu.com/
Host: www.baidu.com
Accept-Encoding: gzip, deflate
Proxy-Connection: Keep-Alive

I've tried to recreate it with cURL (replacing www.baidu.com with IP-address of my server in hosts)
curl -H "Host: www.baidu.com" -H "Referer: http://www.baidu.com" -H "Accept-Encoding: gzip, deflate" -H "Proxy-Connection: keep-alive" -H "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)" -H "Content-Type: application/x-www-form-urlencoded" -v -X GET http://www.baidu.com/

, but it is processed as
GET / HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Content-Type: application/x-www-form-urlencoded
Accept: */*
Referer: http://www.baidu.com
Host: www.baidu.com
Accept-Encoding: gzip, deflate
Proxy-Connection: Keep-Alive

So, my question is - how do I put http://www.baidu.com instead of / (SLASH) in GET request?

A:
So, my question is - how do I put http://www.baidu.com instead of / (SLASH) in GET request?

The request you want to have is not a bad one, but just a proxy request.
To create it just specify your target host as a proxy.
Apart from that curl might be not the right tool to generate real bad requests.


text:
Q: Recommendation needed: Rails, Postgres and fuzzy full text search I have Rails app with a Postgres backend.
I need to add full text search which would allow fuzzy searches based on Levenshtein distance or other similar metrics. Add the fact that the lexer/stemmer has to work with non-English words (it would be ok to just switch language-dependent features off when lexing, to not mess with the target language which may have meaningful words considered by English engine as irrelevant).
I guess Postgres' tsearch won't apply here as it doesn't have fuzzy search -- please correct me if I'm wrong.
What are possible combinations of backends & plugins? It'd like to prefer solutions which add less to the infrastructure (eg. if Postgres can have fuzzy fts, why use external Lucene); OTOH, the quality of Rails plugins involved is important as well.
What would you recommend?
update: seems like I'd need rather n-gram based metrics than Levenshtein.

A: Rails + Postgres + Solr + Sunspot
Solr is based on Lucene so you can take advantage of all Lucene features. Sunspot is an excellent Ruby wrapper for Solr API.
Both Sunspot and Solr work great with Rails and PostgreSQL, I used it for a project no more than one month ago.

A: PostgreSQL comes with an extension called pg_trgm (in the contrib/ directory). In my experience, it is too slow (more like a proof-of-concept implementation), but for your application it might work.

A: texticle offers beta fuzzy search for Postgres.


text:
Q: How do DP and CC change in Piet? According to the specification,

Black colour blocks and the edges of the program restrict program flow. If the Piet interpreter attempts to move into a black block or off an edge, it is stopped and the CC is toggled. The interpreter then attempts to move from its current block again. If it fails a second time, the DP is moved clockwise one step. These attempts are repeated, with the CC and DP being changed between alternate attempts. If after eight attempts the interpreter cannot leave its current colour block, there is no way out and the program terminates.

Unless I'm reading it incorrectly, this is at odds with the behaviour of the Fibonacci sequence example here:

(from: http://www.dangermouse.net/esoteric/piet/samples.html)
Specifically, why does the DP turn left at (0,3) ((0,0) being (top, left)) when it hits the left edge?  At this point, both DP and CC are LEFT, so, by my reading, the sequence should then be:

*

*Attempt (and fail) to leave the block by going off the edge at (0,4),

*Toggle CC to RIGHT,

*Attempt (and fail) to leave the block by going off the edge at (0,2).

*Rotate DP to UP,

*Attempt (and succeed) to leave the block at (1,2) by entering the white block at (1,1)

The behaviour indicated by the trace seems to be that DP gets rotated all the way, leaving CC at LEFT.
What have I misunderstood?

A: Your analysis seems correct; the sample is buggy. The white block at (1,1) should be black. You can verify this by grabbing the sample image and executing it.
Note that at least three of the interpreters linked from DMM's page are buggy - Marc Majcher's is marked as such, Sylvain Tintillier's traverses and outputs correctly but switches the meaning of in and inn from the spec (this is a bug-free version), and PietDev incorrectly traverses colour blocks.
EDIT: other white blocks probably also need to be black, e.g. the block at (6,3).


text:
Q: How can I separate javascript from PHP when the JS needs a PHP variable? Below is a small snippet from a code I saw with jquery and PHP.
Notice the PHP part on line 5, I generally put my javascript into separate files so how would I be able to keep my JS in separate files but still use PHP when needed like below?
//when the DOM is ready
$(document).ready(function(){
    //settings on top
    var domain = 'http://davidwalsh.name/';
    var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
    //function that creates posts
    var postHandler = function(postsJSON) {
        $.each(postsJSON,function(i,post) {

A: If you want to keep your Javascript separate from your PHP, then use a PHP file to generate a small chunk of Javascript just to set variables.  Then use those variables from your .js file:
HTML:
<script>
var INITIAL_POSTS = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
</script>
<script src="my.js">

my.js Javascript file:
//when the DOM is ready
$(document).ready(function(){
    //settings on top
    var domain = 'http://davidwalsh.name/';
    var initialPosts = INITIAL_POSTS;
    //function that creates posts
    var postHandler = function(postsJSON) {
        $.each(postsJSON,function(i,post) {

A: What I generally do is :

*

*put as much JS as possible in a .js file (for caching on the client-side and all that)

*this JS code uses a JS variable

*that JS variable is declared / initialized from a PHP file ; this is the only part where you need some code executed on the server-side, actually

For instance, I would have something like this, I suppose :
my-file.php :
var thisIsMyJSVar = '<?php echo $test; ?>';

So, in PHP, we declare tha variable and set its value. This is the "dynamic" part.
and, in my-file.js :
//when the DOM is ready
$(document).ready(function(){
    //settings on top
    var domain = 'http://davidwalsh.name/';
    var initialPosts = thisIsMyJSVar;  // Use the JS variable declared in the PHP file
    //function that creates posts
    var postHandler = function(postsJSON) {
        $.each(postsJSON,function(i,post) {

Here, in the static JS file, we only use the value ; nothing here is dynamic, and this file can be cached by the client -- to not be re-downloaded on each page.

The problem with that idea is the JS file depends on some initialisation done in the PHP file :-(
So, it might be a good idea to have a "default value" in the JS file, just in case...

Also, you have to have a good namming convention, to not have several files using/declaring/depending on the same JS variable ; it might be a good idea, actually, to put all your "configuration variables" inside a single javascript object, to not pollute the global namespace...

A: You can always have the php "write" the javascript file instead of having it be static- there's nothing to stop <script src="script.php">...

A: There are two basic ways to handle that that don't require mixing JavaScript and PHP at all:

*

*When PHP is generating the page, have it write that output (get_posts(0,$_SESSION['posts_start']); into a hidden input on the form (or elsewhere on the page).  JavaScript can then access this readily

*Let JavaScript fetch that output from a separate PHP request via AJAX.

Generally, if it's the sort of value that won't change while the visitor is browsing the page (or you don't care if it changes, since you won't be updating other content dynamically), write it directly onto the page.
JavaScript and jQuery can then fetch that value easily with code like
var initialPosts = $("#that-hidden-field-mentioned-earlier").val();

A: Until someone drops in a cleaner answer:
You can define a global js variable in your php/html file, and refer to it in your script:
php/html:
<script>
var global = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
</script>

js:
...
var initialPosts = global;
...

A: This should work, i mean is the file .php?
As the JS is client side, the php should be processed through the php engine BEFORE the browser processes the client side javascript?


text:
Q: Deploying Azure Function Swagger API Definition using ARM We are creating an ARM template for our Azure Function that we would like to use for deploying to different environments however we cannot figure out how to deploy the Swagger with it.
As far as we see in the ARM template there is an option to add a link to the Swagger but can the Swagger be deployed as part of the ARM template itself?


text:
Q: How to increase the "memory total" that display on Yarn UI? I have a cluster on EMR (emr-5.20.0) with a m5.2xlarge as Node Master, two m4.large as core and three m4.large as node workers. The sum of memory ram of this cluster is 62GB, but in the YARN UI the total memory displayed is 30GB.
Somebody can help me understand how this value is calculed ?
I have already check the configuration in Yarn-site.xml and spark-default.conf and them is configured according to the AWS recommendadion: https://docs.aws.amazon.com/pt_br/emr/latest/ReleaseGuide/emr-hadoop-task-config.html#emr-hadoop-task-config-m5
Every help is welcome

A: The memory settings in YARN can be configured using the below parameters of cluster:
yarn.nodemanager.resource.memory-mb
yarn.scheduler.minimum-allocation-mb
yarn.scheduler.increment-allocation-mb
yarn.scheduler.maximum-allocation-mb

My tweaking these parameters you can increase/decrease the total memory allocated to the cluster.

A: Yarn do not include the master node in it's available memory/cores.
So you should get roughly 5 x 8GB (m4.large).  You will get less than that because there are memory overhead left for the OS and services.


text:
Q: Exchange truststore on server without stopping server I am using two-way authentication of my client-server socket implementation. Code of my server where I'm loading keystore and truststore looks that :
    private void createSSLServerSocketFactory() {
    try {
        InputStream keyStoreInputStream = new FileInputStream(KEYSTORE_PATH);
        InputStream trustStoreInputStream = new FileInputStream(TRUSTSTORE_PATH);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keyStoreInputStream, KEYSTORE_PASSWORD.toCharArray());
        keyStoreInputStream.close();

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, KEYSTORE_PASSWORD.toCharArray());

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(trustStoreInputStream, TRUSTSTORE_PASSWORD.toCharArray());
        trustStoreInputStream.close();

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());

        factory = sslContext.getServerSocketFactory();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

and function run in Thread :
    public void run() {
    try {
        createSSLServerSocketFactory();
        SSLServerSocket ss = (SSLServerSocket) factory.createServerSocket(port);
        while (true) {
            SSLSocket s = (SSLSocket) ss.accept();
            s.setNeedClientAuth(true);
            SSLSession sslSession = s.getSession();
            X509Certificate x509Certificate = sslSession.getPeerCertificateChain()[0];
            String username = x509Certificate.getSubjectDN().getName().split("CN=")[1].split(",")[0];
            x509Certificate.checkValidity();
             ....
         }
   }

But I would like to change my trustore on server sometimes, but I wouldn't stop server when I do this. How can I do this? Exchange trustore.jks during server?

A: We have done something similar for a different purpose some time back. Read the trust store file on application startup and load the values in trust store to a map. Keep that map it in memory. You should also note the timestamp of that file. Now, you use those values you hold in the map for your authentication. You should also have a periodic check to see if the timestamp of trust store file on disk got changed. If file is changed, reload it to your map. You can have a daemon thread in background to do all this for you.
Hope this helps,Thanks.


text:
Q: View final query in android Cursor c = cr.query(data_uri, projection, where, selectionArgs, ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");

When the where clause contains a ? in it the data is picked up from selectionArgs so is there a way to see the final query before it is executed by the system?
Android gives the final query in the logcat when there is an error in the system but is there a way to get it otherwise?

A: Yes and no.
Under the hood many providers use SQLiteQueryBuilder to construct the SQL. You can use it to construct a SQL string and then to log it.
? variables are part of the SQL itself. Binding values to them happens after the SQL is compiled. You cannot get a "query string" with the variables replaced with corresponding literals, but you can log your selectionArgs separately.


text:
Q: Why can't I use the function in other JS file? Here's my index file
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta content="IE=Edge" http-equiv="X-UA-Compatible">
    <meta name="description" content="test">

    <!-- iOS meta tags & icons -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="test">

    <title>test</title>
</head>

<body>

    <script type="text/javascript">
        console.log('myname');
        calcbymodel('/model.json',[0,0,0,0]);
    </script>

    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/fetch-polyfill@0.8.2/fetch.js"></script><!-- fetch -->
    <script src="./babel.min.js"></script><!-- babel -->
    <script src="./app.js" type='text/babel'></script>
</body>

</html>

And here's app.js file
async function calcbymodel(path, input) {
    const model = await tf.loadLayersModel(path);
    const r = model.predict(tf.tensor(input));
    r.data().then(array => console.log(array));

    return r.data();
}

I wonder why console says:
Uncaught ReferenceError: calcbymodel is not defined
    at (index):21
(anonymous) @ (index):21

For the babel script, it could not be imported as company policy denies.
So, I imported as a local file.
Here's the link:
https://unpkg.com/@babel/standalone/babel.min.js

Can anybody help me out?

It turns out that babel script problem.
Here's the link:
Why JS cannot find the function in babel script?

A: You need to move the app.js file to above where you are using the function. In this case, you either need to move the script tag that you are using the function below the app.js script, or move the app.js script above where you use the function.
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta content="IE=Edge" http-equiv="X-UA-Compatible">
    <meta name="description" content="test">

    <!-- iOS meta tags & icons -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="test">

    <title>test</title>
</head>

<body>

    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js">
    </script>
    <script src="https://cdn.jsdelivr.net/npm/fetch-polyfill@0.8.2/fetch.js">
    </script><!-- fetch -->
    <script src="./babel.min.js"></script><!-- babel -->
    <script src="./app.js" type='text/babel'></script>
    <script type="text/javascript">
        console.log('myname');
        calcbymodel('/model.json',[0,0,0,0]);
    </script>
</body>

</html>

Because HTML loads js files in the order that they are in the file, a function can be used in any script tag below it in the HTML file.

A: The JS is executed currently in the order you have defined it:
<body>
<body>
  <!-- This is first -->
  <script type="text/javascript">
    console.log('myname');
    calcbymodel('/model.json', [0, 0, 0, 0]);
  </script>
  <!-- This is second-->
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
  <!-- This is third-->
  <script src="https://cdn.jsdelivr.net/npm/fetch-polyfill@0.8.2/fetch.js"></script>
  <!-- fetch -->
  <!-- This is fourth-->
  <script src="./babel.min.js"></script>
  <!-- babel -->
  <!-- This is fitht-->
  <script src="./app.js" type="text/babel"></script>
</body>

If you want acces in your code from to another function you need to move your first script to the bottom, the second problem seemed to be that the type="text/babel" must be set onto the babel script and not the app.
I tried it with CDN and this app:
<body>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/fetch-polyfill@0.8.2/fetch.js"></script>
  <script src="./app.js" ></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js" type="text/babel"></script>
  <script type="text/javascript">
    console.log('myname');
    calcbymodel('/model.json', [0, 0, 0, 0]);
  </script>
</body>

in app.js:
const calcbymodel = ()=>{
    console.log("make calculations");
}


text:
Q: Proving questions about posets How do I tackle a proof about posets? I have know idea how to approach this problem. Thanks!
Prove that if all subsets of a poset P have least upper bounds, then all subsets of P have greatest lower bounds.

A: Hint: Let $(P, \le)$ denote your poset and $A \subseteq P$. We want to have a greatest lower bound for $A$, so we consider the set $B = \{p \in P \mid p \le A\}$ of all lower bounds. By assumption, there is a lowest upper bound $p$ for $B$. How does it relate to $A$?


text:
Q: MySql if else statement, if not valid in this position I have a vet table and a medical table with a 1 to many relationship, and the ID's are auto incremented.
CREATE TABLE vet(
      vetID INT NOT NULL AUTO_INCREMENT,
      vetPractice varchar(35),
      Address varchar(150),
      contactNumber varchar (15),
      PRIMARY KEY (VetID)
      );

CREATE TABLE medical(
      medicalID INT NOT NULL AUTO_INCREMENT,
      medication VARCHAR (200),
      PRIMARY KEY (medicalID),
      FOREIGN KEY (vetID) REFERENCES vet(vetID)
      );

Users can enter details of a vet, i want a query to determine;

*

*if the the vet details entered already exist, then update the foreign key in vetID(medical) with the entered vetID.

*else if the vet does not exist create a new vet and update the foreign key in vetID(medical) with the newly created vetID.
I have the following query
IF EXISTS(SELECT * FROM vet WHERE vetPractice = "inputValue")
    THEN
    UPDATE medical set value vetID = (Select max(vetID) from vet)
    ELSE
    INSERT INTO vet values (null, "newVetPractice", "NewAddress", "newContactNumber", "NewEmergencyNumber" );
    Then
    update  medical set value vetID = (Select max(vetID) from vet);
END IF;

However, i am not familiar with if else's in mySQL is this the correct format, i have seen somethings about stored procedures.
Any help would be appreciate.

A: I'm not really clear about your logic; but it seems like you wanted it in a stored procedure format.
CREATE PROCEDURE 'sp_Med' (IN 'in_vetPractice' VARCHAR(35))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
BEGIN
    DECLARE ckExists int;
    SET ckExists = 0;

    SELECT count(*) INTO ckExists from vet WHERE vetPractice = in_vetPractice;

    IF (ckExists > 0) THEN
        UPDATE medical SET vetID = (Select max(vetID) FROM vet WHERE vetPractice = in_vetPractice)
    ELSE
        INSERT INTO vet VALUES (NULL, "newVetPractice", "NewAddress", "newContactNumber", "NewEmergencyNumber");
        UPDATE medical SET vetID = LAST_INSERT_ID();
    END IF;
END;

Execute it like
CALL sp_Med('newPractice')

A: I think you have to update your query, and this is the general syntax you have to use rather tha n yours:-
INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`), `c`=VALUES(`c`);

This query will insert records if they are not present, and on presence it will update them.
So use this rather than your approach


text:
Q: JClouds: Define firewall rules at Google Compute Engine I am trying to use JClouds to create instances in Google Compute Engine. I am not able to set properly the firewall rules, and the only port that is opened is the 22 (the default one).
I found nothing in the documentation and examples. The following code only opens the port 22.
How can I open some other ports, like 80, 5432, etc ?
Is there any way to open all ports ?
    final String POLL_PERIOD_TWENTY_SECONDS = String.valueOf(SECONDS.toMillis(20));

    Properties overrides = new Properties();
    overrides.setProperty(ComputeServiceProperties.POLL_INITIAL_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
    overrides.setProperty(ComputeServiceProperties.POLL_MAX_PERIOD, POLL_PERIOD_TWENTY_SECONDS);

    Iterable<Module> modules = ImmutableSet.<Module> of(new SshjSshClientModule(), new SLF4JLoggingModule());
    //Iterable<Module> modules = ImmutableSet.<Module> of(new SshjSshClientModule());

    ComputeServiceContext context = ContextBuilder.newBuilder("google-compute-engine")
            .credentials("valid email", "valid cert")
            .modules(modules)
            .overrides(overrides)
            .buildView(ComputeServiceContext.class);
    ComputeService computeService = context.getComputeService();

    Template template = computeService.templateBuilder()
            .locationId("asia-east1-a")
            .imageId("https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/ubuntu-1404-trusty-v20150128")
            .hardwareId("https://www.googleapis.com/compute/v1/projects/MY-PROJECT/zones/asia-east1-a/machineTypes/f1-micro")
            .build();

// Those options are not working as expected
    // List<String> networks = new ArrayList<>();
    // networks.add("default");
    // template.getOptions().as(GoogleComputeEngineTemplateOptions.class).networks(networks);
    // template.getOptions().as(GoogleComputeEngineTemplateOptions.class).inboundPorts(5432,1,2,3);

    Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup("m456", 1, template);

    for (NodeMetadata nodeMetadata : nodes) {
        String publicAddress = nodeMetadata.getPublicAddresses().iterator().next();
        //String privateAddress = nodeMetadata.getPrivateAddresses().iterator().next();
        String username = nodeMetadata.getCredentials().getUser();
        String password = nodeMetadata.getCredentials().getPassword();
        System.out.println(publicAddress);
        System.out.println(username);
        System.out.println(password);
    }

Thanks in advance.

A: Try using the complete URI to "default" network. For eg: "https://www.googleapis.com/compute/v1/projects/xxx-project/global/networks/default"

A: As per available providers list in JClouds homepage, support for GCE is here. Once you add it to your project, you have the following classes:

*

*org.jclouds.googlecomputeengine.domain.Firewall.Rule

*org.jclouds.googlecomputeengine.domain.Firewall.Rule.Builder

*org.jclouds.googlecomputeengine.domain.Network

*org.jclouds.googlecomputeengine.domain.Instance.Tags

Although I'm not a Java Developer myself, I bet this is what you are asking for. Using target and instances tags you can restrict the rules only to some instances. If no target targs is used, the ports in the rule will be open for all the instances in the network the rule is applied to. Hope this helps.

A: Google Compute Engine projects have two default firewall rules (on the default network) that allow inbound connections (from the internet) on ports 80 and/or 443 to any instance that has the http-server and/or https-server tag. Said tags can be defined at the moment of VM instantiation, or afterwards.


text:
Q: How far are we from the "edge" of the universe? According the the Big Bang theory, the universe started as a 0-dimensional point of infinite density. Shortly thereafter, it underwent inflation and grew to some measurable size, and continues growing to the present day.
If, when inflation started, the universe was a "ball" of some measurable size, that implies that some of the matter-energy was close to the "outside" of the ball and some was close to the "center", even if there is no "outside" of the ball.
Why is it not possible to determine how far something is from that "edge"? If the answer is that the "edge" is farther away than light travels in 13.7 Gy, I can accept that. It is still some finite distance away, albeit too large to measure.
Am I completely off in my thinking? What is wrong with my logic?


text:
Q: output from server side program in realtime I'm trying to use TCPServer to create both client and server and be able to run server side program.
server code:
require 'socket'
STDOUT.sync = true
server = TCPServer.new 8081

loop do
  Thread.start(server.accept) do | client|
    client.puts(%x[ my_external_program  ] )
    client.close
  end
end

client:
require 'socket'
s = TCPSocket.open(my_server, 8081)

while line = s.gets
  puts line.chop
end
s.close

Depending on client request different programs can be executed with differnet parameters. Problem is their execution takes a lot of time and produces really long log files which I'd like to see in real time. Unfortunately this code only prints output to socket when program is finished.
I know I could use hudson but really prefer something lighter.
Any ideas how to accomplish this?


text:
Q: Getting error when Installing Modx on GoDaddy - 500 internal server error I'm trying to install a ModX Revolution on a new hosting(Never did it before). The hosting is by GoDaddy (a windows server with a Plesk panel).
 I uploaded the modx installation files - setup and core folders, into the httpdocs directory and gave the core folder a needed permission. Now, when i'm entering to the: 'mysitename.net/setup' I'm getting the modx installation menu with language selection as it should be. But when i'm hitting the 'select' button after choosing any language, the page redirecting to the 'mysitename.net/setup/?' = 500 Internal Server Error.
Maybe some body have an idea what am i doing wrong and how to fix this issue?


text:
Q: Truncate double or add extra 0 to the decimal - Java This might be a duplicate, but I cannot find any answers that work with my code.
I'm trying to truncate my results for a method(for calculating a fee) in Java. I then try to write the results to a text file, but it's not showing like it should. This is what I get and what I'd like it to return:

*

*Result of fee is 8.4, it should return 8.40

*Result of fee is 8.0, it should return 8.00

And so on... Any suggestions please?
This is my entire code for the method:
public Double calculateFee(Parcel pcl) {
    // Get type of parcel (E, S or X)
    String typeOfParcel = pcl.getParcelID().substring(0,1);
    // Formula for calculating fee
    Double fee = (double) 1 + Math.floor(pcl.getVolume()/28000) + (pcl.getDays()-1);

    // apply a discount to parcels of type "S"
    if (typeOfParcel.equalsIgnoreCase("S")) {
        fee = fee * 0.9;
    }

    // apply a discount to parcels of type "X"
    else if (typeOfParcel.equalsIgnoreCase("X")) {
        fee = fee * 0.8;
    }

    // This is what I tried:
    // Tried also using #.##, but no result
    DecimalFormat decim = new DecimalFormat("0.00");
    fee = Double.parseDouble(decim.format(fee));

    return fee;
}

A: One way is to use String.format().
  Double fee = 8.0;
  String formattedDouble = String.format("%.2f", fee );

Note that a Double doesn't hold a formatted representation of its value.
Additional details about format strings are available here.

A: The problem here isn't that you are formatting it wrong.  You are formatting your double using:
decim.format(fee);

Then, you parse this string, back into a Double, therefore losing your formatting:
Double.parseDouble(...

Just return a String rather than a Double, and don't use Double.parseDouble.


text:
Q: Onepage checkout sidebar not updated when edit information I have magento onepage checkout process with only three step i.e

*

*billing information

*payment information

*review

when i go through the process it will update sidebar but when edit using previous step it will not reflect on sidebar.
any help would be much appreciate.


text:
Q: Copy Control in C++ template <class Type> class Queue {

    Queue(): head(0), tail(0) {
        cout << "Queue--default constructor called" << endl;
    }

    Queue(const Queue &Q): head(0), tail(0) {
        cout << "Queue--copy constructor called" << endl;
        //...
    }

    Queue& operator=(const Queue&) {
        cout << "Queue--operator= called" << endl;
        //...
    }
    ~Queue() { //... }

private:
    QueueItem<Type> *head;
    QueueItem<Type> *tail;
};

I have defined a template class Queue and tried the codes below:
Queue<char*> cq;
Queue<char*> ccq(cq);
Queue<char*> acq = cq;
Queue<char*> acq2;
acq2 = cq;

and the output is:
Queue--default constructor called
Queue--copy constructor called
Queue--copy constructor called
Queue--default constructor called
Queue--operator= called

what confuse me is the code Queue<char*> acq = cq; has invoked the copy constructor Queue--copy constructor called but not the default constructor and operator= to be called.
Could any one help me?
Thank you for considering my question!

A: This is defined in the standard, it's in the section Explicit initialization

1
  Explicit initialization
  [class.expl.init]
  An object of class type can be initialized with a parenthesized expression-list, where the expression-list
  is construed as an argument list for a constructor that is called to initialize the object. Alternatively, a
  single assignment-expression can be specified as an initializer using the = form of initialization. Either
  direct-initialization semantics or copy-initialization semantics apply; see 8.5.

This is the case describing single assignment-expression and copy-initialization semantics.
Technically there's no difference between the two forms ccq(cq) and acq = cq, as you have already seen from the output.

A: This is called "copy initialization" and C++ standard requires that
Queue<char*> acq  = cq;

shall be equivalent to
Queue<char*> acq (cq);

No mistake here.


text:
Q: Why is switch/case for characters not working? Ignoring lines 1-55, can someone tell me why my switch isn't working for characters ' v ' and ' | ' whenever they appear? I put some print line statements (line 57, 58) to see what's going on, but they don't even get executed!
Only line 56 executes and then it continues reading the file for more characters, skipping the process for ' v ' and ' | ' characters...
Every other switch works fine, excluding those two.
input is a BufferedReader for a text file that looks like this
test.txt
50
5
3
0
s-o o-o-o
| v v | v
o-o-o-oho
v |   v |
o-o-o-e-o

Here is the relevant portion of code:
// loop through remaining lines of file
while (line != null) {
    // get characters in the line
    for (int j = 0; j < line.length(); j++) {

        // if character is even, it is a node
        ch = line.charAt(j);
        if (j % 2 == 0) {
            System.out.println("character even and is: " + ch);
            switch (ch) {
            case 's':
                System.out.println("s test worked");
                break;
            case 'e':
                System.out.println("e test worked");
                break;
            case 'o': // increase the node count
                break;
            }
        }

        // else character is odd, it is an edge
        else {
            System.out.println("character odd and is: " + ch);
            System.out.println(ch == 'v'); // Line 57
            System.out.println(ch == '|'); // Line 58
            switch (ch) {
            // horizontal wall
            case 'h':
                System.out.println("h test worked");
                break;
            // horizontal hall
            case '-':
                System.out.println("- test worked");
                break;
            // vertical wall
            case 'v':
                System.out.println("v test worked");
                break;
            // vertical hall
            case '|':
                System.out.println("| test worked");
                break;
            // unbreakable wall
            case ' ': // don't do anything
                break;
            }
        }
    }
    line = input.readLine();
}

Here is a link to complete, compilable code, given that you give the program the text file as an argument.

A: This is because your code assumes that all edges are located in odd positions. However, this is correct only about the horizontal edges; the vertical edges (i.e. ones on odd-numbered lines) are located in even positions.
You can fix this by adding a line counter, like this:
int lineCounter = 0;
while (line != null) {
    // get characters in the line
    for (int j = 0; j < line.length(); j++) {
        // if character is even, it is a node
        ch = line.charAt(j);
        if ((lineCounter+j) % 2 == 0) {
            ...
        } else {
            ...
        }
    }
    line = input.readLine();
    lineCounter++;
}

This code looks for edges in odd positions on even-numbered lines, and in even positions on odd-numbered lines.


text:
Q: Bash Script execution too long I'm having a trouble with one script that I've made, time execution is too long (like 24 min), but the time is variable (depends of log's) and in the near future the time will increase for sure.
The troube is in a nesteed for loop:
obtener_ErroresLanzados()
{
        #Buscamos los equipos del log lanzados_a_pendientes en los logs de instala_sw_qcc para ver el porque no se han lanzado.
        totalLanzadosPendientes=`cat $rutaTemporales/lanzados_a_pendientes.log | wc -l`;
        lanzadosPendientes=$(cat $rutaTemporales/lanzados_a_pendientes.log);
        #grep "$paqueteBuscado" instala_sw_qcc_2012*.log | cut -f 1 -d ":" > $rutaTemporales/logsErrores.log;
        find $rutaTrazas -name "instala_sw_qcc_2012*" | xargs grep -l "$rutaQcc/$paqueteBuscado" | xargs grep -l "ERROR \[" | cut -f 9 -d "/" > $rutaTemporales/logsErrores.log;
        logsErrores=$(cat $rutaTemporales/logsErrores.log);
        totalLogsErrores=`cat $rutaTemporales/logsErrores.log | wc -l`;

for (( j=1; j<=$totalLanzadosPendientes; j++ ))
    do
equipoBusqueda=`echo $lanzadosPendientes | cut -f $j -d " "`;
            for (( k=1; k<=$totalLogsErrores; k++ ))
            do
            logBusqueda=`echo $logsErrores | cut -f $k -d " "`;
            grep "ERROR \[$equipoBusqueda\]" $rutaTrazas/$logBusqueda >> $rutaTemporales/erroresPendientes.log;
            if [ $? -eq 0 ];then
                    break;
            fi;
                    done;
    done;
    cat $rutaTemporales/erroresPendientes.log | sed 's/  / /g' | sed '/No se ha podido/d' | cut -f 7-14 -d " " | sort -u > $rutaTemporales/erroresPendientes_Final.log;
}

The problem is with $totalLogsErrores that is larger than 20k...
Can I do this by other way?
Thanks you!
----------------------- EDIT 1 -----------------------
$ time find $rutaTrazas -name "instala_sw_qcc_2012*" | xargs grep -l "$rutaQcc/$paqueteBuscado" | xargs grep -l "ERROR [" | cut -f 9 -d "/"

real 0m3.862s
user 0m0.959s
sys 0m2.941s

$ du -h ../trazas/instala_sw_qcc_20120718091838.log

4.0K ../trazas/instala_sw_qcc_20120718091838.log

$ time grep error ../trazas/instala_sw_qcc_20120718091838.log

real 0m0.001s
user 0m0.001s
sys 0m0.000s

A: To qualify this performance issue, you can try the following:
Assess the impact of your first find & grep commands:
$ time find $rutaTrazas -name "instala_sw_qcc_2012*" | xargs grep -l "$rutaQcc/$paqueteBuscado" | xargs grep -l "ERROR \[" | cut -f 9 -d "/" > $rutaTemporales/logsErrores.log;

In your nested for loops, assess the impact the grep. How big are the files? In your comment you mentioned 100*10000 repetition, which is huge if each grep took 4 ms.
The find becomes expensive when you have a lot of sub-directories and the grep becomes expensive when your files are large enough.
$ du -h file.out
  20K   file.out

$ time grep ERROR file.out

real    0m0.004s
user    0m0.000s
sys     0m0.003s

if you have 1000000 loops, that will take a lot :)

A: useless use of cat : wc -l <file instead of cat file | wc -l
useless use of wc : while read line; do ...;done <file instead of for loop :
find $rutaTrazas -name "instala_sw_qcc_2012*" | xargs grep -l "$rutaQcc/$paqueteBuscado" | xargs grep -l "ERROR \[" | cut -f 9 -d "/" > $rutaTemporales/logsErrores.log;
while read equipoBusqueda; do
    while read logBusqueda; do
        grep "ERROR \[$equipoBusqueda\]" $rutaTrazas/$logBusqueda >> $rutaTemporales/erroresPendientes.log
        if [ $? -eq 0 ];then
            break;
        fi;
    done <$rutaTemporales/logsErrores.log
done <$rutaTemporales/lanzados_a_pendientes.log
cat $rutaTemporales/erroresPendientes.log | sed 's/  / /g' | sed '/No se ha podido/d' |
    cut -f 7-14 -d " " | sort -u > $rutaTemporales/erroresPendientes_Final.log;

finally find, grep, sed, cut, etc. commands may be simplified.

A: Yo are reading the whole file into a shell variable and then extracting every line with a
separate cut process. This is very inefficient.
It is difficult to decipher what are you trying to do. Maybe you could replace the function
with something like this:
$ cd $rutaTrazas
$ sed 's/^/ERROR \[/; s/$/\]/' $rutaTemporales/lanzados_a_pendientes.log > search_strings
$ xargs grep -F -f search_strings \
    < $rutaTemporales/logsErrores.log \
    >> $rutaTemporales/erroresPendientes.log
$ < $rutaTemporales/erroresPendientes.log \
    sed 's/  / /g' | sed '/No se ha podido/d' |
    cut -f 7-14 -d " " |
    sort -u > $rutaTemporales/erroresPendientes_Final.log

A: Inefficient Processing with Loops
It's almost impossible to figure out what you're really trying to do here, as there's no corpus or sample output showing what you're actually trying to parse. However, you can boil this problem down to inefficient processing and process forking.
Use AWK for Record-Oriented Operations
Log files are generally record-oriented, where each line is a record with multiple fields. If this is your use case, then AWK (or Perl/Ruby in AWK emulation mode) is usually the right tool for the job. This ensures that you handle each line only once, and reading lines and splitting fields is extremely efficient.
For example, with Bash 4 and GNU awk (a.k.a. gawk):
shopt -s globstar
awk 'BEGIN {error_count = 0}
     /ERROR/ {print $9; ++error_count}
     # other pattern/action pairs
     END {print "Total errors:", error_count}
    ' **/instala_sw_qcc_2012* > /path/to/output/file

You can have multiple pattern matches that are applied to each line, or direct output to individual files from inside awk if you really need to do that. However, by letting awk handle the loops and the line parsing in one process, you are likely to gain a great deal of efficiency.


text:
Q: Azure AD B2C: Bad Request - Request Too Long HTTP Error 400. The size of the request headers is too long. After login I know a similar question is already asked earlier at stack overflow but it didn't worked for me. Kindly read the entire question before answering/commenting.
I have implemented AD B2C in two web application all were working fine till last week. Now all of a sudden we are getting

Bad Request - Request Too Long HTTP Error 400. The size of the request
  headers is too long.

when the user tries to login into the website. Since my website requires every user to be logged in, it has blocked us completely.
My web app are also not working in incognito/inprivate window. Browser: Chrome, Firefox and Edge
When I open the application in chrome(not incognito) after deleting all the history I can see there are around 160+ cookies from the the web app url.
Yes too much cookies seems to be killing my webapp, but its happening even after deleting all the history of browser and in private browsing too.
Even I have reduced the claims attribute to 3 suspecting that more claims attributes might be increasing the header size.

I have tried this too but in vain.
Bottom Line: Deleting cookies and reducing claims both are not working for us and we are blocked. Thanks in advance.

A: I got this fixed after raising a ticket with Microsoft Support team.
Cause: There is a well-known issue with Owin Middle ware where it doesn't set the authentication cookie and we end up being in a login loop. I was using an older version of OWIN.
Resolution: OWIN Version 3.1.0.0 has integrated the fix in terms of a cookie manager.
NOTE: In-spite of using the fix, we can run into issues if we have custom SESSIONSTATE handler being used in the application. In STARTUP.AUTH.CS, we will need to make the following changes
Old:
app.UseCookieAuthentication(new CookieAuthenticationOptions{});

New:
app.UseCookieAuthentication(new CookieAuthenticationOptions   {
      AuthenticationType = "Cookies",
      CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
  });

Below is the question discussing the same:
Second sign-in causes infinite redirect loop after the first successful login MVC .NET 5 OWIN ADAL OpenIDConnect
Hope this helps other.
Happy Coding.


text:
Q: Add PS Profile to a new local user I want to create a Powershell profile for a new local user. This new local user is just a copy of Administrator account.
My function function works when profile has been initialized. But it don't work when the Windows profile is not created yet (user still not logged in since the creation of account).
Here is my try:
function add-PSProfile
{
    [CmdletBinding()]
    Param
    (
        [Parameter( Mandatory=$true )]
        $Login,
        [Parameter( Mandatory=$true )]
        [ValidateScript({Test-Path $_})]
        $RemoteProfilePath
    )

    # Get default profiles directory
    $ProfilesDirectory = ( Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' -ErrorAction Stop ).ProfilesDirectory

    $ProfilePath       = Join-Path $ProfilesDirectory $Login
    $PSProfilePath     = Join-Path $ProfilePath 'Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'

    if( -not ( Test-Path $PSProfilePath ) )
    {
        New-Item -ItemType File -Path $PSProfilePath -Force
    }

    Copy-Item $RemoteProfilePath $PSProfilePath
}

Do you have any suggestion?
Thanks for your help :)


text:
Q: binding MultiSelectionModel to checkBoxColumn in CellTable, but why checkBoxs in column were not AUTO-selected CORRESPONDINGLY to SelectionModel? Here is my problem.
I have simple table with 3 columns (Id, no, text) Id and no combination creates a unique key for each row.

Id - no - text
12 - 1 - my text1
12 - 2 - my text2
13 - 1 - cool
13 - 2 - cool2
13 - 3 - cool3

Now, i want to load these data into a CellTable with 4 columns (the 1st column is checkBoxColumn, the other 3 columns are ID/No/Text textcolum. I also want to put a SelectAllCheckBox on the Header of checkBoxColumn so that when user click on selectAllCheckBox then all the current visible checkBoxes got selected (of cause celltable could have many page but it will select only the visible ones).
Here is the code, i finished all the requirements except 1, that is "when i clicked the selectAllCheckBox, the selectionModel got selected but the correspondingly checkBoxes were not selected.
Here is the Code.
public static final ProvidesKey<String[]> KEY_PROVIDER = new ProvidesKey<String[]>() {
      @Override
      public Object getKey(String[] item) {
        String[] itemArr={item[0],item[1]};
        return item == null ? null : itemArr;

      }
};

Here is the main CellTable  code:
final MultiSelectionModel<String[]> selectionModel = new MultiSelectionModel<String[]>(KEY_PROVIDER);

final CellTable<String[]> cellTable = new CellTable<String[]>();

Column<String[], Boolean> checkColumn = new Column<String[], Boolean>(
                new CheckboxCell(true, false)) {
        @Override
        public Boolean getValue(String[] object) {
                // Get the value from the selection model.
                 String[] objectArr={object[0],object[1]};

                 return selectionModel.isSelected(objectArr);

         }
 };

 cellTable.setSelectionModel(selectionModel);
 CheckboxHeader selectAllCheckBoxHeader = new CheckboxHeader();
 selectAllCheckBoxHeader.addValueChangeHandler(new ValueChangeHandler(){

            @Override
            public void onValueChange(ValueChangeEvent event) {
                // TODO Auto-generated method stub
                System.out.println("test");
                for (String[] item : cellTable.getVisibleItems()) {

                    if (!selectionModel.isSelected(item)) {
                        System.out.println(Arrays.toString(item));
                      selectionModel.setSelected(item, true);

                    }
                }
            }

  });
  cellTable.addColumn(checkColumn, selectAllCheckBoxHeader);

When I clikced the selectAll, then non of visible checkBoxes got check, but when printout
Set<String[]> selSet=selectionModel.getSelectedSet();
for(String[] s : selSet){
  System.out.println("Mine: "+Arrays.toString(s));
}

it showed the currect selected items
Suppose pageSize is 3, then
Output :

Mine: [12,1,my text1]
Mine: [12,2,my text2]
Mine: [13,1,cool]

So how to make visible checkBoxes got selected automatically EXACTLY and CORESPONDINGLY /In TANDEM as the selectionModel got selected
Note: I also tried cellTable.setSelectionModel(selectionModel, DefaultSelectionEventManager.<String[]> createCheckboxManager()); but not working.

A: i fixed
first, just use item[]
public Object getKey(String[] item) {
     return item == null ? null : item;
}

& then
public Boolean getValue(String[] object) {
     return selectionModel.isSelected(object);
}

then use
cellTable.setSelectionModel(selectionModel, DefaultSelectionEventManager.<String[]> createCheckboxManager());

Finally, it works as i expected


text:
Q: Two seemingly contradict ways of obtaining this limit The limit is :
$$
\lim_{x\to 0} f(x)= \lim_{x\to 0}( \frac{2}{x}-\frac{(x^2+1)\ln(\frac{1+x}{1-x})}{x^2})
$$
method 1:
$$
\lim_{x\to 0} f(x)=\lim_{x\to 0}(\frac{2}{x}-\frac{\ln(\frac{1+x}{1-x})}{x^2})=\lim_{x\to 0}(\frac{2}{x}-\frac{\frac{2}{1-x^2}}{2x})=-\lim_{x\to 0}\frac{2}{x}\to -\infty
$$
method 2:
$$
\lim_{x\to 0} f(x) =\lim_{x\to 0} \frac{2x-(x^2+1)\ln(\frac{1+x}{1-x})}{x^2} =\lim_{x\to 0}\frac{2x-\ln(\frac{1+x}{1-x})}{x^2}=\lim_{x\to0}\frac{2-\frac{2}{1-x^2}}{2x} =0
$$
Question is which is right, why the other is incorrect? please help me point out the error.

A: The first method is definitely wrong. Essentially what you are doing is saying that $\lim_{x\to 0}(a(x) - b(x)) = \lim_{x\to 0} a(x) - \lim_{x\to 0} b(x)$. This is valid only if each individual limit on the right exists.
For method 2, as A.G. pointed out, you can't just get rid of $x^2+1$. Instead, you should note that as $x\to 0$,
$$\frac{2x-(x^2+1)\ln(\frac{1+x}{1-x})}{x^2}\to \frac{0}{0},$$
so that L'Hopital's Rule applies. Differentiating, you get
$$
\lim_{x\to 0} \frac{2x-(x^2+1)\ln(\frac{1+x}{1-x})}{x^2}
   = \lim_{x\to 0} \frac{2 - 2x\ln(\frac{1+x}{1-x}) - (x^2+1)\frac{2}{1-x^2}}{2x}.
$$
As $x\to 0$, both numerator and denominator again go to zero; applying L'Hopital again gives
$$\lim_{x\to 0} \frac{-2\ln\frac{1+x}{1-x} - 2x\frac{2}{1-x^2} - 2x\cdot\frac{2}{1-x^2} - (x^2+1)\cdot\frac{4x}{(x^2-1)^2}}{2}.$$
This limit can be evaluated by simply setting $x=0$, giving $0$ for the limit.
It's important to remember what A.G. said. When evaluating a limit, you can't arbitrarily set a variable to a value in one place and leave it alone somewhere else.

A: Easy algebra gives
\begin{eqnarray*}
\frac{2}{x}-\frac{(x^{2}+1)\ln \left( \frac{1+x}{1-x}\right) }{x^{2}} &=&%
\frac{2}{x}-\frac{\ln \left( \frac{1+x}{1-x}\right) }{x^{2}}-\ln \left(
\frac{1+x}{1-x}\right)  \\
&=&\frac{x+x-\ln (1+x)+\ln (1-x)}{x^{2}}-\ln \left( \frac{1+x}{1-x}\right)
\\
&=&\left( \frac{x-\ln (1+x)}{x^{2}}\right) +\left( \frac{x+\ln (1-x)}{x^{2}}%
\right) -\ln \left( \frac{1+x}{1-x}\right)
\end{eqnarray*}
By L'hospital rule twice, it follows that
\begin{equation*}
\lim_{x\rightarrow 0}\frac{x-\ln (1+x)}{x^{2}}=\frac{1}{2}
\end{equation*}
\begin{equation*}
\lim_{x\rightarrow 0}\frac{x+\ln (1-x)}{x^{2}}=-\frac{1}{2}
\end{equation*}
then
\begin{equation*}
\lim_{x\rightarrow 0}\left( \frac{2}{x}-\frac{(x^{2}+1)\ln \left( \frac{1+x}{%
1-x}\right) }{x^{2}}\right) =\frac{1}{2}-\frac{1}{2}-0=0.\ \ \ \blacksquare
\end{equation*}


text:
Q: What do the seasons mean? It's the last day of Summer, and a question came to my mind; In Greek, every season has a meaning:
Άνοιξη    - ανοίγουν τα λουλούδια // the flowers 'open'
Καλοκαίρι - καλός καιρός          // good weather
Φθινόπωρο - φθήνουν τα οπωρικά    // the fruits 'decline'
Χειμώνας  - χειμα = κρύο,ψύχος    // an ancient word, had to ask mama

But what about the English ones? The only results I get from Google are some ridiculous pages - like what is the inner meaning for me personally and stuff..Come someone explain? Or if they don't have, state it in an answer...

A: Here are a few snippets from an interesting article by Daven Hiskey.
Winter:

[...]  probably comes from the Proto-Indo-European (PIE) *wed, meaning "wet".  Alternatively, it may come from the PIE *wind-, meaning "white"

Spring:

plants springing from the ground [...]

Summer:

[...]  a variant of the Proto-Indo-European *sem- meaning "together / one"

Autumn:

[...]  it's thought "autumnus" probably came from an Etruscan word and is possibly related to the Latin "augere" meaning "to increase" [...]  and became common in the 16th century, about the same time calling it "fall" popped up as the name for the season.  Before calling the season "autumn" or "fall" in English, it was called "harvest".

Note 1. Here I'm focusing on word meanings  whereas the original article is more wide-ranging and discusses the words' evolution.
Note 2. As discussed in comments this is a brief summary of someone else's work. I don't want to duplicate the entire article here. The only changes from original is the use of bold text to highlight what I think most interesting.


text:
Q: Javascript Strings, HTML and Character Entities in Dojox Charting Labels I am trying to use HTML in dojox charting pie chart label string
text: 'hello^_^world'

Using the chrome inspector on the pie chart label string, the output is

  "hello"
  ^_^world

So obviously the span tag is not working because for some reason,
it decided to unescape the space entity AND wrap the tag around "world" too.
This is very strange and unexpected behaviour, and I would like to hear from anyone who may know what is going on here.
Thanks,
aylz5073


text:
Q: Paging for ASP.net Repeater control with functionality to show next 10 pages I am using a paging function for repeater control and i have modified a script taken from following link
http://www.dotnetfunda.com/articles/article456-custom-seo-friendly-paging-with-aspnet-repeater-or-datalist-control-.aspx
i have modified it to some extent and it is working fine
and paging is now displayed as
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
Paging function working fine but i need to modify script so that it will display first 5 Pages and next 5 page once user hits the next 10 Link along with Last and First Previous  Functionality
Example based on above scenario
First - Previous 1 | 2 | 3 | 4 | 5 Next5 - Last
if i hit the Next5 link then it should display
First - 5Previous 6 | 7 | 8 | 9 | 10 Next - Last
Below is the code function and my stored procedure a
private string GetPagingDone(int thisPageNo, int totalCount, int pageSize, string pageName, int LangID, string extraQstringToAdd)
{
    int pageno = 0;
    int start = 0;
    int loop = totalCount / pageSize;
    int ilimit = 5;
    int remainder = totalCount % pageSize;
    StringBuilder strB = new StringBuilder("", 500);
    for (int i = 0; i < loop; i++)
    {
        pageno = i + 1;
        if (pageno.Equals(thisPageNo))
            strB.Append(pageno + "  ");
        else
            strB.Append("" + pageno + "  ");
        if (i + 1 == loop)
        { strB.Append("  "); }
        else
        { strB.Append(" | "); }
        start += pageSize;
    }
    if (remainder > 0)
    {
        pageno++;
        if (pageno.Equals(thisPageNo))
            strB.Append("" + pageno + "  ");
        else
            strB.Append("" + pageno + "  ");
    }

    return strB.ToString() + "";
}

ALTER PROCEDURE [dbo].[usp_ArticleListPaging]
        @startRowIndex int,
        @pageSize int,
        @LangID int,
        @totalCount int output
    AS
    BEGIN
        SET NOCOUNT ON;
        SET @totalCount = 0
        SET @startRowIndex = @startRowIndex + 1
        BEGIN
           SELECT * FROM ( Select art_Articles.*, ROW_NUMBER() OVER (ORDER BY art_Articles.ArticlePublishDate DESC) as RowNum
           FROM art_Articles WHERE art_Articles.ArticleActive = 1 AND art_Articles.ArticleVisible = 1 AND LanguageID =@LangID) as ArticleList
           WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @pageSize) - 1 ORDER BY ArticlePublishDate DESC
           SELECT @totalCount = Count(ArticleID) FROM art_Articles WHERE art_Articles.ArticleActive  = 1 AND art_Articles.ArticleVisible = 1 AND LanguageID =@LangID
        END
    END

I have to modify the same code to use this functionality. I tried if for several hours but could not get it right so . any help in this is highly appreciated
I am not sure why i am being given -ve for asking this kind of question

A: here is an example which extends the repeater to work with another inbuilt control called the 'DataPager' which should do all you want.
http://www.codeproject.com/Articles/45163/Extend-Repeater-to-support-DataPager
And another
http://www.dot4pro.com/extend-repeater-support-datapager.html
Some examples on how to use it
http://www.c-sharpcorner.com/uploadfile/nipuntomar/datapager-in-Asp-Net-3-5/


text:
Q: What would be the opa policy in .rego for the following examples? I am new to opa and k8s, i dont have much knowledge or experience in this field. i would like to have policy in rego code (opa policy) and execute to see the result.
the following examples are:

*

*Always Pull Images - Ensure every container sets its 'imagePullPolicy' to 'Always'

*Check for Liveness Probe - Ensure every container sets a livenessProbe

*Check for Readiness Probe - Ensure every container sets a readinessProbe

for the following, i would like have an opa policy:
1.Always Pull Images:
apiVersion: v1
kind: Pod
metadata:
  name: test-image-pull-policy
spec:
  containers:
    - name: nginx
      image: nginx:1.13
      imagePullPolicy: IfNotPresent

2.Check for Liveness Probe
3.Check for Readiness Probe
containers:
- name: opa
  image: openpolicyagent/opa:latest
  ports:
  - name: http
    containerPort: 8181
  args:
  - "run"
  - "--ignore=.*"            # exclude hidden dirs created by Kubernetes
  - "--server"
  - "/policies"
  volumeMounts:
  - readOnly: true
    mountPath: /policies
    name: example-policy
  livenessProbe:
    httpGet:
      scheme: HTTP           # assumes OPA listens on localhost:8181
      port: 8181
    initialDelaySeconds: 5   # tune these periods for your environemnt
    periodSeconds: 5
  readinessProbe:
    httpGet:
      path: /health?bundle=true  # Include bundle activation in readiness
      scheme: HTTP
      port: 8181
    initialDelaySeconds: 5
    periodSeconds: 5

Is there any way to create the opa policy for the above conditions. Could any one help as i am new to opa. Thanks in advance.

A: For the liveness and readiness probe checks, you can simply test if those fields are defined:
package kubernetes.admission

deny["container is missing livenessProbe"] {
  container := input_container[_]
  not container.livenessProbe
}

deny["container is missing readinessProbe"] {
  container := input_container[_]
  not container.readinessProbe
}

input_container[container] {
  container := input.request.object.spec.containers[_]
}

A: #Always Pull Images

package kubernetes.admission

deny[msg] {
        input.request.kind.kind = "Pod"
        container = input.request.object.spec.containers[_]
        container.imagePullPolicy != "Always"
        msg = sprintf("Forbidden imagePullPolicy value \"%v\"", [container.imagePullPolicy])
}


text:
Q: Fluent NHibernate: Mapping Bool Property to ORACLE DB I want to mapping bool c# property to Oracle DB. I tried several methods for this. But didn't work. There is no example on web for best solution.
My entity as bellow:
 public class Department : EntityBase<short>
{
    [JsonIncludeProperty(NameOfSet = "list")]
    public virtual string Name { get; set; }

    public virtual  Department ParentDepartment { get; set; }
    public virtual IList<Department> ChildDepartments { get; set; }
    // Bool value
    public virtual bool IsActive { get; set; }
}

From this Fluent mapping example:
public class DepartmentMap : ClassMap<Department>
{
    public DepartmentMap()
    {
        Table("DEPARTMENTS");
        LazyLoad();
        Id(x => x.Id)
            .GeneratedBy.Sequence("DEPARTMENTS_SEQ")
            .Not.Nullable()
            .Column("DEPARTMENT_ID")
            .CustomSqlType("NUMBER(5,0)");
        Map(x => x.Name).Not.Nullable().Column("DEPARTMENT_NAME").CustomSqlType("NVARCHAR2(100)");

        Map(department => department.IsActive).Not.Nullable().Column("IS_ACTIVE").CustomType<YesNoType>();

        HasMany(x => x.ChildDepartments)
            .AsList()
            .Inverse()
            .Cascade.All()
            .KeyColumn("PARENT_DEPARTMENT_ID");

        References(x => x.ParentDepartment, "PARENT_DEPARTMENT_ID");
    }
}

But this and other methods do not work. Please help me.

A: The example uses a user type. It needs to be implemented somewhere.
By default, booleans are stored in number columns. From Oracle8iDialect.cs (this line is derived by 9i and 10i):
RegisterColumnType(DbType.Boolean, "NUMBER(1,0)");

By default, you need such a number column in the database, then you can map it without special type configuration:
  Map(department => department.IsActive).Not.Nullable().Column("IS_ACTIVE");

If you want to have another type in the database, you can specify an SQL type or your own user type.
The simplest way to have your mappings and database schema aligned is by generating the schema from the mappings using the NHibernate schema generator. You can only create an SQL create tables script for review purposes if you don't  like your schema being created fully automatically.