text:
Q: How to combine a list model to another model in ASP.NET MVC3 I have two models:
public class Model1
    {
        public int? Id { get; set; }
        public string Name{ get; set; }
        private IList<Model2> _model2;
    }

  public class Model2
        {
           public string Name2{ get; set; }
        }

JSON data for ajax call:
[
  {
    "Id": 1,
    "Name": "Foo",
    "Name2": "Foo2"
  },
  {
    "Id": 2,
    "Name": "Foo3",
    "Name2": "Foo4"
  }
]

Controller action:
public ActionResult Save(List<Model1> models)
        {
        }

In this way I do not get Name2 in controller action. Are there any way to get Name2 in controller?
I know it can be solved by creating another model. e.g
public class Model3
        {
            public int? Id { get; set; }
            public string Name{ get; set; }
            private Model2 _model2;
        }

But I don't want to create new model class.
thanks....

A: JSON data should be in this format
[
  {
    "Id": 1,
    "Name": "Foo",
    "_model2":[{"Name2": "Foo2"}]
  },
  {
    "Id": 2,
    "Name": "Foo3",
     "_model2":[{"Name2": "Foo4"}]
  }
]

A: You can derive Model1 from Model2 like this;
public class Model1:Model2
{
    public int? Id { get; set; }
    public string Name{ get; set; }
}

Now you should see Name2 as a property in Model1 and your Json should work as it is.


text:
Q: Want to get redirect URL after sending post Curl request I am sending a basic auth request to a site to log in a user. If they credentials are correct I want to show the dashboard. Therefore I need the redirectURL coming in "redirect_url" under "+curl: curl resource @212 ▼"
This is my code. And I want to get the redirect url in $redirectUrl 1
$curl = new Curl\Curl();
$curl->post('https://xyz.ryver.com/application/login', array(
    'username' => 'xyza@xyz.com',
    'password' => 'mypass',
));

$redirectUrl= ""; //store redirecting URL here
return redirect($redirectUrl);

I want to get this "redirect_url"'s value 2

A: Try this code
return redirect()->away('https://www.your_url_here.com');

Hope this help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When will java.net.URLEncoder.encode function throw UnsupportedEncodingException? If I were to encode a string using the encode method of the URLEncoder class, when will it throw the UnsupportedEncodingException?
String encodedString = URLEncoder.encode(myString, "UTF-8");

I have read the documentation which reads,

Throws:
  UnsupportedEncodingException - If the named encoding is not supported

So, will this ever happen to my code if I always use "UTF-8"?

A: You should be fine with UTF-8, it depends on JVM installed on computer, where final application will run. Anyhow UTF-8 is now supported by java.
You can use static constants in StandardCharsets class:
URLEncoder.encode("Your string", StandardCharsets.UTF_8.toString());


text:
Q: SQL Server 2008 R2: selecting record which are present in another table I have a main table tbl_user and a temporary table tbl_user_temp.
tbl_user contains records in which some are duplicated, so I've moved these records to the temporary table using this query:
INSERT INTO tbl_user_temp
   SELECT
      *
   FROM
      tbl_user
   GROUP BY
      fullname, username, password
   HAVING
      COUNT(*) > 1

Now what I want to do is to delete the records from tbl_user which are present in the tbl_user_temp
I'm using SQL Server 2008 R2.

A: I am guessing you want to remove all the duplicate records from the your main table.
This solution allows you to delete one row from each set of duplicates (rather than just handling a single block of duplicates at a time):
;WITH x AS
(
  SELECT username, rn = ROW_NUMBER() OVER (PARTITION BY
    fullname,username,password
    ORDER BY username)
  FROM dbo.tbl_user
)
DELETE x WHERE rn > 1;

The Row_Number() Will genrate the partitions wise row number. And for each same group the row number will be there.
And in the DELETE x WHERE rn > 1; there it will check if the rownumber is is greater that 1 it will delete that row. If youu just use Select in place of delete query you will see how it generates the rownumber.

A: No need for a temporary table:
delete  u
from    (
        select  row_number() over (
                    partition by fullname, username, password
                    order by newid()) as rn
        from    tbl_user
        ) u
where   rn > 1

Example at SQL Fiddle.


text:
Q: System.FormatException of a string I'm getting System.FormatException: Input string was not in a correct format when running this method.
The values of the fields:
arrayName = "requester";
fieldList = "\"name\" : \"shimshon\""; // "name" : "shimshon"

public override string ToString()
{
   var val = string.Format("\"{0}\" : { {1} }", arrayName, fieldList);

   return val;
}

the expect result of the method is
"requester" : { "name" : "shimshon" }

What is wrong with this format?

A: I think you want:
var val = string.Format("\"{0}\" : {{ {1} }}", arrayName, fieldList);

Note the doubled {{ and }} which is the escape sequence necessary to get braces literally into the output.

A: Try
var val = string.Format("\"{0}\" : {{ {1} }}", arrayName, fieldList);

A: Change:
public override string ToString()
{
    var val = string.Format("\"{0}\" : { {1} }", arrayName, fieldList);

    return val;
}

on:
public override string ToString()
{
   var val = string.Format("\"{0}\" : {{ {1} }}", arrayName, fieldList);

   return val;
}

The way escaped braces are interpreted can lead to unexpected results. For example,
  consider the format item "{{{0:D}}}", which is intended to display an opening brace, a
  numeric value formatted as a decimal number, and a closing brace. However, the format
  item is actually interpreted in the following manner:

*

*The first two opening braces ("{{") are escaped and yield one opening brace.

*The next three characters ("{0:") are interpreted as the start of a format item.

*The next character ("D") would be interpreted as the Decimal standard numeric format specifier, but the next two escaped braces ("}}") yield a single brace. Because the resulting string ("D}") is not a standard numeric format specifier, the resulting string is interpreted as a custom format string that means display the literal string "D}".

*The last brace ("}") is interpreted as the end of the format item.

*The final result that is displayed is the literal string, "{D}". The numeric value that was to be formatted is not displayed.

A: You have to escape the { and } chars that are not part of the format.
string.Format("\"{0}\" : {{ {1} }}",.....)

See this MSDN page:
http://msdn.microsoft.com/en-us/library/txafckwd.aspx

Opening and closing braces are interpreted as starting and ending a
  format item. Consequently, you must use an escape sequence to display
  a literal opening brace or closing brace. Specify two opening braces
  ("{{") in the fixed text to display one opening brace ("{"), or two
  closing braces ("}}") to display one closing brace ("}"). Braces in a
  format item are interpreted sequentially in the order they are
  encountered. Interpreting nested braces is not supported.

A: You need to escape the curly brackets that you want to be curly brackets in your output by using double brackets:
public override string ToString()
{
   var val = string.Format("\"{0}\" : {{ {1} }}", arrayName, fieldList);

   return val;
}


text:
Q: Что делать - вылетает из MySQL Workbench? При запуске базы данных, в программе MySQL Workbench - запускается программа, и потом сразу же закрывается. Подскажите пожалуйста, кто сталкивался с этой проблемой, что делать?
Имя журнала:   Application
Источник:      .NET Runtime
Дата:          04.12.2018 1:53:06
Код события:   1026
Категория задачи:Отсутствует
Уровень:       Ошибка
Ключевые слова:Классический
Приложение: MySQLWorkbench.exe
Версия платформы: v4.0.30319
Описание. Процесс был завершен из-за необработанного исключения.
Сведения об исключении: System.AccessViolationException
   в <Module>.wb.WBContextUI.init_finish(wb.WBContextUI*, wb.WBOptions*)
   в MySQL.Workbench.WbContext.finished_loading(MySQL.Workbench.WbOptions)
   в MySQL.GUI.Workbench.Program.Main(System.String[])

Xml события:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name=".NET Runtime" />
    <EventID Qualifiers="0">1026</EventID>
    <Level>2</Level>
    <Task>0</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2018-12-03T22:53:06.464792100Z" />
    <EventRecordID>18914</EventRecordID>
    <Channel>Application</Channel>
    <Computer>DESKTOP-MSTKF8S</Computer>
    <Security />
  </System>
  <EventData>
    <Data>Приложение: MySQLWorkbench.exe
Версия платформы: v4.0.30319
Описание. Процесс был завершен из-за необработанного исключения.
Сведения об исключении: System.AccessViolationException
   в <Module>.wb.WBContextUI.init_finish(wb.WBContextUI*, wb.WBOptions*)
   в MySQL.Workbench.WbContext.finished_loading(MySQL.Workbench.WbOptions)
   в MySQL.GUI.Workbench.Program.Main(System.String[])

</Data>
  </EventData>
</Event>

И ВТОРАЯ ОШИБКА:
Имя журнала:   Application
Источник:      Application Error
Дата:          04.12.2018 1:53:06
Код события:   1000
Категория задачи:(100)
Уровень:       Ошибка
Ключевые слова:Классический
Пользователь:  Н/Д
Компьютер:     DESKTOP-MSTKF8S
Описание:
Имя сбойного приложения: MySQLWorkbench.exe, версия: 8.0.11.0, метка времени: 0x5aca6da1
Имя сбойного модуля: grt.dll, версия: 0.0.0.0, метка времени: 0x5aca69fa
Код исключения: 0xc0000005
Смещение ошибки: 0x0000000000007f99
Идентификатор сбойного процесса: 0x2b6c
Время запуска сбойного приложения: 0x01d48b5aef8c7c1d
Путь сбойного приложения: C:\Program Files\MySQL\MySQL Workbench 8.0 CE\MySQLWorkbench.exe
Путь сбойного модуля: C:\Program Files\MySQL\MySQL Workbench 8.0 CE\grt.dll
Идентификатор отчета: dc140ae4-7e89-4d26-8445-3ee2622d4ea8
Полное имя сбойного пакета:
Код приложения, связанного со сбойным пакетом:
Xml события:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2018-12-03T22:53:06.660199900Z" />
    <EventRecordID>18915</EventRecordID>
    <Channel>Application</Channel>
    <Computer>DESKTOP-MSTKF8S</Computer>
    <Security />
  </System>
  <EventData>
    <Data>MySQLWorkbench.exe</Data>
    <Data>8.0.11.0</Data>
    <Data>5aca6da1</Data>
    <Data>grt.dll</Data>
    <Data>0.0.0.0</Data>
    <Data>5aca69fa</Data>
    <Data>c0000005</Data>
    <Data>0000000000007f99</Data>
    <Data>2b6c</Data>
    <Data>01d48b5aef8c7c1d</Data>
    <Data>C:\Program Files\MySQL\MySQL Workbench 8.0 CE\MySQLWorkbench.exe</Data>
    <Data>C:\Program Files\MySQL\MySQL Workbench 8.0 CE\grt.dll</Data>
    <Data>dc140ae4-7e89-4d26-8445-3ee2622d4ea8</Data>
    <Data>
    </Data>
    <Data>
    </Data>
  </EventData>
</Event>


text:
Q: Find solution to system of differential equations with initial conditions I have a system
$$
\begin{cases}
x_1'(t) = -x_2(t) \\
x_2'(t) = -x_1(t)
\end{cases}
$$
I have found the linearly independent solutions
$$
\begin{split}
\vec{x}(t) &= e^{\lambda_1 t} \vec{v}_1 = e^t \begin{pmatrix}-1 \\ 1\end{pmatrix}, \\
\vec{x}(t) &= e^{\lambda_2 t} \vec{v}_2 = e^{-t} \begin{pmatrix}1 \\ 1\end{pmatrix}.
\end{split}
$$
and the general solution
$$
\vec{x}(t) = c_1 e^t \begin{pmatrix}-1 \\ 1\end{pmatrix} + c_2 e^{-t} \begin{pmatrix}1 \\ 1\end{pmatrix}
$$
Is it correct that both all the linearly independent solutions and the general solution are all named $\vec{x}(t)$ or should the linearly independent solutions be named $\vec{x}_1(t)$ and $\vec{x}_2(t)$?
Now I have to find the solution to which $x_1(0) = -1$ and $x_2(0) = 1$. How can I do this? I know I have to choose the correct values of $c_1$ and $c_2$ in order to fulfil the conditions. But I don't know where to substitute $x_1(0) = -1$ and $x_2(0) = 1$.
In my system, I have $x_1'(t)$ and $x_2'(t)$ but these are not vector function although I only have found vector functions as solutions. Is it because my general solution $\vec{x}(t)$ consists of the functions $x_1(t) = -c_1 e^t + c_2 e^{-t}$ and $x_2(t) = c_1 e^t + c_2 e^{-t}$, so I just have to find $c_1$ and $c_2$ such that $x_1(0) = -c_1 e^0 + c_2 e^0 = -c_1 + c_2 = -1$ and $x_2(0) = c_1 e^0 + c_2 e^0 = c_1 + c_2 = 1$, resulting in $c_1 = 1$ and $c_2 = 0$?

A: Apart from some confusing notation with indices $(1,2)$ - better replace that with e.g. $(a,b)$ - you've got everything OK. About the initial conditions:
$$
\vec{x}(t) = c_1 e^t \begin{pmatrix}-1 \\ 1\end{pmatrix} + c_2 e^{-t} \begin{pmatrix}1 \\ 1\end{pmatrix}
\quad \Longrightarrow \quad
\vec{x}(0) = c_1 \begin{pmatrix}-1 \\ 1\end{pmatrix} + c_2 \begin{pmatrix}1 \\ 1\end{pmatrix} = \begin{pmatrix}-1 & 1\\ 1 &1 \end{pmatrix}\begin{pmatrix}c_1 \\ c_2\end{pmatrix}
$$ $$
\begin{pmatrix}-1 & 1\\ 1 &1 \end{pmatrix}\begin{pmatrix}c_1 \\ c_2\end{pmatrix}
= \begin{pmatrix} x_1(0) \\ x_2(0) \end{pmatrix} = \begin{pmatrix} -1 \\ 1 \end{pmatrix}
\quad \Longrightarrow \quad
\begin{pmatrix}c_1 \\ c_2\end{pmatrix} =
\begin{pmatrix}-1 & 1\\ 1 & 1 \end{pmatrix}^{-1} \begin{pmatrix} -1 \\ 1 \end{pmatrix}
$$
Inverse of an almost orthogonal matrix is almost the transpose, so:
$$
\begin{pmatrix}c_1 \\ c_2\end{pmatrix} = \frac{1}{2}
\begin{pmatrix}-1 & 1\\ 1 & 1 \end{pmatrix} \begin{pmatrix} -1 \\ 1 \end{pmatrix}
\quad \Longrightarrow \quad
\begin{pmatrix}c_1 \\ c_2\end{pmatrix} = \begin{pmatrix} 1 \\ 0 \end{pmatrix}
$$


text:
Q: Lead sharing in community portal with Account manager and Contact We have the community/partner portal integrated in our org. we have channel managers as internal users with SF license and external users as Partners with Partner Community license.  We have accounts with channel manager as Account manager and have Contacts on that Account as partner.  How do I share Leads owned by the Contact(partner) with the corresponding Account manager(internal user)? My Organization Wide Default(OWD) for Lead is Public Read/Write/transfer.
Really appreciate any advice on this.
Thanks


text:
Q: Should I Use Core Data With A REST API Backend? I am a little confused on what core data is exactly used for. I have googled a lot on it, and a lot of posts on core data are about using Core Data for local storage. At the moment I am developing an app with a REST API backend, and I use AFNetworking to send/receive responses to the REST API.
What I am wondering is if I should instead use Core Data to communicate with the REST API? Is Core Data able to do such a thing? Would it be best to use Core Data or to use AFNetworking?

A: If you do not need CoreData's possibilities of course you should not use it. But if you would like to have some data locally try CoreData or RestKit.
From RestKit wiki:

Until now we have focused on transient objects within RestKit. For
  many applications transient objects are completely the right choice --
  if your data set is constantly changing and your use-cases can rely on
  the availability of network access, using transient objects is a
  simpler, easier way forward. But for some applications, you really
  need the full power of a queryable, persistent object model for
  performance, flexibility, offline access, etc. Apple has provided a
  great solution in Core Data. RestKit integrates with Core Data to
  bridge the gap between your remote server backend and your local
  object model.

A: No, core data is not used to communicate with a back-end (or anything else). As you said, it is for local storage. That's it.
To communicate with a web service or other Internet API, use one of various tools for the job such as NSURLConnection or AFNetworking.


text:
Q: Розовый фон в Unity Когда нажимаю на "Play" или на вкладку "Game", появляется розовый экран. Не создавал никаких объектов, есть только два объекта по умолчанию, и те не показываются, только розовый экран.

изменено: нету теней. Как не было, так и не появилось.

A: Судя по версии Unity 5.6 (последняя 32 битная) вы запустили на старом компе. Видеокарта тоже старая и поддерживает только OpenGL 2-2.2 из-за чего она не может отрисовать шейдер старшей версии (розовый цвет это всегда не отобразившийся шейдер и не только в Unity).
В вашем случае не отображается Skybox. В настройках окна Lighting его можно убрать и использовать вариант с заливочным цветом.
Ошибка SceneView Selected shader is expected to have 7 passes по той-же причине. Не может орисовать оконтовку выделения GameObject. Его можно отключить Gizmos/Selection outline
(сверху-справа окна сцены).


text:
Q: Proving equivalence relations with binary operations I am having trouble with this homework problem:

Let $A$ be a set and $*$ be an associative binary operation on $A$ with the identity element $e$.  Let $R$ be the relation on $A$ defined as follows: Let $a$ and $b$ exist in $A$.  Then $aRb$ if there exists an invertible element $c\in A$ such that $b=c^{-1}*a*c$.  Prove that $R$ is an equivalence relation on $A$.

I know that in order to prove that $R$ is an equivalence relation, I must prove that $R$ is reflexive, transitive and symmetric.  But I cannot figure out how to do it.  Please help!

A: I'll get you started. Note first that $e*e=e$, so $e$ is invertible, and $e^{-1}=e$.

*

*Reflexivity: Let $a\in A$; you need to show that $aRa$. This means finding an invertible $c\in A$ such that $c^{-1}*a*c=a$. What if you take $c=e$?

*Symmetry: Suppose that $a,b\in A$ and $aRb$; you need to show that $bRa$. You know that there is a $c\in A$ such that $c^{-1}*a*c=b$. Multiply that equation on the left by $c$ and on the right by $c^{-1}$ to get $c*c^{-1}*a*c*c^{-1}=c*b*c^{-1}$. Now simplify the lefthand side, and answer this question: what is $(c^{-1})^{-1}$?

*Transitivity: Suppose that $a,b,c\in A$, $aRb$, and $bRc$; you need to show that $aRc$. You know that there are $g,h\in A$ such that $b=g^{-1}*a*g$ and $c=h^{-1}*b*h$; can you find a way to combine these two equations to get an element $x\in A$ such that $c=x^{-1}*a*x$? Substitution, and one more fairly basic fact about inverses should get you there.


text: Q: Why the $L^1(R)$ space does not have a unconditional basis Why the $L^1(R)$  space does not have a unconditional basis. It is a known fact that $L^p(R)$ ($1<p<+\infty$) has unconditional basis. A simple example is the dyadic wavelet or Haar system. I would greatly appreciate it if you can give me some hints of the proof or some related references.


text:
Q: What method am I not using right? I'm new to Julia and currently trying to run the following code:
Using DelimitedFiles

M=readdlm(data)

ts,A=M[:,1],M[:,2:end]

(nsweeps,N)=size(A)

dx=0.01;

x=[minimum(collect(A)):dx:maximum(collect(A))];

bx=[x-dx/2,x[end]+dx/2];

But, when I try to run the last line of code, it gives me the following error:
MethodError: no method
matching(::Array{StepRangeLen{Float64,Base.TwicePrecision
{Float64},Base.TwicePrecision{Float64}},1}, ::Float64)

Closest candidates are:
-(!Matched::BigFloat, ::Union{Float16, Float32, Float64}) at
mpfr.jl:437
-(!Matched::Complex{Bool}, ::Real) at complex.jl:307
-(!Matched::Missing, ::Number) at missing.jl:115

Can you please help me? Also, the data I'm using it's
30×6 Array{Float64,2}

UPDATE here's the whole function I'm trying to run is the following:
function mymain(filename,nsamples)
start_time=time()

M=readdlm(filename)
ts,A=M[:,1],M[:,2:end]
(nsweeps,N)=size(A)

dx=0.01;
x=[minimum(collect(A)):dx:maximum(collect(A))];
bx=[x-dx/2,x[end]+dx/2];
(bx,hA)=hist(A[:],bx);

f1=figure()
subplot(2,1,1); plot(ts,A,"-o"); xlabel("Time [ms]"); ylabel("Amps
[mV]");

subplot(2,1,2); plot(x,hA,"-");  xlabel("Amps [mV]");
ylabel("Density");draw()

nparams=8

Sx=Array(ASCIIString,1,nparams)
Rx=zeros(2,nparams)
nx=zeros(Int,1,nparams)

Sx[1,1]="p";        Rx[1:2,1]=[0.02,0.98];      nx[1]=49
Sx[1,2]="n";        Rx[1:2,2]=[1,20];       nx[2]=20
Sx[1,3]="tD";       Rx[1:2,3]=[50,200];         nx[3]=46
Sx[1,4]="a";        Rx[1:2,4]=[0.05,0.5];       nx[4]=46
Sx[1,5]="siga";     Rx[1:2,5]=[0.01,0.2];       nx[5]=39
Sx[1,6]="sigb";     Rx[1:2,6]=[0.01,0.1];       nx[6]=19
Sx[1,7]="tauf";     Rx[1:2,7]=[50,200];     nx[7]=46
Sx[1,8]="u1";       Rx[1:2,8]=Rx[1:2,1];        nx[8]=nx[1]

x=zeros(maximum(nx),nparams)
p=zeros(maximum(nx),nparams)
dx=zeros(1,nparams)

for j=1:nparams
x[1:nx[j],j]=linspace(Rx[1,j],Rx[2,j],nx[j])'
dx[j]=x[2,j]-x[1,j]
end

S=zeros(Int,nsamples,nparams)

sold=zeros(Int,1,nparams)
for j=1:nparams
sold[j]=rand(1:nx[j])
end

while x[sold[4],4]<=x[sold[5],5]
sold[4]=rand(1:nx[4])
sold[5]=rand(1:nx[5])
end

while x[sold[8],8]<=x[sold[1],1]
sold[1]=rand(1:nx[1])
sold[8]=rand(1:nx[8])
end

xold=zeros(1,nparams)
xnew=zeros(1,nparams)
for j=1:nparams
xold[j]=x[sold[j],j]
end
llold=myloglikelihood(xold,ts,A)

for k=1:nsamples

snew=sold+rand(-1:1,1,nparams)

if all(ones(1,nparams).<=snew.<=nx)

allowed2=x[snew[4],4]>x[snew[5],5]
allowed3=x[snew[8],8]>x[snew[1],1]

if allowed2&allowed3

for j=1:nparams
xnew[j]=x[snew[j],j]
end

llnew=myloglikelihood(xnew,ts,A)

if rand()<exp(llnew-llold)
sold,llold=snew,llnew
end

end
end

S[k,:]=sold

end
for k=1:nsamples
for j=1:nparams
p[S[k,j],j]+=1/(nsamples*dx[j])
end
end

f2=figure()
for j=1:nparams
subplot(2,4,j)
plot(x[1:nx[j],j],p[1:nx[j],j]);
xlabel(Sx[j])
end

diff_time=time()-start_time;
println("Total runtime
",round(diff_time,3),"s=",round(diff_time/60,1),"mins." );

return S

end

This goes in line with some other functions, but as you can see, this is the main function, so I really can't move forward without first runnning this one.

A: It isn't clear what outcome you are hoping for here. So I'll just give some pointers that hopefully help.
First, in this line:
x=[minimum(collect(A)):dx:maximum(collect(A))];

the calls to collect are redundant. Also, I suspect you are trying to construct a StepRangeLen, but by putting it in [] you actually are getting a Vector{StepRangeLen}. I think what you want in this line is actually this:
x=minimum(A):dx:maximum(A);

Second, in this line:
bx=[x-dx/2,x[end]+dx/2];

note that dx/2 is a Float64 while x is a StepRangeLen. This is important because the latter is a collection so if you want to perform this operation element-wise across the collection you need to broadcast, that is, x .- dx/2. Note, I suspect you may not be on the latest version of Julia, because when I run this the error message actually tells me explicitly I need to broadcast. Anyway, in contrast, x[end]+dx/2 is fine and does not need to be broadcast because x[end] is Float64. So I think you want:
bx=[x .- dx/2, x[end] + dx/2];

Having said that, it isn't clear to me why you want this bx, which is why I said at the start I'm not sure what outcome you were hoping for.


text:
Q: NetBeans Change Ant Version I'm using NetBeans to build my project. The version I'm using is 1.8. However, I'm trying to build it again on a computer that can only run ant 1.6.5. Is there any way to specify in Netbeans which version of ant to use?

A: Please follow 3 easy steps as below:

*

*Download Ant 1.6.5 from Apache Binaries and install/extract in your local file system

*Go to Netbeans Tools > Options > Miscellaneous > Ant

*Change the Ant Home to Ant 1.6.5 folder created in step-1 of your local file system
EDIT:
If the above doesn't help because of your specific Net Beans, try steps below:

*

*Go to Help -> Help Contents

*Search for Switching Ant Version

*Click the same link from left pane to get the details in right, you should see a screen as below:

Follow the instructions on the above page.

A: In NetBeans 8.2, go to Tools -> Options -> Java -> Ant -> Ant Home


text:
Q: Data frame aggregating across rows With a data frame df like below
text <- "
State,District,County,Num Voters,Total Votes in State,Votes for None,Candidate Name,Party,Votes Scored
CA,San Diego,Delmar,190962,48026634,2511,A1,IND,949
CA,San Diego,Delmar,190962,48026634,2511,A2,RP(K),44815
CA,San Diego,Delmar,190962,48026634,2511,A3,IND,1036
CA,San Diego,Delmar,190962,48026634,2511,A4,DEM,29235
CA,San Diego,Delmar,190962,48026634,2511,A5,IND,5064
CA,San Diego,Delmar,190962,48026634,2511,A6,IND,803
CA,San Diego,Delmar,190962,48026634,2511,A7,REP,22329
CA,San Diego,Delmar,190962,48026634,2511,A8,BSP,43553
CA,San Diego,La Jolla,190257,48026634,3629,A1,IND,972
CA,San Diego,La Jolla,190257,48026634,3629,A2,RP(K),66168
CA,San Diego,La Jolla,190257,48026634,3629,A3,IND,2763
CA,San Diego,La Jolla,190257,48026634,3629,A4,DEM,32792
CA,San Diego,La Jolla,190257,48026634,3629,A5,IND,8629
CA,San Diego,La Jolla,190257,48026634,3629,A6,IND,1191
CA,San Diego,La Jolla,190257,48026634,3629,A7,REP,28002
CA,San Diego,La Jolla,190257,48026634,3629,A8,BSP,2555
"
df <- read.table(textConnection(text), sep = ",", header = TRUE)

My data contains five political parties: IND, RP(K), DEM, REP, and BSP. I would like to create two new scoring columns:

*

*DRP: DEM score + RP(K) score

*RSP: REP score + BSP score

Additionally, I would like to include columns that group these scores at the District and County level.
How do I go about it with dplyr preferably. I'm thinking of the group function, however haven't been able to figure out the logic for that.

A: By using dplyr you could do something like this.
tg <- df %>%
  group_by(County) %>%
  mutate(DRP_county = sum(Votes.Scored[Party == "RP(K)" | Party == "DEM"]),
         RSP_county = sum(Votes.Scored[Party == "REP" | Party == "BSP"])) %>%
  ungroup() %>%
  group_by(District) %>%
  mutate(DRP_district = sum(Votes.Scored[Party == "RP(K)" | Party == "DEM"]),
         RSP_district = sum(Votes.Scored[Party == "REP" | Party == "BSP"]))

Note:
I think it is better if you keep everything in the same dataframe, but it is of course depending on the data size. Also for future analysis of the dataframe and for model/visualization purposes it might be better to go with mutate instead of summarise, although it would give a cleaner output.
Also, you could probably skip ungroup(), but I believe it is safer to have it included.

A: Using dplyr, if you want just two columns with sum on district and sum on county level for the parties:
df %>%
  mutate(Party2 = ifelse(Party == "DEM" | Party == "RP(K)", "DRP",
                         ifelse(Party == "REP" | Party == "BSP", "RSP", paste(Party)))) %>%
  group_by(District, Party2) %>%
  mutate(Votes.Scored.District = sum(Votes.Scored)) %>%
  ungroup() %>%
  group_by(County, Party2) %>%
  mutate(Votes.Scored.County = sum(Votes.Scored))

Or if you want an overall statistic for parties on district and on county level:
df %>%
  mutate(Party2 = ifelse(Party == "DEM" | Party == "RP(K)", "DRP",
                         ifelse(Party == "REP" | Party == "BSP", "RSP", paste(Party)))) %>%
  group_by(District, Party2) %>%
  mutate(Votes.Scored.District = sum(Votes.Scored)) %>%
  ungroup() %>%
  group_by(County, Party2) %>%
  mutate(Votes.Scored.County = sum(Votes.Scored)) %>%
  group_by(Party2) %>%
  summarise(Votes.Scored.District = min(Votes.Scored.District),
            Votes.Scored.County = min(Votes.Scored.County))

# A tibble: 3 x 3
  Party2 Votes.Scored.District Votes.Scored.County
  <chr>                  <dbl>               <dbl>
1 DRP                  173010.              74050.
2 IND                   21407.               7852.
3 RSP                   96439.              30557.


text:
Q: this.handleChange.bind(this) and render use I got this code from react bootstrap website  https://react-bootstrap.github.io/components/forms/  I will like to know the use of the following in the code

*

*this.handleChange = this.handleChange.bind(this)

*The use of making the value in this.state = {
  value: ''
}; }
empty

*The use of setting the validationState attribute in validationState={this.getValidationState()}

*And the use of setting two renders, why not just one render and is it possible to set more than one render
    class FormExample extends React.Component {
    constructor(props, context) {
    super(props, context);
    this.handleChange = this.handleChange.bind(this);

     this.state = {
   value: ''
   };
   }

   getValidationState() {
   const length = this.state.value.length;
   if (length > 10) return 'success';
   else if (length > 5) return 'warning';
   else if (length > 0) return 'error';
    return null;
    }

    handleChange(e) {
    this.setState({ value: e.target.value });
    }

     render() {
     return (
     <form>
     <FormGroup
     controlId="formBasicText"
  validationState={this.getValidationState()}
>
  <ControlLabel>Working example with validation</ControlLabel>
  <FormControl
    type="text"
    value={this.state.value}
    placeholder="Enter text"
    onChange={this.handleChange}
  />
  <FormControl.Feedback />
  <HelpBlock>Validation is based on string length.</HelpBlock>
</FormGroup> </form>
    );
    }
    }

render(<FormExample />);

A: *

*this.handleChange = this.handleChange.bind(this): This is to make it
so you can use the variable "this" inside of handlechange()

*By setting a blank value, this key will not be empty in the future
if you try to reference it without a value being set

*validationState is being passed into FormGroup as a property

*The renders are not in the same class so the FormExample is being
rendered by something else outside it.

Hope that helps


text:
Q: Error al insertar datos en tabla de MySQL Help me, al momento de insertar datos en la tabla producto me salta este:
Error Code: 1136. Column count doesn't match value count at row 2
Tabla
 create table Producto(
idProducto int not null,
Nombre_Producto varchar(45) not null,
Precio_Producto float not null,
Marca_Producto varchar(45) not null,
Stock_Producto int null,
rucSucursal_fk int (10) not null,
rucProveedor_fk int (13) not null,
idTipo_Producto_fk int not null,
 primary key (idProducto),
index (rucSucursal_fk),
index (rucProveedor_fk),
index (idTipo_Producto_fk),
constraint rucSucursal_fk foreign key (rucSucursal_fk) references Sucursal(rucSucursal),
constraint rucProveedor_fk foreign key (rucProveedor_fk) references Proveedor_Producto(rucProveedor),
constraint idTipo_Producto_fk foreign key (idTipo_Producto_fk) references Tipo_Producto (idTipo_Producto)
) engine = InnoDB;

INSERT
insert into producto (idProducto, Nombre_Producto, Precio_Producto, Marca_Producto, Stock_Producto, rucSucursal_fk, rucProveedor_fk, idTipo_Producto_fk)
                values (1,'Finalin',1,'Finalin',45,1,2,5),
                       (2,'Condones DUO',2.50,'Duo',56,1,3),
                       (3,'Nido',16.50,'Nido',72,1,2,7),
                       (4,'Colgate',1.50,'Colgate',23,4,1,2),
                       (5,'Viagra',15.00,'COMOPIEDRA',3,6),
                       (6,'Té Organico',4.60,'SHICURA',80,3,4,03),
                       (7,'Tamponones',1.00,'LINEA CMAMO',21,3,3,2),
                       (8,'Paracetamol',2.50,'FARMA',73,3,2,1),
                       (9,'Ibutefreno',2.50,'FARMA',20,2,2,1),
                       (10,'Purgante', 3.25,'SIETEREX',61,2,6,3);

Me sale ese error cada vez que intento insertar reviso la tabla y el insert pero sigue igual, no entiendo el error.

A: El error "Error Code: 1136. Column count doesn't match value count at row 2" indica que en values () se ha introducido un número menor o mayor al de número de columnas que la tabla tiene. O también puede indicar que no has especificado las columnas en las que se deben insertar los datos.
Más información en este enlace

A: Revisando detalladamente, me faltaba agregar datos dentro de la tabla, por ejemplo en la columna dos. Pero aun faltaban algunos detalles más dentro de la tabla para agregar. Es decir después de la marca del producto debería a ver cuatro columnas de números pero en algunas filas solo había 2 o 3, así que faltaban datos. Ya lo corregí y funciono.
insert into producto (idProducto, Nombre_Producto, Precio_Producto, Marca_Producto, Stock_Producto, rucSucursal_fk, rucProveedor_fk, idTipo_Producto_fk)
                values (1,'Finalin',1,'Finalin',45,1,2,5),
                       (2,'Condones DUO',2,'Duo',56,1,3,6),
                       (3,'Nido',16,'Nido',72,1,2,7),
                       (4,'Colgate',1,'Colgate',23,4,1,2),
                       (5,'Viagra',15,'COMOPIEDRA',20,3,3,6),
                       (6,'Té Organico',4,'SHICURA',80,3,4,3),
                       (7,'Tamponones',1,'LINEA CMAMO',21,3,3,2),
                       (8,'Paracetamol',2,'FARMA',73,3,2,1),
                       (9,'Ibutefreno',2,'FARMA',20,2,2,1),
                       (10,'Purgante', 3,'SIETEREX',61,2,6,3);


text:
Q: How do I set a checkbox to True using Powershell when processing a form? I need to automate a couple of steps in in a remote website using Powershell.
I am using Invoke-WebRequest to fetch everything into $response which contains the element e.g. "checkboxelement"
$response = Invoke-WebRequest 'www.site.com' -SessionVariable session
$form = $response.Forms[0]
$action = $form.Action
$mycheckbox = $response.ParsedHtml.getElementsByName("checkboxelement")

If I do
@($mycheckbox).checked

This returns
False

But I don't know how to set it to True so I can submit the form using another Invoke-WebRequest to the www.site.com/$form.Action
I have tried
$mycheckbox.checked = $true

But I get this error
The property 'checked' cannot be found on this object. Verify that the property exists and can be set.
At line:1 char:1
+ $mycheckbox.checked = $true
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException

So all I want to do is change the element checked status to True. Any help?


text:
Q: Using Visual Studio and Git. How do I commit a new folder to my Git repository? all. I am very, very new to Git. Places I've worked at usually use TFS, and I want to learn some Git.
I don't even know if I have it set up correctly, but I do have the VS2017 Git Add-on. I've committed some code, and a project. The problem is, I added a couple of folders to my project, but I can't figure out how to check them into my repository. Nor can I figure out how to check in the DLLs that are in the project.
I'm very, very new to Git, so how would I do something like this? I've tried right-clicking on the folder, and looking for some sort of option to add it, so that I can check it in, but I haven't been successful finding anything.

A: To add a file/folder, use git add command. Then use git commit to commit to your local repository. If you want to send it to the base (to be available to other users, for instance), you should git push your changes.
Remember to, before adding the files, to create a .gitignore file in order to avoid persisting binaries and auto-generated things (dlls, exe, etc) - these shouldn't be on repository.
Maybe you should search for some tutorials, documentations. Maybe this would help you improve your knowledge on git.


text:
Q: Expectation of half of a binomial distribution If $X$ is a random variable with binomial distribution $B[2n,p]$, with $p=0.5$, then its mean value is $2np = n$. I would like to calculate the mean value of $X$ given that $X$ is at most $n$, i.e.:
$$\frac{1}{Pr[X\leq n]}\cdot \sum_{k=0}^{n} k \binom{2n}{k} p^k q^{2n-k}$$
To calculate the sum, I used the ideas from this question: Expected Value of a Binomial distribution?
and got:
$$ \frac{2np}{Pr[X\leq n]}\cdot \sum_{k=1}^{n} \binom{2n-1}{k-1} p^{k-1} q^{(2n-1)-(k-1)}$$
$$ = \frac{2np}{Pr[X\leq n]}\cdot \sum_{j=0}^{n-1} \binom{2n-1}{j} p^{j} q^{(2n-1)-j}$$
If the inner sum were for $j=0,...,(2n-1)$, it would be exactly 1 by the binomial theorem. But it is only for half the range, and by symmetry, its value seems to be 0.5. The probability in the denominator is also 0.5, so we get:
$$\frac{2np}{0.5}\cdot 0.5 = 2np = n$$
But this doesn't make sense, since the expectation of values that are at most $n$, cannot be $n$!
Where is my mistake? And what is the correct expectation?

A: Given that $p=q=\frac{1}{2}$,
$$\frac{1}{\mathbb{P}[X\leq n]}\sum_{k=0}^{n}k\binom{2n}{k}\frac{1}{4^n}=\frac{1}{4^n\mathbb{P}[X\leq n]}\sum_{k=0}^{n}k\binom{2n}{k}=\frac{n}{2\mathbb{P}[X\leq n]},$$
but the probability that $X\leq n$ is not $\frac{1}{2}$; it is given by:
$$ \mathbb{P}[X=n]+\mathbb{P}[X<n] = \frac{1}{2}+\frac{1}{2\cdot 4^n}\binom{2n}{n},$$
so the wanted expected value is:
$$\frac{n}{1+\frac{1}{4^n}\binom{2n}{n}}.$$
Which by Stirling's formula is approximately:
$$\frac{n}{1+\frac{1}{\sqrt{\pi n}}} \approx n - \sqrt{\frac{n}{\pi}}$$


text:
Q: Move the marker along the with map as the user moves I have implemented google map into my app. I have added a custom marker at my current location.I want to move the marker as the user moves, along with the map. I want to implement the functionality as in google maps navigation. While googling i found the following links but did not get the result. so can any one help me out ?
I have added this in onLocationChanged()
 LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        sourceLocation = latLng;
        startPoint = new GeoPoint(latLng.latitude,latLng.longitude);
        forNavigation = location;

       //  animation
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        // Zoom in the Google Map
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
       // mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mPositionMarker.getPosition(), 15));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location
                .getLatitude(), location.getLongitude())));

These are the links which i found
Google map: moving marker and map together smoothly along with user?
How to smoothly keep moving current location marker in Google Maps v2 android

A: here is two solution you have.

*

*Use onlocationtrue then it show you blue dot as your current location.

*Use fused api for current location and create you marker in locationchanged.
for fused api you can check from here.
thanks


text:
Q: Filters/Callbacks should be in concerns or not Let's say I have a concern in controllers and it's name is Authentication. It contains a before_action method authenticate_user. Where should I write before_action :authenticate_user? what is the best practice? Is it should be written in concern or in the controller in which this concern is included?
NOTE: I want to implement single responsibility

A: It depends on your controller structure. Auth logic is most commonly placed in a higher-level controller that most other controllers ultimately inherit from, rather than a concern. This is because you can simply enable auth at a higher level and have it be active on all subcontrollers without the need to add a concern explicitly for each of them, which might be more error prone. That higher-level controller would contain both the before_action and the authenticate_user method. If for any reason, there's a controller along the way which needs auth disabled, assuming this would be an exception, you could use skip_before_action.
class UserController < ApplicationController
    before_action :authenticate

    private

    def authenticate
        # ...
    end
end

class SomeController < UserController
    # auth already enabled here
end


text:
Q: Uninstall persistent driver (WinVDEdrv6.sys) When I attempted to enable Memory Integrity in Windows 11 Pro, Windows reported that an incompatible driver, which it identified as WinVDEdrv6.sys, blocked the action (screenshot attached). The driver was not listed in Windows apps using Control Panel; in terminal mode, the command "dism /online /get-drivers /format:table" failed to list this file.

I found a post that linked the driver with NewSoftwares.net, the publisher of the file encryption app FolderLock. Months ago, I downloaded a trial version, decided I didn't need it and uninstalled the program. I did not see FolderLock, NewSoftwares or any other reference to them in Control Panel or the terminal table of drivers.
I've emailed tech support at NewSoftwares but have not received a reply to date.
I located the file WinVDEdrv6.sys in C:\Windows\SysWOW64. My questions are:
Is this a necessary driver?
How can I uninstall or safely delete it?
pnputil /enum-drivers Output

A: WinVDEdrv6.sys was not a necessary driver on my machine. I deleted the file in safe mode, restarted, and enabled Memory Integrity with no problems. Here are the steps I took to confirm I could do this safely.
To look for any drivers associated with WinVDEdrv6.sys, I produced a list of drivers by running "pnputil /enum-drivers" in terminal mode. The list did not include references to WinVDEdrv6.sys, NewSoftwares or FolderLock. So the driver connected to WinVDEdrv6.sys was not installed, though apparently, the existence of the file was enough to block enabling Memory Integrity. Windows blocked me from deleting the file because it was shown as in use (by an unidentified process). I used safe mode to delete the file.
Based on this post, WinVDEdrv6.sys probably was created when I installed a trial version of FolderLock, and was left behind after I uninstalled the program. Many thanks to @Ramhound for his helpful comments.


text:
Q: invalid application of 'sizeof' to incomplete type This is my makefile file
all: trie
trie: trie.o main.o
    gcc trie.o main.o -o trie -std=c11 -g -Wall

trie.o: trie.c trie.h
    gcc -c trie.c -o trie.o -std=c11 -g -Wall

main.o: main.c trie.h
    gcc -c main.c -o main.o -std=c11 -g -Wall

clean:
    rm -f *.o trie

and header file
#ifndef TRIE_H
#define TRIE_H

struct node;
typedef struct node node;

//insert a word in a leaf
void insert(char* word, node* leaf);

#endif //TRIE_H

and trie.c file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "trie.h"

struct node {
  char* data;
  node* child[127];
};

void insert (char* word, node* leaf) {
  node* curr = leaf;
  for (size_t i = 0; i < strlen(word); i++) {//start from beginning of char to end
    if (curr == NULL) {
      curr = (node*)malloc(sizeof(node)); // if it's null, creating new node
      curr->data = "";
    }
    curr = curr->child[(int) word[i]];
  }
  curr->data = word; // set last node stored the word
}

it occurs error message in the main file
#include <stdio.h>
#include <stdlib.h>

#include "trie.h"

int main() {
  node* x = (node*) malloc(sizeof(node));
  insert("hi", x);
  return 0;
}

and this is error message:
main.c: In function 'main':
main.c:7:35: error: invalid application of 'sizeof' to incomplete type 'node {aka struct node}'
   node* x = (node*) malloc(sizeof(node));
have any idea why my code has an error?

A: Your main.c doesn't have a definition of node, just a declaration of the name without defining the structure. You either need to include the definition in the .h file so both trie.c and main.c can see it, or you need to provide an allocator method (declared in trie.h, defined in trie.c) that can perform a definition aware allocation (and possibly initialization) of a node in a place that has access to the definition of the otherwise opaque type.

A: Try to include the Header files containing related structures.


text:
Q: Core Data: Is it possible to use custom function in group by Is it possible to use custom function (strftime) in group by part when crafting NSFetchRequest in objective-c? The sql statements is perfectly valid in sqlite:
select date, count(*) from note group by strftime('%Y%m%d', date)

However, after a day of digging and trying various ways and solutions I came to the conclusion it's impossible to do it with core data in single sql fetch. I'm using NSFetchRequest with setPropertiesToGroupBy (iOS 5.0 only).
UPDATE. There's an example for getting such behavior with core data provided by apple. However, I have enabled "-com.apple.CoreData.SQLDebug 1" for showing SQL performed by core data. It appears, core data is not performing my desired SQL. It just selects them all with a first sql query, and then loops through the groups performing multiple "SELEC .. WHERE ID IN ...." SQL queries. An excerpt from console:
2012-07-05 10:34:57.244 DateSectionTitles[1139:fb03] CoreData: sql: SELECT 0, t0.Z_PK     FROM ZEVENT t0 ORDER BY t0.ZTIMESTAMP
2012-07-05 10:34:57.245 DateSectionTitles[1139:fb03] CoreData: annotation: sql   connection fetch time: 0.0010s
2012-07-05 10:34:57.246 DateSectionTitles[1139:fb03] CoreData: annotation: total fetch    execution time: 0.0015s for 52 rows.
2012-07-05 10:34:57.247 DateSectionTitles[1139:fb03] CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZTIMESTAMP, t0.ZTITLE FROM ZEVENT t0 WHERE  t0.Z_PK IN  (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)  ORDER BY t0.ZTIMESTAMP LIMIT 20
2012-07-05 10:34:57.248 DateSectionTitles[1139:fb03] CoreData: annotation: sql connection fetch time: 0.0012s
2012-07-05 10:34:57.249 DateSectionTitles[1139:fb03] CoreData: annotation: total fetch execution time: 0.0022s for 20 rows.
2012-07-05 10:34:57.250 DateSectionTitles[1139:fb03] CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZTIMESTAMP, t0.ZTITLE FROM ZEVENT t0 WHERE  t0.Z_PK IN  (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)  ORDER BY t0.ZTIMESTAMP LIMIT 20
2012-07-05 10:34:57.281 DateSectionTitles[1139:fb03] CoreData: annotation: sql connection fetch time: 0.0303s
2012-07-05 10:34:57.281 DateSectionTitles[1139:fb03] CoreData: annotation: total fetch execution time: 0.0310s for 20 rows.

A: Yes you can. Assemble your NSFetchedResultsController similar to:
  NSFetchedResultsController *aFetchedResultsController =
  [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
  managedObjectContext:someManagedObjectContext
  sectionNameKeyPath:@"yearOnly" // <==
  cacheName:@"cacheAsneeded"];

Then inside your NSManagedObject class add a method to be used with sectionNameKeyPath
- (int)yearOnly { //
   NSCalendar *cal = [NSCalendar currentCalendar];
   return [[cal components:NSYearCalendarUnit fromDate:self.date] year];
}

The request will return the results grouped by the year so that each encountered year will become a section.
If you need a grouping by  month too, you might want to change the calendar components appropriately.
For the count(*) add an NSExpression to your fetchRequest:
 NSExpression * many = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"someAttribute"]]];


text:
Q: Import existing BlackBerry project in Eclipse How can I import existing Blackberry projects into eclipse?
I found this development guide for BlackBerry Eclipse users, but I didn't find any .jdw file:
Import a BlackBerry application project from an existing workspace
When I make new project and copy all the folder src and res I obtain an error that there is a file  missing and there is no specification of type of the name of this file
Error: Cannot run program "jar": CreateProcess error=2.
Can any one help me to run this project?

A: Click File-->New-->Blackberry Project-->Create project form existing resource --> then browse to your project folder and click finish.

A: Use this BlackBerry Java Plug-in for Eclipse guide: Add a .jar file dependency


text:
Q: how to apply properly scroll-margin-top? I have a fixed header in my website, when i try scrolling to a section  with anchor links (href="#id_of_the_section") in my main page (where the section actually exists) everythng works fine using :
<style>
    #documents, #team {
        scroll-margin-top: 110px;
    }
</style>

but when i try to go to that section from an external page not the main page as mywebsite.com/#id_of_the_section there is a problem.
The position where the scroll stops is not the same as when i click the anchor link in the main page


text:
Q: What are some examples of experimentally confirmed quantum effects at macroscopic level? Please only answer with detailed description and explanations It would be very helpful if you can give a few examples that are at micrometer level or above, and include some explanations or insight on the causes of these behaviors.

A: Black body radiation. . It cannot be fitted classically. It needs quantum mechanics.
The atomic spectra can only be explained by quantum mechanics.

A: Just two simple examples:
(1) The decrease of specific heat with temperature.
(2) Superconductivity.

A: The periodic table of elements. Explainable using Schrödinger's equation, electron spin and the exclusion principle.

A: This is an interesting question. Macroscopic instances of quantum phenomena are usually very dependent on how people interpret quantum mechanics. For some, quantum phenomena are exclusively microscopic so that the macroscopic effects that we see are mere consequence of microscopic quantum phenomena, but not quantum phenomena in and of themselves.
One clear example is that of semiconductors and transistors. In both cases, the underlying theory is manifestly quantum mechanical. Both systems are essential components of modern electronic devices. But would you say that a computer or a smartphone are quantum systems? Conventionally speaking, the answer would be no.
I do have a goodie for you, however. It consists of an experiment in fluid dynamics that exhibits such strong analogies to exclusively quantum phenomena that it has been cited as evidence for the Pilot Wave interpretation of QM. I'll let this Veritasium video paint the rest of the picture for you:

A: According to Seth Lloyd (MIT), the phenomenon of birds migrating, photosynthesis, and even smelling and sneezing might be explained by quantum physics in addition to chemistry.

A: line emission spectra of elements. lasers and masers.


text:
Q: Java XML Reading an XML file from top to bottom I want to read an XML starting from the top to the bottom using Java. However, I don't want to use recursive functions because I want to be able to jump to a different element and start reading from that position.
I've tried using getParent() and indexOf() methods (All three libraries below have these methods) to do this, but it's gotten very messy, mainly because the methods don't distinguish between attributes and elements.
I'm sure there must be a simple way to do this, but after trying dom4j, jdom, and xom, I still have not found a solution.
[Edit] More Information:
My friend wants to make a console text-based game in a question/answer type style. Instead of hard-coding it into java, I decided to try and make it read an XML file instead, because XML has a tree-like style that would be convenient. Here is an example of what my XML file might look like:
<disp>Text to be displayed</disp>
<disp>Text to be displayed afterward</disp>
<disp>What is your favorite color?</disp>
<question>
    <answer name="orange">
        <disp>Good choice.</disp>
        <!-- More questions and stuff -->
    </answer>
    <default>
        <disp>Wrong. The correct answer was orange.</disp>
    </default>
</question>

I don't know if it taboo to use XML like an pseudo programming language. If anyone has other suggestions feel free to give them.

A: Your design is basically good and an example of Declarative Programming. You should read your XML files using an XML parser either into a DOM or using SAX. Since I think you will want to revisit nodes I suspect you will need a DOM (FWIW I use XOM, xom.nu). One of the best examples of XML-based declarative programming is XSLT where the data and commands are all XML.
I use this model a great deal. It has the advantage that the data structure can be external and can be edited.
(Note that your XML needs a root element)

but it's gotten very messy, mainly because the methods don't
  distinguish between attributes and elements.

All DOM or SAX tools differentiate very clearly between attributes and elements, so if there is confusion it is somewhere else.

A: It would be good if you would show what you want to do with the XML snippets, but normally if you want to read off of any kind of file, use java.util.Scanner.
Scanner scan = new Scanner (new File("file.xml"));
while (scan.hasNext()) {
    String theData = scan.nextLine();
}
scan.close();

This should return the values that you need until it runs out of lines to scan.
Hope it works and Happy Coding!

A: Since you want to read a xml file. I recommend go for SAX parser. It is event based parser very fast and efficient for xml reading (top down approach).
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/ will explain about usage of sax parser.
Thanks


text:
Q: How do I save a multidimensional tensor in python? What command should I use if I want to store a tensor in a file with dimensions greater than 2?
For example, if I have a four-dimensional array
train = np.zeros([n1, n2, n3, trainnumber], np.float32)
how should I save it?


text:
Q: Show that $f_n1_{A_n}$ convergences in mean

Consider the measurable space $(\Omega,\mathcal{A},\mu)$. Let $f,f_1,f_2,\ldots$ be measurable functions on that measurable space and $A,A_1,A_2,\ldots\in\mathcal{A}$. Let $(f_n)$ converge in mean to $f$ and $1_{A_n}$ to $1_A$ in measure. Show that then $f_n1_{A_n}$ converges in mean to $f1_A$.

Hello and good evening!
My idea is to show instead that $(f_n1_{A_n})_{n\in\mathbb{N}}$ converges to $f1_A$ in measure and that $(f_n1_{A_n})_{n\in\mathbb{N}}$ is uniformly integrable (because this together is equivalent to the convergence in mean of $(f_n1_{A_n})_{n\in\mathbb{N}}$ to $f1_A$).
I. Uniformly integrability
Consider any $\varepsilon>0$. $(f_n)_{n\in\mathbb{N}}$ is uniformly integrable (and converges to $f$ in measure what is needed below). So there exists an integrable function $h\geq 0$, so that
$$
\sup_{f_n\in (f_n)_{n\in\mathbb{N}}}\int 1_{\lvert f_n\rvert\geq h}\lvert f_n\rvert\, d\mu<\varepsilon.
$$
For this function $h$, it is
$$
(\lvert 1_{A_n}f_n\rvert-h)^+\leq 1_{\lvert 1_{A_n}f_n\rvert\geq h}\lvert 1_{A_n}f_n\rvert\leq 1_{\lvert f_n\rvert\geq h}\lvert f_n\rvert.
$$
So it follows that
$$
\int (\lvert 1_{A_n}f_n\rvert-h)^+\, d\mu\leq\int 1_{\lvert f_n\rvert\geq h}\lvert f_n\rvert\, d\mu\leq\sup_{f_n\in (f_n)_{n\in\mathbb{N}}}\int 1_{\lvert f_n\rvert\geq h}\lvert f_n\rvert\, d\mu<\varepsilon
$$
what means that
$$
\sup_{1_{A_n}f_n\in (1_{A_n}f_n)_{n\in\mathbb{N}}}\int (\lvert 1_{A_n}f_n\rvert-h)^+\, d\mu<\varepsilon.
$$
So $(1_{A_n}f_n)_{n\in\mathbb{N}}$ is uniformly integrable.
II. Convergence in measure
Consider any $\varepsilon>0$. It is
$$
\left\{\omega\in\Omega:\lvert 1_{A_n}f_n-1_Af\rvert>\varepsilon\right\}\\=\left\{\omega\in\Omega:\lvert 1_{A_n}f_n-1_{A_n}f+1_{A_n}f-1_Af\rvert>\varepsilon\right\}\\\subset \left\{\omega\in\Omega:\lvert 1_{A_n}f_n-1_{A_n}f\rvert+\lvert 1_{A_n}f-1_Af\rvert>\varepsilon\right\}\\\subset\left\{\omega\in\Omega:\lvert 1_{A_n}f_n-1_{A_n}f\rvert>\frac{\varepsilon}{2}\right\}\cup\left\{\omega\in\Omega:\lvert 1_{A_n}f-1_Af\rvert>\frac{\varepsilon}{2}\right\}\\=\left\{\omega\in\Omega:\lvert 1_{A_n}(f_n-f)\rvert>\frac{\varepsilon}{2}\right\}\cup\left\{\omega\in\Omega:\lvert f(1_{A_n}-1_A)\rvert>\frac{\varepsilon}{2}\right\}\\\subset\left\{\omega\in\Omega:\lvert f_n-f\rvert>\frac{\varepsilon}{2}\right\}\cup\underbrace{\left\{\omega\in\Omega:\lvert 1_{A_n}-1_A\rvert=1\right\}}_{=\left\{\omega\in\Omega:\lvert 1_{A_n}-1_A\rvert>\lambda\right\}\text{ for a }0<\lambda<1}.
$$
So it is
$$
\mu(\left\{\omega\in\Omega:\lvert 1_{A_n}f_n-1_Af\rvert>\varepsilon\right\})\leq\mu(\left\{\omega\in\Omega:\lvert f_n-f\rvert>\frac{\varepsilon}{2}\right\}\cup\left\{\omega\in\Omega:\lvert 1_{A_n}-1_A\rvert>\lambda\right\})\\\leq\underbrace{\mu(\left\{\omega\in\Omega:\lvert f_n-f\rvert>\frac{\varepsilon}{2}\right\})}_{\to 0}+\underbrace{\mu(\left\{\omega\in\Omega:\lvert 1_{A_n}-1_A\rvert>\lambda\right\})}_{\to 0}\to 0
$$
$$
\Longrightarrow \mu(\left\{\omega\in\Omega:\lvert 1_{A_n}f_n-1_Af\rvert>\varepsilon\right\})\to 0
$$
From I. and II. it follows that $(1_{A_n}f_n)_{n\in\mathbb{N}}$ converges to $1_Af$ in mean.
Could you pls say me if my proof is allright?
With best wishes for X-mas,
math12

A: Does uniform integrability plus convergence in measure imply convergence in $L^1$?
See this. Your assertion about conv in mean, measure, UI is false.


text:
Q: Why does Django generate HTTP 500 errors for static media when Debug is set to False? I'm preparing to deploy my Django app and I noticed that when I change the "DEBUG" setting to False, all references to static files (i.e., JavaScript, CSS, etc..) result in HTTP 500 errors.
Any idea what's causing that issue (and how to fix it)?

A: It sounds like you might be trying to serve your static media using the Django development server.  Take a look at http://docs.djangoproject.com/en/dev/howto/deployment/ for some deployment scenarios/howtos and http://docs.djangoproject.com/en/dev/howto/static-files/ for how to serve static files (but note the disclaimer about NOT using those methods in production).
In general, I'd look at your server logs and see where it's trying to fetch the files from.  I suspect the 500 errors are really 404 errors, but they become 500 errors because Django can't find or render the 404.html template.  If that's not the case, it would be helpful if you could post the specific 500 error you're getting.

A: I would highly recommend letting your web server handle the static requests, without getting to Django. In my urls.py, I only add the static request handler when debug is set to True.
Technically, Django serving the static works fine though. Definitely read the short docs page, http://docs.djangoproject.com/en/dev/howto/static-files/. You'll want to use an entry like this in urls.py
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root': '/path/to/media'})

A: You must also check your URLs all over the place. When the DEBUG is set to False, all URLs without trailing "/" are treated as a bug, unlike when you have DEBUG = True, in which case Django will append "/" everywhere it is missing. So, in short, make sure all links end with a slash EVERYWHERE.

A: Turns out I'd commented out the SECRET_KEY variable. There was no way for me to know though. Just had to try things out.


text:
Q: How to check process log while using iAP protocol MFI? I have all the permission to do MFI, i am developing an ios application in swift which will speak with accessory connected to the device(iphone/ipad).
Question:
How can i debug or how can i check process flow by the perticular device(iphone/ipad)


text:
Q: aes_cbc_128 encrypt/decrypt in c# visual studio Does anyone know what are the settings for salt, nrounds for encryption/decryption in .net c#? I need these information for openssl. I am tying to create an aes_128 with cbc encryption/decryption. In order to create the key I have to know these vaslues too: nrounds and salt. Thx

A: here is the code for aes 128 bytes encryption with cbc and pkcs7
#include <iostream>
#include <sstream>
#include <cstring>
#include <vector>
#include <stdlib.h>
#include <openssl/evp.h>
#define AES_BLOCK_SIZE 128 //256
#include "base64.h"
#include "base64.cpp"
using namespace std;

int aes_init(unsigned char *key_data, int key_data_len, unsigned char *salt, EVP_CIPHER_CTX *e_ctx,
             EVP_CIPHER_CTX *d_ctx)
{
  int i, nrounds = 6;
  unsigned char key[16], iv[16];
    /*
   * Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the supplied key material.
   * nrounds is the number of times the we hash the material. More rounds are more secure but
   * slower.
   */
  i = EVP_BytesToKey(EVP_aes_128_cbc(), EVP_sha1(), salt, key_data, key_data_len, nrounds, key, iv);
  if (i != 16) {
    std::cout<<"Key size is: - should be 256 bits\n "<<i<<std::endl;
    return -1;
  }

  for(int x = 0; x<16; ++x)
{
    std::cout<<"Key: and iv:  \n"<< key[x] <<std::endl;
    iv[x]=0;

}

  for(int x = 0; x<8; ++x)
 {std::cout<<"salt: \n"<< salt[x]<<std::endl;

salt[x]=0; }
  EVP_CIPHER_CTX_init(e_ctx);
  EVP_CIPHER_CTX_set_padding(e_ctx,7);
  EVP_EncryptInit_ex(e_ctx, EVP_aes_128_cbc(), NULL, key, iv);
  EVP_CIPHER_CTX_init(d_ctx);
  EVP_DecryptInit_ex(d_ctx, EVP_aes_128_cbc(), NULL, key, iv);

  return 0;
}

/*
 * Encrypt *len bytes of data
 * All data going in & out is considered binary (unsigned char[])
 */
unsigned char *aes_encrypt(EVP_CIPHER_CTX *e, unsigned char *plaintext, int *len)
{
    if (EVP_CIPHER_CTX_set_padding(e,7)!= 1) std::cout<<"no padding?"<<std::endl;

  /* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
  int c_len = *len + AES_BLOCK_SIZE - 1, f_len = 0;
  unsigned char *ciphertext = (unsigned char *)malloc(c_len);

  /* allows reusing of 'e' for multiple encryption cycles */
  if(!EVP_EncryptInit_ex(e, NULL, NULL, NULL, NULL)){
   std::cout<<"ERROR in EVP_EncryptInit_ex \n"<<std::endl;
    return NULL;
  }

  /* update ciphertext, c_len is filled with the length of ciphertext generated,
    *len is the size of plaintext in bytes */
  if(!EVP_EncryptUpdate(e, ciphertext, &c_len, plaintext, *len)){
   std::cout<<"ERROR in EVP_EncryptUpdate \n"<<std::endl;
    return NULL;
  }

  /* update ciphertext with the final remaining bytes */
  if(!EVP_EncryptFinal_ex(e, ciphertext+c_len, &f_len)){
   std::cout<<"ERROR in EVP_EncryptFinal_ex \n"<<std::endl;
    return NULL;
  }

  *len = c_len + f_len;
  return ciphertext;
}

/*
 * Decrypt *len bytes of ciphertext
 */
unsigned char *aes_decrypt(EVP_CIPHER_CTX *e, unsigned char *ciphertext, int *len)
{
  /* plaintext will always be equal to or lesser than length of ciphertext*/
  int p_len = *len, f_len = 0;
  unsigned char *plaintext = (unsigned char *)malloc(p_len);

  if(!EVP_DecryptInit_ex(e, NULL, NULL, NULL, NULL)){
    std::cout<<"ERROR in EVP_DecryptInit_ex \n"<<std::endl;
    return NULL;
  }

  if(!EVP_DecryptUpdate(e, plaintext, &p_len, ciphertext, *len)){
    std::cout<<"ERROR in EVP_DecryptUpdate\n"<<std::endl;
    return NULL;
  }

  if(!EVP_DecryptFinal_ex(e, plaintext+p_len, &f_len)){
    std::cout<<"ERROR in EVP_DecryptFinal_ex\n"<<std::endl;
    return NULL;
  }

  *len = p_len + f_len;
  return plaintext;
}

int main(int argc, char **argv)
{
  /* "opaque" encryption, decryption ctx structures that libcrypto uses to record
     status of enc/dec operations */
  EVP_CIPHER_CTX en, de;

  /* The salt paramter is used as a salt in the derivation: it should point to an 8 byte buffer or NULL if no salt is used. */
  //unsigned char salt[] = {1,2,3,4,5,6,7,8};
unsigned char salt[]={0,0,0,0,0,0,0,0};
  unsigned char *key_data;
  int key_data_len, i;
  char *input[] = {"convert this string?",
                   NULL};

  /* the key_data is read from the argument list */
  //key_data = (unsigned char *)argv[1];
  //key_data_len = strlen(argv[1]);
  key_data = (unsigned char *) ("hello");
key_data_len = strlen("hello");
  /* gen key and iv. init the cipher ctx object */

  if (aes_init(key_data, key_data_len, salt, &en, &de)) {
  std::cout<<"Couldn't initialize AES cipher\n"<<std::endl;
    return -1;
  }

  /* encrypt and decrypt each input string and compare with the original */
  for (i = 0; input[i]; i++) {
    char *plaintext;
    unsigned char *ciphertext;
    int olen, len;

    /* The enc/dec functions deal with binary data and not C strings. strlen() will
       return length of the string without counting the '\0' string marker. We always
       pass in the marker byte to the encrypt/decrypt functions so that after decryption
       we end up with a legal C string */
    olen = len = strlen(input[i])+1;

    ciphertext = aes_encrypt(&en, (unsigned char *)input[i], &len);
  //  plaintext = (char *)aes_decrypt(&de, ciphertext, &len);
/**/

      std::cout<<"OK: enc ok for: "<< ciphertext<<std::endl;

      std::string encoded_base = base64_encode(ciphertext,strlen((const char*)ciphertext));
      std::cout<<"the encr with base64: "<< encoded_base<<std::endl;

/* DECODING */

std::string decode = base64_decode(encoded_base);
std::cout <<"the decode woth base64: "<<decode<<std::endl;
unsigned char *ciphertext1= (unsigned char *)( decode.c_str() );
std::cout<<"chipertext1: "<<ciphertext1<<std::endl;
//reinterpret_cast< const unsigned char*>*/

char *plaintext1 = (char *)aes_decrypt(&de, ciphertext1, &len);

    if (strncmp(plaintext1, input[i], olen))
      std::cout<<"FAIL: enc/dec failed for: "<< input[i]<<std::endl;
    else
     {

//      std::cout<<"OK: dec ok for: "<< plaintext<<std::endl; // \"%s\"\n

     std::cout<<"the decr with base64: "<<plaintext1<<std::endl;
     }

    free(ciphertext);
    free(plaintext1);
  }

  EVP_CIPHER_CTX_cleanup(&de);
  EVP_CIPHER_CTX_cleanup(&en);

  return 0;
}


text:
Q: Nesting of subexpressions in expression templates We are writing an expression template library to handle operations on values with a sparse gradient vector (first order automatic differentiation). I am trying to figure out how to make it possible to nest sub-expressions by reference or values depending on whether the expressions are temporaries or not.
We have a class Scalar which is containing a value and a sparse gradient vector. We use expression templates (like Eigen) to prevent the construction and allocation of too many temporaries Scalar objects. Thus we have the class Scalar inheriting from ScalarBase<Scalar> (CRTP).
A binary operation (eg +, *) between objects of type ScalarBase< Left > and ScalarBase< Right > return a ScalarBinaryOp<Left, Right,BinaryOp> object which inherits from ScalarBase< ScalarBinaryOp<Left, Right,BinaryOp> >:
template< typename Left, typename Right >
ScalarBinaryOp< Left, Right, BinaryAdditionOp > operator+(
    const ScalarBase< Left >& left, const ScalarBase< Right >& right )
{
    return ScalarBinaryOp< Left, Right, BinaryAdditionOp >( static_cast< const Left& >( left ),
        static_cast< const Right& >( right ), BinaryAdditionOp{} );
}

ScalarBinaryOp must hold a value or reference to the operands objects of type Left and Right. The type of the holder is defined by template specialization of RefTypeSelector< Expression >::Type.
Currently this is always a const reference. It works at the moment for our test cases but this does not seem correct or safe to hold a reference to temporary subexpressions.
Obviously we also do not want that a Scalar object containing the sparse gradient vector be copied. If x and y are Scalar, the expression x+y should hold const reference to x and y. However if f is a function from Scalar to Scalar, x+f(y) should hold a const reference to x and the value of f(y).
Hence I would like to pass the information about whether subexpressions are temporaries or not. I can add this to the expression type parameters:
ScalarBinaryOp< typename Left, typename Right, typename BinaryOp , bool LeftIsTemporary, bool RightIsTemporary >
and to the RefTypeSelector:
RefTypeSelector< Expression, ExpressionIsTemporary  >::Type
But then I would need to define for every binary operators 4 methods:
ScalarBinaryOp< Left, Right, BinaryAdditionOp, false, false > operator+(
    const ScalarBase< Left >& left, const ScalarBase< Right >& right );
ScalarBinaryOp< Left, Right, BinaryAdditionOp, false, true > operator+(
    const ScalarBase< Left >& left, ScalarBase< Right >&& right );
ScalarBinaryOp< Left, Right, BinaryAdditionOp, true, false > operator+(
    ScalarBase< Left >&& left, const ScalarBase< Right >& right );
ScalarBinaryOp< Left, Right, BinaryAdditionOp, true, true > operator+(
    ScalarBase< Left >&& left, ScalarBase< Right >&& right )

I would prefer to be able to achieve this with perfect forwarding. However I do not know how I can achieve this here. First I cannot use simple "universal references" because they match almost anything. I guess it might be possible to combine universal references and SFINAE to only allow certain parameter types but I am not sure this is the way to go. Also I would like to know if I could encode the information about whether Left and Right were originally lvalue or rvalue references in the types Left and Right which parameterize the ScalarBinaryOp instead of using the 2 additional booleans parameter and how to retrieve that information.
I have to support gcc 4.8.5 which is mostly c++11 compliant.
update 2019/08/15: implementation
template < typename Expr >
class RefTypeSelector
{
   private:
   using Expr1 = typename std::decay<Expr>::type;
   public:
   using Type = typename std::conditional<std::is_lvalue_reference<Expr>::value, const Expr1&,Expr1>::type;
};

template< typename Left, typename Right, typename Op >
class ScalarBinaryOp : public ScalarBase< ScalarBinaryOp< Left, Right, Op > >
{

public:

    template <typename L, typename R>
    ScalarBinaryOp( L&& left, R&& right, const Op& op )
        : left_( std::forward<L>(left) )
        , right_( std::forward<R>(right) ))
        , ...
    {
    ...
    }

    ...

private:
    /** LHS expression */
    typename RefTypeSelector< Left >::Type left_;

    /** RHS expression */
    typename RefTypeSelector< Right >::Type right_;

...
}

template< typename Left, typename Right,
typename Left1 = typename std::decay<Left>::type,
typename Right1 = typename std::decay<Right>::type,
typename std::enable_if<std::is_base_of<ScalarBase<Left1>, Left1>::value,int>::type = 0,
typename std::enable_if<std::is_base_of<ScalarBase<Right1>, Right1>::value,int>::type = 0 >
ScalarBinaryOp< Left, Right, BinaryAdditionOp > operator+(
    Left&& left, Right&& right )
{

    return ScalarBinaryOp< Left, Right, BinaryAdditionOp >( std::forward<Left>( left ),
        std::forward<Right>( right ), BinaryAdditionOp{} );
}

A: You can encode lvalue/rvalue information into Left and Right types. For example:
ScalarBinaryOp<Left&&, Right&&> operator+(
    ScalarBase<Left>&& left, ScalarBase<Right>&& right)
{
    return ...;
}

with ScalarBinaryOp being something like this:
template<class L, class R>
struct ScalarBinaryOp
{
    using Left = std::remove_reference_t<L>;
    using Right = std::remove_reference_t<R>;

    using My_left = std::conditional_t<
        std::is_rvalue_reference_v<L>, Left, const Left&>;
    using My_right = std::conditional_t<
        std::is_rvalue_reference_v<R>, Left, const Right&>;

    ...

    My_left left_;
    My_right right_;
};

Alternatively, you can be explicit and store everything by value, except for Scalars. To be able to store a Scalar by value, you use a wrapper class:
x + Value_wrapper(f(y))

The wrapper is simple:
struct Value_wrapper : Base<Value_wrapper> {
    Value_wrapper(Scalar&& scalar) : scalar_(std::move(scalar)) {}

    operator Scalar() const {
        return std::move(scalar_);
    }

    Scalar&& scalar_;
};

RefTypeSelector has specialization for Value_wrapper:
template<> struct RefTypeSelector<Value_wrapper> {
    using Type = Scalar;
};

The binary operator definition remains the same:
template<class Left, class Right>
ScalarBinaryOp<Left, Right> operator+(const Base<Left>& left, const Base<Right>& right) {
    return {static_cast<const Left&>(left), static_cast<const Right&>(right)};
}

Complete example: https://godbolt.org/z/sJ3NfG
(I used some C++17 features above only to simplify the notation.)


text:
Q: How to send an email, using google gmail api in php with cURL? I have a problem sending mail using the Google Api in Php and cURL,
I tried this one:
// ENVOIE EMAIL

$message="To: test@example.com\r\nFrom: test@example.com\r\nSubject: GMail test.\r\n My message";
$email=base64_encode($message);

$url_email = 'https://www.googleapis.com/upload/gmail/v1/users/me/messages/send';

$curlPost = array(
    'raw' => $email,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_email);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $AccessToken, 'Accept: application/json','Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = curl_exec($ch);
// $data = json_decode(curl_exec($ch), true);;
curl_close($ch);
echo '

Send email
';
print_r($data);

But I get an error message like this :

{ "error": { "errors": [ { "domain": "global", "reason": "badContent", "message": "Media type 'application/json' is not supported. Valid media types: [message/rfc822]" } ], "code": 400, "message": "Media type 'application/json' is not supported. Valid media types: [message/rfc822]" } }

And when I tried with :
'Content-Type: message/rfc822';

I have a new error message :

{ "error": { "errors": [ { "domain": "global", "reason": "invalidArgument", "message": "Recipient address required" } ], "code": 400, "message": "Recipient address required" } }

I do not want to use the library offered by google.

A: Looks like you are sending JSON encoded data while you should respect message/rfc822 format.
You should probably not base64-encode + json-encode your message:
<?php
$message = "To: test@example.com\r\nFrom: test@example.com\r\nSubject: GMail test.\r\n My message";

$ch = curl_init('https://www.googleapis.com/upload/gmail/v1/users/me/messages/send');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $AccessToken", 'Accept: application/json', 'Content-Type: message/rfc822'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
$data = curl_exec($ch);


text:
Q: Can every X.509 v3 certificate be used as authenticode certificate I have a X.509 v3 issued by a CA within my company. I am using ClickOnce deployment in Viusal Studio and I want to use code signing. When I click on "Choose from store" the certificate is not shown in the list. That´s why I think it cannot be used as a authenticode certificate.
My question is: Can every X.509 v3 certificate be used as a authenticode certificate for code signing (e.g. in Visual Studio)? And if not: How do I determine whether the certificate is a valid authenticode certificate?
Thanks for reading my question.
Regards
Philipp

A: X.509 certificates used with Authenticode typically would have the Extended Key Usage (EKU) "Code Signing" indicating that the certificate can only be used for code signing purposes.


text:
Q: Asp.net Mvc: Dynamic page title in webforms I would always use my masterpage to set page titles and meta description based on the current url. I was thinking of doing the same for my Asp.net Mvc projects but I ain't sure where to start. It would be nice to be able to set the title/description based on the controller and/or action with some default values incase I don't specify any info. The reason why I do this is because I like everything to be in one place because that makes it easy to spot mistakes.
Edit:
After reading the answers and googling some I was thinking it might be cool to get the info from an xml file. With Xml looking something like this:
<website title="default title for webpage">
    <controller name="HomeController" title="Default title for home controller">
       <action name="Index" title="title for index action" />
    </controller>
</website>

I am new to Asp.net Mvc so I am not sure where to initialize this.

A: I suggest the following strategy:
Create an hierarchy of models:
abstract class MasterModel
{
    public string PageTitle { get; set; }
}

abstract class HomeBaseModel : MasterModel
{
    PageTitle = "Home";
}

abstract class UsersBaseModel : MasterModel
{
    PageTitle = "Users";
}

/************************************/

class HomeNewsModel : HomeBaseModel
{
    PageTitle = "News";
}

class UsersProfileModel : UsersBaseModel
{
    PageTitle = "Profile";
}

You define a master model to hold the page title and you create base models to hold default titles for a controller. This way, you can define the title in each action explicitly or leave it out so that the default title for this controller will be used.
Then in your master view you just write once:
<title><%= Model.PageTitle %></title>

and it's done.

A: You could simply pull that data from the master page's Model, then let that Model have some reasonable defaults.

A: So after a few days of trying stuff I ended up with making a custom filter that reads from a XML file.
I added the code to copypastecode.com
http://www.copypastecode.com/9797/
http://www.copypastecode.com/9809/
http://www.copypastecode.com/9805/
I am very novice at Asp.net Mvc and "real" C# coding so if you see strange stuff please forgive me. If somebody wants to optimize it or has a better solution feel free to post it as an answer.
Next thing I am gonna try is to make it without a filter so it's activated on all controllers. Not sure where to hook up the logic though. So if anybody can push me into the right direction let me know.


text:
Q: How to make columns using a linktable I have the following tables:
packs: pack_id, packtype_id
packtypes: packtype_id, packtype_name
levels: level_id, level_name
levels_in_packtype: level_id, packtype_id

Now I want to display all "packs" in a grid. Packs have no name, they are identified by what packtype and levels they have:
birdpack | USA | California
birdpack | Sweden | Norrland

(birdpack is a packtype, usa and california are levels)
or
temppack | Sweden | Norrland | Umea

(sweden, norrland and umea are levels)
Question: How to write a query so I get a dataset that have columns for all levels that belong to a pack?
I use Postgres.


text:
Q: SQLite in VS2015 MVC 6.0.0-beta8 not working Can't get SQLite to work on an MVC6 beta 8 project.
To reproduce the problem, assuming you have beta 8 already installed in Visual Studio 2015:

*

*Create a new empty WebApi project under ASP.NET 5 Preview Templates

*In project.json, under frameworks remove dnx5, leaving just dnx451

*Create an empty test.dat file in your wwwroot folder

*Install latest 1.0.98.1 SQLite with Nuget: Install-Package System.Data.SQLite

*In startup.cs add using System.Data.SQLite and System.IO and put this 2 lines into public Startup(...
string folder = Directory.GetCurrentDirectory();
SQLiteConnection conn = new SQLiteConnection(@"Data Source="+folder+"test.dat");
Hit F5 and you will get Unable to load DLL 'SQLite.Interop.dll'
There are lot of questions and answers about this topic for previous versions of VS... I tried mostly everything including building for x86 and x64, install other nuget packages (Core / PCL / bare SQLite / Entity, etc) and so on.
There are some workaround copying files by hand, but I need this to deploy on a server without much intervention.
Its hard to believe that the most used compact database in the world can't work out of the box in VS2015, so I'm hopping that I'm doing something incredibly wrong and someone can shed some light.
Thanks.-

A: I feel you try this link SqlLite in EF7. The page refers UWP, but it still can be used with ASP.NET MVC6.

A: Not a real solution but a decent workaround for anyone with the same problem.
Use Microsoft.Data.SQLite
You would need to make some minor adjustment to the class names like SQLiteConnection to SqliteConnection but it works.


text:
Q: StringBuilder remove comma at the end of Last record I am using StringBuilder to show comma between records, but also getting comma at the end of Last Record
How to control on this ? I don't like to see comma at the end of last record - because it's useless
   for (int i = 0; i < arrayList.size(); i++) {

        String name = arrayList.get(i).getName();
        int price = arrayList.get(i).getPrice();

        stringBuilder.append(strName);
        stringBuilder.append(" - "+price+",");

    }

        stringFinal = stringBuilder.toString();

A: Java 8 Solution
You don't need any check when using Java 8. All you need is to use StringJoiner (or String.join()).
StringJoiner joiner = new StringJoiner(",");
for (int i = 0; i < arrayList.size(); i++) {
    String name = arrayList.get(i).getName();
    int price = arrayList.get(i).getPrice();

    joiner.add(strName + " - " + price);
}
String joinedString = joiner.toString();

And you can make it even cleaner by taking advantage of the Stream API (thanks to @Sasha):
String joinedString = String.join(",", list.stream().map(
        e -> e.getName() + " - " + e.getPrice()).collect(Collectors.toList()));

A: Add a check for the last item.
if (i < arrayList.size() - 1) {
  stringBuilder.append(" - "+price+",");
} else {
  stringBuilder.append(" - "+price);
}

or:
stringBuilder.append(" - "+price);
if (i < arrayList.size() - 1) {
  stringBuilder.append(",");
}

A: You can just delete the last character:
 stringBuilder.deleteCharAt(stringBuilder.length()-1);
 stringFinal = stringBuilder.toString();

that would be the simplest solution.

A: int index = stringBuilder.lastIndexOf(",");
if (index != -1){
    stringBuilder.replace(index, index+1, "");
}
String stringFinal = stringBuilder.toString();

A: Or loop till size - 1 and then add the last element after wards without a comma.
int i = 0, price = 0;
String name = null;
for (i = 0; i < arrayList.size() - 1; i++) {
 name = arrayList.get(i).getName();
 price = arrayList.get(i).getPrice();

 stringBuilder.append(strName);
 stringBuilder.append(" - "+price+",");
}

name = arrayList.get(i).getName();
price = arrayList.get(i).getPrice();
stringBuilder.append(strName);
stringBuilder.append(" - "+price);
stringFinal = stringBuilder.toString();

A:     for (int i = 0; i < arrayList.size(); i++) {

    String name = arrayList.get(i).getName();
    int price = arrayList.get(i).getPrice();

    stringBuilder.append(strName);
    if(i== arrayList.size()-1)
       stringBuilder.append(" - "+price);
    else
    stringBuilder.append(" - "+price+",");

     }

    stringFinal = stringBuilder.toString();

A: Instead of placing it in last you can write it in front like :-
        String name = arrayList.get(0).getName();
        int price = arrayList.get(0).getPrice();

        stringBuilder.append(strName).append(" - "+price);
for (int i = 1; i < arrayList.size(); i++) {

        name = arrayList.get(i).getName();
        price = arrayList.get(i).getPrice();

        stringBuilder.append(","+strName).append(" - "+price);

    }

        stringFinal = stringBuilder.toString();


text:
Q: Java Regular Expressions for escaping characters inside quotes I have a document.
All the arithmetic characters (+, -, *, /) in the document; I want to replace with their name (add, sub, mult, div) except if these characters occur inside double quotes.
For example:
a + b;
"a + b";

OUTPUT:
a add b;
"a + b";

You can think of the document as a C program where I want to take arithmetic operations and convert them to their meaning (add, sub, ...) but I don't want to process arithmetic operation if it is inside double quotes.
How can I capture this using Java regular expressions?

A: The following regex (try it on regex101)
[^\"].*(\+|\-|\*|\/).*[^\"]\;

matches:
[^\"] - Anything that's not "
.* - followed by anything
(\+|\-|\*|\/) - The capture group. Captures a +, -, *, or /
.* - followed by anything
[^\"] - Anything that's not "
Since you're using this in Java, you'll have to escape all of the forward slashes again.
Java compatible REGEX:
"[^\\\"].*(\\+|\\-|\\*|\\/).*[^\\\"]\\;"

A: You can use String replaceAll method
Example:
    public class MyTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String operation = "\"a + b / c\"";
        String result = operation.replaceAll("\\+", "add").replaceAll("\\/", "div");
        System.out.println(result);

    }

}

Will output: "a add b div c"

A: Granted this kind of looks like homework, but to me this looks more like a Regex question than a java question.
Here's an example of how you can achieve the output requested in the original question:
$ cat TestRegex.java
public class TestRegex {
    public static void main(final String[] args) {
        String inputString = "c = a + b; cout << \" a + b \";";
        System.out.println("inputString: '" + String.valueOf(inputString) + "'.");
        System.out.println("replace (+, add) ex: '" + String.valueOf(inputString.replaceAll("(\\+)(?=(?:[^\"]|\"[^\"]*\")*$)", "add")) + "'.");
        System.out.println("replacedAll: '" +
            String.valueOf(
                inputString
                .replaceAll("(\\+)(?=(?:[^\"]|\"[^\"]*\")*$)", "add")
                .replaceAll("(\\-)(?=(?:[^\"]|\"[^\"]*\")*$)", "sub")
                .replaceAll("(\\*)(?=(?:[^\"]|\"[^\"]*\")*$)", "mult")
                .replaceAll("(\\/)(?=(?:[^\"]|\"[^\"]*\")*$)", "div")
            ) + "'."
        );
    }
}

With sample output:
$ java TestRegex
inputString: 'c = a + b; cout << " a + b ";'.
replace (+, add) ex: 'c = a add b; cout << " a + b ";'.
replacedAll: 'c = a add b; cout << " a + b ";'.

Modifying the input string further and testing again, I get:
$ java TestRegex
inputString: 'c = a + b + d / e * f - g; cout << " a + b ";'.
replace (+, add) ex: 'c = a add b add d / e * f - g; cout << " a + b ";'.
replacedAll: 'c = a add b add d div e mult f sub g; cout << " a + b ";'.

Hope this helps.

A: My brain hurts.
test1.c
#include <stdio.h>

#define MACRO1 a+b-c*d/e
#define MACRO2 "a+b-c*\
    d/e\
    a + b - c * d / e \
    ", a+b-c*d/e

const char* str = "\
    as\"\\/\"-\\\\+df\
\\""asdf+""-*\\""/""\
";

/* comment + - * /
 a / b * c - d + e */
// comment + - * / blah "+ - * /" \+\\\

char dq = '"'+0*'\"'/'\'';
char* cp = &dq;
const int* ip1;
int const* ip2;
int const * const * ip3;
void* vp;
long (*fp)(int(*));

char *a[23], *ZXCV,
**p2p
,***(xx),
* * c, * * * d[34];

struct s {};
typedef struct s* blah;
struct s s1,*S2;
enum E {E1};
enum E* e;
union U {};
union U* u;

int main(void) {
    int x = 1+2-3*4/5;
    x++ +1; ++x+2;
    x-- -3; --x+4;
    x = - --x;
    x = + ++x;
    x = -- x -3;
    x = ++ x +4;
    x += +1;
    x -= -1;
    x *= +1;
    x /= -1;
    ip1 = (int const *)str;
    int y = * ip1;
    blah *pblah; // can't recognize typedef
    #define OPAQUE int a =
    OPAQUE*ip1; // can't recognize macro
    printf("test: %d %s\n", x, str );
} // end main() 1+2-3*4/5

COpSub.java
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import java.util.Map;
import java.util.HashMap;

import java.nio.file.Files;
import java.nio.file.Paths;

public class COpSub {

    public static void main(String[] args) throws Exception {
        if (args.length != 2) { System.err.println("error: require two arguments."); System.exit(1); }
        String fileName = args[0];
        String encoding = args[1];
        String source = readFile(fileName,encoding);
        System.out.print(sub(source));
        System.exit(0);
    } // end main()

    public static String sub(String s) throws Exception {

        Map<String,String> m = new HashMap<String,String>();
        // note: replacements must be escaped for appendReplacement()!
        m.put("+","plus");
        m.put("+=","plusequals");
        m.put("-","minus");
        m.put("-=","minusequals");
        m.put("*","mul");
        m.put("*=","mulequals");
        m.put("/","div");
        m.put("/=","divequals");
        m.put("++","plusplus");
        m.put("--","minusminus");

        String typeAlternation = "void|char|signed\\s+char|unsigned\\s+char|short|short\\s+int|signed\\s+short|signed\\s+short\\s+int|unsigned\\s+short|unsigned\\s+short\\s+int|int|signed|unsigned|signed\\s+int|unsigned\\s+int|long|long\\s+int|signed\\s+long|signed\\s+long\\s+int|unsigned\\s+long|unsigned\\s+long\\s+int|long\\s+long|long\\s+long\\s+int|signed\\s+long\\s+long|signed\\s+long\\s+long\\s+int|unsigned\\s+long\\s+long|unsigned\\s+long\\s+long\\s+int|float|double|long\\s+double|(?:struct|enum|union)\\s+\\w+|const";
        String safeCluster = ""
            +"(?:"                                               // overarching cluster
            +  "\\s*"                                            // skip over all leading whitespace to get to the interesting stuff
            +  "(?:"                                             // safe extent alternation
            +    "(?:"+typeAlternation+")(?:\\s*\\*)+"           // safe extent #1: pointer (to pointer to pointer...) of type
            +    "|[+-]\\s+[+-]"                                 // safe extent #2: non-lvalue requiring whitespace separation
            +    "|[~!%^&*(=+\\[|;,?-](?:\\s*(?!\\+\\+|--)[+*-](?<!\\+\\+|--))++" // safe extent #3: non-lvalue not requiring whitespace separation -- can't include slash -- must be possessive to not give back part of pre/post increment/decrement -- fix broken vim syntax highlighting: )]
            +    "|[^'\"+*/-]"                                   // safe extent #4: guarantee safe punctuation char
            +  ")"                                               // end safe extent alternation
            +")*+"                                               // possessive gobble of safe extents
        ;

        Pattern pattern = Pattern.compile(""
            +"\\G"                                               // start from previous match, or start-of-string for first search
            +"("                                                 // capture prefix
            +  safeCluster                                       // possessive gobble of safe extents
            +  "(?:"                                             // possessive zero-or-more unsafe extent clusters (possessive required for final match to not give up slash pattern)
            +    "(?:"                                           // unsafe extent cluster alternation (no suffix)
            +      "'\\\\?.'"                                    // unsafe extent #1: single-quoted char
            +      "|\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\""         // unsafe extent #2: double-quoted string; note this has its own internal safe gobble followed by zero-or-more unsafe extent cluster with suffix
            +      "|/\\*[^*]*(?:\\*[^/][^*]*)*\\*/"             // unsafe extent #3: traditional C comments; ditto
            +      "|//[^\\n]*\\n"                               // unsafe extent #4: modern C comments; ditto
            +    ")"                                             // end unsafe extent cluster alternation (no suffix)
            +    safeCluster                                     // unsafe extent cluster safe suffix
            +  ")*+"                                             // end possessive zero-or-more unsafe extent clusters
            +")"                                                 // end capture prefix
            +"(\\+\\+|--|[+*/-]=?)"                              // capture operator
        , Pattern.DOTALL );

        StringBuffer b = new StringBuffer();
        Matcher matcher = pattern.matcher(s);
        boolean lastMatchWasOpAssign = false;
        while (matcher.find()) {
            if (lastMatchWasOpAssign)
                matcher.appendReplacement(b, "$1$2" );
            else
                matcher.appendReplacement(b, "$1 "+m.get(matcher.group(2))+' ' );
            lastMatchWasOpAssign = matcher.group(2).length() == 2 && matcher.group(2).charAt(1) == '=';
        } // end while
        matcher.appendTail(b);
        return b.toString();

    } // end sub()

    public static String readFile(String fileName, String encoding ) throws Exception {
        byte[] encoded = Files.readAllBytes(Paths.get(fileName));
        return new String(encoded, encoding );
    } // end readFile()

} // end class COpSub

Demo
> gcc test1.c -o test1;
> ./test1;
test: -4  as"\/"-\\+df\asdf+-*\/

> javac COpSub.java;
> CLASSPATH=. java COpSub test1.c UTF-8;
#include <stdio.h>

#define MACRO1 a plus b minus c mul d div e
#define MACRO2 "a+b-c*\
    d/e\
    a + b - c * d / e \
    ", a plus b minus c mul d div e

const char* str = "\
    as\"\\/\"-\\\\+df\
\\""asdf+""-*\\""/""\
";

/* comment + - * /
 a / b * c - d + e */
// comment + - * / blah "+ - * /" \+\\\

char dq = '"' plus 0 mul '\"' div '\'';
char* cp = &dq;
const int* ip1;
int const* ip2;
int const * const * ip3;
void* vp;
long (*fp)(int(*));

char *a[23], *ZXCV,
**p2p
,***(xx),
* * c, * * * d[34];

struct s {};
typedef struct s* blah;
struct s s1,*S2;
enum E {E1};
enum E* e;
union U {};
union U* u;

int main(void) {
    int x = 1 plus 2 minus 3 mul 4 div 5;
    x plusplus   plus 1;  plusplus x plus 2;
    x minusminus   minus 3;  minusminus x plus 4;
    x = -  minusminus x;
    x = +  plusplus x;
    x =  minusminus  x  minus 3;
    x =  plusplus  x  plus 4;
    x  plusequals  +1;
    x  minusequals  -1;
    x  mulequals  +1;
    x  divequals  -1;
    ip1 = (int const *)str;
    int y = * ip1;
    blah  mul pblah; // can't recognize typedef
    #define OPAQUE int a =
    OPAQUE mul ip1; // can't recognize macro
    printf("test: %d %s\n", x, str );
} // end main() 1+2-3*4/5

Diff


text:
Q: Cover penetrating powers in Mass Effect 3? Certain powers in Mass Effect 3 are able to penetrate cover such as Shockware and Smash.  These powers are incredibly useful for spamming enemies without exposing yourself to damage.
Are there other powers in Mass Effect 3 that have similar properties?

A: I believe any power that has a radius when used can penetrate cover.
some that come to mind are:

*

*Reave

*Incinerate

*Biotic Strike

*Electric Slash (?)

A: Here are a couple more I can think of:

*

*Shadow strike

*Annihilation Field

*Singularity (it does not go through the cover but if you have a good radius on this skill enemies behind cover will get sucked in)


text:
Q: Combine Similar Strings Value into Unique One I'm fetching a post meta from Wordpress CPT which's returning multiple strings form individually instead of array as shown below:
$data = $calendar->data();
foreach ($data as $event) {
    $days = get_post_meta( $event->ID, 'sp_day', true );
    var_dump($days);
}

string(1) "1" string(1) "1" string(1) "1" string(1) "1" string(1) "1"
string(1) "1" string(1) "2" string(1) "2" string(1) "2" string(1) "2"
string(1) "2" string(1) "2" string(1) "3" string(1) "3" string(1) "3"
string(1) "3" string(1) "3" string(1) "3" string(1) "4" string(1) "4"
string(1) "4" string(1) "4" string(1) "4" string(1) "4" string(0) ""
string(0) "" string(0) "" string(0) "" string(0) "" string(0) ""

I tried to convert it into array like $days = array(get_post_meta( $event->ID, 'sp_day', true )); the dump values were:

array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" }
array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" }
array(1) { [0]=> string(1) "1" } array(1) { [0]=> string(1) "1" }
array(1) { [0]=> string(1) "2" } array(1) { [0]=> string(1) "2" }
array(1) { [0]=> string(1) "2" } array(1) { [0]=> string(1) "2" }
array(1) { [0]=> string(1) "2" } array(1) { [0]=> string(1) "2" }
array(1) { [0]=> string(1) "3" } array(1) { [0]=> string(1) "3" }
array(1) { [0]=> string(1) "3" } array(1) { [0]=> string(1) "3" }
array(1) { [0]=> string(1) "3" } array(1) { [0]=> string(1) "3" }
array(1) { [0]=> string(1) "4" } array(1) { [0]=> string(1) "4" }
array(1) { [0]=> string(1) "4" } array(1) { [0]=> string(1) "4" }
array(1) { [0]=> string(1) "4" } array(1) { [0]=> string(1) "4" }
array(1) { [0]=> string(0) "" } array(1) { [0]=> string(0) "" }
array(1) { [0]=> string(0) "" } array(1) { [0]=> string(0) "" }
array(1) { [0]=> string(0) "" } array(1) { [0]=> string(0) "" }

Than I tried the array_merge() and array_unique()
None of the above steps have solved the issue. As you can see we have repeated values multiple times instead I want them unique to get each value only once such "1, 2, 3, 4, 5, etc."
Suggestions are highly appreciated

A: you can add an empty array before the for loop and inside the for loop you can check if the item exist in the array, if it doesn't exist you add the item to the array.
$data = $calendar->data();
$result = [];
foreach ($data as $event) {
    $days = get_post_meta( $event->ID, 'sp_day', true );
    if(! in_array($days, $result)) {
        $result[] = $days;
    }

}
var_dump($result);


text:
Q: How do I form a Django query with an arbitrary number of OR clauses? I'm using Django 2.0 with Python 3.7.  I want to write a query that returns results if the fields contains at least one of the strings in an array, so I want to set up an OR query.  I have tried this
class CoopManager(models.Manager):
    ...
    # Meant to look up coops case-insensitively by part of a type
    def contains_type(self, types_arr):
        queryset = Coop.objects.all()
        for type in types_arr:
            queryset = queryset.filter(type__name__icontains=type)
        print(queryset.query)
        return queryset

However, this produces a query that ANDs the clauses together.  How do I perform the above but join all the clauses with an OR instead of an AND?
I'm using MySql 5.7 but I'd like to know a db independent solution if one exists.

A: You can create a Q object that constructs this disjunction:
from django.db.models import Q

filter = Q(
    *[('type__name__icontains', type) for type in types_arr],
    _connector=Q.OR
)
queryset = Coop.objects.filter(filter)
Here filter is a Q object that is a disjunction of all the type__name__icontains=type filters.


text:
Q: Generate-pch command failed when embedding Unity to Swift Project I have a Unity app which uses Vuforia. I'm trying to embed this Unity app within a Swift Project. I am following the guide given here Integrating Unity Project into Xcode Swift Project. However when I build the project I get this error:
<unknown>:0: error: generate-pch command failed with exit code 1 (use -v to see invocation)
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

This is my Bridging-Header.h file
#import <Foundation/Foundation.h>

#ifndef BRIDGING_HEADER
#define BRIDGING_HEADER

#import <UIKit/UIKit.h>
#import "UnityUtils.h"
#import "UnityAppController.h"
#import "UnityInterface.h"

#endif /* BRIDGING_HEADER */

This is my project structure:

My xcode Version is 9.2 and Unity Version is 2017.3.1f1
Any suggestions on what I am doing wrong?