text:
Q: Unable to see Tab Indicator in TabLayout design support library I am using Material design library and creating layout using CoordinatorLayout ,AppBarLayout ,RecyclerView and TabLayout .
My issue is i am unable to see Tab indicator in Tablayout .Below is my xml file that i am using in AppCompactActivity.
<android.support.design.widget.CoordinatorLayout
        android:id="@+id/coodinate_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/btn_next_screen">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/list_recycle"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="30dp"
            android:background="@color/white"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"

            />

        <android.support.design.widget.AppBarLayout
            android:id="@+id/abar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar_home"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"
                android:minHeight="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways"

                >

            </android.support.v7.widget.Toolbar>

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabBackground="@color/tab_bg"
                app:tabIndicatorColor="@color/tab_indicator"
                app:tabIndicatorHeight="5dp"
                app:tabMode="fixed"

                ></android.support.design.widget.TabLayout>

        </android.support.design.widget.AppBarLayout>

        <android.support.design.widget.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"
            app:layout_anchor="@+id/list_recycle"
            app:layout_anchorGravity="bottom|right"
            android:id="@+id/floatin_ab_home"
            app:fabSize="mini"
            android:src="@drawable/ic_content_add"

            />

    </android.support.design.widget.CoordinatorLayout>

Below is screen which don't showing Tab indicator so can any one known what i am missing .

A: I think it's bug on Design Support library. that
When You apply both property at the same time
app:tabBackground="@color/tab_bg"
app:tabIndicatorColor="@color/tab_indicator"

the background color overlap the tab indicator.  that's why the tab indicator is not visible.
If you remove tabBackground color property then you can see the indicator.
[Update on 25-06-2015]
As I said it's bug on Design Support library. I reported it to android bug source. here is the refrence https://code.google.com/p/android/issues/detail?id=176540.
So status for this is issue is FutureRelease so bug is fixed. And it will come in future library.
[Update 20-07-2015]
The bug is fixed and Released in v 22.2.1. you can also check it on above link.

A: You can use below methods
1 Change in xml
 app:tabIndicatorColor="" set your indicator color
2 creating costume theme
<style name="AppTheme.TabStyle" parent="Widget.Design.TabLayout">
        <item name="tabTextAppearance">@style/AppTheme.TextStyle</item>
        <item name="tabTextColor">@color/primaryDark</item>
        <item name="tabSelectedTextColor">@color/white</item>
        <item name="tabIndicatorColor">@color/primaryDark</item>
        <item name="tabIndicatorHeight">3dp</item>
        <item name="android:background">?attr/colorPrimary</item>
    </style>

    <style name="AppTheme.TextStyle" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
        <item name="textAllCaps">true</item>
    </style>

set theme in your Tablayout

A: I've just fixed this bug set background color programmatically
tabLayout.setBackgroundColor(getResources().getColor(R.color.primary));

or in xml
android:background="@color/primary"

But I don't know if there is any problem when you set background color this way

A: Here you go.. :)
Change your attribute
app:tabBackground="@color/tab_bg"
to
android:background="@color/tab_bg"
your final code..
 <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/tab_bg"
            app:tabIndicatorColor="@color/tab_indicator"
            app:tabIndicatorHeight="5dp"
            app:tabMode="fixed">
 </android.support.design.widget.TabLayout>

A: You are using RecyclerView as the main content, use ViewPager containing RecyclerView and make sure you give viewpage attribute app:layout_behavior="@string/appbar_scrolling_view_behavior"

A: If anyone still facing the problem this is
Working example from my existing application, try using it and modify based on your needs.
 <com.google.android.material.tabs.TabLayout
    android:id="@+id/homeScreenTab"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:background="@color/design_default_color_primary_dark"
    app:tabIndicatorColor="@color/black"
    app:tabGravity="fill"
    app:tabIndicatorHeight="3dp"
    app:tabMaxWidth="0dp"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@android:color/white" />


text:
Q: Why has WIndows 7 suddenly restricted access to jEdit? I went to start up jEdit today and I was shown a message box saying that "Windows cannot access the specified device, path, or file. You may not have the appropriate permissions to access the item."
Trying to run the program as administrator doesn't work. I even changed the permissions to anyone can do anything. Everyone has full control over the exe (at least I believe I did. User shows up twice now, once with full controls, and once with read and write access).
Any idea why this would suddenly happen, and more importantly, how can I fix it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: rhel/centos vs. ubuntu (possibly other debian-based systems) linux in handling duplicate ips in the same subnet This has bothered me for quite a while but I never found out why or how to change the behavior.
ip duplicates could be caused by typos or dhcp errors etc., but they do occur from time to time.
in rpm-based systems such as centos, the old server with the duplicate ip wins, and the new server will get an error in bringing up the nic (ip address already used). this is somewhat harmless because we can just fix the system that is coming up.
ubuntu only the other hand happily grabs the used ip for itself and leave the old server/device without a valid ip. this is the more dangerous behavior because it causes outages.
what i want is to change the ubuntu behavior to that of the centos/rhel so would appreciate any help.

A: This functionality in redhat based systems is provided by arping.
They use the command (line 261 in /etc/sysconfig/network-scripts/ifup-eth)
/sbin/arping -q -c 2 -w 3 -D -I <dev> <ip>

The important bit is -D which is used for duplicate detection mode. Basically throw that in your startup scripts to check if the address is available before adding it.


text:
Q: Which SQL Query is Better? Is this SQL query statement:
SELECT p.id, p.[name], SUM(ps.sales_amount) AS GROSS_SALES
FROM products p
  LEFT OUTER JOIN product_sales ps ON p.id = ps.product_id
GROUP BY p.id, p.[name]

better than:
SELECT SUM([t2].[value]) AS [SalesAmount], [t2].[id] AS [ProductId], [t2].[name] AS [ProductName]
FROM (
    SELECT (
        SELECT SUM([t1].[sales_amount])
        FROM [dbo].[product_sales] AS [t1]
        WHERE [t1].[product_id] = [t0].[id]
        ) AS [value], [t0].[id], [t0].[name]
    FROM [dbo].[products] AS [t0]
    ) AS [t2]
GROUP BY [t2].[id], [t2].[name]

The second one is a result of a LINQ2SQL query. Still finding a way to re-write the LINQ expression...
What would be the most optimized SQL query in the example?
Your thoughts? Thanks!

A: Well, the first query is better because it is more readable.  However, since the second query was generated than that explains it and since you won't (shouldn't) have to deal with the actual SQL generated from the LINQ expression there probably isn't a problem with the second one.
I would assume that the SQL Server engine can flatten that out into a standard join like the first query.  If you want to know fire up SQL Server Management Studio and look at the actual execution plan of both.

A: As a general statement this seems like a fairly abusive subquery, and on that basis I'd predict that the first query will be faster. Why not try them and see?

A: That first one is more efficient.  In general joins are better than subqueries.  MS-sql does not always optimize subqueries to their logical "join" equivalents.  The query is so small though that either should be reasonably good, and it will probably make no difference.  You'll need to look at the query plan to see the difference, or look at both being executed using a trace.
The first is also of course more readable.  This is what you will tend to get with Linq-to-SQL these days.  Of course, the whole point is that you shouldn't have to deal with the sql yourself.
The story is that the queries generated by Linq-to-Sql will get more and more efficient.

A: My hunch is that both should be the same, performance-wise.  The left join is probably going to be a nested loop join, which is exactly what the subquery version will do.
But don't take my word for it - as everyone else is suggesting, check out the execution plan and see for yourself which one is better.  Or turn on client statistics and see which one takes longer.

A: The real answer is that you can't tell without measuring.  Even then you don't really know unless you measure on a realistic dataset.
Check out this blog post (not by me) where the generated sql looked worse but performed much better.  His example specifically deals with subselects vs joins so I think it is very relevant to your situation.


text:
Q: Which one should I use who or whom? Which of the following sentences is correct?

This car should be used sparingly by whom is concerned with efficiency.
This car should be used sparingly by who is concerned with efficiency.

and why?

A:

*

*This car should be used sparingly by xxx  [who is concerned with efficiency].

*This car should be used sparingly by [wh--- is concerned with efficiency].

The Original Poster is attempting a grammatically sophisticated sentence. They are trying to use who a bit like the pronoun what. Consider the following sentences:

*

*You should do the activities [which make you happy].

*You should do [what makes you happy].

The first sentence has a relative clause which makes you happy. This clause is modifying the noun phrase the activities. Inside the relative clause, the word which refers to the activities. We say that the noun phrase the activities is the ANTECEDENT for the relative clause.
In the second sentence you will see that there is no antecedent. The word what means the thing(s) which. Notice that this whole relative construction is the object of the verb do. There is no noun phrase which the word is modifying. We call this kind of clause a fused relative.
Now, the word what can appear freely in fused relatives, but the wh- words who, which, when and where, cannot usually appear in fused relatives if they are the Subject of that clause. Even when they aren't Subjects, they only appear as the heads of fused relatives with a very few verbs such as choose, want and like.

*

**You can have the party [where is convenient]. (not good)

**I'll take [which she wants]. (not good)

**[Who said that] is an idiot. (not good)

**[Where she goes] she has problems. (not good)

The sentences above are not good because we are using these wh- words without an antecedent for the clause. In other words, we are using them in fused relative constructions.
If we want to use these relative words in fused relative constructions, we need to add the suffix -ever. This will give us a new relative word that we can use freely in fused relative constructions:

*

*You can have the party wherever is convenient.

*I'll take whichever she wants.

*Whoever said that is an idiot.

*Wherever she goes she has problems.

In the Original Poster's sentence there is no antecedent for who is concerned with efficiency. There are two ways to resolve this problem. Firstly we could put an antecedent into the sentence as in (1) at the top of this post. Here are a few suggestions:

*

*This car should be used sparingly by those  [who are concerned with efficiency].

*This car should be used sparingly by drivers  [who are concerned with efficiency].

*This car should be used sparingly by anyone  [who is concerned with efficiency].

Alternatively, we could use a pronoun with -ever:

*

*This car should be used sparingly by [whoever is concerned with efficiency].

The problem with this sentence is that we like to use whoever when we are picking out a specific known group or are selecting people from a narrow set. Because we are identifying an almost unlimited group of people from an unbounded set the sentence doesn't work very well. If you were speaking to a small group of drivers, say ten people, the sentence above would be fine. It's not great however, for the Original Poster's requirements. For this reason I would choose the first or third examples above:

*

*This car should be used sparingly by anyone who is concerned with efficiency.

However, this relative clause begins with who is. We can make the sentence snappier if we delete the who is:

*

*This car should be used sparingly by anyone concerned with efficiency.

*This car should be used sparingly by those concerned with efficiency.

Here the relative clauses have turned into participle clauses modifying the words anyone and those.

A: The mnemonic I use for that is that when him will work, whom will too.
So swap in "him":

... him is concerned with efficiency.

Since "him" doesn't work here, neither does "whom".

... he is concerned with efficiency.

We have a winnah!

A: Neither...
I would reword:

This car should be used sparingly by anyone concerned with efficiency.


text:
Q: Postfix / PHP Mail() sends email as same email address, ignores header $from We recently upgraded our webserver and one of the first issues we came across was having problems sending to the same domain because the website was hosted on a different server to the company's exchange server.  Anyway I fixed that it was some simple config changes and disabling the mail service for the domain.
Anyway, that's not working but what I didn't notice at the time when I was testing some PHP mail forms on the website was that they are all getting sent as my email address to the client.
This is the PHP (Which I don't think is a problem)

<?php
    ini_set("sendmail_from", "noreply@******.com");

    $name       = $_POST['name'];
    $email      = $_POST['email'];
    $phone      = $_POST['phone'];
    $comments   = $_POST['comments'];
    $ip=$_SERVER['REMOTE_ADDR'];

    $recipient  = '*****@******.com';
    $subject    = "Comments submitted from the Contact Us form on www.wavesfm.com from $name" ;

    $message   = "This is an email submitted from the Contact Us form on the website www.*****.com containing details from $name \n";
    $message  .= "    \n";
    $message  .= "Name: $name \n";
    $message  .= "Email: $email \n";
    $message  .= "Phone Number: $phone \n";
    $message  .= "Comments: $comments \n\n\n";
    $message  .= "IP Address: $ip ";

    $headers   = "From: noreply@********.com \n";
    $headers  .= "Reply-To: $email";

    mail($recipient,$subject,$message,$headers);
    header( 'Location: http://www.*****.com/thanks.php' ) ;
?>

Can anyone see any issues with that code? I have tried adding -fnoreply@**.com as a send parameter but it wont change my own email address from appearing as the sender.
I don't think this is a PHP issue it seems more like a Postfix issue, but whats really bothering me is how my email address which isn't used anywhere is appearing as the sender.
Has anyone had experience with this before? as before 2 weeks ago I hadn't used Postfix at all so its all rather new to me.
Web Server: Cent OS, Plesk 11.0.9
Mail Server: MS Exchange Mail Server / Using ORF
Postfix Log for one of the email's
Mar 27 13:48:41 dedicated postfix/pickup[12199]: 652EFA106C5: uid=48 from=
Mar 27 13:48:41 dedicated postfix/cleanup[14376]: 652EFA106C5: message-id=<20130327134841.652EFA106C5@dedicated.mydomain.com>
Mar 27 13:48:41 dedicated postfix/qmgr[12198]: 652EFA106C5: from=, size=726, nrcpt=1 (queue active)
Mar 27 13:48:41 dedicated postfix/smtp[14378]: certificate verification failed for mail.mydomain.com[82.888.888.51]:25: untrusted issuer /CN=clientdomain-WAV01-CA
Mar 27 13:48:42 dedicated postfix/smtp[14378]: 652EFA106C5: to=, relay=mail.client_website.com[82.888.888.51]:25, delay=0.89, delays=0.04/0.01/0.36/0.48, dsn=2.6.0, status=sent (250 2.6.0 <20130327134841.652EFA106C5@dedicated.mydomain.com> [InternalId=11846] Queued mail for delivery)
Mar 27 13:48:42 dedicated postfix/qmgr[12198]: 652EFA106C5: removed

A: There might be some string concatenation issues with the following code:

$headers = "From: noreply@********.com \n";

try
$headers = "From: noreply@********.com \r\n";

I recommend using phpmailer class for sending emails which is widely used:
https://github.com/Synchro/PHPMailer

A: The php.ini sendmail_from directive only really applies on windows boxes

sendmail_from string Which "From:" mail address should be used in mail
  sent from PHP under Windows. This directive also sets the
  "Return-Path:" header.

I don't think it's a code issue as such.  Which user are you running the webserver+php environment from on your Linux box?  If you're running it as yourself then it's probably submitting to postfix using your email address.
Don't forget to tail /var/log/maillog if you're using postfix, that can tell you a lot and help you get to the bottom of the issue.
sudo tail -f /var/log/maillog
You could try signing up for a free account with Sendgrid and coupled with PHPMailer, Zend Mailer or Symfony Mailer libraries use that to send the emails and see if you get the same issue.


text:
Q: I only got a lot of cons folder inside \data\data, and I can't found my app name folder. Anyone have the solution for this?
Actually in my application i instantiated an object of local sq-lite, and i can't see the database in the android monitor file explorer it just displaying can allowance displaying package names.


text:
Q: Domains with prime ideal theorems Let $D$ be a domain, and for prime ideals $\frak P$ of $D$ the norm is $N({\frak P}):=|D/{\frak P}|$. The prime ideal counting function of $D$ is given by $\pi_D(x)=\#\{{\frak P}\in{\rm Spec}(D):N({\frak P})\le x\}.$

*

*For $D=\Bbb Z$, the prime ideals are the principal ideals generated by the positive prime elements, or colloquially just the "primes." The norm is trivial; $N(p\Bbb Z)=p$. The prime number theorem states the asymptotic relation $\pi_{\Bbb Z}(x)\sim\frac{x}{\log_{\Large e}x}$.

*More generally if $D={\frak O}_K$ is the ring of integers of a number field $K$, the same asymptotic relation holds for $\pi_{{\frak O}_K}$. This is known as Landau's prime ideal theorem.

*Let $D={\Bbb F}_q[T]$ where $q$ is a prime power. The explicit formula $\frac{1}{n}\sum_{d\mid n}\mu(\frac{n}{d})q^d$ for the number of monic irreducibles of degree $n$ yields the asymptotic $\pi_{{\Bbb F}_q[T]}(x)\sim\frac{x}{\log_qx}$.

Call an asymptotic relation of the form $\pi_D(x)\sim\frac{x}{\log_{\large b}x}$ a "prime ideal theorem." Some questions:
What general kinds of domains have prime ideal theorems? Any examples strikingly different from above? Is there a conceptual (say, geometric or probabilistic) explanation for why (or heuristic prediction for) the growth class looking like $\frac{x}{\log_bx}$ in (any) of these cases? What kinds of parameters $b$ are possible? Any cases different from $b\in\{e,2,3,5,\cdots\}$? What exactly would $b$ be "saying" about $D$ anyway; what does it measure or describe?


text:
Q: How to subdivide Excel Column? I'm a beginner in Excel and need some help with creating a table.
How would I subdivide the header of a column into two columns underneath it that could each contain data? That if, if I have a header that looks like |random title|, how would I divide the larger column into |random title| with
|sec1||sec2| directly underneath?
Thanks in advance
The image of how I want to subdivide my columns:

A: Figured it out: merge columns together with home>merge


text:
Q: How to check and compare similar folder permissions using vbscript So I have two similar directories full of user profiles folders(one old and one new) I am trying to see if their permissions for the new directory is the same as the old directory. I would like to write a script to reduce the repetitive task of going through all the folders and compare the old directory with the new directory, I have to ensure and validate that all permissions are the same with each folder.
I am thinking that using a Select Case with users name that range from A to Z to display if some changes need to be made.
Any insight and thoughts would be appreciated....Thanks

A: To keep two directories in sync, I use Robocopy. It's easy to use, will keep permissions in sync, and has some nice logging functionality.


text:
Q: Adding arguments to ASP.NET MVC 5.0 Controller Method Causes JQuery Datatable Ajax Call to Hang Exactly as read in the title. For some reason, changing my controller method to accept parameters causes my DataTable ajax call to this method to fail.
Function signature
[AcceptVerbs("POST")]
public JsonResult LoadPayoffAgingGrid(/*string SearchText, DateTime StartDate, DateTime EndDate*/)

DataTable call:
function LoadPayoffAgingReportGrid() {

    var wsUrl = '@Url.Action("LoadPayoffAgingGrid", "Report")';
    var dtStart = $('#dtStart').val();
    var dtEnd = $('#dtEnd').val();
    var sSearch = $('.dataTables_filter input').val();

    oTableLoansView = $('#PayoffAginggridtable').dataTable({
        "bServerSide": true,
        "sAjaxSource": wsUrl,
        "iDisplayLength": 50,

        "bProcessing": true,
        "bDestroy": true,
        "sDom": sDomStandard,
        "bJQueryUI": true,
        "error": function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        },
        "sServerMethod": "POST",
        "sPaginationType": "full_numbers",
        "fnServerParams": function (aoData) {
            aoData.push({ "name": "sDateStart", "value": dtStart });
            aoData.push({ "name": "sDateEnd", "value": dtEnd });
            //aoData.push({ "name": "sSearch", "value": sSearch });
        },
        "bAutoWidth": false,
        "aoColumns": [
                { "sName": "BorrName", "bSortable": true, "sClass": "alignleft hidden-xs" },
                { "sName": "LoanNumber", "bSortable": true, "sClass": "alignleft" },
                { "sName": "SubdivName", "bSortable": true, "sClass": "alignleft hidden-xs" },
                { "sName": "LotNum", "bSortable": true, "sClass": "pointer hidden-xs" },
                { "sName": "OpenDtAge", "bSortable": true, "sClass": "alignright" },
                { "sName": "AgeGroup", "bSortable": true, "sClass": "alignright hidden-xs" },
                { "sName": "PaidOffDt", "bSortable": true, "sClass": "alignright" },
                { "sName": "CommitmentAmt", "bSortable": true, "sClass": "alignright" },

        ],
        "aaSorting": [[1, 'asc']]
    });

}

Could anyone explain what causes MVC and Jquery Datatables to interact like this? I'd imagine it's a facet of AJAX, which I don't understand very well.

A: if you add non-nullable parameters you need to include them in your request
DateTime StartDate and DateTime EndDate is required  and your request seems to be sending sDateStart and sDateEnd which would throw an error since the parameter names do not match

A: I discerned that the issue was there is no implicit conversion between DateTime and null. The other functions work perfectly well because they lack parameters of type DateTime. The solution is to make these parameters nullable, as below:
[AcceptVerbs("POST")]
public JsonResult LoadPayoffAgingGrid(string SearchText, DateTime? StartDate, DateTime? EndDate)


text:
Q: Fourier transform of creation operator on the Schwartz-space Let $f\in S(\mathbb{R})$, where $S(\mathbb{R})$ denotes the Schwartz-space,
and $A=\frac{1}{\sqrt{2}}(x+\frac{\text{d}}{\text{d}x})$ be the creation operator and $A^\dagger=\frac{1}{\sqrt{2}}(x-\frac{\text{d}}{\text{d}x})$ the annihilation operator.
Now I have to show the following:
(a) $\mathcal{F}[Af]=iA\mathcal{F}[f]$
(b) $\mathcal{F}[A^\dagger f]=-iA^\dagger\mathcal{F}[f]$
and (c) $\mathcal{F}[Hf]=H\mathcal{F}[f]$ with $H=A^\dagger A$.
Here $\mathcal{F}$ represents the Fourier transform.
I plugged in the defintions and tried integration by parts but I think I am still missing something. So Help is very much appreciated!

A: Recall that for $u\in\mathcal{S},$
$$D_{\xi}^\alpha (\mathcal{F} u)=\mathcal{F}((-x)^\alpha u)$$
and $$\mathcal{F}(D_x^\alpha  u)=\xi^\alpha \mathcal{F} u,$$ where $D^\alpha=\frac{1}{i^{|\alpha|}}\partial^\alpha$ and $\alpha$ is a multi-index. You can directly derive these facts (the former uses differentiation under the integral sign, and the latter uses integration by parts), and they can be applied easily to get your answers.
For example, for part (a), you can check that $$\mathcal{F}(xu)=i\frac{d}{d\xi} \mathcal{F}(u),$$ and $$\mathcal{F}\left(\frac{d}{dx}u\right)=i\xi\mathcal{F}(u).$$ Using linearity allows you to conclude your first identity.
In case you feel uneasy about using the identities that I wrote, I will explicitly demonstrate part (a) for you (this also shows you how the general identities are obtained):
We see that \begin{align*}
\mathcal{F}(xu)(\xi)&=(2\pi)^{-1/2}\int\limits_{-\infty}^\infty e^{-ix\xi} xu(x)\, dx\\
&=(2\pi)^{-1/2}\int\limits_{-\infty}^\infty \frac{d}{d\xi}\left(\frac{1}{-i}e^{-ix\xi}\right) u(x)\, dx\\
&=i\frac{d}{d\xi}\mathcal{F}u(\xi),
\end{align*} and \begin{align*}
\mathcal{F}\left(\frac{d}{dx}u\right)(\xi)&=(2\pi)^{-1/2}\int\limits_{-\infty}^\infty e^{-ix\xi}\frac{d}{dx}u(x)\, dx\\
&=-(2\pi)^{-1/2}\int\limits_{-\infty}^\infty \frac{d}{dx}(e^{-ix\xi})u(x)\, dx\\
&=i\xi\mathcal{F}u(\xi),
\end{align*}
where we have integrated by parts for the second part.


text:
Q: SQL Aggreate Functions I have table which list a number of cases and assigned primary and secondary technicians.  What I am trying to accomplish is to aggregate the number of cases a technician has worked as a primary and secondary tech.  Should look something like this...
Technician     Primary     Secondary
John             4              3
Stacy            3              1
Michael          5              3

The table that I am pulling that data from looks like this:
CaseID, PrimaryTech, SecondaryTech, DOS

In the past I have used something like this, but now my superiors are asking for the number of secondary cases as well...
SELECT PrimaryTech, COUNT(CaseID) as Total
GROUP BY PrimaryTech

I've done a bit of searching, but cant seem to find the answer to my problem.

A: Select Tech,
       sum(case when IsPrimary = 1 then 1 else 0 end) as PrimaryCount,
       sum(case when IsPrimary = 0 then 1 else 0 end) as SecondaryCount
from
(
  SELECT SecondaryTech as Tech, 0 as IsPrimary
  FROM your_table
  union all
  SELECT PrimaryTech as Tech, 1 as IsPrimary
  FROM your_table
) x
GROUP BY Tech

A: You can group two subqueries together with a FULL JOIN as demonstrated in this SQLFiddle.
SELECT Technician = COALESCE(pri.Technician, sec.Technician)
    , PrimaryTech
    , SecondaryTech
FROM
    (SELECT Technician = PrimaryTech
        , PrimaryTech = COUNT(*)
    FROM Cases
    WHERE PrimaryTech IS NOT NULL
    GROUP BY PrimaryTech) pri
FULL JOIN
    (SELECT Technician = SecondaryTech
        , SecondaryTech = COUNT(*)
    FROM Cases
    WHERE SecondaryTech IS NOT NULL
    GROUP BY SecondaryTech) sec
    ON pri.Technician = sec.Technician
ORDER By Technician;

A: SELECT COALESCE(A.NAME, B.NAME) AS NAME, CASE WHEN A.CASES IS NOT NULL THEN A.CASES ELSE 0 END AS PRIMARY_CASES,
CASE WHEN B.CASES IS NOT NULL THEN B.CASES ELSE 0 END AS SECONDARY_CASES
FROM
(
SELECT COUNT(*) AS CASES, PRIMARYTECH AS NAME FROM YOUR_TABLE
GROUP BY PRIMARYTECH
) AS A
FULL OUTER JOIN
(
SELECT COUNT(*) AS CASES, SECONDARYTECH AS NAME FROM YOUR_TABLE
GROUP BY SECONDARYTECH
) AS B
ON A.NAME = B.NAME


text:
Q: Python universal install with conda I recently got a new M1 MacBook and have been trying to get my Python Dev environment setup. I'm new to conda (previously used virtualenv) and I'm wondering if there's a way to use the Python 3.9.4 universal2 install. 3.9.2 is the highest version listed, and I can't see how to distinguish it from the Intel/ARM installations, but running platform.machine() outputs x86_64, so it seems I have the Intel install by default. Any way to manage this?

A: Step 1: Come here
Scroll down to the line Anaconda 2019.03 for macOS Installer.
You need to know your Python version. To do this, write in the terminal

And select Command Line Installer
Step 2: installing via command line
After the installation is complete, go to the terminal.
If you have Python 3.7, then run:
bash ~ / Downloads / Anaconda3–2019.03-MacOSX-x86_64.sh
For Python 2.7:
bash ~ / Downloads / Anaconda2–2019.03-MacOSX-x86_64.sh
Attention: if you downloaded Anaconda not in the Downloads folder, then in the commands you need to change the path to the distribution kit.
Review the license agreement and press Enter. Finally, after a million Enter hits, type yes if you accept the license agreement.
(If you do not accept the agreement in time, then this clue will constantly catch your eye)

if you are satisfied with the installation path, then press Enter. You can change the location or abort the installation by pressing CTRL-C.
Then you will be asked: Do you wish the installer to initialize Anaconda3 by running conda init? Write yes, of course.
When the installation is complete, close a terminal window and open a new one - this will take effect your changes. Want to make sure everything works? Type conda list and see what happens. If everything works, you will see something like this:

If everything works, then congratulations! Now you can use Anaconda, Jupyter Notebooks, Spyder and other useful things.


text:
Q: Why do I need to set font-weight when setting @font-face? I am working on a React project.
source
The folder structure where the font file is located is as follows.
- src
    assets
       Fonts
           - NotoSansKR-Bold.otf
           - NotoSansKR-DemiLight.otf
           - NotoSansKR-Medium.otf
           - NotoSansKR-Regular.otf

@font-face is set as follows in App.css in root.
@font-face {
  font-family: 'Noto Sans KR-Bold';
  src: url('./assets/Fonts/NotoSansKR-Bold.otf');
}

@font-face {
  font-family: 'Noto Sans KR-Medium';
  src: url('./assets/Fonts/NotoSansKR-Medium.otf');
}

@font-face {
  font-family: 'Noto Sans KR-Regular';
  src: url('./assets/Fonts/NotoSansKR-Regular.otf');
}

@font-face {
  font-family: 'Noto Sans KR-DemiLight';
  src: url('./assets/Fonts/NotoSansKR-DemiLight.otf');
}

And in the components in src/pages/, font is used as follows(using styled-components).
const UserName = styled.div`
  margin-left: 6px;
  font-family: 'Noto Sans KR-Regular';
  font-style: normal;
  font-size: 14px;
  line-height: 20px;
  color: #262e33;
`;

Problem
The result is the same no matter which one of Bold, Medium, Regular, and DemiLight is set. In other words, it seems that the font style is not applied.
As a result of the search, it was found that if the font-weight is specified as follows, the matching font is applied when the corresponding font-weight and font-family are specified.
@font-face {
  font-family: 'Noto Sans CJK KR';
  font-style: normal;
  font-weight: 100;
  src: url("styles/fonts/NotoSansKR-Light.woff2") format('woff2'),
  url("styles/fonts/NotoSansKR-Light.woff") format('woff'),
  url("styles/fonts/NotoSansKR-Light.otf") format('truetype')
}

@font-face {
  font-family: 'Noto Sans CJK KR';
  font-style: normal;
  font-weight: normal;
  src: url("styles/fonts/NotoSansKR-Regular.woff2") format('woff2'),
  url("styles/fonts/NotoSansKR-Regular.woff") format('woff'),
  url("styles/fonts/NotoSansKR-Regular.otf") format('truetype')
}

@font-face {
  font-family: 'Noto Sans CJK KR';
  font-style: normal;
  font-weight: 500;
  src: url("styles/fonts/NotoSansKR-Medium.woff2") format('woff2'),
  url("styles/fonts/NotoSansKR-Medium.woff") format('woff'),
  url("styles/fonts/NotoSansKR-Medium.otf") format('truetype')
}

@font-face {
  font-family: 'Noto Sans CJK KR';
  font-style: normal;
  font-weight: bold;
  src: url("styles/fonts/NotoSansKR-Bold.woff2") format('woff2'),
  url("styles/fonts/NotoSansKR-Bold.woff") format('woff'),
  url("styles/fonts/NotoSansKR-Bold.otf") format('truetype')
}

Question
However, in my opinion, Bold, Medium, etc. are the difference in weight after all, and I do not know why the weight should be specified even though the otf file is divided by font thickness. Why are my settings wrong?

A: Your settings are not wrong. It's about @font-face rule
A given set of @font-face rules define a set of fonts available for use within the documents that contain these rules. When font matching is done, fonts defined using these rules are considered before other available fonts on a system.
Docs source
Easier to understand @font-face blog


text:
Q: Can't use openssl extension for SSL/TLS protection I am running Windows 10 working with Laravel 5.4, homestead 2.0, using VM and Vagrant. Everything works... Except when I am running "laravel new blog" I get:
  [Composer\Exception\NoSslException]
  The openssl extension is required for SSL/TLS protection but is not
  available. If you can not enable the openssl extension,
  you can disable this error, at your own risk, by setting the 'disable-tls'
  option to true.

I know that there are some other questions regarding this but there seem yet not to have emerged a good answer for this. Also, most other questions regarding this is about WAMP... Therefor I think it is relevant to ask agiain when using VM.
I have removed the ; (semicolon) in front of extension=php_openssl.dll in my php.ini-development and php.ini-production. The error still remains.
When I check openssl version in comandline I have:
OpenSSL 1.0.2k  26 Jan 2017

A: ...This was due to something wrong with my PHP-install. What I finally did (which is a kinda bad solution) was to install xampp just to get a correct php version. Then I went to my PATH (winbtn + break(paus) ---> Advanced system settings ---> Environment Variables) and re-routed the php to the xampp php version and VOILA! It works. So either dig in to make a proper PHP install or YOLO like me and add xampp just to get a correct php and then it should work. GL HF!


text:
Q: How to send selected id in parameter using actionURL? Here is my view.jsp:
<portlet:actionURL name="getTravelId" var="travelIdUrl">
</portlet:actionURL>
for (Travel t : list) {
    <a href="<%=travelIdUrl%>"><%=t.getId() %>
}

Then in the class:
 @ProcessAction(name="getTravelId")
        public void getSelectedTravelId(ActionRequest request, ActionResponse response){

        String idTravel = request.getParameter("idTravel");

        System.out.println("TRAVEL ID: " + idTravel);

    }

I tried sending the parameter like:
  <a href="<%=travelIdUrl%>?travelId="<%=t.getId()%>""><%=t.getId() %>

but not working.
Also tried putting the actionURL inside for, still not working
 for (Travel t : list) {
 <portlet:actionURL name="getTravelId" var="travelIdUrl">
        <portlet:param name="idTravel" value="<%t.getId()%>"/>
    </portlet:actionURL>
 <a href="<%=travelIdUrl%>"><%=t.getId() %>
    }

Does anyone have a solution? Thanks..

A: You were definitely on the right path using the <portlet:param> tag to add parameters to a portlet URL. Perhaps you can try using more JSTL and fewer scriptlets. Try something more like the code snippet below.
<c:forEach items='${list}' var="travel">
    <portlet:actionURL name="getTravelId" var="travelIdUrl">
        <portlet:param name="idTravel" value="${travel.id}"/>
    </portlet:actionURL>
    ${travel.id}
</c:forEach>

A: what exactly did not work in your last example? I think you are mixing Java code with HTML and tags. Try this example in your JSP:
<c:forEach var="t" items="${list}">
  <portlet:actionURL name="getTravelId" var="travelIdUrl">
    <portlet:param name="idTravel" value="${t.id}"/>
  </portlet:actionURL>
 ${t.id}
</c:forEach>

It creates an anchor for each item in list with given id parameter. The example uses only HTML and tags and JSP expresion language for accessing variables.


text:
Q: Property 'registerComponent' does not exist on type 'ElementRef' I was trying to work on golden-layout with angular2. I followed this plunker, but I got following errors:

Property 'registerComponent' does not exist on type 'ElementRef'.
Property 'eventHub' does not exist on type 'ElementRef'.
Property'init' does not exist on type 'ElementRef'.
Property 'on' does notexist on type 'ElementRef'.
Property 'updateSize' does not exist on type 'ElementRef'.
Property 'eventHub' does not exist on type
   'ElementRef'

The code of plunked is as:
import {
  Component, ComponentFactoryResolver, HostListener, ComponentFactory, ComponentRef,ViewContainerRef,ReflectiveInjector,
  ElementRef, ViewChild
} from '@angular/core';
import {AppComponent} from './app.component';
import {App2Component} from './app2.component';
declare let GoldenLayout: any;

@Component({
  selector: 'golden-layout',
  template: `
My First Angular 2 App

<button (click)="sendEvent()">Send event through hub</button>`,
  entryComponents: [AppComponent, App2Component]
})
export class GLComponent {
  @ViewChild('layout') private layout: ElementRef;
  private config: any;
  private layout: ElementRef;

  constructor(private el: ElementRef, private viewContainer: ViewContainerRef,
        private componentFactoryResolver: ComponentFactoryResolver){
    this.config = {
            content: [{
                type: 'row',
                content: [{
                    type: 'component',
                    componentName: 'test1',
                    componentState: {
                      message:"Top Left"
                    }
                }, {
                        type: 'column',
                        content: [{
                            type: 'component',
                            componentName: 'test2',
                            componentState: {
                              message:"Top Right"
                            }
                        }, {
                                type: 'component',
                                componentName: 'test1',
                                componentState: {
                                  message:"Bottom Right"
                                }
                            }]
                    }]
            }]
        };
  }

  ngAfterViewInit(){
    this.layout = new GoldenLayout(this.config, this.layout.nativeElement);

    this.layout.registerComponent('test1', (container, componentState) => {
          let factory = this.componentFactoryResolver.resolveComponentFactory(AppComponent);

          let compRef = this.viewContainer.createComponent(factory);
          compRef.instance.setEventHub(this.layout.eventHub);
          compRef.instance.message = componentState.message;
          container.getElement().append(compRef.location.nativeElement);

          container["compRef"] = compRef;

          compRef.changeDetectorRef.detectChanges();
    });

    this.layout.registerComponent('test2', (container, componentState) => {
          let factory = this.componentFactoryResolver.resolveComponentFactory(App2Component);

          let compRef = this.viewContainer.createComponent(factory);
          compRef.instance.setEventHub(this.layout.eventHub);
          compRef.instance.message = componentState.message;
          container.getElement().append(compRef.location.nativeElement);

          container["compRef"] = compRef;

          compRef.changeDetectorRef.detectChanges();
    });

    this.layout.init();

        this.layout.on("itemDestroyed", item => {
            if (item.container != null) {
                let compRef = item.container["compRef"];
                if (compRef != null) {
                    compRef.destroy();
                }
            }
        });
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
      if (this.layout)
        this.layout.updateSize();
  }

  sendEvent(){
    if (this.layout)
      this.layout.eventHub.emit("someEvent");
  }
}

Edit:
I am adding github link to my project, with all config files and components: golden-layout-demo.
Solution:
The code of the plunker was incorrect, used this.layout.nativeElement.registerComponent instead of this.layout.registerComponent and same for Same if for eventHub, init, on, updateSize. This resolved the compile time errors.
Edit2:
Now, I am getting the runtime error, that I can see in my browser:
GET http://localhost:4200/styles.css
GET http://localhost:4200/systemjs.config.js
GET http://localhost:4200/systemjs.config.js
Uncaught Error: Zone already loaded.
GET http://localhost:4200/app 404 (Not Found)
GLComponent_Host.html:1 ERROR TypeError: Cannot read property 'registerComponent' of undefined

The contents of my index file look like:
<!DOCTYPE html>

    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <link type="text/css" rel="stylesheet" href="https://golden-layout.com/files/latest/css/goldenlayout-base.css" />
    <link type="text/css" rel="stylesheet" href="https://golden-layout.com/files/latest/css/goldenlayout-dark-theme.css" />

    <golden-layout>Loading...</golden-layout>

A: The code in the plunk is not incorrect, changing this.layout.registerComponent to this.layout.nativeElement.registerComponent is just hiding the problem and will cause more problems once the application can actually build.
Your application is running using webpack via Angular CLI whereas the application in the plunk is using SystemJS
You have ended up merging the two when trying to implement the plunk in your application and this is causing your issues. You do not need the Load libraries and configure SystemJS sections in the index.html as @yurzui mentioned and you also don't need the systemjs.config.js file


text:
Q: Where to find the permission or policy to allow installation of network adapter service in Win7 I am trying to install a VirtualBox VM on all of my colleagues machines, one of which is giving weird problems - The VirtualBox installer doesn't seem to have installed it's network adapter/services.
It turns out, he doesn't have a certain access permission that the rest of us do, and it is preventing VirtualBox from programmatically allowing adapter installation. It also manifests itself as not allowing us to manually install a network service on his machine. He has, according to our sysadmin, the same user profile as the rest of the team, which gives admin rights.
Following the steps below, I am able to install a service to a network adapter (or at least open the selection window):
Control Panel > By Category > Network and Internet: View network status and tasks > Change adapter settings > Local Area Connection: Right click to properties > Install > Select "Service" > Click "Add" ... ... ...
On my machine, I have a window pop up "Select network service"
On my colleague's machine, He has an access denied error message.
I can supply screenshots if required (or logs if there is a specified location), but I am not currently at his machine.
So, my question: How do I find out where this permission is set, and change it? Are there any areas on the filesystem or in the registry that may affect permissions here?
Many thanks,
Mitch.
edit:
Thanks to an update on the virtual box forums, I have also tried to set the driver signature enforcement. This hasn't had any effect on the virtual box driver installation either, although I'm not too surprised as the manual steps listed above don't actually select anything that may have an (in)valid driver, it is prevented before we get that far...


text:
Q: Access collection from within partial When I render a collection using a partial, I would like to have access to the collection itself from within the partial (I already know how to access the current member).

*

*How do I access the whole collection from within the partial (best without passing the collection as a parameter)?

*I would specifically like to check if the current member being rendered is the last in the collection. How do I do that? (Elegantly, I mean).
PS. I don't have the collection as an instance variable.

A: Unfortunately there is no easy way to reference the original collection from inside the action, nor to check if it's the latest.
From inside the collection you have access to the <partial>_counter variable (in case the partial is called _post, the name of the variable is post_counter) that indicates the number of the item you are rendering in the collection (from 0 to collection.size-1).
But apart from this, no reference to the whole collection.
The only solution, so far, is probably to pass it as locals.


text:
Q: Summing Over Uncountable Index Sets In answering the question Why do we classify infinities in so many symbols and ideas?, William's answer asserted that summing over an uncountable index set necessarily results in an infinite sum. I am curious about whether this is true and, if so, if it is possible to characterise the transfinite nature of the resultant sums over uncountable index sets.
Is it possible to conjecture, e.g., that sums over index sets of $\aleph_{n}$ result in sums of cardinality $\aleph_{n}$? At most $\aleph_{n}$? Between $\aleph_{n-1}$ and $\aleph_{n}$?

A: Summing over an uncountable index results in an infinite sum if uncountably many terms are non-zero.
To see this, we prove the contrapositive: that if a sum over an uncountable index is finite implies that at most countably many terms are non-zero.
Proof. Let $\sum_{\alpha \in A} x_\alpha = L$. Let $S_n = \{\alpha \in A \mid x_\alpha > 1/n\}$. Then
$$L = \sum_{\alpha \in A} x_\alpha > \sum_{\alpha \in S_n} 1/n = \frac{|S_n|}{n}$$
So $| S_n| < nL$.
Let $S = \{\alpha \in A \mid x_\alpha > 0\}$. The $S$ is the countable union of each $S_n$, which are in turn each at most countable, so the result is at most countable.


text:
Q: How to format date in db with php I want to change format of a date:
if (!empty($_POST['dob']) && !empty($_POST['mob']) && !empty($_POST['yob'])) {
    $yob = mysqli_real_escape_string($con, $_POST['yob']);
    $mob = mysqli_real_escape_string($con, $_POST['mob']);
    $dob = mysqli_real_escape_string($con, $_POST['dob']);
    $date = mysqli_real_escape_string($con, "$yob->$mob->$mob");
    $addtothedb = "INSERT INTO login (Dateofbirth) VALUES ('". $date . "')";
    $result = mysqli_query($con, $addtothedb);
}

However the data I get from db is like yyyy-mm-dd whereas I would like to have it like dd-mm-yyyy.

A: You could use the http://php.net/manual/en/function.date.php function to get the desired format.
$result = date('d-m-Y', strtotime($birthdate));

A: You can do this:
$date = new DateTime($gd.'-'.$gm.'-'.$gy);
$formattedDate = $date->format('dd-mm-yyyy');
$addtothedb="INSERT INTO login (Dateofbirth) VALUES ('". $formattedDate . "')";

A: MySQL saves any Date type data in yyyy-mm-dd format. If you want it to be dd-mm-yyyy do NOT use Date data type, instead use VARCHAR(10) to save it.
Hope it helps!

A: I have 2 functions here.
The first function ( mydate($date) ) returns a date from mySQL Date format to a user readable format.
The second function (sqldate($date)) returns a date from user format to mySQL format !!!
  function mydate($date) {
        if ($date<>NULL) {  return date ('d/m/Y', strtotime($date)); } else { return ""; }
        }

function sqldate($date)
        {
        if (trim($date) == "") {return "";  }
        else {
         $date = str_replace('/', '-', $date);
        return date ('Y-m-d', strtotime(str_replace('/', '-', $date)));
        }
        }

A: Use form like this
<form id="form1" name="form1" method="post" action="#">
              From Date
              <input name="from" type="date" id="from" size="1" value="<?php echo $_POST['from']; ?>" />

              To Date
              <input name="to" type="date" id="to" size="1" value="<?php echo $_POST['to']; ?>"/>

And make script for your preferred date format

Then you can assign date to variable using $_POST Method and you got preferred date format


text:
Q: Getting margin-top of element whilst being animated I am animating an element with the top margin. However, when said element reaches a certain margin, I want to create another event. I did what I assumed would work, but it doesnt seem to be doing anything.
So I have an element moving to margin top 300px, and when it hits 300px I want it to got to margin-top -80px.
function raindrop(element,speed) {
    $(element).animate({
        'margin-top':'300px'
    }, speed, 'linear');
    margin = parseInt($(element).css('marginTop'));
    if(margin>=300) {
        $(element).css('marginTop','-80px');
            $(element).animate({
        'margin-top':'300px'
    }, speed, 'linear');
    }
}

I also want to use a re-cursive function here so it keeps doing it. Any ideas what I am doing wrong?

A: You don't need any if statement in your code to check the condition because if statement executes before the animation completes. Instead of if, better to use a callback function which will only execute after the first animation finishes. In callback, you can move your element back to margin-top:-80px once it reaches at 300px. If you also want to do recursion then you can call your raindrop() function as a callback function of second animation which does infinite looping. Here is the modified code:
jQuery:
$(document).ready(function () {
    $("#btn").click(function () {
        raindrop("#mydiv", 1000);
    });
});

function raindrop(element, speed) {
    $(element).animate({
        'margin-top': '300px'
    }, speed, 'linear', function () {
        margin = parseInt($(element).css('marginTop'));
        //alert(margin);
        $(element).animate({
            'margin-top': '-80px'
        }, speed, 'linear', raindrop(element, speed));
    });
}

CSS:
#mydiv
{
    border:1px solid red;
    width:300px;
    height:150px;
}

HTML:
<input type="button" id="btn" value="Press">


text:
Q: How could I set the default Azure Workbook group state to expanded? How could I set the default Azure Workbook group state to expanded?
I want to Show expand / collapse in title of group, but also I want the state to be expanded when a user sees the group for the first time. Right now (by default I assume) the default state is collapse. Is there a way to set the initial value for the collapsed/expanded?


text:
Q: Align 2 spans below an image in a div with CSS I have 3 elements in a div: 2 spans and an image. I need to align both spans below the image, one span on the left and one on the right. The div's width is 180px (if that matters). Any help is much appreciated.

A: HTML code:

CSS styles
div { overflow: hidden; width: 180px; }
span { display: block; }
.left { float: left; }
.right { float: right; }

That should work, if the image doesn't fill the div element, add "clear: both" to .left


text:
Q: Switch Rating for 50W LEDS I plan to have three 50 watt, 12V LEDS, 3750mA wired in parallel.  I would like to have an individual switch for each light.
What amp rating switch would I need for each light.  I wasn't sure if I need to factor the Ah of the battery or just account for the 3750mA the light demands (or is it the combined amps of all lights?) Sorry, learning here obviously.
Resistors aside, I would assume I would run the neutral from the LED to the battery and interrupt the Hot wire with the switch?

A: If each switch is supplying one string, you would just need to size the switch for the individual string - 3.75A.  Just make sure you are using a switch with a DC current rating of 3.75 or more; going off an AC rating alone is risky.
Yes, ground to the battery and switch on the positive supply line is fine.
You would need a separate resistor for each string but we can't speak to its size without knowing about the battery voltage.  However, if you're using a battery, the voltage will vary as it discharges and you're trying to run a pretty high powered system so a simple (high power) resistor is probably not the best choice.


text:
Q: Fluent TestValidate not raising validation errors for rules set on List with SetValidator While using Fluent's Test Helpers TestValidate method to unit test my rules, it throws TestValidationException when List of object is null. The validator setup specifies the NotNull rule.
Validator looks like below
public class RequestValidator : AbstractValidator<Request>
{
    public RulebookRequestValidator()
    {
        RuleFor(x => x.Id).NotEmpty();
        RuleFor(x => x.Name).NotEmpty();
        RuleForEach(x => x.EntryRequests).SetValidator(new EntryRequestValidator()).NotNull(); // Would like to validate this rule when EntryRequests is null.
    }
}

Child validator looks like this,
public class EntryRequestValidator : AbstractValidator<EntryRequest>
{
        public EntryRequestValidator()
        {
            RuleFor(x => x.EntryRequestId).NotEmpty();
            RuleForEach(x => x.Messages).NotNull().SetValidator(new MessagesValidator());
        }
 }

And in my unit test
[TestMethod]
public void Should_Have_Error_When_Object_Is_Empty()
{
    // arrange
    Request model = new () { EntryRequests = new () };
    var validator = new RequestValidator();

    // assert
    var result = validator.TestValidate(model);

    // act
    Assert.IsFalse(result.IsValid);
    result.ShouldHaveValidationErrorFor(x => x.Id)
            .WithErrorCode(NotEmptyValidatorErrorCode);
    result.ShouldHaveValidationErrorFor(x => x.Name)
            .WithErrorCode(NotEmptyValidatorErrorCode);
    result.ShouldHaveValidationErrorFor(x => x.EntryRequests); // throws ValidateTestException.
 }

Is this the right approach to test child validators on a List in Unit test? Looking for a way to use TestValidate to unit test this rule.

A: Your validator works correctly, but has one tiny problem.
Let's look at this rule:
RuleForEach(x => x.EntryRequests).SetValidator(new EntryRequestValidator()).NotNull();
It basically says: Run a NotNull check (and execute EntryRequestValidator)  against every element in the EntryRequest collection.
It does not work because your collection is empty: EntryRequests = new (). It has no elements, so there is nothing to validate.
Change it to:
RuleFor(x => x.EntryRequests).NotEmpty(); // throws validation error when collection is null or empty
RuleForEach(x => x.EntryRequests).SetValidator(new EntryRequestValidator()).NotNull();

With above rules you would get validation error when:

*

*EntryRequests = null

*EntryRequests = empty list

*any element of this list is null

plus all validations from nested validator

A: public class RulebookRequestValidator : AbstractValidator<Request>
{
    public RulebookRequestValidator()
    {
        RuleFor(x => x.Id).NotEmpty();
        RuleFor(x => x.Name).NotEmpty();
        RuleFor(x => x.EntryRequests).NotNull()
            .ForEach(element => element.SetValidator(new EntryRequestValidator()).NotNull());
    }
}

you need to check for null for object, then set the validator for collection elements.
For readiblity you can define a custom rule builder extension method.
public static IRuleBuilderOptions<T, IEnumerable<TK>> MustBeValidCollection<T, TK>(
        this IRuleBuilder<T, IEnumerable<TK>> ruleBuilder,
        AbstractValidator<TK> validator)
    {
        return ruleBuilder.NotNull()
            .ForEach(collection => collection.NotNull().SetValidator(validator));
    }

and use it like  RuleFor(x => x.EntryRequests).MustBeValidCollection(new EntryRequestValidator());


text:
Q: Is my Oauth right? I have had Oauth on my extension for about a month now and To be completely honest, I have no idea what is going on. I try to look at statistics from google API, but there arent any.
SO my question is:
Is there something wrong with my code? And what am I doing wrong with "TRIAL_PERIOD_DAYS"?
 chrome.identity.getAuthToken({
    interactive: true
}, function(token){

var CWS_LICENSE_API_URL = 'https://www.googleapis.com/chromewebstore/v1.1/userlicenses/fcjhennclbpgegahkbbnndbhmlhkdabe';
var req = new XMLHttpRequest();
req.open('GET', CWS_LICENSE_API_URL + chrome.runtime.id);
req.setRequestHeader('Authorization', 'Bearer ' + token);
req.onreadystatechange = function() {
  if (req.readyState == 4) {
    var license = JSON.parse(req.responseText);
    console.log(license);
    verifyAndSaveLicense(license);
  }
}
req.send();
console.log(TRIAL_PERIOD_DAYS);
var licenseStatus;
if (license.result && license.accessLevel == "FULL") {
  console.log("Fully paid & properly licensed.");
  licenseStatus = "FULL";
} else if (license.result && license.accessLevel == "FREE_TRIAL") {
  var daysAgoLicenseIssued = Date.now() - parseInt(license.createdTime, 10);
  daysAgoLicenseIssued = daysAgoLicenseIssued / 1000 / 60 / 60 / 24;
  if (daysAgoLicenseIssued <= TRIAL_PERIOD_DAYS) {
    console.log("Free trial, still within trial period");
    licenseStatus = "FREE_TRIAL";
  } else {
    console.log("Free trial, trial period expired.");
    licenseStatus = "FREE_TRIAL_EXPIRED";
    window.open('https://chrome.google.com/webstore/detail/premium-roulette/fcjhennclbpgegahkbbnndbhmlhkdabe');
  }
} else {
  console.log("No license ever issued.");
  licenseStatus = "NONE";
}
});

A: Kindly check the Tutorial: OAuth guide for Chrome. For actual code samples check this:

*

*oauth_contacts demo.

*gdocs demo.

Also check the subscription guide. It mentions a way of verifying payment and offering free trial which might help in your situation.


text:
Q: how to put Image outside of its parent div when hover I have a scrollable div with some img elements in it. I have added a hover effect of width and height for images. It works fine, but image get stuck in #scroller div. I want that the image get out of scroller div when mouse over it. How can I do that ?
CSS:
#scroller {
    width:100%;
    border:1px solid black;
    white-space:nowrap;
    height:130px;
    display:inline-block;
    overflow-x:scroll;
    overflow-y:hidden;
}
img {
    width:128px;
    height:128px;
}
img:hover {
    width : 192px;
    height:192px;
}

HTML:

     ...and some more images

I didn't try anything because I have no idea.

A: If you are planning to use CSS only, one approach could be to change the position of the image on hover to absolute.
Look at this example: http://jsfiddle.net/Vn8M6/3/
#scroller {
    width:100%;
    height:100%;
    border:1px solid black;
    white-space:nowrap;
    height:130px;
    display:inline-block;
    overflow-x:scroll;
    overflow-y:hidden;
}

img {
    width:128px;
    height:128px;
    transition: ease-in-out 0s;
    -webkit-backface-visibility: hidden;
    -webkit-transform: translateX(0);
     z-index:1;
    background-color:grey;
}

img:nth-child(2) {
    background-color:yellow;
     z-index:2;
}

img:nth-child(3) {
    background-color:red;
    z-index:3;
}

img:nth-child(4) {
    background-color:blue;
     z-index:4;
}

img:hover {
    width : 192px;
    height:192px;
    position:absolute;
    top:0;
}

Otherwise you could use javascript to have achieve better results.

A: This won't work, because u defined:
overflow-x:scroll; overflow-y:hidden;

Delete these or set up your images with style attribute "absolute" and position them with "right, top, left, bottom" for correct placement!
Greetz

A: you need to change CSS to on hover allow image to go outside the bounds of parent.
#scroller:hover {
    overflow-x:scroll;
    overflow-visible;
}

A: You can Try -
 #scroller:hover {
    overflow-x:scroll;
    overflow-y:visible;
    height:100%;
 }

JSFIDDLE


text:
Q: Sphere of circumferential radius $r$ What do you then mean by constructing a sphere of circumferential radius   $r$ centered on the black hole? Is that sphere a 2D surface?

A: This is as discussed in my answer to your previous question: Angular coordinates are unaffected?
The phrase circumferential radius means the radius you get by dividing the circumference of the sphere by $2\pi$ i.e. it is the Schwarzschild $r$ coordinate of the sphere.
The sphere is indeed a two dimensional manifold. That is the $r$ coordinate is fixed and the $t$ coordinate is ignored so points lying in the sphere can be labelled using just the $\theta$ and $\phi$ coordinates.


text:
Q: SonarQube API for getting critical security vulnerabilities Is there a SonarQube API available that will give me the security vulnerabilities and bugs of specific criticality (Ex: Blocker).

A: Use GET api/issues/search with severities parameter.

Search for issues.
At most one of the following parameters can be provided at the same time: componentKeys and componentUuids.
  Requires the 'Browse' permission on the specified project(s).
severities optional
Comma-separated list of severities
Possible values

*

*INFO

*MINOR

*MAJOR

*CRITICAL

*BLOCKER

  Example value: BLOCKER,CRITICAL

UPDATE
In order to retrieve only the newer issues, you could use:

sinceLeakPeriod
To retrieve issues created since the leak period.
  If this parameter is set to a truthy value, createdAfter must not be set and one component id or key must be provided.
Possible values

*

*true

*false

*yes

*no

  Default value: false

or

createdAfter
To retrieve issues created after the given date (inclusive).
  Either a date (server timezone) or datetime can be provided.
  If this parameter is set, createdSince must not be set
Example value: 2017-10-19 or 2017-10-19T13:00:00+0200

or even

createdInLast
To retrieve issues created during a time span before the current time (exclusive). Accepted units are 'y' for year, 'm' for month, 'w' for week and 'd' for day. If this parameter is set, createdAfter must not be set
Example value: 1m2w (1 month 2 weeks)

Just be aware that these parameters are mutually exclusive, and sinceLeakPeriod forces you to specify one component. See the API documentation for more details and examples.


text:
Q: Downloading file with DownloadManager Android I am trying to download a file using the DownloadManager inside an AsyncTask
private class DownloadTask extends AsyncTask<String, Void, Boolean>
{

    private Context mContext;

    public DownloadTask(Context context)
    {
        mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... strings) {

        String fileName = strings[2]+"_"+strings[3]+ strings[4];
        String destination = mDestination + fileName;
        final Uri uri = Uri.parse("file://" + destination);
        mDownloading = true;
        //If the file is already downloading just return.
        File file = new File(destination);
        if (file.exists()) {
            return true;
        }

        //set downloadmanager
        DownloadManager.Request request = new    DownloadManager.Request(Uri.parse(strings[0]));
        request.setDescription(mContext.getString(R.string.downloading)+ " "+strings[1]);
        request.setTitle(mContext.getString(R.string.downloading_title));

        //set destination
        request.setDestinationUri(uri);

        // get download service and enqueue file
        final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

        final long downloadId = manager.enqueue(request);

        //set BroadcastReceiver to enable next download
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            public void onReceive(Context ctxt, Intent intent) {
                unregisterReceiver(this);
                mDownloading = false;
            }
        };
        //register receiver for when file download is compete
        registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        return true;
    }
}`

The code works fine when I pass the url of the file. The thing is, that we want to make a GET call to a WEB made on PHP. This WEB method creates or selects a file and redirects using  header("Location: ".$database->single()['Url']);
But when we make the call from DownloadManager it just calls registerReceiver right away.
Does anyone knows why this happens?
If we use a HttpURLConnection it works fine, but we would like to delegate all the hard work of the download in the DownloadManager.
Thank you for your comments.

A: 3xx: redirects is't supported by DownloadManger. Source code at line 510
And it will download the redirect response and finish right way.
So you should get the response head[Location] by yourself, and pass it to the task.

By the way, you needn't put the download task in the AsyncTask.


text:
Q: sql query to get info from the same table? lets say I have a table structure in the following format:
ParentItemId is an id to the Item table itself.
Item,  ItemId, ParentItemId
---------------------------
 Apple  1         0
Orange  2         1
Lemon   3         2

What i want is, given ItemId= 3, i want a list in the form of, (3,2) (2,1) and (1,0)
If given ItemID = 2, i want a list , (2,1) and (1,0)
ParentItemID = 0, is the terminating condition.
Is there an efficient way to do this in terms of a sql query? i could only think of doing this by joining the same table multiple times...


text:
Q: I can't take a literal string on PHP 5.3 I'm trying publish an automatic tweet using codebird.
My trouble is with the message.
I take the text from my DB an I put in the variable $mensaje, how you can see:
//Formato del texto
$Texto="$tit[title]: $bod[body_value]";
$MaxLENGTH=110;
$TextoResumen = substr($Texto,0,strrpos(substr($Texto,0,$MaxLENGTH)," "));
$TextoResumen = utf8_encode(html_entity_decode($TextoResumen));
$mensaje = $TextoResumen." - ".$short;

And the array for to publish is the next:
$params = array('status' => $mensaje);
$reply = $cb->statuses_update($params);

And the tweet is not published.
But, if I write text in the variable, the tweet is published.
$mensaje = "Hello world!";

or
$mensaje = 'Hello world!';

I tried all without success.
Do you have any idea for me?

A: I have added single quotes to access your array variables in your string, and used concatenation instead, and I have pruned it to Maxlength because I'm not sure what you were trying to acheive with the rest of that substr command. You can share if you like, but you want a tweet to be 110 characters or less, that should be enough:
//Formato del texto
$Texto=$tit['title'].": ".$bod['body_value'];
$MaxLENGTH=110;
$TextoResumen = substr($Texto,0,$MaxLENGTH);
$TextoResumen = utf8_encode(html_entity_decode($TextoResumen));
$mensaje = $TextoResumen." - ".$short;

A: For information, the problem was the domain blocked in Twitter.
I was using the domain adf.ly for to share my twits.
Actually my code is the next:
//Carga texto
            $Texto="$tit[title]: $bod[body_value]";
            $MaxLENGTH=110;
            $TextoResumen = substr($Texto,0,strrpos(substr($Texto,0,$MaxLENGTH)," "));
            $TextoResumen = strip_tags($TextoResumen);
            $TextoResumen = utf8_encode(html_entity_decode($TextoResumen));
            $mensaje = "$TextoResumen... $short";

See you later.


text:
Q: Efficient solution for storing many small integers I am going to generate a dataset that will contain around 7*10^11 integers. Each integer will be between 0-1000. Uncompressed, this will require storage of about 14 TB (short integers).
Is there an efficient database solution with built-in compression for this kind of information?

A: Are you only storing the integers, or something else?
Why wouldn't you make a table with two columns:

*

*Number: being 0 to 1000

*Count: being how many times this appeared in the set

Do you have some unstated requirement, such as having to keep them in order?

A: A storage of 10 bits would cover an integer up to 1024, which is greater than your expected max value of 1000.  So, you could use a multi-bit column which only has a width of 10.  This would reduce your storage overhead to only 875 GB, instead of 14 TB.
In Postgres, there is a BIT type which should work here.  I would expect that most databases would have something similar to this.


text:
Q: JavaScript not working on HTML file (Express) I've got an express server to which I'm rendering my payj.html file which contains a script tag for the clyint.js file. But when I do that I get this error from the browser's console:

GET https://iovyb.sse.codesandbox.io/views/clyint.js net::ERR_ABORTED 404

I also tried including all my JS in the HTML file itself but that didn't work either, for some reason.
ecspres.js
// stop node prawsesiz: pkill -f node
var engines = require("consolidate");
var express = require("express");
var app = express();

app.engine("html", engines.mustache);
app.set("view engine", "html");
// app.use(express.static("src"));
// app.set("port", process.env.PORT || 8080);

var http = require("http");
var server = http.createServer(app);

server.listen(8080, function () {
  console.log("Server Up"); //now??
});

app.get("/", function (req, res) {
  res.render("payj.html");
});

var io = require("socket.io").listen(server);

io.on("connection", (socket) => {
  console.log(socket.id + " joind");
  socket.on("Name", (name) => {
    console.log(name + " cunectid");
  });
});

// //create a server object:
// http
//   .createServer(function (req, res) {
//     res.write("Hello Server!"); //write a response to the client
//     res.end(); //end the response
//   })
//   .listen(8080); //the server object listens on port 8080

payj.html
<!DOCTYPE html>

    <title>TTT!</title>

    <button>PLAY AGAIN</button>

clyint.js
// var name = window.prompt("hoo aar yoo");
var io = require("socket.io-client");
var soc = io("https://iovyb.sse.codesandbox.io/");

soc.emit("Name", "Dhroov");

function reset() {
  console.log("gei");
  var x = document.querySelectorAll("img");
  a = 0;
  while (a < x.length) {
    x[a].setAttribute("src", "");
    a++;
  }
}

var aTurn = true;
// $(window).load(function () {
var buts = document.querySelectorAll("td");
var a = 0;
console.log(buts.length);

while (a < buts.length) {
  // buts[a].addEventListener("click", clic);
  buts[a].setAttribute("id", a.toString());
  buts[a].addEventListener("click", function clic() {
    a = this.id;
    if (aTurn) {
      var t = document.querySelectorAll("td")[a];
      console.log(t);
      var td = t.querySelector("img");
      td.setAttribute("style", "");
      td.setAttribute("which", "cros");
      td.setAttribute("width", "79px");
      td.setAttribute(
        "src",
        "https://cdn.pixabay.com/photo/2012/04/12/20/12/x-30465_640.png"
      );
      t.style.marginLeft = "10px";
    } else {
      var t = document.querySelectorAll("td")[a];
      var td = t.querySelector("img");
      td.setAttribute("width", "99px");
      td.setAttribute("src", "https://otranscribe.com/favicon.png");
      td.setAttribute("which", "not");
      td.setAttribute("style", "");
      t.style.marginLeft = "10px";
    }
    aTurn = !aTurn;
    var but = document.querySelector("button");
    but.addEventListener("click", reset.bind());
  });

  a++;
}
// checking for win:
// a=0
// var num=0
// function checStrayt(hoo, from, to, dir){
//   var t = document.querySelectorAll("td")
//   while(true){
//     if(t[a].which==hoo)
//       num++;
//     else
//       break
//     if(dir==1)
//       a+=3
//     else if(dir==2)
//       a++
//     else

// }

Also, if it helps, this is my folder structure:

What shall I do?

A: you need to set the static directory where you will be saving your static files.
in express you can do it using :
app.use(express.static('public'))
this is a middleware that seta the static folder.
the path '/' will point to the static directory in your HTML code.

A: Add all your static files such as js , css and images in a separate folder, with a name, say, public
and in your express.js file add the following line before any of your routes,
app.use(express.static(path.join(__dirname,'public')))

for this you need to install path module using npm install path command
and in your html file just mention the name of the static file in you script or link


text:
Q: Mobius: How to set CSharpBackendPortNumber for c# app to talk to Spark Cluster on Linux? I have this very basic code to be run from windows machine connecting to a spark cluster running on a linux virtual box:
        string sparkMaster = "spark://192.168.1.193:7077";
        string hdfsURI = "hdfs://192.168.1.193:8020";

        var sparkContext = new SparkContext(new SparkConf().SetAppName("MobiusWordCount").SetMaster(sparkMaster));

Followed the instruction as in "getting started page" (installed spark on the windows gateway machine and other prerequisites):
D:\SparkCLR\runtime>scripts\sparkclr-submit.cmd --master spark://192.168.1.193:7077 --total-executor-cores 2 --exe Spar
kCLR.exe "C:\Users\aaa\Documents\Visual Studio 2015\Projects\SparkCLR\SparkCLR\bin\Debug"
Got this error:
SPARKCLR_JAR=spark-clr_2.10-1.6.100.jar
Exception in thread "main" java.lang.NullPointerException
        at org.apache.spark.launcher.SparkCLRSubmitArguments.concatCmdOptions(SparkCLRSubmitArguments.scala:389)
        at org.apache.spark.launcher.SparkCLRSubmitArguments.buildCmdOptions(SparkCLRSubmitArguments.scala:492)
        at org.apache.spark.launcher.SparkCLRSubmitArguments$.main(SparkCLRSubmitArguments.scala:30)
        at org.apache.spark.launcher.SparkCLRSubmitArguments.main(SparkCLRSubmitArguments.scala)
D:\SparkCLR\runtime>scripts\sparkclr-submit.cmd --verbose --master spark://192.168.1.193:7077 --total-executor-cores 2
--exe SparkCLR.exe "C:\Users\aaa\Documents\Visual Studio 2015\Projects\SparkCLR\SparkCLR\bin\Debug"
SPARKCLR_JAR=spark-clr_2.10-1.6.100.jar
Exception in thread "main" java.lang.NullPointerException
        at org.apache.spark.launcher.SparkCLRSubmitArguments.concatCmdOptions(SparkCLRSubmitArguments.scala:389)
        at org.apache.spark.launcher.SparkCLRSubmitArguments.buildCmdOptions(SparkCLRSubmitArguments.scala:492)
        at org.apache.spark.launcher.SparkCLRSubmitArguments$.main(SparkCLRSubmitArguments.scala:30)
        at org.apache.spark.launcher.SparkCLRSubmitArguments.main(SparkCLRSubmitArguments.scala)
Any thoughts?

A: You do not need to compile Mobius code to use it in Linux. You can either get an official Mobius release and use it or if you have pre-built Mobius binaries (jar file and dlls) from a GitHub repo, you can use them in Windows or Linux irrespective of the platform on which they were built. Mono is a requirement to run Mobius in Linux. If you choose to build Mobius in Linux you need Mono for that as well.
You need to specify CSharpBackendPortNumber and CSharpWorkerPath in your driver config file only for debugging Mobius driver app in local mode. This will enable debugging of your C# Spark application by connecting your C# driver process from Visual Studio to the JVM process (running CSharpRunner) that is launched separately in an IDE (IntelliJ or Eclipse) or using sparkclr-submit script with "debug" parameter.
For normal (non-debug) execution of Apache Spark C# applications implemented using Mobius, you just need to run sparkclr-submit script without enabling debug switches (CSharpBackendPortNumber and CSharpWorkerPath) in the driver config file. You can find instructions to run a Mobius application at getting-started page. The instructions cover running Mobius in standalone and YARN clusters in Windows and Linux.


text:
Q: Trim part of a string in dataframe If I have a dataframe structure like that:
AA1_123.zip
BB2_456.txt
CCC_789.doc

How can I change it to this:
AA1
BB2
CCC

A: You could try sub
sub('_.*', '', df1$Col)
#[1] "AA1" "BB2" "CCC"

data
df1 <- structure(list(Col = c("AA1_123.zip", "BB2_456.txt",
"CCC_789.doc"
)), .Names = "Col", class = "data.frame", row.names = c(NA, -3L))

A: If the strings are all the same style at the start, three characters before the underline, this will work:
df1 <- structure(list(Col = c("AA1_123.zip", "BB2_456.txt",
                              "CCC_789.doc"
)), .Names = "Col", class = "data.frame", row.names = c(NA, -3L))

> substr(df1$Col, 1, 3)
[1] "AA1" "BB2" "CCC"

A: You could also read the column again, using comment.char = "_" to flush the rest of the line.  Y
df <- data.frame(x = c("AA1_123.zip", "BB2_456.txt", "CCC_789.doc"))

read.table(text = as.character(df$x), comment.char="_")
#    V1
# 1 AA1
# 2 BB2
# 3 CCC

Or you can use scan()
scan(text = as.character(df$x), what = "", comment.char="_")
# Read 3 items
# [1] "AA1" "BB2" "CCC"


text:
Q: .htaccess Rewriting All Requests To A Subfolder Based on IP I am trying to create a ban jail for my server and I want to rewrite all requests from an IP to a folder called "banned". From there, several PHP files will take care of the ban notification. I am having no issue with the scripts, but when I try to use the rewrite rules in my .htaccess, my browser simply warns me  that the page isn't redirecting properly. Here is my code
# Configure The Rules
Options +FollowSymLinks
RewriteEngine On

<If "%{REMOTE_ADDR} ='<insert banned IP here>'">
RewriteCond %{REQUEST_URI} !=/banned
RewriteRule .* /banned
</If>

I have tried other solutions, but they either resulted in 500 errors, 400 errors, or a url filled with malformed requests such as "example.com/*If/banned//var/www/html/*If/banned..."
Please help.
Update: Using curl -I: 'example.com' produces the following result:
HTTP/1.1 301 Moved Permanently
Date: Fri, 10 Nov 2017 19:22:27 GMT
Server: Apache
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Location: https://example.com/banned/
Content-Type: text/html; charset=iso-8859-1

A: Be mindful of trailing slash that gets added after a directory by default using mod_dir module.
You can use this rule instead of your code:
# Configure The Rules
Options +FollowSymLinks
RewriteEngine On

<If "%{REMOTE_ADDR} ='<insert banned IP here>'">
RewriteCond %{REQUEST_URI} !^/banned/ [NC]
RewriteRule ^ /banned/ [L]
</If>


text:
Q: How to encrypt sql Tables How do I encrypt sql tables? Any help will be appreciated.
I am starting my encryption on file(items) upload from txt file.
My idea is like this:
global.php
$config["encode_key"] = "T07EGsS123123";

fileupload
 $sql = "UPDATE " . $config["table_items"] . " SET itemContent = AES_ENCRYPT('$content', '$config[encode_key]')

and after it I must show the items using decrypt with config key.


text:
Q: Reset form field to Initial State on submit with React Hooks I'm trying to reset my form fields to blank when a button is pressed.  For some reason its not working.
Here is my sample code:
initialize:
function App() {
  const [textField, setTextField] = useState("");

Clear the state:
  const clearState = () => {
    setTextField('');
  }

On submit:
  const submitForm = () => {
    clearState();
  };

Form field:
        <Form.Group controlId="textField">
          <Form.Control placeholder="Description" onChange={handleTextFieldInput} />
        </Form.Group>

But when I submit, the value is still the same as was input.

A: Set value={textField} on the Form.Control, that should fix it :)


text:
Q: How to keep the android monkey tool running? i.e not limiting the number of events How do I tell the Android Monkey Tool that it should run for an infinite amount of events?

A: Unfortunately the design of the monkey does not fit running an unlimited number of events.
When you provide parameters on your monkey command, it uses those to produce a script file, and then runs that script from the file.  Thus an unlimited number of events would require an infinitely long script file.


text:
Q: Restore files from a recycle bin, that is located on a server store of a roaming profile An organization has a domain and all users have a roaming profiles.
A user deletes files from My Documents, and they appear to be in the recycle bin on the server's user profile store.
How can admin access and restore those files?
A particular computer, from where the files were put to the recycle bin is no longer available. If an admin logs in with this user profile on a different PC, the recycle bin in the profile is empty.

A: If there's a file in the profile on a server that you want access to as an administrator you can take ownership of the profile and all the files under it, give yourself the rights to access that profile and navigate the filesystem as you would any other directory. When done you change the owner of that profile folder and all sub-folders and files back to the original user.
I'm not sure if the files in the recycle bin are typically stored in the profile. The best solution if it's something important is to restore it from your backups so you don't need to mess with the ownership and permissions on the profile. I've had times where things got screwy after changing this, plus you have to make sure the user isn't accessing those files anywhere else on the network at the time.
Another method to check is to have them log in somewhere and access their profile path from their login. They have permission to access it on the server, and if you think it's in a recycle folder within the profile on the server it should get synced to another machine at login. If it's not on the workstation at login, it's not part of the profile...so emptied recycle bin means it's not in the profile. You wouldn't be able to get it back anyway.


text:
Q: How to embed IronPython in a non-.NET application? Is it possible to call IronPython functions (and get access to their return values), from C/C++ code, without .NET? And if yes, how?
Is an embedding approach as in the python-c-api possible (i.e. as described here: http://docs.python.org/2/extending/embedding.html)?.
In our project, we cannot depend on .NET. However, we'd like to interact with other software, which exposes its interface through IronPython.

A: The only way to do it would be to host the .NET runtime or embed Mono in your C++ application, and then run IronPython inside of the embedded CLR. IronPython requires a CLR implementation; there's simply no way around that.


text:
Q: JavaScript Elements of array being equal function not working While taking some online JS tests, I am stuck on why my function for testing if the elements within two arrays are equal is not working. I am using the function to make sure that the new array does not have duplicate values.
The following is my function for testing if the elements of the arrays are equal or not:
  const isEqualArr = (a, b) => {
    for (let i = 0; i < a.length; i++) {
      if (a[i] != b[i]) {
        return false;
      }
    }
    return true;
  };

I call to the function within a for loop, then I test for undefined, because the first time around, the outputArr is empty
for (let x = 0; x < numsLength; x++) {
  if (typeof outputArr[x] != 'undefined') {
     if (isEqualArr(tempArr, [outputArr[x]])) {

However, the result shows that there are duplicates:
0: Array [ -1, 0, 1 ]

1: Array [ -1, 2, -1 ]

2: Array []

3: Array [ -1, -1, 2 ]

4: Array []

5: Array [ 0, 1, -1 ]

6: Array [ 0, -1, 1 ]

7: Array [ 1, 0, -1 ]

8: Array [ -1, 0, 1 ]

The other issue is that not only do I have two null arrays (duplicates), but when I test for null before the push, it is not working either:
if(tempArr != null ) {
  outputArr.push(tempArr);
}

I have tried tempArr[0] != null, tempArr[0] != '' as well as
if (typeof tempArr[0] != 'undefined')

But it still inserts null arrays into the outputArr.
The following is the premise of the test:
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets. Given nums = [-1,0,1,2,-1,-4]
The following code is my solution, but the duplicate entries, as well as the null entries, makes this an incorrect solution. If you guys can see why my isEqualArr function is at fault, then I would appreciate it.
const threeSum = (nums) => {
  let numsLength = nums.length;
  let tempArr = [];
  let outputArr = [];

  if (numsLength > 3) {
    for (let i = 0; i < numsLength; i++) {
      for (let j = 1; j < numsLength; j++) {
        for (let k = 2; k < numsLength; k++) {
          if (
            i != j &&
            i != k &&
            j != k &&
            nums[i] + nums[j] + nums[k] == 0
          ) {
            tempArr[0] = nums[i];
            tempArr[1] = nums[j];
            tempArr[2] = nums[k];

            for (let x = 0; x < numsLength; x++) {
              if (typeof outputArr[x] != 'undefined') {
                if (!isEqualArr(tempArr, [outputArr[x]])) {
                  if (typeof tempArr[0] != 'undefined') {
                    outputArr.push(tempArr);
                    console.log(
                      'temp: ' + tempArr + ' outputArr: ' + outputArr[x]
                    );
                    console.log(
                      'compare: ' + isEqualArr(tempArr, outputArr[x])
                    );
                    console.log(outputArr);
                    tempArr = [];
                  }
                }
              }
            }

            if (i == 0) {
              outputArr.push(tempArr);
              tempArr = [];
            } else {
              // do nothing
            }
          }
        }
      }
    }
  }

  return outputArr;
};

const isEqualArr = (a, b) => {
  for (let i = 0; i < a.length; i++) {
    if (a[i] != b[i]) {
      return false;
    }
  }
  return true;
};

EDIT: I was able to eliminate the null entries by moving the code that checks if it is the first time to run above the for loop:
if (i == 0) {
  outputArr.push(tempArr);
  tempArr = [];
} else {
  // do nothing
}

for (let x = 0; x < numsLength; x++) {
  if (typeof outputArr[x] != 'undefined') {
    if (!isEqualArr(tempArr, [outputArr[x]])) {
      if (typeof tempArr[0] != 'undefined') {
        outputArr.push(tempArr);
        console.log(
          'temp: ' + tempArr + ' outputArr: ' + outputArr[x]
        );
        console.log(
          'compare: ' + isEqualArr(tempArr, outputArr[x])
        );
        console.log(outputArr);
        tempArr = [];
      }
    }
  }
}

BTW, another thing that is not working if the following logic:
i != j &&
i != k &&
j != k &&

You can see by the outputArr that this logic is being completely ignored.
REFACTORED: even though the online test marked my solution as wrong, you can see with the results, that it is correct. Especially when you factor in the conditionals for making sure that nums[i] != nums[j] and so forth:
 const threeSum = (nums) => {
  let numsLength = nums.length;
  let tempArr = [];
  let outputArr = [];

  for (let i = 0; i < numsLength; i++) {
    for (let j = 0; j < numsLength; j++) {
      for (let k = 0; k < numsLength; k++) {
        if (
          nums[i] != nums[j] &&
          nums[i] != nums[k] &&
          nums[j] != nums[k] &&
          nums[i] + nums[j] + nums[k] == 0
        ) {
          if (typeof outputArr[0] != 'undefined') {
            /**********
            * if it reaches this conditional
            * then outputArr has at least one element
            ***********/
            if (typeof outputArr[k] != 'undefined') {
              tempArr[0] = nums[i];
              tempArr[1] = nums[j];
              tempArr[2] = nums[k];
              if (isEqualArr(tempArr, outputArr)) {
                // do nothing because there is already an element within the array
              } else {
                outputArr.push(tempArr);
                // empty tempArr after insert
                tempArr = [];
              }
            }
          } else {
            // push triplet elements into temp array for the first iteration only
            tempArr[0] = nums[i];
            tempArr[1] = nums[j];
            tempArr[2] = nums[k];

            // insert tempArr for the first iteration only
            outputArr.push(tempArr);
            // empty tempArr after insert
            tempArr = [];
          }
        }
      }
    }
  }
  return outputArr;
};

const isEqualArr = (a, b) => {
  for (elem in b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] != elem[i]) {
        // do nothing
      } else {
        return true;
      }
    }
  }
  return false;
};

RESULTS:
(3) [Array(3), Array(3), Array(3)]
0: (3) [-1, 0, 1]
1: (3) [1, 0, -1]
2: (3) [-1, 1, 0]
length: 3

A: Your inner for loop is confusing, if you replace it by a forEach you can see what's going on, you should pass as argument outputArr[x] not [outputArr[x]] and there's more stuff.

const threeSum = (nums) => {
  let numsLength = nums.length;
  let tempArr = [];
  let outputArr = [];
  if(numsLength < 3) return;

  for (let i = 0; i < numsLength; i++) {
     for (let j = 1; j < numsLength; j++) {
        for (let k = 2; k < numsLength; k++) {
          if (
            i != j &&
            i != k &&
            j != k &&
            nums[i] + nums[j] + nums[k] == 0
          ) {
            tempArr.push(nums[i], nums[j], nums[k]); // push three at the same time, it's cleaner and avoid problems

            outputArr.forEach((arr, index) => {
               if(!isEqualArr(arr, outputArr[index])) outputArr.push(tempArr); // outputs correctly
            });

            if (i == 0) {
              outputArr.push(tempArr);
              tempArr = [];
            }
          }
        }
      }
    }
  return outputArr;
};

const isEqualArr = (a, b) => {
  for (let i = 0; i < a.length; i++) {
    if (a[i] != b[i]) {
      return false;
    }
  }
  return true;
};

console.log(threeSum([-1,0,1,2,-1,-4]));


text:
Q: How do I tweak a setting to ask user to input a value on event when one particular custom field is set to yes? I am new to trac and struggling with something. Any help is appreciated.
I have 2 custom fields. Field 1 can be yes or no. and field 2 asks for the number of hours spend.
I am trying to tweak a condition, when field 1 is set to yes, only then user have to put number of hours in the field 2.
I am not able to figure how to put a condition to ask user to input something or a number to be precise.
Thanks

A: While enforcing user input might sound like a common requirement, Trac developers decided, that it is not basic functionality, and as such it does not belong into core.
However, extending Trac to do what you want is easy, because functional extensions are actively encouraged by the modular component architecture and a bunch of extension interfaces, that allow hooking in custom code.
Common way for making certain ticket fields mandatory is to implement an ITicketManipulator according to your requirements. I suggest you look at existing code like TicketValidatorPlugin. Sure, its always better to reusing existing code and possibly contribute to improve it instead of reinventing the wheel over and over again.


text:
Q: Using useEffect does not update DOM element I am trying to set a role attribute of an element, when I console.log it seems that the attribute is changed, however when I inspect the DOM the table role isn't updated and I can't figure out why.
What am I doing wrong here and how can I update the role attribute in the DOM properly?
Here is my code:
import React, { useEffect } from 'react';
import * as ReactDOM from 'react-dom';
import { Grid, GridColumn } from '@progress/kendo-react-grid';
import products from './products.json';

const App = () => {
  useEffect(() => {
    let table = document.getElementsByClassName('grid')[0];
    table.setAttribute('role', 'table');
    console.log(table);
  }, []);
  return (
    <Grid
      style={{
        height: '400px',
      }}
      data={products}
      className="grid"
    >
      <GridColumn field="ProductID" title="ID" width="40px" />
      <GridColumn field="ProductName" title="Name" width="250px" />
      <GridColumn field="Category.CategoryName" title="CategoryName" />
      <GridColumn field="UnitPrice" title="Price" />
      <GridColumn field="UnitsInStock" title="In stock" />
    </Grid>
  );
};

ReactDOM.render(<App />, document.querySelector('my-app'));

A: You are setting the role attribute on the first .grid element which a HTMLDivElement.
Do this instead:
const grid = document.getElementsByClassName('grid')[0];
const table = grid.querySelector("table")
table && table.setAttribute('role', 'table');

Full code
import  React, { useEffect }  from 'react';
import * as ReactDOM from 'react-dom';
import { Grid, GridColumn } from '@progress/kendo-react-grid';
import products from './products.json';

const App = () => {
  useEffect(() => {
    const grid = document.getElementsByClassName('grid')[0];
    const table = grid.querySelector("table")
    table && table.setAttribute('role', 'table');
    console.log(table);
  }, []);

  return <Grid  className="grid" style={{
    height: '400px'
  }} data={products}>
        <GridColumn field="ProductID" title="ID" width="40px" />
        <GridColumn field="ProductName" title="Name" width="250px" />
        <GridColumn field="Category.CategoryName" title="CategoryName" />
        <GridColumn field="UnitPrice" title="Price" />
        <GridColumn field="UnitsInStock" title="In stock" />
      </Grid>;
};

ReactDOM.render(<App />, document.querySelector('my-app'));


text:
Q: how to get array element from model in backbone.js I have the following code:
Person = new Backbone.Model({
 data:[
    { age: "27" },
    {name: "alamin"}
]
});

now, how can I get the value?
person=new Person();
person.get(?);

Please provide me with a solution.

A: If you're using this model:
Person = new Backbone.Model({

data:[
    { age: "27" },
    {name: "alamin"}
]

});

So if you want to pull from an array within a model explicitly you should try this:
i = new App.Model.Person();
i.fetch();
i.get("data")[0].age;

This would return:
27

From there you can iterate through the data however you prefer.

A: I don't know of a data property when defining a model - maybe you mean defaults? as in
var Person = Backbone.Model.extend({
   defaults: {
      property1: value1,
      property2: value2,
      property3: ["arrval1", "arrval2", "arrval3"]
   });

You would retrieve the value of certain property using get: myperson.get('property1').
To set the value of a property use set: myperson.set('property1', 'newValueOfProperty')
If a property is an array the myperson.get('property3')[ index ]

A: To get the array as an object:
Use person.get('data')
To get the value of an attribute from the array:
Use person.get('data').name
Or  person.get('data')['name']

A: To obtain attributes of a specific element of the array:
var people = person.get('data'); // This gets the array of people.
var individual = people[0];      // This gets the 0th element of the array.
var age = individual.age;        // This gets the age property.
var name = individual.name;      // This gets the name property.


text:
Q: Python memory when plotting figures in a loop I am trying to print a sequence of images in a code loop. I will ultimately need to print around 1000 to show how my system varies with time. I have reviewed the methods outlined in Matplotlib runs out of memory when plotting in a loop but I still can't make the code produce more than 96 images or so.
The code I am using in its stripped out form is below
import numpy as np
import matplotlib as mpl
import os
def pltHM(graphname,graphtext,xAxis,yAxis,xMn,xMx,xCnt,yMn,yMx,yCnt,TCrt):
    plt = mpl.pyplot
    fig = plt.figure(figsize=(8,7), dpi=250)
    cmap = mpl.cm.jet
    norm = mpl.colors.Normalize(vmin=-3, vmax=3)
    X = np.linspace(xMn,xMx,xCnt)
    Y = np.linspace(yMn,yMx,yCnt)
    plt.xlabel(xAxis)
    plt.ylabel(yAxis)
    plt.pcolormesh(X,Y,TCrt,  cmap=cmap,norm=norm)
    plt.grid(color='w')
    plt.suptitle(graphtext, fontsize=14)
    plt.colorbar()
    plt.savefig(graphname, transparent = True)
    plt.cla()
    plt.clf()
    plt.close(fig)
    del plt
    del fig
    return

This is used in a simple loop as shown below
for loop1 in range(0,10):
    for loop2 in range(0,100):
        saveName = 'Test_Images/' + str(loop1) + '_' + str(loop2) + '.png'
        plotHeatMap(saveName,'Test','X','Y',-35,35,141,-30,30,121,Z)

Any advice on why the above is not releasing memory and causing the traceback message
RuntimeError: Could not allocate memory for image
Many thanks for any help provided

A: Here is one stripped example of what you can do.  As pointed out by Ajean, you should NOT import plt every time as you did!  It is enough once.  Also, do not delete the figure and create a new one...it is better to use the same figure and just replace the data.
import numpy as np
import matplotlib.pyplot as plt

def plotHeatMap(fig, line, x, y, graphname):
    line.set_data(x, y)
    fig.canvas.draw()
    fig.savefig(graphname)

fig1, ax1 = plt.subplots(1, 1)
line, = ax1.plot([],[])
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
for loop1 in range(0, 2):
    for loop2 in range(0, 2):
        x = np.random.random(100)
        y = np.random.random(100)
        save_name = 'fig_'+str(loop1) + '_' + str(loop2) + '.png'
        plotHeatMap(fig1, line, x, y, save_name)


text:
Q: Deciding If A Relation On A Set Is An Equivalence Relation The relation I am looking at is $\{(0,0),(1,1),(1,3),(2,2),(2,3),(3,1),(3,2),(3,3)\}$, and is on the set $\{0,1,2,3\}$
Apparently, the only thing that does not qualify this as an equivalence relation is the fact that it is not transitive. However, I can not see this.
I tried to work it out: $1R3\wedge3R1 \rightarrow 1R1$ True
$2R3\wedge3R2 \rightarrow 2R2$ True
I didn't feel it was necessary to show things like, $0R0\wedge0R0\rightarrow0R0$

A: $1R3$ and $3R2$ but not $1R2$.