text:
Q: Grid overflowing onto div below I am creating a personal website to show off my other work and thought it wanted to build the site from scratch myself to learn a skill. I ave finished a "portfolio section" that is using display: grid to create multiple tiles to each represent a project I have worked on. It works great and does exactly what I would like it to do. I am now creating a contact section but the portfolio area is overlapping the new contact div I have created and am unsure as to why. Any help is appreciated.
Photo of issue (the lines going through protfolio tiles should say contact and be placed below the portfolio. I set the contact min-height to 800px and only 150-200 is shown as it starts at the beginning of the portfolio section as well.
I also have modal containers that are set to hidden until a button is clicked that is below the final contact code but it doesnt seem to be the issue so I did not post.
Code:

// ----------------------Portfolio Tile Styles----------------------//

.portfolio{
  width: 100%;
  background-color: rgb(245,245,245);
}

//Styles for the portfolio buttons
.btn-container{
  margin-top:50px;
  background-color: rgb(245,245,245);
  text-align: center;

}

//Styles to set all portfolio tiles to be initally hidden;
  .photogrammetry, .cv, .dev{
    display: none;
  }

.filter-btn{
  padding: 5px 20px;
  margin:10px 5px;
  border: 2px solid #e31b6d;
  color: #e31b6d;
  cursor: pointer;
  letter-spacing: 1px;
  background-color: white;
  text-transform: uppercase;
  transition:transform .3s;
  transition: color .3s;
  transition: background-color .3s;
}

.filter-btn:hover{
  color:white;
  background-color: #e31b6d;
}

.gallery-wrapper{
  position: absolute;
  width:100%;
  display: flex;
  background-color: rgb(245,245,245);
}

// Portfolio Gallery Styles
.gallery{
  position: relative;
  width: 100%;
  padding: 0 7%;
  overflow: hidden;
  margin: 0% 5% 2% 5%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(19rem, 1fr));

}

/* The "show" class is added to the filtered elements */
.show {
  display: block;
}

.card{
  overflow: hidden;
  align-items: center;
  width: auto;
  height: 250px;
  margin: 5px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  background-size: cover;

}

.top-text{
  text-align: center;
  transform:translateY(-100px);
  transition:transform .3s;
}

.card-btn,{
  width:50%;
  padding: 5px;
  text-transform: uppercase;;
  letter-spacing: 1px;
  background: transparent;
  color: #e31b6d;
  opacity: 1;
  border: 2px solid #e31b6d;
  outline: none;
  cursor: pointer;
  transform:translateY(100px);
  transition:transform .3s;
  transition: color .3s;
  transition: background-color .3s;
}

.card:hover{
   .card-btn{
    transform: translateY(0px);
  }

  .top-text{
  transform:translateY(0px);
  }
}

.card-btn:hover{
    color:white;
    background-color: #e31b6d;
  }

//Tile Backgrounds
.AutoFP {
    background: url("../images/portfolioTile/AFP_Tile.png") center no-repeat;
    background-size: cover;
  }
.fpl-1 {
    background: url(https://media.defense.gov/2013/Jul/16/2000032379/-1/-1/0/130628-F-DQ639-002.JPG) center no-repeat;
    background-size: cover;
  }

.fpl-2 {
    background: url("../images/portfolioTile/IS_Tile.jpg") center no-repeat;
    background-size: cover;

  }

.fpl-3 {
  background: url("../images/portfolioTile/Algae_Tile.png") center no-repeat;
  background-size: cover;
}
.fpl-4 {
  background: url("../images/portfolioTile/AFP_Tile.jpg") center no-repeat;
  background-size: cover;

}
.fpl-5 {
  background: url("../images/portfolioTile/UCW_Tile.png") center no-repeat;
  background-size: cover;
}
.fpl-6 {

  background: url("../images/portfolioTile/Portrait_Tile.png") center no-repeat;
  background-size: 100%;
  background-color: white;
}
.fpl-7 {
  background: url("../images/portfolioTile/CamCal_Tile.png") center no-repeat;
  background-size: contain;
  background-color: white;
}

//Faded Tile Background
.AutoFP:hover{
    background: linear-gradient(rgba(255,255,255,0.7), rgba(255,255,255,0.7)),url("../images/portfolioTile/AFP_Tile.png") center no-repeat;
    background-size: cover;
}
.fpl-1:hover {
  background: linear-gradient(rgba(255,255,255,0.7), rgba(255,255,255,0.7)),url(https://media.defense.gov/2013/Jul/16/2000032379/-1/-1/0/130628-F-DQ639-002.JPG) center no-repeat;
  background-size: cover;
}

.fpl-2:hover {
  background: linear-gradient(rgba(255,255,255,0.7), rgba(255,255,255,0.7)),url("../images/portfolioTile/IS_Tile.jpg") center no-repeat;
  background-size: cover;
}

.fpl-3:hover {
  background: linear-gradient(rgba(255,255,255,0.7), rgba(255,255,255,0.7)),url("../images/portfolioTile/Algae_Tile.png") center no-repeat;
  background-size: cover;
}
.fpl-4:hover {
  background: linear-gradient(rgba(255,255,255,0.7), rgba(255,255,255,0.7)),url("../images/portfolioTile/AFP_Tile.jpg") center no-repeat;
  background-size: cover;
}
.fpl-5:hover {
  background: linear-gradient(rgba(255,255,255,0.7), rgba(255,255,255,0.7)),url("../images/portfolioTile/UCW_Tile.png") center no-repeat;
  background-size: cover;
}
.fpl-6:hover {

  background: linear-gradient(rgba(255,255,255,0.7), rgba(255,255,255,0.7)),url("../images/portfolioTile/Portrait_Tile.png") center no-repeat;
  background-size: 100%;
  background-color: rgba(255,255,255,0.7);
}
.fpl-7:hover {
  background: linear-gradient(rgba(255,255,255,0.7), rgba(255,255,255,0.7)),url("../images/portfolioTile/CamCal_Tile.png") center no-repeat;
  background-size: contain;
  background-color: rgba(255,255,255,0.7);
}

Projects

   <button class="btn active filter-btn" onclick="filterSelection('all')">All</button>
   <button class="btn filter-btn" onclick="filterSelection('photogrammetry')">Photogrammetry</button>
   <button class="btn filter-btn" onclick="filterSelection('cv')">Computer Vision</button>
   <button class="btn filter-btn" onclick="filterSelection('dev')">Developer</button>

Automated FlightPlanning

       Electron, Python

      <button class="card-btn" id ="AutoFP">Learn More</button>

Change Detection

       OpenCV, Python

      <button class="card-btn" id ="cd">Learn More</button>

Image Stitching

       C++, OpenCV

      <button class="card-btn" id ="imgStitch">Learn More</button>

Algae Detection

       OpenCV, Python

      <button class="card-btn" id ="AlgDec">Learn More</button>

Aerial 3D Model

       DJIFlightPlanner, MetaShape

      <button class="card-btn" id ="A3DM">Learn More</button>

University Course Website

       HTML, CSS

      <button class="card-btn" id ="UCW">Learn More</button>

University Course Website

       Research Paper

      <button class="card-btn" id ="RP">Learn More</button>

Camera Calibration of "Prosumer" drones

       Journal Article

      <button class="card-btn" id ="JA">Learn More</button>

CONTACT


text:
Q: How to operate on value from collecting an IntStream inside a lambda function Let's say I have an IntStream and I would like to get e.g. a list of items from some collection things whose index is in that stream.
I thought it would be as simple as
IntStream.range(0, 10).collect(Collectors.toList(
    _i -> things[_i]
))

but a problem of incompatible types (<lambda parameter> vs. int) appears.
<lambda parameter> can't be cast to Integer. This surprised me because a similar method toMap seems to work fine, if I add boxed() to the stream – then the type of the lambda parameter is java.lang.Object instead of <lambda parameter>:
IntStream.range(0, 10).boxed().collect(Collectors.toMap(
    _i -> things[_i], _i -> 1
))

I am using Java 12.
How can I achieve similar behaviour in the toList method, or if what I am attempting is a bad idea altogether – why, and what would be a good alternative approach?

A:
1) I would like to get e.g. a list of items from some collection things whose index is in that stream

For first question you have to use mapToObj  intermediate operation, To get the elements from another list using index and collecting them into List
List<ObjectType> res = IntStream.range(0, 10)
                                .mapToObj(i-> things.get(i))   // or mapToObj(things::get)
                                .collect(Collectors.toList());

2) This surprised me because a similar method toMap seems to work fine, if I add boxed() to the stream

For second question boxed() will create a Stream of Integer (like Stream<Integer>), were Stream has collect to collect the result into Map by using Collectors.toMap. Here is the article with more information
Stream
<R,A> R collect(Collector<? super T,A,R> collector)

Collectors
public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
                                                Function<? super T,? extends U> valueMapper)

A:
This surprised me because a similar method toMap seems to work fine

You can make it with the same way of a Map by using mapToObj like so
List<Thing> collect = IntStream.range(0, 10)
        .mapToObj(_i -> things[_i])
        .collect(Collectors.toList());

redpajama_set_name: RedPajamaStackExchange


text: Q: Topology of Anti-de Sitter manifold with black hole I'm interested in understanding the topology of space-time with a black hole.  In other words how does having a black hole affect quantities such as the fundamental group, de-Rham cohomologies, Euler character etc of the background space-time manifold. Answering in light of anti-de Sitter space would be very helpful.


text:
Q: How to define sparseness of a vector? I would like to construct a measure to calculate the sparseness of a vector of length $k$.
Let $X = [x_i]$ be a vector of length $k$ such that there exist an $x_i \neq 0$ . Assume $x_i \geq 0$ for all $i$.
One such measure I came across is defined as $$\frac{\sqrt{k} - \frac{\|X\|_1}{{\|X\|_2}}} {\sqrt{k} -1}\;,$$ where $\|X\|_1$ is $L_1$ norm and $\|X\|_2$ is $L_2$ norm.
Here, $\operatorname{Sparseness}(X) = 0$ whenever the vector is dense (all components are equal and non-zero) and $\operatorname{Sparseness}(X) = 1$ whenever the vector is sparse (only one component is non zero).
This post only explains the when $0$ and $1$ achieved by the above mentioned measure.
Is there any other function defining the sparseness of the vector.

A: You could of course generalize your current measure
\begin{align}
 S(X) = \frac{\frac{k^{(1/m)}}{k^{(1/n)}} -\frac{\|X\|_m}{\|X\|_n} } {\frac{k^{(1/m)}}{k^{(1/n)}}-1}
\end{align}
while preserving your properties you specified.
An interesting special case could be $m = 1, n \to \infty$, in which case the expression simplifies to
\begin{equation}
 S(X) = \frac{k-\frac{\|X\|_1}{\|X\|_c}}{k-1}
\end{equation}
where $c = \infty$, (for some reason, mathjax refused to render when I inserted $\infty$ directly in the fraction)

A: There is a definition of sparsity, which is used (amongst others) in the compressed sensing literature, see e.g.  here.
A vector $x\in \mathbb{C}^k$ is called $s$-sparse, if $|| x ||_0 = |\text{supp}(x)| \leq s$, that is, it has at most $s$ non-zero entries. Denote by $\Sigma_s$ the set of all such vectors. Then, the $s$-term approximation error of a vector $x\in \mathbb{C}^k$ is defined as
$$
\sigma_s(x)_p = \min_{y\in\Sigma_s} ||x-y||_p.
$$
Now this quantity equals $0$, if your vector $x$ is $s$-sparse, and will be greater than $0$ otherwise. Note that you now have two parameters $s$ and $p$ to tune this "measure". Clearly, you get your definition of sparsity if you set $s=1$.

A: The paper "Comparing Measures of Sparsity" by Hurley and Rickard has a wide range of sparsity measures considered, along with the analysis of their conformance to a bunch of properties one would consider desirable for such measures.
The one you mention is listed under the name of Hoyer measure and bears most of these properties (except one, namely D4, that makes sense only if we wish to compare vectors of different lengths).

A: Disclaimer: This post considers the case in which you do not mind some computational effort to get nice sparseness value. For something new, please skip to part 2.
Part 1
I agree with Mikael, that kind of generalization is nice, what's more, with Mikael's formula it is intuitive from where it came from: the most basic notion for vector sparseness would be $$\frac{\text{number of indices $k$ such that }X_k = 0}{\text{total number of indices}}.$$
However, by this definition $\langle 0, 0, \ldots, 0\rangle$ is sparse, but vector $\langle c, c, \ldots, c \rangle$ is not. Still, it is easy to fix it:
$$\frac{\text{number of indices on which }X_k - c = 0}{\text{total number of indices}}\,,$$
where $c$ is some average of $X$, e.g. $c = \|X\|_\infty$. The problem with this measure is that it is not easy to count the number of indices. To alleviate for that, we could approximate the number of indices by $\frac{\|X\|_1}{\|X\|_\infty}$. Naturally we need some normalization, and by that we arrive at Mikael's special case: $$\frac{k-\frac{\|X\|_1}{\|X\|_\infty}}{k-1}.$$
But the average we took as an example $x = \|X\|_\infty$ isn't the only one. Similarly we could approximate the number of indices in different fashions:
$\frac{\|X\|_m}{\|X\|_n}$ would do for any $m < n$, and the normalization is just $$\frac{\frac{\|C\|_m}{\|C\|_n}-\frac{\|X\|_1}{\|X\|_\infty}}{R_\max-R_\min}, R_\max = \frac{\|C\|_m}{\|C\|_n}, R_\min = \frac{\|D\|_m}{\|D\|_n},$$
where $C = \langle c, c, \ldots, c \rangle$ and $D = \langle c, 0, 0, \ldots, 0 \rangle$ for any $c \neq 0$.
Part 2
Still, this measure is rather weird, because intuitively it more depends on the sizes of the values, than how many different numbers there are. I am not sure that this is a property we would want to have. There is a different measure that can take that into account, i.e. measure based on entropy. Interpreting $X$ as the samples, one can calculate $$ -\sum_i P(X = i) \log_k P(X = i) .$$
To soften this a bit just pick any distribution you want (best specific to your application), e.g. $F_\mu = N(\mu, \sigma^{2})$, set $$F = \frac{1}{k}\sum_i F_{X_i},$$
and then calculate differential entropy ($f$ is the density function of $F$):
$$-\int_\mathbb{R} f(x) \ln f(x) \ dx$$
or even better relative entropy if you have some reference measure (e.g. the very same $F_\mu$ adjusted a bit might do the trick). Of course, all this has to be scaled to $[0,1]$ what makes the formulas even nastier, however, in my opinion, it catches the notion of sparseness pretty good. Finally, you can combine the two approaches in infinitely many ways, to get even more sparseness models!

A: $
\def\o{{\tt1}}
\def\eo{\|a\|_\o}\def\et{\|a\|_2}
\def\xo{\|x\|_\o}\def\xt{\|x\|_2}
\def\Eo{\|A\|_\o}\def\Et{\|A\|_2}
\def\Xo{\|X\|_\o}\def\Xt{\|X\|_2}
\def\H{{\cal H}}\def\K{{\cal K}}
\def\L{\left}\def\R{\right}
\def\LR#1{\L(#1\R)}
\def\BR#1{\Big(#1\Big)}
\def\bR#1{\big(#1\big)}
\def\fracLR#1#2{\LR{\frac{#1}{#2}}}
$Let $a\in{\mathbb R}^{n}$ denote the all-ones vector,
then
$$\eqalign{
\eo = n\qquad{\rm and}\qquad \et = {\sqrt n} }$$
This means that the Hoyer sparsity can be written as
$$\eqalign{
\H(x) &= \frac{\et\cdot\xt\;-\;\xo}{\et\cdot\xt\;-\;\xt} \\
}$$
However, an equally good sparsity measure is
$$\eqalign{
\K(x) &= \frac{\eo\cdot\xt^2\;-\;\xo^2}{\eo\cdot\xt^2\;-\;\xt^2} \\\\
}$$
Although $\K(x)\ne\H(x)$ in general,
the extrema for both functions are the same
$$\eqalign{
\K(a) &= \H(a) &= 0 \\
\K(e_k) &= \H(e_k) &= \o \\
}$$
where $e_k$ is any cartesian basis vector.

Note that both functions extend naturally to the matrix case
$X\in{\mathbb R}^{n\times m}$
$$\eqalign{
\H(X) &= \frac{\Et\cdot\Xt\;-\;\Xo}{\Et\cdot\Xt\;-\;\Xt} \\
\\
\K(X) &= \frac{\Eo\cdot\Xt^2\;-\;\Xo^2}{\Eo\cdot\Xt^2\;-\;\Xt^2} \\
}$$
where $\Xo$ is the Manhattan norm, $\Xt$ is the Frobenius norm,
and $A$ is all-ones.
The extrema are
$$\eqalign{
\K(A) &= \H(A) &= 0 \\
\K(E_{ij}) &= \H(E_{ij}) &= \o \\
E_{ij} &= e_i\,e_j^T \\
}$$
Update
Choose $\alpha,\beta\in\{{\tt1},2,\infty\},\;\alpha\!\ne\!\beta,\,$ and $\,p\in{\mathbb R}\;$ and define the function
$$\eqalign{
F(X) &= \frac{\big\|X\big\|^p_\alpha}{\big\|X\big\|^p_\beta} \\
}$$
Use this function to construct a generalized sparsity estimate
$$\eqalign{
{\cal S}(X) \;=\; \frac{F(A) \;-\; F(X)}{F(A) \;-\; F(E_{ij})},
\qquad {\cal S}(A)=0,
\;\; {\cal S}(E_{ij})=\o
}$$
Notice that for any choice of parameters
$\;F(E_{ij}) = \o$


text:
Q: Delete message from jabber history in Empathy 3.2 I accidentially sent a message with private information to a friend of mine on Jabber (using Empathy 3.2).
I now want to delete this message from the history, but I cannot find where Empathy 3.2 stores the logs.
Please help me!
Thank you!

A: found it on
http://live.gnome.org/Empathy/FAQ#Where_does_Empathy_save_files_.28accounts.2C_logs.2C_configuration.29.3F
It's stored in ~/.local/share/TpLogger/logs
Thank you!

A: For me this is the right path  "~/.purple/logs/jabber" for remove old converstions.


text:
Q: Running SAS code through Python to login to a specific SAS-database I need to login to a SAS-database through Python, to get access to the SASdata project folders and pull data. I am using updated packages per 01/20/2020, testing via saspy and Jupyter Notebook on Windows 10.
The way I do it at the moment is to pass SAS code on SAS Enterprise login (via %let user = ****** & %let pass = ****** and libnames). My goal is to be able to pull data and work on it through Jupyter, or even just a regular code editor.
The problem I have is gaining access through my Python code. I have looked through https://sassoftware.github.io/saspy/install.html#configuration and tried messing with the authkey. However, I haven't been able to gain access to anything but a regular SAS session, with none of the libraries I need to access being available.
My thinking is that if I could pass the exact same code through my script/notebook, I should be able to connect to the underlying SASdata folder/projects.
EDIT: @Richard This is the little bit of code I use to start the session sas = saspy.SASsession()
I have my config set to 'iomwin':
iomwin   = {'java'      : '/usr/bin/java',
            'iomhost'   : 'the_specific_server',
            'iomport'   : the_specific_port,
            'encoding'  : 'windows-1252',
            'authkey'   : 'data_auth',
            'classpath' : cpL
            }

However, when I run this code I do not get access to the server.
I've tried with the config set to default, typing in my user and pass, but I do not get through to the server.
EDIT 2:
This is the code I run on start up (of a SAS session):
%let user = *****;
%let pass = *****;

libname ***** ***** host="*****" server="*****" user="&user" password="&pass" schema="DBA";

libname ***** ***** host="*****" server="*****" user="&user" password="&pass" connection=unique schema="dbo";

A: You can use the IOM access method to connect to the same workspace server you connect to using EG. See the doc here: https://sassoftware.github.io/saspy/install.html#remote
You can get help with this directly by opening an issue on saspy github page: https://github.com/sassoftware/saspy/issues (click new issue). You can also search all of those issues for the same question and explanation of how to set this up, if you find that helpful.


text:
Q: How to modify the values in a dataframe based on the values from another dataframe in an efficient way? I have 2 dataframes like so:
import pandas as pd
data1 = {'Col1':['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
        'Col2':[3.409836, 2.930693, 2.75, 3.140845, 2.971429, 2.592593, 2.6, 3.1875, 2.857143, 0.714286]}
df1 = pd.DataFrame(data1, columns=['Col1', 'Col2'])

data2 = {'Col1':['B', 'F', 'I'],
         'Col2':[23.45, 32.57, 19.85]}
df2 = pd.DataFrame(data2, columns=['Col1', 'Col2'])

I want to modify the values of Col2 in df1 with the values from df2. This is my code to do that:
for i in range(len(df2)):
    for j in range(len(df1)):
        if df2['Col1'][i]==df1['Col1'][j]:
            df1['Col2'][j]=df2['Col2'][i]

The code works:

But the problem is, this code would be slow for large dataframes as it has complexity O(len(df1)*len(df2)). How do I merge the 2 dataframes in a faster, more efficient way?
I tried merging the dataframes using outer join, but it does not produce the correct result - it keeps both values:
pd.merge(df1, df2, how='outer')

An inner join produces a blank dataframe, a left join produces the same dataframe as df1, and a right join produces the same dataframe as df2.

A: If working only with one column use map:
df1['Col2'] = df1['Col1'].map(df2.set_index('Col1')['Col2']).fillna(df1['Col2'])
print (df1)
  Col1       Col2
0    A   3.409836
1    B  23.450000
2    C   2.750000
3    D   3.140845
4    E   2.971429
5    F  32.570000
6    G   2.600000
7    H   3.187500
8    I  19.850000
9    J   0.714286

If multiple columns is possible use merge with left join and specified column Col1:
cols = df1.columns.difference(['Col1'])
orig_cols = [f'{x}_' for x in cols]

df = pd.merge(df1, df2, how='left', on='Col1', suffixes=('_',''))
print (df)
  Col1     Col2_   Col2
0    A  3.409836    NaN
1    B  2.930693  23.45
2    C  2.750000    NaN
3    D  3.140845    NaN
4    E  2.971429    NaN
5    F  2.592593  32.57
6    G  2.600000    NaN
7    H  3.187500    NaN
8    I  2.857143  19.85
9    J  0.714286    NaN

Then replace missing values of added column by original columns and last remove them:
df[cols] = df[cols].fillna(df[orig_cols].rename(columns=lambda x: x.strip('_')))
df = df.drop(orig_cols, axis=1)

print (df)
  Col1       Col2
0    A   3.409836
1    B  23.450000
2    C   2.750000
3    D   3.140845
4    E   2.971429
5    F  32.570000
6    G   2.600000
7    H   3.187500
8    I  19.850000
9    J   0.714286

A: try this code:
df4=df3.Col3.isnull()
df3=pd.merge(df1, df2,how='outer')
df4=df3[df3.Col3.isnull()]
df5=df3[df3.Col3.notnull()]
df5.Col2=df5.Col3
df6=df4.append(df5)
df6=df6.drop('Col3',axis=1)

df6 is the output you are looking for.


text:
Q: What is the correct notation for "expected value of function, given that we know the variable"? Take a function $f(x)$, where $x$ is a random variable, but $f$ is also a "random function", meaning that even if we know $x$, we don't know $f$ with certainty. (I don't know if it is even acceptable to say this. If it isn't, then just think of $f(x,y)$ instead, where $y$ is also a random variable).
I want two particular things:

*

*The expected value of $f$, given that we know $x$ has some particular value, say 5.

*the expected value of $f$, as a function of $x$, which we don't know.

How do we write these things down as a formula?

A: You can consider $F$ to be a parametric random variable depending on the parameter $x$ and denoted $F_x$ or $F(x)$.
Its pdf would be
$$p_x(f):=\mathbb P(F_x=f).$$
Now if $x$ is a random variable, you can consider the conditional distribution
$$p_x(f):=\mathbb P(F_X=f|X=x)$$
versus the ordinary distribution
$$p_X(f):=\mathbb P(F_X=f).$$
Then
$$E(F_x)=\int f\,p_x(f)\,df\\\text{ vs. }\\E(F_X)=\int f\,p_X(f)\,df=\int f\,\mathbb P(F_X=f\land X=x)\,df\,dx$$

A: In quantum mechanics we would subscript the bra-ket notation
f(x,y) - function of two random variables
$e(x) = \langle f(x,y) \rangle_y = \int_{y \in \Omega} f(x,y)P(y)dy $ - expectation value with respect to variable $y$
$e(y) = \langle f(x,y) \rangle_x = \int_{x \in \Omega} f(x,y)P(x)dx $ - expectation value with respect to variable $x$
I have never heard of "random functions", you will have to be more precise with what you mean by it. If you mean that the function itself can be random, and you can't parameterize that randomness easily using a random variable parameter $y$, then the question is really hard

A: Instead of using the term "random function", you can just say that you are given a statistics $f(X,Y)$ of two random variables $X,Y$. Mathematically, a statistics is just a composite function of random variables.
For your first question, it is common to write $E_{Y}f(x,Y)$ (here "$x$" denotes a realization of $X$); the subscript is used to inform the reader with respect to which random variable we take expectation.
For the other one, just write $Ef(X,Y)$; the absence of subscripts says enough to the reader.
As an appendix, random functions are another type of mathematical objects.


text:
Q: How to autfill a column with data from My Site I would like to create a custom list in SP2013 that would have two People or Group columns. One would display the Name of a user, the other would display his email address of the same user (both information are available in this column type - I assume they are taken somewhere from MySite).
Is there any way how to make the content of the other column display automatically? i.e, When I select User A in the first column, I wouldn't have to manually add his email address to the second column but it would fill automatically?

A: People normally think of using a Calculated column for such requirement, but that will not work. Instead, you may achieve it using SharePoint Designer Workflow.
Modify your list design as below,
Column Name       |       Type             |          Detail
------------------------------------------------------------------------
User Name         |   People or Group      | To select the required user here
Email ID          |  Single line of text   | Email ID populated automatically

Create a SharePoint designer workflow, which will set the Email ID column once the item is created. The workflow will run whenever an item is added and modified.
Workflow step,
Set Email ID to Current Item:User Name

In Current Item:User Name, set the value as
Data Source        : Current Item
Field from source  : User Name
Return field as    : Email Address

Note: Dont forget to hide/disable your Email ID column from the required forms to avoid confusions for end user.


text:
Q: String input in MIPS omits the first four characters that are inputted .data
EntryReq:
    .asciiz "Please enter an 8 digit hexadecimal MIPS instruction: \n"
InputLongError:
    .asciiz "\nYour input was too long, make sure it is 8 digits. "
InputShortError:
    .asciiz "\nYour input was too short, make sure it is 8 digits. "
CharInvalidError:
    .asciiz "\nYour input contains an invalid character. "
ValidChars:
    .asciiz "0123456789abcdef\n\b\0"

.align 4
input:
    .space 20

.text

main:
    #Print input request
    la $a0, EntryReq #loads input into arg. reg.
    li $v0, 4 #op code for print string
    syscall

    #take input for input (stored)
    li $v0, 8 #op code for take user input
    la $a0, input #provide address for syscall
        li $a1, 20 # tell syscall the byte space required for the string
    syscall

    #move to input(stored)
    sw $v0, input #move inputted into from $v0 to input(stored)

    #check validity of input
    la $a0, input #load address of input to arg. reg. for method call
    la $a1, ValidChars #load address of string of valid chars
    jal verifyInput #call the verifyInput method which does as expected

    #test if string length count works
    addi $a0, $v0, 0 #load from $v0 to arg. reg.
    li $v0, 1 #op code for print int
    syscall

terminate:
    li $v0, 10
    syscall

verifyInput:
    li $v0, -1 #start length count at 0
verifyLoop:
    lb $t0, ($a0) #load current
    li $a2, 0 #loop for char check, loops up to length of validChar string
    la $a1, ValidChars
    j checkChar
charVerified: #ignore this, is entry point back into verifyLoop for checkChar
    addi $a0, $a0, 1 #increment
    addi $v0, $v0, 1
    bgt $v0, 8, printTooLongError #if result bigger than 8, error
    bne $t0, 10, verifyLoop #10 is string end, so check if string is end
    blt $v0, 8, printTooShortError #if result less than 8, error
    jr $ra #if here string input was confirmed okay

checkChar: # loops through valid chars for each char in $a0                 | Valid Chars: 0123456789abcdef\n |
    lb $t1, ($a1) #loads in byte from char string
    addi $a1, $a1, 1 #increment address, for the next char
    addi $a2, $a2, 1 #increment until length of valid char string is reached
    beq $t0, $t1, charVerified
    bne $a2, 19, checkChar #if length of valid chars changes, change second argument here
    j charNotValidError
charNotValidError:
    la $a0, CharInvalidError #loads input into arg. reg.
    li $v0, 4 #op code for print string
    syscall
    j terminate
printTooLongError:
    la $a0, InputLongError #loads input into arg. reg.
    li $v0, 4 #op code for print string
    syscall
    j terminate
printTooShortError:
    la $a0, InputShortError #loads input into arg. reg.
    li $v0, 4 #op code for print string
    syscall
    j terminate

The general gist of this code is for the user to input an 8 digit hexadecimal string, and then the program checks whether it is a valid hexadecimal string (i.e. includes only 0-9 and a-f). However, whenever I run it, the string that I input is missing the first four characters. So if I place invalid characters in the first four digits, like wwww1abc, then the code runs fine, which it shouldn't. But if I do 1abcwwww, it outputs an invalid character error, which it should. I'm genuinely confused as to why this is the case, nor have I seen anyone else experience this issue. Any help is greatly appreciated.

A: The problem is this line:
#move to input(stored)
sw $v0, input #move inputted into from $v0 to input(stored)

Unlike read integer syscall, read string puts the result in the input buffer, in your case input. So you don't need to read out the value in $v0 and by storing it in input you're overwriting the first 4 bytes of the buffer with the value of $v0, which is still 0x00000008, which conveniently is the same as the string "\b\0\0\0" for little endian machines, all of which are in your validity list. Removing that line should fix your program (though I didn't look over all the rest of the code for errors).


text:
Q: Detecting a -301 DB2 error in .NET I have an application in VB.NET which is generating some -301 errors in DB2 on an update statement using an ADO.NET connection.
It appears that DB2 reports the occurrence of this error, but then fixes whatever data was wrong and resubmits. This fixing and resubmission comes with additional overhead and in turn real dollars and cents cost because this is mainframe DB2.
Is there a way to detect this -301 error in some way? I am not able to recreate the problem. I only know this is happening because DB2 reports that the error occurred, but because I am using a parameterized query and due to the configuration of DB2 I am not able to determine the values of the parameters.
At this point I think that my best bet is to serialize the inputs that I am getting and then write them out to xml and when my DBA is able to tell me when an error occurs, I will take the file and then reprocess in a test environment one by one. That is, unless there is something which I can check, like a return code, and then send an error email with a serialization of the offending object instance.

A: The reason for DB2 -301 error is Input host variable or argument not valid.
More details about DB2 errors mentioned in this article.

A: That DB2 fixes and resubmits the statement sounds very odd!
Perhaps there is some extra layer between your program and DB2 that does that?

Well, when you don't get the error returned to your program then ...
First you could ask your DBA to send you the error with the position-number and the update-statement so you can see which host-variable is the problem.
The variable is probably used in some SQL-function. Your DBA should be able to say which datatypes are allowed there.

Here a link to e description of the error (if you don't have it):
http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.codes/n301.htm

My answer is not quite what you asked for but I don't think it can be any closer.
Regards
    Sigersted


text:
Q: position inconsistency with carousel indicators I am using this code to create a basic carousel slider with 4 items.When I go to next slides it works well but when I navigate to first slide via carousel indicators, the carousel indicator's position becomes inconsistent.
    <!DOCTYPE html>

    <title></title>
    <link href="bootstrap/css/bootstrap.css" rel="stylesheet" />

Image 1

This is the description for Image1

Image 2

This is the description for Image2

Image 3

This is the description for Image3

Image 4

This is the description for Image4

This is the first slide when the page loads. It works well when I go to next slides.

But when I navigate to the first slide I face with some inconsistency with carousel position, here is the second snapshot.

How can I overcome this issue?

A: Are you sure you are initializing your carousel correctly?
$(document).ready(function () {
        $('#imageCarousel').carousel();
    });

I found the problem, your markup is wrong. ol must have carousel-indicators class but you wrap this to div. Correct markup is:

Look here for more details:
https://getbootstrap.com/javascript/#carousel
And this is the workingjsfiddle


text:
Q: Position of a UIView that's inside of the main UIView in a ViewController? I'm doing an app project in Swift, and I have an UIView moving inside the main View (the one that it's by default in the ViewController).
I want to know the exact position of the UIView when a button is pressed (X and Y).
I tried things like this but doesn't work for me:
let X = pointView.frame.origin.x + pointView.frame.origin.x;
let Y = pointView.frame.origin.y + pointView.frame.origin.y;

or
let frame = self.view.convertRect(self.view.frame, fromView:pointView)

The code I have at the moment:
    @IBAction func pressButton(sender: AnyObject) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let screenSize: CGRect = UIScreen.mainScreen().bounds
        let screenWidth = screenSize.width
        let screenHeight = screenSize.height

        UIView.animateKeyframesWithDuration(4, delay: 0, options: UIViewKeyframeAnimationOptions.Repeat, animations: { () -> Void in

            UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1.5/4.0, animations: { () -> Void in
                //1
                self.pointView.center = CGPointMake(2, screenHeight-2)
                //2
            })
            UIView.addKeyframeWithRelativeStartTime(1.5/4, relativeDuration: 1/4, animations: { () -> Void in
                self.pointView.center = CGPointMake(screenWidth-2, screenHeight-2)
            })
            UIView.addKeyframeWithRelativeStartTime(2.5/4, relativeDuration: 1.5/4.0, animations: { () -> Void in
                self.pointView.center = CGPointMake(screenWidth-2, 1)
            })
            //3
        }, completion: nil)
        //4
    }

A: Try this then:
let frame = pointView.superview?.convertRect(pointView.frame, toView: nil)

Sometime the view need his superView to find it's coordinates
Put it when you animation is finished
   UIView.animateWithDuration(1, animations: { () -> Void in
        //animation code
    }) { (success) -> Void in
        let frame = self.pointView.superview?.convertRect(self.pointView.frame, toView: nil)
    }


text:
Q: Does JQuery's Ajax refer to maxJsonLength property in web.config In my ASP.NET site, I use Jquery AJAX to load json data (in fact a string) from a webservice when clicking the search button :
$.ajax({
  type: "POST",
  url: url,
  data: JSON.stringify(parameterArray),
  contentType: "application/json",
  dataType: "json",
  success: function(response) {
    d = JSON.parse(response.d);
  }

When the return string gets too big, the page stop responding. I have to go to web.config and add this property in order for the website to work :
<jsonSerialization maxJsonLength="2147483644"/>

Here is how do the application handle the search result before returning data to the browser :
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
string strData = dService.searhforData(ipt);
List<Dictionary<string, object>> lRow = processData(strData);
string r = serializer.Serialize(lRow);
return r;

In case the Json string got too long, the page just stop responding,  there wasn't any error in the console window. As I debug at the .Net application side, the serializer.Serialize(lRow); went smoothly and successfully return the r, after that, the loading icon on the page just keep spinning. If I press F5 on the page, the search data appears.
My question is, if JQuery's Ajax refers to the web.config for the max json string length, why couldn't I find any information regarding this on the internet ?

A: I'm sure there is a limit on the amount of data that JSON.parse() can handle, but that's not related to your problem.
Your web.config file holds settings to be used server side. The JS on the client is not related to that at all. If you needed to amend that setting it's because your ASP.Net code was producing a JSON response longer than was previously allowed by the default setting of jsonSerialization.
If you checked the browser console after making the failed request you would most likely have seen an error in the response which guided you to the problem.


text:
Q: Open old app this message told me problem Open old app this message told me problem.

Could not find method taskclean() for arguments [{type=class
  org.gradle.api.tasks.Delete},
  build_2ep35kdoesf1fdcr2my3t2kqi$_run_closure2@1deb1fad] on root
  project 'playmusicexporter-develop' of type org.gradle.api.Project.

A:
taskclean(type:Delete) {
  deleterootProject.buildDir
}

The section above is erroneous. You have missed some spaces in between. Change it like  this:
task clean(type: Delete) {
  delete rootProject.buildDir
}

Update:
For your updated 2nd problem, still missing space is a problem. It should be like:
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'


text:
Q: Check if user is logged in, inside php file in template directory I have a php file in my template directory which generates some data from a database. I only want this data to be accessable for my wordpress users.
I tried by using this line of code but it gives me an error saying "headers already sent".
What is wrong? Or is there any other way to solve this?
<?php

 require_once('../../../wp-blog-header.php');

 if (is_user_logged_in())
 {

    echo "hello world";

 }
 else
 {
    echo "You do not have access to this resource!";
 }
?>

A: Since the file is in your theme directory, Wordpress may not want the user to "directly" access it. Why not create a Page in wordpress, assign a Template Name to your PHP page and then assign that to the new page created in wordpress. For example, you would have a new page called "Members Only" and its template is "php-page-located-in-theme". Then, in the code, you don't have to call the blog header, just simply wrap the entire page in your "Is user logged in" if else statement.
Example:
<?php
Template Name: php-page-located-in-theme

get_header();

if ( is_user_logged_in() ) {
    echo 'Welcome, registered user!';
    /*PHP Generated Content Goes Here*/
} else {
    echo 'You cannot access this page.';
}
get_sidebar();
get_footer();
?>

A: <?php
require_once('../../../wp-blog-header.php');
global $wpdb;
global $current_user,$user_ID;
get_currentuserinfo();
if($user_ID=="")
{
echo "You do not have access to this resource!";
}
else
{
    echo "hello world";
}
?>
You can use global variable global $current_user,$user_ID for checking user is login or not.


text:
Q: integration by parts to solve this problem Can someone please show me the steps to solve
$$
\frac{\sqrt{5}}{2}\int_{-1}^{1}xe^{-\frac{1}{2}x+\frac{3}{2}}dx
$$
with integration by parts. I did it twice and got all different answers. I know the answer has to be -1.712. Thanks for your help

A: $$I=\frac{\sqrt{5}}{2}\int_{-1}^{1}xe^{-\frac{1}{2}x+\frac{3}{2}}dx$$
$$=\frac{\sqrt{5}}{2}\cdot e^{\frac32}\int_{-1}^1xe^{-\frac12x}dx$$
Putting  $x=2y,dx=2dy$
When $x=-1,y=\frac x2=-\frac12$ and when $x=1,y=\frac x2=\frac12$
$$\implies I=\frac{\sqrt{5}}{2}e^{\frac32}\int_{-\frac12}^{\frac12}2ye^{-y}2dy=2\sqrt5e^{\frac32}\int_{-\frac12}^{\frac12}ye^{-y}dy$$
Now,
$$
\begin{align}
\int ye^{-y}dy &= y\left(\int e^{-y}dy\right)-
\int\left(\frac{dy}{dy}\cdot\int e^{-y}dy\right)dy\\
&=-ye^{-y}+\int e^{-y}dy\\
&=-ye^{-y}-e^{-y}
\end{align}
$$
Can you take it from here?

A: $$ \int_{-1}^{1}xe^{-\frac{1}{2}x+\frac{3}{2}}dx =-2xe^{-\frac{1}{2}x+\frac{3}{2}}|_{x=-1}^{x=1}  +2\int_{-1}^{1} e^{-\frac{1}{2}x+\frac{3}{2}}dx=-2e-2e^2-4 e^{-\frac{1}{2}x+\frac{3}{2}}|_{x=-1}^{x=1}$$
$$=-6e +2e^2.$$
We use the fact that $\int_a^bf'g = fg|_{a}^b-\int fg'$ and the fact that $\left(-2 e^{-\frac{1}{2}x+\frac{3}{2}}\right)'=e^{-\frac{1}{2}x+\frac{3}{2}}.$


text:
Q: Does timeout causes an API endpoint trigger multiple times? I have a GO Post API endpoint with a somewhat time-consuming task in the handler (time can be 2 minutes even, when I running it locally).
In my FE I call the API once and it triggers only once (in the network tab, there are no multiple requests) (1). The running time of the API call differs since it runs according to some dynamic data.
But on the API side, the call takes some time and succeeds, but doesn't send a response (still Pending in FE side). Then right away the handler runs again (still Pending in FE side) and the logic runs again. So, due to logic, since it's run already, it fails. Then that response is returning as the response for the request from FE (1) . So, the logic is a success, and DB is updated, but the response sends an error.
Does this due to a time-out issue? If so, how can I get this fixed?
I use go-chi as the GO framework and react for FE.
r := chi.NewRouter()

r = helpers.AttachLoggerMiddleware(r, pretty)
r.Route("/apps", func(r chi.Router) {
    r.Post("/{id}/clone", service.Clone)
}

func (s *Service) Clone(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Calling Clone !!")
    //logic
}

This is somewhat of a sample of how the API method configured

A: You should redesign your approach to use Long polling mechanism, use WebSosket or JSON streaming also will be an option.
A bit explanation:
You have a time-consuming task (takes 2 minutes, pretty sure it can take even more if your app will have more load). So, if you will use a simple Request-Respons approach, you will have an error because of timeout issues.
Because of that, using of proposed approaches will be better for your case.
Let's look at the WebSocket example:
In your go code, you will have something like(it's just an example to catch up an idea, I don't know chi and use github.com/gorilla/websocket and vanilla net/http but I'm pretty sure that you can do the same with chi):
package main

import (
    "fmt"
    "github.com/gorilla/websocket"
    "log"
    "net/http"
    "time"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func main() {
    http.HandleFunc("/ws", wsHandler)

    panic(http.ListenAndServe(":8080", nil))
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }

    if err != nil {
        http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
    }

    go echo(conn)
}

func echo(conn *websocket.Conn) {
    defer conn.Close()
    m := ""

    err := conn.ReadJSON(&m)
    if err != nil {
        fmt.Println("Error reading json", err)
    }

    // receive some data from your reactjs
    fmt.Printf("Got message: %#v\n", m)

    om := struct {
        mes string
    }{
        mes: "Send to client",
    }

    // send some data
    if err = conn.WriteJSON(om); err != nil {
        fmt.Println(err)
    }

    // do some work in 2 min
    time.Sleep(120 * time.Second)

    // send some data
    if err = conn.WriteJSON(om); err != nil {
        fmt.Println(err)
    }
}

In your react js app you will have something like:
import React, { useState } from "react";

function  App() {
  let isDone = false;
  const messages = []
  const ws = new WebSocket("wss://localhost:8080/ws");

  const apiCall = {
    mes: "Your json for server"
  };

  ws.onopen = (event) => {
    ws.send(JSON.stringify(apiCall));
  };

  ws.onmessage = function (event) {
    const json = JSON.parse(event.data);
    messages.push(json)
    } catch (err) {
      console.log(err);
    }
  };

  ws.onclose = function (event) {
    isDone = true
  };

  const mess = messages.map((item) => {
    return (

 {item}

    );
  });

  return (

{mess}

 is work done?: {isDone}

   );
}

export default  App;

In this example, we send some info to the server and start waiting when work will be finished(isDone =  true when ws closed), meanwhile receiving some messages(maybe it's non needed in your case).
Same for implementation of this idea with Long polling and JSON streaming (I think you easily find something on the internet:) )


text:
Q: Jquery animation on Firefox 7.0.1 lags Does anyone know why this very simple jquery animation works perfectly in some browsers like Chrome and seems to be bugged in Firefox 7.0.1?
Here's a link to the animation.
If you try it in Firefox you'll see that the animation sometimes freezes then restarts.
As you can see the code is very simple, only one animation, no images, and inline CSS.
html:

JS:
$(document).ready(function () {
    to_move=$('#slider');
    to_move.animate({
       top: "-1000px"
    }, 15000,'linear');
});

Thanks you for your help.

A: What you're seeing is Firefox's garbage collector kicking in every so often.
Via Dave Mandelin's blog:

Background on what GC is if you are not familiar: As a JavaScript
  program runs, it creates objects, arrays, strings, and functions,
  which take up memory. In order to not use up all your memory and
  crash, the JS engine must be able to automatically discover which
  objects are not in use anymore (so they are now "garbage") and free
  them up. This "automatic memory reclamation" subsystem is called the
  garbage collector, or GC.)
The reason for the pauses is that SpiderMonkey uses an old-school
  stop-the-world mark-and-sweep collector

Vast improvements to Firefox's GC are planned but not yet implemented - see that link for more info.

A: I don't know much about the inner workings of jquery, but I assume it's using a resize event for that div. Firefox handles resize events poorly, I'm not sure there's a way to fix it. Here's some more information: http://www.quirksmode.org/dom/events/resize.html


text:
Q: Mudar a classe de acordo com a condição Gostaria de fazer duas coisas:

*

*Um que o label com id cnt, quando apertasse o botão mais, somasse mais 1 e quando apertasse o botão menos, subtrai-se menos 1.

*Fora isso, quando o label cnt fosse igual a zero, retirasse a classe pizzaselecionada.

Fazer a classe mudar se o label=#cnt for igual a 0

29,90

        <button id="mais">mais</button>
        <button id="menos">menos</button>
        0
        R$0,00

A: Acredito que seja isto que esteja querendo fazer, lembrando que neste cenário apenas vai funcionar para 1 pizza para mais pizzas deveria mudar totalmente a programação.

   $(document).ready(function(e) {
     var mais = $("#maois"),
       menos = $("#menos"),
       qtd = $("#qtd"),
       total = $("#total"),
       pizza = $('.pizzadisponivel'),
       valuePizza = $(".pizzadisponivel > label").attr('value').replace(/,/, '.');

     $('#mais').click(function(e) {
       var novaQtd = parseInt(qtd.text()) + 1;
       total.text("R$ " + (novaQtd * valuePizza).toFixed(2));
       pizza.addClass("pizzaselecionada");
       pizza.removeClass('pizzadisponivel');

       qtd.text(novaQtd);

     });

     $('#menos').click(function(e) {
       if (parseInt(qtd.text()) > 0) {
         var novaQtd = parseInt(qtd.text()) - 1;
         qtd.text(novaQtd);
         total.text("R$ " + (novaQtd * valuePizza).toFixed(2))
         if(novaQtd == 0){
           pizza.removeClass("pizzaselecionada");
           pizza.addClass("pizzadisponivel");

           }
       }
     });

   });

      Calabresa 29,90

    <button id="mais">mais</button>
    <button id="menos">menos</button>
    0
    R$0,00


text:
Q: get model object as json response asp net mvc 4 What i want to achieve

*

*Initiate jQuery ajax get request if radio button is selected

*Retrieve Model object as json response with values

*Using that model object display data on razor view

I am stuck in third step.How can i use model object to display data on razor view
P.S. I am able to get alert as "Building No : 1" from my ajax code
JS
$('input[name=PerAddress]').on('change', function () {
    if ($('input[name=PerAddress]:checked', '.form-group').val() == 'true') {
        $.ajax({
            url: "CAD",
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                alert(data.PresentAddress1);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }
});

Controller Action Method :
[HttpGet]
[ActionName("CAD")]
public JsonResult CustomerAddress()
{
    var model = new AccountOpeningComplete
    {
        PresentAddress1 = "Building No : 1", // To be later retrieve from database
        PresentAddress2 = "Mumbai", // To be later retrieve from database
        PresentPostalCode = "497989", // To be later retrieve from database
        CityList = new SelectList(DataAccess.DAL.DropDownValues("City"), "Value", "Text"),
        ProvinceList = new SelectList(DataAccess.DAL.DropDownValues("Province"), "Value", "Text"),
        CountryList = new SelectList(DataAccess.DAL.DropDownValues("Country"), "Value", "Text")
    };
    return Json(model, JsonRequestBehavior.AllowGet);
}

Razor View
@Html.LabelFor(m => m.PresentAddress1, new { @class = "col-xs-6 col-md-3 control-label" })

    @Html.TextBoxFor(m => m.PresentAddress1, new { @class = "form-control" })

A: Based on your code, if you are able to get response correctly the data object on success is the javascript object as you have give json as datatype in your ajax call.
Now, as such you are only returning json from your asp.net mvc controller, you need to bind those new returned values to the controls/elements in your razor view i.e. html.
So. in case of PresentAddress1 textbox, you need to add this code in your success block:
success: function (data) {
                $("#PresentAddress1").val(data.PresentAddress1);
            }

You will have to take values from data javascript object and set those in respective controls.
Your other options are:
1) Return a partial view with new data to get rid of setting values to controls individually as done above. So, you will need to set datatype for html support and just replace the view with data. Example is below:
$.ajax({
    url: "CAD",
    type: 'GET',
    dataType: 'html',
    success: function (data) {
        $('#shell').html(data); //where shell is the id of the container that you want to update with the response from your controller.
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

2) Use two way data binding library like knockoutjs where you can request JSON data and directly bind with controls in your view. Recommended

A: You have two alternatives:

*

*Load the JSON data into pre-existing divs using jQuery in the existing view:
$("#PresentAddress).val(data.PresentAddress1);

where you have

*

*Call a partial view from your controller. This will return an HTML formatted string to your AJAX call which you can then assign to an empty div.
$("#AllContent).html(returnedValue);


text:
Q: Ionic 3 Deep link opening any link issue I have an Ionic 3 app, I installed the ionic-plugin-deeplinks plugin and it works for what I want. When I press on a certain link in an email, it opens my app and redirects it to the necessary page. However, I have some URL on the web version of the app that has target="_blank" on them. Whenever I click on those, it opens the app instead of a new tab. I don't want it to open the app or ask me to open the app in those situations because it has nothing to do with the app. Just open the link in a new tab. I've tried a million things but I can't find any solution sadly...
Here's my code in config.xml.
    <plugin name="ionic-plugin-deeplinks" spec="^1.0.15">
    <variable name="URL_SCHEME" value="myapp123" />
    <variable name="DEEPLINK_SCHEME" value="https" />
    <variable name="DEEPLINK_HOST" value="app.myapp123.com" />
    <variable name="ANDROID_PATH_PREFIX" value="/" />
    <variable name="ANDROID_2_PATH_PREFIX" value="/" />
    <variable name="ANDROID_3_PATH_PREFIX" value="/" />
    <variable name="ANDROID_4_PATH_PREFIX" value="/" />
    <variable name="ANDROID_5_PATH_PREFIX" value="/" />
    <variable name="DEEPLINK_2_SCHEME" value=" " />
    <variable name="DEEPLINK_2_HOST" value=" " />
    <variable name="DEEPLINK_3_SCHEME" value=" " />
    <variable name="DEEPLINK_3_HOST" value=" " />
    <variable name="DEEPLINK_4_SCHEME" value=" " />
    <variable name="DEEPLINK_4_HOST" value=" " />
    <variable name="DEEPLINK_5_SCHEME" value=" " />
    <variable name="DEEPLINK_5_HOST" value=" " />
</plugin>

I want this link to act normally
Random URL

but this link to ask or open the Ionic app
 Random URL

Is there a way to set this up?

A: I use another plugin to achieve the same:
<plugin name="cordova-plugin-customurlscheme" spec="^4.3.0">
    <variable name="URL_SCHEME" value="myapp123" />
</plugin>

After that you can create links like "myapp123://path-to-page".
So the protocol is "myapp123" instead of https.
In that way URL's like https://app.myapp123.com/ won't be caught anymore by your app.
More info on installation can be found here:
https://github.com/EddyVerbruggen/Custom-URL-scheme
One warning though: ionic 3 deeplinking for reset password : there seems to be an issue when using this technique in combination with gmail.


text:
Q: Recursive duplicate removal from a type list causes compiler out heap space error (VS2017) I tried to strip down as much code as I could from my actual project. This is the minimal code required to reproduce this error.
It seems the compiler needs exponentially more space the more types are added to the base type list.
Why is that? and
Any ideas how to work around this limitation?
The code constructs a flattened type list from other type lists and types and removes duplicates to provide a unique id for each type registered in the list.
I need this code to work with at least 30-50 types in the type list. The purpose of the code is to provide a runtime type reflection system for explicitly listed types like in this example:
#include <tuple>

// Utils
// Type for concatenated tuples
template<typename... input_t> using tuple_cat_t = decltype(std::tuple_cat(std::declval<input_t>()...));

// Helper to check if a type is contained in a tuple already
template <typename T, typename Tuple> struct contains;
template <typename T, typename... Us> struct contains<T, std::tuple<Us...>> : std::disjunction<std::is_same<T, Us>...> {};
template< class T, class U > inline constexpr bool contains_v = contains<T, U>::value;

// Filter Code:
template <class Out, class In> struct filter_duplicates;

// Partial spezialization for the recursive deduction to end (when input tuple is empty)
template <class Out> struct filter_duplicates<Out /*finished filtered output tuple*/, std::tuple<> /*empty input tuple*/>
{
    using filtered_tuple_t = Out;

    // The filter function deduction ends here if the input tuple is empty (every element checked). In this case _In is the found filtered output tuple
    static constexpr Out& filter(Out&& _In) { return _In; }
};

/* Filter template that is used as long the input tuple is not empty.
It builds the output tuple by recursively checking every element in the
input tuple and deciding whether is can be added to the output tuple and
then continuous deduction with the next input element until the
filter_duplicates definition above matches. */
template <class... OutTypes, class InTest, class... InRest>
struct filter_duplicates<std::tuple<OutTypes...>, std::tuple<InTest, InRest...>>
{
    // contained is true if the InTest element from the input tuple is contained in the output tuple already
    static constexpr bool contained = contains_v<InTest, std::tuple<OutTypes...>>;
    // depending on the condition above either add_t or rem_t is used (which adds InTest to the output tuple or not
    using add_t = filter_duplicates<std::tuple<OutTypes..., InTest>, std::tuple<InRest...>>;
    using rem_t = filter_duplicates<std::tuple<OutTypes...        >, std::tuple<InRest...>>;
    // These types resolve to a tuple<...> with either added or remove InTest type
    using add_tuple_t = typename add_t::filtered_tuple_t;
    using rem_tuple_t = typename rem_t::filtered_tuple_t;
    // This type is the result of the check if InTest is contained, so its either add_tuple_t or rem_tuple_t
    using filtered_tuple_t = std::conditional_t<contained, rem_tuple_t, add_tuple_t>;
    // This type is the result of the check if InTest is contained, so its either the filter_duplicate type containing InTest in the OutTypes or not
    using filter_t = std::conditional_t<contained, rem_t, add_t>;

    // The function takes the unfiltered tuple instance and returns the filtered tuple instance (duplicate tuple entries are filtered)
    static constexpr auto filter(std::tuple<OutTypes..., InTest, InRest...>&& _In)
    {
        return filter_seq<contained>(std::make_index_sequence<sizeof...(OutTypes)>{}, std::make_index_sequence<sizeof...(InRest) + 1 - contained>{}, std::move(_In));
    }

    // The input tuple for the next deduction step is built by getting all tuple elements except "InTest" in the case it is in the output list already
    template<size_t _Skip, size_t... TIndicesOut, size_t... TIndicesIn, class... In>
    static constexpr auto filter_seq(std::index_sequence<TIndicesOut...>, std::index_sequence<TIndicesIn...>, std::tuple<In...>&& _In)
    {
        return filter_t::filter(std::make_tuple(std::move(std::get<TIndicesOut>(_In))..., std::move(std::get<sizeof...(TIndicesOut) + _Skip + TIndicesIn>(_In))...));
    }
};
// Some declarations for easier use
template <class T> using no_duplicates_tuple_t = typename filter_duplicates<std::tuple<>, T>::filtered_tuple_t;
template <class T> using no_duplicates_filter = filter_duplicates<std::tuple<>, T>;
// Function to return a filtered tuple given an unfiltered tuple. It uses the filter type above to construct the new tuple with correct type
template<class... In> constexpr auto make_tuple_no_duplicates(std::tuple<In...>&& _In)
{
    return no_duplicates_filter<std::tuple<In...>>::filter(std::move(_In));
}

// Type info wrapper (In my project it contains functions like construct or copy and much more for the runtime type reflection)
struct IType {};
struct STypeUnknown : IType { using TType = void; };
template<typename T> struct SType : IType { using TType = T; };

// STypeList forward declation
template <typename...> struct STypeList;

// This type unwrappes a given STypeList into a flattened plain tuple, so it can be concatenated with other STypeLists or Types

// In case the given type is just a normal type, it is converted into a tuple with a single element: tuple<T> (so tuple_cat() can be used later)
template<typename T> struct SUnwrapTypeList
{
    using tuple_type = std::tuple<T>;
    tuple_type as_tuple;
    SUnwrapTypeList(T& _Value) : as_tuple{ _Value } {}
};
// In case the Type is a STypeList its filtered and flattened tuple is used
template<typename... TypeDefs> struct SUnwrapTypeList<STypeList<TypeDefs...>>
{
    using TypeList = STypeList<TypeDefs...>;
    using tuple_type = typename TypeList::TTupleDef;
    tuple_type as_tuple;
    SUnwrapTypeList(TypeList& _Value) : as_tuple(_Value.infos) {}
};

// The actual STypeList that can be constructed from other STypeList instances
template<typename... TypeDefs> struct STypeList
{
    // Defines the actual underlying flattened and filtered tuple<...>
    using TTupleDef = no_duplicates_tuple_t<tuple_cat_t<typename SUnwrapTypeList<TypeDefs>::tuple_type...>>;
    // Type count after flattening and filtering
    static constexpr size_t TypeCount() { return std::tuple_size<TTupleDef>::value; }
    // helper to get an index_sequence for the filtered flattened tuple
    static constexpr auto type_seq = std::make_index_sequence<TypeCount()>{};

    // All type infos given via the STypeList constructor, flattened and filtered
    TTupleDef infos;

    // This constructor is used in the example below. It can take arbitrary STypeLists or SType<XXX> lists and flattens and filteres them using the code above
    STypeList(TypeDefs... _Types) noexcept : STypeList(type_seq, std::tuple_cat(SUnwrapTypeList<TypeDefs>(_Types).as_tuple...)) {}
    STypeList(TTupleDef& _Types) noexcept : STypeList(type_seq, _Types) {}
    STypeList(STypeList&& _Move) noexcept : STypeList(type_seq, _Move.infos) {}
    STypeList(const STypeList& _Copy) noexcept : STypeList(type_seq, _Copy.infos) {}

private:
    // Final constructor initializing infos. TListIndices is the index_sequence for the filtered and flattened tuple, while TType is the unfiltered flattened tuple from the constructors above
    template <size_t... TListIndices, typename... TTypes>
    STypeList(std::index_sequence<TListIndices...>, std::tuple<TTypes...>&& _Types) noexcept
        : infos{ make_tuple_no_duplicates(std::move(_Types)) }
    { }

    // Final constructor initializing infos via copy
    template <size_t... TListIndices>
    STypeList(std::index_sequence<TListIndices...>, const TTupleDef& _Infos) noexcept
        : infos(_Infos)
    { }
};

// Test Code:
struct STestType1 { };
struct STestType2 { };

static inline auto TypeListBase = STypeList
(
    STypeUnknown()
    ,SType<bool>()
    ,SType<float>()
    ,SType<double>()
    ,SType<int>()
    ,SType<long>()
    ,SType<char>() //<- comment in to produce error
);

static inline auto TypeListA = STypeList
(
    TypeListBase
    ,SType<STestType1>()
);

static inline auto TypeListB = STypeList
(
    TypeListBase
    ,SType<STestType2>()
);

static inline auto TypeListAB = STypeList
(
    TypeListA,
    TypeListB
);

int main()
{

}

When trying to compile the output will be (using Visual Studio 2017, problem seems to occur in gcc and VS2019 as well):
1>------ Build started: Project: VsTest, Configuration: Debug x64 ------
1>VsTest.cpp
1>XXX\vstest.cpp(20): fatal error C1060: compiler is out of heap space
1>Done building project "VsTest.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

A: The problem I see is that your filter_duplicate, the recursive specialization, ever follows both cases: the case the InTest is in the OutTypes... list and the case it isn't.
This force the compiler to follows a lot of dead cases.
Suggestion: split the recursive specialization in two recursive specializations: the version "is in list" and the "isn't in list" one.
I suggest an additional helper template
template <typename, typename>
struct with_duplicate : public std::false_type
 { };

template <typename OTuple, typename IT0, typename ... ITs>
struct with_duplicate<OTuple, std::tuple<IT0, ITs...>>
   : public contains<IT0, OTuple>
 { };

Now the filter_duplicates declaration, with an additional template defaulted parameter (based on with_duplicate)
template <typename Out, typename In, bool = with_duplicate<Out, In>::value>
struct filter_duplicates;

The ground case remain almost the same (just added the third template parameter)
// ground case
template <typename Out>
struct filter_duplicates<Out, std::tuple<>, false>
 {
   using filtered_tuple_t = Out;
   static constexpr Out& filter(Out&& _In) { return _In; }
 };

Now the recursive case "is in list"
// with duplicate case
template <typename... OutTypes, typename InTest, typename... InRest>
struct filter_duplicates<std::tuple<OutTypes...>,
                         std::tuple<InTest, InRest...>,
                         true>
 {
   using filter_t = filter_duplicates<std::tuple<OutTypes...>,
                                      std::tuple<InRest...>>;

   using filtered_tuple_t = typename filter_t::filtered_tuple_t;

   static constexpr auto
      filter (std::tuple<OutTypes..., InTest, InRest...>&& _In)
    { return filter_seq(
          std::make_index_sequence<sizeof...(OutTypes)>{},
          std::make_index_sequence<sizeof...(InRest)>{},
          std::move(_In)); }

   template <std::size_t... TIndicesOut,
             std::size_t... TIndicesIn, typename... In>
   static constexpr auto filter_seq (std::index_sequence<TIndicesOut...>,
                                     std::index_sequence<TIndicesIn...>,
                                     std::tuple<In...>&& _In)
    { return filter_t::filter(std::make_tuple(
             std::move(std::get<TIndicesOut>(_In))...,
             std::move(std::get<sizeof...(TIndicesOut) + 1u + TIndicesIn>(_In))...)); }
 };

and the recursive case "isn't in list"
// without duplicate case
template <typename... OutTypes, typename InTest, typename... InRest>
struct filter_duplicates<std::tuple<OutTypes...>,
                         std::tuple<InTest, InRest...>,
                         false>
 {
   using filter_t = filter_duplicates<std::tuple<OutTypes..., InTest>,
                                      std::tuple<InRest...>>;

   using filtered_tuple_t = typename filter_t::filtered_tuple_t;

   static constexpr auto
      filter (std::tuple<OutTypes..., InTest, InRest...>&& _In)
    { return filter_seq(
          std::make_index_sequence<sizeof...(OutTypes)>{},
          std::make_index_sequence<sizeof...(InRest) + 1u>{},
          std::move(_In)); }

   template <std::size_t... TIndicesOut,
             std::size_t... TIndicesIn, typename... In>
   static constexpr auto filter_seq (std::index_sequence<TIndicesOut...>,
                                     std::index_sequence<TIndicesIn...>,
                                     std::tuple<In...>&& _In)
    { return filter_t::filter(std::make_tuple(
             std::move(std::get<TIndicesOut>(_In))...,
             std::move(std::get<sizeof...(TIndicesOut) + TIndicesIn>(_In))...)); }
 };

Not sure all indexes in filter() and filter_seq() methods are correct (check yourself) but, this way, the compiler should avoid a lot of unuseful implementations.
In my Linux platform, splitting the recursive specialization, I've reduced the compilation time (clang++ and g++, in sequence) from 51",1 to 1",6. No exact data abut memory consumption but I can say that is greatly reduced.

A: And now... for something completely different...
What about avoiding the recursive sequence of filter() and filter_seq() calling using a variadic list of bool that say which element extract and which are duplicates?
I mean... given the same helper class with_duplicate in the other answer
template <typename, typename>
struct with_duplicate : public std::false_type
 { };

template <typename OTuple, typename IT0, typename ... ITs>
struct with_duplicate<OTuple, std::tuple<IT0, ITs...>>
   : public contains<IT0, OTuple>
 { };

I propose a filter_duplicate declaration a little more complicated
template <typename Out, typename In,
          typename = std::integer_sequence<bool>,
          typename = std::index_sequence<>,
          bool = with_duplicate<Out, In>::value>
struct filter_duplicates;

Now the two recursion cases, cases "is in list" and "isn't in list", that simply inherit from the old filter_t types
template <typename... OutTypes, typename InTest, typename... InRest,
          typename Is, bool ... Bs>
struct filter_duplicates<std::tuple<OutTypes...>,
                         std::tuple<InTest, InRest...>,
                         std::integer_sequence<bool, Bs...>,
                         Is, true>
   : public filter_duplicates<std::tuple<OutTypes...>,
                              std::tuple<InRest...>,
                              std::integer_sequence<bool, Bs..., true>,
                              std::make_index_sequence<sizeof...(Bs)+1u>>
 { };

template <typename... OutTypes, typename InTest, typename... InRest,
          typename Is, bool ... Bs>
struct filter_duplicates<std::tuple<OutTypes...>,
                         std::tuple<InTest, InRest...>,
                         std::integer_sequence<bool, Bs...>,
                         Is, false>
   : public filter_duplicates<std::tuple<OutTypes..., InTest>,
                              std::tuple<InRest...>,
                              std::integer_sequence<bool, Bs..., false>,
                              std::make_index_sequence<sizeof...(Bs)+1u>>
 { };

Now the complex part is the ground case that receive a variadic list of bool, one for every type in the original tuple, Bs..., where true is "duplicate type" and false is "no duplicate type"
// ground case
template <typename Out, bool ... Bs, std::size_t ... Is>
struct filter_duplicates<Out, std::tuple<>,
                         std::integer_sequence<bool, Bs...>,
                         std::index_sequence<Is...>, false>
 {
   using filtered_tuple_t = Out;

   template <bool B, std::size_t I, typename Tpl>
   static constexpr auto getTplCond (Tpl && t)
    {
      if constexpr ( B ) // duplicate
         return std::tuple<>{};
      else // not duplicate
         return std::tuple{std::get<I>(t)};
    }

   template <typename ... Ts>
   static constexpr std::enable_if_t<sizeof...(Ts) == sizeof...(Bs), Out>
       filter (std::tuple<Ts...> && _In)
    { return std::tuple_cat( getTplCond<Bs, Is>(_In)... ); }
 };

This way you call a single filter() method that isn't recursive but is recursively inherited.
Also filtered_type_t is recursively inherited.


text:
Q: Optional Discount textbox gives 0 value I'm trying to calculate the discount of totalAmount by the sum of quantity
and unitPrice.The thing is discount can be optional.It can be use or not it depends on the user if he/she going to input some value in the discount textbox.
What I did is leave the discount textbox empty if I am not going to input a value on it,
but my totalAmount still gives me a zero value for an output.
 protected void btnCalculate_Click(object sender, EventArgs e)
    {
        double quantity, unitPrice,totalAmount;

        double discount;

        double d;

        bool canProcess = true;

        //Quantity
        if (!double.TryParse(lblQuantity.Text, out quantity))
        {
            //Conversion Failed
            string script = "alert(\"Quantity cannot be converted\");";

            ScriptManager.RegisterStartupScript(this, GetType(),
                "ServerControlScript", script, true);
        }
        //UnitPrice
        if (!double.TryParse(txtUnitPrice.Text, out unitPrice))
        {
            //Conversion Failed
            string script = "alert(\"Unit Price cannot be converted\");";

            ScriptManager.RegisterStartupScript(this, GetType(),
                "ServerControlScript", script, true);
        }
        if (!double.TryParse(txtDisc.Text, out discount))
        {
            //Conversion Failed
            string script = "alert(\"discount cannot be converted\");";

            ScriptManager.RegisterStartupScript(this, GetType(),
                "ServerControlScript",script,true);
        }
        if (canProcess)
        {
          d = quantity * unitPrice;

            totalAmount = ((d*discount)/100);
            lblTotalAmount.Text = totalAmount.ToString();
        }
    }
    //#calculator end
}

A: If you want discount to be optional, than decide how you want to calculate your amount:
    if (canProcess)
    {
        d = quantity * unitPrice;

        if(discount == 0)
        {
            totalAmount = d;// any calculation
        }
        else
        {
            totalAmount = ((d*discount)/100);
        }

        lblTotalAmount.Text = totalAmount.ToString();
    }

A: Of course you need to check first discount is greater then 0, then you can calculate the total amount
if (canProcess)
{
    d = quantity * unitPrice;

    if(discount == 0)
    {
        totalAmount = d;
    }
    else
    {
        totalAmount = ((d*discount)/100);// if here d is 0 your total amt will be 0.
    }

    lblTotalAmount.Text = totalAmount.ToString();
}


text:
Q: Use fully qualified type names in UML class diagrams According to UML (or its standard usage), it is better to use fully qualified names (namespace::type_name) for attribute types and operation parameters in the class diagrams. I have special interest in third party data types. For example: I'm working with OpenCV in my application, should I put cv::Mat or just Mat in the class diagrams?
Thanks in advance for any help and/or suggestion.

A: It depends on the readership. If your diagrams are all in a certain context where you can expect people to know that Mat is an OpenCV class, you can probably omit it. Further, UML tools are able to optionally show the FQN, so you can turn that on or off.


text:
Q: Issue with 'unknown advertising packet type, invalid advertising data, advertising length corrected' Linux, Raspberry Pi, iOS, Homepod I have been using a small c program I wrote to get bluetooth ble advertising packets from low cost bluetooth temperature sensors. A number of these sensors broadcast their temperature and humidity readings in either type 0 or type 4 bluetooth advertising packets. This gives me the ability to get this data from low cost sensors and not have to use the vendors app or cloud services.
This has been working great for months using a raspberry pi to collect this data and publish to MQTT. Recently the program started to fail. I tracked down the issue to the bluetooth stack crashing after some number and combination of it logging errors like these:
Bluetooth: hci0: unknown advertising packet type: 0xdf
Bluetooth: hci0: unknown advertising packet type: 0xd8
Bluetooth: hci0: Dropping invalid advertising data
Bluetooth: hci0: advertising data len corrected

I see these errors when I run my program on:
ARM Raspbian GNU/Linux 10 (buster)
Intel Ubuntu 18.04.5 LTS
The bluetooth stack failure and reload seems to occur most often on a Raspberry Pi with a USB Bluetooth adapter. A lower occurrence on Raspberry Pi using internal UART Bluetooth adapter, or any adapter on a beefier i5 x86 Ubuntu machine. However all log some combo of the above messages.
Here is where this starts to get a bit weird. I'm pretty sure the actions that are causing these messages and crashes are my using my iPhone to control my HomePods.....
This is moved quickly out of my pay grade. I have seen some reports of some similar messages well prior to HomePods at seem to indicate that the rate of advertising packets is exceeding some internal of Linux bluetooth stack. But, as I said, my system had been running for months with no issues. Until, I think, I introduced the HomePods into my home, and even then I think it might have been a new version of HomePod firmware that started the issues.
Any ideas or direction to explore would be appreciated.
Thanks!


text:
Q: SQL & PHP Unique Number I will be using the GET method with NFC to pull some data, I want to populate a database with a ton of unique digits, I don't mind them having keywords in them like
TOM05543
TOM04423
KEL04432
KAL43242

What would be the best method of doing this and filling my database with these unique ID's before hand?

A: Create a PHP function which can generate a random apha numeric code and check that code exist in DB table or not. If exist then function call recursively until unique code will be generated. And insert uniquely generated record in DB table.
<?php
//DB connection
$con=mysqli_connect("localhost","my_user","my_password","my_db");

//Function to generate unique alpha numeric code
function generateRandomNumer($con,$len=8){
    $randomString = substr(MD5(time()),$len);

    //Check newly generated Code exist in DB table or not.
    $query = "select * from table_name where col_name='".$randomString."'";
    $result=mysqli_query($con,$query);
    $resultCount=mysqli_num_rows($result);

    if($resultCount>0){
        //IF code is already exist then function will call it self until unique code has been generated and inserted in Db.
        generateRandomNumer($con);
    }else{
        //Unique generated code will be inserted in DB.
        mysqli_query($con,"INSERT INTO Persons (col_name) VALUES ('".$randomString."')");
    }
}

//Loop to insert number of unique code in DB.
//NUM_OF_RECORD_YOU_WANT_TO_INSERT define constant which contain number of unique codes you wants to insert in DB.
for($i=0;$i<NUM_OF_RECORD_YOU_WANT_TO_INSERT;$i++){
    generateRandomNumer($con);
}
?>

A: You may use the solution offered at http://guid.us/GUID/PHP which is :
function getGUID(){
    if (function_exists('com_create_guid')){
        return com_create_guid();
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
            .substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12)
            .chr(125);// "}"
        return $uuid;
    }
}

More information on GUIDs can be found at https://en.wikipedia.org/wiki/Globally_unique_identifier
I do realise that a GUID is not technically unique, however the chance that a good random number generator generates 2 identical GUIDs is about 1 in 2^122 which means if you generate a GUID every 1 millisecond you'd hit the first duplicate in about 10^26 years.
This has the advantage of not needing to check the database if the key is already there or not since we assume it's not.


text:
Q: PostgreSQL Docker zsh: root not found I'm following guide for Docker, and I'm stuck on creating Postgresql DB, as I use this command
docker run  -it  \
  -e POSTGRES_USER ="root" \
  -e POSTGRES_PASSWORD = "root" \
  -e POSTGRES_DB = "ny_taxi" \
  -v /Users/ruslanpilipyuk/Desktop/data-engineering-zoomcamp-main/week_1_basics_n_setup/2_docker_sql/ny_taxi_postgres_data:/var/lib/postgresql/data \
  -p 5432:5432 \
  postgres:13

however somehow it gives error:
zsh: root not found

But I'm sure that this root exists as I just copied it, maybe I have stated it wrongly or something?


text:
Q: how to fix: Array index is out of range i have this problem
Have the function WildcardCharacters(str) read str which will contain two strings separated by a space. The first string will consist of the following sets of characters: +, , and {N} which is optional. The plus (+) character represents a single alphabetic character, the asterisk () represents a sequence of the same character of length 3 unless it is followed by {N} which represents how many characters should appear in the sequence where N will be at least 1. Your goal is to determine if the second string exactly matches the pattern of the first string in the input.
i have the solution with js, but now i am trying to solve with swift, i need your help.
this work with js, and i'm using swift v4.2
code with js
function WildcardCharacters(str) {

  // code goes here
  let strArr= str.split(' ')
  let specChar = strArr[0]
  let charStr = strArr[1].split('')

  let arr = specChar.split('')
  let letters = /^[A-Za-z]+$/
  let i = 0
  while(i< arr.length){
      if(arr[i] == '+'){
          if(!charStr[0].match(letters)) return "false"
         charStr = charStr.slice(1,charStr.length)
      }
      else if(arr[i] == '*'){
          let curr = charStr[0]
          let j = 1, k = 0
          if(arr[i+1] != undefined && arr[i+1] == '{'){
              k = arr[i+2]
              i = i+4
          }else{
              k = 3
              i++
          }

          while(j < k){
            charStr = charStr.slice(1,charStr.length)
            if(charStr[0] != curr) return "false"
            j++
          }
          charStr = charStr.slice(1,charStr.length)
          continue
      }
      i++
    }
    if(charStr.length != 0) return 'false'
     return "true"
}

// keep this function call here
WildcardCharacters("+++++* abcdemmmmmm");

code by Smakar20 (user github)
code with swift
extension String {

    func isAlphanumeric() -> Bool {
        return self.rangeOfCharacter(from:         CharacterSet.alphanumerics.inverted) == nil && self != ""
    }

    func isAlphanumeric(ignoreDiacritics: Bool = false) -> Bool {
        if ignoreDiacritics {
            return self.range(of: "[^a-zA-Z0-9]", options:     .regularExpression) == nil && self != ""
        }
        else {
            return self.isAlphanumeric()
        }
    }

}

func wild (str: String) -> String
{
    let strArr = str.split(separator: " ")
    let specChar = strArr[0]
    var charStr = Array(strArr[1])

    let arr = Array(specChar)

    var i = 0

    while (i<arr.count)
    {
        if arr[i] == "+"
        {
            if !String(charStr[0]).isAlphanumeric()
            {
                return "false"
            }
            charStr = Array(charStr[0...charStr.count])
        }
        else if arr[i] == "*"
        {
            let curr = charStr[0]
            var j = 0
            var k = 0
            if String(arr[i+1]).isAlphanumeric() != true && arr[i+1] == "{"
            {
                k = Int(String(arr[i+2]))!
                i = i+4
            }
            else
            {
                k = 3
                i += 1
            }
            while (j<k)
            {
                charStr = Array(charStr[1...charStr.count])
                if charStr[0] != curr
                {
                    return "false"
                }
                j += 1
            }
            charStr = Array(charStr[1...charStr.count])
            continue
        }
        i += 1
    }
    if charStr.count != 0
    {
        return "false"
    }
    return "true"
}

wild(str: "+++++* abcdemmmmmm")

if str is "++*{5} gheeeee" then the second string in this case does match the pattern, so your program should return the string true. If the second string does not match the pattern your program should return the string false.
heeelp


text:
Q: Update a column that is similar to all tables - MYSQL A this point I have a database with almost 1000 tables, several of them have a lat lng field and a user with a ID ( every table that has that lat lng has the ID field also ) has changed his location.
Now I have to update all the tables but I haven't designed this database ( basically I'm new at this job and my boss threw this hot bowl to me ) so I don't know even where to start.
Is there a way to change the data on every tables that have a latlng field and share this ID number ?
For example: if ID = 1024 and the table has a latlng cell, update that latlng cell to the new value.

A: So, as this had some views, I'll post my solution :
In order to update all tables that share a id number ( for instance, I have one table for each service and the id and the address of every client that bought it at some point, one client had his location changed so ), in order to update this I made a php script that goes like this:
    <?php
    // connecting !
    $con =mysqli_connect("localhost","my_username","my_password","database");

    // convert code
    $showTables = mysqli_query($con,"SHOW TABLES");
    while ($row = mysqli_fetch_array($showTables))
    {
    foreach ($row as $key => $table)
    {
        mysqli_query($con,"UPDATE `". $table . "` SET `addres`='new_address' WHERE `id`= '27' ");
        echo "UPDATE `". $table . "` SET `address`='new_address' WHERE `id`= '27' "; // for testing purposes - you can delete this!
    }
}
?>

This is it, it made me want to break the pc at some point but when you see it, it is simple!
Best regards.


text:
Q: sum value column b only if value in column a is unique looking for direction on how to do the following, thank you in advance for any insight provided:
I want to sum the total values in column C (Total Lines per order) ONLY once per the value in column A (Sales Order). So Sales Order "A" appears three times in column A, however I only want to sum the corresponding value in column C one time as part of the sum, and not include the duplicate lines.
I could use the "Delete Duplicates" function, but I want to keep the unique item Part Numbers on each line on the report.
Example:
Sales Order "A" has 3 total Lines
Sales Order "B" has 4 total lines
Sales order "C" has 2 total lines
Sales Order "D" has 5 total lines
                  = 14 total lines

I've attached an example list in the link Below

A: The formula you want is:
=SUMPRODUCT(C2:C14/COUNTIF(A2:A14,A2:A14))


text:
Q: debo hacer un programa que verifique cuantas veces se repite un carácter consecutivamente en la cadena y eliminar las repeticiones Este es el código de prueba que hice, pero esto debe servir con cualquier combinación de letras que se le ingrese, ósea con un input, pero no se como hacer para que sea eso lo que el diccionario tenga en cuenta.
letras = ["a", "a", "c", "a"]

diccionario = {}
contador = 0

for letra in letras:
   if letra == "a":
       contador += 1
       diccionario[letra] = contador
   else:
       contador -= 1

for llave, valor in diccionario.items():
  print(f"{llave}\n{valor}")

Y esta es una imagen de ejemplo de la entrada y la salida que debe tener el programa, agradecería su ayuda y correciones.

A: Esto te podria servir:

letras = ["a", "a", "c", "a"]
diccionario = {}

for letra in letras:
    if(letra in diccionario):
        diccionario[letra] +=1
    else:
        diccionario[letra] = 1

no es necesario el contador y solo debes buscar si la letra ya esta en el diccionario y si no se encuentra entonces la agregas al diccionario en 1.
y para imprimirlas puedes hacer esto:
print(list(diccionario))
print(list(diccionario.values()))

o:
for llave,valor in diccionario.items():
    print(llave, end="\t")

print("")

for llave,valor in diccionario.items():
    print(valor,end="\t")

Depende de como te lo pidan e incluso puede haber alguna mejor forma de imprimirlo..
te dejo un enlace que te puede servir:
https://j2logo.com/python/tutorial/tipo-dict-python/#dict-in

A: Bueno yo lo implemente de la siguiente manera:
elem = list(map(str, input().split()))

Declaro una variable llamada elem donde almacenare los caracteres ingresado por teclado, utilizo el objecto iterador map.
Despues declaro dos listas donde en una almacenare las letras y en otro la cantidad de veces que se repite.
Despues declaro un auxiliar llamado aux donde alamcenare en primera instancia el primer elemento ingresado aux = elem[0].
Por ultimo declaro e inicializo una variable llamada c conde se almacenara la cantidad de veces que se repite un caracter es como un contador.
lista_elemento = []
lista_cantidad = []
aux = elem[0]
c=0

Bueno aca viene lo mas importante espero ser claro y ojo se que puede mejorar el algoritmo y la logica...
for i in range(len(elem)):
  if(elem[i]==aux):
    c=c+1
  else:
    lista_elemento.append(aux)
    lista_cantidad.append(c)
    c=1
    aux=elem[i]
lista_elemento.append(elem[i])
lista_cantidad.append(c)

Primero en el for voy a recorrer cada uno de los elementos que se almacenaron en elem.
Despues en if(elem[i]==aux): voy a verificar si el caracter de mi primera posicion es igual a auxiliar si es asi que contador incremente c=c+1.
Lo logica aca es .. mientras se cumpla la condicion contador va a incrementar.
Despues Si no se cumple la condicion almacenamos el caracter y la cantidad acumulada en el if anterior en su lista respectiva, para despues limpiarlo y darle un valor de  c=1 porque ya que estamos en el nuevo caracter por eso le doy a c=1, despues aux=elem[i] a la varaible auxiliar cambia de caracter y lo asigno al nuevo caracter que voy a trabajar.
Por utlimo tenemos lo siguiente:
lista_elemento.append(elem[i])
lista_cantidad.append(c)

Bueno lo que hice fue ya que al ultimo caracter y su contador, el algoritmo de arriba no lo guardaba, lo tuve que hacer al final ya se va a hacer el ultimo recorrido que te bota el bucle y lo almacene como lo vez pero agregando el elem[i] y despues su cantidad c. eso es todo ..
Después ya solo mostramos los resultados en el bucle for..
for i in range(len(lista_elemento)):
  print(lista_elemento[i],end=" -> ")
  print(lista_cantidad[i])

ejemplo:
D D D D T T T D A A T T T A A A U Y U U U
D -> 4
T -> 3
D -> 1
A -> 2
T -> 3
A -> 3
U -> 1
Y -> 1
U -> 3

A: Una alternativa  a lo que deseas es hacerlo utilizando expresiones regulares de la siguiente forma:
Con la siguiente expresión regular: (\w)\1* indicamos que capture una letra \w. (\w)  agrupa cada letra. \1 seguido  de la letra capturada anteriormente. En pocas palabras la expresión (\w)\1* va a capturar todas las letras iguales.
Eso nos basta  para programarlo en  Python:
# importamos la libreria de expresiones regulares
import re
# nuestra expresion  regular
regex = r"(\w)\1*"

#  texto de  prueba
test_str = "TTTTTTTDDDDDDYYYYYYYUUUUDDIII"

#test_str =  "YYYTAAYYYYAAADDDDBBBBUUUAAAAG"
#test_str  = "BBBBGGGGUAAAAUUUUUUUGGGGDDDYAAAA"

letras=""
numeros=""

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):
    numeros+=str(match.end() - match.start())
    letras+=match.group(1)

print(letras)
print(numeros)

Con lo anterior obtenemos los resultados de la imagen que adjuntaste a tu pregunta.  Ahora si quieres contar cuantas letras se repiten en total. Le añades el diccionario al for para que acumule por letra.
Si  quieres manejar arreglos:
import re
regex = r"(\w)\1*"

test_arr = ['D','D','D','D','T','T','T','D','A','A','T','T','T','A','A','A','U','Y','U','U','U']

#test_arr = ['T','T','T','T','T','T','T','D','D','D','D','D','D','Y','Y','Y','Y','Y','Y','Y','U','U','U','U','D','D','I','I','I']
test_str = "".join(test_arr)

letras=[]
numeros=[]
diccionario={}
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
    numeros.append(match.end() - match.start())
    letras.append(match.group(1))
    cant = diccionario.get(match.group(1)) or  0
    diccionario[match.group(1)] = cant + (  match.end() - match.start()    )

print("".join(letras))

print("".join((str(x) for x  in  numeros)))
print(diccionario)


text:
Q: How to combine values in dict to new key/value pair, replacing None with empty string? I have a dictionary (d) like so:
d = {
'[primary_number]': '12345',
'[street_name]': 'Main',
'[street_predirection]': 'NW',
'[street_postdirection]': None,
'[street_suffix]': 'St',
'[secondary_number]': None,
'[secondary_designator]': None,
'[extra_secondary_number]': None,
'[zipcode]': '12345'
}

And I would like to create a new Key/Value pair called AddressStr that combines several (but not all) of the fields in d. I am trying to combine it with the following code:
d['AddressStr'] = d["[zipcode]"] + \
    d["[street_name]"] + \
    d["[primary_number]"] + \
    d["[secondary_number]"] + \
    d["[street_predirection]"] + \
    d["[street_postdirection]"] + \
    d["[street_suffix]"]

However, this produces the error:
can only concatenate str (not "NoneType") to str

Because [street_postdirection] = None. Ideally, I would like to just have a check/replace to change the None values in those 7 fields to '', but I'm not quite sure how to do that. I'd also like to do in place during the creation of d['AddressStr'], but if that's not possible I'm OK with that.

A: You can join the values that are not None:
keys = ["[zipcode]", "[street_name]", "[primary_number]",
        "[secondary_number]", "[street_predirection]", "[street_postdirection]",
        "[street_suffix]"]

d['AddressStr'] = ' '.join([d[key] for key in keys if d[key] is not None])

A: You could use the str() method and use the property that None behaves as false on a boolean check:
d['AddressStr'] = str(d["[zipcode]"] or '') + \
str(d["[street_name]"] or '') + \
str(d["[primary_number]"] or '') + \
str(d["[secondary_number]"] or '') + \
str(d["[street_predirection]"] or '') + \
str(d["[street_postdirection]"] or '') + \
str(d["[street_suffix]"] or '')


text:
Q: Return data from checked elements in UITableView using Navigation button I have a UITableView that show some elements on it.
The elements on the text field can be checked if the user clicks in any element.
I have the code for that and it works perfectly.
class MyTableViewController: UITableViewController {

    let foods = ["tomato", "cheese", "bread", "apple"]
    let cellReuseIdentifier = "cell"

    @IBOutlet weak var myTableView:UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "DONE", style: .done, target: self, action: #selector(self.avancar(sender:)))
    }

    @objc func avancar(sender: UIBarButtonItem) {
        print("DONE button clicked")
        print("myTableView.numberOfSections: \(myTableView.numberOfSections)")
        print("myTableView.numberOfRows: \(myTableView.numberOfRows(inSection: 0))")

        for i in 0..<foods.count {
            if tableView.cellForRow(at: [0, i])?.accessoryType == UITableViewCell.AccessoryType.none {
                print("item \(i) is UNchecked")
            } else {
                print("item \(i) is checked")
            }
        }

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return foods.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
        cell.textLabel?.text = foods[indexPath.row]
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("x: \(foods[indexPath.row])")
        print(indexPath)
        if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCell.AccessoryType.checkmark {
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.none
        } else {
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.checkmark
        }
    }

}

But what I want now is to return a string with all elements that are checked to a UITextField inside a UIViewController.
I want to put the following behaviour on it, when a user clicks on the TextField, the user must be redirected to a UITableView that show elements that can be checked it.
After the user click in any number of elements of the UITableView, the user will click on the DONE button that will get the text(string) of all checked elements in return it to the UITextField.
How can I return a String to the UITextField in the UIViewController.
Below you can find the images of the screen that I create.

Edit
I put another screenshot to show what my code is doing now.
.
I want to return the text that is checked, not selected.
ANOTHER EDIT
I was able to get the String result of the elements checked using the code below, now I still need to know how to return the data to the previous UIViewController
@objc func avancar() {
        textToReturn = ""

        for i in 0..<foods.count {
            if tableView.cellForRow(at: [0, i])?.accessoryType == UITableViewCell.AccessoryType.none {
                print("item \(i) is UNchecked")
            } else {
                textToReturn = textToReturn + foods[i] + ", "

            }
        }

        print("textToReturn: \(textToReturn)")

    }

A: Use a custom struct to maintain the selected status. This is the most convenient way
struct Food {
    let name : String
    var isSelected = false
}

Declare the datasource
let foods = [Food(name:"tomato"),
             Food(name:"cheese"),
             Food(name:"bread"),
             Food(name:"apple")]

In cellForRow set the accessory view according to the isSelected property
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return foods.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
    cell.textLabel?.text = foods[indexPath.row].name
    cell.accessoryType = foods[indexPath.row].isSelected ? .checkmark : .none
    return cell
}

In didSelect toggle the isSelected property in the data source and reload the row
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("x: \(foods[indexPath.row])")
    foods[indexPath.row].isSelected.toggle()
    tableView.reloadRows(at: [indexPath], with: .none)
}

In the action method filter the selected items, map them to their name and join them to one string.
@objc func avancar(sender: UIBarButtonItem) {
    print("DONE button clicked")

    let selectedItems = foods.filter{$0.isSelected}.map{$0.name}.joined(separator: ", ")
    print(selectedItems)
}