text:
Q: Simular Enter en Batch Tengo un script que me descarga automáticamente el backup de un S3. Lo malo es que me pide una confirmación con un enter después de introducir la contraseña así que no es automático al 100%. ¿Alguien sabe si existe alguna forma de simular un enter?
He probado con usar el type de un .txt con un solo enter pero no me ha funcionado:
type archivo_con_un_enter.txt | script.bat

Aquí os dejo el script:
set ano=%date:~6,4%
set mes=%date:~3,2%
set dia=%date:~0,2%
cd %ProgramFiles%\S3 Browser
s3browser-con
s3browser-con.exe download Server:[password] bucket/%ano%-%mes%-%dia%/ C:\Backup

A: Parece que el password debería ir después de Server, tal que así (sin corchetes)
s3browser-con.exe download Server:mi_password bucket/%ano%-%mes%-%dia%/ C:\Backup

Lo probaste así tal cual?
Si no, otra opción sería probar con
echo mi_password|s3browser-con.exe download Server:[password] bucket/%ano%-%mes%-%dia%/ C:\Backup


text:
Q: $_FILES['file_upload']['tmp_name'] is undefined I am writing a upload file page. Here's the html code:
<form action="verify.php" id="upload" method="post" enctype="multipart/form-data">
<input id="file_upload" type="file" name="file_upload" />
<button id="submit" name="submit" type="submit">Upload</button>
</form>

And this is my php code:
if ($_FILES['file_upload']['error']==UPLOAD_ERR_NO_FILE){
    return;
  }
  try{
    $email_add='MY@gmail.com';
    $subject="Driver Verification";
    $mail = $this->emailConfig();
    $mail->addAddress($email_add, "LALALA");  // Add a recipient
    $mail->Subject = $subject;
    echo $_FILES['file_upload']['name'];
    echo $_FILES['file_upload']['tmp_name'];
    $mail->Body    = "This driver requires a verification."
    $mail->AddAttachment($_FILES['file_upload']['tmp_name'],$_FILES['file_upload']['name']);
    if(!$mail->send()) {
      echo 'Message could not be sent.';
      echo 'Mailer Error: ' . $mail->ErrorInfo;
      exit;
    }
    return;
  }
  catch(PDOException $e){
    return;
  }
}

So when I run the code, it just can echo ['name'] but can't echo ['tmp_name'], and thus there's no attachment in the email.
Any thoughts? Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: tr command in awk to change the column values I am using in my shell script TR command in awk to mask the data.  Below example file  affects only first line of the my file when i used tr command in awk. when i use the same in while loop and called the awk command inside of it then its working fine but it taking very long time to get completed. Now my requirement i want to mask many columns[example :$1, $5, $9] in the same file(file.txt) and this should affect the whole file not first line and i want to achieve this as much as faster to mask the data.  Please advise
cat file.txt
 ========
abcbchs,degehek
abcbchs,degehek
abcbchs,degehek
abcbchs,degehek
abcbchs,degehek
abcbchs,degehek,lskjsjshsh
abcbchs,degehek
abcbchs,degehek,lskjsjshsh
OUTPUT
awk -F"," -v OFS=","  '{ "echo \""$1"\" | tr \"a-c\" \"e-f\" | tr \"0-5\" \"6-9\"" | getline $1 }7' file.txt

effffhs,degehek
abcbchs,degehek
abcbchs,degehek
abcbchs,degehek
abcbchs,degehek
abcbchs,degehek,lskjsjshsh
abcbchs,degehek
abcbchs,degehek,lskjsjshsh
Expected output
effffhs,degehek
effffhs,degehek
effffhs,degehek
effffhs,degehek
effffhs,degehek
effffhs,degehek,lskjsjshsh
effffhs,degehek
effffhs,degehek,lskjsjshsh

A: The code you found runs an external shell command pipeline on each input line.  Like you discovered, that's an awfully inefficient way to do what you are asking.  Awk isn't really an ideal choice for this task at all.  Maybe try Perl.
perl -F, -lane '$F[$_] =~ tr/a-c/e-f/ =~ tr/0-5/6-9/ for (0, 4, 8); print join(",", @F)' file

The -F, option is like with Awk, but Perl doesn't automatically split the input line.  With -a it does, splitting into an array named @F, and with -n it loops over all input lines.  The -l is a convenience to remove newlines from each input line and adding one back when you print.
Notice how the columns are numbered from zero, not one, like in Awk; so the indices in the for loop access the first, fifth, and ninth elements of @F.

A: You forgot to close() the command after every invocation. Here's the correct way to write it:
$ cat tst.awk
BEGIN { FS=OFS="," }
{
    cmd="echo '" $1 "' | tr 'a-c' 'e-f' | tr '0-5' '6-9'"
    $1 = ( (cmd | getline line) > 0 ? line : $1 )
    close(cmd)
    print
}

$ awk -f tst.awk file
effffhs,degehek
effffhs,degehek
effffhs,degehek
effffhs,degehek
effffhs,degehek
effffhs,degehek,lskjsjshsh
effffhs,degehek
effffhs,degehek,lskjsjshsh

You also didn't protect yourself from getline failures, hence the extra complexity around the getline call, see http://awk.info/?tip/getline.
Given your comments, this shows how to modify multiple fields (1, 3, and 5 in this case) simultaneously:
$ cat tst.awk
BEGIN { FS=OFS="," }
{
    cmd = "echo '" $0 "' | tr 'a-c' 'e-f' | tr '0-5' '6-9'"
    new = ( (cmd | getline line) > 0 ? line : $1 )
    close(cmd)
    split(new,tmp)
    for (i in tmp) {
        if (i ~ /^(1|3|5)$/) {
            $i = tmp[i]
        }
    }
    print
}

$ cat file
abc,abc,abc,abc,abc
abc,abc,abc,abc,abc,abc,abc
abc,abc,abc,abc,abc,abc
abc,abc,abc,abc

$ awk -f tst.awk file
eff,abc,eff,abc,eff
eff,abc,eff,abc,eff,abc,abc
eff,abc,eff,abc,eff,abc
eff,abc,eff,abc

To handle quotes in the input data:
$ cat tst.awk
BEGIN { FS=OFS="," }
{
    gsub(/'/,SUBSEP)
    cmd = "echo '" $0 "' | tr 'a-c' 'e-f' | tr '0-5' '6-9'"
    new = ( (cmd | getline line) > 0 ? line : $1 )
    close(cmd)
    split(new,tmp)
    for (i in tmp) {
        if (i ~ /^(1|3|5)$/) {
            $i = tmp[i]
        }
    }
    gsub(SUBSEP,"'")
    print
}

$ cat file
a'c,abc,a"c,abc,abc
abc,a'c,abc,a"c,abc,abc,abc
abc,abc,abc,abc,abc,abc
abc,abc,abc,abc

$ awk -f tst.awk file
e'f,abc,e"f,abc,eff
eff,a'c,eff,a"c,eff,abc,abc
eff,abc,eff,abc,eff,abc
eff,abc,eff,abc

If you don't have any particular control char that's guaranteed not to appear in your input, you can create a non-existent string to use instead of SUBSEP above by using the technique described at the end of https://stackoverflow.com/a/29237745/1745001


text:
Q: Using a switch case statement with a List in c# I am having trouble getting a Switch Case statement to work while switching on a list
    List<int> Test = new List<int>(){9, 6, 5};
    switch(Test)
    {
        case new List<int>(){9, 6, 5}:
            Console.Write("Yes");
        break;

        case new List<int>(){2, 4, 8}:
            Console.Write("No");
        break;
    }

I get the error "A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type".
Do switch statements just not work on collection types like List and Arrays?

A: C#11 (as of writing still in preview) got you covered with the list pattern which might look something like this with your example (I can't fully test this, so take it with a grain of salt - @MatthewWatson posted a version without the case guards):
    List<int> Test = new List<int>(){9, 6, 5};
    switch(Test)
    {
        case var _ when Test is [9, 6, 5]:
            Console.Write("Yes");
        break;

        case var _ when Test is [2, 4, 8]:
            Console.Write("No");
        break;
    }

Until then you can do it using case guards like they did here
which might look something like this:
    List<int> Test = new List<int>(){9, 6, 5};
    switch(Test)
    {
        // maybe implement it like some of the answers here https://stackoverflow.com/questions/876508/what-is-the-best-way-to-check-two-listt-lists-for-equality-in-c-sharp
        case var _ when Helper.AreEquivalent(Test, new List<int>(){9, 6, 5}):
            Console.Write("Yes");
        break;

        case var _ when Helper.AreEquivalent(Test, new List<int>(){2, 4, 8}):
            Console.Write("No");
        break;
    }

A: You can use the new C# 11 pattern matching to solve this. You can enable it now in Visual Studio 2022 (in preview form) if you add the following to your project file (assuming SDK-style projects):
<LangVersion>preview</LangVersion>

Be aware that preview features might change before C# 11 is released, so you can't rely on this C# 11 feature until then.
Then you can write a switch statement like this:
switch (Test)
{
    case [9, 6, 5]:
        Console.WriteLine("Yes");
        break;

    case [2, 4, 8]:
        Console.WriteLine("No");
        break;
}

Note that if you were trying to return a value rather than call a void-returning method, you could use a Switch Expression instead, which is nicer for some things.
Suppose you were returning a string instead:
Console.WriteLine(Test switch
{
    [9, 6, 5] => "Yes",
    [2, 4, 8] => "No",
    _         => "Other"
});

But of course if you're using a switch expression, you MUST provide a default value for it to return if no match for the cases is found.

A: Switch statement only works on primitive data type i.e. int, string, bool etc.
You can use the if else condition for this.


text:
Q: Is it true that this function $f(n)=n^{13}$?
Assume strictly monotone increasing function;
   such that $f:N^{+}\to N^{+}$, $h$ for all
  $n\in N^{+}$,
  $$f(f(f(n)))=f(f(n))\cdot f(n)\cdot n^{2015}$$
Prove or disprove:$f(n)=n^{13}$

Put $n=1,f(1)=m$
$$f(f(m))=mf(m)$$
Put $n=m$,
$$f(f(f(m)))=f(f(m))f(m)m^{2015}\Longrightarrow f(mf(m))=m^{2016}(f(m))^2$$
  What about following?

A: Re-arranging:
$h(n) = \dfrac{f(f(f(n)))}{f(f(n))\cdot f(n)} = n^{2015} $
Suppose $f(n) = n^{k}$:
$\dfrac{n^{k^3}}{n^{k^2 + k}} = n^{2015} $
$k^3 - k^2 - k - 2015 = 0$
which has solutions of $\{13, -6 \pm i \sqrt{119} \}$. The complex solutions oscillate, so $k = 13$. Clearly, $h(n)$ is unique and of the form $n^k$, and there's only one mapping from $f$ to $h$, so $f(n$) is unique.
EDIT: Regarding solutions not of the form $n^k$, define $g(n) = f(f(n))$
$f(g(n)) = g(f(n)) = g(n) \cdot f(n) \cdot n^{2015} $
We have to deal with the $n^{2015}$ term as it is of the form $n^k$. Suppose that $f(n) = \dfrac{l(n)}{n^{a}}$ and $g(n) = \dfrac{m(n)}{n^{b}}$ where $a+b = 2015$ and $l$ and $m$ are non-power series solutions by hypothesis:
$\dfrac{l\left(\dfrac{m(n)}{n^b}\right)}{n^a} = \dfrac{m(n)}{n^{b}}  \cdot \dfrac{l(n)}{n^{a}} \cdot n^{2015}$
$l\left(\dfrac{m(n)}{n^b}\right) = m(n) \cdot l(n) \cdot n^{2015 - b}$
but $f(g(n)) = g(f(n))$, so
$\dfrac{m(l(n))}{n^b} = m(n) \cdot l(n) \cdot n^{2015 - b}$
$m(l(n)) = l(n) \cdot m(n) \cdot n^{2015} $
Which is what we started with. Therefore, both $f(g(n))$ and $g(f(n))$ must produce $n^{2015}$, but neither $f(n)$ nor $g(n)$ may contain $n^{\pm q}$ by hypothesis and then redundancy.

A: No, there are many such functions. For convenience (to avoid writing $\mathbb{N}^+$ too much) my intervals will only consist of natural numbers, so I'll write $[a, b]$ to mean $\mathbb{N}^+ \cap [a, b]$ and $(a, b)$ to mean $\mathbb{N}^+ \cap (a, b)$ below.
Consider any $f$ defined as follows: first let $f(1) = 1$ and $f(n) = n^{13}$ for $n$ of the form $n = 2^{13^k}$ ($k \geq 0$), so clearly $f$ satisfies the functional equation for $n = 1, 2^{13^k}$. We'll now inductively define $f$ on $A_k = [2^{13^k}, 2^{13^{k+1}}]$ for each $k \geq 0$, so that $f$ is strictly increasing on $A_k$. Note that since we already have $f(2^{13^k}) = 2^{13^{k+1}}$ and $f(2^{13^{k+1}}) = 2^{13^{k+2}}$, $f$ being strictly increasing will imply $f^{-1}(A_{k+1}) = A_k$.
First, for $k = 0, 1$, let $f|(2^{13^k}, 2^{13^{k+1}})$ be any strictly increasing function from $(2^{13^k}, 2^{13^{k+1}})$ to $(2^{13^{k+1}}, 2^{13^{k+2}})$ (where there is at least one such function since the second set is larger than the first), so clearly $f$ is increasing on $[2^{13^k}, 2^{13^{k+1}}] = A_k$.
Now let $k \geq 2$. Assume we've defined $f$ on $A_0, \dots, A_{k-1}$, hence on all $n \leq 2^{13^k}$. We define $f$ on $A_k$ in two steps. First, to ensure that $f$ satisfies the functional equation, we only need to correctly set the values of $f(f(f(n)))$, i.e. to correctly set the values of $f(a)$ for $a$ in the image of $f^2$. Since our $f$ will satisfy $f^{-1}(A_{i+1}) = A_i$ for each $i$, the image of $f^2$ in $A_k$ will be exactly $f(f(A_{k-2}))$; we already know these points since we've defined $f$ on $A_{k-2}$ and $A_{k-1}$. Second, since the definition in the first step will actually guarantee that $f$ is strictly increasing on the image of $f^2$, to make $f$ strictly increasing on all of $A_k$ we only need check that that there's enough room to assign $f$-values to the remaining points.
Step 1: Defining $f$ on $f(f(A_{k-2}))$. Write $f(f(A_{k-2})) = \{a_0, \dots, a_r\}$ where $a_0 < a_1 < \cdots < a_r$, so in particular since $f(f(2^{13^{k-2}})) = 2^{13^k}$ and $f(f(2^{13^{k-1}})) = 2^{13^{k+1}}$ we have $a_0 = 2^{13^k}$ and $a_r = 2^{13^{k+1}}$. For each $a_i$ we have $a_i = f(f(m_i))$ for some $m_i \in A_{k-2}$, hence for $0 < i < r$ we define
$$f(a_i) := f(f(m_i)) f(m_i) m_i^{2015} = a_i f(m_i) m_i^{2015}$$
by necessity (to satisfy the functional equation), where this already holds for $i = 0, r$. Note that $m_0 < m_2 < \cdots < m_r$ since $f^2$ is strictly increasing on $A_{k-2}$.
Step 2: Defining $f$ on $A_k \setminus f(f(A_{k-2}))$. Having now defined all $f(a_i)$, we define $f$ on each $(a_i, a_{i+1})$ to be any strictly increasing function $(a_i, a_{i+1}) \to (f(a_i), f(a_{i+1}))$. There is more than one such function since
\begin{align*}
f(a_{i+1}) - f(a_i)
&= a_{i+1} f(m_{i+1}) m_{i+1}^{2015} - a_i f(m_i) m_i^{2015} \\
&> (a_{i+1} - a_i) f(m_i) m_i^{2015} \\
&> a_{i+1} - a_i
\end{align*}
which means $|(f(a_i), f(a_{i+1}))| > |(a_i, a_{i+1})|$. $f$ is now defined and strictly increasing on each $[a_i, a_{i+1}]$, so it's defined and strictly increasing on $[a_0, a_r] = A_k$.
After the induction, we've defined an $f$ which is strictly increasing on each $A_k$, hence strictly increasing on all of $\mathbb{N}^+$. The functional equation holds, since for any $n \neq 1$, we have $n \in A_k$ for some $k$, hence by our definition of $f$ at $f(f(n)) \in A_{k+2}$, $f$ satisfies the functional equation at $n$. To conclude, note that for each $k$ we made at least one choice (since $|A_k| > |A_{k-2}|$, so the set $A_k \setminus f(f(A_{k-2}))$ is nonempty). This means there are uncountably many (at least $|2^{\mathbb{N}}|$) functions $f$ which can be constructed this way, each of which is strictly increasing and satisfies the functional equation.

A: Let us denote by $f^{[k]}(n)$ the $k$th iterate of $f$. I cannot prove the claim, but I can prove that for all integers $n>1$ we have
$$
\lim_{k\to\infty}\frac{\log f^{[k+1]}(n)}{\log f^{[k]}(n)}=13.
$$
This is some kind of asymptotic evidence in favor of $f(n)=n^{13}$ being the only solution - alas, anything but conclusive.
This is seen as follows. We first prove that for all $k\ge3$ we have
$$
f^{[k]}(n)=f^{[2]}(n)^{A_k} f(n)^{B_k} n^{C_k}\qquad(*)
$$
for the sequence of vectors of positive integer determined by the recurrence relations
$$
\left(\begin{array}{r}
A_2\\B_2\\C_2\end{array}\right)=\left(\begin{array}{r}
1\\0\\0\end{array}\right),\qquad
\left(\begin{array}{r}
A_{k+1}\\B_{k+1}\\C_{k+1}\end{array}\right)=M\left(\begin{array}{r}
A_k\\B_k\\C_k\end{array}\right),
$$
where $M$ is the $3\times3$ matrix
$$
M=\left(\begin{array}{crr}
1&1&0\\1&0&1\\2015&0&0\end{array}\right).
$$
The proof follows from the given functional equation of $f$ by induction on $k$. The case $k=3$ is exactly the functional equation. The inductive step follows from the induction hypothesis by substituting $f(n)$ in place of $n$ and again applying the given functional equation.
The eigenvalues of $M$ are $\lambda_1=13$ and $\lambda_{2,3}=-6+i\sqrt{119}$.
The key is that of these $\lambda_1$ has the largest absolute value. Furthermore, if we write the vector
$$
(A_2,B_2,C_2)^T=x_1e_1+x_2e_2+x_3e_3
$$
in terms of unit eigenvectors $e_1,e_2,e_3$ belonging to the respective eigenvalues, we see that $x_1\neq0$.
For any $k\ge3$ we then have
$$
(A_k,B_k,C_k)^T=\lambda_1^{k-2}x_1e_1+\lambda_2^{k-2}x_2e_2+\lambda_3^{k-2}x_3e_3.
$$
For very large values of $k$ the first component dominates, and consequently
$$
\lim_{k\to\infty}\frac{A_{k+1}}{A_k}=\lim_{k\to\infty}\frac{B_{k+1}}{B_k}=\lim_{k\to\infty}\frac{C_{k+1}}{C_k}=13.
$$
It takes a while to see these limits if you calculate them. For some numerical support I fired up my Mathematica. The entrywise ratios of $M^{129}$ and $M^{128}$ are all in the interval $(12.9,13.2)$.
The claim follows from this by taking logarithms from $(*)$.

I don't know if this helps. It does seem to me that we should concentrate on large values of $n$ and asymptotics first. If only we could prove that $f$ must be a homomorphism of multiplicative monoids. Then it being strictly increasing would force it to a power function, and we know the exponent. If we know that $f$ is a power function the exponent can be determined without resorting to the above asymptotic gymnastics.


text:
Q: How to show data from firebase database in TableLayout android I searched and didn't find any method to show data that retrieved from firebase databse in a tablelayout.

A: To show the data on the table layout you can create:

*

*An adapter, which is the same way as putting data on the recyclerview or the listview. ref: Android: Customize list view, Table view in adapter

*Manual putting tablerow on the table layout


text:
Q: Django, change username form I'm trying to create a modelform to allow users to change their username. I'm trying to do this using FormView instead of UpdateView because I want to include other forms (user management functionality) in this view eventually.
Relevant forms.py:
    class FormHorizontalModelForm(forms.ModelForm)
        def __init__(self, *args, **kwargs):
            super(FormHorizontalModelForm, self).__init__(*args, **kwargs)
            self.helper = FormHelper()
            self.helper.form_class = 'form-horizontal'

    class PlayerRenameForm(FormHorizontalModelForm):
        def __init__(self, user, *args, **kwargs):
            super(PlayerRenameForm, self).__init__(*args, **kwargs)
            self.helper.add_input(Submit('change_username', 'Change Username'))

        class Meta:
            model = User
            fields = ('username',)

        def save(self):
            pass # I figured this might be saving the object since this is inherited off ModelForm

        def form_valid(self, form):
            self.change_username(new_username = self.cleaned_data['username'])
            # self.send_email(new_username = self.cleaned_data['username'])

        def change_username(self, new_username):
            player = Player.objects.get(user = self.instance)
            self.instance.username = new_username
            self.instance.save()
            player.changed_username = True
            player.save()

views.py
    class AccountView(UserAuthenticationMixin, FormView):
        template_name = 'game/profile.html'
        success_url = '/accounts/'
        form_class = PlayerRenameForm
        form_class_two = CrispyPasswordSetForm
        form_class_three = CrispyPasswordChangeForm

        def get_context_data(self, **kwargs):
            context = super(AccountView, self).get_context_data(**kwargs)
            if 'form' not in context:
                context['form'] = self.form_class(user = self.request.user, data = (self.request.POST or None))
            if 'password_set_form' not in context:
                context['password_set_form'] = self.form_class_two(user = self.request.user, data = (self.request.POST or None))
            if 'password_change_form' not in context:
                context['password_change_form'] = self.form_class_three(user = self.request.user, data = (self.request.POST or None))
            return context

        def form_invalid(self, **kwargs):
            return self.render_to_response(self.get_context_data(**kwargs))

        def get_form(self, form_class):
            return form_class(user = self.request.user, **self.get_form_kwargs())

        def post(self, request, *args, **kwargs):
            if 'change_username' in request.POST:
                form = self.form_class(user = request.user, instance = request.user, data = self.request.POST)
                form_name = 'form'
            elif 'set_password' in request.POST:
                form = self.form_class_two(user = request.user, data = self.request.POST)
                form_name = 'password_set_form'
            elif 'change_password' in request.POST:
                form = self.form_class_three(user = request.user, data = self.request.POST)
                form_name = 'password_change_form'

            if form.is_valid():
                return self.form_valid(form)
            else:
                return self.form_invalid(**{form_name: form})

The form returns valid, and returns to success_url. I know for a fact that it is passing into the correct part of the post function since I have stripped away the other parts to ensure that was working.


text:
Q: MVC - Best pattern (UoW + Repositories + Services + DI) I've been doing mvc for some time, but it's my first contact with DI.
I started a new project with Ninject which seems pretty simple and easy to understand, however almost every tutorial I saw has UoW, Repositories and Services.
What I understand is that:

*

*Repositories - Abstract Layer for interactions with EF / MongoDB / XML / Whatever may be a database (CRUD Operations)

*UoW - Set of operations that correlate together, it may use N repositories to perform tasks that will be used in Controllers

*Services I don't really get the point of this, it seems just one more step as it uses multiple UoW's to perform "more tasks"? I'm lost in this one.

Ok, it took me some time to "eat" the Repository thing since i prefer to pass the EF Context trough the UoW.
Is it ok if i forget the Repository and just use the context? Or is it used for any Unit Test task?
What's the Service's usage?
Since I may perform every actions/tasks inside UoW and then call it inside the controllers.
Is there any better set of patterns to use?

A: Since these are very common and you might be talking about either, I'm going to give a brief explanation about each.
Domain Services: When you have an entity and you start to push logic into it, you might get to a point where part of the logic doesn't really belong to that entity, so you create a Domain Service to abstract this logic away. An example would be:
public class Shipment
{
    ...
    public void CalculateFee(IFeeCalculatorService feeCalculatorService)
    {
        ... Any additional and entity relevant logic for fee calculation can be here as well.
        this.Fee = feeCalculatorService.Calculate();
    }
    ...
}

Application Services: These are the services that you will be calling from your controllers to encapsulate the operations needed for a specific task. Let's say you have a controller to receive a friendship request approval or rejection. Your Application Service should receive enough data to be able to:

*

*Find the friendship request domain entity

*Call its approve or reject method

*Call the methods to persist that change back to the database

*Return relevant information to the controller

Infrastructure Services: These services will abstract the logic that is not related to the business, but related to how the application works. An example would be a service to validate security tokens received on your requests, or to perform logging activities.

A: EFs DBContext already implements both the UoW and Repository patterns, so yiu have no benefit of implementing those again in yiur own code.
Services are a way to abstract business logic so it can be reused


text:
Q: How to add both character encoding and the attachment for response? I have a requirement to set both character encoding and the attachment for the responseheader
during file download. How can I do that?
ResponseBuilder lResBuild = Response.ok(lResult);
lResBuild.type("application/vnd.ms-excel");
lResBuild.header("Content-Type", "text/xml; charset=UTF-16LE");
lResponse = lResBuild.build();
lResponse = Response.ok(lResponse).header("Content-Disposition",
    "attachment; filename = " + lFileName + ".xls").build();

Something like this. For special characters I am getting underscore.


text:
Q: Get Host's IP Address and HTTP Status, following redirects I'm building a little web app that will ping an array of domains and return their status, letting me monitor if they're up or down, pointing to the right servers, etc. (live example that may or may not be working)
I started out using exec("ping -n 3 -w 3 {$_POST['host']}", $output, $status); and am now using exec("traceroute -w 1 {$_POST['host']}", $output, $status); and grabbing the last $output and matching the IP there.
This works for the most part except I'm noticing it's not following 301 redirects, etc.
For example a traceroute on myrayhawk.com yields something like:
 1  192.168.1.1 (192.168.1.1)  0.495 ms  0.683 ms  0.911 ms
 2  10.71.96.1 (10.71.96.1)  32.220 ms  55.987 ms  57.109 ms
 3  ip68-4-12-93.oc.oc.cox.net (68.4.12.93)  58.231 ms  59.353 ms  60.424 ms
 4  68.4.15.242 (68.4.15.242)  72.339 ms  73.451 ms  74.641 ms
 5  ip68-4-11-16.oc.oc.cox.net (68.4.11.16)  76.265 ms  77.383 ms  79.591 ms
 6  ip68-4-11-94.oc.oc.cox.net (68.4.11.94)  143.201 ms  18.749 ms  41.717 ms
 7  langbprj01-ae1.rd.la.cox.net (68.1.1.13)  42.843 ms  43.971 ms  68.194 ms
 8  reserved.metro.la.ipv4.godaddy.com (206.223.123.32)  45.094 ms  70.501 ms  69.329 ms
 9  ip-97-74-253-94.ip.secureserver.net (97.74.253.94)  71.622 ms  72.754 ms  74.844 ms
10  ip-97-74-253-94.ip.secureserver.net (97.74.253.94)  108.322 ms  112.058 ms  109.446 ms

11  ip-97-74-253-98.ip.secureserver.net (97.74.253.98)  110.589 ms  37.376 ms  38.861 ms
12  ip-97-74-254-134.ip.secureserver.net (97.74.254.134)  68.868 ms  70.791 ms  72.282 ms
13  ip-184-168-86-185.ip.secureserver.net (184.168.86.185)  82.400 ms  76.183 ms  78.540 ms

But doing the same on rayhawk.com since I know there's a 301 redirect in there:
 1  192.168.1.1 (192.168.1.1)  0.738 ms  0.868 ms  1.174 ms
 2  10.71.96.1 (10.71.96.1)  95.723 ms  119.914 ms  122.994 ms
 3  ip68-4-12-89.oc.oc.cox.net (68.4.12.89)  123.558 ms  124.115 ms  124.679 ms
 4  68.4.15.240 (68.4.15.240)  127.319 ms  127.933 ms  128.523 ms
 5  ip68-4-11-16.oc.oc.cox.net (68.4.11.16)  126.672 ms  132.373 ms  131.802 ms
 6  ip68-4-11-94.oc.oc.cox.net (68.4.11.94)  130.986 ms  65.913 ms  64.542 ms
 7  langbprj01-ae1.rd.la.cox.net (68.1.1.13)  89.395 ms  88.751 ms  88.113 ms
 8  reserved.metro.la.ipv4.godaddy.com (206.223.123.32)  97.840 ms  89.999 ms  90.593 ms
 9  po36.trma0202-01.bbn.mgmt.phx3.gdg (216.69.188.33)  98.454 ms  99.034 ms  115.921 ms
10  po36.trma0202-01.bbn.mgmt.phx3.gdg (216.69.188.33)  114.698 ms  114.032 ms  115.263 ms
11  * * *
12  * * *
13  * * *
14  * * *
15  * * *

I've tried using wget --spider hostname.com but wget doesn't like to work nicely in php exec() calls.
When doing a wget in plain SSH I get:
Resolving rayhawk.com... 72.167.131.159
Connecting to rayhawk.com|72.167.131.159|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: http://www.rayhawk.com/ [following]
Spider mode enabled. Check if remote file exists.
--2012-04-12 11:37:42--  http://www.rayhawk.com/
Resolving www.rayhawk.com... 72.167.131.159
Connecting to www.rayhawk.com|72.167.131.159|:80... connected.
HTTP request sent, awaiting response... 200 OK

And could then parse out the stuff I wanted.
How can I resolve the final location of a host and retrieve it's HTTP status code in PHP?

A: I've written a blog post about how to get the trail of HTTP redirects that can happen, it comes with code examples:

*

*HEAD first with PHP Streams + Updated codepad viper example
Example output for http://example.com/:
Status code (after all redirects): 200
Number of responses: 2 (1 Redirect(s))
* http://example.com/ -- 302 --> http://www.iana.org/domains/example/

You find a more in depth discussion of the code in the answer to a related question HTTP response code after redirect.


text:
Q: SetBackgroundImage prevents animation to run properly For some reason my animation does not run properly when I change the background of my button. I am new to animations was trying something new. I don't really need to change the background but it was how I had it in sketch and in my opinion it looks better when it is changed.
Code:
@IBAction func didTapWithUsername(sender: AnyObject)
    {
        // When this button is tapped the two buttons below should move down far enough to reveal
        // two labels and two textboxes
        // choose animation
        if(userBtnTapped == 0)
        {
            tappedwithUserAnimationForSeperate()
            userBtnTapped = 1
            self.withUserNameBtn.setBackgroundImage(UIImage(named: "loginUserbtnWithFill.png"), forState: UIControlState.Normal)
        }
        else
        {
            tappedwithUserAnimationForClose()
            userBtnTapped = 0
            self.withUserNameBtn.setBackgroundImage(UIImage(named: "LoginWithUserbtn.png"), forState: UIControlState.Normal)
        }

    }

animation functions:
func tappedwithUserAnimationForSeperate()
{

    UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 5.0, options: [], animations: ({

        // code for animation goes here here
        self.withUserNameBtn.center.y = self.withUserNameBtn.center.y - 60
        self.withFBbtn.center.y = self.withFBbtn.center.y + 60
        self.signUpBtn.center.y = self.signUpBtn.center.y + 60

    }), completion: nil)
}

func tappedwithUserAnimationForClose()
{

    UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 5.0, options: [], animations: ({

        // code for animation goes here here
        self.withUserNameBtn.center.y = self.withUserNameBtn.center.y + 60
        self.withFBbtn.center.y = self.withFBbtn.center.y - 60
        self.signUpBtn.center.y = self.signUpBtn.center.y - 60

    }), completion: nil)
}


text:
Q: Mule: Thread count under load with doThreading="false" we have a mule app with HTTP inbound endpoint and I'm trying to figure out how to control the thread count under load. As an experiment I have added the following configuration:
<core:configuration>
    <core:default-threading-profile doThreading="false" maxThreadsActive="500" poolExhaustedAction="RUN"/>
</core:configuration>

Under load I'm seeing the thread count peak at over 1000 threads. Am not sure why this is the case give the maxThreadsActive setting and the doThreading="false". Reading about poolExhaustedAction="RUN", I would expect the listener thread to block while processing inbound requests rather than spawn new ones, and finally reject the connection if its backlog queue is full. I never see rejected client connections.
Does Mule maintain a separate thread pool for each inbound endpoint in the app (sorry if this is in the documentation)? Even if so, don't think it helps explain what I'm seeing.
Any help appreciated. We are running a number of mule apps in one container and I'd like to control the total number of threads.
Thanks, Alfie.

A: Clearly the doThreading attribute on default-threading-profile is not enough to control Mule threading as a whole nor limit with a global cap the specific threading behaviour of transports. I reckon you're getting 500 threads for the HTTP message receiver pool and 500 for the VM message dispatcher pool.
I strongly suggest you reading about tuning Mule: http://www.mulesoft.org/documentation/display/current/Tuning+Performance
My gut feel is that you need to

*

*configure threading on each transport (VM, HTTP), strictly specifying the pool size for receivers and dispatchers,

*select flow processing strategies that prevent Mule from spawning new threads (i.e. use synchronous to hog the receiver threads),

*select exchange patterns that also prevent Mule from spawning new threads (i.e. use request-response to piggyback the current execution thread).


text:
Q: Is there a way to override sensor data? I plan to make an app that send data sensors and another that receive them. The next step is that received data has to be used for the phone (replace/override internal sensors data with received one), a basic usage of this would be to deport all sensors.
Of course, the problem is the receiver part, as I would like to use received data sensors on any other app (games, Google Maps, Camera feed ...).
I found two options that I think are not practical :

*

*Modifying the kernel to add a driver to a virtual sensors that I could add data so that any app will read from this virtual sensor. (I don't know if this is feasible)

*Use XPOSED as I found a VirtualSensor project by Frazew (https://github.com/Frazew/VirtualSensor/blob/master/app/src/main/java/fr/frazew/virtualgyroscope/XposedMod.java) so that any calls to registerListener is redirected to a custom and modified methods implementation.
But both would need systems modifications and is unpractical for publishing the app (either flash the system or install XPosed on the device).
Thanks for any reply to any another methods or feasability issues I may encounter !


text:
Q: How to set default value of a directory path as a project setting In a winform C# project, I added HomeDir as a directory path in the project settings. I want to set its initial value to Documents folder. This directory is not a constant string, so I can't use it in the setting dialog and also in the Settings.Designer.cs something like :
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments))]
    public string HomeDir
    {
        get
        {
            return ((string)(this["HomeDir"]));
        }
        set
        {
            this["HomeDir"] = value;
        }
    }

It will give the following error:

Error 1   An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

A: well, if HomeDir is not set in Settings (or path doesn't exist), use:
string docs = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);

to get Documents folder full path


text:
Q: An unhandled exception of type 'System.ArgumentNullException' occurred in Microsoft.Extensions.Logging.Abstractions.dll: 'Value cannot be null.' This is my Program.cs class
 private static void ConfigureServices(ServiceCollection services)
 {
         var serilogLogger = new LoggerConfiguration()
           .WriteTo.File("TheCodeBuzz.txt")
           .CreateLogger();

            services.AddLogging(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Information);
                builder.AddSerilog(logger: serilogLogger, dispose: true);
            });

}

And This is My MainForm.cs as I am designing a desktop application
partial class MainForm : IDisposable
{
     private readonly ILogger _logger;

     public MainForm(ILogger logger)
     {
          _logger = logger;
     }

     private void Hello()
     {
         _logger.LogInformation("message");
     }
}

_logger.LogInformation throws a run time error i.e. An unhandled exception


text:
Q: Does JQuery Toggle() function only supports div to hide? I'm trying to set up a toggle function to show more content IN A TABLE.
So here it is, I can't do much things with my
, I don't know if its because I missed something or because toggle() only works with
 ?
Here is what I did :
The script

The button :

Show more

The table (the tr to Toggle):

        <img id="tableImage" src="<?php echo base_url($product['image_url'])?>" alt="product" width="121"/>

        <?php echo $product['title'] ?>

        <?php
            $options = array(
                         '0'  => '0',
                         '1'  => '1',
                         '2'  => '2',
                         '3'  => '3',
                         '4'  => '4',
                         '5'  => '5',
                         '6'  => '6',
                         '7'  => '7',
            );

            if($product['quantity']==0){
               $value[$product['title']] = set_value('quantity'.$product['title']);
            }else{
               $value[$product['title']] = $product['quantity'];
            }

            $data0 = 'class="quantSelect" value="'.$value[$product['title']].'" id="quant'.$product['title'].'"';
            echo    form_dropdown('quantity'.$product['title'], $options, $value[$product['title']],$data0);
        ?>

        <?php echo $product['price'] ?>

    <td id="<?php echo 'price'.$product['title']?>">$<?php echo $total[$product['title']] ?>

A: How about toggleClass?
$('.more-info').click(function() {
    $(this).toggleClass('hidden');
    return false;
});

.hidden {
    display: none;
}

Other thing, why don't you separate PHP from HTML?
reference
This demo can help you.

A: .toggle() is definitely not limited just to div elements, indeed it appears to work fine with tr elements: http://jsfiddle.net/sdWVU/ - including if you specify a duration: http://jsfiddle.net/sdWVU/1/
However, your code doesn't actually use .toggle(), it uses .slideToggle(). That doesn't "work" with a tr element in the sense that it does hide and show the element but it doesn't slide it: http://jsfiddle.net/sdWVU/2/ The lack of slide effect is a limitation of how tables work.
If you want to make the row hide and show with animation I suggest .toggle('slow').


text:
Q: How do I check for two words on a string using include()? I've tried &&, ||, and some other comparison methods between the words. Currently, it's like this:
if(str.includes("a", "b") {
console.log(a and b received)
}

And the problem is that currently, it logs that a and b received even if the string only has a, when I only want it to log that if the string has both a and b. Does anyone know what's the proper command for this? (ps I'm a total noob to js and I have no idea am I even supposed to use include() for something like this)

A: if(str.includes("a") && str.includes("b")) {
console.log(a and b received)
}

should do it.

A: There are various method:
Method 1 - using includes
 str.includes("a") && str.includes("b")

Method 2 - using indexOf
str.indexOf("a") > -1 && str.indexOf("b") > -1

Method 3 - using contains
str.contains("a") && str.contains("b")

Method 4 - using search
str.search('a') > -1 && str.search('a') > -1

Method 5 - using match
str.match('a') && str.match('b')

Method 6 - using RegExp
RegExp('a').test(str) && RegExp('a').test(str)

A: if(str.includes("a") && str.includes("b")) {
  console.log("a and b received")
}

You can also read from the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes, that includes function receives only a valueToFind argument (plus an optional fromIndex One), and that's the reason why your approach doesn't work.

A: if(str.includes('word1') && str.includes('word2')){
  console.log("word1 and word2 received");
}

A: A canonical solution is to take a quantifier, like Array#every and take the result.
The advantage is to have the option to add more values to the array for checking isntead of adding another condition for a check.
if (["a", "b"].every(part => str.includes(part)) {
    console.log('str contains a and b');
}

A: As you can read on the docs the .includes() method determines whether one string may be found within another string, returning true or false as appropriate.
Can take up to 2 parameters the second parameter is optional (by default is 0) and indicates de position where is going to start the searching.
.includes() method is case sensitive so be aware of that.

let str = "Helloab World";

if ( str.includes("a") && str.includes("b") ){
  console.log( "a and b received" )
} else {
  console.log("String do not containt a or b")
}

// Example with the second parameter.
// Would go to the else statement because it would
// start searching from the 8th position of the string
console.log("Second if statement start here")
if ( str.includes("a", 8) && str.includes("b", 8) ){
  console.log( "a and b received" )
} else {
  console.log("String do not containt a or b")
}

Hope this example can help you a little.


text:
Q: AWS Amplify CLI commands give no return value at all unless run with sudo After installing amplify with npm, any amplify command simply returns with no result. No error, no value. If run with sudo, I get a result.
After contacting AWS, I got the answer, so sharing it with anyone else who hits this below:

A: For me, this was due to permissions on the amplify directory. To fix it:
sudo npm uninstall -g @aws-amplify/cli
sudo rm -rf ~/.amplify/
npm i -g @aws-amplify/cli
I believe this removes the configs, so you may need to set up amplify again.


text:
Q: SKScene and URLQueryItems in Swift3? Ok, I am new to URL querying and this whole aspect of Swift and need help. As is, I have an iMessage app that contains and SKScene. For the users to take turns playing the game, I need to send the game back and forth in messages within 1 session as I learned here : https://medium.com/lost-bananas/building-an-interactive-imessage-application-for-ios-10-in-swift-7da4a18bdeed.
So far I have my scene all working however Ive poured over Apple's ice cream demo where they send the continuously-built ice cream back and forth, and I cant understand how to "query" everything in my SKScene so I can send the scene.
I'm unclear as to how URLQueryItems work as the documentation does not relate to sprite kit scenes.
Apple queries their "ice cream" in its current state like this:
    init?(queryItems: [URLQueryItem]) {
            var base: Base?
            var scoops: Scoops?
            var topping: Topping?

            for queryItem in queryItems {
                guard let value = queryItem.value else { continue }

                if let decodedPart = Base(rawValue: value), queryItem.name == Base.queryItemKey {
                    base = decodedPart
                }
                if let decodedPart = Scoops(rawValue: value), queryItem.name == Scoops.queryItemKey {
                    scoops = decodedPart
                }
                if let decodedPart = Topping(rawValue: value), queryItem.name == Topping.queryItemKey {
                    topping = decodedPart
                }
            }

            guard let decodedBase = base else { return nil }

            self.base = decodedBase
            self.scoops = scoops
            self.topping = topping
        }
    }

fileprivate func composeMessage(with iceCream: IceCream, caption: String, session: MSSession? = nil) -> MSMessage {
        var components = URLComponents()
        components.queryItems = iceCream.queryItems

        let layout = MSMessageTemplateLayout()
        layout.image = iceCream.renderSticker(opaque: true)
        layout.caption = caption

        let message = MSMessage(session: session ?? MSSession())
        message.url = components.url!
        message.layout = layout

        return message
    }
}

But I cant find out how to "query" an SKScene. How can I "send" an SKScene back and forth? Is this possible?

A: You do not need to send an SKScene back and forth :) What you need to do is send the information relating to your game set up - such as number of turns, or whose turn it is, or whatever, as information that can be accessed by your app at the other end to build the scene.
Without knowing more about how your scene is set up and how it interacts with the information received for the other player's session, I can't tell you a lot in terms of specifics. But, what you need to do, if you are using URLQueryItems to pass the information, simply retrieve the list of query items in your scene and set up the scene based on the received values.
If you have specific questions about how this could be done, if you either share the full project, or post the relevant bits of code as to where you send out a message from one player and how the other player receives the information and sets up the scene, I (or somebody else) should be able to help.
Also, if you look at composeMessage in the code you posted above, you will see how in that particular code example the scene/game information was being sent to the other user. At the other end of the process, the received message's URL parameter would be decomposed to get the values for the various query items and then the scene would be set up based on those values. Look at how that is done in order to figure out how your scene should be set up.


text:
Q: HP Touch Sreen does not have WIFI connection anymore I had a desktop (HP Touchsreen320 with Windows 7)  working for years. I turned it off, moved the computer to another room, and I guess the WIFI didn't like the move.
I have spent so much time on this problem...
It has Cable Ethernet connection. It had wifi, not anymore.
Things I have tried:
  1. Under Device Manager, Network adapters, we have only one option -
Realtec PCIe GBE Family Controller. Nothing else as we should expect

  2. Under Basic Network information and set up connections:

   2a) The troubleshooter only tries to fix the cable, never the wifi.

  3. Set up a new connection => Connect to network => do you want to use a connection that you already have? =>
    there are 2 options, a) no, b) yes => there is only Broadband Connections WAN Miniport (PPOE).

   3b. If I click on it and choose the broadband, I have "Type the info form you ISP - At this level, it does not accept my credentials on the Moden - native credentials working in other devices. It throws an error 651.

  4. I called Uverse, and their opinion is that probably nothing related to the Modem. They suggested buying a new adaptor.

  5. If I troubleshoot the adaptor or Internet connection, I only get the cable is the problem
  6. Restore: the last one is the day I moved to another room: 2/13. 5 days ago. More dates and it shows that there was on windows update on the 13, but I am sure this happened after the problem
    6a) scan for affected problems: a few items, and HP support 8.5.37.19 & HP support solutions framework 12.8.47.1 (I am pretty sure this took place after the problem)

I am running out of skills to keep troubleshooting.
    Any help will be greatly appreciated.
PS. I tried to install window 10, it goes through 100% and then there another round and then checking for updates forever. Tried twice. This was a computer with little use before. Wifi was good, however.
PS2 There is one critical update and then goes preparing to install and never ends.

A: You can try going into the bios and making sure your wireless card isn't disabled.
Some laptops have a key combo or a switch to turn the wireless card on and off. It's usually  fn key & whichever keyboard key has the wireless symbol.
You can try googling your models service manual and reseat the wireless card. If windows fails to recognize the card after trying these steps, it could be that you have a defective wireless nic in your computer. It's rare but does happen.
Hope this helps.


text:
Q: Does JSTL Make JSP pages running slow? Some time, more JSP servlet developers may say that JSTL must be used in JSP instead of scriptlets.My question is not to ask whether it should be or not.But, if JSTL is used in JSP pages,does it cause to make jsp page running slow or effects to the performance,effiency as it loads some other classes together with jsp servlets?( Also does the number of times we use JSTL inside a jsp page effect,too?)
 OR
even though a little performance issue is available, can it be neglected because of JSTL's benefits/advantages over plain scriptlets?

A: The response time of a web app mainly depends on the network latency and on the IO (database requests, for example) in server-side code (and I'm ignoring the cost of rendering by the browser here, which is also non negligible, especially if images, scripts, etc. must be loaded).
The JSTL vs. scriptlet time difference is negligible, and you should favor clean code, best practices, maintainability and separation of concerns rather than trying to gain a few nanoseconds by using scriptlets. If JSTL caused performance problems, they would have been noticed, and would have been fixed already (or nobody would use it and recommend it).


text:
Q: How to make field dependencies? How can we make the picklist with the values in it are checkboxes and the picklist with another field. How to make field Dependencies.
can we make the field dependencies between the field with picklist values and another field with picklist values of checkboxes. is it possible?


text:
Q: Add PXButton in top Navbar How do I put a PXActionButton that I have created using the below code in top nav bar of Acumatica.
public override void Initialize()
        {
            if (!String.IsNullOrEmpty(Base.PrimaryView))
            {

                Type primaryViewItemType = Base.Views[Base.PrimaryView].Cache.GetItemType();
                PXAction action = PXNamedAction.AddAction(Base, primaryViewItemType, "SubmitTicket", "Submit Ticket", TestClick);
            }
        }

        public IEnumerable TestClick(PXAdapter adapter)
        {
            throw new PXException("Button clicked from graph" + Base.GetType().Name);
        }

I tried to edit in Menu.aspx inside Frames page. But it doesn't seem to be the right one.
Is there some way, that I can choose the top nav as container while adding the button via my code in PXGraphExtension?

A: The screen you are showing "PM3010PL" is a Generic Inquiry screen:

Generic Inquiries can't be customized using Acumatica Project Editor like the other regular screens such as project "PM301000". This applies to all screen ending with suffix "PL".
Editing Menu.ASPX is out of customization scope and strongly discouraged. To achieve what you want, I would create a new Custom Inquiry screen using template 'Grid (Grid View)' that is functionally equivalent to 'PM3010PL'. Since that screen would be a Custom Inquiry instead of Generic Inquiry you can extend the graph and screen to customize it like all other screens.
The trick to have the button appear at the top is to decorate the action event handler with 'PXProcessButton' attribute instead of 'PXButton':
  public class ProjectEntry_Extension : PXGraphExtension<ProjectEntry>
  {
    public PXAction<PMProject> testBill;

    [PXUIField(DisplayName = "Test Bill", MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Select)]
    [PXProcessButton(Tooltip = "Test Bill")]
    public virtual IEnumerable TestBill(PXAdapter adapter)
    {
      return adapter.Get();
    }
  }

Then you declare the action in the Customized screen (Button Actions->Edit ASPX), this is the part you can do with regular screens but can't do with Generic Inquiries:

The Action will then be displayed on top:

EDIT:
For the top most navigation bar (in blue in your screenshot), this is completely out of customization scope. You could work out something in ASP I guess but this can't be packaged in customization and will be rejected for customization certification process.


text:
Q: Casting from IEnumerable to IEnumerator I'm playing with IEnumerable/<T> and IEnumerator/<T>. In one of my trials, I tried to assign a returned value of type IEnumerable<T> to a value of IEnumerator<T> by using casting, and then trying to execute MoveNext() and Current. Though the casting issued no errors, I got no output:
class Animal
{
    public string AnimalType { get; set; }
    public Animal(string animal_type)
    {
        AnimalType = animal_type;
    }
}

class FarmCollection
{
    readonly Animal[] _farm =
          { new Animal("duck"), new Animal("cow"), new Animal("sheep") };

    public IEnumerable<Animal> GetEnumerable()
    {
        foreach (Animal a in _farm)
            yield return a;
    }
}

class Test
{
    public static void Main()
    {
        FarmCollection farm = new FarCollection();
        IEnumerator<Animal> enumerator = (IEnumerator<Animal>)farm.GetEnumerable();
        while (enumerator.MoveNext())
        {
            Animal a = (Animal)enumerator.Current;
            Console.WriteLine(a.AnimalType);
        }
    }
}

First question: Why I got no output, and Main simply returns?
Second question: Why did the casting from IEnumerable<Animal> to IEnumerator<Animal> didn't issue compiling error?

A: Here is how your FarmCollection.GetEnumerable method looks like when it is decompiled:
public IEnumerable<Animal> GetEnumerable()
{
    FarmCollection.<GetEnumerable>d__0 <GetEnumerable>d__ =
        new FarmCollection.<GetEnumerable>d__0(-2);
    <GetEnumerable>d__.<>4__this = this;
    return <GetEnumerable>d__;
}

The type FarmCollection.<GetEnumerable>d__0 is also generated by the compiler. See this article for more details. Here is how this class looks like:
[CompilerGenerated]
private sealed class <GetEnumerable>d__0 : IEnumerable<Animal>, IEnumerable, IEnumerator<Animal>, IEnumerator, IDisposable
{
    private Animal <>2__current;

    private int <>1__state;

    private int <>l__initialThreadId;

    public FarmCollection <>4__this;

    public Animal 5__1;

    public Animal[] <>7__wrap3;

    public int <>7__wrap4;

    Animal IEnumerator<Animal>.Current
    {
        [DebuggerHidden]
        get
        {
            return this.<>2__current;
        }
    }

    object IEnumerator.Current
    {
        [DebuggerHidden]
        get
        {
            return this.<>2__current;
        }
    }

    [DebuggerHidden]
    IEnumerator<Animal> IEnumerable<Animal>.GetEnumerator()
    {
        FarmCollection.<GetEnumerable>d__0 <GetEnumerable>d__;
        if (Environment.CurrentManagedThreadId == this.<>l__initialThreadId && this.<>1__state == -2)
        {
            this.<>1__state = 0;
            <GetEnumerable>d__ = this;
        }
        else
        {
            <GetEnumerable>d__ = new FarmCollection.<GetEnumerable>d__0(0);
            <GetEnumerable>d__.<>4__this = this.<>4__this;
        }
        return <GetEnumerable>d__;
    }

    [DebuggerHidden]
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.System.Collections.Generic.IEnumerable<ConsoleApplication479.Animal>.GetEnumerator();
    }

    bool IEnumerator.MoveNext()
    {
        bool result;
        try
        {
            switch (this.<>1__state)
            {
            case 0:
                this.<>1__state = -1;
                this.<>1__state = 1;
                this.<>7__wrap3 = this.<>4__this._farm;
                this.<>7__wrap4 = 0;
                goto IL_8D;
            case 2:
                this.<>1__state = 1;
                this.<>7__wrap4++;
                goto IL_8D;
            }
            goto IL_A9;
            IL_8D:
            if (this.<>7__wrap4 < this.<>7__wrap3.Length)
            {
                this.5__1 = this.<>7__wrap3[this.<>7__wrap4];
                this.<>2__current = this.5__1;
                this.<>1__state = 2;
                result = true;
                return result;
            }
            this.<>m__Finally2();
            IL_A9:
            result = false;
        }
        catch
        {
            this.System.IDisposable.Dispose();
            throw;
        }
        return result;
    }

    [DebuggerHidden]
    void IEnumerator.Reset()
    {
        throw new NotSupportedException();
    }

    void IDisposable.Dispose()
    {
        switch (this.<>1__state)
        {
        case 1:
            break;
        case 2:
            break;
        default:
            return;
        }
        this.<>m__Finally2();
    }

    [DebuggerHidden]
    public <GetEnumerable>d__0(int <>1__state)
    {
        this.<>1__state = <>1__state;
        this.<>l__initialThreadId = Environment.CurrentManagedThreadId;
    }

    private void <>m__Finally2()
    {
        this.<>1__state = -1;
    }
}

So in your code, the enumerator variable refers to an object of this type. Since this type implements IEnumerator<Animal>, this explains why the cast did not fail.
Now, to your second question. Notice that the GetEnumerable method generated by the compiler constructs the FarmCollection.<GetEnumerable>d__0 instance and gives the value -2 to the constructor. This is stored in the <>1__state variable. Now, take a look at the MoveNext() method. It has a switch statement over the <>1__state variable. If the value of such variable is not 0 or 2, then the method is guaranteed to return false which means that no values would be returned from the enumeration.
Notice how the GetEnumerator() method in this class changes the state to 0 and returns the same instance (in some case, it returns a new instance of the class with state 0) which would make the MoveNext method work.
So basically the MoveNext method will not work without executing GetEnumerator().

A: If you look at the de-sugared code, you can see that using yield return will create an inner class that implements both IEnumerable<T> and IEnumerator<T>. That's why the cast is valid.
The important line is in the method GetEnumerable():
It returns new FarmCollection.<GetEnumerable>d__1(-2);
So, the initial state is -2, the "No-one-has-requested-an-Enumerator-yet state". If you call GetEnumerator() it will set its state to 0, the "start of enumeration state".
But since you are not calling GetEnumerator(), its state will remain -2 and therefore, when MoveNext() checks the state, it will see -2 and return false.


text:
Q: How to customize and color a Matlab 2D-line? I used this code to draw every 2D-line in the following picture :
Code:
plot([p1(2),p2(2)],[p1(1),p2(1)],':bs');

Result:

As you can see, every line is composed of:

*

*1 right point (a blue square).

*1 left point (a blue square).

*1 line in between (a dashed blue line).

I want to have a different color for each component of the line.And if possible, how to modify the type too of every component .
For example I want the result to be like this for every line:

*

*1 right point (a blue filled square) .

*1 left point (a red filled circle).

*1 line in between (a dashed green line).

How can I plot those colors?
Thank you in advance.

A: You have to decompose your plot procedure in three operations:
hold on

% First point (blue filled squares)
scatter(p1(2), p1(1), [], 'bs', 'filled')

% Second point point (red filled squares)
scatter(p2(2), p2(1), [], 'rs', 'filled')

% Dashed green line in between
plot([p1(2),p2(2)],[p1(1),p2(1)],'g--');

Best,


text:
Q: `Vector.erase()` does not work for vector of classes I've made a class of gym pass that has expiration date (int expiration), price for the pass (float price) and name of its' holder (string data). It also has services (char services), where 0 is basic, 1 is with free showers and 2 is VIP room.
Here's the definition of class:
    class GymPass
    {
        int expiration; //the amount of days
        char services; //0 - basic, 1 - shower, 2 - VIP room
        float price = ((int)services - 47) * expiration;
        string data; //client's identifiable data
    public:

        GymPass()
        {
            cout << "this: " << this;
            expiration = 0;
            services = '0';
            price = 0;
            data = "Lorem ipsum";
        }
        Pass(int expiration, char services, string data)
        {
            this->expiration = expiration;
            this->services = services;
            this->data = data;
        }

        void Print()
        {
            cout << "Gym Pass: ";
            switch (services)
            {
            case '0':
            {
                cout << "Basic gym access, ";
            }
            case '1':
            {
                cout << "gym + shower room, ";
            }
            case '2':
            {
                cout << "Luxurious gym pass with VIP room, ";
            }
            default:
            {
                cout << "Error."; //this should never happen
            }
            }
            cout << "valid for: " << expiration << " days, price: " << price << " zl." << endl;
        }
        void NewPass()
        {
            cout << "Choose service type: \n0 - basic\n1 - showers included\n2 - vip room included";
            {
                char temp{};
                do
                {
                    cin >> temp;
                    if (!((int)temp > 47 & (int)temp < 51)) cout << endl << "Incorrect service type.";
                } while (!((int)temp > 47 & (int)temp < 51));
                this->services = temp;
            }
            cout << endl << "Input the expiration date of the Pass:";
            cin >> this->expiration;
            cout << endl << "Input your name: ";
            cin >> this->data;
        }
        friend bool operator==(const GymPass& lhs, const GymPass& rhs)
        {
            if (lhs.price != rhs.price) return false;
            if (!(lhs.data._Equal(rhs.data))) return false;
            if (lhs.services != rhs.services) return false;
            if (lhs.expiration != rhs.expiration) return false;
            return true;
        }
    };

I also made a class that's basically a vector of my GymPass classes. I'm trying to make a void function to delete one gym pass, but the erase throws error:
no instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=GymPass, _Alloc=std::allocator<GymPass>]" matches the argument list
Like a good programmer, I've done hours of googling, but to no luck. Here's definition of gym class
     class Gym
    {
        vector <GymPass> Clients;
    public:
        void add(GymPass pass)
        {
            Clients.push_back(pass);
        }
        void remove(GymPass pass)
        {
            for (int i = 0; i < Clients.size(); i++)
            {
                if (Clients[i] == pass) Clients.erase(i);
            }
        }
    };

void remove is the delete function, where I get the error. How do I fix the error?

A: std::vector::erase takes an iterator not an index as the argument.
Stali_Klienci.erase(Stali_Klienci.begin() + i);

is a reasonable hack. Stali_Klienci.begin() is the iterator to the first element, the + i increments the iterator to the ith element.
If you want to remove every element from a std::vector then clear does that in one call.

A: You must read erase()  doc first: erase() expects an iterator
Then something like this must do the job:
for (auto it = Stali_Klienci.begin(); it != Stali_Klienci.end(); )
{
   if (*it == karnet) {
        it = c.erase(it);
   } else {
        ++it;
   }
}


text:
Q: Sleep via shortcut causes schedule tasks to not wake computer Thanks to this site and others I have learned to invent a shortcut to put my Windows 10 pc to sleep.  I've tried both "rundll32.exe powrprof.dll,SetSuspendState Sleep" and the same thing but with "0,1,0" instead of "Sleep".  Both work fine to put my machine to sleep.
My problem is that scheduled tasks don't wake the computer when it was put to sleep with the shortcut, but do wake it if the computer was put to sleep with Start>Shut down or sign out>Sleep or Start>Power>Sleep.
Of course there is an obvious work-around: don't use the shortcut.  But I would like to understand what's going on.

A: I was in the same situation and found out my problem was with the way my PC entered sleep mode. I managed to solve this by downloading PsShutdown from Microsoft, following the instructions and using the command to put my machine to sleep:
psshutdown -d -t 0

After doing this, my computer could wake up on schedule. No installation needed, just put the file anywhere and use it's path in the command line.

A: The commonly used batch script command Rundll32.exe Powrprof.dll,SetSuspendState Sleep sleeps the computer in such a way that scheduled tasks are not able to wake the computer from sleep, this is due to what appears to be a bug in Rundll32.exe.
Credit goes to Techie007L's post on the microsoft forums for discovering this and proposing a solution. Instead of calling Rundll32.exe in your batch script you download an alternative tool and call that instead.

Unfortunately, after all the features it has, the Microsoft shutdown command
  is missing the standby feature!  So, it you want to put your computer to sleep
  via command line, you'll need to install a more capable tool before you can
  use the last command above:

*

*Download Sysinternals PsTools.

*The download should be a ZIP file.  Open it and copy PsShutdown.exe to your > desktop.

*On your desktop, right-click PsShutdown.exe and click Copy.  Right-click it > again and click Properties.

*Tick Unblock and click [OK].

*Open File Explorer, navigate to "C:\Windows", scroll down, right-click the > system32 folder and click Paste.

*To enter standby, you can now use this command: psshutdown -d -t 0


text:
Q: Arabic Font Not Appearing in Birt 3.7.1 PDF Report
*

*Environment: Birt 3.7.1 / Maximo 7.5.0.4 / Sun Solaris 10

*Problem: Arabic Font Not Appearing in Birt 3.7.1 PDF Report generated from Maximo 7.5.0.4 Application running on Sun Solaris 10.

*Details:

*

*Birt Viewer is displaying the report correctly with Arabic font as HTML and MS Word, but PDF is eliminating the Arabic characters completely.

*I changed the encoding in both files fontsConfig.xml and fontsConfig.xml from cp1252 to cp1256, in the generated PDF file from Maximo the Arabic letter were replaced by '?'

*I changed the encoding from to utf-8 as per advise in one of the web notes, but again Arabic disappeared from the PDF.

*The PDF report shows the Arabic correctly from windows environment.

Kindly advise.

A: Birt doesn't understand arabic well, in my case i use a localization which holds Arabic language in it as Unicode


text:
Q: Kotlin null-safety for class properties How can I avoid using !! for optional properties of class
class PostDetailsActivity {

    private var post: Post? = null

    fun test() {
        if (post != null) {
            postDetailsTitle.text = post.title    // Error I have to still force using post!!.title
            postDetailsTitle.author = post.author

            Glide.with(this).load(post.featuredImage).into(postDetailsImage)

        } else {
            postDetailsTitle.text = "No title"
            postDetailsTitle.author = "Unknown author"

            Toast.makeText(this, resources.getText(R.string.post_error), Toast.LENGTH_LONG).show()
        }
    }
}

Should I create a local variable? I think using !! is not a good practice

A: You can use apply:
fun test() {
    post.apply {
        if (this != null) {
            postDetailsTitle.text = title
        } else {
            postDetailsTitle.text = "No title"
        }
    }
}

or with:
fun test() {
    with(post) {
        if (this != null) {
            postDetailsTitle.text = title
        } else {
            postDetailsTitle.text = "No title"
        }
    }
}

A: This:
if (post != null) {
    postDetailsTitle.text = post.title    // Error I have to still force using post!!.title
} else {
    postDetailsTitle.text = "No title"
}

Could be replaced with:
postDetailsTitle.text = post?.title ?: "No title"

If the expression to the left of ?: is not null, the elvis operator returns it, otherwise it returns the expression to the right.


text:
Q: Safari jittering/jumping (bug?) on first "focus" event of page load I'm currently fighting a very frustrating bug on Safari, and I'm not sure where else to turn.
It seems most elements (but not all, and I can't discern the differentiating factor) that will trigger a focus event will cause all elements on the page that are transitioned or animated to jump ~2px to the top and left. And this only occurs on the first focus event after the page loads.
It's a little annoying to see the bug, as it's in the logged-in portion of droplr.com, and I have been completely unable to distill down a simpler case on JSFiddle.
If you have/create an account and log-in, click on this edit icon for a drop:

You'll see that on the first focus of the page, things jitter. Here's the timeline when there's a single drop on the page and I trigger focus on an offending element:

With more drops, it's just more of the same, but it seems to max out around 40 paints. And the profiler doesn't suggest anything nefarious. Just a trip through jQuery internals.
If instead of laying elements out via a translate3d or matix3d, I simply use top and left, this bug goes away. After hours and hours of debugging this, I'm at a complete loss.
Hoping someone has seen something similar, could take a look, or could give me advice on debugging next steps.
Thanks so much!
Update: Dave Desandro suggested it was the 3d acceleration kicking in, so I tried it out with a translate instead, and sure enough, that did not cause the jitter. I have no idea why the hardware acceleration would be firing up with a focus event though, and only once.
I've tried setting a transformZ of 0 on page load to go ahead and ramp-up the hardware, but no luck there, either. Any more ideas are welcomed.

A: I've had this issue a while back and honestly I don't remember what exactly was the cause but here are some of the steps I followed:
Check that you don't have hide() and show() for the same element in the next line or vice versa.
Example:
el.show()
el.hide()
Change Custom fonts to "Arial"
For the elements you don't want focus events add this code at the bottom of your scripts:
noFocusElem.off('focus');
This will make sure to remove any focus handlers you might have added by mistake
Finally place your css before any scripts. It's a know fact that adding css rules after an inline style has been applied may cause jitter especially if you're using line-hieght property
Hope this helps :)

A: I've had this happen when using custom font kits. Could this be the issue? Some events cause custom fonts to re-draw, which can cause a ever so slight "jitter" in page display.
Sometimes, manually setting heights and widths on all the parent HTML elements can reduce the flicker.

A: I know this question was posted a while ago and this is a bit of a long shot but here goes:
Maybe as a starting point go back to chrome and look at the composite layering:
Hit this into the address bar:
about:flags
You will be able to enable composite borders from within there. The red borders generally indicate a rendering issue:
http://www.chromium.org/developers/design-documents/gpu-accelerated-compositing-in-chrome
What I have found from time to time is that although there are rendering issues in Chrome the browser copes pretty well with hiding them from me. In other webkit based browsers however the result can be more noticable (i.e. android).
I've also seen flickering occur when z-indexes are being used in conjunction with content that is being transformed.
Either way it would be great to know how you resolved this issue (if you did). Post an answer to your own question perhaps?

A: A way to avoid spending time fixing load time twitches; you could set the page to hidden then make elements visible with the load.  If your page is slow to load, you may want to have a spinner default to visible, then  have load hide it.  Then you could come back to the issue when you have nothing better to do.

A: Just my 2c worth.
The first thing I would try:
First in chrome, whack in 'about:flags' (yes I know you're not using Chrome). Find the 'Composited render layer borders' and turn it on. Once this feature is switched on you'll get a rough idea of what is being rendered/hardware accelerated.
See: http://www.chromium.org/developers/design-documents/gpu-accelerated-compositing-in-chrome
and look for any rendering problems. These are normally caused by z-indexes. Play around with any z-indexes and hide/show certain elements until the rendering issues are resolved. Then work from there. translate-z hacks and opacity can also cause problems.
From experience I've found rendering problems in other webkit browsers can be diagnosed using chrome. Flickering is a common occurrence on the stock android browser.
Secondly: take a look at the focus event itself and try things like preventing the default behaviour. Seems like a long shot to me but give it a go.

A: I haven't tested this, so I will be very surprised if it works... but here's an idea:
$(document).ready(function() {
  $(document).focus(function(e) {
    e.preventDefault();
  });
  $(document).click(function() {
      $(document).unbind();
  });
});

A: I've been running into the same issue recently and found something that fixed it in my case.
Check for anything that's hidden offscreen like:
text-indent: -9999px;
left: -9999px;

Removing any instance of these from the 3d accelerated elements (including children) stopped the content jump on focus for me.


text:
Q: Can firebase be used as a database in China now I am now developing a social application. But recently I noticed that Firebase is blocked in China. So I want to make sure whether firebase can be used in China?

A: * EDIT 24 January 2020 *
Some of the information here might be out of date.
Firebase has a China service at https://firebase.google.cn/ which is not blocked in the PRC. (Thanks to @c-an for bringing this up.)
That said, *.google.com and *.googleapis.com are still blocked in China. I'll change/update this as I get more information.
Original Answer
For now Firebase is blocked and can't be used in China, along with other Google services, because the PRC has blocked all URIs with *.google.com and *.googleapis.com.
This also means, for example, that the Play app store can't be accessed from China. If you don't know what's going on between Google and the PRC, here's a primer.
Also, according to Chinese law, user data of Chinese citizens must be stored inside of the PRC. You might be able to get away with only addressing this once you have a significant number of users, but the trend has been for the CCP to crack down more and more on foreign information, even busting VPNs and declaring them illegal despite complaints of academics who say that they need, you know, real information.
As we're now in the run-up to the 19th Party Congress this autumn, we can expect the situation to get worse before it gets better.  Maybe 2018 will leave room for relaxation?
For now, very sadly, forget anything Google in China, and be prepared to store user data of PRC citizens on servers located inside the Great Firewall. Also be prepared for seemingly random degradations of your service within China, or to be blocked altogether, along with these other blocked services.
Update 2017-11-23:  The 19th Party Congress has come and gone and, if anything, Google services look less likely than ever to become available in China. The great firewall is likely to continue to be strengthened as the Chinese Communist Party extends its role into corporations, and foreign firms are generally disadvantaged.
Update 2018-08-05: Google plans to open a censored version of its search in China, according to leaked documents.  It seems reasonable to assume that if a censored Google Search becomes available in the PRC, then Firebase and other Google Cloud products may as well. The censored search plan, code-named Dragonfly, has reportedly been in the works since December 2017, possibly a result of meetings that month between Google CEO Sundar Pichai and an unnamed top Chinese official when they met at the World Internet Conference in Wuzhen, China, where PRC General Secretary and President Xi Jinping gave a speech.
Update 2018-12-23: It appears that Google's Project Dragonfly is now on hold if not outright abandoned. This implies that the outlook for Firebase in China has worsened.

A: You can build your own Rest API server outside of China, and make the server talks to Firebase rest api endpoints of Realtime db or Authentication, https://firebase.google.com/docs/reference/rest/database. So you web app talks to your rest api server (accessible from China), and your rest api server talks to Firebase.

A: The answer is NO :
Using a huge part of Firebase services, I contacted the support, this is the answer :

I'm glad you are considering Firebase for your project. However, in
accordance with current U.S. policies, it is not possible to use
Firebase from within certain countries. For more information about
these restrictions, please refer to the U.S. Department of the
Treasury website. The current list is of blocked countries is listed
here. If you have end-users located within China, it's quite difficult
to access Firebase there since the use of Firebase requires Google
Play Services, which most of the devices in China don't have. We
understand that access to our products has been problematic from
within mainland China. We believe it may have been caused by
networking conditions in China, rather than Google's own services.
Since access to services is determined by the respective country's
government and they don't report to Google, the Transparency Report is
the most authoritative it can be.

A: I just tested and I am able to access my realtime database hosted on the Singapore region in China mainland. No need to modify anything. Whatever works overseas, works in China. Tested in Beijing.

A: Facing the same problem, if you are in china, install Astrill VPN and change from openweb to StealthVPN, connect to a server like USA for china one and login to firebase. It will work successfully.


text:
Q: how to force all users on Windows server 2019 to open .csv file using Excel I need to set Excel as the default app for all users on Windows server 2019 to open file extensions with .csv.
please assist.

A: You could use the free
SetUserFTA.
The syntax is :
SetUserFTA.exe extension progid (optional:Groupname)

To find out which is the progid of Excel, you could run in a
Command Prompt (CMD) this command:
assoc | find ".xlsx"

For Office 2019 and 365 this should give : Excel.Sheet.12.
The command to use will be similar to the following, to operate on all users:
SetUserFTA.exe .csv Excel.Sheet.12 "Users"

(Note : I haven't tested this utility on my computer.)


text:
Q: What do you call extended words like 'Nooooo'? Is there a word or phrase for this? When you take a word and extend the sound of a letter - usually a vowel - to intensify it. Sometimes you might say Helloooo and stretch out the 'o' sound. What is this called?

A: It's called (monosyllabic) word elongation or word lengthening.

From The Atlantic Magazine:

Evvvvverywherrrre, from instant messages to texts to tweets and even e‑mails, I see examples of what language watchers call word lengthening. The habit began among teens and 20-somethings, but it is no longer limited to them. Adults are adding o's to their no's, s's to their yes'es, and i's to their hi's, to say nothing of a glut of exclamation points. In response to some recent news, my 60-something mom wrote, "LOVE IT AND YOU TOO!!!!" What is going on?

References:

*

*The Atlantic magazine

*Urban Dictionary

*ACL web

*Wired

A: It can be referred to simply as "adding letters to words" or more conveniently as "word lengthening".
Reference: Huffpost

A: Could this be a special form of onomatopoeia, which is the term for a word that sounds like the sound of the object it describes?
I think that might be stretching the definition (no pun intended), but perhaps there's an argument that "Nooooo" sounds very much like a long denial.


text:
Q: AttributeError: 'History' object has no attribute 'predict' - Fitting a List of train and test data I am trying a NN model using this example. I am fitting a list of values to a NN model. However, I am getting an AttributeError. This has been asked before and has been answered. Unfortunately, it is not working for me. As shown in the example, I created the following,
from keras.models import Sequential
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from keras.layers import Dense

def neuralnetmodel():
    #Crete model
    model = Sequential()
    model.add(Dense(13, input_dim = 13, kernel_initializer = 'normal', activation = 'relu'))

model.add(Dense(1, kernel_initializer = 'normal', activation = 'relu'))
model.add(Dense(1, kernel_initializer = 'normal', activation = 'relu'))
## Output layer
model.add(Dense(1, kernel_initializer = 'normal'))

#Compile model
model.compile(loss = 'mean_squared_error', optimizer = 'adam')
return model

fit training data,
NNmodelList = []

for i,j in zip(X_train_scaled,y_train):
    nn_model = KerasRegressor(build_fn= neuralnetmodel, nb_epoch = 50, batch_size = 10, verbose = 0)
    NNmodelList.append(nn_model.fit(i,j))

predict from test data,
PredList = []
for val in X_test_scaled:
    for mod in NNmodelList:
    pred = mod.predict(val)
PredList.append(pred)

Now, I am getting the error:

AttributeError: 'History' object has no attribute 'predict'

In previous threads , it seems to be the train set was not fit to the model before predict. However, in mine, I fit them in the second code snippet. Any ideas what other possible mistakes I am making?

A: model.fit() does not return the Keras model, but a History object containing loss and metric values of your training. So in this code:
NNmodelList.append(nn_model.fit(i,j))

you're creating a list of History objects, not models. A simple fix would be:
NNmodelList.append(nn_model)
nn_model.fit(i,j)

A: enter code here

def build_regressor() :
  regressor = Sequential()
  regressor.add(Dense(units = 64, kernel_initializer = 'uniform', activation = 'relu', input_dim = 5))
  regressor.add(Dense(units =64 , kernel_initializer = 'uniform', activation = 'relu'))
  regressor.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'relu'))
  regressor.compile(optimizer='adam', loss='mean_squared_error')
  return regressor
regressor=KerasRegressor(build_fn=build_regressor, batch_size=32,epochs=200)
results=regressor.fit(X_train,y_train)
regressor.history
print(results.coef_)

but this shows the following error:

AttributeError: 'KerasRegressor' object has no attribute 'history'


text:
Q: Bulk Remove Database Objects From Database Project I'm currently maintaining a SQL Server database that is over 17 years old, and has a large number of unused and outdated artifacts within it.
Over the last several months we have been profiling the database to determine which of the 1800+ stored procedures are actually being used, and which ones we can safely remove.  And as of right now, we have a list of about 1300 that we are planning on removing.
This database is also checked in under our source control in a SQL Server Database Project.
Now, what I'd like to do is generate a script to remove the 1300 procedures and apply that script to the database project first, before applying the script to our Development environment.  But I can't seem to figure out a way to update the project via a script.
I've tried doing an Import > Script and importing a .sql file with DROP PROCEDURE commands, but it throws the following error whilst not removing the procedure from the project:

In the script that you provided to the import operation, one or more statements were not fully understood. These statements were moved to the ScriptsIgnoredOnImport.sql file. Review the file contents for additional information.

The contents of the file tested was the following:
Drop Procedure spProcedureName;

I could go through the project and remove each procedure one-by-one... but there are over 1300 to remove...
Is there any way to do a bulk update (via a script or otherwise) to a database project to remove multiple database objects?

Additional Information:

*

*Creating a shell database from the project and making updates to that will prove to be just as much effort as manually removing the 1,300 stored procedures one-by-one.  This is due to the fact that many of the stored procedures we're planning on removing contain outdated/invalid references to tables, views, functions, OPENROWSET connections, and other procedures.  Because of that, the deploy script fails, and a shell database cannot be created without modifying the individual invalid objects in the script.

*Getting a backup/restore of the current database is also not a viable solution, as the current database is a little over 3 TB in size.

Because of the above limitations, I am only looking for a solution that can be applied to the database project directly without any dependency on a secondary physical database.

A: *

*Deploy your project to a new DB (DB_Temp)

*Drop old stored procedures via TSQL

*Create a new DB project and import the database schema from DB_Temp.

*Update/check project settings, including Publish settings to drop SPs that are not in the project.

*Deploy the project to DEV and Test environment, and test.

*Drop the old project

*Drop DB_Temp

UPDATE:
Alternative way:

*

*Deploy your project to a new DB (DB_Temp)

*Drop old stored procedures via TSQL

*In VS, run Tools-->SQL Server-->Schema Comparison (Source: DB_Temp, Target: your project)

*Press "Update" to remove the old SPs from the project

*Deploy the project to DEV and Test environment, and test.

*Drop DB_Temp

A: To remove the object programmatically from a project, you may use EnvDTE.ProjectItem class, Remove() method.
https://msdn.microsoft.com/en-us/library/envdte.projectitem.remove.aspx
There are many VS extensions that can run EnvDTE commands, like this: https://vlasovstudio.com/visual-commander/index.html
Or you can use Package Management Console (Tools--> NuGet Package Manager --> Package Management Console)
Step1. Assign the list of SPs to variable:
$IncludeList = "SP1.sql", "SP2.sql"
Step2. Drop SP from the project if it is in the list.
If your project path to SPs is like "Database2\dbo\Stored Procedures\", then it's like:
$DTE.Solution.Projects | ForEach { if ($.Name -eq "Database2") {$.ProjectItems | ForEach { if ($.Name -eq "dbo") {$.ProjectItems | ForEach { if ($.Name -eq "Stored Procedures") {$.ProjectItems | ForEach {if ($IncludeList -contains $.Name) {$.Remove()}}}}}}}}


text:
Q: How to know if RAPI dll is existing I have build C# program that work with RAPI (communication to PPC or WinCE)
My problem is, if the user was not installed the ActiveSync - my program crashed !!
How can I load and work with my program without install ActiveSync ?
(maybe something like #if...#define..... i realy dont know.....)
thank's in advance

A: You have two choices here:
One, delay load the RAPI dll so you're app won't complain if the DLL is not there. In this situation, you'd only use the RAPI calls if ActiveSync was installed (you can determine this by checking the registry).
-or-
Two, dynamically load the RAPI dll and only reference the RAPI functions if ActiveSync is installed.

A: I am not sure if this is what you are thinking, but you put your code behind an interface and into another DLL, then when you program starts, look to see if RAPI can be found (look for the files or install code).
If it is found, load the DLL and get the interface to the code that uses it, if it is not found, the don't load the DLL and disable any UI options that need it.


text:
Q: Pager toolbar in custom module in magento I use this tutorial and display products on the basis of multiple categories but now I am getting in issue is that the pager tool bar not working on that.
My block code is :
<reference name="content">
    <block name="mymodule" type="mymodule/product_listcategories"  template="catalog/product/list.phtml">
        <action method="setCategories">
            <ids>2,3,4</ids>
        </action>
    </block>
</reference>

I also add this code with above
<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
    <block type="page/html_pager" name="product_list_toolbar_pager"/>
    </block>
    <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
</block>

It display toolbar but the toolbar is not working (limit,orderby).
My block code is
class Mymodule_Block_Product_Listcategories extends Mage_Catalog_Block_Product_List
{
    protected function _getProductCollection()
    {

        $this->_productCollection = Mage::getModel('catalog/product')->getCollection();
        $this->_productCollection->addAttributeToSelect('*');

        if($this->getCategories()!="")
            $this->_productCollection->addCategoriesFilter($this->getCategories());

            return $this->_productCollection;
        }
    }
}

Does anyone know where is the problem? I think I'm missing some code for the pager? Thanks in advance

A: After search so much i got a solution.I didn't know whether it right or wrong way but it solve my problem.On my block i create intance of
$cpBlock = $this->getLayout()->getBlockSingleton('Mage_Catalog_Block_Product_List_Toolbar');
and access the pager core function like  $this->_itemPerPage =  $cpBlock->getLimit(); .In the above code itemperpage is the total no of items to be displayed on listing page.This code work if you create custom module and extend you block from list block.Thanks


text:
Q: Dynamic memory allocation of struct in c Code:
struct T_Name
{
   char *First;
   char *Middle;
   char *Last;
};

struct T_FullName
{
   char *Title;
   struct T_Name Name;
   char *Suffix;
};

struct T_Person
{
   struct T_FullName *FullName;
   int Age;
   char Sex;
   struct T_Person *BestFriend;
};

typedef struct T_Person *ptrPerson;

ptrPerson pFriend[10];

struct T_Person Person[10];

How could I write necesarry code to dynamically allocate memory to store a value in pFriend[2]->FullName->Name.First?

A: Assuming you know the length of the first name to store,
// Allocate memory for FullName.
Person[2].FullName = malloc(sizeof(T_FullName);

// Allocate memory for the first name.
Person[2].FullName->Name.First = malloc(FIRSTNAME_LENGTH);

A: Your pFriend is a pointer variable, so you have to allocate memory for pointer variable first. Then after allocation of the memory again your FullName is pointer type , so we need to allocate memory for it, Finally your Name member in FullName is not a pointer type , so you can use First from Name with a . operator to allocate memory for it.
//Allocate space for T_Person
pFriend[2] = malloc(sizeof(T_Person);
//Allocate space for FullName
pFriend[2]->FullName = malloc(sizeof(T_FullName);
//Allocate space for First Name
pFriend[2]->FullName->Name.First = malloc(sizeof(urstringlength));

A: pFriend[2] = malloc( sizeof *pFriend[2] );
pFriend[2]->FullName = malloc( sizeof *pFriend[2]->FullName );
pFriend[2]->FullName->First = malloc( strlen(the_name) + 1 );
strcpy(pFriend[2]->FullName->First, the_name);

Note that you probably don't actually want to do this, it will be difficult to use this jumble of structures. You should at least set pointers which aren't in use to NULL , so that your other code can tell which pointers point to allocated memory and which ones don't.
Also, Person is unused in this example. If you wanted pFriend[i] to point at Person[i] you have to say that explicity; replace my first line with:
pFriend[2] = &Person[2];


text:
Q: Date check is not working to show error if End Date is less than Start Date I am trying to add a check in my form to check if the End Date is less than the Starting Date it should throw an error which is not working. Don't know whats the issue here.
my .html code is as follows:
Event Starting Date

    <input class="validate" #startdate="ngModel" [(ngModel)]="input.event_starting_date" name="startdate" type="date" placeholder="Event Starting Date" class="form-control" required>

Starting Date is required!

 Event Ending Date

     <input class="validate" #enddate="ngModel" [(ngModel)]="input.event_ending_date" name="enddate" type="date" placeholder="Event Ending Date" class="form-control" required>

Ending Date is required!

        <div class="alert alert-danger" *ngIf="enddate<startdate">Ending Date Must be greater than Starting Date!

A: The end- and startdate are put in a model like this:

date = {
    year: '',
    month: '',
    day: ''
  };

Have you tried comparing every different property of both date models? I don't think you can compare both models directly to each other since they both have their own underlying properties.


text:
Q: Term for when someone falsely accuses you of doing to them what they are actually doing to you UPDATE: (2018-02-08) Pot-Calling-The-Kettle-Black (PCKB) reconsideration and another example:
The Wikipedia article on PCKB indicates something interesting. It says that originally, the term was Spanish (c. 17th Century) and most often used to indicate hypocrisy, because in those days, BOTH the pot and the kettle were made of a black cast iron, which I why I did not accept it from those who suggested it as an answer. However, the plot thickens ... I don't know if I never researched Wikipedia, if I missed the part I'm about to quote, or if it was added after I originally posted this, but essentially, Wikipedia goes on to say that PCKB has since the 1800's come to mean what I'm talking about (emphasis mine).

An alternative modern interpretation,[6][7] far removed from the original intention, argues that while the pot is sooty (being placed on a fire), the kettle is shiny (being placed on coals only); hence, when the pot accuses the kettle of being black, it is the pot's own sooty reflection that it sees: the pot accuses the kettle of a fault that only the pot has, rather than one that they share.

Have two possible meanings simultaneously is very tricky to deal with, because if you say PCKB to someone, some will think it is the meaning of hypocrisy, and others will think it is projection. However, both cases fail to convey the deliberate and devious manipulation that I'm talking about.
Another example of this scenario is the all-too-common occurrence of a female, usually a wife or girlfriend, calling the cops on the man in the relationship for abuse, after she was the one and only that was doing any abusing.
Therefore, for the most part I am abandoning my search for a term to describe this, because all the answers I received were great but none of them hit the target. This leads me believe that maybe no such word exists.
Thus, I shall have to coin one myself.

UPDATE: (2017-11-23) [Thanksgiving in the USA] I learned of another example just recently that may help sum this concept up in an easily understandable way: You are minding your own business then somebody punches you and yells "He hit me!"

ORIGINAL:
Is there a term for when someone falsely accuses you of doing to them what they are in actuality doing to you?
When I was a child, my younger brother would punch me and then would tell my mom I punched him (which was in no way true). I know some would call this lying, but I'm looking for a more specific term. I suspect there may be something to do with logical, rhetoric, politics, or debate, but I'm not cognizant of the term if it exists. Perhaps something like the term "ad hominem"?
Any help is appreciated!

A: One relevant term is "hypocrisy", "The practice of engaging in the same behaviour or activity for which one criticises another." (https://en.wiktionary.org/wiki/hypocrisy) It does miss, though, the point where you're innocent; someone can justly indict another for vice and still be a hypocrite.
Another related term is "gaslighting", from a 1938 play, which means "To manipulate someone psychologically such that they question their own sanity." (https://en.wiktionary.org/wiki/gaslight#English) That might be too specific, but trying to re-write fact that thoroughly often involves gaslighting.
The term "ad hominem", though, is a fallacy of logic, whereby you attack "an argument or factual claim by appealing to a characteristic or belief of the person making the argument or claim, rather than by addressing the substance of the argument or producing evidence against the claim." (https://en.wiktionary.org/wiki/ad_hominem)

A: Isn't this a type of 'projection' in the psychological sense?
http://changingminds.org/explanations/behaviors/coping/projection.htm

Projection
When a person has uncomfortable thoughts or feelings, they may project these onto other people, assigning the thoughts or feelings that they need to repress to a convenient alternative target.
[…]

*

*Neurotic projection is perceiving others as operating in ways one unconsciously finds objectionable in yourself.

A: This is a form of projection. Oftentimes people (generally the more unhealthy ones) will project their own shortcomings and missteps on others as a form of defense.
More accurately though the act of doing this is generally considered gaslighting. It is literally the adult equivalent of the "I know you are but what am I?"
It can become quite frustrating and demoralizing to the victim. Oftentimes people who are considered Narcissistic Personality, Sociopaths and Borderline Personality will employ this tactic.

A: Check this idiom: The pot calling the kettle black

From Wikipedia: The phrase "The pot calling the kettle black" is
  an idiom used to claim that a person is guilty of the very thing of
  which they accuse another.

A: I understand exactly what you mean, and your frustration in not having a proper answer.
Someone that KNOWINGLY & deliberetly puts you on the defensive & on your heels by accusing you for something that they are guilty of, thus the guilty person is taking the focus off of themselves. A deliberate manipulation.
 I'm not sure if "gaslighting" is specific enough to describe this ruthless tactic.
"Pot calling the kettle black" is more Hypocrisy (often unknowing that they are being a hypocrite) & more importantly does not covey that the accusation is deliberate & meant to mislead. The same goes for "projection" which is unconcious and not deliberate, concious strategy. I would bet there is a specific word for this in German!

A: I believe the latin term "Tu Quoque" may be apropos....! ;-)
From Merriam–Webster:

tu quoque
a retort charging an adversary with being or doing what the adversary criticizes in others
First Known Use: 1614, in the meaning defined above
History and Etymology: Latin, you too