Error in ExecuteNonQuery

Question: There seems to be a problem with my code. It appears there is something wrong with my .ExecuteNonQuery. The error I am receiving is
"No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type."
Could anyone see what is wrong with what I'm doing? Thanks a lot
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class CustomerLogin : System.Web.UI.Page
{
static readonly string scriptErrorUserId =
 "";

static readonly string scriptSuccessNewAccount =
"";

static readonly string scriptErrorInput =
"";

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection sqlCon = new SqlConnection(@"Data Source=DESKTOP-UNIV3GV;Initial Catalog=Bolsen;Integrated Security=True; MultipleActiveResultSets=true;");
    sqlCon.Open();
    Type csType = this.GetType();
    //Check to ensure that UserId keyed in is not being in used by other Customers

    SqlCommand sqlcmd;
    SqlDataReader rdr;
    string strSQLSelect = "SELECT cEmail FROM Customers ";
    sqlcmd = new SqlCommand(strSQLSelect, sqlCon);
    //SqlDataReader reader = sqlcmd.ExecuteReader();
    rdr = sqlcmd.ExecuteReader();
    while (rdr.Read() == true)

        if (txtEmail.Text == (string)rdr["cEmail"])
        {
            ClientScript.RegisterStartupScript(csType, "Error", scriptErrorUserId);
            sqlCon.Close();
            return;
        }
    if (txtEmail.Text == "")
    {
        ClientScript.RegisterStartupScript(csType, "Error", scriptErrorInput);
        sqlCon.Close();
        return;
    }
    // insert new record
    string strSQLInsert = "INSERT INTO "
        + " Customer  (Firstname, Lastname, cNumber, cCompanyName, cCompanyAddress, cEmail, cPassword)"
        + " VALUES (@FN, @LN, @Num, @CName, @CAdd, @Email, @PW)";
    sqlcmd = new SqlCommand(strSQLInsert, sqlCon);
    sqlcmd.Parameters.AddWithValue("@CFN", txtFN.Text);
    sqlcmd.Parameters.AddWithValue("@LN", txtLN.Text);
    sqlcmd.Parameters.AddWithValue("@Num", txtNum.Text);
    sqlcmd.Parameters.AddWithValue("@CName", txtCN);
    sqlcmd.Parameters.AddWithValue("@CAdd", txtCA.Text);
    sqlcmd.Parameters.AddWithValue("@Email", txtEmail.Text);
    sqlcmd.Parameters.AddWithValue("@PW", txtPwd.Text);
    sqlcmd.ExecuteNonQuery();
    sqlCon.Close();

    ClientScript.RegisterStartupScript(csType, "Success", scriptSuccessNewAccount);

    // prepare Session variables for newly registered customer

}

}
Comment: It's not your problem (as pointed out by TheGeneral) but you should get out of the habit of using `AddWithValue`, it has quirks which can end up biting you. It's preferable to use (for example) `sqlcmd.Parameters.Add("@name", SqlDbType.NVarChar, FieldLength).Value = YourValue;`
Comment: Thanks for the advice, this was taught to me by my school but in all honesty I think they're lacking behind.
Answer: Simple missing Property Text
Essentially, it doesn't know how to convert a TextBox (object), to your Sql parameter
Replace
sqlcmd.Parameters.AddWithValue("@CName", txtCN);

With
sqlcmd.Parameters.AddWithValue("@CName", txtCN.Text);

Error in ExecuteNonQuery


What is the technical term for this style lighting?

Question: It's basically looking like LED strip lights, whose light bounces off the ceiling, and the strips are on top of some sort of mold/ceiling fascia. I don't even know what to google to find a picture to add to the post
Comment: indirect lighting
Comment: actually making one for my son at the moment... led strip and wood cut to hold the led so it is recessed... Can't buy that in a shop...
Comment: I used to call it "cove lighting" but not sure if that's the right name.  Back in the day, you'd use common fluorescent tubes with a ballast with a very low ballast factor.  But today LED strips make it crazy easy.
Comment: Uplighting also comes to mind now... but that is just a particular form of indirect...
Comment: I've always heard either 'uplighting' or 'cove lighting'. I like the LED pucks and tubed strips like, ehem, that Scandinavian store sells. Unitized, stringable, and easy to clean compared to the cheaper, raw led strips. They do cost more.
Comment: I couldn't find anything except Indirect Lighting on the Illuminating Engineering Society list of definitions [ANSI/IES RP-16-17].  Really, the EIS actually exists.
Answer: Indirect lighting.
example here
Usually the light source is hidden by an archtectural feature, so the feature is constructed by normal building means and then the light source is hidden in it.
At my house we have one strip light hidden in an open topped curtain pelmet and another hidden behind an one of the exposed rafters.
These are 5' flourescent tubes with 40 year old iron ballasts.
Led strips could be hidden in a cornice moulding. etc.
it's going to be tricky to clean.
Comment: If it is sensibly designed then it can easily be removed for cleaning...


Removing brackets inside a formula

Question: So I created a macro that muliplies a cell value with 100 (10^2). If the cell is simply a value it justs multiplies the cell value with 100, however if it's a formula it puts the formula in brackets and adds a 100* to the beginning
As you can't undo a macro easily but I need it, I tried to create an "undo" macro.
The Cell Value-Undo is quite easy, however for the formulas I struggle to delete the outer brackets.
An example process would be:
Original: =1+1 becomes =100*(1+1) and the undo should return to =1+1 (without brackets).
This is my code for the multiplication:
Private Sub MultiplySelectionBy100(Control As IRibbonControl)

Dim Cell As Range
For Each Cell In Selection
If Len(Cell.Value) > 0 And Application.IsNumber(Cell.Value) Then
If Cell.HasFormula Then
Cell.Formula = Replace(Cell.Formula, "=", "=100*(") & ")"
Else
Cell.Value = 100 * Cell.Value
End If
End If
Next
Application.OnUndo "Undo something", "UnDoSomething"
End Sub

For the UNDO, this is what I have so far:
Public Sub UnDoSomething()
Dim Cell As Range
Dim bet As String
For Each Cell In Selection
If Len(Cell.Value) > 0 And Application.IsNumber(Cell.Value) Then
If Cell.HasFormula Then
Cell.Formula = Replace(Cell.Formula, "=100*(", "=") 'This is not running
Cell.Formula = Replace(Cell.Formula, Chr(41), Chr(0))
Else
Cell.Value = 100 / Cell.Value
End If
End If
Next
End Sub

I don't know how to attach multiple replace functions but it gives me an error every time (mostly because I delete a opening bracket but the closing bracket remains).
I also can't delete all brackets as there may be more brackets inside the formula.
Maybe you have an idea...
Comment: Does the formula get reformatted to have spaces?  i.e. you enter "=100*" but this gets respaced to "= 100 * (". In your undo try adding a debug.print Cell.Formula and then stepping through the undo to see what to change.
Answer: Your main problem is that the first replace command will set the formula invalid because the closing ")" is still there, and Excel (not VBA) doesn't allow an invalid formula, so you get a runtime error (1004).
You should use an intermediate variable to handle the string manipulation of the formula, and only if that is done completely, assign the formula back to the cell. Using intermediate variables is always a good idea if you are dealing with formulas in VBA - you can check with the debugger if the formula looks really as expected before you write it back to the cell.
You need to be careful with your second replace-statement: This will remove all closing parenthesis characters, even if it has nothing to do with your "Undo". You should (a) check if you really want to remove it and (b) remove only the last closing parenthesis.
    Dim f As String
    f = cell.Formula
    If Left(f, 6) = "=100*(" Then
        f = Replace(cell.Formula, "=100*(", "=")
        f = Left(f, Len(f) - 1)
        cell.Formula = f
    End If

Or, maybe easier
    If Left(f, 6) = "=100*(" Then
        f = "=" & Mid(f, 7, Len(f) - 7)
        cell.Formula = f
    End If

Removing brackets inside a formula


How to run Gunicorn inside virtualenv?

Question: Background
I'm currently configuring a Nginx + Gunicorn + Django + virtualenv setup. I have a prod_settings which will be used for production, and set DJANGO_SETTINGS_MODULE env variables to it by adding export DJANGO_SETTINGS_MODULE=project.prod_settings to project/venv/bin/activate. This works perfectly if I first run source project/venv/bin/activate.
Now I followed Instructions from DigitalOcean to use systemd to monitor Gunicorn.
Inside gunicorn.service file, I have ExecStart=/path/to/project/venv/bin/gunicorn.
Problem

If .../venv/bin/gunicorn runs inside virtualenv, will it activate virtualenv if I call this command from a system environment?

Also, I'm absolutely sure that calling  .../venv/bin/gunicorn from system env won't trigger source /project/venv/activate as the env variables are not defined.

Since .../venv/bin/gunicorn can be run from the system env, I wonder how it finds the lib of the virtualenv, instead of lib of the system?

This is how ../venv/bin/gunicorn looks
#!/home/hao/Eng-Memo/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from gunicorn.app.wsgiapp import run
if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(run())

Some reference resources can be extremely helpful!
Answer: I think I finally figured this out. According to Python Official docs:

You don't specifically need to activate a virtual environment, as you
can just specify the full path to that environment's Python
interpreter when invoking Python. Furthermore, all scripts installed
in the environment should be runnable without activating it.
In order to achieve this, scripts installed into virtual environments
have a "shebang" line which points to the environment's Python
interpreter, i.e. #!//bin/python. This means that the
script will run with that interpreter regardless of the value of PATH.
On Windows, "shebang" line processing is supported if you have the
Python Launcher for Windows installed. Thus, double-clicking an
installed script in a Windows Explorer window should run it with the
correct interpreter without the environment needing to be activated or
on the PATH.

So the first line of ../venv/bin/gunicorn, which looks like a comment actually plays a huge role. It specifies the Python interpreter to be used is the one of virtualenv. Hence, sys.path will add the site-packages folder inside lib of the virtualenv.
Comment: The 1st line that looks like a comment is called [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) and actually is a directive to Unix/Linux kernels what interpreter to run for this particular file.

How to run Gunicorn inside virtualenv?


How can parameters/settings be passed to a Scala macro?

Question: How can parameters/settings be passed to a Scala macro?
These settings should not be global, but per macro invocation.
What I would like to have is something similar to this:
def a(param: Int) = macro internalMacro("setting 1")
def b(param: Int) = macro internalMacro("setting 2")

whereas setting 1 and setting 2 should then be constant values, accessible from within the macro, so I can make the internal behavior dependent on them.
Answer: The parameter lists of your method and the macro definition have to line up exactly, with the macro definition method having an extra initial parameter list for the context, and every other parameter from the method definition having the same name and the same type wrapped in a c.Expr. (Note however that the type parameter lists can differ.)
This means that you can't pass information to the macro implementation as arguments in your method definition. You can use a static annotation to accomplish the same thing, though (this is a trick I learned from Eugene Burmako, who used it to implement structural types without reflective access, a.k.a. vampire methods):
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context

class setting(value: String) extends StaticAnnotation

def internalMacro(c: Context)(param: c.Expr[Int]) = {
  import c.universe._
  val settingValue = c.macroApplication.symbol.annotations.filter(
    _.tree.tpe <:< typeOf[setting]
  ).headOption.flatMap(
    _.tree.children.tail.collectFirst {
      case Literal(Constant(s: String)) => s
    }
  ).getOrElse(
    c.abort(c.enclosingPosition, "Annotation body not provided!")
  )
  settingValue match {
    case "setting 1" => c.Expr(q"42")
    case _ => param
  }
}

And then:
scala> @setting("setting 1") def a(param: Int): Int = macro internalMacro
defined term macro a: (param: Int)Int

scala> @setting("setting 2") def b(param: Int): Int = macro internalMacro
defined term macro b: (param: Int)Int

scala> def c(param: Int): Int = macro internalMacro
defined term macro c: (param: Int)Int

scala> a(10)
res0: Int = 42

scala> b(10)
res1: Int = 10

scala> c(10)
<console>:22: error: Annotation body not provided!
              c(10)
               ^

And I didn't even examine any enclosing trees. See my blog post here for an example of this approach in action.
Comment: Sure, I don't think it's overwhelmingly better, but if e.g. your macro definitions are in a separate object, using this approach lets you see the difference between two macro methods without guessing from names, jumping over to the macro definitions, etc.
Comment: Does this have any advantages over providing multiple macro wrapper impls (ie. `internalMacroSetting1`, `internalMacroSetting2`) which delegate (with argument) to the full impl?
Comment: It makes the parametrization clearer where it matters, and if you wrap up the annotation reading stuff once there can be less repetition / boilerplate (especially if you have lots of parameters).
Comment: I can see it's a win if there are multiple parameters. I'm not completely convinced in the single parameter case.
Comment: @MilesSabin multiple macro impls (one for each setting) will only work if the set of possible settings is finite (and reasonably small).
Comment: @TomasMikula I'd love to see a program with an infinite set of definitions `@setting("one")`, `@setting("two")`, etc. ... ;-) How long do you think it would take to compile?
Comment: @MilesSabin :D Any one program will have a finite set of settings, but there can be a potentially infinite number of programs using the same macro.


There's planar graph. Prove that for every $3$ (pairwise different) vertices $u, v, w$ the inequality holds: $deg(u) + deg(v) + deg(w) \leq 2|V| + 2$

Question: Let G = (V, E) be any planar graph.
Prove that for every three (pairwise different) vertices $u, v, w$ the inequality holds:
$$deg(u) + deg(v) + deg(w) \leq 2|V| + 2$$
I know that in a graph with |V| vertices, the maximum degree of each vertex is |V| − 1. Therefore it must be true that:
$$deg(u) + deg(v) + deg(w) \leq 3|V| - 3$$
For planar graphs it's true that $|V| - |E| + |F| = 2$ (Euler's equation), from that we can find the largest number of edges that a planar graph of $V$ vertices can have.
Each region defined by a drawing of graph on the plane is bounded by a cycle of the graph. If that cycle is not a triangle, we can add an edge between two opposite vertices and increase the number of edges. Therefore we conclude then that a graph with $V$ vertices with the most edges will have triangles for all its faces.
Then each face has three edges on its boundary, and the number of edge-face pairs with the edge bounding the face will be $3|F|$. But each edge bounds $2$ faces, so that the number of edge-face pairs with the edge bounding the face will also be $2|E|$.
We deduce then that $|F|= \frac{2}{3}|E|$, so that in this case we can write Euler's formula as: $|V| – |E| + \frac{2}{3}|E| = 2 \iff 3|V| = |E| + 6$
We notice also that the number of edge-vertex pairs with the vertex in the edge, is $2|E|$ and is also the sum of the degrees of all the vertices. This tells us that the sum of the degrees of the vertices of any edge maximal planar graph is equal to $2|E|$ or $6|V| – 12$. But I don't know how to translate that into our inequality.
Answer: Call a triplet $(v,w,u)$ of vertices in a planar graph ideal if the subgraph generated by considering only vertices adjacent to one of $v,w,u$, contains only vertices which are adjacent to at least $2$ of $v,w,u$
It suffices to prove the inequality for the subgraphs generated by ideal triplets, since if a triplet is not ideal, there is some vertex $x$ such that $x$ is adjacent to only one of $v,w,u$, in which case we can remove $x$ from the subgraph, and both sides of the inequality decrease by $1$. So we can keep removing vertices until the original triplet is ideal.
Now consider the subgraph $G'$ generated by an ideal triplet $(u,v,w)$. Since any vertex in this graph is shared by at least $2$ of $v,u,w$, define
$s_{v,w} = s_{w,v} =$ the number of vertices shared by $v$ and $w$ only in the subgraph.
Similarly define $s_{u,w}$ and $s_{v,u}$.
And let $s_{v,w,u}$ be the number of vertices shared by all $3$ of $v,w,u$.
It is clear that
$$ s_{v,u}+s_{w,u}+s_{v,w}+s_{v,w,u} \leq |V'|$$
Where $V'$ is the number of vertices of the subgraph.
And also note that
$$ s_{v,u} + s_{v,w} + s_{v,w,u} = deg(v) $$
So
$$ 2s_{v,u} + 2s_{w,u} + 2s_{v,w} + 3s_{v,w,u} = deg(v) + deg(u) + deg(w)$$
So
$$ deg(v)+deg(w)+deg(u) \leq 2|V'| + s_{v,w,u} $$
And I suspect that for a planar graph $s_{v,w,u} \leq 2$, which you can verify intuitively if you draw the star graph with $3$ vertices, and try to add $2$ more vertices shared by all $3$ original vertices, but I am not sure how to prove this part
Comment: I know this doesn't follow along the lines you were thinking, but I am not too familiar with some of the theorems you mentioned, so the partial solution was not too tractable for me
Comment: If $S_{u,v,w}$ is 3 or more doesnt that makes $K_{3,3}$?


How to clean unnecessary full text user queue items in dm_queue_item table in Documenutm 7.1/16.4 and Xplore 1.6?

Question: I have faced an issue where my environment's Index agent was NOT able to process new documents. While checking I fond out that dmi_queue_item cont is very high, so I am posting this self answered question which will let us know how to get your queue items cleaned up with Xplore OLD items.
Answer: In order to clear the unwanted queue items , we will have to perform following steps

Stop the Services for XPlore and CS
Backup the items that are not index user

create table temp_dmi_queue_item_s as (select * from dmi_queue_item_s where name <> 'dm_fulltext_index_user' AND name <> 'dm_fulltext_index_user_01' );

Truncate table

truncate table dmi_queue_item_s;

Restore the items that are not index user

insert into dmi_queue_item_s select * from temp_dmi_queue_item_s;

4)Run ftintegrity in order to fix any inconsistencies between Repository and Index data

Start the Services and add the test document, check if its getting queued for indexing

Note- Make sure, implementation of the above steps should be tested on non-production environment before production


$x \vee y \Rightarrow z \vee t$ - logic

Question: I show that $x \Rightarrow z$ and $y \Rightarrow t$ are true.
Is $x \vee y \Rightarrow z \vee t$ then true?
Comment: I see that the answers here use truth tables or otherwise implicitly use the law of the excluded middle. This is more general than that though, and still holds in constructive logic.
Answer: Instead of a brute force approach, one can prove the claim.
Assume $(x\Rightarrow z)\land (y\Rightarrow t)$. Since $(x\lor y)\Rightarrow(z\lor t)$ true if and only if whenever $(x\lor y)$ is valuated as true, then also $(z\lor t)$ does.
$x\lor y$ is true if and only if $x$ is true or $y$ is true.

If $x$ is true, then $z$ is true, therefore $t\lor z$ is true.
If $y$ is true, then $t$ is true, and thus $t\lor z$ is true.

Either way, if $x\lor y$ is true then $z\lor t$ is true as needed.
(Of course this can formalized completely using the $\operatorname{val}$ function and assignment of truth values for $x,y,z,t$.)
Answer: Yes, here is the truth table:

(Built by the java applet here)
Answer: Since $A \Rightarrow B \Leftrightarrow \lnot A \lor B $ we may write :
$\lnot(x \lor y) \lor (z \lor t)$
$(\lnot(x \lor y) \lor z)\lor t$
$((\lnot x \land \lnot y)\lor z)\lor t$
$((\lnot x \lor z)\land(\lnot y \lor z))\lor t$
$((x \Rightarrow z)\land(\lnot y\lor z))\lor t$
$(\top \land (\lnot y\lor z))\lor t$
$(\lnot y\lor z)\lor t$
$(\lnot y \lor t) \lor z$
$(y \Rightarrow t)\lor z$
$\top \lor z$
$\top$

$x \vee y \Rightarrow z \vee t$ - logic


Javascript not resolving worker path relative to current script

Question: I have a script at http://localhost/js/foo.js which needs to spawn a Web Worker from the file http://localhost/js/fooWorker.js. I assumed I could just do something like this:
var worker = new Worker('fooWorker.js')

However, this results in a 404 error, as the browser cannot find http://localhost/fooWorker.js. I was under the impression that worker paths were resolved relative to the script spawning the worker, so shouldn't I just be able to specify the name of another .js file in the same directory without having to provide an absolute path? Am I doing something wrong?
Comment: According to https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers?redirectlocale=en-US&redirectslug=Using_web_workers#Spawning_subworkers , this should work...
Comment: @ziesemer: The link you provided talks about sub-workers. These are not fully supported yet.
Answer: From http://www.w3.org/TR/workers/:

When the Worker(scriptURL) constructor is invoked, the user agent must
  run the following steps:

Resolve the scriptURL argument relative to the entry script's base
  URL, when the method is invoked.
Comment: Does anyone know how can base url be overriden when you instantiate a worker? Or are there some other practices how one can ship web workers in a lib?
Answer: Actually, it should be relative  to the embedded document path
For example,
I have
pathDoc\docA.html
js\b.js
js\worker\c.js

then code should be
var worker = new Worker('..\js\worker\c.js')

Comment: I tried this in a IIS hosted ASP.Net MVC app. But it didnt resolve the path. In the F12 network tab it shows 404. Any idea on IIS hosted sites
Answer: Note, you can still get the script url within the worker using the self.location and just prepend it to the paths to make them relative to the worker script rather than the html base url.
const workerUrl = location + '';
const basePath = workerUrl.replace(/\/[^/]+$/, '/');

self.importScripts(basePath + '/fooWorker.js');

Btw, if you include your worker via blob, you can still pass meta info like it's url via # hash params.
Comment: Why would you pass information through such an hacky way when you can postMessage it?
Comment: Weren't sure if `importScripts` can be called in a message listener. If it can, then sure, posting a message is also an option. Though that would be teensy bit slower I think.
Answer: With import.meta.url, you should be able to have it work like relative path.
var worker = new Worker(new URL('./fooWorker.js', import.meta.url));


Computational Geometry - Triangulation

Question: I'm trying to triangulate complex 3D objects, that may have holes in them. Now I tried going over the problem myself, after a few hours I didn't get anything that would work all of the time, so I've been searching around and without much luck. Does anyone know of any algorithms, or free libraries, that would suit my needs. Links to any relevant documentation would be appreciated as well.
Also as a note, I'm a self taught programmer/cs-tist.
I have a set of points and I need to provide a game engine the shape in triangles. I get these points from a shape, I then add points to add area, subtract area, or split the shape. After modifying/adding points I need to give the game engine the shape in triangles as well as other information. Holes could be anywhere in any shape.
Comment: Can you expand on what you mean by "complex 3D objects"? How are you representing the objects currently?
Comment: Are you dealing only with closed surfaces with holes (such as a bagel or doughnut) or also with holes that lead to the interior of the surface (such as a sphere with a hole leading inside)?
Comment: A given collection of points can be connected into a wide variety of different shape surfaces. Could you explain how these points are produced or how they relate to the intended surface?
Comment: Would using some algorithm like [marching cubes](https://en.wikipedia.org/wiki/Marching_cubes) over a density field work for you? You could populate a density field with contributions from the points and then sample from that.
Answer: What it means to "triangulate complex 3D objects" is not unambiguous.
Just one possible interpretation: You have a 3D polygon in space, and you
want to triangulate that. This is NP-hard:

Barequet, Gill, Matthew Dickerson, and David Eppstein. "On triangulating three-dimensional polygons." Proceedings of the 12th Symposium on Computational Geometry. ACM, 1996. (ACM link.)

Computational Geometry - Triangulation


MATLAB indexing by indexes in another matrix

Question: I'm trying to generate a new matrix, based on index values stored in another matrix.
This is trivial to do with a for loop, but this is currently the slowest line in some code I'm trying to optimise, and so I'm looking for a way to do it without the loop, and pulling my hair out.
I'm sure this has been answered before, and that I just don't know the right search terms.
n1 = 10;
n2 = 100;

a = randi(n2,[1,n1]);
b = randi(n2,[4,n1]);
c = rand(100,100);

for i = 1:n1
    d(:,i) = c(a(i),b(:,i));
end

Comment: Although it is possible to do this without a for loop, this piece of code already runs pretty fast (I'm getting <1ms). What are the values for `n1` and `n2` in your actual code?
Comment: Just preallocating the array `d` will speed up this code significantly. `d = zeros(4,n1);`, like @BillBokeey did in the answer below.
Answer: I'm assuming the value of n1 in your code is way bigger than in the example you provide, which would explain why it is "slow".
In order to do this without a loop, you can use Linear indexing:
n1 = 1e6;
n2 = 100;

a = randi(n2,[1,n1]);
b = randi(n2,[4,n1]);
c = rand(n2,n2);

% With a loop
d = zeros(4,n1);
tic

for i = 1:n1
    d(:,i) = c(a(i),b(:,i));
end

toc

% A faster way for big values of `n1`
d2 = zeros(4,n1);
tic

a_rep = repmat(a,4,1); % Repeat row indexes to match the elements in b

idx_Lin = sub2ind([n2,n2],a_rep(:),b(:)); % Get linear indexes

d2(:) = c(idx_Lin); % Fill

toc

isequal(d,d2)

Elapsed time is 1.309654 seconds.

Elapsed time is 0.062549 seconds.
ans =
logical
1
Answer: Try This:
n1 = 10;
n2 = 100;
a =  randi(n2,[1,n1]);
b =  randi(n2,[4,n1]);
c = rand(100,100);
idx = (1:n1);
tic
d1=(c(a(idx),b(:,idx)))';
[idx,idy]=meshgrid(0:44:400,1:4);
d1=d1(idy+idx);
toc

this is the timeing:
Elapsed time is 0.000517 seconds.

Comment: Now do `n1 = 1e6` or `n1 = 1e8` and see what happens…
Comment: Now worries, just two more lines & it is working.
Comment: But you create an intermediate `n1` square matrix, if `n1` is large, this will be slower than the loop version, just because of the large memory usage. I'm pretty sure BillBokeey's solution is faster even for fairly small `n1` values.
Comment: this is the time of 1st(ME),2nd(loop), & 3rd(BillBokeey): Elapsed time is 0.000616 seconds.
Elapsed time is 0.001542 seconds.
Elapsed time is 0.000857 seconds.


If kicked from CWL clan do you still get reward tokens?

Question: I recently was in a clan for their CWL and attacked their #1 for a three star even though I was #7. The leader had already claimed that base and got mad and kicked me.
Will I still be rewarded the CWL tokens after their CWL ends, or will they be lost? I have been jumping around clans so I'm not sure if that will affect it.
Answer: Taking a look at the wiki on Clan War Leagues, there are two interesting points it makes (emphasis mine).

Aside from being in a league setting, Clans can still earn war loot and Clan XP in the same way as they do in a Clan War. Players can earn war loot that they've won even if they leave the Clan before the relevant war concludes.

and

Players can only be in one Clan's War League roster at any one time. Once they have been signed up by the leader for a particular Clan, their War League participation is only limited to that Clan. The player will only be eligible for War League rewards in the Clan he/she participates in.

Based on these, even though you have hopped around to other clans, since you can only ever participate for one clan in CWL during a given season, I would say you should still get your rewards, however note that I have never participated in a CWL so I cant say this is true from experience.
Comment: To add onto this for future reference, I did receive my tokens. You are allowed to ALSO simultaneity be in "normal" wars while in CWL and jump around back and forth. Leaving or being kicked does not effect your earnings. Once CWL ends you get the respected rewards.


Connect washer drain lines to metal pipe

Question: How do I best connect my drain lines to make the rubber-pvc and pvc-metal transitions water tight?
I've got a washer and drawer washer combo with a drain line for each. There's no vent pipe to the roof and the drain in the wall is galvanized or something along those lines.
The pvc 'solution' I have at this point is just hand tight, so water can leak a little at the pvc-metal transition and gray drain line to pvc transition. The studor vent has helped tremendously in cutting down sewer smell, but the rest of the fitting probably still leaks some sewer gas.
In case the pics aren't shown, I have two gray, rubber, 3/4" diameter, corrugated washer drain lines pushed into a 3/4" x 1-1/2" slip pvc adaptor. Both of those adaptors are connected to a 3-way T PVC. A studor vent is attached via a vertical stand pipe of maybe 18" to the middle connection on the 3-way T. That 3-way is connected via a 45 degree connector over the metal drain pipe in the wall.
Answer: Washer drain lines are not supposed to have an "air and water tight" connection - they are specifically supposed to have an air gap, or loose fit into the top of a standpipe.
The (bottom of the) standpipe should have a trap, which appears to be missing or hidden. Evidently missing, given you report stink. The water in the trap is what seals out sewer gas.
Comment: Thanks, I'm pretty sure you are right about the missing trap. Since it also doesn't have a vent pipe, the studor vent is the next best thing I've done to allow it to vent air in without venting sewer gas out. Opening the wall and adding a trap is kind of my last resort. I'll rephrase as I'm more concerned now with water right at the pvc-metal and pvc-rubber transitions.
Comment: Put the trap on the outside of the wall, then, before you enter the trapless pipe in the wall. A studor is not a trap. Use a rubber coupling to make a proper metal to PVC connection to the pipe in the wall, and glue the PVC joints, while providing the drains with standpipes above the trap(s).
Comment: Thanks, I will do that. I don't know why I didn't think of a p-trap outside the wall.


Is there a way to get context inside getters?

Question: I'm using  flutter_localizations to internationalize my app. So i have this class
final Article article;
ArticleViewModel({required this.article});

String get name {
 return article.name;
}

String get isGood {
 return article.isGoods ? 'Goods' : 'Services';
}
}

Inside the isGood getter, i need to return "Goods" or "Services" translated depending on the language
but i don't have the context to call Applocalization.of(context)
I need a good approach to achieve this wihthout passing a BuildContext as parameter.
Answer: You can try my approach, I have used this way for many of my apps. My way is inject BuildContext to a singleton class with get_it, like this:
@singleton
class AppContext {
  final navigatorKey = GlobalKey<NavigatorState>();

  BuildContext get navigatorContext => navigatorKey.currentState!.context;
}

then at your first time your app run, put the injected navigatorKey to MaterialApp:
MaterialApp(
  navigatorKey: getIt<AppContext>().navigatorKey,
)

Then, you can get BuildContext after that everywhere with:
getIt<AppContext>().navigatorContext

Comment: Aw yes, I forgot @singleton is the part of https://pub.dev/packages/injectable, which is code generator for get_it. You can register by yourself like you say but if you too lazy like me, you can use injectable xD
Comment: Works fine! But where does the @singleton decorator comes from? I did withour it, and i had to register with ```getIt.registerSingleton(AppContext());```  inside the main before runApp();
Answer: You could pass a BuildContext to your ViewModel (like you did with article) and call Applocalization.of(context) inside your getter
Comment: I edited my post. I forgot to mention without passing BuildContext as a parameter.


Blog Engine 2.0 Error

Question: I AM getting an error while opening blogengine.net 2.0 in visual studio 2010 designer view.It is showing the master page error.
But while executing the page it is loading correctly.
Answer: You have a similar problem to this question.
This has to do with the fact that BlogEngine.net is setting the Master Page in the PreInit event of the page's base class (BlogBasePage). It does this based on the theme you have chosen. Because of that, at design time VS can't figure out what the master page is.
You could set a default master page file in the web.config <pages> directive, as in the answer to the question above. The master page file you use would be based on the theme you are using (/themes/yourtheme/site.master).
Comment: thank you patmortech.I made the changes in webconfig.i am able to view the pages correctly.
Answer: Maybe the master page is determined dynamically?
Try opening in code (rather than designer) and seeing what the MasterPageFile attribute of the @Page directive says.
Comment: thank You.the masterpagefile attribute was missing in the pages.

Blog Engine 2.0 Error


How to select a radio button by default in asp.net

Question: I have a radio button and I would like to default the first item as checked by default. How do I go about doing that? Below is my source code for the radio button.
<asp:RadioButtonList ID="radRiskLevel" runat="server" RepeatDirection="Horizontal">
     <asp:ListItem Value="High">High</asp:ListItem>
     <asp:ListItem Value="Mid">Mid</asp:ListItem>
     <asp:ListItem Value="Low">Low</asp:ListItem>
</asp:RadioButtonList>

Answer:
ASPX Markup

<asp:RadioButtonList ID="radRiskLevel" runat="server" RepeatDirection="Horizontal">
     <asp:ListItem Value="High" Selected="True">Select</asp:ListItem>
     <asp:ListItem Value="High">High</asp:ListItem>
     <asp:ListItem Value="Mid">Mid</asp:ListItem>
     <asp:ListItem Value="Low">Low</asp:ListItem>
</asp:RadioButtonList>

Answer:
Selecting default value via ASPX markup:

<asp:RadioButtonList ID="radRiskLevel" runat="server" RepeatDirection="Horizontal">
     <asp:ListItem Value="High" Selected="True">Select</asp:ListItem>
     <asp:ListItem Value="Mid">Mid</asp:ListItem>
     <asp:ListItem Value="Low">Low</asp:ListItem>
</asp:RadioButtonList>

Selecting default value via C# codebehind:

if (!IsPostBack) // prevent from selecting default value during postback
{
    if (radRiskLevel.SelectedIndex == -1) //-1 is the indication of none selected
    {
        radRiskLevel.SelectedIndex = 0; // the index of items in radiobutton in the list you want to select
        //radRiskLevel.Items.FindByText("Select").Selected = true;  //can also be selected by text, need to pass text name as parameter
        //radRiskLevel.Items.FindByValue("High").Selected = true;  //can also be selected by value, need to pass value name as parameter
    }
}


Too many active consumers for ActiveMQ queue

Question: My Spring app consumes ActiveMQ queue. There are two approaches possible. Initial part of ActiveMQ integration is the same for the both approaches:
<code>@Bean
public ConnectionFactory connectionFactory() {
    return new ActiveMQConnectionFactory();
}

@Bean
public Queue notificationQueue() {
    return resolveAvcQueueByJNDIName("java:comp/env/jms/name.not.important.queue");
}
</code>
Single thread approach:
<code>@Bean
public IntegrationFlow orderNotify() {
    return IntegrationFlows.from(Jms.inboundAdapter(connectionFactory()).destination(notificationQueue()),
            c -> c.poller(Pollers.fixedDelay(QUEUE_POLLING_INTERVAL_MS)
                                 .errorHandler(e -> logger.error("Can't handle incoming message", e))))
                           .handle(...).get();
}
</code>
But I want to consume messages using the several worker threads, so I refactored the code from Inbound adapter to Message driven channel adapter:
<code>@Bean
public IntegrationFlow orderNotify() {
    return IntegrationFlows.from(Jms.messageDriverChannelAdapter(connectionFactory()).configureListenerContainer(c -> {
                final DefaultMessageListenerContainer container = c.get();
                container.setMaxConcurrentConsumers(notifyThreadPoolSize);
            }).destination(notificationQueue()))
                           .handle(...).get();
}
</code>
The problem is that the app doesn't stop ActiveMQ's consumer when it being redeployed into Tomcat or being restarted for the second approach. It creates new consumer during it's startup. But all new messages are being routed to the old "dead" consumer so they're sat in the "Pending messages" section and never being dequeued.
What can be the problem here?
Answer: You have to stop Tomcat fully, I believe. Typically during redeploy for the application, the Spring container should be stopped and clear properly, but looks like that's not your case: there is something missed for the Tomcat redeploy hook. Therefore I suggest to stop it fully.
Another option is to forget external Tomcat and just migrate to Spring Boot with its ability to start embedded servlet container. This way there is not going to be any leaks after rebuilding and restarting application.
Comment: You definitely need to fully close an application context to let it to clean up all the processes it has started. Not sure what should be configured in the Tomcat to do that properly...
Comment: Thank you, I know that Tomcat's restart helps with the issue but this is not the option for me as well as the Spring Boot migration because I have to patch an existing project. I'm trying to find an option to reset the container or to close the consumer manually.


short list of recently changed pages in mediawiki

Question: I'm using mediawiki to run a wiki for my (relatively small <10 users) team and would like to know if its possible to get a short list of, say, the last 5 changed pages to appear in the side bar.  I know I can go to recent changes page, but my users are used to seeing a list of the most recent changed pages on every page.
Thanks
Comment: [example](http://www.mediawiki.org/wiki/Help:Recent_changes)
Comment: I can't get the transclude of the recent changes to work in the side bar. Nothing shows up.  Thanks for the tip regarding limiting the number of results returned
Comment: What do you mean in the sidebar? Like on http://www.mediawiki.org/wiki/MediaWiki:Sidebar? I don't imagine that can accept transcludes, I think it would be too intensive for the server.
Answer: I saw here that you got a hack to put wikitext into the sidebar: http://www.mwusers.com/forums/showthread.php?15842-Show-recent-changes-in-sidebar
Try transcluding the recent changes into a template, then putting that template in the sidebar.
Comment: Thanks for the link.  I could get it to work. I even tried the CustomNavBlock extension but that didn't work either as it seem to not want to render the RecentChanges page in the sidebar.
Comment: I think it might be blocked in code somewhere, maybe you could change it.


How to create a named object from an array?

Question: const field = ['name', 'address']

const data = field.map(item => {
  return {item: {mode: 'insensitive', sort: 'desc'}}
})

the variable data above is
[
 {
  item: {
   mode: 'insensitive',
   sort: 'desc'
  },
  item: {
   mode: 'insensitive',
   sort: 'desc'
  }
 }
]

I want the value to be
[
 {
  name: {
   mode: 'insensitive',
   sort: 'desc'
  },
  address: {
   mode: 'insensitive',
   sort: 'desc'
  }
 }
]

is that possible? or any method to do it better, thank's for your help
Comment: Does this answer your question? [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal)
Answer: You can achieve this by wrapping your item object around brackets []
const data = field.map(item => {
    return {[item]: {mode: 'insensitive', sort: 'desc'}}
})

Output:
[
  { name: { mode: 'insensitive', sort: 'desc' } },
  { address: { mode: 'insensitive', sort: 'desc' } }
]

You can alternatively also use arrow functions to make your code look cleaner, You can learn more about arrow functions here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
const field = ['name', 'address']
const data = field.map(item => ({[item]: {mode: 'insensitive', sort: 'desc'}}));
console.log(data)


How is the new 3DS different from the previous 3DS?

Question: I've got a 3DS XL released in 2012. I'd like to know how the "new" 3DS XL, released in 2014, is different so I can figure out if it is worth the upgrade.
Answer: The most notable changes from the 3DS XL to the New 3DS XL include:

"Super Stable 3D". A feature that makes use of the front IR camera to track your face to adapt the 3D image appropriately, which improves the 3D. Thanks to it, you won't have to worry about holding the device at the right angle as much as before.
The New 3DS XL is slightly larger than its predecessor and weighs slightly less.
Cartridge slot, stylus holder, and the power button have been moved to different locations.
The physical WiFi switch has been removed in favor of a software toggle.
The New 3DS has a faster processor and more RAM, which means some games can only run on the New one (list of exclusives). Some 3DS games benefit from the extra performance, such as better framerates (Hyrule Warriors) or faster loading times (Super Smash Bros. for 3DS). Aside from that, the improved specs greatly reduce the time it takes for the system to suspend a game.
2 new shoulder buttons (ZR & ZL) as well as a second analog stick (C stick), rendering the Circle Pad Pro accessory obsolete.
Has an NFC reader right below the lower screen.
Uses Micro-SD cards instead of regular SD cards. If you're not already using a Micro-SD card via an adapter, you'll have to buy a new SD card to increase the New 3DS' storage. Unlike with the older models, you'll have to use a screwdriver to insert/exchange SD cards in the New 3DS, due to the slot being next to the battery compartment, whose cover is secured by screws.
The AC adapter is not included in the package, so you'll need to keep your old AC adapter, or buy one separately.

One thing to keep in mind: The regular New 3DS also has colored face buttons (ABXY) which match the colors of the SNES controller, and supports replaceable faceplates. The New 3DS XL does not support faceplates, and the coloration is applied to the buttons' text instead of the buttons themselves, therefore being much less noticeable.
Comment: One addition to the last paragraph: The face buttons of the **New 3DS XL** do have coloration, though it's more subtle than the non-XL version. The text of each button's letter is colored rather than the "background" (the button itself).
Comment: Another game that only runs on the new 3ds is Binding of Isaac: Rebirth (although last i checked it was still buggy on the new one)


Mapping a class to multiple tables

Question: I have a class that can't be mapped to one explicit table. The table in which it is mapped depends on the context in which it is used. Basically it should work the same way as if I were trying to bind an IDictionary<string, int> to a table.
// this is a mapped entity, with a Guid Id, but it can't be mapped to one explicit table
public class NoTableClass : Entity<Guid>
{

}

// the table that this class gets its MyCollectionContext1 from depends on the HasMany mapping for that property
public class MappedClass1 : Entity<Guid>
{
    public IEnumerable<NoTableClass> MyCollectionContext1 { get; set; }
}

// the table that this class gets its MyCollectionContext2 from depends on the HasMany mapping for that property
public class MappedClass2 : Entity<Guid>
{
    public IEnumerable<NoTableClass> MyCollectionContext2 { get; set; }
}

// Mapping overrides

public void Override(AutoMapping<MappedClass1> mapping)
{
    mapping.HasMany(Reveal.Member<MappedClass1, IEnumerable<NoTableClass>>("MyCollectionContext1"))
        .Table("Table1")
        .Access.Field()
        .Cascade.AllDeleteOrphan();
}

public void Override(AutoMapping<MappedClass2> mapping)
{
    mapping.HasMany(Reveal.Member<MappedClass2, IEnumerable<NoTableClass>>("MyCollectionContext2"))
        .Table("Table2")
        .Access.Field()
        .Cascade.AllDeleteOrphan();
}

It seems like NHibernate ignores the .Table() mapping method when the collection has a custom class. I don't understand why a dictionary of simple types can be mapped this way, but a collection with a custom class can't.
Note: I have my reasons for not wanting to use inheritance/generics to solve this problem, and not wanting to have a concrete type for each table i'm mapping to. We have a working solution using generics, but it creates other problems down the line for us.
Answer: I think that what you are trying to do could be achieved with components:
public static void Override(AutoMapping<MappedClass1> mapping) {
    mapping.HasMany(Reveal.Member<MappedClass1, IEnumerable<NoTableClass>>("MyCollectionContext1"))
            .Component(c => {
                c.Map(x => x.Id);
                c.Map(x => x.Name);
            })
            .Table("Table1")
            .Cascade.AllDeleteOrphan();
}

public static void Override(AutoMapping<MappedClass2> mapping) {
    mapping.HasMany(Reveal.Member<MappedClass2, IEnumerable<NoTableClass>>("MyCollectionContext2"))
            .Component(c => {
                c.Map(x => x.Id);
                c.Map(x => x.Name);
            })
            .Table("Table2")
            .Cascade.AllDeleteOrphan();
}

Here is the code to play with: https://gist.github.com/4620069
Comment: That works perfectly, I've been searching for this solution for day, thanks you :) There is one issue. I don't see any way to map the primary key for `NoTableClass` so that it generates a new `Guid` with every insert. This is normally taken care of by extending `Entity` or in the class map by using `.Id()` The only thing I can do inside of `.Component()` is `c.Map(x => x.Id)` which will just insert an empty Guid. Once i resolve this I'll accept your answer.
Comment: If all you need is `Guid` id generation then you could generate it in `NoTableClass` contrsuctor: `thid.Id = Guid.NewGuid()`.
Comment: We really don't want to generate the guid in code, our entire system uses Guid's as the unique identifier, and it's generated by the database when inserted, and we don't want to have one case where we generate the id in code before inserting.
Comment: In that case you should create tables `Table1` and `Table2` manually and mark `Id` column as `identity`, so the database would generate it for you.
Comment: This is an enterprise scale application, we use Guid's and we cant change the database structure. This needs to be handled by nhibernate

Mapping a class to multiple tables


how can we create a Jira Ticket based on Card count more than 10 in published PBI dashboard

Question: I have card with count of table names, I need to create a jira ticket if card count goes beyond 10.
Comment: you need to add more information to get answer.
Answer: Getting into specifics is probably too much for this forum; however, as for general architecture, I think you may be able to use PBI Alerts and integrate them into a power automate flow that creates a JIRA ticket. The trickiest part will be the JIRA ticket creation which will probably require some kind of custom Azure App. The data driven power bi alert kicking off a power automate flow is a common pattern though so the first couple steps should be straightforward.
https://learn.microsoft.com/en-us/power-bi/collaborate-share/service-flow-integration


What is the null pointer optimization in Rust?

Question: In Learning Rust With Entirely Too Many Linked Lists, the author mentions:

However, if we have a special kind of enum:
enum Foo {
    A,
    B(ContainsANonNullPtr),
}

the null pointer optimization kicks in, which eliminates the space needed for the tag. If the variant is A, the whole enum is set to all 0's. Otherwise, the variant is B. This works because B can never be all 0's, since it contains a non-zero pointer.

I guess that the author is saying that (assuming A is 4 bits, and B is 4 bits)
let test = Foo::A

the memory layout is
0000 0000

but
let test = Foo::B

the memory layout is
some 8 bit non 0 value

What exactly is optimized here? Aren't both representation always 8 bits What does it mean when the author claims

It means &, &mut, Box, Rc, Arc, Vec, and several other important types in Rust have no overhead when put in an Option
Answer: The null pointer optimization basically means that if you have an enum with two variants, where one variant has no associated data, and the other variant has associated data where the bit pattern of all zeros isn't a valid value, then the enum itself will take exactly the same amount of space as that associated value, using the all zeroes bit pattern to indicate that it's the other variant.
In other words, this means that Option<&T> is exactly the same size as &T instead of requiring an extra word.
Comment: The compiler has built-in knowledge about the memory layout of various types. For example, it knows that `&`-references can never be null. It also knows that `String` and `Vec` can never be all zeroes; following this down into the implementation, `String` is backed by `Vec`, which is backed by `RawVec`, which is backed by `Unique`, which contains a `*const T` but has a compiler attribute that declares that it can't be null. Similarly there's a stdlib `NonNull` type that acts like a `*mut T` that can never be null.
Comment: To elaborate, empty strings and vectors don't point to null, they point to a fixed nonnull address with zero capacity. Same thing with other containers like HashMaps that can be cheaply created. The Rust stdlib tries very hard to avoid nulls in pointers specifically so the all-zeroes value can be reserved for things like the null pointer optimization.
Comment: I understand that. But how does the compiler know if all-zeros is an invalid value? I assume the optimization only kicks in for specific built-in types. If so, which ones?
Answer: enum is a tagged union. Without optimization it looks like
Foo::A;    // tag 0x00 data 0xXX
Foo::B(2); // tag 0x01 data 0x02

The null pointer optimization removes the separate tag field.
Foo::A;    // tag+data 0x00
Foo::B(2); // tag+data 0x02

Comment: The second example seems to be a little bit inaccurate, taking into account that `0x00` is a valid bit pattern for an integer, thus it's ambiguous meaning both `Foo::A` and `Foo::B(0)`.
Answer: I m also learning too many linked list, perhaps this code snippet can deepen your understanding
pub enum WithNullPtrOptimization{
    A,
    B(String),
}

pub enum WithoutNullPtrOptimization{
    A,
    B(u32),
}

fn main()  {
    println!("{} {}", std::mem::size_of::<WithNullPtrOptimization>(), std::mem::size_of::<String>()); // 24 24
    println!("{} {}", std::mem::size_of::<WithoutNullPtrOptimization>(), std::mem::size_of::<u32>()); // 8 4
}


Should a curtain drain be covered/back filled?

Question: I do some light maintenance and yard work in exchange for rent.
The building had some problems with flooding. We have an extensive drain system, but it was a bit clogged. Even after the plumbers unclogged the drain the owner of the property is having a sump pump plus a curtain drain installed.
We have had some dispute about covering/back filling the curtain drain. The contractor is against it. I don't want to insult the contractor or the owner of the property. As the contractor is a friend of the owners. The owner of the property is a very intelligent woman, and if a logical argument is made will likely reconsider. Should a proper curtain drain be covered/back filled or should we really leave a gravel trench in the middle of a yard? I have spent a little bit of time researching curtain drains, and most instructions indicate that the last step is to landscaping fabric, and few inches of soil and some grass. While this will certainly make mowing and autumn leaf removal a pain, I also generally care about the appearance of the property and this decision seems wrong.
the question: to cover/backfill with soil and plant grass or not to cover/backfill a curtain drain
Comment: I think the word you want is "covered" instead of "back-filled".  Back filling refers to the act of piling up dirt against a vertical substance like a foundation wall or retaining wall.
Answer: The usual purpose of a curtain drain is to divert (under)groundwater away from a structure. The only reason to not cover it with fabric and a few inches of soil is to capture surface drainage as well. If you need to capture surface drainage, then there must be a significant grading issue that is allowing surface water to stand near the structure.
Such a grading issue should be corrected, in which case the curtain drain could be covered. If for some reason it cannot be corrected, (or this is actually a gravel filled trench drain) then the gravel should be left exposed. It will also need to be maintained so that it does not get clogged with silt and other material carried in surface runoff.
In summary, the proper surface treatment depends on the intended purpose(s) of the drain.
Comment: 4" of rain an hour is gonna pool no matter what, for a little while at least.  If it takes 4" of rain to cause minor pooling then I'd go with covering it.  The fabric will keep dirt out of the gravel, protecting it from getting clogged.  With it exposed like it is, clogging with gunk is *more* likely than with a good fabric layer and 3-4" of top soil.
Comment: there is a small slope from the drive way, but the driveway itself has a small lip and drain. We have had a case this summer of the hard dry soil pooling water in an unusual downpour of 4+ inches in about an hour. So yes, we do have some surface pooling, but it seems improper to leave a gravel trench in the middle of a yard.
Comment: Thanks, that was the point I was trying to get across to the owner. I'm still working on her.


FAQ: A guide to moderation: Voting to close a question

Question: What does it mean to close a question? Who can do it? Why should you do it?
This is a very nice guide provided by Ninefingers on the Cryptography Meta Site. Following the example from other sites and reassured by his blessing, I'm going to post it here.
A note: if a new user asks for explanations about their question being closed, you can redirect them to this guide.
Return to FAQ index
Answer: Rationale: why do we close questions?
There are really two ways to do moderation. If you've been on any of the <code>.moderated</code> newsgroups you'll be well aware that to get a post on there, it needs to undergo a review process first and be accepted. The aim is to keep problem discussions from arising.
SE is slightly different - it works the other  way. Anyone can ask a question on SE and closing a question is the equivalent of putting that question back into review/improve mode. It's a feedback mechanism designed to react to problem cases only, so the usual business of asking and answering good questions can just... happen.
Why do we close a question?
The philosophy of SE is that each site handles questions on problems you face or things you are trying to understand. The don't ask section of the FAQ gives you a good overview of things that don't work - to summarise:

Some questions invite arguments or extended debate that suck up time when members could be helping other people.
Some questions are too broad, too narrow or have other content problems.
Some questions belong elsewhere.

These have been worked out over time and with a lot of experience from Stack Overflow and are, broadly speaking true. Sometimes, exceptions are made - it is always a case-by-case thing.
Is closing like deletion?
No. Actually, deletion is a different concept on SE. Closed questions are put "into improve mode" if you like, and are still visible for anyone to improve. That's the idea. Deleted questions are different - they have a red background and are invisible to all but high reputation users. So deletion is different and solves a slightly different problem.
What are the requirements for closing a question?
If you have 500 reputation on the site currently, or 3000 reputation on a graduated site, you can vote to close any question for the reasons above. More on that in a moment.
If you do not have this level of reputation, you will find that under the flag menu, you have an option "this question does not belong here". That will raise a flag for users who can vote to close.
Why can anyone vote to close/reopen?
Firstly, anyone can vote to close or reopen (or flag as such) because it is your site. This is really important - it's about expressing what you feel works and doesn't.
How are moderators different?
Moderator close votes complete the required vote count immediately, no matter how many people have voted. This applies for both close/reopen votes.
Initially, as the reputation requirement rules out many users, you will see moderators doing most of the closing to guide the site and look after the content. As you gain in reputation, you get to join in.
Ok, so how does it work?

Ok, the important piece. Voting to close works like this:

Underneath the question, there will be a close link. When you click on this, you will be presented with a list of options from which you can pick a close reason most appropriate to the situation.

If other people have voted, you will see blue numbers against the reason they chose.

The exact duplicate page takes you to a page that allows you to specify a question to close as an exact duplicate against.
The "off topic" page will present you with two options - one to migrate here, to meta, and one just off topic. On SE betas, only moderators can send questions elsewhere, so feel free to cast a vote here and flag if you have a target in mind.
The other options are straight out closes.
Once you pick your option and click "close", your vote is registered. You cannot retract it at this stage, but nobody else, including moderators, will know it was you who voted.
If five people agree, the question will be closed. You've seen the effect of these before.
Your name, and the name of other closers, will appear on the bottom of the question.

How does vote to re-open work?
A closed question has a "reopen" link underneath it. If you click this, a dialog box will ask you if you are sure - click yes and your vote will be registered to re-open the question.
Below, you can see an example of the re-open link with two votes registered for re-opening (out of five).

What happens if I make a mistake?
Don't worry! Unless five people agree, or a moderator agrees, the question won't be closed.
I've seen a closed question and I disagree. What can I do?
Well, one option is to use your re-open vote! You can also always raise a discussion here on meta to seek clarification on why a question is closed and hopefully either a resolution will be reached, or you will get an explanation for the closure.
My name appears on the bottom - isn't this going to cause problems with other users?
Actually, surprisingly few closed questions generate any response at all.
However, if you experience difficulties as a result of closing a question, you can and should contact a moderator via the flag mechanism (which is anonymous). We can then take any necessary action.
How do I find questions I might need to close? What about re-opens?
Actually there are two tools for this.

Review. Here, there are a number of options for seeing things that might need say editing. One of these is a tab for all questions with close votes. You are then free to look at the question and decide if you agree.
Tools. Commonly referred to as the "10k tools", this page let's you see even more information - certain anonymous flags, re-open votes, delete votes etc. The important one for this is the re-open page. Here, you can see questions that might have been closed incorrectly.


syntax error in conditional expression with bash script

Question: I am running the below script :
status="UNKNOWN"
while [[ "$status" != "OUTPUT"]]; do
    echo "Checking
    status of job $jobid" status=$(zowe zos-jobs view job-status-by-jobid "$jobid" --rff status --rft string)
    echo "Current status is $status"
    sleep 5s
done;

all the time I am getting errors like :
  syntax error in conditional expression: unexpected token `;'
I tried allot of combinations to solve this issue but every time I am getting different error .
PS : I am running on  PowerShell of windows
Comment: Add a space before the closing `]]` (and maybe after).
Answer: When I am writing bash scripts I use shellcheck to check, if there are any syntax errors etc. You can either install it via apt-get install shellcheck or you use the shellcheck website.
I pasted your script there and it gives following output:
Line 2:
while [[ "$status" != "OUTPUT"]]; do
^-- SC1009: The mentioned syntax error was in this while loop.
      ^-- SC1073: Couldn't parse this test expression. Fix to allow more checks.
                                ^-- SC1020: You need a space before the ]].
                                ^-- SC1072: Missing space before ]. Fix any mentioned problems and try again.

Try to fix the mentioned stuff from the output.
Comment: Thank you , I resolved this :status="UNKNOWN"
while [ "$status" != "OUTPUT" ]; do
 echo "Checking status of job $jobid"
 status=$(zowe zos-jobs view job-status-by-jobid "$jobid" --rff status --rft string)
 echo "Current status is $status"
 sleep 10s
done


reordering alphanumeric age group in R

Question: assume this is what R gives me.
df1 = data.frame(grp = c("<2", "2-5", "21-26","27-32","6-10"), val= rep(0,5))
     grp val
1    <2   0
2   2-5   0
3 21-26   0
4 27-32   0
5  6-10   0

but I want R to understand 6 < 21 and to give:
df2 = data.frame(grp = as.factor(c("<2", "2-5", "6-10", "21-26", "27-32")), val= rep(0,5))
    grp val
1    <2   0
2   2-5   0
3  6-10   0
4 21-26   0
5 27-32   0

I tried mixedsort() from gtools but it returns indices instead of a reordered dataframe.
any tips or idea how to get to this?
edit. Thanks to wonderful @akrun, I realized I must first assign his dplyr suggested answer to another object , say new_df and then pipe new_df to the rest of my code.
Answer: you can explicit the desired levels (and force rank order) also with base R:
grp <- factor(c("<2", "2-5", "6-10", "21-26", "27-32"),
       levels = c("<2", "2-5", "6-10", "21-26", "27-32"),
       ordered = TRUE
       )

note the use of factor not as.factor in this case
Answer: It can be easily done with parse_number to reorder the rows with arrange
library(dplyr)
df1 %>%
   arrange(readr::parse_number(grp))

-output
    grp val
1    <2   0
2   2-5   0
3  6-10   0
4 21-26   0
5 27-32   0

Or using base R
df1[do.call(order, read.csv(text = gsub("<", "-Inf,",
    chartr("-", ",", df1$grp)), header = FALSE)),]
    grp val
1    <2   0
2   2-5   0
5  6-10   0
3 21-26   0
4 27-32   0

Comment: @Mathica Can you show the `unique(df1$grp)` values
Comment: @Mathica Have you assigned the output back to another object or same object i.e. `df2 <- df1 %>%
   arrange(readr::parse_number(grp))`
Comment: thank you for the dplyr suggestion. so my actual dataframe is very similar to my small example just more rows and columns. both are dataframes, grp colum returns character when taking str(). but I do not know why your cool suggestion works for this one and not for my actual dataframe. any idea what to check for?
Comment: it is "<2"  "2-6"  "21-27"  "28-35" "36-50" "7-20" "51+"
Comment: Okay, there is `+` at the end that could be the issue
Comment: @Mathica I tried with `df2 = data.frame(grp = c("<2", "2-5", "21-27","28-35","36-50", "51+", "6-10"), val= rep(0,7));df2 %>% arrange(readr::parse_number(grp)) %>% pull(grp)#
[1] "<2"    "2-5"   "6-10"  "21-27" "28-35" "36-50" "51+"`  it seems to be working fine
Answer: Not sure if this is exactly what you're looking for, but if you have a raw set of numbers you're creating a dataframe from, you can also just use cut() to create an ordered factor that aggregates your data and then table() to count frequencies within each cut range.
set.seed(100)
observations <- rnorm(20, 5, 5)
cut(observations, c(0, 2, 9, 10), include.lowest = T) |>
  table() |>
  data.frame()

#     Var1 Freq
# 1  [0,2]    2
# 2  (2,9]   16
# 3 (9,10]    1

reordering alphanumeric age group in R


Bitwise shift returns unexpected value in Python

Question: I'm performing 55 << 30 in C# and Python 3. C# returns -1073741824, which is what I want, but Python returns 59055800320. Can someone explain why exactly this happens, and what I can do to fix it?
Answer: python ints are arbitrarily large ... you can force it sort of
import numpy

numpy.int32(55) << 30

Answer: Python integers are unbounded, so 59055800320 is the correct answer, but to simulate C#'s 32-bit limitation on integers and 2s complement negative numbers, you can do the math:
>>> hex(55)
'0x37'
>>> hex(55 << 30)  # 36-bit result, too large for 32-bit integers
'0xdc0000000'
>>> hex(55 << 30 & 0xffffffff) # mask off lower 32 bits.
'0xc0000000'
>>> ((55 << 30) & 0xffffffff)  # but the sign (bit 31) is a one, so it should be negative
3221225472

Bit 31 in a 32-bit signed integer has value -231, but unsigned it has value 231, meaning the value is 232 too high, so:
>>> ((55 << 30) & 0xffffffff) - (1<<32)
-1073741824

Here's a function:
def signed_32bit_shift_left(n,s):
    tmp = (n << s) & 0xffffffff
    return tmp - (1<<32) if tmp & 0x80000000 else tmp

Answer: As the others have said, Python ints are much larger than you might expect.  To observe this (Python 3.7.4):
>>> import sys
>>> type(55)
<class 'int'>
>>> sys.getsizeof(int())
24

sys.getsizeof() will return the size, in bytes, of an object in memory.


Given 3 random points, what is the probability of these two situations involving a perpendicular bisector and distances?

Question: Suppose we're given 3 random points $p_0=(x_0,y_0),p_1=(x_1,y_1),p_2=(x_2,y_2)$ from a two-dimensional continuous uniform distribution $\{U(a,b)\}^2$, for some $(a\in\mathbb{R})\lt (b\in\mathbb{R})$, and it is known that $y_0\lt y_1\lt y_2$.
Also, let $B(x):\mathbb{R}\rightarrow\mathbb{R}$ be the function which graphs the perpendicular bisector of $p_0$ and $p_1$, such that $(x,B(x))$ intercepts the perpendicular bisector.
Finally, let $p_b=(x_2,B(x_2))$, let $d_1=dist(p_1,p_b)$, and let $d_2=dist(p_2,p_b)$, where $dist(\alpha,\beta):\mathbb{R^2,R^2}\rightarrow\mathbb{R}$ is the Euclidean distance between the points $\alpha$ and $\beta$.

Assuming $x_2\lt x_1$, what is the probability that $d_2\lt d_1$?
Assuming $x_2\gt x_1$, what is the probability that $d_2\gt d_1$?

As a side note, in case anyone can point me to a source which may have information related to what I'm looking for, these questions are part of my attempting to do some analysis and optimization of Fortune's algorithm, which used to generate Voronoi diagrams, given a set of points.
Comment: Got something for you: the region in which $d_2 > d_1$ is the area contained outside the lobes of a right hyperbola with asymptotes that pass through the midpoint of $p_1p_2$ and bisect the angle that $p_1p_2$ make with vertical lines.
Comment: @DanUznanski This implies that the region in which $d_2\lt d_1$ is the area contained **inside** the lobes of the same hyperbola. And since it is given that $y_0\lt y_1\lt y_2$, $p_2$ therefore cannot be in the bottom lobe.
Answer: First, let's find the perpendicular bisector of the line $p_0p_1$.
We'll call the midpoint of $p_0p_1$ $M$, and its slope $s$.  Also, $s'$ will be the slope of the bisector, $s' = -1/s$.
$$y = s'(x - M_x) + M_y = -\frac{x - M_x}{s} + M_y$$
Now, let's find the location of a $p_2$ that happens to be exactly the same distance from $p_b$ as $p_1$ is (it'll also be the same distance as $p_0$, since $p_b$ is on the bisector).
$$y_2 = y_b - \sqrt{(y_b - y_1)^2+(x_b-x_1)^2}$$
But $y_b$ is on the line, so we can find its location based on $x_b$, and actually $x_b = x_2$, so
$$y_2 = s'(x_2-M_x)+M_y - \sqrt{(s'(x_2-M_x)+M_y - y_1)^2+(x_2-x_1)^2}$$
Everything below this has $d_2 > d_1$.
From here you'll have to integrate to find the probabilities you need.  I'm not entirely sure if that is nicely integrable though.
Comment: Also, this is complicated by the fact that $p_2$ must be inside $[a,b]^2$, yet the function for $y_2$ can possibly extend beyond $[a,b]^2$, as seen here: http://imgur.com/u3qsUvt


Using Old Paint on Inside Wall

Question: If I used old expired paint 2 or 3 years ago on an inside bedroom wall, could it be causing health issues to a child if the smell still comes and goes in the warmer weather ?
Comment: Paint doesn't "expire" (as in there's no "Best If Used By" date).  Whether or not the paint was good to use was before it was used (ie. did the colour mix well?, was there a rancid odor?, were there solids in the bottom of the can after mixing?, was there no odor at all when the can was opened? did the paint experience a freeze-thaw cycle?).
Comment: Latex or oil (alkyd)?
Answer: Unless your paint is pre-1985, you really don't have to worry about lead.
Paint doesn't expire but it can go bad.
It's totally OK to use your high-VOC paint.  You're just not allowed to sell it at retail, or sneak it in to bypass local environmental regs.  Trying to educate 70 million people in the 12-state areas is a lost cause, so the (US and state) government's approach is to ensure that any product you buy in a local store is legal. As far as products you already bought, they're not worried about it.
So if this is "new old stock" sitting on your shelf, for God's sake, paint it before it goes bad.  The second best way to dispose of old paint is to paint something you don't want, then throw that thing away.  The worst possible way is throw it in a landfill, it'll leach chemicals for years.   Let paint do its job.  It's designed for that.
That said...
One curse of low-VOC paint is it's vulnerable to mold and mildew, in the can.  If you open a can of normally mild-smelling latex paint, and it's Stinky, that's what has gone wrong.  Do not paint stinky latex paint on anything (except for the "paint something you don't want and throw it away" rule).  Believe me, you'll want to throw it away!
I have no idea how toxic it is, except for what it is - mold and mildew, which, yes, is not good for humans to be around.
There are lot of answers for how to encapsulate it, but none of the answers have reported particularly good results in the long term. Having forcibly removed much worse paint, I'd remove it.  Latex is pretty flimsy stuff, and it'll practically fall off the wall with enough persuasion, i.e. wetting and firm nylon brushes.  The goal being not to damage the substrate so you don't have to drywall rework.
Answer: Paint doesn't expire, it just loses moisture until it's unusable.  There's nothing wrong with "old " paint, unless it's so old that it has additional VOC's or in the worse case lead.  3 year old paint should be fine if it's not dried out.

Using Old Paint on Inside Wall


3D array of numbers output as 2D isometric image

Question: I have a 3D array of numbers from 0 to 9 to represent objects in a space, where
0 - empty space,
1 - space boundary,
2 - item 1,
3 - item 2,
...
Is it possible to assign colours to each number and output these as part of a 2D isometric view (viewed from a certain angle) of a 3D objects? (with 0 being transparent)
I would like a 3D representation of the object i have described.
I understand there is a concept for RGB colours but that only serves to populate the array with 3 colours, which means i have to break down my array further?
sorry i am very new to CS in general with a background in mechanical engineering so i am trying to learn.
Comment: i have found that 3D scatter plot on Excel does the job quite well though it is essentially on a 2D plane.
Comment: http://www.doka.ch/Excel3Dscatterplot.htm
Answer: The simplest way would be to use a plotting library like matplotlib. You will only be able to draw simple shapes but that is enough for the problem you have.
See this question for an example of how you can plot a 3d array.
Matplotlib is a python library, if you are using a different language I'm sure it has a similar library available.


What are the different endings in Revolution 60 and how are they achieved?

Question: The game mentions different endings based on your performance and choices. What are the endings and how do you get them?
Answer: I'm Brianna Wu, the developer of this game. There are 24 ending permutations.
First variable: Professional or Rogue
Second variable: Align with Minuete, Amelia or Neutral
Third Variable: Does a major character live or die?
Fourth Variable: Proficiency Pass or Fail. It's set at different levels depending on difficulty.
I won't spoil the endings, but I will say there's no one good ending. Either you fail your mission, or you partially succeed. There are no perfect resolutions in this universe.
I'd also say, as the creator, the ending I consider best is R M L P. I think P A L P is the most interesting opening in R62 though.


How to retrieve a window from a dead/disabled monitor?

Question: Background:
I'm using a Ubuntu 12.10 Live CD (USB) in order to resize some partitions on my laptop.
My laptop is connected to an additional monitor which I have set as a separate screen.
I started the partition process and went to get a snack while I waited for the tasks to finish.
The problem:
When I came back from getting my snack I found that my computer's monitor had been disabled. I shook the mouse expecting it to wake up, however, only my external monitor came to life.
GParted was hidden behind the disabled monitor, and when I attempted to open the displays tab, it too opened inside of the disabled screen.
I opened the console by pressing alt + f6 and attempted to use xrandr commands only to be met with error messages reading "Can't open display".
I did not want to restart as my partition task was still running in the background and disabling it could potentially endanger the data I was transferring.
Comment: I found the solution by opening the workspace switcher and clicking and dragging the windows inside of it. I would self-answer my own question but apparently I need to wait seven hours before I can do so as I am a new account.
Answer: The Solution:
By chance I found a solution to my problem. I was trying to move the windows from one monitor to the next by blindly fishing for them in the
other window and dragging them back while holding alt. In order to get an idea of the window's position I opened the Workspace Switcher.
One of the times that I opened the Workspace Switcher I inadvertently found that you can click and drag to reorganize windows while still inside the workspace overview screen.
This handy little feature that I didn't know about helped me immensely tonight.
I'm posting the solution to my own problem in case someone else happens to follow in my footsteps.
Note:
When I was finally able to retrieve the display window from the other screen I set my monitors to mirror in hopes that it would fix the problem.
It did not.
However, when I opened the console by pressing alt + f6 (in order to double check the error message that I received while trying xrandr) and
returned to my desktop with alt + f7, my monitor came back to life.
Changing it back to "extend" instead of "mirror" mode has not caused the error to reoccur.
I have not noticed any error messages or warnings.


Python histogram bins

Question: I have this histogram:
    hist
(array([49, 33, 21, 11, 10,  9,  0,  0,  0,  2]), array([ 0.        ,  0.26274885,  0.52549769,  0.78824654,  1.05099538,
        1.31374423,  1.57649308,  1.83924192,  2.10199077,  2.36473962,
        2.62748846]))

which has 10 bins and the number of counts in each bin. I would like to extract the first array, i.e the number counts in each bin (array([49, 33, 21, 11, 10,  9,  0,  0,  0,  2]) to use for another calculation.
Is this possible?
Comment: Please make an answer for this. Hilarious!
Comment: @srivatsan - added as an answer so that you may upvote. And may I suggest that you go through the official tutorial @ http://docs.python.org/2.7/tutorial/
Answer: use hist[0]
Read more in the official tutorial
http://docs.python.org/2.7/tutorial/introduction.html#lists
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on:
>>> a = ['spam', 'eggs', 100, 1234]
>>>
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']

Python histogram bins


Keep logged in jQuery Mobile

Question: I'm developing my first mobile application using jquery mobile and phoneGap to build my application on the different operating system for mobile and i'm blocked on how to keep the users logged in once they enter their information of authentication the first time
Can you share with me your propositions i read some subject on how to keep logged in by using cookies for the browsers and now i need a solution for mobile application
thank you in advance friends
Answer: localStorage allows permanent storage,
window.localStorage.key = value;
To get the value, Use this;
var value = window.localStorage.key;

sessionStorage allows storage in the session.
window.sessionStorage.key=value;
To get the value, Use this;
var value = window.sessionStorge.key;

See the Link
OR use the Local Data Base to store the data at client side.
var dbShell = window.openDatabase(name, version, display_name, size);

in Device Ready Function create the data base
var db = window.openDatabase("test", "1.0", "Test DB", 1000000);

function populateDB(tx) {
     tx.executeSql('DROP TABLE IF EXISTS DEMO');
     tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}

function errorCB(err) {
    alert("Error processing SQL: "+err.code);
}

function successCB() {
    alert("success!");
}

db.transaction(populateDB, errorCB, successCB);

PhoneGap Documentation
Refer These Links for More Info
IndexDB
HTML5 Storage
Comment: thank you and how can i read this informations from the localStorage later.when the user try to connect to my application an other time ??
Comment: use var userName = window.localStorage.name you will get the user name

Keep logged in jQuery Mobile


Find the limit of $a_n$ = sin($n$)sin($1/n$) from real analysis point of view

Question: Find the limit of the following sequence:
$a_n$ = sin($n$)·sin($1/n$)
I know that by limit theorems, lim(sin($n$)·sin($1/n$)) = lim(sin($n$)) ·lim(sin($1/n$)
Obviously, lim sin(n) = undefined & lim sin(1/n) = 0
How do I  find this limit from real analysis standpoint?
Comment: $\lim \sin(n)$ may be undefined, but $\sin(n)$ is nicely bounded.
Comment: Try to prove: sequence converging to zero time a bounded sequence converges to zero.
Comment: That is helpful because I do know how to prove that. since we would know that there exists $M$ > 0 such that |$b_n$|< M for all n... I have proven this on another homework problem. Now I just need to figure out how to find lim sin(1/n)
Answer: I am not sure that I am not missing aprt of the question.
When $n$ is large $\sin \left(\frac{1}{n}\right)$ is close to $\frac{1}{n}$, so $\sin \left(\frac{1}{n}\right) \sin (n)$ behaves as $\frac{\sin (n)}{n}$ and $-1 < \sin (n) <1$. So, $a_n$ is bounded by the two curves given by $-\frac{1}{n}$ and $\frac{1}{n}$. So, if $n$ goes to infinity, $a_n$ goes to zero by positive or negative values.
Answer: Hint:  $-1 \le \sin(n) \le 1$.
Answer: /a(n)/ < /sin(1/n)/ --> 0. Use squeeze theorem to get lim = 0
Comment: I'm not sure what to put as the right hand side of the inequality so I can find a limit
Comment: would this work?

$a_n$ < sin(1/n) < sin(1/n) / (1/n) < 1/n    ??
Comment: sin(1/n) < 1/n works fine.


How to add n hours in java

Question: I have n no of times.
ex:-
01:00:06

02:30:00

05:00:09

01:59:06

10:15:06

I want to add all this times. Finally calculate how may hours, min and seconds.
Please let me an idea to solve this.
I ma trying to do this using Calendar.
Updated:-
private void test() {

        String[] dates = { "01:00:06", "02:30:00", "05:00:09", "01:59:06",
                "10:15:06" };

        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        long totalHours;

        for (int i = 0; i < dates.length; i++) {

            calendar.setTime(ConstantFunction.StringToDate("HH:mm:ss",
                    dates[i]));
            int hours = calendar.get(Calendar.HOUR_OF_DAY);
            int minutes = calendar.get(Calendar.MINUTE);
            int seconds = calendar.get(Calendar.SECOND);

            if (i == 0) {
                calendar1.add(Calendar.HOUR_OF_DAY, hours);
                calendar1.add(Calendar.MINUTE, minutes);
                calendar1.add(Calendar.SECOND, seconds);
            } else {
                calendar2.add(Calendar.HOUR_OF_DAY, hours);
                calendar2.add(Calendar.MINUTE, minutes);
                calendar2.add(Calendar.SECOND, seconds);
            }
        }
        long diffInMilis = calendar2.getTimeInMillis()
                - calendar1.getTimeInMillis();

        long diffInSecond = diffInMilis / 1000;
        long diffInMinute = diffInMilis / (60 * 1000)% 60;
        long diffInHour = diffInMilis / (60 * 60 * 1000);
        System.out.println("diffInSecond==> " + diffInSecond);
        System.out.println("diffInMinute==> " + diffInMinute);
        System.out.println("diffInHour==> " + diffInHour);
    }

I am do like this. But here I am getting wrong output.
diffInSecond==> 67455
diffInMinute==> 44
diffInHour==> 18

Comment: Please go through the documentation: http://developer.android.com/intl/es/reference/java/util/Calendar.html
Comment: I would recommend you to use [JodaTime](http://www.joda.org/joda-time/)
Comment: In java there is no native method available?
Comment: why dont you `trim` string and simply add them..
Answer: Finally I conclude with this solution. But I don't know this is a correct way to do this. Bu I got expected OP.
private void test() {

        String[] dates = { "01:00:06", "02:30:00", "05:00:09", "01:59:06",
                "10:15:06" };
        long totalSecs=0;
        for(int i=0;i<dates.length;i++){
            totalSecs+=GetSeconds(dates[i]);
        }

        long hours = totalSecs / 3600;
        long minutes = (totalSecs % 3600) / 60;
        long seconds = totalSecs % 60;

        System.out.println("hours==> " + hours);
        System.out.println("minutes==> " + minutes);
        System.out.println("seconds==> " + seconds);

    }

    private long GetSeconds(String time){
        String[] parts = time.split(":");
        long totSec=0;
        int hour=Integer.parseInt(parts[0]);
        int min=Integer.parseInt(parts[1]);
        int sec=Integer.parseInt(parts[2]);

        totSec=(hour*3600)+(min*60)+sec;

        return totSec;
    }

How to add n hours in java


"cd /ect/mysql/" gives error "-bash: cd /ect/mysql : No such file or directory" when it exists

Question: I recently started an EC2 AWS Linux server instance with Ubuntu 14.04. I am very new to ubuntu and launching websites on servers, but here is (in short) what I have done so far.
I successfully installed LAMP server and I am able to access the webpage and its phpMyAdmin through pasting the instance's URL in Chrome.
I successfully edited the index.html file using nano that is located in /var/www/html and the website changes accordingly.
I successfully created a database in phpMyAdmin and I now wish to access it using php and mysql.
Upon connecting the database using the mysqli_connect function the connection fails.
I read that in order to connect the database to an external server one must edit the my.cnf file here: https://mariolurig.com/coding/connect-remotely-mysql-database-amazon-ec2-server/
I am having trouble to access the file.
I used locate my.cnf and tried to use cd to access it as follows:
ubuntu@ip-172-31-18-130:/usr/local$ locate my.cnf
/etc/mysql/my.cnf
ubuntu@ip-172-31-18-130:/usr/local$ cd /ect/mysql
-bash: cd: /ect/mysql: No such file or directory

I read about how a 32-bit binary can't run on a 62-bit system here: No such file or directory? But the file exists!
So I entered the command
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0

It seemed to install just fine, the only odd thing I noticed is that the installation ends with the line:
Processing triggers for libc-bin (2.19-0ubuntu6.14) ...
and I can type commands on my terminal again. I tried entering cd /ect/mysql/ again, but I am met with the same error.
I noticed while searching through my file directories the error happens whenever I try to access the /ect directory, for example, the following happens:
ubuntu@ip-172-31-18-130:/usr/local$ l
bin/  etc/  games/  include/  lib/  man@  sbin/  share/  src/
ubuntu@ip-172-31-18-130:/usr/local$ cd /usr/local/ect
-bash: cd: /usr/local/ect: No such file or directory

Does anyone know why this is happening and how I can fix it? I have been struggling with it for long and the similar questions' solutions I find doesn't seem to work. Any help would be greatly appreciated
edit:
As requested I checked the directory permissions where /etc is and got the following:
ubuntu@ip-172-31-18-130:~$ cd /usr/local
ubuntu@ip-172-31-18-130:/usr/local$ l -l
total 32
drwxr-xr-x 2 root root 4096 Sep 13 15:29 bin/
drwxr-xr-x 2 root root 4096 Sep 13 15:29 etc/
drwxr-xr-x 2 root root 4096 Sep 13 15:29 games/
drwxr-xr-x 2 root root 4096 Sep 13 15:29 include/
drwxr-xr-x 4 root root 4096 Sep 13 15:31 lib/
lrwxrwxrwx 1 root root    9 Sep 13 15:29 man -> share/man/
drwxr-xr-x 2 root root 4096 Sep 13 15:29 sbin/
drwxr-xr-x 7 root root 4096 Oct 27 11:58 share/
drwxr-xr-x 2 root root 4096 Sep 13 15:29 src/

Comment: `cd /usr/local/etc` I guess you're giving wrong spelling `ect` instead of `etc`
Comment: Check permissions on `/etc`. The `cd`  command is bash's built-in command and if bash works cd works as well,  so it has nothing to do with 32 bit libraries and you didn't have to install those.
Comment: @SergiyKolodyazhnyy Thank you for the suggestion, I will check it and add it to the question.
Comment: You wrote: `cd /ect/mysql`. It's `etc` (from *et caetera*), not `ect`.
Comment: @ AlexP & @BarathVutukuri Thank you, that solved my problem. Thank you for pointing out my silly mistake
Answer: It turns out I made a spelling mistake when trying to access the my.cnf file. I retyped the directory and the following happened:
ubuntu@ip-172-31-18-130:/var$ cd /etc/mysql
ubuntu@ip-172-31-18-130:/etc/mysql$

I got in with no problem. Thank you so much for pointing out my silly mistake.


How to match the data with new line.?

Question: I tried to match the data with newline and some other data but its not working.
My perl code
open(data,"filename");
@file = <data>;
@get = grep{m/^\>.*\n.*/} @file;
print "$get[1]";

My file like this
>1AA7
LSLLSEVESFVLSVVPSGPLKAEVAQKLEEVFAGKQSELEVLLEFLKSKPVLSPLSKGVLGFVFSLSVPSEKGLQKKKFVQQALQGQGEPQQLEKAVKLFK

>1ABV
SEFVSVAKPFAKAAFEFAVEKQSVEKFQELLAFAAEVSKQEQLAELLSGALAPESLAESFVAVCGEQLEEQGQQLVKVLAEQGKLQALPEVLEQFVKLKAVSEASAEVEVVSAAALSEQQLAKVSAALEKKLSK

>1AEP
AAGKVQVAEAVQQLQKSVVQAAKELKESLGLPSPEEALQLLSEQAQAFKSKVAEVSSSLKQEAEKKQGSVAEQLQAFAKQLQQSVKEAASSLQLQEQLQSLQSALSQVGKQFQEVASKSQASAQEAFAPVQSALQEAAEKSKEAAAQLQQSVQSAVQKPAQ

In this program gives the output only >1ABV not working the \n and another charactor in my code. But I expect the output from this code
>1ABV
SEFVSVAKPFAKAAFEFAVEKQSVEKFQELLAFAAEVSKQEQLAELLSGALAPESLAESFVAVCGEQLEEQGQQLVKVLAEQGKLQALPEVLEQFVKLKAVSEASAEVEVVSAAALSEQQLAKVSAALEKKLSK

Answer: It looks like you want paragraph mode for reading.
You can obtain that by modifying the $INPUT_RECORD_SEPARATOR:
use strict;
use warnings;

local $/ = '';  # Paragraph mode

my @data = <DATA>;

print $data[0];

__DATA__
>1AA7
LSLLSEVESFVLSVVPSGPLKAEVAQKLEEVFAGKQSELEVLLEFLKSKPVLSPLSKGVLGFVFSLSVPSEKGLQKKKFVQQALQGQGEPQQLEKAVKLFK

>1ABV
SEFVSVAKPFAKAAFEFAVEKQSVEKFQELLAFAAEVSKQEQLAELLSGALAPESLAESFVAVCGEQLEEQGQQLVKVLAEQGKLQALPEVLEQFVKLKAVSEASAEVEVVSAAALSEQQLAKVSAALEKKLSK

>1AEP
AAGKVQVAEAVQQLQKSVVQAAKELKESLGLPSPEEALQLLSEQAQAFKSKVAEVSSSLKQEAEKKQGSVAEQLQAFAKQLQQSVKEAASSLQLQEQLQSLQSALSQVGKQFQEVASKSQASAQEAFAPVQSALQEAAEKSKEAAAQLQQSVQSAVQKPA

Outputs:
>1AA7
LSLLSEVESFVLSVVPSGPLKAEVAQKLEEVFAGKQSELEVLLEFLKSKPVLSPLSKGVLGFVFSLSVPSEKGLQKKKFVQQALQGQGEPQQLEKAVKLFK

Live Demo
Note: array indexes start from 0 in Perl.
Comment: @Hussain: your regex is not your problem; your problem is that you only use the regex on one line at a time.  Use paragraph mode and continue to use your regex.
Comment: @Miler: Thank you. please explain this code `local $/ = '';`
Comment: Read the [linked to docs](http://perldoc.perl.org/perlvar.html#%24INPUT_RECORD_SEPARATOR).  The first paragraph explains.
Comment: @Miller: It is not possible using regular expersion.
Comment: @ysth: Thank you. I get a idea about it :)
Answer: If you want to read content separated by multiple newlines into an array,
use strict;
use warnings;
use autodie;

my @get = do {
  open(my $data, "<", "filename");
  local $/ = "";
  <$data>;
};

From perldoc perlvar

$/
[...] Setting to "" will treat two or more consecutive empty lines as a single empty line.

How to match the data with new line.?


Javascript using regular expression to get date in middle of object

Question: I have this object "FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020" and need to extract the FROM_DATE value 2/9/2020. I am trying to use replace, to replace everything before and after the from date with an empty string, but I'm not sure how to get both sides of the value.
at the moment I can remove everything up until the date value with this... /.*FROM_DATE":"/ but how can I now remove the final part of the object?
Thanks
Comment: `var x = JSON.parse("{" + your_string + "}").FROM_DATE` is one way to get that and the other values, begs the question of your input is a json string in the first place?
Comment: Do you mean an Object or a String?
Comment: apologies, it is a string in this case/
Answer: If you need to make it with replace, just use:
const input = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
const date = input.replace(/^.*"FROM_DATE":"([\d/]+)".*$/, '$1');

Now you can use date with just the date in it...
Comment: Thanks, this is the closest I was looking for.
Answer: In a second time you could remove /",.*/, but this seems too much heuristic to me.
You'd better just catch the first capturing group from the following regex:
/FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/

let str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
let pattern = /FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/
alert(str.match(pattern)[1]);
Answer: Your sample string looks very much like JSON. So much so in fact that you could just wrap it in braces, parse it as and object, and get the value of the FROM_DATE.
EG:

function almostJsonStringToObject(str) {
  return JSON.parse('{' + str + '}');
}
var str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
var obj = almostJsonStringToObject(str);
var fromdate = obj.FROM_DATE;
console.log(fromdate);


Can I glue a sleeve over a cracked dishwasher inlet line on my brand new garbage disposal unit?

Question:
The disposal is brand new and I can't return it even though it was damaged in shipping, as I'm well outside the return window. I believe the inlet is ABS plastic, as it's stamped with a small number 2.  The crack runs about as deep as the barbed end.
Can I just cut back the damaged area and weld/glue an ABS sleeve with a hose barb over the inlet?
My plumber was nervous about using it, but maybe he's being overly cautious.
Comment: It looks like a big split on the underside of the inlet that goes pretty deep (past the barbs?), and a smashed edge.  Attempt a repair only if there is no chance of return.  If you are able to swap it out, I wouldn't chance a repair, and any attempts would likely void any return.
Comment: Not sure why my comment was removed, but I'd trust a clamped hose on the existing nipple before an additional joint. It doesn't need to be that complicated.
Answer: With your inlet line cracked it might be possible to repair depending on how much of that inlet line exists.
as an FYI fro a better route: If you purchased that thing via HD or Lo - take it back for an exchange - they generally will do it. even if you are outside of 30 days. Damaged in shipping file a damage claim with the carrier.
Now on to the answer if the better route is not possible for you.
Repairing ABS plastic is not the easiest and I do not know if ABS is weldable like PVC pipe is.
What I would do is insert a small piece of Thin Wall copper pipe on the inside of the inlet for support and on the outer side maybe fit PVC or a tight fit Rubber Hose over the outer side with and connect my dishwasher outlet into it. You can use a high temp gasket sealant with this setup as well but don't use too much. Make sure you provide some strain/stress relief on the pipe as well.
See below for an example.
Answer: You could try opening the crack slightly with a screwdriver and putting ABS glue on the crack.  If it's ABS it will be weldable with the same glue that is used for black plastic drain pipe.
You can test it by putting a small dot of glue on the plastic and see if it starts to soften and become sticky.
I have used a similar repair on the ABS case of a hand-held tool, and while it doesn't look spectacular it works just fine.
Pictures of the crack might help.
Comment: thanks Keith - image above.  I have contacted Amazon and they will take it back, though it's well outside the return window.  I'm impressed (and pleased.. but Im also tempted to just test a drop of glue on this sucker and try save myself the shipping and hassle...
Answer: thanks for all your help here.  I contacted amazon and they agreed to ship me a new one or allow me to return this one even though it was well past the return window - they were really great about it, and made it easy.  Thanks to all.