What would be the best way to guide users in this design and avoid forcing users to make the mistake then correcting them?

Question: I am trying to find the best way to guide user to achieve their goal (Submitting a course) without the need to force users to make a mistake then correcting them.
In this design:

User lands on this page "Course Details" (option on the left). Here the user needs to fill out some information (some are mandatory and some are not).
Please notice that the "Submit" button is disabled.
User must select the "Course Date" option on the left. Must set a date. Only after the date is set, the "Submit" button will be enabled and user can submit. Meaning all other options are optional. The required ones are on the "Course Details" and "Course Date" options.

Submit button has to be visible on all pages (Whatever option you chose on the left displays a page on the right with either mandatory fields, optional fields, or both. So user can submit at any point, no matter the page they are on) AFTER all required data is provided, button gets enabled and user can submit (in this case required data is only under Course Details&Course Date).
My question is: While user is on the "Course Details" page, how can I let them know that the "Submit" button is still disabled (Although they filled out all mandatory fields at the "Course Details" page) because they still must go to the "Course Date" option and set a date, so the "Submit" button gets enabled?
So here is what I thought of doing, Either:

I put an asterisk next the "Course Date" option and I add a help icon next to the disabled "Submit" button, guides the user to go set the date and then they will be able to submit.
Help icon disappears once the button is enabled.
I put an asterisk next the "Course Date" option and I keep the "Submit" button enabled all the time, and once user clicks it before they set the date under the "Course Date" option, I show a message guides users to set a date then submit. (This way I am kind of forcing the user to make a mistake trying to submit then teaching them that they need to set a date first then submit)

I know the design is not great to start with, I appreciate better ideas!
Please note that this is not a finalized design, this design is just a sketch to explain the case, so no focus on fonts, or colors matching ...etc.
Update: (to claify more)
"Submit" button has to stay visible all the time like in the picture provided. As users do not need to fill out all data in all pages. Think about it as u click a button "Create new course", takes u to this page (default = Course Details page), U can fill out all data on all pages and submit. But u still can fill out "only" required data (in this case only at the Course details and date pages) and Submit. What if there are other required data on some other pages that each has several required data but it cannot be placed on the same page as the Course Details page. So how will u handle that? Think of the design as several pages each has specific data some pages has required data while some has optional. User can Submit at any page (all required data is provided).
One more point, there should not be a forced flow. Meaning, there should not be a "Next" button at each page to take the user to next page, as some users know what they need to fill out so they do not want to go to every single page. Some returning users might only want to provide some data (including the required data) and submit. So they want to keep it that way.
Comment: Why is it all the way off to the left, in a different color box with different font? Why can't all the data you're asking for be in the same main-body box, sorted from required to optional? And why is the Submit button in the top left? It's literally the last thing I looked at, while reading your text talking about it at first I thought it wasn't included in the screenshot at all. Most English-speaking readers look Left-to-Right, Top-to-Bottom. If this is not your demographic or are designing for an extremely diverse demographic, please elaborate.
Comment: *"Top-Right", I'm a durrr... So it seems you didn't design the whole layout, or are working with someone else who did? In the end, if you can fix the design, the rest will follow. You can add hints & tricks to a bad design, but most likely it will end up looking like "[My Company's App](https://rodgersnotes.files.wordpress.com/2010/10/simplicity.png)". Stick to what's common and intuitive, the way people have already been trained, or you will always have to [tell users they are doing it wrong](https://www.joelonsoftware.com/2001/12/15/humane-programming/).
Comment: Is this for desktop browsers only?
Comment: @IT Bear. Plz focus on the question, colors and it being all the way off to the left...etc is not a concern. There is a need to have different pages, each has different required data. Regarding Submit button, is it "top left" anyway? again this is not a finalized design, this is just a very simple fast design to explain the case. However, Submit button is intended to be placed there. Not designing for a different demographic. Submit button must be visible all the time, I know whoever designed it didnt want to place it bottom right or left bcz on some pages user has to scroll down to find it
Comment: @Confused. Yes it is.
Answer: It's all in the placement.
It would be best to have the submit button positioned below the Course Date option, because this is the typical logical reading order that implies the date should be set before the submit button is clicked.
I would also suggest putting a tooltip on the disabled submit button - as soon as the user hovers over the disabled button, it should say something like: Please set a course date. Of course, asterisks on required fields (and red outlines if not complete when submit is pressed) is the expected standard, so I would use that as well. Reduce user cognitive load by introducing all these elements.
With these improvements, although maybe not everyone will get it, the majority of users will understand that they need a date before they can submit.
Comment: Thnks. Submit button has to be visible on all pages (Whatever option you chose on the left displays a page on the right with either mandatory fields, optional fields, or both. So user can submit at any point, no matter the page they are on) AFTER all required data is provided, button gets enabled and user can submit (in this case required data is only under Course Details&Course Date). 2nd suggestion, I assume it is for when we leave the "Submit" button enabled, right? in this case yes, these suggestions work. I am trying to achieve it with Submit is disabled till all required data is provided
Comment: Voted up. Will be using the Tooltip on the disabled Submit button.
Answer: The current de-facto standard is an immediately-visible (i.e. large) asterisk next to each mandatory field, with a lead-in explanation that the starred items are required.

Given that this app is for the use of teachers, it can be accommodated on one page, e.g. (this has not been prettified):
Comment: User lands at the Course Details page, I need to let them know that there are some other mandatory fields that they cannot see at the "Course Details" page (Mandatory field on other pages i.e. here on the Course Date page), and that's why the Submit button is disabled till all required fields are provided. Mandatory fields on each page have asterisks to denote they are mandatory.
Comment: If the submit button depends on items on another page, why isn't it on that page instead?  Or, if the person might land on that other page first, why aren't all the mandatory items grouped on the same page?  It sounds like that page separation is serving interests other than those of the student, doesn't it?
Comment: Submit button has to be visible on all pages (Whatever option you choose on the left displays a page on the right with either mandatory fields, optional fields, or both. So user can submit at any point, no matter the page they are on) AFTER all required data is provided, button gets enabled and user can submit (in this case required data is only under Course Details&Course Date). Each option on the left displays a specific page on the right that has specific data. Having these separate pages is mandatory
Comment: You, as the u/i designer, have the responsibility to explain to them why it should be changed **in the interest of the students** (the principles involved are Be Obvious (also called Avoid Surprises), and Keep It Simple).  If they indicate that they don't believe you or don't care, then the most ethical thing you can do is walk away.  If that's not possible, add some js to monitor the mandatories and put a line of big red text over the button saying **"There are still mandatory items on the next/preceding page.  You must complete those items before this button will become active**
Comment: How about adding a Help icon next to "Submit" button, on mouse over (over the help icon) show text says i.e. "select dates to submit"? I think they will be open to changes if v needed. But what would u change if the "Submit" button has to stay visible all the time like in the picture provided. As users do not need to fill out all data in all pages. If u fill out required data in the two pages (course details, date) u can submit. If I put submit on a specific page then (1)user has to search for it(2)user can only submit at that page. This design allow users to fill out some info and submit
Comment: Think about it as u click a button "Create new course", takes u to this page (default = Course Details page), U can fill out all data on all pages and submit. But u still can fill out "only" required data (in this case only at the Course details and date pages) and submit. What if the other required data is not just to select a date. It is a whole page that has several required data but it cannot be placed on the same page of the Course Details page. So how will u handle that? Think of the design as several pages each has specific data some pages has required data while some has optional.
Comment: One more point, they do not want to force a flow on the users. Meaning, they do not want to put "Next" button at each page to take the user to next page, as they believe that some users know what they need to fill out so they do not want to go to every single page. Some users might only want to provide some data (including the required data) and submit. So they want to keep it that way. I will add these comments to the post in case they provide more clarification.
Comment: I'm afraid that I may be confused.  Is this application for **teachers** to use when defining and scheduling their own course(s)?
Comment: not sure what difference it makes, but yes u can say so.
Comment: Now that I have a better understanding, I've added to my response.
Comment: your solution helps by providing some good ideas on merging some of the options in one page. However, It does not actually solve my problem,merely because i am trying to find a solution to the current design without redesigning it all over. Some pages have big tables where the user selects from one table and add to another- Search and add from one list to the other (selected items) (i.e. subjects to be covered in one course- there are hundreds of courses and even more subjects). That's why we have options on the left to display the content on the right using the whole space.
Comment: What would be best, using a help icon next to the disabled "Submit" button that disappears once button is enabled. Or using a tooltip instead? A tooltip text will change to "Submit Course" when the "Submit" button gets enabled. My thoughts are, if i use a help button next to the disabled button, then i will have to do that next to every disabled button in the design. Tooltip is less exposed and does not really add more items on the page. thoughts?
Comment: *"Some pages have big tables where the user selects from one table and add to another- Search and add from one list to the other (selected items) (i.e. subjects to be covered in one course- there are hundreds of courses and even more subjects)."*  I don't think you understand the problem you're trying to solve.  Don't tell us about your app.  Describe who is going to use the app you eventually build, and for what purpose.
Comment: I think you do not understand the Question to start with. I made it very clear that this is how the design now and I am trying to handle a current situation, NOT redesigning it all over. (there is a need to have it designed this way). If I needed a whole new design, do you think my question will be the way it is?!! I got some good tips, I will provide my solution to the CURRENT design later on.
Comment: I'll bow out here.
Comment: Nooo, please dont lol. This should stay professional anyway.


Is there a UK equivalent to a BC Dry Chemical Extinguisher?

Question: I realise that in the USA, you can buy a dry chemical fire extinguisher rated for class B (flammable liquids) and class C (electrical) fires. Here in the UK, class B is the same, but class C is flammable gases.
I have one of these which I bought from Argos a while back, along with a fire blanket. What would be the equivalent of a BC dry chemical fire extinguisher from the USA, in the UK?
Answer: It seems that the new type "AF" is what is recommended. It is a watermist type extinguisher. While using water seems counterintuitive, it contains an additive that renders the water non conductive. When combined with the misting properties it smothers the fire. The other advantages are that it leaves no toxic residue and can be used in small areas without the concern of lung damage that can be a issue with dry powder.
Comment: When the electrical equipment is **on fire**, you WANT it disabled until the problem that caused it to catch on fire is fixed, and the damage the fire caused is also fixed, so that really does not seem like a sensible concern. In either case, it's useless on grease (these are class "AC" in the US system.) Most of the electrical non-conduction comes from the extinguisher spaying a mist, rather than a stream, and it is probably also de-ionized water (which can be an excellent insulator, until it finds some ions and dissolves them.) As such, simple drying is enough for non-affected equipment.
Comment: Cheers! Water would damage electricity though, so that doesn't particularly answer my question.
Comment: normal  would,but treated, chemically modified nonconductive water, apparently does not
Comment: Sorry, I meant electrical equipment. Water could extinguish it but would disable the equipment. Dry powder or CO2 has a lesser chance.
Comment: Fair play.  Any idea of the BC powder equivalent in the UK?
Comment: What is referred to as "dry mist" is becoming the standard for grease fires in industrial kitchens. According tohttp://www.fireservice.co.uk/safety/water-mist-extinguishers they are the latest and greatest.
Comment: You can either use them, wet chemical, or a fire blanket. Does anybody have any idea on the BC powder?
Comment: Most dry chemical extinguishers are very corrosive so will destroy your electronics anyways.


Dynamically linked pages ASP.NET

Question: I have created a Master page. And I have created a default page named default.aspx The defult aspx file has all of the standard content and ID's. In the ID I made a div tag to hold content for the dynamic page.
<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master"         CodeBehind="Default.aspx.vb" Inherits="P03_S02.Link1" %>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

</asp:Content>

This is all good. So by using SQL server express that comes with Visual Studio 2012 I created a table with data in it. The entitys in the table is
    ProductID
    Name
    Price
    Quantity
Now in the default.aspx.vb page I completed the following code.
Imports System.Data
Imports System.Data.SqlClient
Public Class Catelog
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        Dim Connection As SqlConnection
        Dim Command As SqlCommand
        Dim Reader As SqlDataReader
        Connection = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Products.mdf;Integrated Security=True")
        Dim CommandString As String
        CommandString = "SELECT * FROM Product"
        Command = New SqlCommand(CommandString)
        Command.CommandType = CommandType.Text
        Command.Connection = Connection
        Command.Connection.Open()
        Command.ExecuteNonQuery()
        Reader = Command.ExecuteReader(CommandBehavior.CloseConnection)

        Dim ProductList As String
        If Reader.HasRows Then
            ProductList &= "
"
            ProductList &= "
"
            ProductList &= "ID	"
            ProductList &= "Product	"
            ProductList &= "Price	"
            ProductList &= "Quantity	"
            ProductList &= "
"
            While Reader.Read
                Dim newProduct As String
                ProductList &= "
"
                ProductList &= "" & Reader("ProductID") & "	" & _
                "" & "" &      Reader("Name") & "" & "	" & _
                    "" & Reader("Price") & "	" & _
                    "" & Reader("Quantity") & "	"
                    ProductList &= "
"
                End While
                ProductList &= "
"
            End If
            Catelog.InnerHtml = ProductList
            Command.Connection.Close()
       '    Command.Dispose()
            Connection.Dispose()
            ProductCatelog.InnerHtml = ProductList
        End If
    End Sub

End Class

As you can see the table will display all data form the table. In the while loop I make each name in the table hyperlinks to another apsx file named Link1.
I used the same code as above but changed a few things in Link1.aspx.vb
Added:
  Dim ProductID As String
  ProductID = Request.QueryString("ProdID").ToString()'problem possible here

Changed the Display of data:
     Dim ProductList As String
        If Reader.HasRows Then
            ProductList &= "
"
            ProductList &= "
"
            ProductList &= "Product	"
            ProductList &= "Price	"
            ProductList &= "Quantity	"
            ProductList &= "
"
            While Reader.Read
                Dim newProduct As String
                ProductList &= "
"
                ProductList &= "" & Reader("Name") & "	" & _
                    "" & Reader("Price") & "	" & _
                    "" & Reader("Quantity") & "	"
                ProductList &= "
"
            End While
            ProductList &= "
"
        End If

Used the following to display only one record:
        Dim CommandString As String
        CommandString = "SELECT * FROM Product where ProductID =" & ProductID

My goal is if you click on a name it will link it to Link1.aspx and display only information about that name (Info in table). That does not happen because the program crashes.  I have used all my basic debugging knowledge.
Answer: Firstly, look up SqlParameters, because you've just opened your code up to SQL injection by passing parameters in the QueryString.
To address your question, I think the problem lies with this line:
"" & "" &      Reader("Name") & "" & "	" & _
You are closing your double-quote too soon and the productId isn't being put inside the href.
I'd rewrite it like this:
"" & "" &      Reader("Name") & "" & "	" & _
Subtle difference, but it should make it work.
Finally, always do a null/empty string check on the QueryString before you call .ToString().  Compare your QueryString entry using String.IsNullOrWhiteSpace(), and then only continue processing when String.IsNullOrWhiteSpace() returns false.
Answer: In default.aspx.vb you have :
"" & "" &      Reader("Name") & "" & "	" & _

passing name as ProdID
for ProdID you are passing Name  and in link1.aspx.vb you are querying like:
Dim ProductID As String
ProductID = Request.QueryString("ProdID").ToString()'problem possible here

and later:
Dim CommandString As String
CommandString = "SELECT * FROM Product where ProductID =" & ProductID

expecting ProdID, not Name.
So, in default.aspx.vb you should change the line to:
" & "" &

Dynamically linked pages ASP.NET


slice second level datetime multindex dataframe

Question: I have a dataframe that looks like that:

I am trying to slice for a particular symbol and as from a date.
doing
df.loc[symbol]

I obtain that dataframe:

So it goes from 2021-3-1 to 2023-1-31.
I have a variable "date" = Timestamp('2021-03-01 00:00:00'), so the first date.
When I try to slice it like that:
df.loc[pd.IndexSlice[symbol, date:]]

I get the error:

KeyError: Timestamp('2021-03-01 00:00:00')

same for:
df.loc[pd.IndexSlice[symbol, :date]]

When I print
df.index[0]

('BOTTO/WETH', Timestamp('2023-01-31 00:00:00'))

to prove that the second level is indeed a timetamp.
Any idea how I could do please?
Answer: For me working well if added : for select all columns before last ]:
df = pd.DataFrame(

    np.random.randn(20, 1),

    columns=["A"],

    index=pd.MultiIndex.from_product(

        [["a", "b"], pd.date_range("20210228", periods=10, freq="D")]

    ),

)

symbol = 'a'
date = pd.Timestamp('2021-03-01 00:00:00')

df = df.loc[pd.IndexSlice[symbol, date:], :]
print (df)
                     A
a 2021-03-01  0.228366
  2021-03-02 -1.092949
  2021-03-03 -1.086836
  2021-03-04 -1.155692
  2021-03-05  0.382733
  2021-03-06 -1.653822
  2021-03-07  0.978806
  2021-03-08 -1.537005
  2021-03-09 -0.200136

Comment: Indeed, the problem was the index need to be sorted first, while I sorted on timestamp and something else


How to keep insulated water pipes in attached garage and attic in garage from freezing again

Question: My water pipes, insulated, are in my garage and garage attic. It is a 2 car garage attached to my home. The pipes froze and I had no water for a week. I bought a 1500w space heater that is not doing much of anything.I am also worried about power going off. Would insulated garage doors help and be worth the money? I have some gas in the house. What about a gas heater?Thanks for any help you can give me.
Comment: How are the pipes insulated?  Are they inside a wall on the heated side with the insulation on the cold side?  Is the garage insulated?  Insulated doors not much use unless the garage is also.
Comment: If there are drafts blowing on the pipes then insulate the pipes. If the pipes are in frequent use then that may be sufficient.
Comment: at bare minimum install a temperature monitor on the water pipe. At least you will be alerted if the pipe temperature drops below freezing and you can take action.
Answer: Assuming that proper re-plumbing through conditioned spaces is not an option then you could buy an automatic electric heat cable.
I read the product specs on this 30' Frost King brand and it uses 7 watts per foot so a 15 amp circuit could safely support up to 205 feet of continuous operation.

Just make sure to read all safety precautions especially in regards to using it in conjunction with insulation and pipe material.
Comment: Do have to be careful if the pipes are a plastic type and insulated or will have insulation placed on them.
Comment: You can also get product like this that is a wrap and automatically controls how much current flows inversely with temperature so you can always keep it plugged in or hardwire it.
Comment: @GlenYates Yep, lots of choices out there. None of which are 100% guaranteed to work for OP since we don't know their skill level nor utility configuration.
Comment: how is this going to work over the existing insulation ?


error in upload file to ftp with ftp_nb_fput

Question: I wrote this code for upload file via ftp.
<code><?php

$file = 'index.php';

$fp = fopen($file, 'r');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Initate the upload
$ret = ftp_nb_fput($conn_id, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue upload...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

fclose($fp);
?>
</code>
and I get this error:
Warning: ftp_nb_fput(): Could not open data connection to port 2804: Connection refused
I disable my firewall but not work!
Comment: Try running in pasv mode, `ftp_pasv($conn_id, true);` Also please use `ftp_close($conn_id)` when you're done.
Answer: Try running in pasv mode, ftp_pasv($conn_id, true); Also please use ftp_close($conn_id) when you're done.
Thanks  Ohgodwhy!


How to call var from another form in C#

Question: i have two form in C#... i declare 3 var in form 1 pic, pic2 and picC.
In zoomform i instantiate the form1 object to try to get the variables values.. but i ran into stackoverflow exception...
 namespace Disimage
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    zoomForm zf = new zoomForm();

     public Bitmap pic;
            public Bitmap pic2;
            public Bitmap picC;
    }
    }

    namespace Disimage
    {
        public partial class zoomform : Form
        {
            public zoomform()
            {
                InitializeComponent();
            }
    Form1 f1 = new Form();

    }
    }

Comment: no vote or correct answer for this? So many answers are posted, might be somebody from them solve your problem or at least helped you.
Answer: That's beacause you create an instance of Form1 which contains an instance of zoomForm which contains an instance of Form1 which contains an instance of zoomForm which contains an instance of Form1 which contains an instance of zoomForm which contains an instance of Form1 which contains an instance of zoomForm which contains an instance of Form1 which contains an instance of zoomForm and there goes your stack.
Answer: this is because when you call
zoomForm zf = new zoomForm();  it will create a Form1 object which again create ZoomForm object results in a cycle and eventually  results in the stackoverflow
it is^similar to the fllowing suisidal code
Class A
{
        A a ;

   A()
   {
        a = new A();
    }
}

Answer: In zoomForm you instanciate a Form1 and in Form1 you instanciate a zoomForm, so your callstack looks like this(assuming you create a zoomForm first):
...
Form1
zoomForm
Form1
zoomForm
Form1
zoomForm
Form1
zoomForm
Form1
zoomForm
Form1
zoomForm
Form1
zoomForm
Form1
zoomForm
...
for about 8 thousand lines or some other way too high number. One easy way to solve this is to not instanciate the objects in the classes but set the objects from the outside.
zoomForm zf = new zoomForm();
form f1 = new Form1();
zf.form1 = f1;
f1.zoomForm = zf;

Answer: Change your code to something like
namespace Disimage
{
    public partial class Form1 : Form
    {
        zoomForm zf;
        public Bitmap pic;
        public Bitmap pic2;
        public Bitmap picC;
        public Form1()
        {
            InitializeComponent();
            zf = new zoomForm();
            zf.Parent = this;
        }
    }
}

namespace Disimage
{
    public partial class zoomform : Form
    {
        Form1 Parent;
        public zoomform()
        {
            InitializeComponent();
        }
    }
}

If you wish to have a reference to the Parent/Calling form, you need to explicitly set such a reference.
Answer: Try this.Here i am passing the 3 var to another form by declaring the same value types in another form as public property
    namespace Disimage {
    public partial class Form1 : Form
    {
        public Form1()
    {
            InitializeComponent();

    }
        private Bitmap pic;
        private Bitmap pic2;
        private Bitmap picC;
        zoomForm zf = new zoomForm();
        zf.pic = pic;
        zf.pic2 = pic2;
        zf.picC = picC;
        zf.ShowDialog();

    }
}
namespace Disimage
{
    public partial class zoomform : Form
    {
        public Bitmap pic;
        public Bitmap pic2;
        public Bitmap picC;
        public zoomform()
        {
            InitializeComponent();
        }
        Form1 f1 = new Form();
    }
}

Comment: No, you're not declaring any properties at all - you've got public *fields*, which is generally a bad idea.

How to call var from another form in C#


equation of the plane passing point

Question: Find the equation of the plane passing points $A = (3,5,1)$ and $B = (0,3,−1)$ and
parallel with the line $x=1-2t, y=2+t ,z=3t+2$
I don't really know what the line look like? what is the variable t here? THank you
Comment: For every value of t you will get points (x,y,z) on the line
Comment: The line $$\begin{bmatrix}x\\y\\z\end{bmatrix}=\begin{bmatrix}1\\2\\2\end{bmatrix}+t\begin{bmatrix}-2\\1\\3\end{bmatrix}.$$ This line passes through the point $(1,2,2)$ and has direction vector $(-2,1,3)$. So now you have a vector that is parallel to the plane. From the information given, can you find another vector **in** the plane?
Comment: Hint: Your math will get better if you do your own work.
Comment: can you give me more hints? sorry,my mathematics is bad.
Comment: What definition of a line in 3D coordinate geometry are you familiar with? Does this help?          $$\frac{x-1}{-2}=\frac{y-2}{1}=\frac{z-2}{3}$$ this is the cartesian equation for line in 3D. Are you familiar with direction ratios and concepts like that?
Comment: You wrote "I don't really know what the line look like?" But this isn't a question, it's a disclaimer.  You ask what the variable $t$ is, but you can't expect Readers to tell you what something you said means.  We need you to be the expert about what you are asking.  Then we can help with an Answer.
Answer: $t$ is just a parameter. as $t$ varies over all real numbers , you will get the coordinates of the points of the line. Try and relate with what happens in 2D.
Technically a line in 2d say $y=mx+c$ is can be written in a set builder form as :-
$$\{(t,at+c)\,,-\infty<t<\infty\}$$.
The coefficients of the parameter $t$ in each of the expressions for $x,y$ and $z$ are called the direction ratios and when viewed as a tripple , they give a vector which is parallel to the line.
Compare this with the technique you actually use to draw a line with a ruler and pencil. Once you are given a point and a direction , or two points, you join them using the ruler and extend it on both sides. Isn't it analogous to considering a point of starting point $O$ with it's position vector given by $\vec{p}$ and a direction given by $\vec{v}$ and just saying that all the points in your line are the same as those with coordinates $\vec{p}+t\vec{v}\,\,$ for all $-\infty<t<\infty$?
For a hint on trying to solve a problem:-
Are you aware that for two vectors lying in a plane, their cross product is perpendicular to it. If yes then what can you say about the cross product of the pair of vectors $\vec{BA}=(3,2,2)=3\hat{i}+5\hat{j}+2\hat{k}$ and the vector parallel to the line given by it's direction ratios $-2\hat{i}+\hat{j}+3\hat{k}$?
Will it be perpendicular to the plane?. If yes then don't you already have a point on the line and a vector perpendicular to it ?.
Another hint:- A tripple of vectors in $\mathbb{R}^{3}$ are coplanar iff their scalar tripple product is $0$.  Then for an arbitrary point $(x,y,z)$ in the plane , what can you say about the tripple ?
1.$(x,y,z)-(3,5,1)$
2.$(-2,1,3)$
3.$\vec{BA}=(3,2,2)$
If $(x,y,z)$ lies on the plane then are they not coplanar?. If yes then using the fact that the scalar tripple product is $0$? can you come up with an equation of the plane?

equation of the plane passing point


Android AAR NoClassDefFoundError

Question: I am attempting to open source a library that I have created but encountering problems with the generated AAR and NoClassDefFoundErrors when I attempt to use the library under a Gradle built APK. Notably, if I convert the AAR to the older, unofficial and now deprecated apklib format (and use under a android-maven-plugin built APK) the library works without issue.
With this evidence I'm likely seeing an android-gradle-plugin deficiency. From attempting all of the documented roots including relying on a local maven repo including the AARs and importing the AARs using Studio's module import mechanism the error remains.
Deeper investigation indicates that not all the library's classes suffer the issue noted below. Specifically, there are problems with those classes that themselves rely on Google Play Services or the Android Support Library. A similar issue (probably exactly the same, in fact) was noted here back in February.
The exception I am seeing is below;
04-21 00:02:25.863  21336-21336/com.oceanlife E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.oceanlife, PID: 21336
    java.lang.NoClassDefFoundError: com.brantapps.polaris.google.GoogleMapWrapper
            at com.brantapps.polaris.PolarisModule.provideMappable(PolarisModule.java:46)
            at com.brantapps.polaris.PolarisModule$$ModuleAdapter$ProvideMappableProvidesAdapter.get(PolarisModule$$ModuleAdapter.java:57)
            at com.brantapps.polaris.PolarisModule$$ModuleAdapter$ProvideMappableProvidesAdapter.get(PolarisModule$$ModuleAdapter.java:41)
            at com.oceanlife.fragment.addspot.AddSpotMapFragment.onCreate(AddSpotMapFragment.java:171)
            at android.support.v4.app.Fragment.performCreate(Fragment.java:1763)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:915)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
            at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
            at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1220)
            at android.app.Activity.performStart(Activity.java:5949)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

The project's configuration can be viewed under the GitHub repo here but here are the build dependencies I have for clarity;
dependencies {
    compile 'com.android.support:support-v4:22.0.0'
    compile 'com.google.guava:guava:18.0'
    compile 'com.squareup.dagger:dagger:1.2.1'

    googleCompile 'com.google.android.gms:play-services:7.0.0'

    kindleCompile 'org.osmdroid:osmdroid-android:4.1'
    kindleCompile 'org.osmdroid:osmbonuspack:4.4'
    kindleCompile 'org.slf4j:slf4j-android:1.7.7'

    provided 'com.squareup.dagger:dagger-compiler:1.2.+'
}

Any insight/workarounds to this issue graciously received.
Comment: I've worked around this by placing the AAR code under a flavour. Will retry with the next release of the build tooling.
Comment: Still doesn't work as I seem to expect...
Answer: I've found that if I repeat the dependencies that are causing the NoDefFoundError (as described in the linked SO) within the main application then the issue goes away...
It seems that the library AARs are built without the Google Play and Support Library dependencies. I believe I can build it correctly and force the dependencies to be resolved by generating an appropriate pom.xml that sits alongside the AAR in my local maven repo.
For reference here is my project configuration;
Android Studio:
--App
  -- build.gradle (repeat dependencies of Polaris)
--Polaris
  -- build.gradle (Google Play and Support dependencies)
--ApiClient
  -- build.gradle (just another module)

Local Maven:
--.m2
  -- com
    -- brantapps
      -- polaris-google
        -- 1.0.0
          -- polaris-google-1.0.0.aar
          -- polaris-google-1.0.0.pom (need to build one of these maybe!)

Android AAR NoClassDefFoundError


Validation Forms without Entity with form class

Question: I need help about validation forms without entity but with form class. My problem is the collection constraint in my form class in the override method getDefaultOoptions. It doesn't take this collection into account when I bind the form in my controller.
This is my class form
    namespace Projet\TicketBundle\Form;

use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Collection;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class TicketPackAndAppType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('total', 'text' ,array('label' => 'Total de la commande  ',     'read_only' => true))

            ->add('address_delivery', 'entity' , array('class' => 'TacTill\CustomerBundle\Entity\Address',
                  'property' => 'address',
                  'required' => false,
                  'label' => 'Adresse de livraison  ',
                  'required' => false
                 ))
            ->add('address_invoice', 'entity' , array('class' => 'TacTill\CustomerBundle\Entity\Address',
                  'property' => 'address',
                  'required' => false,
                  'label' => 'Adresse de facturaton  ',
                  'required' => false
                 ))

            ->add('color', 'choice', array(
                'choices' => array(
                    'B' => 'Noir',
                    'W' => 'Blanc'),
                'required' => true,
                "property_path" => false,
                'expanded' => true,
                'multiple' => false
            ))

            ->add('model', 'choice', array(
                'choices' => array(
                    'iPadDeux16Gowifi' => '16 Go Wifi',
                    'iPadDeux16Gowifi3G' => '16 Go Wifi et 3G',
                    'iPadNew16Gowifi' => '16GoWifi',
                    'iPadNew32Gowifi' => '32 Go Wifi',
                    'iPadNew64Gowifi' => '64 Go Wifi',
                    'iPadNew16Gowifi4G' => '16 Go Wifi et 4G',
                    'iPadNew32Gowifi4G' => '32 Go Wifi et 4G',
                    'iPadNew64Gowifi4G' => '64 Go Wifi et 4G'
                    ),
                'required' => true,
                "property_path" => false,
                'expanded' => true,
                'multiple' => false
            ))

            ->add('stand', 'choice', array(
                'choices' => array(
                    'standsecurity' => 'Sécurité',
                    'standdesign' => 'Design',
                    'standmobility' => 'Mobilité'
                    ),
                'required' => true,
                "property_path" => false,
                'expanded' => true,
                'multiple' => false
            ))

            ->add('printer', 'choice', array(
                'choices' => array(
                    'printerB' => 'Noire',
                    'printerW' => 'Blanche'
                    ),
                'required' => true,
                "property_path" => false,
                'expanded' => true,
                'multiple' => false
            ))

            ->add('cashDrawer', 'choice', array(
                'choices' => array(
                    'cashDrawerG' => 'Graphite',
                    'cashDrawerP' => 'Perle'
                    ),
                'required' => true,
                "property_path" => false,
                'expanded' => true,
                'multiple' => false
            ))

            ->add('app', 'choice', array(
                'choices' => array(
                    'appSmall' => 'S\'abonner à TacTill',
                    'noApp' => 'Télécharger l\'application plus tard'
                    ),
                'required' => true,
                "property_path" => false,
                'expanded' => true,
                'multiple' => false
            ))
        ;

    }

    public function getName()
    {
        return 'ticket_packandapptype';
    }

    public function getDefaultOptions(array $options)
    {
        $collectionConstraint = new Collection(array(
                'color' => new NotBlank(array('message' => 'Champ vide')),
                'model' => new NotBlank(array('message' => 'Champ vide')),
                'stand' => new NotBlank(array('message' => 'Champ vide')),
                'printer' => new NotBlank(array('message' => 'Champ vide')),
                'cashDrawer' => new NotBlank(array('message' => 'Champ vide')),
                'app' => new NotBlank(array('message' => 'Champ vide')),
        ));

        return array('validation_constraint' => $collectionConstraint);
    }
}

In my controller
public function createOrderAction()
{

    $em = $this->getDoctrine()->getEntityManager();

    $requestInArray = $this->getRequest()->request->get('ticket_packandapptype');

    $request = $this->getRequest();
    $form    = $this->createForm(new TicketPackAndAppType());

    if ($request->getMethod() == 'POST') {

        $form->bind($requestInArray);

        $stand = $requestInArray['stand'];
        $printer = $requestInArray['printer'];
        $cashDrawer = $requestInArray['cashDrawer'];
        $app = $requestInArray['app'];
  }
}

I have also test with bindRequest and that is the same problem.
I follow the Validation without class but i don't where is the mistake.
When i have done the without form class the collection constraints works well.
If you have any idea, explain to me. Thank you
Answer: You should do smth like this:
if ($request->getMethod() == 'POST') {

    $form->bindRequest($request);
    if ($form->isValid()) {
        //do your actions with form values
    } else {
       //return form with error messages
       //or do smth else...
    }

}
When you call isValid() Symfony tries to checks you daya with your constraint...
Also you should get your data through form:
$data = $form->get('your_field_name')->getData();

Of course you should do it after binding form from request...


Optimizing a "reposts" MySQL query

Question: I have a table of posts, a table of reposts, and a table representing "user following" status.
I want to do something like Twitter, where I show all the posts or reposts from followed users.
I want the post to appear the first time it occurs, such that if multiple users repost the post, it only appears the first time.
In order to speed up this query, I insert into the repost table whenever a post is created, such that a corresponding repost (from the author) is also created.
My schema looks something like this:
Table Post
id: INT
userId: INT
time: INT

Table Repost
id: INT
postId: INT
userId: INT
time: INT

Table users_following
userId: INT
followerId: INT

And my query looks like this.
SELECT sr.* FROM Repost sr
INNER JOIN (
    SELECT MIN(ir.time) min_time, ir.postId FROM Repost ir
    WHERE ir.userId IN (
        SELECT uf.userId FROM users_following uf WHERE
        ir.userId = uf.userId AND uf.followerId = 1
    )
    OR ir.userId = 1
    GROUP BY ir.postId
) rr ON rr.postId = sr.postId AND sr.time = rr.min_time

The idea is this:

SELECT FROM users_following uf. Select all the user ids followed by the viewer.
SELECT FROM Repost ir. Select the min repost time for a given post, where the reposter id is either a followed user or the viewer.
SELECT FROM Repost sr. Select the repost with the min time for a given post using inner join.

This works, but stage 3 is slow. I believe this is because once we have a big list of min_times, we can't use any indexes to select from that subquery, meaning we need to scan everything. Is there a way to structure this query to make it more performant?
Here's the full EXPLAIN and SHOW CREATE TABLE for the hardcore readers.
EXPLAIN
+----+--------------------+------------+------------+--------+-------------------------------------------------------------+----------------------+---------+---------------------------------+--------+----------+--------------------------+
| id | select_type        | table      | partitions | type   | possible_keys                                               | key                  | key_len | ref                             | rows   | filtered | Extra                    |
+----+--------------------+------------+------------+--------+-------------------------------------------------------------+----------------------+---------+---------------------------------+--------+----------+--------------------------+
|  1 | PRIMARY            | <derived2> | NULL       | ALL    | NULL                                                        | NULL                 | NULL    | NULL                            | 797455 |   100.00 | Using where              |
|  1 | PRIMARY            | sr         | NULL       | ref    | IDX_DA9843F3E094D20D,repost_time_idx,repost_stream_idx      | repost_time_idx      | 4       | rr.min_time                     |      1 |     4.92 | Using where              |
|  2 | DERIVED            | ir         | NULL       | index  | IDX_DA9843F364B64DCC,IDX_DA9843F3E094D20D,repost_stream_idx | IDX_DA9843F3E094D20D | 4       | NULL                            | 797456 |   100.00 | Using where              |
|  3 | DEPENDENT SUBQUERY | uf         | NULL       | eq_ref | PRIMARY,IDX_17C2F70264B64DCC,IDX_17C2F702F542AA03           | PRIMARY              | 8       | prose_2_24_2021.ir.userId,const |      1 |   100.00 | Using where; Using index |
+----+--------------------+------------+------------+--------+-------------------------------------------------------------+----------------------+---------+---------------------------------+--------+----------+--------------------------+

SHOW CREATE TABLE Repost
CREATE TABLE `Repost` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `postId` int(11) NOT NULL,
  `userId` int(11) NOT NULL,
  `time` int(11) NOT NULL,
  `isRepost` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `IDX_DA9843F364B64DCC` (`userId`),
  KEY `IDX_DA9843F3E094D20D` (`postId`),
  KEY `repost_time_idx` (`time`),
  KEY `repost_stream_idx` (`time`,`userId`,`postId`),
  CONSTRAINT `FK_DA9843F364B64DCC` FOREIGN KEY (`userId`) REFERENCES `ProseUser` (`id`),
  CONSTRAINT `FK_DA9843F3E094D20D` FOREIGN KEY (`postId`) REFERENCES `Post` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=809018 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

SHOW CREATE TABLE users_following
CREATE TABLE `users_following` (
  `userId` int(11) NOT NULL,
  `followerId` int(11) NOT NULL,
  PRIMARY KEY (`userId`,`followerId`),
  KEY `IDX_17C2F70264B64DCC` (`userId`),
  KEY `IDX_17C2F702F542AA03` (`followerId`),
  CONSTRAINT `FK_17C2F70264B64DCC` FOREIGN KEY (`userId`) REFERENCES `ProseUser` (`id`),
  CONSTRAINT `FK_17C2F702F542AA03` FOREIGN KEY (`followerId`) REFERENCES `ProseUser` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

EDIT
Adjusting the query like so yields much faster results, though adding the ORDER BY makes it slow. Without ORDER BY, this query is great.
SELECT sr.* FROM Repost sr
INNER JOIN (
    SELECT MIN(ir.time) min_time, ir.postId FROM Repost ir
    INNER JOIN users_following uf ON ir.userId = uf.userId AND uf.followerId = 1
    GROUP BY ir.postId
) rr ON rr.postId = sr.postId AND sr.time = rr.min_time
ORDER BY sr.time desc
LIMIT 10

Here's the explain for this query:
+----+-------------+------------+------------+--------+--------------------------------------------------------------------------------+----------------------+---------+---------------------------+------+----------+----------------------------------------------+
| id | select_type | table      | partitions | type   | possible_keys                                                                  | key                  | key_len | ref                       | rows | filtered | Extra                                        |
+----+-------------+------------+------------+--------+--------------------------------------------------------------------------------+----------------------+---------+---------------------------+------+----------+----------------------------------------------+
|  1 | PRIMARY     | <derived2> | NULL       | ALL    | NULL                                                                           | NULL                 | NULL    | NULL                      |  691 |   100.00 | Using where; Using temporary; Using filesort |
|  1 | PRIMARY     | sr         | NULL       | ref    | IDX_DA9843F3E094D20D,repost_time_idx,repost_stream_idx,repost_stream2_idx      | repost_stream2_idx   | 8       | rr.min_time,rr.postId     |    1 |   100.00 | NULL                                         |
|  2 | DERIVED     | uf         | NULL       | ref    | PRIMARY,IDX_17C2F70264B64DCC,IDX_17C2F702F542AA03                              | IDX_17C2F702F542AA03 | 4       | const                     |  145 |   100.00 | Using index; Using temporary; Using filesort |
|  2 | DERIVED     | ir         | NULL       | ref    | IDX_DA9843F364B64DCC,IDX_DA9843F3E094D20D,repost_stream_idx,repost_stream2_idx | IDX_DA9843F364B64DCC | 4       | prose_2_24_2021.uf.userId |    9 |   100.00 | NULL                                         |
|  2 | DERIVED     | rp         | NULL       | eq_ref | PRIMARY,post_spotlight_idx,post_time_idx,post_trending_idx                     | PRIMARY              | 4       | prose_2_24_2021.ir.postId |    1 |    50.00 | Using where                                  |
+----+-------------+------------+------------+--------+--------------------------------------------------------------------------------+----------------------+---------+---------------------------+------+----------+----------------------------------------------+

Comment: Run `SHOW CREATE TABLE post` and paste the result into your question. Do the same thing with `repost` and `users_following` tables. That way we can see the full table schema including PK, indexes etc. And please post along your full `EXPLAIN` result.
Comment: @FaNo_FN Added them just now. I left out Post, since it's more for context, and not part of the actual query in question.
Comment: To find out what's slow, try first to prepend `EXPLAIN EXTENDED ....` to your query.
Comment: WHERE .. IN must be convertied to JOIN. PS. It's interesting, how do you save repost of repost (which is a post of reposter!) on this structure...
Comment: EXPLAIN shows type `ALL` on `` table consisting of about 800k rows. Not great. :p
Comment: @Akina repost of repost is not supported. Just reposts of the original post. :)
Comment: @Akina yeah I experimented with that. I wasn't seeing a big improvement, though it makes sense that it'd be faster in theory. The slow part is the outer-most INNER JOIN (stage 3).
Comment: Some sample data and a desired result might be fun
Comment: @Akina I conoverted the WHERE .. IN to an INNER JOIN, which is much faster. Now the only issue is the ORDER BY clause.
Comment: Remove keys `IDX_17C2F70264B64DCC` and `IDX_17C2F702F542AA03` but create index `users_following (followerId, userId)`. Also try to create ```Repost (`time`, postId)```.
Comment: It looks like the Edit lost the `OR ir.userId = 1` -- Maybe that is why it sped up; does it give the wrong answer now?
Answer: The typical way I'd write such a ranking query is thus:
select id, postid, userid, time
from
(
  select rp.*, min(time) over (partition by postid) as first_time
  from repost rp
  where userid = 1
  or userid in (select userid from users_following where followerid = 1)
) numbered
where time = first_time;

Sometimes optimizers have problems with OR and fail to see they can run through the table twice, if they consider this faster. In that case we can hint with UNION:
select id, postid, userid, time
from
(
  select rp.*, min(time) over (partition by postid) as first_time
  from
  (
    select *
    from repost
    where userid = 1
    union all
    select *
    from repost
    where userid in (select userid from users_following where followerid = 1)
  ) rp
) numbered
where time = first_time;

Once MySQL was known for having trouble with IN clauses. I don't think that is the case anymore. If the DBMS does have problems, you can use EXISTS instead:
from repost rp
where exists
(
  select null
  from users_following uf
  where uf.userid = rp.userid
  and uf.followerid = 1
)

In MySQL versions prior to version 8 analytic functions like MIN OVER were not available. In these versions you'd have to find the minimum time per post and then read the table again. One straight-forward way:
select *
from repost
where (postid, time) in
(
  select postid, min(time)
  from repost
  where userid = 1
  or userid in (select userid from users_following where followerid = 1)
  group by postid
);

In any case you want an index to look up followed users quickly. The DBMS is free to come with a repost user and check if they are followed by user #1 or to take user #1 and find all followed users. So I'd provide two indexes:
create index idx1 on users_following (userid, followerid);
create index idx2 on users_following (followerid, userid);

Then you want to find their reposts quickly, then group by post ID and order by time. The index for this:
create index idx3 on repost (userid, postid, time);

Another way to look at this: If we read through the whole table and keep the rows for the desired users, it would be great were the rows already sorted by postid, time. So, just in case:
create index idx3 on repost (postid, time);

for a full index scan.
Indexes are an offer to the DBMS. The DBMS can accept this offer and use the index or not. What I often do:

Think about in which order the DBMS may access the tables.
Provide indexes for those routes.
Use EXPLAIN to see which of my indexes get used.
Drop the others.
Comment: `OVER` needs 8.0 or 10.2; what version are you using?
Answer: Repost needs an overhaul of indexes from
  PRIMARY KEY (`id`),
  KEY `IDX_DA9843F364B64DCC` (`userId`),
  KEY `IDX_DA9843F3E094D20D` (`postId`),
  KEY `repost_time_idx` (`time`),
  KEY `repost_stream_idx` (`time`,`userId`,`postId`),

to
  PRIMARY KEY(postId, userId, time, id),   -- `id` is for uniqueness
  INDEX(id)  -- to keep AUTO_INCREMENT happy

(I don't know if the others have any use.)
Change IN ( SELECT ... ) to EXISTS ( SELECT 1 ... )
OR is a performance killer.  Time the query with one side of the OR, then with the other side.  Assuming the sum of those times is faster than your current time, UNION those together.  Simplify each of the queries if practical.  Show me the results; I may have more index suggestions.

Optimizing a "reposts" MySQL query


Docker should throw an error when "package.json" is not found but no error is thrown

Question: I am learning Docker and created a very simple image that creates a container with node dependencies downloaded.
See the docker image (Dockerfile) below:
FROM node:14-alpine
RUN npm install
CMD ["npm", "start"] here

The directory has the following files Dockerfile, index.js, package.json. All three files are at the same level.
when I run docker build ., I expect the step 2 to throw an error indicating package.json was not found as the temporary container created from step 1 should not have the package.json file, but I do not get this error, instead the build is completed successfully. Could someone explain why does the build is completed successfully and I don't get any error?
See the output from the build below:
[+] Building 4.2s (6/6) FINISHED                                                                                docker:desktop-linux
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 95B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/node:14-alpine                                                                             0.9s
 => [1/2] FROM docker.io/library/node:14-alpine@sha256:434215b487a329c9e867202ff89e704d3a75e554822e07f3e0c0f9e606121b33                       2.6s
 => => resolve docker.io/library/node:14-alpine@sha256:434215b487a329c9e867202ff89e704d3a75e554822e07f3e0c0f9e606121b33                       0.0s
 => => sha256:4cf6a83c0e2af3c780abcda02cc33f9e812fdcb40b610ed1838281cc9ab94ec8 2.43MB / 2.43MB                                                0.2s
 => => sha256:434215b487a329c9e867202ff89e704d3a75e554822e07f3e0c0f9e606121b33 1.43kB / 1.43kB                                                0.0s
 => => sha256:3380ed827b250d2db2bd38c15f090af2b303b3c9ebb42f5927cb5b9adeea7a6e 1.16kB / 1.16kB                                                0.0s
 => => sha256:d561716d42b6a03639723c382c62977347ed62f13925e836614583253308e6c3 6.45kB / 6.45kB                                                0.0s
 => => sha256:c41833b44d910632b415cd89a9cdaa4d62c9725dc56c99a7ddadafd6719960f9 3.26MB / 3.26MB                                                0.2s
 => => sha256:683339ce8d6b9be2ca150a8de67b895e20ea5594b91d3911c95b0b8fea3e314c 36.99MB / 36.99MB                                              1.3s
 => => extracting sha256:c41833b44d910632b415cd89a9cdaa4d62c9725dc56c99a7ddadafd6719960f9                                                     0.1s
 => => sha256:686172e40c38722891b4004f55f6447548c8367968ac523a612591e0d92f9db3 447B / 447B                                                    0.3s
 => => extracting sha256:683339ce8d6b9be2ca150a8de67b895e20ea5594b91d3911c95b0b8fea3e314c                                                     1.2s
 => => extracting sha256:4cf6a83c0e2af3c780abcda02cc33f9e812fdcb40b610ed1838281cc9ab94ec8                                                     0.0s
 => => extracting sha256:686172e40c38722891b4004f55f6447548c8367968ac523a612591e0d92f9db3                                                     0.0s
 => [2/2] RUN npm install                                                                                0.7s
 => exporting to image                                                                                0.0s
 => => exporting layers                                                                                0.0s
 => => writing image sha256:9ffbc17f35fbca106a7a540b8433b8e5144d792244a35aa140d1c57bd1b8387c

Comment: Are you sure there's no `package.json`? Do you have a volume/bind mount? What happens if you `RUN ls` ?
Answer: It looks like npm install in that image does not return an error code when package.json is missing.
Try starting a shell in that image and running npm install, then inspecting the exit code:
$ docker run --rm -it node:14-alpine sh
/ # npm install
npm WARN saveError ENOENT: no such file or directory, open '/package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open '/package.json'
npm WARN !invalid#2 No description
npm WARN !invalid#2 No repository field.
npm WARN !invalid#2 No README data
npm WARN !invalid#2 No license field.

up to date in 0.208s
found 0 vulnerabilities

/ # echo $?
0

The key part is that last line, which shows that despite the warnings on output, the command completes successfully.
Since the command doesn't exit with an error, Docker believes it is successful and continues to build the image.

Note that this behavior seems to have changed with more recent versions of npm. For example, using the latest image:
$ docker run --rm -it node:20-alpine sh
/ # npm install
npm ERR! Tracker "idealTree" already exists

npm ERR! A complete log of this run can be found in: /root/.npm/_logs/2023-07-07T01_02_38_828Z-debug-0.log
/ # echo $?
1

So if you were to use that version of the image it would fail as you expect.


type does not satisfy interface (method has pointer receiver)

Question: is it possible to do something like this:
package main

type reader interface {
   read()
}

type hello int

func (*hello) read() {}

func set[T reader](a *T) {
   var b T
   *a = b
}

func main() {
   i := hello(1)
   set(&i)
}

no matter what I change I get an error.
Answer: Type hello doesn't implement method read. The interface reader is implemented by the type *hello. That is why the call set(&i) has the signature set(T), not set(*T), and go can't derive the type for the generic.
What you need is call set(*T) such that *T is reader:
package main

type reader interface {
    read()
}

type hello int

func (*hello) read() {}

func set[T any, U interface {*T;reader}](a U) {
    var b T
    *a = b
}

func main() {
    i := hello(1)
    set(&i)
}


laravel 5.1 authserviceprovider define a permission

Question: Trying to sort out this new AuthServiceProvider in Laravel 5.1.
<?php

namespace App\Providers;

use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    $gate->define('test-permission', function ($user) {
        return true;
    });

}

In my blade I try
@if (Gate::allows('test-permission'))
    hello world.
@endif

I get no love. If I change it to Gate::denies('test-permission') the hello world renders.
Ultimate I want to pull my permissions from my Entrust data to migrate my permissions to a Laravel 5.1 environment.
Answer: Laravel will only call your closure if there's a logged-in user.
If there's no logged-in user, Laravel will always deny everything.

If you are logged in, chances are you haven't properly registered the AuthServiceProvider.
Comment: I am logged in - but perhaps I need to make a change to my authentication to make it 5.1 compatible. I followed the instructions. I dd(Auth::user()) and it looks good. Also if (Auth::check()) returns true.
Comment: Try `dd`ing in your `define` callback. Is it reached at all?
Comment: Nope - dd anywhere in AuthServiceProvider does nothing
Comment: Are you sure it's actually registered in `config/app.php`'s `providers` array?
Comment: Like so:   'Illuminate\Auth\AuthServiceProvider',
Comment: That's wrong. It should be `App\Providers\AuthServiceProvider`
Comment: Thanks Joseph - you have me on the right track now - not sure how/where I missed that - maybe was an upgrade step. If you want to post that as an answer I'll check it as the right one.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97004/discussion-between-dylan-glockler-and-joseph-silber).


Get SP Configuration Database Version in C#

Question: I'm looking to grab the SharePoint Configuration Database version via C# and found the SPConfigDatabase class under Microsoft.SharePoint.Administration which has a Version member. This is exactly what I'm looking for, but this is now obsolete.
What is the best method for doing this? Ideally I'd like to grab the Cumulative Update date as well, though this is essentially just another name for the version number.
Thanks
Answer: The way to get it using C# is to use the Microsoft.SharePoint.Administration.SPFarm class and the property you are looking for is BuildVersion:
var v = SPFarm.Local.BuildVersion;

As that returns a System.Version object, you may want to concatenate the values together to make the string appear as it does in the central admin:
var friendly = v.Major + "." + v.Minor + "." + v.Build + "." + v.Revision;

Also, please note that to access the SPFarm.Local property, you will need to be running the code in 64-bit mode as well as have an authorized account. In fact, with the UAC enabled on my VM I needed to run my code by right-clicking on it and choosing "Run as Administrator" as well.
Answer: I found a tentative solution by executing a powershell script. Here's my solution that prints out the result to the console from the powershell script:
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
.
.
.
MAIN CODE:
Runspace runspace = RunspaceFactory.CreateRunspace();

runspace.Open();

PowerShell ps = PowerShell.Create();
ps.AddScript("Add-PsSnapin Microsoft.SharePoint.Powershell");
ps.AddScript("get-spfarm | select BuildVersion");
ps.AddCommand("Out-String");

Collection <PSObject> results = ps.Invoke();
runspace.Close();

foreach (PSObject obj in results)
{
    Console.WriteLine(obj.ToString());
}

Credit to http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C
and http://social.msdn.microsoft.com/Forums/hu/sharepoint2010general/thread/88b11fe3-c218-49a3-ac4b-d1a04939980c
Answer: just connect to the database and execute this query
SELECT SERVERPROPERTY ('productversion'),
       SERVERPROPERTY ('productlevel'),
       SERVERPROPERTY ('edition')

references:
http://support.microsoft.com/kb/321185
I hope that helps
Comment: Thanks for the response, but this is not what I'm looking for. This gets the version of SQL Server Management Studio, but not my SP Config Database version. You can see what I'm referring to by going to SharePoint Central Admin > Servers in Farm > Configuration database version.
Comment: You can use SQL Server Profiler to find out the SQL query used when you open that page. Then take the same approach and answer your own question :)


Left Ctrl Key doesn't work (but right one does)

Question: My left ctrl key isn't working. The right ctrl key works fine. I'm not skilled at all with problem sovling in Linux. Could someone point me the right direction, please? From what I learn when I run xev is that the right key is correctly associated with Control_R, while the left key is not. How can I fix this? The same problem occurs under Ubuntu 18.04 and under Linux Mint (installed one after the other hoping the issue would resolve itself). Other keys seem to work fine so far.
Output of xev when I press the Ctrl keys:
<code>KeyPress event, serial 38, synthetic NO, window 0x5200001,
root 0x15a, subw 0x0, time 1330613, (-134,341), root:(727,796),
state 0x0, keycode 105 (keysym 0xffe4, Control_R), same_screen YES,
XLookupString gives 0 bytes:
XmbLookupString gives 0 bytes:
XFilterEvent returns: False

KeyRelease event, serial 38, synthetic NO, window 0x5200001,
    root 0x15a, subw 0x0, time 1330692, (-134,341), root:(727,796),
    state 0x4, keycode 105 (keysym 0xffe4, Control_R), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyPress event, serial 38, synthetic NO, window 0x5200001,
    root 0x15a, subw 0x0, time 1332145, (-134,341), root:(727,796),
    state 0x0, keycode 151 (keysym 0x1008ff2b, XF86WakeUp), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 38, synthetic NO, window 0x5200001,
    root 0x15a, subw 0x0, time 1332155, (-134,341), root:(727,796),
    state 0x0, keycode 151 (keysym 0x1008ff2b, XF86WakeUp), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False
</code>
Comment: keycode 151 should be your function key -- did you swap the Left Ctrl and Function key at some point?
Comment: no, it's a fresh installation. Hardly changed anything so far.

... but we're on something here! Fn and Ctrl are reversed... can I switch them so they match the sign printed on the keyboard?
Comment: Take a look at https://askubuntu.com/questions/68819/swap-two-keys-using-xmodmap (or search this site for "swap keys".
Comment: so ubfan1 was right: Switching of Fn and Ctrl had been enabled in the BIOS by a previous owner of the notebook. thanks for clarifying everyone!
Answer: Switching Ctrl and Fn should be available in BIOS. OEMs may have Windows apps to change it, but it's just another way of changing the same setting.
Comment: Jepp, Bios swapp it was. Thanks everyone!
Comment: @mathew7 Please elaborate on this. I have a Dell Inspiron and I see nothing on keyboards on its BIOS menu.
Comment: @Trunk My experience is with Lenvo, specifically Thinkpads. My 2013 x230 and 2018 x280 have the Fn key in the corner where 90% of keyboards have ctrl (fn,ctrl,win,alt,space order).
Searching for Dell Inspiron images, I see them having ctrl in corner. For such layouts, I don't think they would have the swap option.
Comment: @mathew7 Just found the answer. Open Tweaks > Keyboard & Mouse > Additional Layout Options > CTRL Position  and then check the Bottom Left box. Ideally I'd like to move my Compose key across to the Right CTRL key but that's another puzzle . . .
Comment: Just commenting here to say that this worked on a Lenovo Legion laptop, where the "Fool proof Fn and Ctrl" option was on by default.


Anyone recognize this faucet? How to remove these faucet handles?

Question: I'm trying to remove these bathroom faucet handles. There are no screws anywhere on the outside surface.
Is it just a matter of prying them off, either using a screwdriver or just pulling up on the knobs really hard? Or should I try turning the knobs the wrong way?
I don't want to force it, so I figured I'd ask first.
Does anyone recognize the make / model? It would be good to know what replacement parts I'd need to buy before I disassemble it.
Comment: See also https://diy.stackexchange.com/questions/78912/how-to-remove-the-handles-from-this-faucet ?
Answer: If there are no obvious means of disconnecting, it ALMOST has to be a "pop off" design.   What other options are there???    I'd take a putty knife and gently pry on it from different sides and see if it "wants" to break free.
Comment: Highly highly unlikely.   How would that work?   And it'd probably be the stupidest design ever, unless the engineer had never climbed under a sink....
Comment: LOL Ok I'll play along... Ever seen one that mounts the handles from underneath??
 The "axle" you speak of is where the valve stem would be.   To say such an arrangement would be "awkward" is an understatement.   Are you just trying to be difficult or are you actually posing a serious reply???   Because I'm not of the mind to tolerate silliness ATM.    Would it have been better to say "It "almost" has to be a pop off?"  Because, ya know, nothing in the world is absolute.  And there's always somebody who's happy to call out typos and grammar errors. "These handles pop off"  There, I said it.
Comment: "If there are no obvious means of disconnecting, it has to be a "pop off" design." Does it actually? It could be that the means to detach them is on the bottom of the mounting.
Comment: "How would that work?" Screws that slide along a track when the handles are turned? Screws attached to an axle to prevent it from being pulled out? Or, if you meant "how would it be assembled", I imagine that you'd attach the handles to the mounting, then attach the mounting to the sink and before attaching the pipes and hoses.
Comment: I'm not a plumber, but I do have a bit of experience studying engineering. I think it might be physically possible, yes, but I don't know what the standards are regarding plumbing. If you think that having a bottom-mounted handle would violate standards, feel free to quote them.
Comment: Who said anything about standards???  I'm talking about practical implementation and, since you played the card I'll mention I don't just have  a bit of experience studying engineering, I'm a degreed engineer with 30 years product development.    Your two ideas of 'how this could be done' are impractical.   Screws in a slot would mean the handle is never 'tight' because the screws couldn't hold it down w/o a little wiggle (fail) and running a screw through the axis can't work because the valve stem is there (fail).    "Physically possible" doesn't mean it's practical.
Comment: Any engineer with half a brain would also realize that any sort of 'bottom mount' on the handle would attract goop and water, and the fasteners would get gummed up and corroded fast.  Have you ever taken a faucet off a sink?  They're disgusting.  And getting at the faucet from underneath usually means twisting your body in contortions, working in cramped spaces. It also would cost a whole lot more than injection molding a snapfit.  It's just a bad idea. Unless the engineers goal was to create a failed product. Find ANY EXAMPLE of what you describe, and I'll recant it all.  But you won't....
Comment: See Kris' link to the a previous Stack Ex question below.   What was the solution there???
Comment: "Your two ideas of 'how this could be done' are impractical." Design is an iterative process; I was just throwing a couple of ideas out there. You could also do something like having a fastener around the axle underneath mount that is screwed shut. As for a single example... how about this, maybe? https://www.camperid.com/valterra/single-piece-kitchen-faucet-mpn-pf211323.html?view=702056#features A single-piece faucet intended for use in the outdoors.
Comment: What makes you think those handles don't  pop off so the valve seat & washer can be serviced???       Also occurred to me ....  If a faucet worked as you suggest, to remove or install the handles would require a second person to hold the handle while person #1 was under the sink with tools.   "Impractical"    After 120 years of manufacturing faucets, what you describe probably HAS been implemented at some point.   And quickly discovered it was impractical.    I also edited my original answer so it doesn't offend your sensibilities....
Answer:

I think I see the set screw at the base if the handle.
Usually a small Allen wrench.
Comment: No, those are just reflections. There are no screws anywhere on the outside--I looked all over, felt everywhere for them, on the knobs, on the base.
Comment: In the early 1970s I encountered a kitchen faucet that did not have replaceable valve seats! Is it possible that these handles are pressed on and are not removable?
Comment: Oh my bad.  Is this plastic or metal under the chrome?
Comment: All good. They sound metallic.
Comment: https://diy.stackexchange.com/questions/78912/how-to-remove-the-handles-from-this-faucet.    Check this similar question out


Setting IsUnicode to false for all types in Entity Framework Core 6

Question: In normal Entity Framework you could use the code
modelBuilder.Properties<string>().Configure(c => c.IsUnicode(false));
to set all created column times to a non-unicode version. I am working in EF Core 6 and trying to do this but modelBuilder does not have a Properties attribute and I am not finding any solutions that parting to EFCore 6 when searching around Has doing this universially been droped and I must specify it for every column now or is there a hidden method some where I am not seeing?
Answer: You can set all string properties to be non-unicode by default via pre-convention model configuration:
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    configurationBuilder.DefaultTypeMapping<string>(
        b => b.HasColumnType("varchar(max)").IsUnicode(false));
}

Alternative:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var property in modelBuilder.Model.GetEntityTypes()
                 .SelectMany(e => e.GetProperties()
                     .Where(p => p.ClrType == typeof(string))))
    {
        property.SetIsUnicode(false);
    }
}


How to use paper prototyping on an existing product

Question: Paper prototyping is a very powerful tool early on in a new product build as it helps you to iron out ux and rapidly iterate.
However if you're working on an existing product and want to test small feature changes, adding fields to a form for example, or changing the layout of features should you consider paper prototyping as an option and if so how? Are there better methods of testing/building iteration...
FYI: This is inside a startup using lean-startup and user testing experiments each week
Answer: There isn't a right way to do prototyping.  People feel most comfortable with a range from paper prototypes to high fidelity Photoshop mockups.  It all depends on the person doing them and their skills and preferences.
My usual method is to:

Always start with paper / whiteboard sketches regardless of whether it's a new product or an iteration on an existing one.  I find that it gives me the freedom to not think about the tool, and so it lets me focus on the problem.
Once I think there is a winner idea, I move it to interactive wireframes, which I also use for initial user testing.
Build the interface in whatever makes the most sense for the project and do more user testing.
Iterate between stages until done.

You will find a lot of variation between people.  Just try a few different things, and settle on what works best for you rather than try to copy the way that person x or person y does it.
Answer: The goal is to get feedback as quickly and accurately as possible.
Paper prototyping is a great tool for rapid feedback - but it's not necessarily always the fastest way.
Choose the fastest way.
Some examples:

If I don't have any existing interface, I'll just jump to paper prototyping. That's going to be faster than building something.
I've got a build web app in a vaguely sane dev setup. I want to test how a new  font choice and header layout effects usage. Adding in some CSS on a dev branch of the app is almost certainly going to be faster than mocking up the existing app on paper
I've got a built web app and I want to try out a new style of interaction on a page. That involves some serious dev time to do, but mocking up the existing app on paper would be a bit of a pain. I might do a bit of both and print out a few pages from the existing app and then paper prototype the new interaction on top of those to provide context.
Answer: The very first step is to sketch your idea on a sheet of paper. If you consider yourself to be a bad artist - don't let that stop you. A paper prototype isn't about art, it's about presenting the idea in a simplified way.
Take a sketchbook and a pen and try to put your idea on paper. To make it more visual, you can use a sketchbooks with phones templates on every page, or download and print such templates. This allows you to get a clear view of how the app will look on the device screen.
It is important to sketch all the screens of the app to get a clear structure. If your product  includes many screens - present them on a single page, and add the connections.
A pen-and-paper sketch is just a draft for an interactive prototype. So, at this stage, you should pay more attention to key items and their placement and not to the detailed design. The UI of the future app or website is born right now.
Besides the pictures, you can sketch additional information that will be helpful for the project. Describe your buyer personas - the potential clients who will pay to use your product. Describe the possible user journey through the application, their steps and their impressions. And remember, you aren't writing a novel, so don't aim for perfection in your writing. A paper prototype is just a raw visualization of your thoughts.
Why are paper prototypes good?
Firstly, you can make them anytime, anywhere. Traveling on a train, walking the dog, watching the morning show - an idea can hit you unexpectedly. If you have a notepad and a pen, you are fully equipped for your first prototype. If not, check for other available material. Maybe you can grab several napkins from the nearest KFC.
Secondly, you don't need any background in programming or design to know how to make a paper prototype. An understanding of your future product is enough.
Thirdly, prototypes cost you almost nothing. You don't need expensive devices and prototyping tools to sketch the first model of your app. You won't have to pay anyone for making the prototype for you. Yes, it will take you some time, but believe me, you would spend much more time explaining what you actually to a developer.
With a bit of creativity, your paper prototype can become interactive.
After the first paper prototype is ready, you can start showing it to other people. The visual presentation of your idea might be quite helpful for finding like-minded people, who will potentially join your team.


Matlab code to transfer between gregorian-hijri calendars

Question: Is there a Matlab code that transfer the date ( day,month,year) from gregorian
to Hijri (Islamic) calendar and also from hijri to gregorian calendar,
Let's assume that we want to change the gregorian date:
Friday, 18 / 11 / 2011
to the Hijri date which is Friday 22 / 12 / 1432
Thanks
Comment: Please see the discussion here: http://www.mathworks.com/matlabcentral/newsreader/view_thread/146181. It says "The Hirji calendar is different for different locations.
There is therefore no generalized conversion algorithm possible, only historical data tables relating to some particular location."
Comment: Thanks for your reply. Yes, it is known that Hijri calendar depends on moon and the converting between the two calendars have a maximum error of one day as seen from many converter programs in the internet. I want the formula of this conversion. Also, I found a java script in this link:                                                               http://stackoverflow.com/questions/5177598/how-to-convert-gregorian-date-to-hijri-date                                                                    but I don't know ho translate it to Matlab. regards
Comment: I also googled but couldn't find a ready-to-use code for that. I guess you will be the first :)
Comment: I think the code is already written in the above link but it is based on java, I will try to translate it to Matlab.
Answer: If you are on Windows, you could use the .NET Framework from inside MATLAB.
Here is a function to convert Gregorian dates to Hijri (based on an article on CodeProject):
<code>function out = GregToHijri(str, frmtIn, frmtOut)
    % English (US) and Arabic (Saudi Arabia) cultures
    enCult = System.Globalization.CultureInfo('en-US',false);
    enCult.DateTimeFormat.Calendar = System.Globalization.GregorianCalendar();
    arCult = System.Globalization.CultureInfo('ar-SA',false);
    arCult.DateTimeFormat.Calendar = System.Globalization.HijriCalendar();

    % parse using supplied input format
    dt = System.DateTime.ParseExact(str, frmtIn, enCult.DateTimeFormat);

    % convert datetime as formatted string
    out = char( dt.ToString(frmtOut, arCult.DateTimeFormat) );
end
</code>
Tested on your input:
<code>>> GregToHijri('Friday, 18/11/2011', 'dddd, dd/MM/yyyy', 'dd/MM/yyyy')
ans =
22/12/1432
</code>


Django elasticsearch transport error no query found

Question: I followed tutorial on:
http://krzysztofzuraw.com/blog/2016/haystack-elasticsearch-part-two.html
http://www.techstricks.com/django-haystack-and-elasticsearch-tutorial/
Everything works fine but when i try to query something from the search box it shows no result found and in the console this error appears.
<code>INFO base GET http://127.0.0.1:9200/haystack/_mapping [status:200 request:0.015s]
INFO base PUT http://127.0.0.1:9200/haystack [status:400 request:0.018s]
INFO base PUT http://127.0.0.1:9200/haystack/_mapping/modelresult [status:200 request:0.023s]
WARNING base GET http://127.0.0.1:9200/haystack/modelresult/_search?_source=true [status:400 request:0.005s]
Failed to query Elasticsearch using '(a)': TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
Traceback (most recent call last):
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search
    _source=True)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/utils.py", line 71, in _wrapped
    return func(*args, params=params, **kwargs)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/__init__.py", line 569, in search
    doc_type, '_search'), params=params, body=body)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/transport.py", line 327, in perform_request
    status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/http_urllib3.py", line 124, in perform_request
    self._raise_error(response.status, raw_data)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/base.py", line 122, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
ERROR elasticsearch_backend Failed to query Elasticsearch using '(a)': TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
Traceback (most recent call last):
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search
    _source=True)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/utils.py", line 71, in _wrapped
    return func(*args, params=params, **kwargs)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/__init__.py", line 569, in search
    doc_type, '_search'), params=params, body=body)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/transport.py", line 327, in perform_request
    status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/http_urllib3.py", line 124, in perform_request
    self._raise_error(response.status, raw_data)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/base.py", line 122, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
WARNING base GET http://127.0.0.1:9200/haystack/modelresult/_search?_source=true [status:400 request:0.003s]
Failed to query Elasticsearch using '(a)': TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
Traceback (most recent call last):
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search
    _source=True)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/utils.py", line 71, in _wrapped
    return func(*args, params=params, **kwargs)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/__init__.py", line 569, in search
    doc_type, '_search'), params=params, body=body)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/transport.py", line 327, in perform_request
    status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/http_urllib3.py", line 124, in perform_request
    self._raise_error(response.status, raw_data)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/base.py", line 122, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
ERROR elasticsearch_backend Failed to query Elasticsearch using '(a)': TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
Traceback (most recent call last):
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search
    _source=True)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/utils.py", line 71, in _wrapped
    return func(*args, params=params, **kwargs)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/__init__.py", line 569, in search
    doc_type, '_search'), params=params, body=body)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/transport.py", line 327, in perform_request
    status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/http_urllib3.py", line 124, in perform_request
    self._raise_error(response.status, raw_data)
  File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/base.py", line 122, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
[29/Oct/2016 10:10:28]"GET /search/?q=a HTTP/1.1" 200 22675
</code>
Comment: I am getting the same. Find an answer?
Comment: Are you trying Elasticsearch 5.0? If so, try 2.4, solved it for me.
Answer: I set up elasticsearch 2.3.1 instead of 5 and it's worked! I think the answer is:

We don't support 5.0 yet, but I'll try to get ahead of it

from github


Knime - How to use path input and output as variable

Question: This seems a quite simple question but I could not find a straight question.
Scenario
I have a workflow in Knime that reads a file (excel), processes and outputs to several files. The input files and output file are in the same folder and its a different folder than the one where the knime workflow is.
I want to run this workflow in several different folders. Each folder has the same input file and the output files will always have the same name.
Now, I need to change manuallly the path to the folder in every input/output nodes, for each different folder.
Possible solution
A variable with the path of the folder. To run the workflow on another folder, I would change that variable only. Is that possible in knime? How?
Answer: You can use the Java Edit Variable node to append the same filename to the flow variable containing the path of the actual folder (both for input and output files).
Not sure how you would like to change the input folders, in case manually, you are done, you can use the QuickForms nodes for selection (from the Labs for Wrapped nodes). For multiple folders within a folder, you might use the List Files node.
To set the parameters using flow variables, first you have to specify a value for them, after that you can adjust the values in the Flow variables tab of each node.
Comment: I've created a worfflow variable named "PATH" with the path of the folder. And tried to use it in as XLS_Locationa in Flow Variables of the XLS Reader node. But didn't work. Note: I'm a basic user of knime....
Comment: You need to use the `Java Edit Variable` node with a code similar to this:
`out_xlsPath = c_PATH + "/yourExcelFile.xls";` to create a flow variable that matches the path of your xls file, not its folder. Now you can use that flow variable in the XLS Reader node.
Answer: Solution
The XLS Reader node can not use a variable as input (diferrent from csv importer, for example).
So, i select the input file manually and pass the XLSLocation as a variable to  Java Edit Variable. Here, I substring the path of the input file and concatenate the name of the outputfiles. Those are outputed as a variable that is then used on the output nodes.
Comment: Not just the CSV Importer, but _every_ node (with modifiable settings) can be adjusted through the flow variables tab, not just those that have a special button for it on the regular settings tab.
Comment: No, nothing special. You need to create a flow variable just like you did in your solution (like with Java Edit Variable), go to the XLS Reader node's `Flow Variables` tab and select from the dropdown menu besides the `XLS_LOCATION` option the flow variable you have created. (Note that the flow variable expects a path, not a URI in case that is what CSV Importer expects.) You need to connect the flow variable to the XLS Reader node though using a red line (as you can see that in many examples).


Can't connect to the internet (LAN) on Ubuntu Server 15.10

Question: After installing Ubuntu server 15.10, I am unable to reach the Internet and do not have an IPv4 address. ifconfig only shows lo, but if I type in ifconfig -a, it also shows enp1s0f0, which matches up to the internal ethernet port, but it doesn't have an IP address. I skipped around the steps in the installer, though I did auto-configure DHCP...
As far as I can tell, "enp1s0f0" seems to correspond to virtual machines, on CentOS/Red Hat, and I'm not sure why it's this instead of eth0...
I have tried renaming it to eth0 (fwiw), but a reboot wiped that out. I also tried adding auto-config code to /etc/network/interfaces, but no luck with that, either.
EDIT: Here's the interfaces file, more or less:
"# The loopback..."
auto lo
iface inet loopback
"# eth0"
auto enp1s0f0
iface enp1s0f0 inet dhcp
Also, I unplugged the Ethernet and plugged it into a Thunderbolt to Ethernet adapter, which Ubuntu recognizes, still no Internet... Plugged it back into internal Ethernet port, now Internet works. I don't know why. I'd still like to know about the enp1s0f0 interface, why it's not "en0" and how it's different.
Comment: Please edit your question to show your `/etc/network/interfaces` file.
Comment: Does `sudo dhclient -4 -v enp1s0f0` allow you to get an IP address at all?
Comment: Also, Ubuntu now follows the Predictable Network Interface Naming standard, too.  ([Details on the standard, from freedesktop.org](http://www.freedesktop.org/wiki/Software/systemd/PredictableNetworkInterfaceNames/))
Comment: Ah gotcha, I figured it was a new thing in 15.10, I just didn't know what to search for (now I know PNIN is a thing!)
Comment: I am able to get an IP address now, I'm not sure why I wasn't before. Thanks for your assistance.
Answer: As Thomas W mentioned, the naming scheme (enp1s0f0) replaced the old one (en0) in 15.10 and it is not indicative of any issues.
I wish I knew exactly what I did to get an IP address (and therefore on the Internet), but I make those edits to the interfaces file (the part for "en0"), rebooted (still no luck), plugged in a Thunderbolt to Ethernet adapter (still no luck), plugged the ethernet cable back into the internal Ethernet port, had internet.


How many subgroups does $\mathbb{Z}_5$ have

Question: How many subgroups does $\mathbb{Z}_5$ have (addition)?
here is my Cayley table (sorry for the formatting):
$\ \ \ 0\ 1\ 2\ 3\ 4\
\\
0\ 0\ 1\ 2\ 3\ 4
\\
1\ 1\ 2\ 3\ 4\ 0
\\
2\ 2\ 3\ 4\ 0\ 1
\\
3\ 3\ 4\ 0\ 1\ 2
\\
4\ 4\ 0\ 1\ 2\ 3
$
So I think that there are 5 subgroups because each row contains all the possible entries. Is this right?
Answer: For $p$ prime, $\langle \mathbb Z_p, +\rangle $ has only two subgroups: the trivial group $\{0\}$, and $\mathbb Z_p$ itself.
If $G$ is a group, then you will find that each row and each column contain every group element exactly once. So that feature, when seen in a Cayley table, gives no information as to how many subgroups a group contains.


Upgrading to 3.18 kernel causes wireless not to work

Question: So I got the 3.18 kernel working on my system (I can boot into Unity now: hooray!). Unfortunately, this seems to have broken my wifi. Wired ethernet is still working, but Network Manager isnt recognizing any wireless networks, whereas it worked fine (comparatively speaking) on the 3.13 kernel I upgraded from.
Checking the "Additional Drivers" app says that I am using the Broadcom 802.11 Linux STA wireless driver source from bcml-kernel-source, which is the same thing it said for when I was on the 3.13 kernel.
I'm on a Macbook pro, 64-bit. Can anyone help me out with this?
Answer: Ok, so I finally got this working. My solution was to run the instructions I found on this website
sudo apt-get update
sudo apt-get install firmware-b43-installer

and then to unload all wireless drivers using
sudo modprobe -r b43 bcma
sudo modprobe -r brcmsmac bcma
sudo modprobe -r wl

and then finally to reload the working driver with
sudo modprobe b43

NOTE: The "Additional Drivers" Program still lists my wireless card as "not working." As I am currently typing this from my laptop on wireless, I can happily verify that this is completely false


printing bot messages discord.py

Question: Are there any changes in discord.py ?
Since yesterday my bots doesnt work.
They were supposed to mention someone when another bot writes someting
async def on_message(message):
    if message.author.id == 123456789: #any bot ID
        if message.content.startswith(
            "Alright"): #message
            await message.channel.send("<@123213213321231> look")
print("Done")

I tried to print messages from specific channel to see if there are any changes in bots messages but i cant even print them..
async def on_message(message):
    if message.channel.id == 123456789:
        print(message.content)

Carlbot for example - it prints my messages but carlbot messages are blank space...
abc
!lock

!unlock

?remindme 1min blahblah

I didnt change anything it was working for over a month and suddenly it doesnt and i have no idea why.
Comment: Are you using a self-bot?
Answer: Do you have intents enabled?
(from d.py server!)
What are intents?
As of 2020-10-28, discord requires users declare what sort of information (i.e. events) they will require for their bot to operate.
This is done in the form of intents.
You can read more about intents here: https://discordpy.readthedocs.io/en/latest/intents.html
By default some intents such as members and presences are disabled as they are what is referred to as privileged.  Meaning you'll need to take some extra steps to support them.
Read up on privileged intents here: https://discordpy.readthedocs.io/en/latest/intents.html#privileged-intents
If you use on_member_* events in your code, without changes your bot will not function anymore!
Steps on how to enable them:
1 - in code
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=...., intents=intents)

2 - on discord developer portal
applications > yourApplication > bot > scroll down then check these https://i.stack.imgur.com/EtACo.jpg (only ones you need!)

printing bot messages discord.py