text:
Q: What is the probability of 2 players meeting during a random knockout tennis tournament? A tennis tournament has $n$ players. $n$ is an even number. Each round, we randomly pair two players and all players have the same ability and the winner is random. All winners go to the next round and are paired up again randomly. We repeat this process until one player left as the champion.
Say we have two players $A$ and $B$, what's the probability that $A$ meet $B$ during the entire tournament?
For the answer, I get that 1) we need $n-1$ games in total to eliminate $n-1$ players 2) there is $C^{n}_{2}$ way to match $2$ players.
What I don't understand is why the answer is $\frac{(n-1)}{C^{n}_{2}}$.
Isn't that $C^{n}_{2}$ is only for the first round when we still have $n$ players? For the second round, if $A$ and $B$ still stay in the game, but the number of the plays in the game has been reduced to $0.5n$, so $C^{0.5n}_{2}$ is probability for $A$ to meet $B$? And if any of $A$ or $B$ got knocked out, they will never meet? What I don't get is, the denominator only holds before any matches start right? once the game started and getting the n-1 games, in each round, the probability for A meet B is different, correct?

A: (1) Since there are $n$ players, and exactly $1$ player is eliminated from each match, there need to be a total of $n-1$ matches played.
(2) Before playing any matches, there is an $1/{n\choose 2}$ chance that any two random players will meet in any one match.
Thus there is $(n-1)\frac{1}{{n\choose 2}}$ chance that any two players will meet in the tournament (since there are $n-1$ matches for them to meet in, with a probability $1/C^n_2$ in each match).
It can also be thought of as you have a $1/C^n_2$ chance of satisfying the criterion (players $A$ and $B$ meet) and you get $n-1$ chances (before any matches are played).

A: Addendum added to respond to a comment/question.

original answer
Alternative approach that is very similar to Brian Tung's comment, which immediately followed the question.
Each time that a match is played, there are two man-meetings: For example, if A plays B, then A has met with a person and B has met with a person.
There will be a total of $(n-1)$ matches played.  This means that there will be a total of $2(n-1)$ man-meetings that occur.  Since there are $n$ people, each person, will on average, experience $\frac{2(n-1)}{n}$ man meetings.
This means that the chance that a given person's man meetings include a specific one of the other $(n-1)$ people is
$$\frac{2(n-1)}{n} \times \frac{1}{n-1} = \frac{2}{n}.$$

Addendum
Responding to a comment question:

What I still don't get is, the denominator only holds before any matches start right? once the game started and getting the $n-1$ games, in each round, the probability for $A$ meet $B$ is different, correct?

Yes, the probability for $A$ and $B$ to meet, does change, round by round.  The original question was to compute the overall chance of $A$ and $B$ meeting anywhere in the tournament.  This overall chance has been computed as $(2/n)$, where $n$ is the number of original players.
The same answer, $(2/n),$ can be computed by a direct round by round examination of the tournament.  The approach is much less elegant, but still do-able.  I will illustrate with two examples: $(n=16)$ and $(n=10)$.

$\underline{\text{Case 1:} ~n=16}$
For Round $1$:
There are $\binom{16}{2}$ possible pairings, of which $8$ will occur in Round $1$.  Therefore, the chance of $A$ and $B$ meeting in Round $1$ are
$\displaystyle \frac{8}{\binom{16}{2}} = \frac{2 \times 8}{16 \times 15} = \frac{1}{15}.$
Note that since the number of players is $n = 2^4$, the tournament will have $4$ rounds.
For $k \in \{1,2,3,4\}$, I will let $T_k$ denote the probability of $A,B$ meeting in Round $k$.  Then, the overall probability will be $T_1 + T_2 + T_3 + T_4.$
For Round $1$, $T_1$ has been computed as
$$T_1 = \frac{1}{15}.$$
I will also employ helper variables $S_1, S_2, S_3$, where $S_k$ will represent the probability that $A,B$ were not paired together in Round $k$, given that they each made it to Round $k$.
Here, $$S_1 = 1 - \frac{1}{15}  = \frac{14}{15}.$$

In order to meet in Round $2$, several things must happen.

*

*They must not meet in Round $1$, but must each survive Round $1$.
The chances of this happening are
$\displaystyle \frac{14}{15} \times \frac{1}{4}.$

*They must be paired together in Round $2$, which will have $4$ pairings out of a possible $\binom{8}{2}$.  The chances of them being paired together are therefore
$\displaystyle \frac{4}{\binom{8}{2}} = \frac{4 \times 2}{8 \times 7} = \frac{1}{7}.$
Therefore
$$T_2 = \frac{14}{15} \times \frac{1}{4} \times \frac{1}{7} = \frac{1}{30}.$$
Further, since $(1/7)$ is the chance that they were paired together in Round $2$, assuming that they made it that far, then
$$S_2 = 1 - (1/7) = (6/7).$$

In order to meet in Round $3$, several things must happen.

*

*They must not meet in Round $1$, but must each survive Round $1$.
The chances of this happening are
$\displaystyle \frac{14}{15} \times \frac{1}{4}.$

*Then, they must not meet in Round $2$, but must each survive Round $2$.
The chances of this happening are
$\displaystyle \frac{6}{7} \times \frac{1}{4}.$

*They must be paired together in Round $3$, which will have $2$ pairings out of a possible $\binom{4}{2}$.  The chances of them being paired together are therefore
$\displaystyle \frac{2}{\binom{4}{2}} = \frac{2 \times 2}{4 \times 3} = \frac{1}{3}.$
Therefore
$$T_3 = \frac{14}{15} \times \frac{1}{4} \times
\frac{6}{7} \times \frac{1}{4} \times
\frac{1}{3} = \frac{1}{60}.$$
Further, since $(1/3)$ is the chance that they were paired together in Round $3$, assuming that they made it that far, then
$$S_3 = 1 - (1/3) = (2/3).$$

In order to meet in Round $4$, several things must happen.

*

*They must not meet in Round $1$, but must each survive Round $1$.
The chances of this happening are
$\displaystyle \frac{14}{15} \times \frac{1}{4}.$

*Then, they must not meet in Round $2$, but must each survive Round $2$.
The chances of this happening are
$\displaystyle \frac{6}{7} \times \frac{1}{4}.$

*Then, they must not meet in Round $3$, but must each survive Round $3$.
The chances of this happening are
$\displaystyle \frac{2}{3} \times \frac{1}{4}.$

*They must be paired together in Round $4$.  Since Round $4$ will be the championship match, Round $4$ will only have 1 pairing.  Therefore, if $A,B$ each make it to Round $4$, then they are certain to meet.
Therefore
$$T_4 = \frac{14}{15} \times \frac{1}{4} \times
\frac{6}{7} \times \frac{1}{4} \times
\frac{2}{3} \times \frac{1}{4} = \frac{1}{120}.$$

Therefore, the overall chances are $T_1 + T_2 + T_3 + T_4$ which equals
$$\frac{1}{15} + \frac{1}{30} + \frac{1}{60} + \frac{1}{120}$$
$$= \frac{8 + 4 + 2 + 1}{120} = \frac{15}{120} =
\frac{1}{8} = \frac{2}{16} = \frac{2}{n}.$$

$\underline{\text{Case 2:} ~n=10}$
This will be somewhat complicated by the fact that $n=10$ is not a power of $2$ (e.g. such as $16 = 2^4$).  Therefore, some of the Rounds will feature a player being given a bye, where they are automatically passed to the next round.  Note that when a player is given a bye, for a specific round, they don't play anyone during that round.
As in the case of $n = 16$, I will let $T_k$ denote the chance of $A,B$ meeting in Round $k$.
If Round $k$ features a bye, then I will let $R_k$ denote the chance that any player receives a bye, and I will then let $S_k$ denote the chance of $A,B$ not meeting in Round $k$, given that they each made it to Round $k$, and also given that neither of them are given a bye for Round $k$.
Alternatively, if Round $k$ does not feature a bye, then I will let $S_k$ denote the chance of $A,B$ not meeting in Round $k$, given that they each made it to Round $k$.
For Round $1$:
There are $\binom{10}{2}$ possible pairings, of which $5$ will occur in Round $1$.  Therefore, the chance of $A$ and $B$ meeting in Round $1$ are
$$T_1 = \frac{5}{\binom{10}{2}} = \frac{2 \times 5}{10 \times 9} = \frac{1}{9}.$$
$$S_1 = 1 - \frac{1}{9}  = \frac{8}{9}.$$

In order to meet in Round $2$, several things must happen.

*

*They must not meet in Round $1$, but must each survive Round $1$.
The chances of this happening are
$\displaystyle \frac{8}{9} \times \frac{1}{4}.$

*With Round $2$ having $5$ players, a bye will be given.  Therefore, in order for $A,B$ to meet, neither of them must be given a bye.  The chances of neither $A,B$ being given a bye are $\displaystyle \frac{3}{5}.$

*Assuming that neither of $A,B$ are given a Round $2$ bye, they must be paired together in Round $2$.  With the Round $2$ bye person eliminated from consideration, Round $2$ will have $2$ pairings out of a possible $\binom{4}{2}$.  The chances of $A,B$ being paired together in Round $2$, assuming that neither of $A,B$ are given a bye in Round $2$, are therefore
$\displaystyle \frac{2}{\binom{4}{2}} = \frac{1}{3}.$
Therefore
$$T_2 = \frac{8}{9} \times \frac{1}{4} \times \frac{3}{5} \times \frac{1}{3} = \frac{2}{45}.$$
Here, $$R_2 = \frac{1}{5} ~~~\text{and}~~~ S_2 = 1 - (1/3) = (2/3).$$

In order to meet in Round $3$, several things must happen.

*

*They must not meet in Round $1$, but must each survive Round $1$.
The chances of this happening are
$\displaystyle \frac{8}{9} \times \frac{1}{4}.$

*Then, they must not meet in Round $2$, but must each survive Round $2$.
This computation is complicated by the possibility that one of $A,B$ was given a bye in Round $2$.  If either one of them was given a bye, then only one of them played a match.  Therefore, the chances of them both surviving because one of them was given a bye is
$\displaystyle \frac{2}{5} \times \frac{1}{2} = \frac{1}{5}.$
Alternatively, if neither was given a bye, they would have had to both survive without having played each other.  The probability that this happened is
$\displaystyle \frac{3}{5} \times \frac{2}{3} \times \frac{1}{4} = \frac{1}{10}.$
Therefore, assuming that $A,B$ both made it to Round $2$ without playing each other, the probability of them both surviving Round $2$ without playing each other is
$\displaystyle\frac{1}{5} + \frac{1}{10} = \frac{3}{10}.$

*They must be paired together in Round $3$, which will have $3$ people.  Round $3$ will therefore have 1 bye and 1 pairing.  Therefore, the chances of them being paired here are
$\displaystyle \frac{1}{3}.$
Therefore
$$T_3 = \frac{8}{9} \times \frac{1}{4} \times
\frac{3}{10} \times
\frac{1}{3} = \frac{1}{45}.$$
Further, assuming that they made it to Round $3$, then the chance of either one receiving a bye is $(1/3)$ and the chance that they then played each other, if neither was given a bye is $(1/1).$
Here, $$R_3 = \frac{1}{3} ~~~\text{and}~~~ S_3 = 0.$$

In order to meet in Round $4$, several things must happen.

*

*They must not meet in Round $1$, but must each survive Round $1$.
The chances of this happening are
$\displaystyle \frac{8}{9} \times \frac{1}{4}.$

*Then, they must not meet in Round $2$, but must each survive Round $2$.
As analyzed in the previous section, the chances of this happening are
$\frac{3}{10}.$

*They must not meet in Round $3$, but each must survive Round $3$.  The only way that this can happen is if one of them is given a bye in Round $3$.
The chance of that happening is $\displaystyle \frac{2}{3}.$
When it does happen, only one of them is playing a match, with a survival chance for that person of $\frac{1}{2}.$
Therefore, the relevant computation here is
$\displaystyle \frac{2}{3} \times \frac{1}{2} = \frac{1}{3}.$

*Having each made it to Round $4$, they must then play each other in Round $4$.  Since Round $4$ is the championship round, this is a certainty, assuming that they both make it to Round $4$.
Therefore
$$T_4 = \frac{8}{9} \times \frac{1}{4} \times
\frac{3}{10} \times
\frac{1}{3} = \frac{1}{45}.$$

Therefore, the overall chances are $T_1 + T_2 + T_3 + T_4$ which equals
$$\frac{1}{9} + \frac{2}{45} + \frac{1}{45} + \frac{1}{45}$$
$$= \frac{5 + 2 + 1 + 1}{45} =
\frac{9}{45} = \frac{1}{5} = \frac{2}{10} = \frac{2}{n}.$$

A: The only thing we need to remember is that there are $n-1$ matches, each one between a different pair of opponents, and the possible sequences of events are completely symmetrical: for any possible history of the tournament (who played whom in each pairing of each round), any permutation of the player's roles in that history is equally likely to have occurred. In particular, no two players are more likely to meet than any other two players.
Give the players identifying numbers from $1$ to $n$ inclusive.
For $1 \leq j < k \leq n,$ let $X_{j,k}$ be $1$ if player number $j$ ever plays player $k$ during the tournament, $0$ otherwise.
Then $X_{j,k}$ is a Bernoulli random variable.
Since each $X_{j,k}$ is a Bernoulli variable, $E(X_{j,k}) = P(X_{j,k} = 1)$.
Since no two players are more likely to meet than any other two players,
no probability $P(X_{j,k} = 1)$ is greater than any other, so no expected value is greater than any other, and therefore
$$ E(X_{1,2}) = E(X_{1,3}) = E(X_{2,3}) = \cdots = E(X_{n-1,n}). $$
There are $C_2^n$ such variables $X_{j,k}$. Their sum is
$$ Y = X_{1,2} + X_{1,3} + X_{2,3} + \cdots + X_{n-1,n} = n - 1 $$
because exactly $n - 1$ pairs must play, $X_{j,k} = 1$ for each of those pairs, and
$X_{j,k} = 0$ for every other pair.
By linearity of expectation,
\begin{multline}
E(X_{1,2}) + E(X_{1,3}) + E(X_{2,3}) + \cdots + E(X_{n-1,n}) \\
= E(X_{1,2} + X_{1,3} + X_{2,3} + \cdots + X_{n-1,n}) = n - 1
\end{multline}
since the expectation of a constant is just the constant.
But since the expected values of $E(X_{j,k})$ for each pair of players are all equal,
$$ E(X_{1,2}) + E(X_{1,3}) + E(X_{2,3}) + \cdots + E(X_{n-1,n}) = C_2^n E(X_{A,B}) $$
where $A$ and $B$ are the numbers assigned to the two players in the question.
That is,
$$ C_2^n E(X_{A,B}) = n - 1, $$
therefore
$$ P(X_{A,B} = 1) = E(X_{A,B}) = \frac{n - 1}{C_2^n} $$
And of course $P(X_{A,B} = 1)$ is the probability that $A$ and $B$ meet.


text:
Q: C#: How do I dynamically load/instantiate a DLL? I've seen a couple examples out there that could possibly help me, but I don't have that much time to explore them as I just found out today that my bosses have to demo this a week earlier than planned, and I want to add this new functionality.  I'll try and keep this short and sweet.
Ok, this is like my 10th time trying to right this to make it clear, hopefully it is.  This is an application.  Rows of data need to be displayed in a DataGridView (done).  Some rows are highlighted differently based on reports (done).  Most reports have their own SQL file and are implemented at runtime from an INI file (done).  However, some reports need to call a Function.  The application is using an SQLite database.  I would like to have DLLs that are reports, all of the same format, and all of them return a List of ReportRecord.  ReportRecord is a class defined in my main application but I would also define it in each DLL when they are created.  I want to instantiate the DLL, call it's "GetRecords" function, and use it in my main application.  Here is some psuedocode.  If you guys can tell me if it's possible, or give me an idea of a better way to do this, I'd appreciate it.
PSUEDOCODE
 foreach (string str in System.IO.Directory.GetFiles("C:\\ReportDlls", "*.dll"))
 {
   //Instantiate DLL e.g. newReport
   //_lstReportRecords.AddRange(newReport.GetReportRecords());
 }

Is there anyway to do this?
Currently, I have the following to supplement until I find this out:
        private void RefreshReports(string strReportTitle)
        {
            _lstReportRecords = _lstReportRecords.Where(rr => rr.Description != strReportTitle).ToList<ReportRecord>();
            string strColumn = iniFile.GetString(strReportTitle, "Column", "");

            if (strColumn != null)
            {
                _lstReportRecords.AddRange(_dataController.BuildReportList(strColumn, strReportTitle, GetReportSQL(strReportTitle)));
            }
            else
            {
                switch (strReportTitle)
                {
                    case "Improper Indenture":
                        _lstReportRecords.AddRange(_dataController.ImproperIndenture());
                        break;
                    case "Skipping Figure":
                        _lstReportRecords.AddRange(_dataController.SkippingFigure());
                        break;
                    default: break;
                }
            }
            FormatCells();
        }

Thanks everyone.
Edit: Sorry guys, looking at that stuff is honestly making me feel stupid.  Like, my mind is going blank and all and can't concentrate on it.  :)  What you guys have provided is probably the best way, but since I have to have a quality Demo ready by Tuesday and there shouldn't be any more reports added needing functions until then, I'm going to keep this open.  Once my boss is out of town to demo it, I'll work on implementing this.  But right now, it's going to go unanswered unless I see an example that is very very (for 2 year olds) straight forward.

A: You can simply create a C# library project implementing the interfaces below and store the binary file in the database or on the file system. You could then load the assembly from raw assembly bytes/file path an instantiate an object. With reflection you can also call the constructor directly, but i prefer the factory pattern for such tasks.
public interface IReportModule
{
}

public interface IReportModuleFactory
{
    IReportModule Create();
}

private static IReportModule CreateReportModuleFromRawAssemby(byte[] rawAssembly)
{
    var reportModule = Assembly.Load(rawAssembly);
    var factoryType = reportModule.GetExportedTypes()
        .FirstOrDefault(x => x.IsAssignableFrom(typeof(IReportModuleFactory)));
    if (factoryType != null)
    {
        var reportModuleFactory = (IReportModuleFactory)
            reportModule.CreateInstance(factoryType.FullName);
        return reportModuleFactory.Create();
    }
    else
        throw new NotImplementedException("rawAssembly does not implement IReportModuleFactory");
}

A: Don't look at this in terms of DLL's, which are the raw files, but Assemblies, which is how .NET sees things. You can load an Assembly using Assembly.Load. Having said this, have you considered a more generic solution, such as inversion of control?

A: I'm not really understanding what exactly you're trying to do, and IOC is probably the way to go here. But from what I understand, you could do this with pure reflection.
Mind you, this is far from the ideal way of doing things like this, but you're asking for it :)
Here it goes (top of my head, so don't shoot me if anything is wrong, it should be pretty close, though not foolproof)
// load assembly
var assemblyWithReport = Assembly.LoadFrom("Path of your assembly");

// or another Loadxx to get the assembly you'd
// like, whether it's referenced or not

// load type
var reportType = assemblyWithReport.GetTypes().ToList()
   .Where(t => t.Name == "ReportRecord").Single();

// create instance of type
var instance = Activator.CreateInstanceOf(reportType);

// get getrecords method of the type
var getRecordsMethod = reportType.GetMethod("GetRecords");

// invoke getrecords method on the instance
object result = getRecordsMethod.Invoke(instance, null);

A: Consider a plugin architecture, such as the Managed Extensibility Framework, for managing your report modules.

A: You may want to consider using the Managed Extensibility Framework for this.  It makes this type of operation trivial.
You can download it above for .NET 3.5 (it's in the framework in .NET 4 already).  By using MEF, you could just import the collection of all exported "reports" in one shot via a DirectoryCatalog, and it will take care of all of the wiring for you.
For details, see the help on Importing Collections here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to loop in R to create multiple columns and populate with values Hi I have a dataset and would like to make new columns and populate its rows by computations. I did something like this
# ETR = PhiPSII * 0.55 * Qin * fractionPSII
MGCons_FL2$ETR25 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.25
MGCons_FL2$ETR30 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.30
MGCons_FL2$ETR35 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.35
MGCons_FL2$ETR40 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.40
MGCons_FL2$ETR45 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.45
MGCons_FL2$ETR50 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.50
MGCons_FL2$ETR55 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.55
MGCons_FL2$ETR60 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.60
MGCons_FL2$ETR65 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.65
MGCons_FL2$ETR70 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.70
MGCons_FL2$ETR75 <- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*0.75

Can you help me use a loop function to automate this?
Thank you

A: Consider sapply or vapply across a sequence of multiples of 5 and assign to block of columns:
mult5 <- seq(25, 75, by=5)

MGCons_FL2[paste0("ETR", mult5)] <- sapply(
    mult5, \(x) with(MGCons_FL2, PhiPS2 * 0.55 * Qin * (x/100))
)

MGCons_FL2[paste0("ETR", mult5)] <- vapply(
    mult5, \(x) with(MGCons_FL2, PhiPS2 * 0.55 * Qin * (x/100)),
    numeric(nrow(MGCons_FL2))
)

A: # make a fake dataframe to test function
MGCons_FL2 <- tibble(PhiPS2 = rnorm(50),
                     Qin = rnorm(50))

# make a function that adds specified columns to the dataframe
column_maker <- function(col_name, number) {

  MGCons_FL2[ , col_name] <<- MGCons_FL2$PhiPS2*0.55*MGCons_FL2$Qin*number

}

# map the function over you column names and the multiplier that changes with each column
map2(.x = c("ETR25", "ETR30", "ETR35", "ETR40"), .y = seq(from= .25, to = .4, by = .05), .f = column_maker)

# check the object, the columns have been put there
MGCons_FL2

A: library(dplyr); library(tidyr)
MGCons_FL2 %>%
  crossing(fracPSII = seq(0.25, 0.75, by = 0.05)) %>%
  mutate(col = paste0("ETR", fracPSII * 100),
         val = PhiPS2*0.55 + Qin*fracPSII) %>%
  select(-fracPSII) %>%
  pivot_wider(names_from = col, values_from = val)


text:
Q: 130 GB Syslog files I have the same issue as many in this forum with the syslog file becoming massive in my case it gets to 130 GB in a day, when I looked into the file with the tail command I fund continuous remote connection attends from a couple different IP's this continuous attends is what is causing the file to become this big, this machine is my Plex media server where I have my movies, and this is the only function for this box, this is a problem for me because my primary drive is a 500gb SSD so after a couple of days I'm out of space. Any way I can block this connection attends without stopping my internet connection all along***
Jan 16 12:04:18 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:18 PM Client Protocol Version 3.4
Jan 16 12:04:18 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:18 PM Ignoring minor version mismatch
Jan 16 12:04:18 T1-UHD-Movies-7PS1 gnome-session[1729]: ** (vino-server:1964): WARNING **: Deferring authentication of '50-207-72-206-static.hfc.comcastbusiness.net' for 5 seconds
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: ** (vino-server:1964): WARNING **: VNC authentication failure from '50-207-72-206-static.hfc.comcastbusiness.net'
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:24 PM rfbAuthPasswordChecked: password check failed
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:24 PM [IPv4] Got connection from client 50-207-72-206-static.hfc.comcastbusiness.net
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:24 PM   other clients:
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:24 PM      50-207-72-206-static.hfc.comcastbusiness.net
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: message repeated 6 times: [ 16/01/2018 12:04:24 PM      50-207-72-206-static.hfc.comcastbusiness.net]
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:24 PM      192.168.23.22
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:24 PM Client Protocol Version 3.4
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:24 PM Ignoring minor version mismatch
Jan 16 12:04:24 T1-UHD-Movies-7PS1 gnome-session[1729]: ** (vino-server:1964): WARNING **: Deferring authentication of '50-207-72-206-static.hfc.comcastbusiness.net' for 5 seconds
Jan 16 12:04:29 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:29 PM [IPv4] Got connection from client 50-225-42-82-static.hfc.comcastbusiness.net
Jan 16 12:04:29 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:29 PM   other clients:
Jan 16 12:04:29 T1-UHD-Movies-7PS1 gnome-session[1729]: 16/01/2018 12:04:29 PM      50-207-72-206-static.hfc.comcastbusiness.net


text:
Q: Is it OK to hold back ack for a long time in RabbitMQ? Is it OK for a consumer (in manual ack mode) to hold back the ack message for a long time?
The use case is that a process (the consumer) processes messages from a queue (ack is set to manual), the processing takes a long time (several minutes to hours), after the processing is done, an ack is sent back.
Is RabbitMQ server/client designed to handle this kind of usage pattern?

A: This design can be done, but is not strongly recommended.  Starting in RabbitMQ 3.8.15, there is a new feature that will close connections if a message is unacknowledged longer than the configuration.  So you will want to ensure that the configuration is set for a duration greater than what your clients will experience.  See consumer_timeout documentation.


text:
Q: Как решить ошибку при тестировании angular Тестирую метод провайдер:
'use strict';

angular.module('ngTokenAuth', ['ngCookies'])
.provider('$auth', function () {

  $get: function ($http, $q, $log, $cookieStore, $rootScope, $interpolate, $timeout) {
    return {
      user: {},
      userAuth: false,
      userFirstUpdate: false,

      login: function (params) {
        var _this = this;
        var dfd = $q.defer();
        $http.post(configs.apiUrl + configs.loginPath, params)
          .success(function (resp) {
            _this.setAuthorized(resp);
            _this.setAuthorizedHeader(resp);
            return dfd.resolve(resp);
          })
          .error(function () {
            return dfd.reject();
          });
        return dfd.promise;
      }
    }
  }
};

Тесты:
    describe('Тестируем провайдер аутентификации $auth', function () {

  //Поскольку я использую ui-router, то приходится делать кастомный загрузчик
  beforeEach(module('webConsole', function($provide, $translateProvider){
    $provide.factory('customLoader', function ($q) {
      return function () {
        var deferred = $q.defer();
        deferred.resolve({});
        return deferred.promise;
      };
    });

    $translateProvider.useLoader('customLoader');

  }));

  beforeEach(module('ngTokenAuth'));

  var $auth;
  var $httpBackend;
  var $rootScope;
  var dfd;

  beforeEach(inject(function (_$auth_, _$httpBackend_, _$cookieStore_, _$rootScope_, $q) {
    $auth = _$auth_;
    $httpBackend = _$httpBackend_;
    $cookieStore = _$cookieStore_;
    $rootScope = _$rootScope_;
    dfd = $q.defer();
    spyOn($rootScope, '$broadcast');
  }));

    describe("Тестируем метод login", function () {

      describe("Тестируем положительный ответ от сервера", function () {

        var data = {
          "token": "cm9vdApwb3J0....mRFaUUDto2Ro9bI0oqSrToC0w1OdUeeMDHkRedg="
        };

        beforeEach(function () {

          console.log(data)
          dfd.resolve(data);

          spyOn($auth, 'login').and.returnValue(dfd.promise);
        });

        afterEach(function() {
          $httpBackend.verifyNoOutstandingExpectation();
          $httpBackend.verifyNoOutstandingRequest();
        });

        it("spec name", function () {

          var result;

          $auth.login()
            .then(function(resp){
              console.log(resp)
              result = resp;
            });

          $httpBackend.flush();
          expect(result).toEqual(data)
        });

      });

    });
});

В итоге я получаю ошибку:
TypeError: Cannot read property 'defaultPrevented' of undefined
...
Error: [$rootScope:inprog] $digest already in progress
    http://errors.angularjs.org/1.4.8/$rootScope/inprog?p0=%24digest
...

Тест работает если не использовать кастомный загрузчик вначале, но тогда появлется баг описанный здесь (Unit Testing with angular-translate).


text:
Q: Fetch columns by their names from an SQL database I have a data.frame stored in an SQL database, created with the dbWriteTable function of the R sqldf package.
I was wondering whether there is a way to fetch specific columns by their names from this data.frame in this SQL database.
For fetching rows by their names, this code  works:
#let's say the row names I want to select from the data.frame are in a vector called selected_row_names, where the data.frame is called df and the SQL database is called db
query_text <- paste("('",paste(selected_row_names,collapse="', '"),"')",sep="")
query_expression_text <- paste("select * from ",df," where row_names in ",query_text," order by row_names",sep="")
selected_df = dbGetQuery(db, query_expression_text)

My question is whether there's anything equivalent for selecting columns by their names?
If I try this code, where my selected column names are: "col-1T-A_m1" and "col-1T-A_m2":
query_string <- paste("select col-1T-A_m1, col-1T-A_m1 from ", df, sep="")
selected_df  <- dbGetQuery(db, query_string)

I get this error message:
Error in sqliteSendQuery(con, statement, bind.data) : error in statement: unrecognized token: "1T".

A: Assuming you are running raw SQL queries, then you should be able to simply specify the column names you want after SELECT, e.g.
query_string <- paste("select col1, col2, col3 from ", df)
selected_df  <- dbGetQuery(db, query_string)


text:
Q: Minor grid in pgfplot not showing when specifying ticks manualy Firstly I would like a minor tick between every major tick in my pgfplots graph (and minor grids). I wrote minor tick num=1 but it doesn't work. I am not using a logarithmic axis so it is unrelated to other questions.
Secondly, why is the tick label "1" missing for each axis? How do I get that to display?

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}

\begin{axis}[%
footnotesize,
width=4in,
height=4in,
axis equal,
scale only axis,
separate axis lines,
grid=both,
every outer x axis line/.append style={black},
every x tick label/.append style={font=\color{black}},
xmin=0,
xmax=1,
xlabel={X},
every outer y axis line/.append style={black},
every y tick label/.append style={font=\color{black}},
ymin=0,
ymax=1,
ylabel={Y},
minor tick num=1,
xtick={0,0.1,...,1},
ytick={0,0.1,...,1},
axis background/.style={fill=white},
legend style={at={(0.97,0.03)},anchor=south east,legend cell align=left,align=left,fill=white}
]

\end{axis}

\end{tikzpicture}%
\end{document}

A: You could also try
xtick distance=.1,
ytick distance=.1,

instead of xtick={0,0.1,...,1},ytick={0,0.1,...,1},.

Code:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}

\begin{axis}[%
footnotesize,
width=4in,
height=4in,
axis equal,
scale only axis,
separate axis lines,
grid=both,
every outer x axis line/.append style={black},
every x tick label/.append style={font=\color{black}},
xmin=0,
xmax=1,
xlabel={X},
every outer y axis line/.append style={black},
every y tick label/.append style={font=\color{black}},
ymin=0,
ymax=1,
ylabel={Y},
minor tick num=1,
xtick distance=.1,% <-
ytick distance=.1,% <-
axis background/.style={fill=white},
legend style={at={(0.97,0.03)},anchor=south east,legend cell align=left,align=left,fill=white}
]

\end{axis}

\end{tikzpicture}%
\end{document}

A: Setting all the ticks explicitly works:
\documentclass[border=2mm]{standalone}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}

\begin{axis}[%
grid=both,
minor tick num=1,
xtick={0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0},
ytick={0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0},
]

\end{axis}

\end{tikzpicture}%
\end{document}

I would think this is caused by roundoff-errors. You can see easily that 0,0.1,...,1 doesn't create the same sequence if numbers as above with
\documentclass{article}
\usepackage{pgffor}

\begin{document}
\foreach \x in {0,0.1,...,1} {
 \x
}
\end{document}

which outputs

The reason why the 1 tick was missing from both axes is clear. I'm not sure why the minor ticks are missing, it could be because the distances between the major ticks are not all equal, at least the manual states

Minor ticks will be disabled if the major ticks don't have the same distance and they are currently only
  available for linear axes (not for logarithmic ones).


text:
Q: unit test repetition issue Tests are here and they are extremely repetitive, which I would like to change…
     [TestClass]
    public class CompareDataTest
    {
private void GenerateTerms(int firstTerm, int secondTerm, out TaughtUnit firstGrade, out TaughtUnit secondGrade)
        {
            firstGrade = new TaughtUnit("foo");
            secondGrade = new TaughtUnit("bar");
        }

        [TestMethod]
        public void CompareResultsTest1()
        {
            var firstGrade = new TaughtUnit("foo");
            firstGrade.Percentage.Add("GRADE", 38);
            var secondGrade = new TaughtUnit("foo");
            secondGrade.Percentage.Add("GRADE", 70);
            var oldTerm = new List<TaughtUnit>() { firstGrade };
            var newTerm = new List<TaughtUnit>() { secondGrade };
            var rankBefore = firstGrade.Percentage;
            var rankNow = secondGrade.Percentage;
            var messages = Program.CompareData(oldTerm, newTerm);

            Assert.AreEqual(0, messages.Count);
        }

        [TestMethod]
        public void CompareResultsTest2()
        {
            var firstGrade = new TaughtUnit("foo");
            firstGrade.Percentage.Add("GRADE", 0);
            var secondGrade = new TaughtUnit("foo");
            secondGrade.Percentage.Add("GRADE", 35);
            var oldTerm = new List<TaughtUnit>() { firstGrade };
            var newTerm = new List<TaughtUnit>() { secondGrade };
            var rankBefore = firstGrade.Percentage;
            var rankNow = secondGrade.Percentage;
            int gradeOld = 0; int gradeNew = 10;
            var getGradeOld = firstGrade.Percentage.TryGetValue("GRADE", out gradeOld);
            var getGradeNew = secondGrade.Percentage.TryGetValue("GRADE", out gradeNew);
            var difference = gradeNew - gradeOld;

            var messages = Program.CompareData(oldTerm, newTerm);

            Assert.AreEqual(1, messages.Count);
            Assert.AreEqual("foo: GRADE rank has dropped by 30", messages[0]);
        }

I think I should use a private void before the set of tests, but I do not know how…
How do I refer to what is created in private void?

A: Declare those variable at Test class level. Populate the setup variable using private method.
 [TestClass]
public class CompareDataTest
{
    private TaughtUnit firstGrade;
    private TaughtUnit secondGrade;

    private void GenerateTerms(int firstTerm, int secondTerm, out TaughtUnit firstGrade, out TaughtUnit secondGrade)
    {
        firstGrade = new TaughtUnit("foo");
        secondGrade = new TaughtUnit("bar");
    }
    [TestMethod]
    public void CompareResultsTest1()
    {
        GenerateTerms(..., ..., ..)
        firstGrade.Percentage.Add("GRADE", 38);
        secondGrade.Percentage.Add("GRADE", 70);

        // rest of other things you want to set specific to the test.

        Assert.AreEqual(0, messages.Count);
    }
}

A: NUnit Framework has a number of ways to passin a Value Source for your tests.
For example I could test Guid.Parse like so
public static Dictionary<int, string> Datas
    {
        get
        {
            return Enumerable.Range(0, 100) //Lots of numbers
                             .ToDictionary(x => x, x => Guid.NewGuid().ToString());
        }
    }

    [Test]
    public void MultiCacheTest([ValueSource("Datas")] KeyValuePair<int, string> item)
    {
        //ACT ...Yes this tests Guid.Parse 100 times
        var value = Guid.Parse(item.value);

        Assert.AreEqual(item.Value, value.ToString());
    }

The idea would be to pass all the purmutations needed to test all the various paths your unit could take and allow the key of the pair to be the input value of the method, with the value of the pair being the expected result. In your case you might pass in 2 percentage values as the key "0|35" and "foo: GRADE rank has dropped by 30" would be the expected value.


text:
Q: Excel remove timestamp from date and subtract days So I have a column say Date1 which has date in datetime stamp. I want to subtract 10 days from Date1 column and keep in another column say Date2. I only want to subtract ten days from date not from datetime.
How to remove the time stamp. Read many solutions online but could not find for excel
Input table
 Date1
26-03-2000 21:00:00
25-04-2000 00:00:00
21-03-2000 01:00:00
31-03-2000 13:00:00
05-03-2012 12:00:00

Expected output
Date1                    Date2       Date1_no_timestamp
26-03-2000 21:00:00     16-03-2000   26-03-2000
25-04-2000 00:00:00     15-04-2000   25-04-2000
21-03-2000 01:00:00     11-03-2000   21-03-2000
31-03-2000 13:00:00     21-03-2000   31-03-2000
05-03-2012 12:00:00     24-02-2012   05-03-2012   and so on

A: You could use the TEXT() function.
=TEXT(B2, "DD-MM-YYYY")
Alternatively, as the above solution could cause issue based on timezone formatting, you could remove anything past the first space:
=LEFT(B2, FIND(" ",A2,1)-1)
Place either the following in C2 (assuming those headers exist) and drag down.

A: You could use:
Method 1:

*

*Date1_no_timestamp:

=TEXT(A2,"dd-mm-yyyy")

*

*Date2:

=TEXT(A2-10,"dd-mm-yyyy")
Method 2

*

*Date1_no_timestamp:

=RIGHT("0"&DAY(A2),2)&"-"&RIGHT("0"&MONTH(A2),2) & "-" & YEAR(A2)

*

*Date2:

=TEXT(DATEVALUE(E2)-10,"dd-mm-yyyy")
Results:

A: You can also use the INT() and TRUNC() functions:
=INT(A2)
=TRUNC(A2)
Their behavior is identical for positive numbers - the decimal part is sliced off.


text:
Q: Wrap javascript text by a certain amount of words I have some string text that I get from an API. I am displaying it in an outlook-addin which is just html, javascript and css.
I am putting the string of text in a panel window which is small. I have been trying to wrap the text using css or javascript but so far no luck.
Here is the code:
Javascript:
 for (let i = 0; i < data.length; i++) {
        let text = "Subject: " + JSON.stringify(data[i].subject) + "
"+
        "CC Emails: " + JSON.stringify(data[i].cc_emails).replace("[]","No Emails are CC'd").replace("[","").replace("]","") + "
" +
        "Ticket Creation Date: " + JSON.stringify(data[i].created_at) + "
" +
        "Ticket Status: " + JSON.stringify(data[i].status).replace("2", "Open").replace("3", "Pending").replace("4", "Resolved").replace("5", "Closed").replace("6", "Waiting On Customer") ;
        let pre = document.createElement('pre');

        pre.innerHTML = text;
        pre.style.cssText += 'font-size:24px;font-weight:bold;width:30px'

        output.appendChild(pre);

html:

    <button style="margin:1px;" id="get-freshdesk" class="ms-Button ms-Button--primary">
      Freshdesk Tickets
    </button>

    <button class="ms-Panel-closeButton ms-PanelAction-close">

    </button>

Freshdesk Integration

        Latest Ticket information

Yet the text still keeps getting cut off:

I also tried changing the ms-Panel-headerText to pre in the css style section but no luck.
Any ideas are appreciated.
Thanks

A: As mentioned in my comment.
When you look at the documentation about the pre element on MDN Web Docs, it states:

"The  HTML element represents preformatted text which is to be
presented exactly as written in the HTML file. "

source
So try any other (inline-)block element and it should work.

A: Pre displays text just as it is in your code file so no word-wrap is applied.
However this seems to work if you really want it to be wrapped in pre tags.

    The purpose of lorem ipsum is to create a natural looking block of text (sentence, paragraph, page, etc.) that doesn't distract from the layout.


text:
Q: mysql result into php array I'm trying to convert the result that i'm getting from mysql to a php array
can anyone helps me
<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "women";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $id=$_GET['id'];
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS,
                   DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`))AS DAYS
           FROM normalW
           where id = '$id'";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        foreach($new_array as $array){
            echo $row['DAYS'].'
';
            echo $row['MONTHS'].'
';
        }
    } else {
        echo "0 results";
}
$conn->close();
?>

Problem solved Thank you guys

A: To answer your question you must first declare the new array
$new_array = array();
Then loop through your query results to populated the array
while ($row = $result->fetch()) {
  $new_array[] = $row;
}

But as one of the comments mentioned you really should be using prepared statements to protect yourself from sql injection.
    $stmt = $mysqli->prepare("SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS, DAY(ADDDATE(ADDDATE(`dateDebutC`,  `dureeC`),`dureeR`)) AS DAYS FROM normalW where id = ?");

    /* bind parameters i means integer type */
    $stmt->bind_param("i", $id);

    $stmt->execute();

    $new_array = array();

    while($row = $stmt->fetch()) {
        $new_array[] = $row;
    }


text:
Q: TabelView Cells are shaking when giving corner radius? My requirement is to display circular images in table view cells. For that purpose in cell for row i gave corner radius for outlet of my imageview now image is displaying in circular format but when scrolling cells are shaking if i stop the corner radius code working fine can any one tell me the issue?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *cellIdentifier =@"notification";

    NotifiucationTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[NotifiucationTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }

    ZSAnnotation *objArray = [personDetails objectAtIndex:indexPath.row];
    [cell.profilePic sd_setImageWithURL:[NSURL URLWithString:objArray.personImage]
                       placeholderImage:[UIImage imageNamed:@"profile-pic-big.png"]];

    cell.personDescription.text = objArray.personDescription;
    cell.personTitle.text = objArray.personTitle;
    myString =  [[NSNumber numberWithFloat:objArray.rating] stringValue];
    km = [NSString stringWithFormat:@"%@%@", myString, @" KM"];

    cell.personNearbyDistance.text = km;
    [cell.callButton addTarget:self action:@selector(callButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    cell.profilePic.layer.cornerRadius = 30;

    return cell;
}

A: try to put the cell UI settings in the cell class's "awakeFromNib" method, like:
- (void)awakeFromNib{
    self.imageView.layer.cornerRadius = 30;
}

because UITableViewCell is always reused, if you try to update cell's UI in "cellForRowAtIndexPath" method, the code is executed every time before a cell is displayed, but if you put the code in "awakeFromNib", the code may only executed a few times when the tableView is loading and won't execute again when you scroll up and down, and cells appears smoothly.

A: I think you can give the corner radius inside the cell itself.
The reason why the cells are flickering is because the tableView tries to deque the cell when the table view is scrolled inside cellForItemAtIndexPath method which causes the cell to flicker.
you can do like this in awake from nib
-(void) awakwFromNib
{
  self.yourImageView.cornerRadius = 30;
  self.yourImageView.layer.maskToBounds = YES;
}

A: Try replacing
cell.profilePic.layer.cornerRadius = 30;

with
if (cell.profilePic.layer.cornerRadius != 30){
    cell.profilePic.layer.cornerRadius = 30;
    cell.profilePic.clipsToBounds = YES;
}

that way, the radius will be applied only once when creating the cell.


text:
Q: Input button image color How to set the color images in a snap? I can not find the property of how this can be done.
There is a button in which there is a picture.
.button {
        background: url('../image/arrow.png') 189px no-repeat; /* картинка */
        background-color: #ff5c36; /* цвет кнопке*/
        color:  #ffffff; /* цвет текста в кнопке*/
        width: 100px;
    }

<input class="button" type="button" value="Send">

I don't understand how to add image in code.

A: You have defined 189px which is taking backgound-position.
The css rule for background
background: background-color background-image background-repeat background-attachment background-position;

There is not inline property for background-size. Because background-size was introduced late in css3.
So you can define with background-position / background-size.
background: background-color background-image background-repeat background-attachment background-position/background-size;

Or it's better to use: background-size below after background property.
background: background-color background-image background-repeat background-attachment background-position;
background-size: width height; // Yes in background-size first one is width and 2nd is height

example:
background: url('image.png') no-repeat right center/14px;

or
background: url('image.png') no-repeat;
background-position: right center;
background-size:14px;

.button {
        background: url('https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-right-b-128.png') no-repeat right center/14px;
        background-color: #ff5c36; /* цвет кнопке*/
        color:  #ffffff; /* цвет текста в кнопке*/
        width: 100px;
    }
<input class="button" type="button" value="Send">


text:
Q: Error opening Serial Port - Arduino I try to upload arduino code to an Arduino Mega. The serial port is detected the first time I plug in the board. As soon as I upload, I get an error saying 'Error opening Serial Port '. And then the Serial Port option is not available for some time. The error repeats the next time I try to upload.
Binary sketch size: 1,500 bytes (of a 258,048 byte maximum)
processing.app.SerialException: Error opening serial port    '/dev/ttyACM0'.
at processing.app.Serial.<init>(Serial.java:178)
at processing.app.Serial.<init>(Serial.java:77)
at processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:77)
at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:175)
at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)
at processing.app.Sketch.upload(Sketch.java:1671)
at processing.app.Sketch.exportApplet(Sketch.java:1627)
at processing.app.Sketch.exportApplet(Sketch.java:1599)
at processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)
at java.lang.Thread.run(Thread.java:745)
Caused by: gnu.io.UnsupportedCommOperationException: Invalid Parameter
at gnu.io.RXTXPort.setSerialPortParams(RXTXPort.java:213)
at processing.app.Serial.<init>(Serial.java:163)
  ... 9 more
processing.app.debug.RunnerException: Error opening serial port '/dev/ttyACM0'.
at processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:101)
at      processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:175)
at
processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)
at processing.app.Sketch.upload(Sketch.java:1671)
at processing.app.Sketch.exportApplet(Sketch.java:1627)
at processing.app.Sketch.exportApplet(Sketch.java:1599)
at processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)
at java.lang.Thread.run(Thread.java:745)

A: To solve that I added myself to the group that owns the port device (the dialup or dialout group from memory). Either that or make the port device world writable.

A: It may be Mega may not be at the serial port /dev/ttyACM0: at first, check that the port is correct.
If port number is correct then maybe serial does not have permissions to be opened in user mode. Try adjusting that by typing
sudo chmod a+rw /dev/ttyACM0

on the terminal (open it by Ctrl+Alt+T).


text:
Q: Strategy for Sorting "Recently Online" Lists when Data Changes Continuously (PHP) We have run into an interesting challenge when it comes to creating paged lists for a "members recently online" app view. The source of the challenge stems from paging on data that updates regularly.
When a member launches the view in the application it's easy to get a list in a given location (by most recent login order in New York for instance) with a simple call to the database. This works perfectly for the first set (page 1). However, when the member scrolls and the app requests the next set (page 2) the list may have new members added to the top of it, this causes overlaps between result set 1 and 2 and so on.
To complicate things a little more, we want to store accountID's from the results in Redis to prevent unnecessary duplicate MySQL queries hitting the DB and helps speed things up.
We considered using timestamps as a starting point. This strategy gives us a set point in time ensuring our list is always returned in order until the members does a pull to refresh list. The problem with this solution though means the DB gets hit every time and Redis can't be used effectively.
Furthermore, a member may have their app on the "recently online" view, leave the app and come back 30 minutes later and continue scrolling from where they were which will surely lead to unexpected results.
Does anyone have a good solution or strategy that solves this kind of a problem without creating a wonky user experience and unnecessary taxation on server resources?

A: We have landed on strategy to handle this challenge that solves most of what we are trying to accomplish. To solve this problem we are implementing the following.
When a member requests "Who's Recently Online" We generate a list of local members capped to 150 accounts. The entire list is passed to the app in a comma delimited string of member ID's so that the app has a set of records that it can page through. This solves the problem of relying on the API to have knowledge of where a member is in a list at any given time.
With the initial request we also include the member information for the first 15 most recently logged in accounts so that the screen can populate without having to make a second call to the API. Since we have passed a complete snapshot of the online now list, the app can request the next set of 15 accounts by passing their ID's to our API to return those account details.
When the member does a pull to refresh or leaves the list and returns to it after moving to another area of the app, the process starts all over again.
This is how we have been able to solve the paging problem. Essentially give the app a snapshot in time and let it page through that snapshot until it's time to update/renew the list.


text:
Q: Android: UI not refreshing with data binding on MutableSet MutableLiveData Here's my XML:
android:textColor="@{viewModel.daysSet.contains(viewModel.days.mon) ? @color/selectedText : @color/black }"

View Model:
val daysSet = MutableLiveData<MutableSet<Days.Day>>().apply {
        value = HashSet<Days.Day>()
    }

Whenever daysSet gets changed, the UI does not change. I've also done
binding.setLifecycleOwner(viewLifecycleOwner)

Adding to the set:
fun evalDaySet(day: Days.Day):String {
        val daysSet = daysSet.value
        testText.value=true
        if (!daysSet!!.contains(day)) {
            daysSet.add(day)
            return "Add"
        } else {
            daysSet.remove(day)
            return "Remove"
        }
    }

It just doesn't refresh. However, the set is definitely adding and it sets the color when the view is recreated. The binding is not being notified of a change.
It seems to be a problem with MutableSet. Is there another data structure that works for this goal? Do Maps accomplish this goal?
It says they are "supported" here:
https://developer.android.com/topic/libraries/data-binding/expressions#collections


text:
Q: how to create a preview version of a multi-page pdf in carrierwave? In carrierwave (1.2.1) using MiniMagick, a simple "process convert: png" will convert a spreadsheet, word doc, or single page pdf into a png file.  However, the whole thing chokes when processing a multi-page pdf.  I wish MiniMagick made some assumptions and automatically converted page 1.  This seems like a fairly common usage...and, yet there seem to be many ideas on how to do it...and, none of them seem to work.  ImageMagick seems to have better support for this.  But, alas...I am using MiniMagick.  Back in carrierwave 0.11.2 (not sure what version of MiniMagick), a multi-page PDF would assume page 1...and, create a preview png using this same version code.  Not anymore.
version :large do
  process convert: 'png'
  process :set_png_content_type
  process resize_to_limit: [1024, 1024]
  def full_filename(for_file = model.receipt.file)
    super.chomp(File.extname(super)) + '_large' + '.png'
  end
end

The code above will successfully convert a single-page PDF named "my_pdf_file.pdf" into a png version named "my_pdf_file_large.png"
However, that version will fail if the pdf supplied is multi-page.
Partial stack trace:
Validation failed: Asset Failed to manipulate with MiniMagick, maybe it is not an image?
Original Error: `identify /Users/secret/Sites/secret/tmp/1514239240-67574-0020-1237/large/agency_card.png`
failed with error: identify: improper image header `/Users/secret/Sites/secret/tmp/1514239240-67574-0020-1237/large/agency_card.png' @ error/png.c/ReadPNGImage/4227.

The error "improper image header" occurs (per reliable sources) when the image isn't found.  In this case I'm assuming it isn't being found in the cache (tmp directory)?
- - - - - - - - - - - -
If I change the version to this:
version :large do
  process convert: 'jpg'
  process :set_jpg_content_type
  process resize_to_limit: [1024, 1024]
  def full_filename(for_file = model.receipt.file)
    super.chomp(File.extname(super)) + '_large' + '.jpg'
  end
end

I get a different error:
 Validation failed: Asset Failed to manipulate with MiniMagick, maybe it is not an image?
 Original Error: `identify /Users/secret/Sites/secret/tmp/1514240098-67574-0022-1346/large/agency_card.jpg`
 failed with error: identify: insufficient image data in file `/Users/secret/Sites/secret/tmp/1514240098-67574-0022-1346/large/agency_card.jpg' @ error/jpeg.c/ReadJPEGImage/1069.

So, my question is this:  why is there not a uniformed way (baked in to MiniMagick preferably) to handle converting multi-page PDF documents.  Some people want to convert each page of the PDF, while others just want the first page.  This feels like magic...and, it should be easy.
Is there a smart, simple way to accomplish this using MiniMagick?
Rails 5.1.4
Carrierwave 1.2.1
Ghostscript
Heroku
Ruby 2.4.3
MiniMagick
- - - - - UPDATE - - - - -
The error "improper image header" indicates that the image can't be found.  The path in the error message:
 `/Users/secret/Sites/secret/tmp/1514240098-67574-0022-1346/large/agency_card.jpg'

but, should actually be (and, the image does actually exist here):
 `/Users/secret/Sites/secret/tmp/uploads/1514240098-67574-0022-1346/agency_card.jpg'

my carrierwave config does set config.cache_dir = "#{ Rails.root }/tmp/uploads"...which is not being used when the image is retrieved from cache (tmp).  And, I'm not sure where the version name in the path comes from...but, no subdirectories exist in my tmp directory named for the version name.


text:
Q: How can I tell robot framework not to log a keyword? In a robot framework test case I set a variable and then do a process.
Because the setting of the variable is not a very interesting bit of information, I don't want to include that in my report.
| Verifying STUFF  |
| | ${endpoint}=    | set variable | STUFF
| | Verify

My report contains this:
KEYWORD: ${endpoint} = BuiltIn.Set Variable STUFF

But I would rather not have it there.  How can I tell Robot Framework to just not log that line?
------edit------
It looks like this should do it:
pybot --removekeywords NAME:SetVariable testcase.txt

But the Set Variable keywords are still there.
(And yes, I upgraded my robot framework to 2.8.3 to take advantage of this function.)

A: The best you can do is to use
Set Log Level    NONE

but it will still log all the keyword calls, just not anything inside those.
Or if you call a python function which calls another function, then the call to the second function is not logged.
Like this:
*** Settings ***
Library           lib.py

*** Test Cases ***
demo
    Set Log Level    NONE
    ${a}    foo
    xyzzy

*** Keywords ***
xyzzy
    qwerty

qwerty
    No Operation
    Log    123

and lib.py being like this:
def foo():
    abc = bar()
    return abc

def bar():
    c = 1
    print c
    return c

A: The problem is that when you assign a variable like ${var} =    Keyword, the name of the keyword in Robot Framework outputs is ${var} = Keyword, not Keyword as you would expect. If your keyword is from a library or a resource file, its name will also be included like ${var} = MyLibrary.Keyword. The latter is a feature but the former is a bug that is hopefully fixed in RF 2.9.
An easy workaround for the keyword name, for now, including the variable name is using wildcards. Something like this ought to work for you:
--RemoveKeywords 'name:* = BuiltIn.Set Variable'

A: You can use --removekeywords or --flattenkeywords option on pybot to remove the content of keyword So if you have e.g. keyword "foo" that contains lot's of logging keywords, you can set "--flattenkeywords name:foo" option to pybot, and In the log you'll only see the primary keyword, but no keywords inside it.
http://robotframework.googlecode.com/hg/doc/userguide/RobotFrameworkUserGuide.html?r=2.8.3#removing-and-flattening-keywords

A: If you use a python library, the following monkey-patching works for me:
from robot.libraries.BuiltIn import BuiltIn
from robot.output.logger import LOGGER
import types

def _nothing(*args, **kwargs):
    pass

def disable_keyword_logging(self):
    self._logging_methods = (LOGGER.start_keyword, LOGGER.end_keyword)
    LOGGER.start_keyword = types.MethodType(_nothing,LOGGER)
    LOGGER.end_keyword = types.MethodType(_nothing,LOGGER)

def enable_keyword_logging(self):
    LOGGER.start_keyword, LOGGER.end_keyword = self._logging_methods

Then when this script is run:
Disable keyword logging
Log    Hello world
Enable keyword logging

the "Log" keyword is not logged to the output but the output is.
If you really want nothing (also no debug/info/warn information logged by the called keywords), you will still have to set the log level to "NONE".

A: Robot Framework doesn't log "global" variables as part of a variable table. Global is in quotation marks because Set Global Variable actually is logged, but if you initialize your variable like so...
*** Variables ***
${endpoint}     stuff

*** Keywords ***

...then it will not be in the Log. Additionally, if you don't want anyone to see the variable at all if they're just looking at the front end of your testing suite, you can bury it in a Resource file and the call the Resource file.
Robot Framework logs your Set Variable keywords and results because Set Variable implies that you're setting a variable dynamically and might be setting it based on the result of a keyword, in which case you'd probably want to know what the result of the keyword is. If you're just creating a static variable, then no extra work beyond the table is required. Is a dynamic variable a required part of your code?


text:
Q: Limit as x approach to infinity of Log. I'm trying to solve this:
$$\lim_{x\rightarrow+\infty} (x-\ln(1+2e^x))= ?$$
I tried L'Hôpital's rule but it didn't get me where I want to...
Any hints?

A: $x-\ln(1+2e^x)=$
$ \ln (e^x) -\ln(1+2e^x)=$
$\log (\dfrac{e^x}{1+2e^x}).$
Set $y:= e^x$, and consider $y \rightarrow \infty$ :
$f(y) := \dfrac{y}{1+2y} = \dfrac{1}{1/y +2}.$
$\lim_{y \rightarrow \infty} (\log f(y)) =$
$\log( \lim_{y \rightarrow \infty} f(y)) =$
$=\log(1/2)= -\log 2$.
Used:
1) $\lim_{y \rightarrow \infty} f(y) = 1/2;$
2) $\log$ is continuous.

A: Note that
$$x-\ln(1+2e^x)=x-\left[\ln e^x+\ln \left(\frac1{e^x}+2\right)\right]=x-x-\ln \left(\frac1{e^x}+2\right)\to -\ln 2$$
To figure out at first sight the result note that for $x\to +\infty$

*

*$\ln(1+2e^x)\sim \ln 2e^x=\ln2+\ln e^x=\ln 2 +x$

observe that the latter is not a proof but only a method to guess what the limit could be.

A: use that $$\ln(1+2e^x)=\ln\left(e^x\left(\frac{1}{e^x}+2\right)\right)=x+\ln\left(\frac{1}{e^x}+2\right)$$


text:
Q: intelliSense 'No members available' using inheritence and generic in c++ ,this problem appeared to me:
this is my abstract base class
    template<class Type>
struct A
{
Type info;
};
template<class Type>
class base
{
protected:
     A<Type>* ptrA;
public:
    virtual void func(Type X) = 0;
    void func(Type X)
     {
         ptrA->info = x;         //no Errors occured
     }
};

and this is the derived
template<class Type>
class derived : class base<Type>
{
public:
  void func(Type X)
  {
    ptrA-> info  = x ;       // this is the problem

  }
};

the problem appeared to me at the function definition of the derived class : that i cannot access the
member that ptrA refrenced ,,, any help ,please


text:
Q: Counting number of occurrences on the whole Pandas DataFrame My dataset has this structure
A = [A1, A2, A3, A4]
B = [B1, B2, B3]
C = [C1, C2, C3, C4, C5]

I want to count the occurrences of all variables in my dataset, such as:
A1    3
A2    2
A3    1
...
C4    4
C5    5

I have tried
df.groupby(df.columns[0]).A.count()

but it only works column by column, is there any way to count occurrences for the whole dataset at once?
Thank you.

A: You can use stack the value_counts
df.stack().value_counts()
Out[1298]:
4    2
3    2
2    2
5    1
1    1
dtype: int64

Data input
df=pd.DataFrame({'A':[1,2,3,4],'B':[2,3,4,5]})

A: pd.value_counts(df.values.ravel())

A: You can use apply with count on axis = 1
>>> df=pd.DataFrame({'A':[1,2,3,4],'B':[2,3,4,5]})
>>> df.apply(pd.value_counts).count(axis=1)

Outputs
1    1
2    2
3    2
4    2
5    1
dtype: int64


text:
Q: How can I capture screen (in video format) in HTML 5? I want to capture the screen (or all the actions done in a canvas). I require this in video format and do not want a screenshot but a video of all actions done on the screen over a period of time.
I want to implement this functionality in HTML5.
Please advise. Also if this is not possible in HTML5, please suggest alternative technology for this?

A: If I'm understanding right, you want to save a canvas with an interval of x ms. That part's easy.
Note that you 're not clear in your question. Do you want to capture the screen, the complete document or a single canvas?
Second part do you want to render it as a 'video like' component using javascript? Or do you want to save it as a video. The first idea is possible. De second one not so much. At least not using javascript. You could send all images to a backend (like php, asp, jsp) and create a video on the server side using tools like ffmpeg. More info

A: HTML5 doesn't offer camera capabilities.
But, there's a jQuery Plugin that offers just that using a small flash utility..


text:
Q: ReplicaFailure set to FailedCreate while creating bookinfo sample with istio I have installed istio 1.5.4 version. I am trying to deploy the bookinfo app using the command - kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml
service/details created
serviceaccount/bookinfo-details created
deployment.apps/details-v1 created
service/ratings created
serviceaccount/bookinfo-ratings created
deployment.apps/ratings-v1 created
service/reviews created
serviceaccount/bookinfo-reviews created
deployment.apps/reviews-v1 created
deployment.apps/reviews-v2 created
deployment.apps/reviews-v3 created
service/productpage created
serviceaccount/bookinfo-productpage created
deployment.apps/productpage-v1 created

-bash-4.2$ kubectl get services
NAME          TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
details       ClusterIP   10.108.221.161   <none>        9080/TCP   9s
kubernetes    ClusterIP   10.96.0.1        <none>        443/TCP    35d
productpage   ClusterIP   10.106.237.68    <none>        9080/TCP   9s
ratings       ClusterIP   10.96.155.198    <none>        9080/TCP   9s
reviews       ClusterIP   10.107.119.19    <none>        9080/TCP   9s
-bash-4.2$ kubectl get pods
No resources found in default namespace.

Pod is not getting created.
-bash-4.2$ kubectl get all
NAME                  TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
service/details       ClusterIP   10.108.221.161   <none>        9080/TCP   107s
service/kubernetes    ClusterIP   10.96.0.1        <none>        443/TCP    35d
service/productpage   ClusterIP   10.106.237.68    <none>        9080/TCP   107s
service/ratings       ClusterIP   10.96.155.198    <none>        9080/TCP   107s
service/reviews       ClusterIP   10.107.119.19    <none>        9080/TCP   107s

NAME                             READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/details-v1       0/1     0            0           107s
deployment.apps/productpage-v1   0/1     0            0           107s
deployment.apps/ratings-v1       0/1     0            0           107s
deployment.apps/reviews-v1       0/1     0            0           107s
deployment.apps/reviews-v2       0/1     0            0           107s
deployment.apps/reviews-v3       0/1     0            0           107s

NAME                                        DESIRED   CURRENT   READY   AGE
replicaset.apps/details-v1-78d78fbddf       1         0         0       107s
replicaset.apps/productpage-v1-85b9bf9cd7   1         0         0       107s
replicaset.apps/ratings-v1-6c9dbf6b45       1         0         0       107s
replicaset.apps/reviews-v1-564b97f875       1         0         0       107s
replicaset.apps/reviews-v2-568c7c9d8f       1         0         0       107s
replicaset.apps/reviews-v3-67b4988599       1         0         0       107s

-bash-4.2$ kubectl describe deployment.apps/reviews-v1
Name:                   reviews-v1
Namespace:              default
CreationTimestamp:      Thu, 06 Aug 2020 07:04:25 -0400
Labels:                 app=reviews
                        version=v1
Annotations:            deployment.kubernetes.io/revision: 1
                        kubectl.kubernetes.io/last-applied-configuration:
                          {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"labels":{"app":"reviews","version":"v1"},"name":"reviews-v1","na...
Selector:               app=reviews,version=v1
Replicas:               1 desired | 0 updated | 0 total | 0 available | 1 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:           app=reviews
                    version=v1
  Service Account:  bookinfo-reviews
  Containers:
   reviews:
    Image:      docker.io/istio/examples-bookinfo-reviews-v1:1.15.0
    Port:       9080/TCP
    Host Port:  0/TCP
    Environment:
      LOG_DIR:  /tmp/logs
    Mounts:
      /opt/ibm/wlp/output from wlp-output (rw)
      /tmp from tmp (rw)
  Volumes:
   wlp-output:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
   tmp:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
Conditions:
  Type             Status  Reason
  ----             ------  ------
  Progressing      True    NewReplicaSetCreated
  Available        False   MinimumReplicasUnavailable
  ReplicaFailure   True    FailedCreate
OldReplicaSets:    reviews-v1-564b97f875 (0/1 replicas created)
NewReplicaSet:     <none>
Events:
  Type    Reason             Age    From                   Message
  ----    ------             ----   ----                   -------
  Normal  ScalingReplicaSet  5m54s  deployment-controller  Scaled up replica set reviews-v1-564b97f875 to 1

I am getting ReplicaFailure set to FailedCreate
I tried increasing the progressDeadLineSeconds as mentioned in another thread but still I am getting the same issue.
-bash-4.2$ kubectl patch deployment.apps/reviews-v1 -p '{"spec":{"progressDeadlineSeconds":6000}}'
deployment.apps/reviews-v1 patched
-bash-4.2$ kubectl get pods
No resources found in default namespace.

Pods are not getting created. Any idea what could have gone wrong?
-bash-4.2$ kubectl get events
LAST SEEN   TYPE      REASON              OBJECT                                 MESSAGE
4m32s       Warning   FailedCreate        replicaset/details-v1-78d78fbddf       Error creating: Internal error occurred: failed calling webhook "sidecar-injector.istio.io": Post https://istio-sidecar-injector.istio-system.svc:443/inject?timeout=30s: x509: certificate signed by unknown authority
59m         Normal    ScalingReplicaSet   deployment/details-v1                  Scaled up replica set details-v1-78d78fbddf to 1
4m32s       Warning   FailedCreate        replicaset/productpage-v1-85b9bf9cd7   Error creating: Internal error occurred: failed calling webhook "sidecar-injector.istio.io": Post https://istio-sidecar-injector.istio-system.svc:443/inject?timeout=30s: x509: certificate signed by unknown authority
59m         Normal    ScalingReplicaSet   deployment/productpage-v1              Scaled up replica set productpage-v1-85b9bf9cd7 to 1
4m32s       Warning   FailedCreate        replicaset/ratings-v1-6c9dbf6b45       Error creating: Internal error occurred: failed calling webhook "sidecar-injector.istio.io": Post https://istio-sidecar-injector.istio-system.svc:443/inject?timeout=30s: x509: certificate signed by unknown authority
59m         Normal    ScalingReplicaSet   deployment/ratings-v1                  Scaled up replica set ratings-v1-6c9dbf6b45 to 1
4m31s       Warning   FailedCreate        replicaset/reviews-v1-564b97f875       Error creating: Internal error occurred: failed calling webhook "sidecar-injector.istio.io": Post https://istio-sidecar-injector.istio-system.svc:443/inject?timeout=30s: x509: certificate signed by unknown authority
59m         Normal    ScalingReplicaSet   deployment/reviews-v1                  Scaled up replica set reviews-v1-564b97f875 to 1
4m32s       Warning   FailedCreate        replicaset/reviews-v2-568c7c9d8f       Error creating: Internal error occurred: failed calling webhook "sidecar-injector.istio.io": Post https://istio-sidecar-injector.istio-system.svc:443/inject?timeout=30s: x509: certificate signed by unknown authority
59m         Normal    ScalingReplicaSet   deployment/reviews-v2                  Scaled up replica set reviews-v2-568c7c9d8f to 1
4m34s       Warning   FailedCreate        replicaset/reviews-v3-67b4988599       Error creating: Internal error occurred: failed calling webhook "sidecar-injector.istio.io": Post https://istio-sidecar-injector.istio-system.svc:443/inject?timeout=30s: x509: certificate signed by unknown authority
59m         Normal    ScalingReplicaSet   deployment/reviews-v3                  Scaled up replica set reviews-v3-67b4988599 to 1
-bash-4.2$ kubectl describe rs replicasetname
Error from server (NotFound): replicasets.extensions "replicasetname" not found

A: From the docs here

x509: certificate signed by unknown authority errors are typically
caused by an empty caBundle in the webhook configuration

Verify the caBundle in the mutatingwebhookconfiguration matches the root certificate mounted in the istiod pod.
$ kubectl get mutatingwebhookconfiguration istio-sidecar-injector -o yaml -o jsonpath='{.webhooks[0].clientConfig.caBundle}' | md5sum
4b95d2ba22ce8971c7c92084da31faf0  -
$ kubectl -n istio-system get secret istiod-service-account-token -o jsonpath='{.data.root-cert\.pem}' | md5sum
4b95d2ba22ce8971c7c92084da31faf0  -

The CA certificate should match. If they do not, restart the istiod pods.
$ kubectl -n istio-system patch deployment istiod \
    -p "{\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"`date +'%s'`\"}}}}}"
deployment.extensions "istiod" patched

A: I have the same issue :
[root@bio DimetisOrchestrator]# kubectl get mutatingwebhookconfiguration istio-sidecar-injector -o yaml -o jsonpath='{.webhooks[0].clientConfig.caBundle}' | md5sum
917d9c9007d2cd128b91c0005ac3fa84  -
[root@bio DimetisOrchestrator]# kubectl -n istio-system get secret istiod-service-account-token -o jsonpath='{.data.root-cert.pem}' | md5sum
Error from server (NotFound): secrets "istiod-service-account-token" not found
d41d8cd98f00b204e9800998ecf8427e  -
The certificates do not match even after restarting istiod
[root@bio DimetisOrchestrator]#
[root@bio DimetisOrchestrator]# kubectl get deployment -n istio-system istiod
NAME     READY   UP-TO-DATE   AVAILABLE   AGE
istiod   1/1     1            1           16h


text:
Q: CoreLocation can't use with Estimotes Beacon I build a app with Estimotes indoor Location ,any I use CoreLocation to find our beacon, and my app will change label.text. App can run,but didn't work ,label.text can't change.
   override func viewDidLoad() {
   super.viewDidLoad()

    let path = NSBundle.mainBundle().pathForResource("location", ofType: "json")
    do {
    let content = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)

    let locationSetup = ESTLocationBuilder.parseFromJSON(content)

    //set up delegate
    manager.delegate = self
    locationManager.delegate = self
 if (CLLocationManager.authorizationStatus() !=  CLAuthorizationStatus.AuthorizedWhenInUse) {
        locationManager.requestWhenInUseAuthorization()
    }
    locationManager.startRangingBeaconsInRegion(region)
}
  func locationManager(manager: CLLocationManager, didRangeBeacons beacons:[CLBeacon], inRegion region: CLBeaconRegion){

    let knownBeacons = beacons.filter{ $0.proximity != CLProximity.Unknown }
    if (knownBeacons.count > 0){
        let closestBeacon = knownBeacons[0] as CLBeacon
        if(closestBeacon.minor.integerValue == 41016)
        {
            self.snow.text = "find"
        }
    }
}

A: First thing to try:
I would move the initialization of locationManger = CLLocationManager() outside the class instance declaration and inside viewDidLoad.    I have seen problems initializing the location manager during object construction.


text:
Q: How to know which library a specific function is defined in? [root@xxx memcached-1.4.5]# objdump -R memcached-debug |grep freeaddrinfo
0000000000629e10 R_X86_64_JUMP_SLOT  freeaddrinfo

...
(gdb) disas freeaddrinfo
Dump of assembler code for function freeaddrinfo:
0x00000037aa4baf10 <freeaddrinfo+0>:    push   %rbp
0x00000037aa4baf11 <freeaddrinfo+1>:    push   %rbx
0x00000037aa4baf12 <freeaddrinfo+2>:    mov    %rdi,%rbx

So I know freeaddrinfo is a dynamically linked function,but how to know which .so it's defined in?

A: See this answer. The info symbol freeadrinfo is one way to find out.
On Linux and Solaris you can also use ldd and LD_DEBUG=symbols. For example, if you wanted to find out where localtime in /bin/date is coming from:
LD_DEBUG=bindings ldd -r /bin/date 2>&1 |  grep localtime
     26322: binding file /bin/date [0] to /lib/libc.so.6 [0]: normal symbol `localtime' [GLIBC_2.2.5]

A: For certain low version gdb, "info symbol " could not work as you want.
So please use below method:

*

*Run 'p symbol_name' to get symbol address
(gdb) p test_fun
$1 = {<text variable, no debug info>} 0x84bcc4 <test_fun>

*Check /proc/PID/maps to find out the module which the symbol address is in.
# more /proc/23275/maps
007ce000-0085f000 r-xp 00000000 fd:00 3524598    /usr/lib/libtest.so

0x84bcc4 is in [007ce000, 0085f000]

A: Inside the libraries directory you could execute the following command to search for a specific symbol on all libraries:
for file in $(ls -1 *.so); do echo "-------> $file"; nm $file; done | c++filt | grep SYMBOL*

An enhanced version would be to list all libraries that are linked to the executable (through ldd) and go after each library listed searching if the symbol is defined there. Depending on your *nix you might have to tweak the cut parsing:
APP=firefox; for symbol in $(nm -D $APP | grep "U " | cut -b12-); do for library in $(ldd $APP | cut -d ' ' -f3- | cut -d' ' -f1); do for lib_symbol in $(nm -D $library | grep "T " | cut -b12-); do if [ $symbol == $lib_symbol ]; then echo "Found symbol: $symbol at [$library]"; fi ; done; done; done;


text:
Q: Spring Data MongoDB non-existent switch error I am running aggreagaton logic behind one of my services in spring using MongoDB.
aggregation logic looks like following:
MatchOperation dateMatchOperation = Aggregation.match(
    Criteria.
            where("date").
            gte(new Date(startStamp)).lte(new Date(endStamp)));

MatchOperation propertyMatchOperation = Aggregation.match(
    Criteria.
            where("abc1").is(abcVal1)
            .and("abc2").is(abcVal2)
            .and("abc3").is(abcVal3)
            .and("abc4").is(abcVal4)
            .and("abc5").is(abcVal5)
);

List<Date> dates = new ArrayList<>();
//Create appropriate interval arraylist which will be passed to mongo
for (int i = 0; i < (endStamp - startStamp)/aggregationInterval; i ++) {
dates.add(new Date(startStamp + i * aggregationInterval));
}

BucketOperation bucketOperation = Aggregation.bucket("date").withBoundaries(dates.toArray())
    .andOutput(AccumulatorOperators.Sum.sumOf(aggregationInput)).as("value")
    .andOutput(AccumulatorOperators.Min.minOf("date")).as("from")
    .andOutput(AccumulatorOperators.Max.maxOf("date")).as("to");

AggregationOptions aggregationOptions = AggregationOptions.builder().allowDiskUse(true).build();
AggregationResults<MetricAggregationResult> aggregationResults = mongoTemplate.aggregate(
    Aggregation.newAggregation(dateMatchOperation, propertyMatchOperation, bucketOperation)
        .withOptions(aggregationOptions),
    "mongocollectionname",
    MetricAggregationResult.class);

I am testing this on collection with 4.5m documents. When aggregationInterval is small and there are many elements in arraylist it works OK, however at some point, gradually increasing aggregation interval I have noticed that after some point aggregation throws following error :
com.mongodb.MongoCommandException: Command failed with error 40066: '$switch could not find a matching branch for an input, and no default was specified.'

It's strange, because I am not using any $switch aggregations in my logic, as for AggregationOptions, I thought mongo aggregation was hitting it's 100MB limit and I allowed disk usage.
At this point my hands are tied, I don't know what's causing an issue (I searched all over the StackOverflow for $switch error, but I could not find anything since all asking guys had been using $switch in their code at some extent), but I'm pretty confident it's something that mongo side misses.

A: Use BucketAutoOperation

 BucketAutoOperation bucketAutoOperation = Aggregation.bucketAuto("date", 2)
                .andOutput(AccumulatorOperators.Sum.sumOf(aggregationInput)).as("value")
                .andOutput(AccumulatorOperators.Min.minOf("date")).as("from")
                .andOutput(AccumulatorOperators.Max.maxOf("date")).as("to");

A: To use a bucket operation, we specify the following:

groupBy: the field that the boundaries will apply to. This field must be numeric or a date field.
boundaries: an array of boundary points. Documents which have a groupBy field falling between two elements in the array go into that bucket. The between test here is half-open, so the first point is inclusive, second point is exclusive, which is the behavior developers would expect
default: any documents in the pipeline which don't go into one of the buckets will go into default. This is required. Using a match operation in the pipeline before the bucket operation will remove documents which shouldn't be processed.
output: an aggregation expression to generate the output document for each bucket

IN the above code, we missed specifying default.

final BucketOperation bucketOperation = Aggregation.bucket("date").
                withBoundaries(now.minus(10, ChronoUnit.DAYS), now.minus(9, DAYS),
                        now.minus(8, DAYS), now.minus(7, DAYS), now.minus(6, DAYS),
                        now.minus(5, DAYS), now.minus(4, DAYS), now.minus(3, DAYS),
                        now.minus(2, DAYS), now.minus(1, DAYS), now.minus(0, DAYS)).
                withDefaultBucket("defaultBucket").
                andOutput(countingExpression).as("count");

Refer the below link :-
https://chiralsoftware.com/idea/spring-data-aggregation-operations


text:
Q: What is the difference between apiserver-kubelet-client, apiserver and kubelet certificates I am getting confused with all the certificates and keys in Kubernetes.
Inside the master I have the following certificates and keys:
/etc/kubernetes/pki/apiserver.crt
/etc/kubernetes/pki/apiserver.key

/etc/kubernetes/pki/apiserver-kubelet-client.crt
/etc/kubernetes/pki/apiserver-kubelet-client.key

/var/lib/kubelet/pki/kubelet.crt
/var/lib/kubelet/pki/kubelet.key

The apiserver-kubelet-client (crt\key) is used for secure communication between the apiserver and the kubelet inside the Master.
Why I have also the kubelet (crt\key)? Isn't the apiserver-kubelet-client (crt\key) is enough ?
Why I need apiserver (crt\key) if I have apiserver-kubelet-client (crt\key)  ?
Hope someone can make some order with this.
I read this article about Kubernetes PKI but I am still don't understand what is difference between the above certificates and keys.

A: While preparing certs, you will end up with at least 1 file.

*

*CA_CERT

*

*put in on node where apiserver runs, for example in /srv/kubernetes/ca.crt.

*MASTER_CERT

*

*signed by CA_CERT

*put in on node where apiserver runs, for example in /srv/kubernetes/server.crt

*MASTER_KEY

*

*put in on node where apiserver runs, for example in /srv/kubernetes/server.key

You can read about it in Kubernetes docs here.
It's hard to say by the names of your certs what are they used for.
You should refer to the standard configuration.
Besides, you can have a look at kelseyhightower/kubernetes-the-hard-way as he's showing how and when to use certificates.
You can check this comment posted on Github regarding what kind of certifications are needed between which services.

A: I was also asking my self similar question.
The first thing u need to know is that both the kubelet and the api-server communicate with each other [0].
The second thing is that Kubernetes uses client certificates to authenticate a client identity to the server and a server certificate to authenticate the server's identity to the client and establish an encrypted connection .
In case of kubelet -> api-server kubelet needs a client certificate and api-server a server certificate and for api-server -> kubelet then the otherway around.
you can check if a certificate is a server or client one using:
openssl x509  -noout -text -in apiserver.crt

Now back to the question :

*

*/etc/kubernetes/pki/apiserver.crt and /var/lib/kubelet/pki/kubelet.crt are server certificates

*/etc/kubernetes/pki/apiserver-kubelet-client.crt and /var/lib/kubelet/pki/kubelet-client-current.pem are client certificates

*https://kubernetes.io/docs/concepts/architecture/control-plane-node-communication/


text:
Q: How to avoid the ROOT Element when parsing from XML to JSON in C# I am trying to create a JSON from an xml using JSON.NET
XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson); //xmlPerson is the xml from above
JObject personDefinition = JObject.Parse(JsonConvert.SerializeObject(docPerson));
Tasks.personDefinition = personDefinition["personDefinition"];

OUTPUT JSON
"person":{"person":[{"personId":"1","firstName":"Name1","lastName":"lastName1"},                  {"personId":"3","firstName":"Name2","lastName":"lastName2"}]}

I don't need the outer person and just need the following json
REQUIRED JSON
"person":[{"personId":"1","firstName":"1","lastName":"Weight"},{"personId":"3","firstName":"4","lastName":"Pulse Ox"}]}

I have tried using the .first method however it is throwing an error. Can anyone suggest on how to strip the root  from the output json

A: JSON.Net has a SerializeXmlNode() method that can do exactly what you want.  Simply pass true to the omitRootObject parameter.
Observe:
string xmlPerson = @"<PersonDefinition><Person><name>Nicolas</name><age>22</age></Person><Person><name>Pankaj</name><age>25</age></Person></PersonDefinition>";
XmlDocument docPerson = new XmlDocument();
docPerson.LoadXml(xmlPerson);
string json = JsonConvert.SerializeXmlNode(docPerson, Formatting.None, true);
Console.WriteLine(json);

Output:
{"Person":[{"name":"Nicolas","age":"22"},{"name":"Pankaj","age":"25"}]}

A: string xml = "<PersonDefinition><Person><name>Nicolas</name><age>22</age></Person><Person><name>Pankaj</name><age>25</age></Person></PersonDefinition>";

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person[]), new XmlRootAttribute("PersonDefinition"));
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();

using (TextReader reader = new StringReader(xml))
{
    Person[] people = xmlSerializer.Deserialize(reader) as Person[];
    string json = jsonSerializer.Serialize(new Person());
}

Use some kind of variation of this.


text:
Q: Document type does not allow element "span" here? I am working on getting my XHTML validated.
In my page, I have dynamic creation (in JS) of many HTML elements.
For example, I have a for loop that parses an Array that hold value's of a select tag, and then my JS code created the select with the given values. Therefore, my JS contains HTML elements inside quotes (strings). Unfortunately, I cannot get my XHTML validated because the validator things that these guys are actual elements.
How do I avoid this? Is is necessary to avoid this?

A: You'll need to tell the XHTML validator to parse your JavaScript different then the rest of your code. You can do this by using CDATA blocks in your script tags.
Example:
<script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>

For more information for as to why, see the question When is a CDATA section necessary within a script tag?


text:
Q: Simplify javascript password show/hide function I have 3 different password input as:
   --Current Password Input
   <input asp-for="ChangePassword.OldPassword" class="form-control" id="currentPassword"   required autofocus />
   <button class="btn btn-light shadow-none ms-0" type="button" id="toggleCurrentPassword" tabindex="99"></button>

   --New password input
   <input asp-for="ChangePassword.NewPassword" class="form-control" id="newPassword" required autofocus />
   <button class="btn btn-light shadow-none ms-0" type="button" id="toggleNewPassword" tabindex="99"></button>

   --Confirm password input
   <input asp-for="ChangePassword.ConfirmPassword" id="confirmPassword" class="form-control" required autofocus />
   <button class="btn btn-light shadow-none ms-0" type="button" id="toggleConfirmPassword" tabindex="99"></button>

As you can see each one have a button, when user click I remove the type password, and if the user click again I add it again.
My script to do that:
    $('#toggleCurrentPassword').click(function() {
      if ($('#currentPassword').attr('type') === "password") {
        $('#currentPassword').attr('type', 'text');
      } else {
        $('#currentPassword').attr('type', 'password');
      }
    })

  $('#toggleNewPassword').click(function() {
    if ($('#newPassword').attr('type') === "password") {
      $('#newPassword').attr('type', 'text');
    } else {
      $('#newPassword').attr('type', 'password');
    }
  })

  $('#toggleConfirmPassword').click(function() {
      if ($('#confirmPassword').attr('type') === "password") {
        $('#confirmPassword').attr('type', 'text');
      } else {
        $('#confirmPassword').attr('type', 'password');
      }
    })

It is working, but I think it should be a better way to do this, there is a lot of repeated code in function. How can I do a better work here? Regards

A: You could create a function to handle each eventListener:
function passwordToggle(button, input) {
  $(button).click(function() {
    if ($(input).attr('type') === "password") {
      $(input).attr('type', 'text');
    } else {
      $(input).attr('type', 'password');
    }
  })
}

passwordToggle('#toggleCurrentPassword', '#currentPassword');
passwordToggle('#toggleNewPassword', '#newPassword');
passwordToggle('#toggleConfirmPassword', '#confirmPassword');

A: In my opinion, you could simply create a function to be reusable, I think.
Example:

 --Current Password Input

   <input asp-for="ChangePassword.OldPassword" class="form-control" id="currentPassword"   required autofocus />
   <button class="btn btn-light shadow-none ms-0 btn-password-toggle" type="button" id="toggleCurrentPassword" data-input-id="#currentPassword" tabindex="99">Password Toggle</button>

   --New password input

   <input asp-for="ChangePassword.NewPassword" class="form-control" id="newPassword" required autofocus />
   <button class="btn btn-light shadow-none ms-0 btn-password-toggle" type="button" id="toggleNewPassword" data-input-id="#newPassword" tabindex="99">Password Toggle</button>

   --Confirm password input

   <input asp-for="ChangePassword.ConfirmPassword" id="confirmPassword" class="form-control" required autofocus />
   <button class="btn btn-light shadow-none ms-0 btn-password-toggle" type="button" id="toggleConfirmPassword" data-input-id="#confirmPassword" tabindex="99">Password Toggle</button>


text:
Q: How to make a UIButton border flash when touched So far the border flashes when touched to match the text, but the border doesn't revert to white after being pressed. I don't know how to make the border flash while it's being pressed (initiated in an @IBAction function) I believe it has to do with the button's Touch Up Inside sent event.
@IBAction func buttonSearchAction(sender: AnyObject) {

    let myColor : UIColor = UIColor(red: (255/255.0), green: (255/255.0), blue: (255/255.0), alpha: 0.5)
    buttonSearch.layer.borderColor = myColor.CGColor
}

A: [myButton addTarget:self action:@selector(highlightBorder) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(unhighlightBorder) forControlEvents:UIControlEventTouchUpInside];

- (void)unhighlightBorder
{
    myButton.layer.borderColor = [[UIColor greenColor]CGColor];
}

- (void)highlightBorder
{
    myButton.layer.borderColor = [[UIColor blueColor]CGColor];
}

A: Same solution as above written in Swift:
myButton.addTarget(self, action: "unhighlightBorder", forControlEvents: UIControlEvents.TouchDown);

myButton.addTarget(self, action: "highlightBorder", forControlEvents: UIControlEvents.TouchUpInside);

func unhighlightBorder(){
    myButton.layer.borderColor = UIColor.greenColor().CGColor;
}

func highlightBorder(){
    myButton.layer.borderColor = UIColor.blueColor().CGColor;
}


text:
Q: Unit testing never run after setup UI testing Xcode 7 I set up UI testing MyProjectUITests in Xcode 7 and I also added a new unit test in to target MyProjectTests. However, when I typed Command + U, it seems like Xcode always testing my project with UI Testing.
Question: How could I choose to build specifically for UI testing or unit testing if need ?

A: Select your scheme.
Edit scheme ->Test- > Add Unit test with '+' button

To choose to build specifically you can check/uncheck the checkbox under Test.


text:
Q: delwin(),endwin(), not working inside a condiional statement As per logic, the below code must end the window and must return the console window with output of ls but its returning the window with a black background and in that window every command is running but it is not displayed that what i am writing and output is coming in a pretty unusual manner even though i had not used noecho().
else if(selected_item==0){
  wprintw(messagebar,"You have selected menu SHAILENDRA SINGH.",1);
  write_data0();
  if(fork())
    wait(0);
  else
    execlp("clear","clear",(char *)NULL);
  execlp("ls","ls",(char *)NULL);
  execlp("konsole","konsole",(char *)NULL);
  ESCAPE;
  refresh();
  delwin(menubar);
  delwin(messagebar);

  endwin();
}

need help and suggestion in removing this bug in my code.

A: execlp will end the current program and run the called program instead.
Anything after execlp("ls","ls",(char *)NULL); will never get executed.
You need a fork for each execlp.


text:
Q: SQL Server, using a table as a queue I'm using an SQL Server 2008 R2 as a queuing mechanism. I add items to the table, and an external service reads and processes these items. This works great, but is missing one thing - I need mechanism whereby I can attempt to select a single row from the table and, if there isn't one, block until there is (preferably for a specific period of time).
Can anyone advise on how I might achieve this?

A: The only way to achieve a non-pooling blocking dequeue is WAITFOR (RECEIVE). Which implies Service Broker queues, with all the added overhead.
If you're using ordinary tables as queues you will not be able to achieve non-polling blocking. You must poll the queue by asking for a dequeue operation, and if it returns nothing, sleep and try again later.
I'm afraid I'm going to disagree with Andomar here: while his answer works as a generic question 'are there any rows in the table?' when it comes to queueing, due to the busy nature of overlapping enqueue/dequeue, checking for rows like this is a (almost) guaranteed deadlock under load. When it comes to using tables as queue, one must always stick to the basic enqueue/dequeue operations and don't try fancy stuff.

A: "since SQL Server 2005 introduced the OUTPUT clause, using tables as queues is no longer a hard problem". A great post on how to do this.
http://rusanu.com/2010/03/26/using-tables-as-queues/

A:
I need mechanism whereby I can attempt
  to select a single row from the table
  and, if there isn't one, block until
  there is (preferably for a specific
  period of time).

You can loop and check for new rows every second:
while not exists (select * from QueueTable)
    begin
    wait for delay '00:01'
    end

Disclaimer: this is not code I would use for a production system, but it does what you ask.

A: The previous commenter that suggested using Service Broker likely had the best answer. Service Broker allows you to essentially block while waiting for more input.
If Service Broker is overkill, you should consider a different approach to your problem. Can you provide more details of what you're trying to do?

A: Let me share my experiences with you in this area, you may find it helpful.
My team first used MSMQ transactional queues that would feed our asynchronous services (be they IIS hosted or WAS). The biggest problem we encountered was MS DTC issues under heavy load, like 100+ messages/second load; all it took was one slow database operation somewhere to start causing timeout exceptions and MS DTC would bring the house down so to speak (transactions would actually become lost if things got bad enough), and although we're not 100% certain of the root cause to this day, we do suspect  MS DTC in a clustered environment has some serious issues.
Because of this, we started looking into different solutions. Service Bus for Windows Server (the on-premise version of Azure Service Bus) looked promising, but it was non-transactional so didn't suit our requirements.
We finally decided on the roll-your-own approach, an approach suggested to us by the guys who built the Azure Service Bus, because of our transactional requirements. Essentially, we followed the Azure Worker Role model for a worker role that would be fed via some queue; a polling-blocking model.
Honestly, this has been far better for us than anything else we've used. The pseudocode for such a service is:
hasMsg = true

while(true)

    if(!hasMsg)
         sleep

    msg = GetNextMessage

    if(msg == null)
        hasMsg = false
    else
        hasMsg = true

    Process(msg);

We've found that CPU usage is significantly lower this way (lower than traditional WCF services).
The tricky part of course is handling transactions. If you'd like to have multiple instances of your service read from the queue, you'll need to employ read-past/updlock in your sql, and also have your .net service enlist in the transactions in a way that will roll-back should the service fail. in this case, you'll want to go with retry/poison queues as tables in addition to your regular queues.


text:
Q: Sphinx search: Empty attributes with multiple indexes When using the PHP Sphinx client this works:
SphinxClient::query ('*', 'index1');

But when I try this:
SphinxClient::query ('*', 'index1, index2');

The result contains no attributes. I'm using Sphinx 2.0.4-release (r3135) and searched the Sphinx forums and google but without any results except this post http://sphinxsearch.com/forum/view.html?id=5141 which didn't help a lot. Anyone here to help?

A: Have you checked the two indexes to make sure they have the same schema - ie the same attributes?