Issue with SQL thinking my table name is a full table when I cast or convert it to a string

Question: So I got a problem looks like with string conversion. I have tried everything under the sun. My goal is to inert the values from the loop into the table. However I can get the field value but I can not get the table name value due to sql thinks I am calling a table rather than a string. I have tried casting converting everything. Here is the code sample:
DECLARE @C varchar(65)
DECLARE @FieldName varchar(50)
SET @FieldName = 'ProjectID'
SELECT @C = MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'Base Table'

CREATE TABLE #temp_t (
    [field] varchar(100),
    [tblname] varchar(100)
    )

WHILE @C is not null
    BEGIN
        DECLARE @qbExists int
        DECLARE @tblname varchar(100)
        SET @tblname = CONVERT(varchar(100), @C)
        SELECT @qbExists = COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @C AND COLUMN_NAME = @FieldName
        IF @qbExists = 1 AND
           @C <> 'TimeExpenseUnionQuery' AND
           @C <> 'TimeExpense' AND
           @C <> 'BC_BA' AND
           @C <> 'BC_BE' AND
           @C <> 'BC_EL' AND
           @C <> 'BC_TE'
          BEGIN
            EXEC('
                  SELECT ' + @FieldName + ', ' + @C + ' FROM ' + @tblName +'
                 ')
          END

        SELECT @C = MIN( TABLE_NAME ) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME > @C
END

SELECT * FROM #temp_t

DROP TABLE #temp_t

The problem child lies within the SELECT ' + @FieldName + ', ' + @C + ' FROM ' + @tblName.
Now if I do not use the @C it works fine. If I try to CONVERT or CAST the @C I get an invalid column name? What gives?
Answer: You need to quote it to make it a constant, which requires doubling up because of dynamic SQL
EXEC('
              SELECT ' + @FieldName + ', ''' + @C + ''' FROM ' + @tblName +'
             ')

Whether the use of dynamic SQL is a good idea or not is a different matter...
Comment: I love you, wow how could I miss that. Thank you very much buddy!
Answer: One thing that's always a good idea when developing dynamic SQL solutions like you're doing here is printing out the statement first and making sure that it looks like you want it to.  I think the other answerers have the gist of it: it seems that you're trying to print out a string literal of your table name.  If that's the case, you'll need to surround it in quotes in the query that gets executed, which means some work when you're building the query.
Answer: It looks like you're trying to execute:
SELECT <fieldname>, <tablename> FROM <same tablename>

e.g.
SELECT ProjectID, myTable FROM myTable

Do you mean to put the tablename in quotes?


Jetty8 virtual hosts

Question: I have a server JAR that is deployed once per customer, it is the API server for their software package. To that end, the port for each API instance must be the same, so that anything programmed against it can always find it. Each instance is deployed on a different domain name
The problem I'm having is that, even when using a SelectChannelConnector and setting the host property, I can't get two instances to run simultaneously, I get a BindException with  "Address already in use".
I suppose my question is: can Jetty do this, or do I need to do some external re-writing, or is there a better way I can go about achieving the same ends?
Thanks.
Comment: Are you running the API server code for several customers on a single machine of yours? Are you testing or hosting it?
Answer: Assuming that I understand what you are trying to do, it seems the easiest way is to front your jetty instances with apache. Set apache up with virtual hosts and the appropriate configuration to send each virtual host's requests to the appropriate jetty instance.
Comment: Thanks Allen, this is roughly what I did, but I used Jetty instead, and each API instance tells the Jetty proxy server which port to find it on, and the Jetty proxy forwards the request appropriately.
Answer: A bit late maybe but, it this what you're looking for? You'll configure a single connector (because you're listening on a single port) but let it answer for different domain names, and then you configure each webapp to answer to only a single domain. You can even make them have the same context path, so the only thing you change in your client code is the domain name.

Jetty8 virtual hosts


If $h(t)=-16t^2+80t$ then simplify $\frac{h(a)-h(1)}{a-1}$

Question: I am to simplify $\frac{h(a)-h(1)}{a-1}$ given $h(t)=-16t^2+80t$. The solution provided is
$\frac{-64+80a-16a^2}{-1+a}$ = $-16a+64$
I cannot see how this was arrived at. Here's as far as I got:
$\frac{h(a)-h(1)}{a-1}$
$\frac{(-16a^2+80a)-(-16+80)}{a-1}$ # substitute in the function h(t)
$\frac{-16a^2+80a-64}{a-1}$ # simplify numerator
$\frac{16(-a^2+5a-4)}{1-a}$ # 16 is a common factor in the numerator, attempted to simplify
...
I was not able to factor $-a^2+5a-4$
How can I arrive at the provided solution? More granular baby steps appreciated.
Answer: We have that
$$\frac{-16a^2+80a-64}{a-1}=\frac{-16(a^2-5a+4)}{a-1}$$
and
$$a^2-5a+4=(a-4)(a-1)$$
indeed by quadratic equation for $a^2-5a+4=0$
$$a_{1,2}=\frac{5\pm \sqrt{25-16}}{2}=4,1$$
that is
$$a^2-5a+4=(a-a_1)(a-a_2)=(a-4)(a-1)$$
therefore providing that $a\neq 1$
$$\frac{-16(a^2-5a+4)}{a-1}=\frac{-16(a-4)(a-1)}{a-1}=-16(a-4)=-16a+64$$
Answer: Sometimes it's helpful (but not really necessary) to have positive leading coefficients on the terms of highest power.
$$\begin{align}
\frac{16(-a^2+5a-4)}{1-a} &= \frac{-16(a^2-5a+4)}{-(a-1)}\\
&= \frac{-1}{-1}\cdot\frac{16(a^2-5a+4)}{a-1}\\
&= \frac{16(a^2-5a+4)}{a-1}\\
\end{align}$$
In order to factor the polynomial in the numerator, we need to find two numbers that when multiplied together give $4$ and when added give $-5$. But, we can also make the guess that the denominator is a factor of the numerator (because the question asks us to "simplify").
$$\begin{align}
\frac{16(a^2-5a+4)}{a-1} &= \frac{16(a^2-a-4a+4)}{a-1}\\
&= \frac{16(a(a-1)-4(a-1))}{a-1}\\
&= \frac{16(a-4)(a-1)}{a-1}\\
&= \frac{16(a-4)}{1}\cdot\frac{a-1}{a-1}\\
&= \frac{16(a-4)}{1}\cdot1\\
&= \frac{16(a-4)}{1}\\
&= 16(a-4)\\
\end{align}$$
Comment: Thanks, this was also very helpful for understanding.


Let $\{x_n\}\subseteq \mathbb{R}^n$. Prove that the following statements are equivalent

Question:
Let $\{x_n\}\subseteq \mathbb{R}^n$. Prove that the following statements are equivalent:

$\displaystyle \lim _{k\to\infty} \|x_k\|= \infty$
$\{x_n\}$ has no convergent subsequences.
For each bounded set $X \subseteq \mathbb{R}^n$, the index set $k \in \mathbb{N}$ such that $x_k \in X$ is finite.

What I've done so far:
(1 $\Rightarrow$ 2) $\forall$ $M>0 \in \mathbb{R^n}$, $\exists n_0 \in \mathbb{N}$ such that if $n\geq n_0$ $\Rightarrow ||x_n|| > M$. And this implies that {$x_n$} is not bounded (Right?). Let {$x_{n_k}$} be a subsequence of {$x_n$}. We have that {$x_{n_k}$} is not bounded, so it does not converges.
(2 $\Rightarrow$ 3) Since {$x_n$} has no convergent subsequences, it does not converges. I'm stuck here.
Any hints, please? Thank you!
Answer: Assume that for some cube $Q$ in $\mathbb{R}^{n}$ containing $x_{k}$ infinitely many. Divide the cube into congruent $2^{n}$ cubes and look for one that contains infinitely many $x_{k}$, and proceed this fashion, you get a limit point, and a subsequence that converges to this point.
$3\rightarrow 1$ is easy. For any $M>0$, consider the bounded set $\{|x|\leq M\}$, then choose the maximal $N$ such that $x_{N}\in\{|x|\leq M\}$, then for all $n\geq N+1$, we have $|x_{n}|>M$.


Why finger 4 on G-sharp, finger 5 on Fx=G in Moonlight Sonata mvmt. 3?

Question:

This is the Casella edition of Beethoven's "Moonlight" Sonata (Op. 27, No. 2) from IMSLP, and the text recommends fingering 1-4(G#4-G#5) and 1-5(A4-F##5), since G# is farther than F##(G), wouldn't it be simpler to use finger 5 for G# and finger 4 for F##?
What is the logical reasoning behind this choice?
Answer: The reason I would use a fingering like this is to place the longer finger (4) on the black key (G♯) — the leading edge of which is further away from the body than those of the white keys — and let the shorter finger (5) handle the white key (Fx = G). This has the advantage of allowing my hand to relax (contract) a bit on the A-Fx pair rather than leaving it open for the entire passage.

When I place finger 5 on G♯, finger 4 lies across F♯ and far toward the fall board. To maintain this hand position, I have to hook or curl finger 4 around the F♯, play on the narrowest part of the G, and also play where I have the least leverage on the key.

To adjust for that problem, I have to pull my hand back a fair distance, adding extra movement at a time I'm trying to play very quickly.

By using finger 4 on G♯, I can move finger 5 to G with much less overall hand movement. It does require curling finger 5, which is not ideal, but is okay here since it's for such a brief time.

Notice the hand position below compared to the corresponding hand position above. In particular, notice how much further the thumb travels in the first set of photos than in the second. That more dramatic movement (first photo pair) slows down the passage and is also less accurate.
Comment: I think you got the more specific question title backward.  I've corrected it, but I'm a little spacy today so I'm calling it to your attention in case I am confused.
Comment: @phoog It seems you're at least less spacey than I. Thanks for the correction.


How to set up a contextual filter or child relationship?

Question: Every now and then I'm re-attempting to set up a decent taxonomy explorer/browser. I have already managed to customize a tpl file for that (oh, I know, tpl should not contain advanced logic, some day I'll learn how to do that properly). Now I decided to give it a shot using Views. While I managed to set up a view for the top-level listing, now I'm trying to set up a decent lower-level browser.
I don't think it's possible, but maybe you will prove to me that it is.
My taxonomy has a very simple structure in that at a given level it has only branches or leaves, never are they mixed. Now, at some level (the depth is variable at different branches), the branches end and the leaves are to be listed. Therefore I'd thought this logic would be appropriate:
<code>on page taxonomy/term/%
list items which
(a) belong to vocab X
and ((b1) are either children of parent with tid=%1
(b2) or are published nodes of content type Y with term tid=%1 assigned.)
</code>
For (b1) I have defined a parent term relationship and used it as a contextual filter. This alone works, but I don't know how to set up the b2 part. Can I re-use the same part of URL for another or'ed contextual filter. The '%1' string does not seem to work when entered in the filter section. What am I doing wrong?
Thanks.
Answer: Apparently there is no way to solve it using contextual filters and relationships. I solved the b2 part by using a separate dedicated view of content nodes as a No results view. It works because the taxonomy has consistent, non-mixed level contents.


Are 'safe_value' values generated dynamically from the 'value' value?

Question: I'm changing the content of an HTML field using entity_metadata_wrapper, and I see 3 values, like value, format, and safe_value.
My question is if I have to also edit safe_value or it will be generated dynamically. Thanks
PS: I edited and saved only value then in next load, the other were empty. I went to the node and clicked Save and the safe value was regenerated. Maybe I should call a hook after editing value?
Currently I'm using the check_markup function to generate the safe_value from the modified value
Answer: Yes. safe_value is derived from value; safe_value contains the results of _text_sanitize() after it applies all the filters you've set on your text field.
It isn't set after a node save; it's set on a field load; the field module loads it via hook_field_load() with its text_field_load() invocation.


Any suggestion for clustering method for unknown number of clusters and non-Euclidean distance?

Question: I need some suggestion for clustering (unsupervised classification) method for a consulting project. I am looking for a method that hopefully has the following properties:

The subject of my study has three properties. One is represented by
a (non-Euclidean) distance matrix and the other two are in the form
of vectors in Euclidean space. The distance matrix comes from
sequences and can be in the form of percent of dissimilarity or
other measurement of distance of sequences. The algorithm should be
able to take both vectors in euclidean space and non-euclidean
distance as input. For example, K-medoids can work with a distance
matrix but K-means can not.
I would like the algorithm to select the number of clusters and the
weight for three properties automatically (with prior knowledge and
constraint).
I have information of previously identified "centers of clusters". I
would like to incorporate it as prior or initial values.
As a statistician, I would prefer the method to have a clear
likelihood or loss function.

The closest thing I can think of is fitting a mixture model in Bayesian framework using reverse jump MCMC to determine the number of clusters. The vectors in R^d can be easily formulated into a normal likelihood but how to deal with the distance matrix is unclear to me. I can restrict the mean of normal likelihood to be at each of the observation of get the MCMC running but that does not have a clear mathematical / statistical meaning.
Does anyone have experience with a similar problem? Suggestion to references will be highly appreciated!
Comment: Why not project the non-euclidian vectors into euclidian space?
Answer: I think that using a MAP/Bayesian criterion of in combination with a mixture of Gaussians is a sensible choice. Points
You will of course object that MOGs require Euclidean input data. The answer is to find a set of points that give rise to the distance matrix you are given. An example technique for this is multidimensional scaling: $\text{argmin}_{\lbrace x_i \rbrace} \sum_{i, j}(||x_i - x_j||_2 - D_{ij})^2$ where $D_{ij}$ is the distance of point $i$ to point $j$.
Comment: Thanks. I am using a similar approach! I think there is a typo in your post: there shouldn't be a square on $(x_i-x_j)$.
Comment: Why not? It is a Euclidean distance, thus it has to be squared. However, it is a norm, thus I will try to make that clearer.
Answer: I dealt with a problem for my thesis where I had to do clustering on a data set for which I only had a similarity (= inverse distance) matrix. Although I 100% agree that a Bayesian technique would be best, what I went with was a discriminative model called Symmetric Convex Coding (link). I remember it working quite nicely.
On the Bayesian front, perhaps you could consider something similar to clustering, but not? I'm thinking along the lines of Latent Dirichlet Allocation -- a really marvelous algorithm. Fully generative, developed in the context of modeling topic contents in text document corpora. But it finds plenty of applications in other types of unsupervised machine learning problems. Of course, the distance function isn't even relevant there...
Answer: DBSCAN works without knowing the number of clusters ahead of time, and it can apply a wide range of distance metrics.
Comment: Thanks for your answer BTK, though it is more of a comment. To make it more of an answer, you might want to add a bit more detail on DBSCAN and how it applies to the specific question at hand.
Answer: You could use affinity propagation or better adaptive affinity propagation.
Here is the Wikipedia link.
There are two main advantages for your case and another third one that I think is an advantage but may not be of importance to you.

You do not supply the number of clusters. The final number of clusters depends on the preference value and the similarity matrix values.
The easiest way to work with the preference values is either to use the minimum value of the similarity matrix (that isn't zero) to get the smallest number of clusters, then try e.g.  the maximum for the most clusters possible and continue with the median value and so on...
OR
Use the adaptive affinity propagation algorithm and have the preference determined by the algorithm.
You can supply any similarity measure you can come up with or take the inverse of a distance measure (maybe guard against dividing by zero when you do that).

3.(extra point) The algorithm chooses an exemplar representing each cluster and which examples belong to it.
This means the algorithm doesn't give you an arbitrary average but an actual datapoint. However you can still calculate averages later of course.
AND this also means that the algorithm doesn't used intermittent averages!
Software:
There are several packages listed for Java, Python and R on the Wikipedia page.
If you love MATLAB, like I do, then here is an implementation.


Como criar um log em html com log4net

Question: Tenho um projeto que já utiliza o log4net, porém gostaria de mostrar esse log em HTML. Procurei em vários sites e ninguém implementou essa solução.
Alguém tem ideia de como fazer isso?
Comment: Qual é o tipo de projeto?
Comment: É um Webservice Framework 3.5 C#.
Answer: Partindo do princípio que tu consegue salvar o log como XML e que HTML também é uma linguagem de marcação, tu pode tentar se aproveitar disso.
Você pode reescrever a classe XmlLayoutBase, como foi feito pelo Darin:
public class MeuHtmlLayout : XmlLayoutBase
{
    protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
    {
        writer.WriteStartElement("div");
        writer.WriteStartElement("p");
        writer.WriteString(loggingEvent.RenderedMessage);
        writer.WriteEndElement();
        writer.WriteEndElement();
    }
}

No seu app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>

  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
      <param name="File" value="log.html" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="SeuNamespace.MeuHtmlLayout" />
    </appender>

    <root>
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>
</configuration>

Para testar:
class Program
{
    static void Main(string[] args)
    {
        XmlConfigurator.Configure();
        ILog log = log4net.LogManager.GetLogger(typeof(Program));
        log.Debug("Hello world!");
    }
}

É para produzir uma saída do tipo:

Hello world

Como criar um log em html com log4net


Cannot convert MATLAB y-axis to latex format

Question: I recently started doing some prototyping using MATLAB.  I like to make my axises in latex font because it is consistent with the rest of my writing.  I used the following code:
figure()
plot(t, y(:, 1), t, y1, '--r')
legend('Transfer Function', 'State Space', 'Interpreter', 'latex');
xlabel('Time, \textit{t} (s)', 'Interpreter', 'latex');
ylabel('%MeOH in Distillate, \textit{X_D} (%)', 'Interpreter', 'latex');

By doing so, I got my x-axis and legend in latex format.  However, my y-axis was not in latex format.. I am wondering why this is.

Thanks!
Comment: It appears that the latex interpreter cannot handle subscripts in italics. The following worked (but terrible font) ylabel('Stuff stuff, X_D','Interpreter','tex') If desired, you could access the handle to the ylabel and set the font and fontangle by hand.
Answer: You have messed up some LaTeX syntax. See the highlighted changes:
ylabel('\%MeOH in Distillate, \textit{$X_D$} (\%)', 'Interpreter', 'latex');
%       ^                             ^   ^   ^

Comment: Ahh ok, I had no idea there would be no errors popping up.  I added the \%, but nothing changed so I thought I was doing something wrong.  But I did not realize I messed up the X_D as well.  Thanks for the answer.


what is the internal folder to save files or pictures on android when there is no SDCard present

Question: When an SDCARD is present and I take a picture with my app, I can save it to:
<code>Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
</code>
I want to achieve the same, but for internal storage.
Is there an internal directory?
Answer: The very same path in code. When there's no external storage, it will refer to the internal one (the one your system settings is configured as "default storage").
Comment: Great thanks.  What about if I want to FORCE to save to the internal storage? any way to get that path ?
Comment: Not that I am aware. I think it ALWAYS uses the card which is set as primary.


ECS (EC2 type) task is failing container health check, but ALB health check works

Question: I have ECS cluster (EC2 type, 1 service only) with ALB and Target Group. Desired count is set to 2 on ECS service level, no ASG for tasks. Technically everything works. I can communicate with my API without  any problem, but there is a small issue that bothers me. Container health check for my ECS tasks doesn't work. I'm mapping container port 3000 to host port 0, but since it's inside container it shouldn't matter?
I'm struggling to understand why, here is the cmd I use (I will just paste my whole health check block since I'm using terraform to deploy my infra)
healthCheck = {
    retries = 10
    command = ["CMD-SHELL", "curl -f http://localhost:3000/health || exit 1"]
    timeout : 5
    interval : 10
    startPeriod : 45
}

I's worth mentioning that both my task with random ports are visible in Target Group health check, where I'm using the same endpoint. Here is how it looks like:
resource "aws_alb_target_group" "my_api_backend_tg" {
  name                 = "my_tg_name"
  port                 = 3000
  protocol             = "HTTP"
  vpc_id               = "vpc_id"
  deregistration_delay = 25

  health_check {
    path                = "/health"
    healthy_threshold   = 2
    unhealthy_threshold = 5
    timeout             = 5
    interval            = 15
    matcher             = "200"
  }

  lifecycle {
    create_before_destroy = true
    ignore_changes        = [name]
  }
}

I'm relatively new to AWS, so it might be trivial, but I'm not even sure how can I debug it, would appreciate any help.
Comment: What are the target group health check settings?
Comment: TG resource looks like this:
`resource "aws_alb_target_group" "my_api_backend_tg" {port= 3000 protocol =http health_check { path = "/health" healthy_threshold  = 2 unhealthy_threshold = 5 timeout = 5 interval = 15 matcher = "200" }}`
Comment: Please don't post code in comments, it is unreadable. You can edit your original question to add more information like this.
Answer: After all it was something trivial and not even related to AWS, but to docker itself. Image was so thin that there was no curl installed. Installing it fixed my problem.
Comment: You save the day!


Data warehouse logical model

Question: I have drawn a logical model for a  hotel room booking OLTP system Logical model
I'm facing a problem querying it.
the question is: For each Country and quarter, produce the cumulative income of 3-star-rooms
Noted that RoomBand contain how many starts for each room
I have tried this
SELECT Quarter, Country
FROM DT_Date, Country, RoomBand
where RoomBand = 3

the output was this
CountyName  Quarter
  USA          2
  Uk           1
  USA          2
  UK           1

as it has shown it repeated USA and UK
why is that happening
Thanks for the support all
Comment: You are asking why your results look certain way without providing us he source data and the expected results. That's a no go.
Comment: *Never* use commas in the `FROM` clause.  *Always* use proper, explicit, **standard**, readable `JOIN` syntax.
Answer: Try the DISTINCT operator with your query. For example: SELECT DISTINCT column1, column2, .... You can read more about it here.
Comment: We do not know enough about the problem to provide an answer. Distinct may or may not be a good solution.

Data warehouse logical model


Why did Stuart and Sons invent a 102-key piano?

Question: Stuart and Sons have invented a huge 102-key grand piano.  What is the reason behind this?
Comment: https://www.npr.org/2011/01/18/132945634/musical-innovation-a-grander-grand-piano This article is found immediately with Google and gives the designer's own words on the reason. How can anyone here do better?
Comment: Most likely because the answer is easily found with the minimum of Googling? We do like to think that questions are researched by the OP prior to being asked here. Probably even more information that may be forthcoming from contributors on this site can be gleaned by use of such methods.
Answer: The maker has said in an interview (link from replete's comment):

I'd hate to go back to the 88-key piano... I couldn't stand it. It's too limited.

Which suggests he values having the extra notes.
He also said:

I'm all for innovation in the modern piano. To me, the piano is a pinnacle of human achievement. So it seems right and proper that it should continue to develop.

Which clarifies he is in favor of finding ways to expand the capabilities of the piano in general.
Note that while organs and synthesizers don't always have keyboards with as many keys, they generally can both be played higher and lower than typical pianos, so it's not like an 88 key piano has all the notes we would want to play or hear.
Comment: It pretty much does, though. The notes added by super-sized pianos like the Bösendorfer are musically almost worthless; the point of having them is that they provide richer resonance to the sound of the standard notes.
Comment: If they add a benefit at all, which you concede, then they aren't worthless, are they


Variable/column selection in tidyr fill()

Question: Suppose a df with some missing values like this:
   ID col_A_1 col_A_2 col_B_1 col_B_2
1   1       1      NA      NA       a
2   1       2      NA       1       b
3   1       3       1       2       c
4   1       4       2       3       d
5   1      NA       3       4       e
6   2      NA       1       5       f
7   2      NA       2       6       g
8   2       1       3       7       h
9   2       2       4       8    <NA>
10  2       3       5      NA    <NA>

I want to fill the missing values using tidyr fill(), however, only the missing values in columns containing A.
I was able to achieve it using:
library(dplyr)
library(tidyr)

df %>%
 group_by(ID) %>%
 fill(names(.)[grepl("A", names(.))], .direction = "up") %>%
 fill(names(.)[grepl("A", names(.))], .direction = "down") %>%
 ungroup()

      ID col_A_1 col_A_2 col_B_1 col_B_2
   <dbl>   <int>   <int>   <int> <chr>
 1     1       1       1      NA a
 2     1       2       1       1 b
 3     1       3       1       2 c
 4     1       4       2       3 d
 5     1       4       3       4 e
 6     2       1       1       5 f
 7     2       1       2       6 g
 8     2       1       3       7 h
 9     2       2       4       8 <NA>
10     2       3       5      NA <NA>

however, I'm looking for other variable/column selection possibilities inside tidyr fill().
Sample data:
df <- data.frame(ID = c(rep(1, 5), rep(2, 5)),
                 col_A_1 = c(1:4, NA, NA, NA, 1:3),
                 col_A_2 = c(NA, NA, 1:3, 1:5),
                 col_B_1 = c(NA, 1:8, NA),
                 col_B_2 = c(letters[1:8], NA, NA),
                 stringsAsFactors = FALSE)

Answer: The fill can take select_helpers
library(tidyverse)
df %>%
   group_by(ID) %>%
   fill(matches('A'), .direction = 'up') %>%
   fill(matches('A'), .direction = 'down')
# A tibble: 10 x 5
# Groups:   ID [2]
#      ID col_A_1 col_A_2 col_B_1 col_B_2
#   <dbl>   <int>   <int>   <int> <chr>
# 1     1       1       1      NA a
# 2     1       2       1       1 b
# 3     1       3       1       2 c
# 4     1       4       2       3 d
# 5     1       4       3       4 e
# 6     2       1       1       5 f
# 7     2       1       2       6 g
# 8     2       1       3       7 h
# 9     2       2       4       8 <NA>
#10     2       3       5      NA <NA>


xamarin forms. Ipad no render full screem

Question: I'm using xamarin forms, When I run on an ipad, this does not render ful screen. What should I configure?enter image description here
Comment: That is an iPhone app running on an iPad.  You need to open the project properties and set it to Universal (iPhone + iPad)
Answer: In the iOS project locale the Info.plist file and double click on it.
There change the Device Family from iPhone/iPod to Universal


Run C# UrlEncode String in HTML

Question: I need to URL encode an email address. If I do this (without URL encode), it works:
<!DOCTYPE html>

    <title>Test</title>

The email address is printed raw, not URL-encoded.
What I'd really like to do is the following, but HttpUtility.UrlEncode() doesn't execute:
<!DOCTYPE html>

    <title>Test</title>

Any suggestions on how to execute HttpUtility.UrlEncode() for usage in the above manner? Thanks for any help.
Comment: For more information on inline expressions in asp.net.... https://learn.microsoft.com/en-us/troubleshoot/aspnet/inline-expressions
Answer: You need to use  <%= %>
like:
<a href="https://portal.nchinc.com/reset-password?e=
 <%=HttpUtility.UrlEncode("%7bEMAILADDRESS%7d") %>"/>

The <%= ... %> is used when you need to display an expression.

Run C# UrlEncode String in HTML


Python: Trying to get index of an intersection

Question:
Possible Duplicate:
Python: Finding corresponding indices for an intersection of two lists

I have the following line of code:
for i in [i for i,x in enumerate(catdate) if x == set(NNSRCfile['datetimenew']).intersection(catdate)]:
    print i

I am trying to find the index of the intersection for the two components above. Both are lengthy lists that have several commonalities. The intersection part works perfectly; however, the for loop seems to output nothing. (ie: there is nothing that is printed).
Python outputs no error, and when I run the code in IPython, I notice that i is equivalent to to the very last element in the list "catdate", instead of listing the indices of "catdate" that are equivalent to the intersection values.
Any help is greatly appreciated!
Comment: is this different from your post yesterday?
Comment: Yes, it is, though it is the same problem. I am trying a different approach though.
Comment: are you sure you don't want to use `x in ...` to test if `x` is in your intersection ?
Comment: @Pierre, do you mean using "x in" instead of "x ==" ?
Comment: You know the .intersection doesnt (logically) do anything since we know x is in catdate you need only test if x is in set(NNSRCfile['datetimenew']).   Precomputing the intersection might be more efficient though.
Answer: If you want to test whether x is in your intersection, you should use:
indices = [i for (i, x) in enumerate(catdate) if x in set(NNSRCfile['datetimenew']).intersection(catdate)]
for i in indices:
    print i

Otherwise, you're comparing a single element to a set, which is unlikely to work (therefore, the test always fail, your indices list is empty, nothing gets printed...
Comment: I think that solved my problem. I didn't know you could you "if... in..."
Thank you very much for your help. :)
Comment: @user1620716 Glad to help. Practice makes perfect, keep going!
Answer: set() will not match a single value, try:
if set(x) == set( ...

Personally I'd avoid using the same "i" in nested contexts like that, btw, although python alloqws it. At least it is confusing to read..


Spring MVC 406 Response using Ext JS Ajax Call

Question: I am currently working on a simple application that gets a list of users from a MySQL database and returns the data as JSON format. I am using a Ext JS Store to make the ajax call.
Store:
Ext.define('MyApp.store.AdminUsers', {
    extend: 'MyApp.store.BaseStore'
    ,model: 'MyApp.model.AdminUser'
    ,remoteSort: true
    ,pageSize: 20
    ,proxy: {
        type: 'ajax'
        ,url: contextPath + '/admin/users/list.htm'
        ,actionMethods: 'POST'
        ,simpleSortMode: true
        ,pageParam: undefined
        ,reader: {
            type: 'json'
            ,root: 'adminUsers'
            ,successProperty: 'success'
            ,totalProperty: 'totalCount'
        }
    }
});

Spring MVC Controller:
@Controller
@RequestMapping("/admin/users/")
public class AdminUserController extends BaseController {
 // items removed for brevity
@RequestMapping(value = "/list")
@ResponseBody
public Model listAllAdminUsers(Model model, HttpServletRequest request) throws Exception {
    FindInfo findInfo = getFindInfo(request);
    model.addAttribute("totalCount", adminUserService.getCount(findInfo));
    model.addAttribute("adminUsers",    AdminUserConverter.createListData(adminUserService.getList(findInfo)));
        return model;
    }
}

web.xml:
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springConfig/applicationContext.xml</param-value>
</context-param>

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springConfig/mvc-dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<session-config>
    <session-timeout>20</session-timeout>
</session-config>

mvc-dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <import resource="spring-controller.xml" />
    <import resource="spring-view.xml" />
    <context:component-scan base-package="com.myapp.web.controller" />

    <mvc:resources mapping="/lib/**" location="/lib/" />
    <mvc:resources mapping="/extjs/**" location="/extjs/" />

    <mvc:annotation-driven />
</beans>

spring-controller.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter" />
            </list>
        </property>
    </bean>

    <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

</beans>

spring-view.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd" >

    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"></bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

I have the proper Jackson libraries on my class path, sometimes I am getting 406 error and have tried changing accept and content-type headers in Ext JS and defining produces type for the listAllAdminUsers method. When I get a 404 (I have tried several different things), spring is trying to resolve the controller method as view and is looking for admin/users/list.jsp (not sure why?). I have exhausted all of the options by searching numerous answers and I have tried everything it seems. Please help!!
Answer: You have two problem :
1. The first is about the Accept header. Problem you resolved as you mentioned.
2. Is about the url mapping, in your request you send a request /admin/users/list.htm but your Controller cannot only respond to request made to /admin/users/list
Try this
Ext.define('MyApp.store.AdminUsers', {
    extend: 'MyApp.store.BaseStore'
    ,model: 'MyApp.model.AdminUser'
    ,remoteSort: true
    ,pageSize: 20
    ,proxy: {
        type: 'ajax'
        ,url: contextPath + '/admin/users/list'
        ,actionMethods: 'POST'
        ,simpleSortMode: true
        ,pageParam: undefined
        ,reader: {
            type: 'json'
            ,root: 'adminUsers'
            ,successProperty: 'success'
            ,totalProperty: 'totalCount'
        }
    }
});

Comment: thanks for your answer but I am still getting a 404 and it is looking for admin/users/list.jsp for some reason. The weird thing is the code is going into that method but not returning the model for some reason. Thoughts?
Comment: Could you post your complete controller code please ?
Comment: Besides autowiring a service class and a validator, there isn't much else. It is very weird because it is making the controller call (can see a sysout) but it won't return the model :/
Comment: I should also say that I noticed if I return a String, it works and no 404.
Answer: All I had to change was to put the @ResponseBody onto the return Model, rather than on the method itself.


Setup two-way SSL on Nginx with upstream server

Question: I have two independent systems interacting with each other with two-way SSL.
System A <---2 way ssl---> Third Party System
I have a use-case where the request needs to be forwarded to third-party system via Nginx. How to I avoid SSL handshake at Nginx and proxy it to the original systems or have handshake between Nginx and upstream (Third Party System).
System A <------>NGIXN<---2 WAY SSL--> Third Party System
or
System A <-----2 WAY SSL--- (proxy)NGIXN ---2 WAY SSL--> Third Party System
Comment: I would think the answer is you can't do this.  Why are you trying to have nginx in the path?
Comment: Possibly what you are looking for is a stream proxy?  https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/
Comment: @Zoredache The third party can whitelist limited IPs. Need to route all my requests through a common proxy.
Comment: @Zoredache its not a stream, these are https requests. I want either nginx to not interfere with the two way ssl handshake or do handshake between nginx and upstream.
Comment: Right, which is exactly what a 'stream' proxy should do.  It will listen for the TCP connect, and forward it. It will not do anything with http/https/tls stuff.  BTW, you could always just use any other simple TCP proxy.
Comment: @Zoredache Ohh, let me try it out. Will update you soon.
Answer: Nginx has a module to arbritrary TCP/UDP proxy .
Your nginx binary must have compiled with option <code>--with-stream</code>
See
https://nginx.org/en/docs/stream/ngx_stream_core_module.html
See
https://nginx.org/en/docs/stream/ngx_stream_proxy_module.html
Answer: I believe that Nginx only plays a proxy role in your system, given the SSL mechanism of System A and Third Party System unchanged.
I suggest just using the IP forwarding mechanism built in Linux.
enable the ip forwarding of your middle machine;
add ip forwarding rule on its firewall, and masquerade source IP if needed.
Middle Machine has the IP allowed by Third Party.
And you tell that system A to connect to middle machine on a particular port 7777.
Middle Machine than forward local port 7777 to the Third Party ip:port with masquerade. The Third Party would see your middle machine connecting to it.


Natural deduction proof / Formal proof : Complicated conclusion with no premise

Question: Find a formal proof for the following:
$\vdash [(\neg p \land r)\rightarrow (q \lor s )]\longrightarrow[(r\rightarrow p)\lor(\neg s \rightarrow q)]$
As you can see.
No premise to use.
We have to use assumptions and eliminate them.
This also means no using equivalent formulas.
Because we can easily end the problem by finding a shorter and equivalent formula.
But the problem here specifically asks for a natural deduction/formal proof.
I'm always arriving at the conclusion but my problem is I always have ONE non-eliminated assumption left.
Comment: Please don't ask us to reinvent the wheel.  Tell us what do you have so far so we can identify your issue.
Answer: Here's how to do it, not in full gory detail — three of the steps below appeal to simple equivalences; each has to be expanded to establish the particular case of the cited equivalence:
$$
\begin{array}{r|ll}
\text{step} & \text{Formula} & \text{How obtained} \\
\hline
1 & (\neg p \land r)\to (q \lor s ) & \text{assumption} \\
2 & \neg(r\to p) & \text{assumption} \\
3 & \neg s & \text{assumption} \\
4 & r \land \neg p & \text{From 2.: $\neg(A\to B) \equiv (A\land \neg B)$} \\
5 & \neg p \land r & \text{From 4.}  \\
6 & q\lor s & \text{From 5. and 1. by MP}  \\
7 & \neg s\to q  & \text{From 6.: $(A\lor B)\equiv (\neg B\to A)$}  \\
8 & q & \text{From 3. and 7. by MP}  \\
9 & \neg s \to q& \text{From 3. and 8. — discharge 3.}  \\
10 & \neg(r\to p)\to (\neg s \to q) & \text{From 2. and 9. — discharge 2.}  \\
11 & (r\to p)\lor (\neg s \to q)  & \text{From 10.: $(\neg A\to B)\equiv (A\lor B)$}  \\
12 & [(\neg p \land r)\to (q \lor s )] \longrightarrow [(r\to p)\lor (\neg s \to q)] & \text{From 1. and 11. — discharge 1.}
\end{array}$$
The steps that use equivalences $(\phi\equiv\psi)$ — 4., 7. and 11. — are shorthand for a sequence of multiple steps which deduce $\psi$ from $\phi$.
Comment: Thanks for the attempt.
But my question was WITHOUT using simple equivalences.
This was the question formalized.
I reached a few minutes ago to a result.
I'll post the answer to the question.
Thanks everyone.
Comment: So eliminate those yourself — that's the easy part, That's what's had you stumped for over 3 weeks?!? Can't deduce $\neg B\to A$ from $A\lor B$ ? I hope that's not the case. Inserting them would just make the answer long-winded. I wasn't using "shorter equivalent formulas". Good luck.
Comment: That WAS the case. See now I agree with you this is a really easy and dull problem IF you can deduce an IMPLIES from OR. But for some reason the formulation of the problem insists that we only stick to 5 natural deduction rules of inference (Introduction/Elimination for AND, OR, IMPLIES, NOT, CONTRADICTION).
It's merely a matter of limiting your comfort with what you can use.
What solved this is using the same assumption way too many times along the proof to get where we want. And yes, this took me 3 weeks (not really, on/off work), merely because  the proof is gigantic. Many thanks BrianO.
Comment: Then my sympathies & also congratulations. Problems like this build character, they say ;)
Comment: @ex.nihil: Actually it's not that hard, but it takes practice to get used to natural deduction. If you've learnt the tableaux method (https://en.wikipedia.org/wiki/Method_of_analytic_tableaux) you'll notice that the steps in natural deduction correspond quite closely to the choices made in the tableaux method.
Answer: General Strategy
Break down what you need to prove according to the introduction rule. This is always possible for conjunction and implication. For a disjunction "$A \lor B$", it may not be possible because sometimes you can prove neither "$A$" nor "$B$", in which case you need to go by contradiction, which is to assume $\neg ( A \lor B )$ and obtain a contradiction, from which you can obtain $\neg \neg ( A \lor B )$ without any assumption and then use double negation elimination. Under the assumption, you still want to prove something of the form "$A \lor B$" but this time it is possible. First assume $A$ and obtain a trivial contradiction. So you can conclude $\neg A$ and proceed.
Solution (Fitch-style natural deduction)
$\def\imp{\rightarrow}$
If $( \neg p \land r ) \imp ( q \lor s )$:
  If $\neg ( ( r \imp p ) \lor ( \neg s \imp q ) )$:
    If $r \imp p$:
      $( r \imp p ) \lor ( \neg s \imp q )$.
      Contradiction.
    $\neg ( r \imp p )$.
    If $r$:
      If $\neg p$:
        $\neg p \land r$.
        $q \lor s$.
        If $\neg s$:
          If $\neg q$:
            If $q$:
              Contradiction.
            If $s$:
              Contradiction.
            Contradiction.
          $\neg \neg q$.
          $q$.
        $\neg s \imp q$.
        $( r \imp p ) \lor ( \neg s \imp q )$.
        Contradiction.
      $\neg \neg p$.
      $p$.
    $r \imp p$.
    Contradiction.
  $\neg \neg ( ( r \imp p ) \lor ( \neg s \imp q ) )$.
  $( r \imp p ) \lor ( \neg s \imp q )$.
$( ( \neg p \land r ) \imp ( q \lor s ) ) \imp ( ( r \imp p ) \lor ( \neg s \imp q ) )$.
Comment: These are all valid answers. And I thank you very much for the detailed effort. But what I'm not able to inform you, is that, the problem is forcing me to use only the following rules:
Comment: Sorry I got logged out for some reason.

These are all valid answers. And I thank you very much for the detailed effort. But what I'm not able to inform you, is that, the problem is forcing me to use only the following rules:
AND introduction/elimination.
OR introduction/elimination.
NOT introduction/elimination.
IMPLIES introduction/elimination.
CONTRADICTION introduction/elimination.

So using equivalencies such as $p \rightarrow q \equiv \neg p \lor q$ is  not allowed.

I appreciate the answers, and I will validate these.
Comment: @ex.nihil: Did you read my answer before commenting? I **didn't use** any equivalences. Also, don't **assume** that everyone knows exactly what your rules are, because there are about as many variants of natural deduction as there are authors. However, it should be quite trivial to translate between variants.
Comment: Of course I have, and it looked very similar to my attempt only shorter (which is what I was looking for). Your answer is 100% valid, but like you said it's a different variant. The way I understood your answer is by translating it to the variant I was working with. And as for the method of analytic tableaux, it made me understand the order of the assumptions you took, while non-intuitive, got there concisely. What I sometimes do with long expressions is I work backwards in a sort of "Reverse Mathematics" kind of way. I start with the conclusion and work my way back to the premises.
Comment: @ex.nihil: Right. The tableaux method also shows that for propositional logic you should not have to use each piece of the desired theorem more than a few times (I think twice at most). To get the shortest proof you have to work both forward and backward. The reason for my comment is that in your second comment you said "using equivalences is not allowed" as if implying my answer did so. Also, I do not see why you accepted Brian's answer instead of mine since he didn't answer the question (especially given your complaint about equivalences) while I did!
Comment: My bad, I'm a newborn to this site, so the functionality is still new to me.
I accepted both answers actually and I didn't think I couldn't do that.
I accepted yours first then Brian's, and since only one is allowed, it remained his. Fixed.
Either way, my question has unreasonable constraints (thanks to an unreasable instructor).
And apologies, in my second comment the "no equivalencies" weren't aimed at your answer.
I'll look more into this tableaux method and your guidelines.
Thanks again for the solution.
Comment: @ex.nihil: Actually you'll be surprised to learn that what you think is unreasonable is actually quite reasonable in the world of automated reasoning, because the fact that natural deduction corresponds to the tableaux method (unlike proofs using equivalences) and the fact that the tableaux method can be systematically performed (for propositional logic) means that one can write a program to find the natural deduction proof. Also, you'll be surprised that when you fully understand natural deduction, other aspects of logic will be obvious to you (as you learn more later).
Comment: Kind of makes sense now, because the course is taken from a Computer Science perspective. Even though it's a pure mathematics course, but all engineers, computer scientists and mathematicians are required to take it.
The instructor never explained what or why. I'll be sure to go into detail with this stuff. It's quite interesting. Thanks for the insight.
And you spoke about programs, does this explain why their proofs are somewhat long for somewhat simple conclusions? But the advantage is always getting there right?
Comment: @ex.nihil: The length of proofs is not directly related to what I was saying above. For a statement in propositional logic you can check whether it is true (tautology) by using the truth table, but its size is about proportional to $2^n$ where $n$ is the number of variables. Also, it does not give you a short proof since it is essentially case whacking. In contrast, using the tableax method, every step on a branch eliminates the outermost boolean operation, so it usually requires much less work (especially if you reuse results that you compute in other branches). [continued]
Comment: @ex.nihil: And then the nice thing is that the tableax method translates quite directly to a natural deduction proof. And believe me, almost all mathematical proofs actually do follow natural deduction when you look at their logical structure, even though usually we skip steps or use other rules to make our lives easier. Once you are able to use natural deduction correctly, you won't make logical errors anymore except for careless mistakes, because you can mentally see the logical structure. One extremely common error is accidentally switching quantifiers.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/35791/discussion-between-user21820-and-ex-nihil).


A question about an exercise on measure theory

Question: I will write a question from Folland's book. What I want to ask is not the solution of this problem, but the way how to approach it. Question is as follows:

If $f \in L^+$ and $\int f < \infty$, for every $\epsilon > 0$ there exists $E \in \mathcal{M}$ such that $\mu(E) < \infty$ and $\int_E f > (\int f) - \epsilon$.

So as I said, I simply need to understand the approach I should take. For instance, what does the last inequality mean? What it says when you write a statement like $b > a - \epsilon$?
Also, I want to gain intuition about the way of full solution. Thanks.
Comment: @Amr: the support of an integrable function is necessarily $\sigma$-finite (in fact, [integrable functions form a dense subset of the set of all $\sigma$-finitely supported functions](http://math.stackexchange.com/questions/179285/boundary-of-l1-space/179326#179326) ), so assuming that $\mu$ is $\sigma$-finite is not much of a restriction.
Comment: What about the measurable space we are working one (I guess the total mass is infinite in order to avoid a trivial problem)? Can you do it when $f$ is the characteristic function of a set of finite measure? What the inequality gives is $\int_{X\setminus E}f<\varepsilon$, that is, the integral of $f$ is "almost" concentrated on a set of finite measure.
Comment: What does L+ stand for?
Comment: @Amr: Fix a measure space $(X, \mathcal{M}, \mu)$, then $L^+$ is the space of all measurable functions from $X \to [0,\infty]$.
Comment: I can only prove the theorem for sigma finite measure spaces
Comment: Are you sure that the theorem still holds even when (X,M,μ) is not sigma finite ?
Comment: Amr: I checked the book, but there is no restriction about the measure space.
Answer: We have to show that for each $\varepsilon>0$, we can find $S_{\varepsilon}$ which concentrates the integral up to $\varepsilon$, i.e.
$$\int_{X\setminus S_{\varepsilon}}fd\mu<\varepsilon$$ and is of finite measure.  We can try, and expand, the following sketch of proof:

Using the definition of Lebesgue integral, we can restrict ourselves to simple functions.
By linearity, we can do a further restriction to characteristic function of measurable sets of finite measure.
This case is easy.

Note that this doesn't need $\sigma$-finite of the measure space.


How to search between two dates and time from sql in vb,net?

Question: I am trying to create a Crystal Report where I can search between two dates selected by datetimepicker1 and datetimepicker2. MySql database date column has saved datetime like this (12/26/2018 3:28:30 PM). my select statement and parameters are not correct. How can I do this?
Private Function GetData() As billing

    Dim x = Form25.DateTimePicker1.Value.Date.ToString("MM-dd-yyyy")

    Dim y = Form25.DateTimePicker2.Value.Date.ToString("MM-dd-yyyy")

    Dim constr As String = ("server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=True")

    Using con As New SqlConnection(constr)

        Using cmd As New SqlCommand("select goldrate,date,itemcode,karat,category,item,qty,grossweight,netweight,discountrs,finalamount from allsaledata where date >= @date AND date <= @date", con)
            cmd.Parameters.AddWithValue("@date", x And y)

            Using sda As New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dsCustomers As New billing()
                    sda.Fill(dsCustomers, "DataTable1")
                    Return dsCustomers

                End Using
            End Using
        End Using
    End Using
End Function

Answer: The first thing to do when you execute a query against a column of type Date is not to pass a parameter of type string. This will force the database engine to do its own conversion and you have a very high risk to get a wrong conversion.
So you should pass parameters of type DateTime and you need two parameters because you have two date limits to check
' Do not convert to strings here. Work with dates
Dim x = Form25.DateTimePicker1.Value.Date
Dim y = Form25.DateTimePicker2.Value.Date

Using cmd As New SqlCommand("select goldrate,date,itemcode,karat,
                                    category,item,qty,grossweight,
                                    netweight,discountrs, finalamount
                             from allsaledata
                             where date >= @init AND date <= @end", con)

    cmd.Parameters.Add("@init", SqlDbType.Date).Value = x
    cmd.Parameters.Add("@end", SqlDbType.Date).Value = y

Another thing to pay attention is the fact that, if you use a DateTime without the Time part, then your query could exclude the dates for the last day.
For example, if you have an end date like 02/05/2019 00:00:00, then a record with a date and time like 02/05/2019 19:40:00 will not be included in the results because a time of 00:00:000 is midnight and every other time is after midnight.
If you want to avoid this situation then add a day to the ending date, like this
Dim y = Form25.DateTimePicker2.Value.Date.AddDay(1)


Eaccelerator with mod_deflate or gzip

Question: First. Which differences between mod_Deflate and gzip, which is better ?
And can i use Eaccelerator + mod_deflate together.
Answer: You can use eAccelerator and mod_deflate simultaneously. They work in different areas of the response process. eAccelerator works by caching partial interpretation of your php so that, in theory, it takes less CPU to render the same php a second time. mod_deflate compresses the output from apache (rendered php or other files) to reduce the amount of traffic passing over the network. So the first is intended to help the results leave your server faster and the second is intended to help those results travel from the server to the client faster.
Obviously the compression costs CPU (at both ends); so there's a trade off that may or may not be beneficial for you depending on whether you have extra CPU or extra bandwidth.
The main problem with eAccelerator is that it appears to be unsupported. There have been no updates since 2010 and it will not compile under php 5.4. XCache appears to work well with php 5.4.4 on FreeBSD.
Answer: As such no comparision, both are intended to do the same task.
gzip was supported in old version of apache1.3 and mod_deflate is supported in apache2.0 and further.

Eaccelerator with mod_deflate or gzip


Quais são as diferenças entre HashMap e Hashtable?

Question: Quais são as diferenças entre HashMap e Hashtable em Java?
Qual é mais eficiente?
Comment: Consequentemente, se for uma situação sem concorrência, em que tanto faz usar uma ou outra, a versão não-sincronizada (HashMap) será mais eficiente.
Comment: Resumindo em um linha: A HashTable é sincronizada(thread-safe). O HashMap, não.
Answer: Hashmap

Não é sincronizada
Aceita valores nulos e uma chave nula
É possível varrer toda estrutura com um iterador de forma simples
Possui containsValue() e containsKey()
É mais rápida
Consome menos memória
Mais moderna
Mãe: AbstractMap

Hashtable

Sincronizada e pode ser facilmente usada em ambiente concorrente
Não aceita nulos
Iterar é mais complicado
Possui contains()
Tem overhead pela sincronização
Ocupa mais memória
Considerada obsoleta
Mãe: Dictionary

Retirei a informação principalmente dessa resposta no SO.
Coloquei no GitHub para referência futura.


Changing an exposed filter to use check_plain() or filter_xss()

Question: I have a view with a search filter. I am using Acunetix scanner to scan for vulnerabilities, which reports me an issue about the search filter. How do I alter it to use check_plain(filter_xss($string)) or filter_xss(check_plain($string)) in view exposed forms (a block, in my case)?
Comment: I find it odd and hard to believe that views doesn't do this already... Perhaps somewhere behind the scenes, they are already doing this?
Answer: You can write a form alter in your custom module. ie :
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'views_exposed_form') {
        $view = $form_state['view'];
        if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
            // alter your exposed form here
            $form['yourdata_item'] = check_plain(filter_xss($string));
        }
    }
}


Is it possible to alter workflow step properties from code in Dynamics CRM 2013

Question: If I create a Workflow from a template in code in Dynamics CRM, is it possible to change the values for the workflow step properties?
I have a custom workflow step, that is part of a workflow template, but for each workflow I create from this, I want to pass in different values to the step.
I'm creating the workflows from C# as part of a powershell cmdlet. I've tried creating the workflow from scratch with xaml but it's causing more problems that it solves.
I can create and retrieve the workflow with the following code, but I can't see anything to point me to the steps on the Workflow object I retrieve.
<code>using (var proxy = auth.GetOrganizationProxy())
        {
            // This statement is required to enable early-bound type support.
            proxy.EnableProxyTypes();

            OrganizationServiceContext _orgContext = new OrganizationServiceContext(proxy);

            CreateWorkflowFromTemplateRequest request = new CreateWorkflowFromTemplateRequest()
            {
                WorkflowName = "(" + EntityLogicalName + ") Migrate Notes to SharePoint",
                WorkflowTemplateId = new Guid(ProcessTemplateId)
            };

            var response = (CreateWorkflowFromTemplateResponse)proxy.Execute(request);

            ColumnSet cols = new ColumnSet(true);
            Workflow newWorkflow = (Workflow)proxy.Retrieve(Workflow.EntityLogicalName, response.Id, cols);

            newWorkflow.PrimaryEntity = EntityLogicalName;
        }
</code>
Answer: When archiving workflow XAML, then creating a new workflow from scratch with this xaml (with values replaced) I got an error, CRM thought the XAML was produced externally and failed to work, wouldn't let me delete the workflow, and it failed to run.
My solution was to create a workflow as a template, then in code, create a workflow from that template using a "CreateWorkflowFromTemplateRequest". This produces a workflow with the same base entity as the template, and the "CreateWorkflowFromTemplateResponse" contains this workflow's ID
I then looked this workflow up by ID, altered the base entity, replaced my values in it's XAML property and saved it as a new Workflow (with a new ID), then deleted the original workflow I created from the template.
Resulting in my code creating a new workflow, based on a template, but regarding a different entity.
You can't edit the entity of an existing workflow, hence the lookup, alter, re-save. I could probably have looked up the Template by name, altered it, but I am unsure how CRM handles templates vs workflows and chose to clone an actual workflow produced from the template.


Voice type question

Question: I have a question that's been on my mind a lot.My voice is naturally low.But my vocal range extended from D3-G5 (two years ago) but now it is C3-C6 with a whistle note A#6...What does that make me? I am a girl.
Comment: Man, I wish I could whistle that high. Other than that, the second one actually sounds similar to my range.
Answer: Many people would consider you a mezzo soprano (most mezzo soprano ranges lie between A below middle C and up to C6 for those with fairly high range).
Comment: The C6 might be possible with a special mezzo, but I doubt it would be produced incredibly comfortably, accurately, consistently, or wouldn't drain the singer too much. If you're writing high C's for your average mezzo, they're not being used correctly. A5 is pretty safe for a top-of-range note.

Voice type question


Threads não executam - Python

Question: Preciso alocar diversas threads para processarem um determinado array de dados. Porém independentemente do número de threads que aloco, uma delas sempre fica sem executar (geralmente a primeira). Segue trecho de código:
def iniciaThreads(self, tamanho, funcao):
    _passo = int( (tamanho/self.NUM_THREADS) )
    _resto = tamanho%self.NUM_THREADS

    _process = None

    _limites = []
    _limites.append(0)
    _limites.append(_passo-1)

    for i in range(self.NUM_THREADS-1):
        _process =  threading.Thread(target=funcao, name=str(i), args=[_limites])
        _process.start()
        self.threads.append(_process)
        _limites[0] += _passo
        _limites[1] += _passo

    _limites[1] += _resto
    _process =  threading.Thread(target=funcao, name=str(self.NUM_THREADS), args=[_limites])
    _process.start()
    self.threads.append(_process)

def joinThreads(self):
    for i in self.threads:
        i.join()

Função executada pelas threads:
def processaDescricao(limites):
   print("INICIADA: " + str(limites[0])+" - "+str(limites[1]))
   for i in range(limites[0], limites[1]+1):
       for j in palavras_chave:
           requisicoes[i].eliminaPalavra(j)
       requisicoes[i].eliminaCaracteresEspeciais()

Comment: Quem seta o valor de `self.NUM_THREADS`?
Comment: self.NUM_THREADS = multiprocessing.cpu_count()
Comment: Cara, esse código isolado parece estar funcionando normalmente. https://repl.it/@MaxFratane/OblongMarvelousPublishers
Comment: Poisé, mas a primeira thread não executa, inicia mas não executa. Parece que é finalizada quando as demais iniciam.
Answer: Provavelmente a thread é iniciada, e sua surpresa vem do fato de que a sua variável _limites  vai ser o mesmo objeto dentro de cada thread.
Você está passando uma lista para uma thread - as outras threads vão ver a mesma lista. Quando os valores forem atualizados na thread principal, as workers vão ver os valores atualizados.
Se quiser mesmo usar uma lista para isso, passe uma cópia da mesma:
from copy import copy
...
    _process =  threading.Thread(target=funcao, name=str(self.NUM_THREADS), args=[copy(_limites)])

Ou simplesment, já que são só dois valores, expanda a sequência "limites", de forma que cada item vire um parâmetro diferente:
    _process =  threading.Thread(target=funcao, name=str(self.NUM_THREADS), args=[*_limites])

...

def processaDescricao(inicio, fim):
   print("INICIADA: " + str(limites[0])+" - "+str(limites[1]))
   for i in range(limites[0], limites[1]+1):
       for j in palavras_chave:
           requisicoes[i].eliminaPalavra(j)
       requisicoes[i].eliminaCaracteresEspeciais()

Algumas notas não relacionadas com seu problema principal:
Você provavelmente vai ter um erro no tamanho da sua fatia aí  - o comportamento
padrão do Python, de fatias fechadas no início e abertas no final (o elemento na posição final não é incluido na fatia), resolve quase todos os problemas desse tipo, sem necessidade de ficar subtraindo ou aumentando "1" aos índices de inicio e final de fatias.
Em particular, essa linha aqui: _limites.append(_passo-1)  deveria ser só _limites.append(_passo)  - e você vai ter menos dor de cabeça.
Segundo: Python tem várias formas de interpolar valores em strings, e todas elas mais práticas do que fechar um trecho da string e usar + para concatenar o valor desejado.
A recomendação em Python moderno é usar as f-strings que podem expandir expressões de código dentro de  {  } dentro da string.
Ou seja:
 print("INICIADA: " + str(limites[0])+" - "+str(limites[1]))

fica
 print(f"INICIADA: {limites[0]} - {limites[1]}")

E por fim, o uso de "_" como prefixo de nomes de variáveis é recomendado para indicar que variáveis, atributos e métodos são de uso privado do implementador daquele código. Mas nem isso muda nada na forma como o Python trata essas variáveis, nem faz sentido para variáveis locais (que já são  de acesso restrito por natureza). Elas só fazem atrapalhar a leitura do codigo, com símbolos que fazem o cérebro parar pra pensar "que esse  _ tá fazendo aí". (é uma parada pequena e imperceptível conscientemente, mas repetida pra cada nome de variável que você vê no seu programa enquanto estiver mexendo no código - o saldo final é um programador mais cansado)

Threads não executam - Python


SQL Server 2005 joining results of two different sp like

Question: I want to join results of two different store procedures that returns same structure
in following fashion:
   EXEC StoreProcedure1 p1
   UNION
   EXEC StoreProcedure2 p2

I realize that is not possible, can sombody suggest elegant alternative?
I beleive I should use temp table ?
Thanks
Answer: You could convert the stored procedures into user defined functions that return tables instead and do:
SELECT * FROM dbo.MyFunction1(p1)
UNION
SELECT * FROM dbo.MyFunction2(p2)

Comment: You still would be: all the functions need to do is call the stored procedures and return the results.   It's really the better way to do this.
Answer: In SQL Server you could do the following:
create table #temp (
  col1 type,
  col1 type,
  ...
)

insert into #temp
exec sproc1
go
insert into #temp
exec sproc2
go

select * from #temp
go

drop table #temp

However, my preference would be to determine which queries both stored procedures are running and then write a query from scratch performing the same queries and unioning them together.
Comment: as I expected, thanks, I was wandering if there was way around it
Comment: just be aware of the performance hit from using temp tables for this. If you're dealing with small data, you'll prob not notice, but otherwise you will be hit by writing to tempdb


Isolating a computer in the network

Question: I've got a small network and want to isolate one of the computers from the whole network.
My Network:
<code>                               <----> Trusted PC 1
ADSL Router --> Netgear dg834g <----> Trusted PC 2
                               <----> Untrusted PC
</code>
I want to isolate this untrusted PC in the network.
That means the network should be secure against :
 * ARP Poisoning
 * Sniffing
 * Untrusted PC should not see / reach any other computers within the network but can go out the internet.

Static DHCP and switch usage solves the problem of sniffing/ARP poisoning.
I can enable IPSec between computers but the real problem is sniffing the traffic between the router and one of the trusted computers.
Against getting a new IP address (second IP address from the same computer) I need a firewall with port security (I think) or I don't think my ADSL router supports that.

To summarise I'm looking for a hardware firewall/router which can isolate one port from the rest of the network. Could you recommend such a hardware or can I easily accomplish that with my current network?
Comment: You didn't mentioned type of connection between PCs and dg834g Ethernet or Wireless. And are you planning to add more wired/wireless trusted/untrusted computers?
Answer: Solution 1:
Hide untrusted PC under another router. This will solve arp-spoofing/mitm problem.
Solution 2:
Use any router with DD-WRT firmware. There you can setup different Wireless LANs and even put them in different VLANs. Too bad that ADSL modems aren't supported by it.
Comment: +1 for cheap solutions.  Correct me if I'm wrong, but wouldn't you want the trusted PC's under a second router?  This would add another firewall between them and the untrusted PC.

Although you say ADSL isn't supported, couldn't he do a hybrid of your two solutions.  Get a second router and put DD-WRT on it.  Then, jack that into the port on the ADSL router.
Comment: if you hide trusted PCs under router untrusted-one can spoof IP of router gateway(ADLS router) and intercept all traffic.
And, yes the only solution with DD-WRT is to use second router, but still unless you setup firewall rules untrusted PC will be able to connect to trusted ones.
Answer: A firewall with either several physical interfaces (atleast 3), or with virtual interface (VLAN) support will solve this for you. I think Linksys sells SBS VPN Routers that can do this cheap.
Answer: I can't specifically recommend a device, but the situation you're describing is called a DMZ and is often used to exclude servers from other parts of the network or other networks themselves (e.g. the internet).
Comment: This isn't necessarily a DMZ situation. A DMZ would leave the untrusted computer open to the Internet, at least on consumer level products.  Just because he wants that computer isolated from the rest of the network does not mean he wants it open to access from the Internet.
Comment: @NYSA - Not necessarily .. "DMZ" does not imply open to the internet (or unprotected).  It really implies that the rest of the network is protected from the DMZ.  Generally, the DMZ is behind a firewall, but specific services and computers are exposed through the firewall.
Answer: My favorite solution ... Astaro Security Gateway - free for non-commercial use - download the software and put it on an old PC with a couple of extra NICs - use the router as an access point.
<code>                                     -- NIC #2 - router - TRUSTED PCs
DSL Modem -- NIC #1 - PC running ASG -
                                     -- NIC #3 - UNTRUSTED PC
</code>

Also, the Netgear site shows that the device you list has "exposed host (DMZ)" capabilities.  Not sure if that means the "exposed" computer is isolated from the rest of the network, although the manual should make that clear.

Alternatively, put the UNTRUSTED PCs behind a second router as SaveTheRbtz suggests.  This will protect the trusted PC traffic from the untrusted PC, but does not protect the trusted PCs from attacks from a compromised untrusted PC.
<code>                      -- Router 2 -- Untrusted PC
DSL Modem -- Router 1 -
                      -- Trusted PCs
</code>
EDIT: Put untrusted PC behind the router.  This addresses original question concerns for untrusted PC seeing trusted PC traffic.
 - apologies to SaveTheRbtz
Comment: I think the only problem in here that untusted pc *might* control the traffic between "router 1" and "router 2". To avoid this I should use some MAC filtering/binding or static routing and none of them seems feasible with my hardware and setup.
Comment: +1. In second scheme untrusted PC can intercept all taffic of Trusted ones.
Comment: See my EDIT to address these issues ... I skipped the "sniffing" part of the question.
Answer: If you are really that concerned about it, then get a separate DSL account for that computer.
Otherwise you can pick up a DD-WRT Linksys router on ebay for $80 or so and set up a vlan.
Comment: I can't have a separate DSL with the same line. Otherwise that's what I'd have done.
Answer: Look for VLAN support, anything above the normal consumer grade stuff should have it. We do it on our Draytek 3300, and on our Cisco Catalyst 3548 switch.
Comment: I want it for home so don't want to spend too much to be honest. But VLAN sounds like a good idea, do you know any cheap recommendations?
Comment: If you can pick up some second hand Cisco kit (877 range, perhaps, or the 2900/2500 switches), that might be cheapest, I got a 3548 for £23 on Ebay.

DD-WRT has vlan support, if you've got a router you can install that on, it's a free option.
Answer: If you wanted to stop access entirely for that machine You could use mac filtering.
Comment: MACs can be easily spoofed.
Comment: @SaveTheRbtz - just one part of a puzzle.
Answer: I have to agree with Adam, you need a DMZ. By not opening any ports from the Internet to the DMZ it cannot be accessed from the Internet but should still have Internet access.
I suggest you forget about doing this with routers and switches and install a proper firewall and I highly recommend Smoothwall.
Answer: a super cheap solution is to have a small $10.00 workgroup switch after the modem but before the router. Then use the router to send out to your trusted PCs. thats if you want to have the untrusted pc on the internet. the router you use will need to be locked down and undetectable to even the "trusted" computers. is it sniffable? sure. is that probable? not really.
cisco has a couple awesome switches with Vlan ect... for $100.00 on Ebay, they also have POE ports if you have wireless access points or IP security cameras.
Answer: PfSense on an ALIX board, ~$200 USD from Netgate.  Powerful (500MHz proc, 256MB RAM), silent, passively-cooled, very low power consumption (~5 Watts avg.), 3 NICs (so you can setup a separate VLAN), and great community support.

Isolating a computer in the network


Centering a transform:scaled image

Question: I have an img that I've scaled to half size via;
transform: scale(0.5);

As seen above, the result is such that an invisible margin/padding is evident on the top & left of the image (equaling half the size the original image).  Inspecting the resulting img in chrome dev tools shows that no margin or padding is evident.
If I know the size of the image prior, I can set position: absolute and offset the top & right values to position it in the center of the container div.  This will not however work with dynamic image sizes.
How can I center the scaled image within the parent div without needing to know the image size prior?
codepen and snippet:

#container {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 300px;
  height: 100px;
  background: #AAA;
}
#image {
  transform: scale(.5);
}

Expected result;
Comment: remove the transform and check
Comment: Is scale always `.5`?
Answer: If scale is constant 0.5 you can use left/right 50% and translate(-100%, -100%), width and height of image and container can be dynamic and this will work.

#container {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 300px;
  height: 100px;
  background: #AAA;
}
#image {
  transform: scale(.5) translate(-100%, -100%);
  position: absolute;
  left: 50%;
  top: 50%;
}

Answer: Adding max-width: 100% to the #image seems to center the image inside the container.

#container {
  position:absolute;
  top: 0;
  bottom:0;
  left: 0;
  right:0;
  margin: auto;
  width: 300px;
  height: 100px;
  background: #AAA;
}

#image {
  transform: scale(.5);
  max-width: 100%;
}

Check it out and let me know your feedback. Thanks!
Comment: The scaling occurs with respect to the image - not the container.  If the original image is 500px wide, then the resulting image should be 250px.
Comment: Cheers for the snippet edit, for some reason the editor wouldn't show in my browser.  I've updated the question to include the expected result - your answer seems to shrink the image again.
Comment: when you use `max-width: 100%` you would be scaling down by half with respect to the width of the container (you have given a fixed height and width for it)... maybe you should adjust the scale factor...
Comment: Well, in that case @NenadVracar 's solution should do fine :)
Answer: Your img element is bigger than your container.
use;
max-width: 100%;

and also;
transform-origin: 50% 50%;

Comment: Tried this, but `max-width: 100%` seems to shrink/scale the image smaller again.  Not sure what effect `transform-origin` is having.  I've added a screenshot of the expected result to the question.
Comment: Your container has 300px width right? So your image will be the same. And after, you are using scale(.5) exatly half of your parent container. So your image will be 150px width. transform-origin has the effect of where should the transform start. y-x values. top left or bottom right or middle center etc. see here: https://css-tricks.com/almanac/properties/t/transform-origin/
Comment: The image supplied is 500 width, the transform: scale(0.5) makes it 250px - not 150 px.

Centering a transform:scaled image


Finding a Noetherian faithful module

Question: Let $M$ be a faithful $A$-module with the property that the modules of the form $IM$ for some ideal $I\subseteq A$ satisfy the ascending chain condition; also, suppose that $\{m_1,\dots,m_r\}\subseteq M$ is a set of generators. I have to find a Noetherian faithful $A$-module.
I tried two ways: first considering a $JM$ maximal among the submodules of the form $IM$ for which $M/IM$ is not Noetherian; then considering a $JM$ maximal among the submodules of the form $IM$ for which $M/IM$ is faithful. (In both cases $(0)\subset A$ satisfies the condition, so there is also a maximal submodule among those satisfying it). However I don't see how too continue, admitting that one of those path is the correct one. I think that an answer could be the one to this question (Ring is Noetherian if it admits a faithful finitely generated module with ACC on submodules generated by ideals), putting together first step and the second approach below. However I don't understand why we can make the reduction in the first step, nor the argument used in the second approach. Could you give me a clarification? Thanks
Answer: Perhaps I should spell out the argument given in the linked answer, and you can let me know which step(s) you query.
(1) Let $M$ be as given in your question.  If $M$ is Noetherian, then as $M$ is also faithful, it will give you an answer to your question.  Suppose that $M$ is not Noetherian.  We will deduce a contradiction.
(2) By the ACC condition given, we may pick a maximal submodule of the form $IM\subseteq M$ where $I\subset A$ an ideal, and $M/IM$ not Noetherian.
(3) Let $I_0={\rm Ann}(M/IM)$.  Then $I\subseteq I_0$ and $I_0M\subseteq IM$ by definition of annihilator. Thus $IM=I_0M$.  Let $M'=M/I_0M$. Then $M'$ is faithful as a module over $A'=A/I_0$.
(4) $M'$ is not Noetherian over $A$ by construction.  It has the same submodules when regarded as a module over $A'$, so it is not Noetherian over $A'$ either.
(5) However  for any ideal $0\neq J\subset A'$, we have $M'/JM'=M/KM$ for some ideal of $A$: $K\supsetneq I_0\supset I$. Here $K$ is the preimage of $J$ under the quotient map $A\to A/I_0$.  By the maximality condition on $I$, we have that $M/KM$ is Noetherian over $A$, so $M'/JM'$ is Noetherian over $A'$.
(6) Suppose that $N\subseteq M'$ is a submodule (over $A'$).  Either $M'/N$ is faithful, or it is not, in which case $N\supset iM'$ for some $0\neq i\in A'$, so $M'/N$ is a quotient of $M'/iM'$, hence Noetherian by (5).
(7) Given a nested chain of submodules $\{N_i\subseteq M'|i\in \mathcal{I}\}$, with $M'/N_i$ faithful over $A'$, let $N$ be the union of the $N_i$.  If  $aM'\subseteq N$, for some $0\neq a\in A'$, then for $s=1,2,\cdots,r$, we have $am_s\in N$, so we have $am_s\in N_{i_s}$ for some $i_s\in \mathcal{I}$. Let $i$ denote the supremum of $i_1,i_2,\cdots,i_r$. Then we have $aM\subseteq N_i$, contradicting the assumption that $M/N_i$ is faithful for all $i\in \mathcal{I}$.  Thus $M'/N$ is faithful.
(8) By (3) we know that $M'/\{0\}$ is faithful.  By (7) we know that modules $N$ with $M/N$ faithful are closed under nested unions.  Thus by Zorn's lemma, we may choose $N$ maximal such that $M'/N$ is faithful.
(9) Let $M''=M'/N$.  By the maximality of $N$, we know that any proper quotient of $M''$ is not faithful, hence by (6) such a quotient must be Noetherian.
(10) Let $$\{0\}\subsetneq N_1\subsetneq N_2\subsetneq N_3\subsetneq\cdots$$ be a strictly increasing infinite chain of submodules in $M''$.  Then $$N_2/N_1\subsetneq N_3/N_1\subsetneq N_4/N_1\subsetneq\cdots$$ is a strictly increasing infinite chain of submodules of $M''/N_1$, contradicting (9).
(11) Now we know that $M''$ is both faithful and Noetherian (over $A'$), we will deduce that $A'$ is Noetherian:  Suppose we have an infinite strictly increasing chain of ideals $I_i$ in $A'$.  For fixed $s=1,2,3,\cdots,r$, we know that the submodules $I_im_s\subseteq M''$ will eventually be constant.  Thus we have an infinite strictly ascending chain of ideals $I_i\cap {\rm Ann} (m_s)\subseteq {\rm Ann} (m_s)$ (Important: Here we regard $m_s\in M''$).  Repeating this step for $s=1,2,3,\cdots,r$, we obtain an infinite strictly ascending chain of ideals inside $${\rm Ann} (m_1)\cap {\rm Ann} (m_2)\cap {\rm Ann} (m_3)\cap\cdots\cap {\rm Ann} (m_r).$$
However this intersection is $\{0\}$ as $M''$ is faithful over $A'$. This gives us a contradiction to the existence of the infinite strictly increasing chain of ideals in $A'$. We conclude $A'$ is Noetherian.
(12) As $A'$ is Noetherian, and $M'$ is finitely generated over $A'$, we have that $M'$ is Noetherian over $A'$, contradicting (4).
(13) This is the contradiction we were seeking in (1).  Thus we know that $M$ is both faithful and Noetherian over $A$, answering your question.

Finding a Noetherian faithful module


How does the probability of dependent events change?

Question: Let's say you have a $50\%$ chance of going to the club on Friday and $30\%$ chance of going on Saturday, then (assuming the events are independent), the probability of going at least once on the weekend, which I'll call $P$, is $P=1-0.5\times0.7=0.65$.
Now let's say the events are dependent; if you go on Friday, you're $10\%$ less likely to go on Saturday. Does $P$ increase, decrease, remain unchanged, or is there not enough information?
Comment: P can go either way. You'll need to define how exactly they are dependent so you can form a strategy for the question (sounds like a classic bays low theorem)
Answer: Let $E_1$ be the event that you go on Friday and let $E_2$ be the event that you go on Saturday. We then have
$$P = \mathbb{P}(E_1) + \mathbb{P}(E_2) - \mathbb{P}(E_1\cap E_1).$$
Like you said, if $E_1$ and $E_2$ are independent, then $\mathbb{P}(E_1\cap E_2) = \mathbb{P}(E_1)\cdot \mathbb{P}(E_2)$, giving $P = 0.5 + 0.3 -0.15 = 0.65$. But $\mathbb{P}(E_1\cap E_2)$ can be any number less than $0.3$ since $E_1\cap E_2 \subseteq E_2$. Say you pledge to never go to the club on both days (that is, $E_1$ and $E_2$ are mutually exclusive -- very not independent). Then $\mathbb{P}(E_1\cap E_2) = 0$ and $P = 0.8$. On the other hand, say you pledge to only go on Saturday if you went on Friday as well. Then $E_2 = E_1\cap E_2$ and $P = 0.5$.
The short of it is that it depends on how your events depend on each other.


I can not realize the task of transferring from xlsx to csv

Question: Condition:
In the Excel office program (or its analogues), you can always save the table in csv format.
Imagine that this functionality is broken.
Write your own excel -> csv transcoder using the appropriate libraries.
Your program should open the data.xlsx file containing arbitrary data and save the result in output.csv
Input format
Not
Output format
In the output.csv file, output data from the source file in csv format.
Separator - "semicolon"
Quotation - quotation marks
Notes
Use the csv module
My code:
import csv
import openpyxl
from openpyxl import Workbook

wb = openpyxl.load_workbook(filename='data.xlsx', data_only=True)
with open('output.csv', 'w', newline='', encoding="utf8") as csvfile:
    writer = csv.writer(csvfile, delimiter=';', quotechar='"')
    for ws in wb:
        for row in ws.iter_rows():
            line = []
            for v in row:
                line.append(str(v.value))
            writer.writerow(line)

for some reason real numbers do not pass
Comment: At least for me real numbers do actually pass. openpyxl just seems to convert numbers with a decimal fraction of 0 into integers, which seems to happen in your case as well. Just have a look at the last element of each row.
Comment: Using `str()` is going let Python decide. Use string formatting if you want more control.
Answer: Is it okay if I could suggest you to use pandas?
import pandas as pd

full_dataset = pd.read_xls('file.xlsx')

Assuming that it has 2 worksheets
full_dataset['worksheet1'].to_csv('worksheet1.csv', index = False, headers = True)
full_dataset['worksheet2'].to_csv('worksheet2.csv', index = False, headers = True)

And you are done. Have a nice day!
Comment: Not really suitable for very large files because it adds an intermediate step. It's easy enough with openpyxl.
Comment: But Excels have a limitation to be functional and usable, and as long as it's not a relational database with more than 1 million records. This is more than sufficient.
Comment: Dataframes are in memory objects and are not required here. The deficiencis of the XLSX file format are well known but not relevant here.


Find $\mathbb{P}[\exists n>0 : X_n=j \mid X_0=i]$ in Markov Process

Question: Let $\left\{B_n\right\}_{n=0}^{\infty}$ be an i.i.d. process, such that, for every $n\in\mathbb{N}\cup{0}$:
$$\mathbb{P}[B_n=-1]=p \\ \mathbb{P}[B_n=+1]=q$$
Such that $p+q=1$. Let $\left\{X_n\right\}_{n=0}^\infty\subset\mathbb{S}$ be a markov chain, where $\mathbb{S}=\left\{i\right\}_{i=0}^K=\left\{0,1,...,K\right\}$ for some $K\in\mathbb{N}$, such that:
$$X_n=X_{n-1}+B_{n}\qquad0<X_{n-1}<K \\ X_n=X_{n-1}\qquad\qquad \ \ X_{n-1}\in\left\{0,K\right\}$$
I drew the diagram of the process in order to see things more clearly:

Define the probabilty $\rho_{ij}$ for every $i,j\in\mathbb{S}\setminus\left\{0,K\right\}$ such that:
$$\rho_{ij}\triangleq\mathbb{P}[\exists n>0 : X_n=j \mid X_0=i]$$
(In other words, $\rho_{ij}$ is the probability that the chain would somewhen visit the state {$j$}, given that the initial state is {$i$}. It is clear that if the initial state is $X_0=0$, then it is certain that the chain would visit the state {$0$} again, but never any other state. In other words, $\rho_{0k}=\delta[k]$ where $\delta$ is the delta of kronecker.)
It is given that $p=q=1/2$. Find $\rho_{ij}$ for every $i,j\in\mathbb{S}\setminus\left\{0,K\right\}$.

I feel like I've tried everything. It seems that doing this straightforward is impossible, since the total number of paths that must be considered is too large. I understand that the expression would be different for the three cases $i=j,i>j$ and $i<j$. Finding $\rho_{ii}$ shouldn't be a problem if I knew $\rho_{ij}$ for $i>j$ and $i<j$, since:
$$\rho_{ii}=p\rho_{i-1,i}+q\rho_{i+1,i}=[\rho_{i-1,i}+\rho_{i+1,i}]/2$$
And obviously $i>i-1$ & $i<i+1$.
Thank you very much!
Comment: @copper.hat $X_0\in\mathbb{S}=\left\{0,1,2,...,K\right\}$ where $K\in\mathbb{N}$
Comment: I'm a bit lost in notation, what is $X_0$?
Comment: @copper.hat $X_0$ is the initial state of the chain. For example, if $X_0=4$, then $X_1=3$ with probability $p=1/2$ or $X_1=5$ with probability $q=1/2$. I am required to compute $\rho_{ij}$, meaning the initial state is $X_0=i$, and I need to find what is the probability that the chain would somewhen visit the state $j$.

For example, $\rho_{00}=1$ and $\rho_{05}=0$, because if you start from the state {$0$}, it is certain that the chain will visit the state {$0$} again, and it is certain that it will never reach the state {$5$} (since the state {$0$} is a closed connected group).
Comment: Is it an integer, positive, ...?
Comment: Sorry, I see you did define it. Excuse my inattention :-(.
Answer: A suggestion:
Merge states $1$ and $2$, and also $K-1$ and $K$. Find the transition matrix $P_{(K-2)\times (K-2)}$ for the new $(K-2)$-state Markov chain, which the elements of $P^n$ gives you the transition probabilities for states $3$ to $K-2$. A conditional probability would yield the desired result for the inner states of the two merged states.


Read in input text Yes/No Boolean from user to proceed the next step

Question: I amm at my very beginning at java and just wanted to ask.
I want to ask the user to put Yes/No to a question and proceed to the next question. How do I do it?
import java.util.Scanner;

public class sff {

    public static void main (String args[]) {

        System.out.println("Hello There! We want to ask you some questions! but first: ");
        System.out.print("Enter your age: ");

        Scanner in = new Scanner(System.in);
        int num = in.nextInt();

        int age = num;

        if( age == 12){
            System.out.println("Hello Dan, I know you very well! ");
        }

        {

        System.out.println("First question: ");
        System.out.println("Do you exercise?(Yes/No) ");
        // how do i proceed from here??

Comment: What have you done by now?
Comment: @MichaelBistritzki Post that in the question. You can't expect anyone to read that in the comments. And if you have code, what's your question?
Comment: There is no need to assign the value captured by `int num` to the new `int age` variable so you can use that in your `if` statement. `if (num == 12) {...`. A `boolean` can only be `true` or `false` so I think it's best to just capture the yes/no in a `String` object and check what the user has choosen. Since you are checking age in your `if` you can remove `num` variable all together as `age` would be a more suitable name.
Comment: What's your problem? You don't know how to read a string from scanner? You dunno how to do a string comparison?
Comment: Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content ([under the CC BY-SA 4.0 license](https://stackoverflow.com/help/licensing)). By SE policy, any vandalism will be reverted.
Answer: Use Scanner and get next line, then check if that line is yes or no then handle respectively.
In the example below, I used a while loop to keep asking them to input yes or no in case they enter something different like "maybe".
For example:
Scanner in = new Scanner(System.in);

// Loop until they enter either yes or no.
while(true){
String line = in.nextLine();
    // Use this to check if it is yes or no
    if(line.equalsIgnoreCase("yes")){
      // Process yes
      break;
    }else if(line.equalsIgnoreCase("no")){
      // Process no
      break;
    }else{
      // Tell them to enter yes or no since they entered something else.
    }
}

Answer: Are you looking for something like this?
//import to use the Scanner
import java.util.Scanner;

public class Stack_Overflow_Example {
    public static void main(String[] args) {

    System.out.println("First question: ");
    System.out.print("Do you exercise?(Yes/No) ");
    Scanner in = new Scanner(System.in);
    //get the user input and store it as a String
    String exerciseQuestion = in.nextLine();
    //check what the user said.
    if(exerciseQuestion.equalsIgnoreCase("yes")){
        System.out.println("Dan does exercise");
        //do you code when he exercises
    }
    else{
        System.out.println("Dan does not exercise");
        //do your not exercise code here
    }
    System.out.println("Ask your next question so on....");

  }//main
}//class

If you want to deal with answers other than yes/no you can use this code:
import java.util.Scanner;

public class Stack_Overflow_Example {
    public static void main(String[] args) {

    System.out.println("First question: ");
    System.out.print("Do you exercise?(Yes/No) ");
    Scanner in = new Scanner(System.in);
    String exerciseQuestion;
    while (true){
        //get the user input
        exerciseQuestion = in.nextLine();
        //check if user input is yes or no
        if((exerciseQuestion.equalsIgnoreCase("yes")) ||
                     exerciseQuestion.equalsIgnoreCase("no"))
            //if yes break and continue with your code
            break;
        else
            //else loop back to get user input until answer is yes/no
            System.out.println("Please answer with yes or no only");

    }//while . i.e answer not yes or no
    if(exerciseQuestion.equalsIgnoreCase("yes")){
        System.out.println("Dan does exercise");
       //do your code
    }
    else{
        System.out.println("Dan does not exercise");
        //do your not exercise code here
    }//else

  }//main
}//class

Comment: Can the down voter explain why the down vote, please?
Comment: Yes, something like this but what about if the user puts an input that is "yes" and not "Yes"? or this kind of stuff?
Comment: Check the new edit. Just use, `equalsIgnoreCase` instead of `equals`
Comment: I have also added in the edit, to deal with answers other than `yes/no.`
Comment: Thank you very much for your help :)
Comment: Can you please, mark it as answered if this is what you were looking for. I am not sure why someone down voted this answer.