Form validation not working in bootstrap select option live search

Question: Form validation not working in my select option live search but text box's successfully  validated

Access Level
        <select class="form-control selectpicker" name="access" data-live-search="true" required><option value="">--Select--</option>
                <option value="0">Yes</option>
                <option value="1">No</option>
            </select>

Any one help me please.
Answer: Looks like a syntax error
Check demo here
HTML:

  <form class="well form-horizontal" action=" " method="post" id="contact_form">
    <fieldset>

      <legend>Contact Us Today!</legend>

        First Name

            <input name="first_name" placeholder="First Name" class="form-control" type="text">

        Last Name

            <input name="last_name" placeholder="Last Name" class="form-control" type="text">

        E-Mail

            <input name="email" placeholder="E-Mail Address" class="form-control" type="text">

        Phone #

            <input name="phone" placeholder="(845)555-1212" class="form-control" type="text">

        Address

            <input name="address" placeholder="Address" class="form-control" type="text">

        City

            <input name="city" placeholder="city" class="form-control" type="text">

        State

            <select name="state" class="form-control" required>
      <option value=" " >Please select your state</option>
      <option>Alabama</option>
      <option>Alaska</option>
      <option >Arizona</option>
      <option >Arkansas</option>
      <option >California</option>
      <option >Colorado</option>
      <option >Connecticut</option>
      <option >Delaware</option>
      <option >District of Columbia</option>
      <option> Florida</option>
      <option >Georgia</option>
      <option >Hawaii</option>
      <option >daho</option>
      <option >Illinois</option>
      <option >Indiana</option>
      <option >Iowa</option>
      <option> Kansas</option>
      <option >Kentucky</option>
      <option >Louisiana</option>
      <option>Maine</option>
      <option >Maryland</option>
      <option> Mass</option>
      <option >Michigan</option>
      <option >Minnesota</option>
      <option>Mississippi</option>
      <option>Missouri</option>
      <option>Montana</option>
      <option>Nebraska</option>
      <option>Nevada</option>
      <option>New Hampshire</option>
      <option>New Jersey</option>
      <option>New Mexico</option>
      <option>New York</option>
      <option>North Carolina</option>
      <option>North Dakota</option>
      <option>Ohio</option>
      <option>Oklahoma</option>
      <option>Oregon</option>
      <option>Pennsylvania</option>
      <option>Rhode Island</option>
      <option>South Carolina</option>
      <option>South Dakota</option>
      <option>Tennessee</option>
      <option>Texas</option>
      <option> Uttah</option>
      <option>Vermont</option>
      <option>Virginia</option>
      <option >Washington</option>
      <option >West Virginia</option>
      <option>Wisconsin</option>
      <option >Wyoming</option>
    </select>

        Zip Code

            <input name="zip" placeholder="Zip Code" class="form-control" type="text">

        Website or domain name

            <input name="website" placeholder="Website or domain name" class="form-control" type="text">

        Do you have hosting?

                                    <input type="radio" name="hosting" value="yes" /> Yes

                                    <input type="radio" name="hosting" value="no" /> No

        Project Description

            <textarea class="form-control" name="comment" placeholder="Project Description"></textarea>

Success  Thanks for contacting us, we will get back to you shortly.

          <button type="submit" class="btn btn-warning">Send </button>

    </fieldset>
  </form>

JS:
$(document).ready(function() {
    $('#contact_form').bootstrapValidator({

      fields: {
        first_name: {
          validators: {
            stringLength: {
              min: 2,
            },
            notEmpty: {
              message: 'Please supply your first name'
            }
          }
        },
        last_name: {
          validators: {
            stringLength: {
              min: 2,
            },
            notEmpty: {
              message: 'Please supply your last name'
            }
          }
        },
        email: {
          validators: {
            notEmpty: {
              message: 'Please supply your email address'
            },
            emailAddress: {
              message: 'Please supply a valid email address'
            }
          }
        },
        phone: {
          validators: {
            notEmpty: {
              message: 'Please supply your phone number'
            },
            phone: {
              country: 'US',
              message: 'Please supply a vaild phone number with area code'
            }
          }
        },
        address: {
          validators: {
            stringLength: {
              min: 8,
            },
            notEmpty: {
              message: 'Please supply your street address'
            }
          }
        },
        city: {
          validators: {
            stringLength: {
              min: 4,
            },
            notEmpty: {
              message: 'Please supply your city'
            }
          }
        },
        state: {
          validators: {
            notEmpty: {
              message: 'Please select your state'
            }
          }
        },
        zip: {
          validators: {
            notEmpty: {
              message: 'Please supply your zip code'
            },
            zipCode: {
              country: 'US',
              message: 'Please supply a vaild zip code'
            }
          }
        },
        comment: {
          validators: {
            stringLength: {
              min: 10,
              max: 200,
              message: 'Please enter at least 10 characters and no more than 200'
            },
            notEmpty: {
              message: 'Please supply a description of your project'
            }
          }
        }
      }
    })

  });

Comment: sorry normal select option working but autocomplete(select2) not working
Comment: @HariKannan which plugin are you using for live search or autocomplete. It will be good if you replicate the problem in codepen or jsfiddle.
Comment: I am using bsselect [here]https://silviomoreto.github.io/bootstrap-select/examples/#live-search
Comment: @HariKannan I have updated my demo link, Its working fine with the plugin


Why is dividing the radical in the denominator flipping my function in the negative domain?

Question: Have this function:
$$f(x) = \frac{x}{\sqrt{x^2+2x}}$$
And for whatever reason I decide to divide both the numerator and denominator by $x$:
$$f(x) = \frac{1}{\sqrt{1+\frac{2}{x}}}$$
My understanding is that the function is equivalent because dividing both parts by the exact same value doesn't change it algebraically.
And yet, when I look at the graphs, something strange happens with minus infinity:
The original:

The modified one:

The positive domain is the same it seems - it only appears flipped in the negative domain. My original understanding was that if the functions were algebraically the same, the graphs should be identical. But it appears that my division messed it up somehow.
Why is the negative domain flipped because of my division?
Answer: Because, for all $x\in(-\infty, -2)\cup (0,\infty)$, $\sqrt{x^2+2x}=\lvert x\rvert\sqrt{1+\frac2x}$, as opposed to your suggestion $x\sqrt{1+\frac2x}$.
Comment: Which means that if instead of dividing the numerator and denominator by $x$ I divide them by $|x|$, it will work as expected? (I just tested and yeah the graphs now look the same, just wanted to confirm if this was a valid way to do it)
Comment: Yes.${}{}{}{}{}$
Answer: I think you have done the following steps:
$ \frac{\sqrt{x^2+2x}}{x}= \sqrt{\frac{x^2+2x}{x^2}}.$
But this is only valid for $x>0$, since $ \sqrt{x^2}=|x|.$
Answer: You are not dividing both the numerator and denominator by $x$, but by $|x|$(that is, $\sqrt{x^2}$).
Answer: By forcibly putting $\frac1x$ into the square root, you need to consider $\pm\sqrt{\frac{1}{x^2}}$.
Otherwise, the below is correct:
$$f(x)=\frac{x}{\sqrt{x^2+2x}}=\frac{1}{\frac1x\sqrt{x^2+2x}}.$$


pycrypto with multiple users in virtual environment

Question: I'm using Paramiko (which depends on PyCrypto) on Windows in a virtual environment.
Because I'm on Windows, I don't have a C compiler by default, so I got the windows executable from XXX, and installed it using:
workon myenv
easy_install pycrypto-2.6.win32-py2.7.exe
python myscript.py

And everything worked for me.
Now my colleague (Steve) would like to use the same program, so he does:
workon myenv
python myscript.py

and it fails with "ImportError: no module named Crypto".  Which is odd.  What is odder is that if Steve easy_installs the PyCrypto module, he can use it, but I can't.  The library only seems to work for the person who installed it.
Any idea what I'm missing?
Answer: You're using virtualenvwrapper, which creates virtualenv directory in .virtualenvs inside users' home directory by default. ([WORKON_HOME][1])
Users' home directories are not shared. So other user cannot use your virtualenv.
Make a virtualenv in a directory that your friend can access.
virtualenv /some/shared/virtualenv-dir

And let other user activate it:
/some/shared/virtualenv-dir/activate

If you want to use virtualenvwrapper, you and other users need to set WORKON_HOME environmental variable to a shared directory. (Not sure this also apply for win32 version of virtualenvwrapper you're using)
Comment: good thinking (I forget that we're using virtualenvwrapper).  sadly, we both have WORKON_HOME=c:\python-envs in our environments.  I also had Steve go directly to the scripts directory and "activate", but we're getting the same problem.


VBA: Error 3265 - "Item not found in this collection"

Question: In Access 2016 I'm trying to open a recordset and save data from it in other variables, but I keep getting this error.
The program itself has more parts, but I only get error in this one, it just update data on its database.
This is my code:
Option Compare Database
Option Explicit

Private Sub btnValidateTimesheet_Click()

    ' Update timesheet to "Justificat"

    Dim intIdTimesheet As Integer

    If IsNull(cmbDraftTimesheets.Value) Then
        MsgBox("You have to select a timesheet that is Borrador")
        Exit Sub
    End If

    intIdTimesheet = cmbDraftTimesheets.Column(0)

    DoCmd.SetWarnings False
    DoCmd.RunSQL "update Timesheets set estat = ""Justificat"" where id=" & intIdTimesheet
    DoCmd.SetWarnings True

End Sub

Private Sub btnValidateTimesheetLines_Click()

    ' We select the timesheet_lines for employee, project, activity and dates selected
    ' For each justification, a new "Justificat" Timesheet is generated which hang timesheet_lines

    ' ------------------------------- Variables -------------------------------
    Dim dictTsLines As Object
    Set dictTsLines = CreateObject("Scripting.Dictionary")

    ' Form inputs
    Dim intCodTreb As Integer
    Dim strCodProj As String
    Dim dateInici, dateFi As Date
    Dim intExercici As Integer

    ' Query strings
    Dim strSQLFrom, strSQLWhere As String
    Dim strSQLCount, strSQLJustAct, strSQLTsLines As String

    ' Recordsets
    Dim rsCount, rsJustAct, rsTimesheets, rsTsLines As Recordset

    ' Aux and others...
    Dim continue As Integer
    Dim intIdJustificacio, intIdTs As Integer
    Dim strActivitat As String

    ' --------------------------------------- Main ---------------------------------------------
    ' Taking form data
    intCodTreb = cmbTreballador.Column(0)
    strCodProj = cmbProjecte.Column(1)
    dateInici = txtDataInici.Value
    dateFi = txtDataFi.Value

    ' We check the dates are correct
    If IsNull(dateInici) Or IsNull(dateFi) Then
        MsgBox("Dates can't be null")
        Exit Sub
    End If

    If dateFi < dateInici Then
        MsgBox("Start date must be earlier or the same as final date")
        Exit Sub
    End If

    If year(dateInici) <> year(dateFi) Then
        MsgBox("Dates must be in the same year")
        Exit Sub
    End If

    intExercici = year(dateInici)

    ' Make of the clause FROM and WHERE of the select query of timesheet_lines
    strSQLFrom = " from (timesheet_lines tsl " & _
        " left join timesheets ts on tsl.timesheet_id = ts.id) " & _
        " left join justificacions j on j.id = ts.id_justificacio "

    strSQLWhere = " where ts.estat = ""Borrador"" " & _
        " and tsl.data >= #" & Format(dateInici, "yyyy/mm/dd") & "# " & _
        " and tsl.data <= #" & Format(dateFi, "yyyy/mm/dd") & "# "

    If Not IsNull(intCodTreb) Then
        strSQLWhere = strSQLWhere & " and tsl.cod_treb = " & intCodTreb
    End If

    If Not IsNull(strCodProj) Then
        strSQLWhere = strSQLWhere & " and j.cod_proj=""" & strCodProj & """ "
    End If

    ' Alert how much timesheet_lines are going to be validated
    strSQLCount = "select count(*) " & strSQLFrom & strSQLWhere
    Set rsCount = CurrentDb.OpenRecordset(strSQLCount)
    Continue Do = MsgBox( rsCount(0) & " registries are going to be validated" & vbNewLine & _
        "Do you want to continue?", vbOKCancel)

    If continue <> 1 Then
        Exit Sub
    End If

    ' We select the tuples Justificacio, Activitat of timesheet_lines selected
    strSQLJustAct = "select distinct ts.id_justificacio " & strSQLFrom & strSQLWhere
    Set rsJustAct = CurrentDb.OpenRecordset(strSQLJustAct)
    Set rsTimesheets = CurrentDb.OpenRecordset("Timesheets")

    ' A new timesheet is generated for each tupla
    Do While Not rsJustAct.EOF
        intIdJustificacio = rsJustAct(0)
        strActivitat = rsJustAct(1)

        rsTimesheets.AddNew
        rsTimesheets!data_generacio = Now()
        rsTimesheets!estat = "Justificat"
        rsTimesheets!Id_justificacio = intIdJustificacio
        rsTimesheets!activitat = strActivitat
        rsTimesheets!data_inici = dateInici
        rsTimesheets!data_fi = dateFi
        rsTimesheets!exercici = intExercici
        intIdTs = rsTimesheets!Id
        rsTimesheets.Update

        ' We save the related id of the selected timesheet in a dictionary
        dictTsLines.Add intIdJustificacio & "_" & strActivitat, intIdTs

        rsJustAct.MoveNext
    Loop

    ' We select all the affected timesheet_lines and we update the related timesheet using the dictionary
    strSQLTsLines = "select tsl.id, tsl.timesheet_id, ts.id_justificacio, ts.activitat " & strSQLFrom & strSQLWhere
    Set rsTsLines = CurrentDb.OpenRecordset(strSQLTsLines)
    With rsTsLines
        Do While Not .EOF
            .EDIT
            intIdJustificacio = !Id_justificacio
            strActivitat = !activitat
            !timesheet_id = dictTsLines.Item(intIdJustificacio & "_" & strActivitat)
            .Update
            .MoveNext
        Loop
    End With

    rsTimesheets.Close
    Set rsCount = Nothing
    Set rsJustAct = Nothing
    Set rsTimesheets = Nothing
    Set rsTsLines = Nothing

End Sub

Debugger: The error is coming up at the line:
strActivitat = rsJustAct(1)

I checked that the data the recordset is saving exists and it does.
Comment: How does the quoting of strings work: `" where ts.estat = ""Borrador"" " &`. Why one should use two double quotes here?
Answer: Your recordset contains just one column ("select distinct ts.id_justificacio"), but you are trying to read second column strActivitat = rsJustAct(1)
Add requred column to recordset.


Azure Cloud Service Role's instance have access denied errors: "caller was not found on any access policy"

Question: My Azure Cloud Service (classic) has one role with two instances that are receiving access denied errors when trying to access a key vault because a caller that they are using was "not found on any access policy". I don't know who the caller is, but it did provide me with the caller's appid, oid, and iss. How do I find out who the caller is?
I've also looked at this question... do I use one of the accepted answer's procedures to grant the caller access to the key vault?
Thank you for helping!
Answer: You can search the caller by appid when adding a Service Principal to an access policy. I then followed the question that I linked above and it all worked.


How to find find $f(x)$ such that $f'(x)=\sin^2(x)$ & $f\left(\frac{\pi}{2}\right)=\frac{\pi}{4}$?

Question: I need to find $f(x)$ such that $f'(x)=\sin^2(x)$ & $f\left(\frac{\pi}{2}\right)=\frac{\pi}{4}$. How to do it?
Comment: **Hint::** $$\int f'(x) = f(x) + \mathcal C$$ and you can eliminate that $\mathcal C$ using the f(x) value you already know.
Answer: $$f(x)=\int \sin^2{x}dx=\int\dfrac{1-\cos{(2x)}}{2}=\dfrac{x}{2}-\dfrac{\sin{2x}}{4}+C$$
since
$$f(\dfrac{\pi}{2})=\dfrac{\pi}{4}\Longrightarrow C=0$$


How we get and store the editText value in card RecylerView in Android?

Question: Please Give me an Solution I am new in Android, On BindView Holder Code is:
I am using Cards in RecylerView
@Override
    public void onBindViewHolder(SeedlingViewHolder holder, final int position) {

        holder.seedling_CardView.setTag(position);

        if(holder instanceof SeedlingViewHolder) {
            holder.centerUnit.setText("Assigned To : "+placedOrderDetailBeanArray.get(position).eoCenterUnit);
            holder.creationDate.setText("Creation Date :"+placedOrderDetailBeanArray.get(position).orderCreationDate);
            holder.no_bag.setText("No. of Bag :"+placedOrderDetailBeanArray.get(position).noOfBags);
            holder.no_seedling.setText("No. of Seedling :"+placedOrderDetailBeanArray.get(position).noOfSeedling);

          /*  holder.target.setTag(position);
             value=(String) holder.centerUnit.getTag(R.id.seedling_Target_GM);*/

            holder.save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    placedOrderDetailBeanArray.get(position).target = targetVal;
                    Log.v("ORDER DEATIL ***** ",placedOrderDetailBeanArray.toString());
                }
            });
            Log.v("Seeding Adapter","Holder");
        }

    }

My edit Text name is Target an I want to save this value in a Variable so that I can send it on server Later
@Override
    public int getItemCount() {
        return placedOrderDetailBeanArray.size();
    }

    public class SeedlingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView creationDate,completionDate,no_seedling,no_bag,achievement,centerUnit;
        public EditText target;
        public Button save;
        public View seedling_CardView;
        public SeedlingViewHolder(View convertView) {
            super(convertView);
            seedling_CardView = (CardView) convertView.findViewById(R.id.cardViewSeedling_GM);
            seedling_CardView.setOnClickListener(this);

            creationDate=(TextView)convertView.findViewById(R.id.seedling_CreationDate_GM);
            no_seedling=(TextView)convertView.findViewById(R.id.seedling_no_seedling_GM);
            no_bag=(TextView)convertView.findViewById(R.id.seedling_bag_GM);
            centerUnit=(TextView)convertView.findViewById(R.id.seedlingCenterUnit_GM);
            save=(Button)convertView.findViewById(R.id.btnSave_GM);

            target=(EditText)convertView.findViewById(R.id.seedling_Target_GM);
        }

        @Override
        public void onClick(View v) {

        }
    }

Comment: So you just want to get the value from EditText?
Comment: Yes I want to getedit Text value and want to save in a variable
Comment: You can save the value in `SharedPreferences` then get the value when is needed.
Comment: Not need to save i shared preferences @tahsinRupam , You can save your edit text value in array list by using model mechanizm
Comment: Yeah, that's another solution indeed.
Comment: @AbhinavSrivastava can you show me you model code.
Comment: He could always assign a different key for each row. It's just a solution may not be most efficient. Creating model, setting and getting the values might be a better idea.
Answer: First: Create custom wrapper class with setter and getter methods with needed variables
Like This:
public class WrapperClass {

    private String Name;
    private String MaidID;
    private String Phone;

    public WrapperClass(String name,String Phone,String Mail) {
        Name = name;
        this.Phone=Phone;
        MaidID=Mail;

    }

    public String getMaidID() {
        return MaidID;
    }

    public void setMaidID(String maidID) {
        MaidID = maidID;
    }

// Other Variable Getter Setter with constructor of values you want to retrieve

Second:
Create Custom List on Main activity where you have you edit text
List<WrapperClass> Data=new ArrayList<WrapperClass>();

Then call constructor like this
WrapperClass wrap=new WrapperClass(nameEdittext.gettext().toString,MailEdittext.gettext().toString,PhoneEdittext.gettext().toString);

Then Add WrapperClass Object into list
data.add(wrap)

Finally in onBindView Holder get value like this
    wrapperClass = UsersList.get(position);
holder.Name.setText(wrapperClass.getName());

Note:Don't forget to pass custom list as parameter of recyclerAdapter.


Avoid Access Denied when writing to file

Question: I am logging to file with the following method
public static void LogDataContractToFile(string XMLStringToLog, string filePathAndName)
{
    FileInfo fileinfoMaster;
    FileInfo fileinfoLog;
    string fileName = string.Empty;
    int tmpInt = 0;
    filePathAndName = filePathAndName.ToLower();

    while (true)
    {
        lock (LogDataContractToFileLock)
        {
            if (!_workingWithFiles.Contains(filePathAndName))
            {
                _workingWithFiles.Add(filePathAndName);
                break;
            }
        }
        Thread.Sleep(100);
    }

    try
    {
        #region Create XMLFile

        if ((tmpInt = filePathAndName.LastIndexOf('.')) > 0)
            fileName = filePathAndName.Remove(tmpInt, filePathAndName.Length - tmpInt);
        else
            fileName = filePathAndName;

        fileinfoMaster = new FileInfo(fileName + ".xml");
        fileinfoLog = new FileInfo(fileinfoMaster.DirectoryName + "\\" + Path.GetFileNameWithoutExtension(fileinfoMaster.Name) + ".log");

        if ((fileinfoMaster.Exists && !fileinfoLog.Exists) ||
            (!fileinfoMaster.Exists && fileinfoLog.Exists))
        {
            fileinfoMaster.Delete();
            fileinfoLog.Delete();
        }

        //Se så att filen är 50 MB eller mindre annars arkivera
        if (fileinfoMaster.Exists && fileinfoLog.Length > 52428800)
        {
            tmpInt = FileWriter.FileCount(fileinfoLog.DirectoryName, Path.GetFileNameWithoutExtension(fileinfoMaster.Name) + "*.log");
            fileinfoLog.MoveTo(Path.Combine(fileinfoLog.DirectoryName, Path.GetFileNameWithoutExtension(fileinfoLog.Name) + "_" + tmpInt.ToString() + ".log"));
            CreateLogDataMasterFile(Path.Combine(fileinfoMaster.DirectoryName, Path.GetFileNameWithoutExtension(fileinfoMaster.Name) + "_" + tmpInt.ToString() + ".xml"), fileinfoLog.Name);
            fileinfoLog = new FileInfo(fileinfoMaster.DirectoryName + "\\" + Path.GetFileNameWithoutExtension(fileinfoMaster.Name) + ".log");
        }

        if (!fileinfoMaster.Exists)
        {
            DirectoryInfo info = new DirectoryInfo(fileinfoMaster.DirectoryName);
            if (info.Exists == false)
                info.Create();

            CreateLogDataMasterFile(fileinfoMaster.FullName, Path.GetFileNameWithoutExtension(fileinfoMaster.Name) + ".log");
        }

        #endregion

        using (StreamWriter sw = File.AppendText(fileinfoMaster.DirectoryName + "\\" + Path.GetFileNameWithoutExtension(fileinfoMaster.Name) + ".log"))
        {
            sw.Write(XMLStringToLog);
            sw.Flush();
        }
    }
    finally
    {
        lock (LogDataContractToFileLock)
        {
            _workingWithFiles.Remove(filePathAndName);
        }
    }

}

private static void CreateLogDataMasterFile(string filepathAndName, string dataFileName)
{
    XmlTextWriter xmlWriter;
    using (xmlWriter = new XmlTextWriter(filepathAndName, System.Text.Encoding.UTF8))
    {
        xmlWriter.Formatting = Formatting.Indented;
        xmlWriter.WriteStartDocument();
        xmlWriter.WriteDocType("DataLog", null, null, "<!ENTITY data SYSTEM \"" + dataFileName + "\">");
        xmlWriter.WriteStartElement("root");
        xmlWriter.WriteRaw("&data;");
        xmlWriter.WriteEndElement();
        xmlWriter.Flush();
    }
}

Several different threads might write to file at the same time and in some cases they will write to the same file. To avoid problems with access denied, used by other process I have implemented some logic as you can see.
The problem is that I am still getting access denied, used by other process from time to time.
I have looked at the build in tracers like the TextWriterTraceListener and here I can see the following note :

If an attempt is made to write to a file that is in use or
  unavailable, the file name is automatically prefixed by a GUID.

So it looks like even Microsoft has problems with this? Is it a Windows problem? Is there any way to handle this becides generating a new file? Generating a new file will mess of the data flow in files a lot!
Comment: Another option (per @spender answer) is to block callers. I am unsure if you did it correctly, would expect a `lock` around write to file method.
Comment: Im blocking other callers to the same file with the first while and lock code. So if there is already a thread writing to the specific file no other will be able to until it is "checked in" again.
Comment: `lock` before and after writing will not ensure (from my point of view) what 2 or more threads will not be able to pass first lock and won't try concurrently write something into file. E.g. think about locking call to a whole `LogDataContractToFile` method. Lock has to be hold until operation is completed, you are either release it earlier or locking (second `lock`) when it's already too late.
Answer: Yes. Don't write to a file from multiple threads. Create a single thread that is reponsible for file writes, and have it read what to write from a ConcurrentQueue. Any thread that needs to write should just add data to the queue.
Comment: So I should create one thread (and only one) that writes to all files and then have a queue with objects(containing data and file metadata) for this one thread that all other threads places objects in?
Comment: "to write all files"... no not necessarily, but for a single thread to take all responsibility for writing data to a single file, such that it's not possible for two threads to simultaneously write to the same file.
Comment: Okay, so what you suggests is that I have a collection of objects that holds a thread and metadata about that file. When another thread arrives I take out this object, uses the thread in this object and writes to the specific file. The question is what will happen if 2 threads instructs this stored thread to write to a file at the same time? Will I have to handle some kind of synchronization?
Comment: That's why you have the queue. You don't instruct a write, you queue it. The writing thread dequeues write messages one at a time.


Distributing balls into bins randomly

Question: Problem:

If $n$ balls are distributed at random into $r$ boxes (where $r \geq 3$), what is the probability that box $1$ at exactly $j$ balls for
  $0 \leq j  \leq n$ and box $2$ contains exactly $k$ balls for $0 \leq k  \leq n$ ?
Answer:
Let $p$ be the probability that we seek. First we consider a special case. If $j + k > n$ then $p = 0$. Let $p_1$ be the probability that
a ball is placed in box $1$.  Let $p_2$ be the probability that a ball is placed in box $2$. Let $p_3$ be the probability that a ball is placed in box other than box $1$ and box $2$.
\begin{align*}
p_1 &= \frac{1}{r} \\
p_2 &= \frac{1}{r} \\
p_3 &= \frac{r-2}{r}
\end{align*}
Now we have a multinomial distribution.
\begin{align*}
P &= \left( \frac{n!}{j!k!(n-j-k)!} \right) \left( \frac{1}{r}\right) ^j \left( \frac{1}{r}\right) ^k \left( \frac{r-2}{r} \right)^{n - j - k} \\
P &= \left( \frac{n!}{j!k!(n-j-k)!} \right) \left( \frac{1}{r}\right) ^{j+k}  \left( \frac{r-2}{r} \right)^{n - j - k} \\
P &= \left( \frac{n!}{j!k!(n-j-k)!} \right) \frac{ (r-2)^{n-j-k} } {r^n}
\end{align*}
So for example, if we have: $j = 2$, $k = 2$, $n = 8$ and $r = 8$ then
\begin{align*}
P &= \left( \frac{8!}{2!2!(8-2-2)!} \right) \frac{ (8-2)^{8-2-2} } {8^8} = \left( \frac{8!}{4(8-2-2)!} \right) \frac{ (6)^{4} } {8^8} \\
P &= \left( \frac{8!}{4(4)!} \right) \frac{ (6)^{4} } {8^8} =  \left( \frac{8(7)(6)(5)}{4} \right) \frac{ 2^4(3^4) } {8^8} \\
P &= \frac{ 8(7)(6)(5)( 2^4)(3^4) } { 4(8^8) } = \frac{ 2(7)(6)(5)( 2^4)(3^4) } { 4(8^7) } \\
P &= \frac{ 7(6)(5)( 2^4)(3^4) } { 2(8^7) } =  \frac{ 7(6)(5)( 2^3 )(3^4) } { (8^7) }\\
P &= \frac{ 7(6)(5)(3^4) } { 8^6 } = \frac{ 17010 } { 262144 } \\
P &= \frac{8505 } { 131072 } \\
P &\doteq 0.064888
\end{align*}
I think I have it right now. Do I?
Comment: The problem statement has n balls and r boxes, but the question has a limit of r balls per box, and your analysis has $0$ probability for $j+k\gt r$.  You need to clarify.
Comment: Did you mean to write $0 \leq k \leq r$ for box $2$?
Comment: There are some other typos.  For instance, you meant $p_1 = \frac{1}{r}$ and the $m$ in the exponent in your second expression for $P$ should be an $n$.  I assume $p_3$ is supposed to represent the probability that a ball is placed in a box other than boxes $1$ and $2$.  You are missing a factor of $(n - j - k)!$ in the denominator of the multinomial coefficient.  In your example, you are missing a factor of $(8 - 2 - 2)! = 4!$ in the denominator of your multinomial coefficient.
Comment: Following up on herb steinberg's comment, did you mean $0 \leq j \leq n$ and $0 \leq k \leq n$ since you have a total of $n$ balls?
Comment: I believe it is.
Comment: @N.F.Taussig Yes I did. I will fix it.
Comment: @N.F.Taussig That is what I meant. Herb's comments was right on.
Comment: @N.F.Taussig I believe that I have fixed all the mistakes you have found. Is my solution right now?
Comment: @N.F.Taussig I am thinking that you should answer my question, with the answer: I believe it is. Once you do that, I will accept your answer and you will get points.
Answer: You have corrected the mistakes that were your initial solution.  Your work is now correct.

Distributing balls into bins randomly


Find range of possible values for probability of intersection given individual probabilities

Question: If given probability of $A$ is $a$ and probability of $B$ is $b$, how do I find min/max probability of intersection? Max value of intersection would be $\min(a,b)$, how do I find the min?
Answer: if $a+b \le 1$, then presumably one can find disjoint sets $A$ and $B$ with ${\rm P}A = a$ and
${\rm P}B = b$. so in this case, the min is 0.
if $a+b > 1$, we get a smallest intersection by choosing $B$ to contain all of $A^C$, which has probability $1-a$ and then adding to that a piece of $A$ to bring ${\rm P}B$ up to $b$. so the piece of $A$ added in has to have probability $b - (1-a) = a+b - 1$. this last quantity is then the min probability for the intersection when $a+b > 1$.
so in any case. the min is $(a+b-1)^+$.
Comment: your last explanation on finding the smallest intersection can be applied to all cases. Min `A∩B` is `max(a+b-1,0)`
Answer: The min is the smaller of two values: $\min(a,b) = a$ if $a < b$ and $b$ otherwise. Though I do not think this is what you are asking for...
Comment: what? the question says 'blah blah blah would be $min(a,b)$, how do I find the min?' I answered the question.
Comment: @shabbychef I agree; bad questions should be punished with no answers.
Comment: No, that's not what he's asking for. He asked for the min of the intersection, as can be deducted by careful reading of the first of the two sentences in the opening post.
Comment: @mbq - whats wrong with the question?
Comment: @saminny You could have formulated it better so that it would be less ambiguous and easier to understand. shabbychef just pointed it out with his answer.
Comment: before the question was edited to have proper LaTeX, when I answered it, it was very hard to parse. Look at this in plaintext: 'Max value of intersection would be min(a,b). how do I find the min?'
With the proper markup, it is much easier to parse. (Though it looks like a homework question to me...)
Comment: If $a$ and $b$ are sufficiently small, $\min$ could be $0$. E.g. consider a population consisting of 50% cats and 50% dogs. Let $A=\text{animal is a dog}$, $B=\text{animal can retract nails}$. Clearly, $P(A)=P(B)=0.5$ but $P(A\cap B)=0$.


How to add dynamic fields with condition?

Question: I have a website that is about automobiles, I want when a user choose a brand drupal shows some of its models:
This image show an example:
for example I want when a user selected BMW drupal shows BMW's models in other select tag dynamic. and for example selected Lamborghini  drupal shows Lamborghini's models.

I mean a tree stystem
Answer: I would recommend you to use any one of following modules.
Hierarchical Select

This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

Simple hierarchical select

Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Taxonomy Term Reference Tree Widget

This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.
Comment: what are these?
Comment: These are contributed modules that gives you feature of such type of problem, you are facing. Gone through once from any of links, get brief idea of each. Your problem looks like the same that these modules can easily solve.
Answer: You can check the conditionnal fields module which is based on the States API if you want to do this hardcoded.
An other way to do this is by using hierarchical taxonomy and a module like Hierarchical Select even though you might be limited.
Comment: I want editors do it now super user or administrator
Comment: Once the module or your taxonomy is configured then the editors will be able to do this.
Comment: I should test it


Discrete uniform distribution on a finite set

Question: I have a random variable Y which has a discrete uniform distribution on the set {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5}.
I have to find the following:
i) Find P(Y)
ii) P($Y^2$)?
iii) E($Y^2$)
Answers:
The first one's quite easy I guess. Since P(Y) = $\frac{1}{N}$, I got $\frac{1}{10}$ for that.
I'm not sure for the second one. Is it $\frac{1}{5}$? If I square all the terms of X I'll have that N=5. And the third question follows up from the second.
Need someone to verify this.
Comment: Please check http://stats.stackexchange.com/tags/self-study/info and edit your question appropriately
Comment: What is "X" and what exactly do you mean by "P(Y)"?  The entire probability function?
Comment: @whuber the X there is supposed to be a Y (edited) and yes, it's the probability function.
Comment: A specification of a function should state where it takes what values, not just its value when it isn't zero (at least the very least not without an indication of where that is).
Answer: As this is self-study I can only supply hints.  Yes, $P(Y=-5)=P(Y=-4)=\cdots=P(Y=5)=1/10$.  Think of $Y^2$ as a transformation. Although the only possible values for $Y^2$ are 1,4,9,16 and 25, do you think they all have the same probability?
Now once you have the answer to ii) you can get iii) by summing
$iP(Y^2=i)$ for each $i$.


Should installing local Drush and Drupal via Composer on my personal computer be any different than on hosting platform?

Question: Should installing local Drush and corresponding Drupal via Composer on a personal computer with Ubuntu-Apache-MySQL-PHP be any different than on a shared hosting platform?
Should I just do the following in both environments?
cd web_application_root
composer create-project drupal/recommended-project my_site_name_dir
# PHP MYADMIN GUI
# GUI install
composer require drupal/metatag

Answer: Short answer
When installing drupal and drush with composer, you can do it the same way on a shared hosting platform as you do locally-- assuming the shared hosting platform gives you access to the same command-line tools that you have available locally.
Long answer: Use version control
Generally speaking, you want to use composer with git, and you will check in your composer.json and composer.lock files into the git repo.  You would then clone that repo to your local environment + your shared hosting environment.
This way, although you have multiple copies of composer.json and composer.lock, they are all managed via the git repo, so it is much easier to sync changes between your local environment and the shared hosting server.
Comment: Thank you, and I appreciate the "generally speaking" as Git might be an overkill for me because I aim to create just one Drupal website, for myself (no team members), for my personal services, only core with Metatag module, only text, updated directly online.
Comment: Not using version control is a huge mistake no matter how few people will be touching it. It is never overkill. Do yourself a favor and use it.
Comment: @drupal_love I develop everything by myself, but I do use git on all my projects now.  It really comes in handy when you need to do a rollback because something goes wrong with a major upgrade (such as the coming Drupal 10 upgrade this year).  When you're comfortable with version control, it can be set up in less than five minutes-- in my case, it's `git init` the repo and copy my SSH public key file to shared hosting-- so it's really not huge additional overhead.


How can I make Slidingbar's SLIDING_CONTENT work in ActionbarSherlock?

Question: SLIDING_CONTENT parameter means only the content of the Activity sliding when touching,titlebar stays.
When I import ActionbarSherlock, I found it did not work well.
I saw the source code
this is a part of code in class SlidingMenu (attachToActivity)
    case SLIDING_CONTENT:
        // take the above view out of
        View content = activity.findViewById(android.R.id.content);
        ViewGroup contentParent = (ViewGroup) content.getParent();
        contentParent.removeView(content);
        contentParent.addView(this, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        setContent(content);
        // save people from having transparent backgrounds
        if (content.getBackground() == null)
            content.setBackgroundResource(background);
        break;
    }

it works with the Activity which contains titlebar, but you know abs customized titlebar.....
how can i alter something to make SLIDING_CONTENT alive?
thx a lot!!
Comment: witch activity you are extending ?
Comment: I extended SherlockActivity~
Answer: I solved this problem , how fast i am~
:)
Only create a new constructor
public void attachToActivity(Activity activity, int slideStyle,int id)

add a new param 'id' id represent the main activity layout id.
and then change
View content = activity.findViewById(android.R.id.content);

to
View content  = activity.findViewById(id);

and change another function which is calling the old attachToActivity (It is easy)
if you have any question, email me email@example.com


Draw a Card from a Deck for a Monte Carlo Simulation of Poker

Question: At the moment I am working on an iOS-application in which I need to draw random cards from a carddeck. At the moment my Code looks like this:
- (PlayingCard*) drawRandomCard
{
    PlayingCard * randomCard = nil;

    NSUInteger index = arc4random_uniform(self.cards.count);
    randomCard = self.cards[index]; //self.cards is an NSArray of PlayingCard's
    while (randomCard.isUsed) {
        index = arc4random_uniform(self.cards.count);
        randomCard = self.cards[index];
    }
    randomCard.used = YES;
    return randomCard;
}

This methods gets called  a lot (50'000 - 1'000'000 times for one monte-carlo-simulation)!
At the moment the whole thing is way to slow and I need really to optimize it.
I have some Ideas:

faster random number generator
change the whole high-level representation of the deck (Objective-C Class including an NSArray of PlayingCards) and cards (Objective-C Class) to a representation in normal C-Arrays and structs
change the whole representation of the deck and cards to the bitwise level and do everything down there

What do you think?
Do you have any other ideas?
Do you know a better suited (faster) random number generator?
Thanks in advance!
Answer: By randomly looking at the full deck in the loop

while (randomCard.isUsed) {

and not only the ones still in play, you will get a lot of retries when you reach the end of the deck. With the last card (number 52) giving > 25 misses on avareage. Treversing a full deck gives a total of more than 600 misses on average.
In adition to this, you also need to reset your deck before you can use it again. I guess you have a methode that resets the deck by looping through all the cards, and doing a used = NO. This gives 52 operations on the deck even if you only need to deal one card.
You can avoid both problems by this simple solution.
Store all your cards in an array. Then dedicate one end to cards not yet dealt, and the other end to cards that have been dealt:
                                                                                <---------------------- not yet dealt ---------------------->
[ ah 2h 3h 4h 5h 6h 7h 8h 9h 10h jh qh kh ad 2d  ..... jk qk kk ]
                                                               ^
                                                            dealt
                                                            cards

Randomly pick a card (7h) in the range of not yet dealt cards:
[ ah 2h 3h 4h 5h 6h 7h 8h 9h 10h jh qh kh ad 2d  ..... jk qk kk ]
                    ^^

Switch it with the last not yet dealt, and move the dealt card pointer on place left.
  <-------------------- not yet dealt --------------------->
[ ah 2h 3h 4h 5h 6h kk 8h 9h 10h jh qh kh ad 2d  ..... jk qk 7h ]
                                                            ^
                                                           dealt
                                                           cards

Repeat for as long as needed:
  <------------------ not yet dealt ----------------->
[ ah 2h qk 4h 5h 6h kk 8h 9h 10h jh jk kh ad 2d  ..... qh 3h 7h ]
                                                      ^
                                                    dealt
                                                    cards

When you need a new deck, just move the dealt cards pointer back to the end, and the deck is ready for a new use.
  <----------------------- not yet dealt ---------------------->
[ ah 2h qk 4h 5h 6h kk 8h 9h 10h jh jk kh ad 2d  ..... qh 3h 7h ]
                                                               ^
                                                             dealt
                                                             cards

The new order of the deck just adds to the randomness...
Comment: I changed my implementation to this and it works fine! Thanks! Do you have another idea to get more speed?
Comment: So how fast is it now? What part is taking the time?
Comment: So, if you use the solution maybe you could accept the answer?
Answer: Keep a static index pointing to the last card drawn (initially set to -1). Every time the method is invoked, advance the index modulo self.cards.count, and if the result is zero shuffle the deck.  Then return the card at index.  Since a decent shuffle such as Fisher-Yates/Knuth is Theta(self.cards.count) but gets invoked only one time out of self.cards.count, the result is amortized constant time per draw.  This should avoid any overhead due to identifying already drawn values and rejecting.  You could add a reset method if you want to avoid dealing out the whole deck before reshuffling.
Answer: I assume you are calling this method multiple times to draw cards from a deck, setting the used property of the drawn card to YES so that it doesn't get drawn again.
Instead of setting the property, you can just remove the card from the deck and place it in a usedCards array, saving you the potentially never ending while loop.
Another approach would be to shuffle the deck initially, and then draw cards from the beginning or the end of the array.
Comment: The reason for this implementation was, that I have to draw some (2 - 23) cards out of the deck, do some computation and then reset the deck and do all this again and again and again (50'000 - 1'000'000 times)...  So I don't really know if your suggestion leads to a speed up. Because I think that the overhead of creating an NSArray, coping some elements, copy elements back (reset) is bigger than just setting some bools, and setting the bools back for reset... Can you explain why you think it would help?
Comment: It seems that your while loop isn't as much of a bottleneck as I thought (unless the number of drawn cards gets very close to the deck size).


Reset Disk - Windows Storage Server 2012

Question: I set up windows storage server 2012 and have 6 SATA drives in a raid configuration.
Prior to production use I tested by removing drive and adding a spare and rebuilding. That went fine.
Now I see that the original drive can not be reused in the array (and the spare in a different drive slot) unless I presume it is re initialized.
In the same server I had one more sata connector so I am using that and trying to "reset" or "format"  the original drive or the spare.. but the format option does not illuminate (it is disabled) offline option doesn't take off line  but I can toggle from dynamic disk and static disk...
How can I reset the drive w/o finding a different PC?
Comment: Is there still a partition on this disk?
Comment: Yes - I believe so. In Disk Management it shows colored and the legend says "primary partition" after the word healthy it says "Storage Spaces Protective Partition" .. I guess I want to flush that out.
Comment: I think you have to delete the partition before you can reinitialize the disk.
Comment: You could always use some tool to low-level format the drive, then stick it back in the array. GParted is a popular one.
Answer: The solution to clear the disk was:

run diskpart
list disk
select disk 0/1/2...
clean
Answer: <code>run diskpart
list disk
select disk 0
list partition
select partition 3
delete partition
</code>
Comment: It differs because it doesn't answer the question. This would only delete the partition. It won't reset the disk.
Comment: How does this answer differ significantly from the answer Aug 24 2013?


Add metatags import to migration

Question: I have made a migration module to import the full content from a legacy Drupal 6 site to my new Drupal 7 site, using the migrate d2d module. Everything works fine, but I have just discovered that there are many custom meta tags added manually for both nodes and taxonomy in the legacy site (using the Metatags module). The taxonomy meta tags I can deal with manually, but I really would need to figure out how to add the mapping for metatags in my node migration classes. Do I add code in my general migration class in node.inc (that extends DrupalNode6Migration)?
Do I use prepareRow() to fetch info from the database and add this to a mapping with a default value in the new site? As far as I can see there are no fields in the legacy site that holds the metatags (I need title, keywords and description).
If anyone knows how to do this, please help.
Answer: Finally I came up with a solution and I post it here in case anyone else has the same problem. There are two tables in the legacy site named metatags and  metapages, in which you can find everything needed for importing the metatags.
So in my prepareRow() in each node migration class I added these rows, and now the metatags from the legacy Drual 6 site has been imported to my Drupal 7 site :-)
$metapages_path = !empty($row->nid) ? 'node/'.$row->nid : false;
if($metapages_path){
    $meta_title_pid = Database::getConnection($target='default', $key='legacy')->query('SELECT f.title, f.pid FROM {metapages} f WHERE f.path = :path',array(':path' => $metapages_path))->fetchAssoc();
}
$meta_title = !empty($meta_title_pid['title']) ? $meta_title_pid['title'] . ' | [site:name]' : '';
$this->addFieldMapping('metatag_title')->defaultValue($meta_title);
$meta_pid = !empty($meta_title_pid['pid']) ? $meta_title_pid['pid'] : false;
if($meta_pid){
    $meta_keywords = Database::getConnection($target='default', $key='legacy')->query('SELECT f.value FROM {metatags} f WHERE f.name = :key AND f.parent_pid = :pid',array(':pid' => $meta_pid, 'key' => 'keywords'))->fetchAssoc();
    $meta_description = Database::getConnection($target='default', $key='legacy')->query('SELECT f.value FROM {metatags} f WHERE f.name = :key AND f.parent_pid = :pid',array(':pid' => $meta_pid, 'key' => 'description'))->fetchAssoc();
}
$keywords = !empty($meta_keywords['value']) ? $meta_keywords['value'] : '';
$this->addFieldMapping('metatag_keywords')->defaultValue($keywords);
$description = !empty($meta_description['value']) ? $meta_description['value'] : '';
$this->addFieldMapping('metatag_description')->defaultValue($description);

Add metatags import to migration


Breakpoint not being hit after hot module reload

Question: I have a node server running in debug which works fine and hits breakpoints. Also i have hot module replace hooked up.
When changes are made, the HMR updates the files and the changes can be seen. However, now it just skips past the breakpoints.
I'm assuming that when the HMR file is created the debugger doesn't know about the new file eg. main.<hashcode>.js or somehow the link is lost.
Is there any way tell the debugger there is a new file without restarting the debug session?
Maybe some extra config in webpack config eg.
output: {
    path: path.join(__dirname, 'dist', 'server'),
    filename: './main.js'
  }

Answer: You can use watchOptions.ignored
module.exports = {
  //...
  watchOptions: {
    ignored: ['/path/main*.js']
  }
};

Comment: Sorry this made no difference and still skips the breakpoint


Are there any musical pieces that experiment with the frequency - tempo relationship?

Question: I am interested in the relationship between frequency and tempo, both of which measure the same thing (repetitions per unit time) for different ranges (units of time).
Are there any musical pieces that experiment with this concept?
As an example of what I mean, we can work out the tempos that match A:
<code>A4 = 440Hz
A3 = 220Hz
A2 = 110Hz
A1 = 55Hz
A0 = 27.5Hz
A-1 = 13,75Hz
A-2 = 6.875Hz
A-3 = 3.4375Hz
A-4 = 1.71875Hz
A-5 = 0.859375Hz

A-4 * 60 (seconds per minute) = 103.125 BPM and
A-5 * 60  = 51.5626 BPM
</code>
So if we had a sampled A4 and kept transposing down by an octave, 8 octaves later it would be at 103.125BPM.
OR
If we had a sample of something played at 103.125 BPM and we played it on a sampler at increasing octaves, it would eventually be tuned to an A. At least that's what my suspicion is...
Are you aware of any pieces of music that play with this idea?
How does temperament complicate things?
Comment: Adam Neely did [some](https://www.youtube.com/watch?v=mq0z-sxjNlo) [videos](https://www.youtube.com/watch?v=_gCJHNBEdoc) that  explore the effect. I think Stockhausen also used it in some compositions, but I forgot which.
Comment: @leftroundabout Thanks. I'm surprised you didn't put this as an answer because it was exactly what I was asking for.
Answer: Since you've said this:

If we had a sample of something played at 103.125 BPM and we played it on a sampler at increasing octaves, it would eventually be tuned to an A. At least that's what my suspicion is...
Are you aware of any pieces of music that play with this idea?

There's an entire subgenre of electronic music that plays with the idea of speeding up atonal samples so fast they become musical tones. It's called extratone. It doesn't have its own Wikipedia article, but the Wikipedia article on its super-genre, speedcore, puts it like this:

When a song reaches 1000 bpm, the music is known as extratone. However, when beats are in the range of 1000–1500 bpm the individual beats become indistinguishable, and turn into continuous tones.

You can find some extratone songs on YouTube, and they typically string together and speed up drum beats so fast that they sound like notes with strange timbres.


Dados tipo Date

Question: Tenho uma duvida e não sei se é possivel isso no Html.
Dentro de um formulario tenho varios tipos de campos e um deles é o tipo DATE que recebe (Dia/mes/Ano) e agora queria alterar isso para receber apenas (mes/ano).
Consigo fazer essa alteração de forma simples?
Isso uso Jquery e Html

Dados Estatisticos:

    Data:
    <input type="date" name="EstatisticosValidade">

Comment: você está utilizando alguma máscara no campo? usa jquery? acrescente mais detalhes para ajuda-lo.
Comment: Consegue, sim. Mas pra gente poder ajudar, você precisa responder o comentário do Filipe.
Answer: Utilize month no lugar de date. Talvez isso resolva o seu problema.
<input type="month" name="EstatisticosValidade">

Answer: Você pode utilizar dois campos (type month e type number, com valor mínimo e máximo) ou separar por javascript ou php o valor inserido no campo com type date. Eu normalmente uso a segunda opção.

Dados tipo Date


Can't edit Main menu block in sidebar by clicking on "gear"

Question: Today on one of my websites I encountered something strange. I have my "Main menu" block in my left sidebar, and when I hover over that block, the "gear" to edit it shows up, but clicking on it does nothing. Also, on pages that the block wouldn't show up on, it does (rather, the blank space does) with nothing in it, and the gear still shows up and is not clickable.
I tried moving the block out of the region, saving, refreshing, moving it back, saving, and refreshing again to see if that would fix anything, but that has not.
Any help would be greatly appreciated!
Updates:

What I mean by "nothing" is that there is the empty region with my main content area pushed over as if there actually was block content there.
And 3 errors in the console: Uncaught TypeError: Cannot read property 'msie' of undefined panels.js?ndi45m:6.... Uncaught TypeError: Cannot read property 'msie' of undefined admin_menu.js?ndi45m:223.... Failed to load resource: net::ERR_CACHE_MISS
Comment: @ashlinry That error usually comes from using the Admin Menu module along with jQuery update...I don't recall it knocking out the rest of the page js though, so that might not be the problem. You could test quickly by putting the jQuery version down to something lower than 1.9
Comment: What is in the browser's console? How does that "nothing" look like? Any http request sent?
Comment: "Nothing" as in there is the empty region with my main content area pushed over as if there actually was block content there.
Comment: And 3 errors in the console: Uncaught TypeError: Cannot read property 'msie' of undefined panels.js?ndi45m:6
Uncaught TypeError: Cannot read property 'msie' of undefined admin_menu.js?ndi45m:223
Failed to load resource: net::ERR_CACHE_MISS
Comment: Here is your **[edit](http://drupal.stackexchange.com/posts/134361/edit)** link, please use it :)
Comment: Hmm, unfortunately I don't have the authority to change the jQuery version on this site. Red tape and all...
Answer: It is caused by legacy functionality in old versions of jQuery no longer being supported in more modern versions. In this particular case I think it has to do with browser version detection, which has fallen out of favour for feature detection.
Add the jquery-migrate script to your theme's javascript folder and load it via your theme's info file.
If you continue to have issues you might need to make sure this file loads directly after the jQuery main file.


Plugin para criar construtor de instância da variável em tempo de execução

Question: Preciso criar alguns testes utilizando variáveis já instanciadas em tempo de execução, e invés de montar manualmente, objeto por objeto, atributo por atributo, gostaria de alguma ferramenta que automatiza-se isso e já trouxesse o código com os objetos e variáveis preenchidas, essa ferramenta existe no Intellij?
Por exemplo, apenas arrastando a variável do Watch para o código, gostaria que já trouxesse os objetos valorizados. São muitos objetos e atributos que tem que preencher, ocasionando uma perda de tempo.
Comment: Você quer uma ferramenta dentro do Intellij IDEA que preencha com valores aleatórios uma classe qualquer no meio do debug do código?
Answer:
Por exemplo, apenas arrastando a variável do Watch para o código, gostaria que já trouxesse os objetos valorizados

O Intellij IDEA em si não fornece um recurso assim, e ao meu ver não faria muito sentido para o seu teste unitário, dado o início da sua pergunta:

Preciso criar alguns testes utilizando variáveis já instanciadas em
  tempo de execução, e invés de montar manualmente, objeto por objeto,
  atributo por atributo, gostaria de alguma ferramenta que automatiza-se
  isso e já trouxesse o código com os objetos e variáveis preenchidas

Pelo que entendo, você precisa na verdade de uma ferramenta no seu teste unitário para preencher classes com valores aleatórios, para que não precise ficar populando manualmente cada um.
Uma biblioteca que pode te ajudar é o PODAM:
<code>// Simplest scenario. Will delegate to Podam all decisions
PodamFactory factory = new PodamFactoryImpl();

// This will use constructor with minimum arguments and
// then setters to populate POJO
Pojo myPojo = factory.manufacturePojo(Pojo.class);

// This will use constructor with maximum arguments and
// then setters to populate POJO
Pojo myPojo2 = factory.manufacturePojoWithFullData(Pojo.class);

// If object instance is already available,
// Podam can fill it with random data
Pojo myPojo3 = MyFactory.getPojoInstance();
factory.populatePojo(myPojo3);
</code>
Existem outras também. Mas a ideia é resolver este problema antes da execução do seu teste unitário.


A question about functional calculus

Question: Here is a Lemma in a book "C*-algebras and Finite-Dimensional Approximations" P238.

Definition 7.1.1 A C*-algebra $A$ is called quasidiagonal (QD) if there exists a net of c.c.p. maps $\phi_{n}: A\rightarrow M_{k_{(n)}}(\mathbb{C})$ which is both asymptotically multiplicative (i.e., $||\phi_{n}(ab)-\phi_{n}(a)\phi_{n}(b)||\rightarrow 0$ for all $a, b\in A$) and asymptotically isometric (i.e., $||a||=limi_{n\rightarrow\infty}||\phi_{n}(a)||$ for all $a\in A$).
Lemma 7.1.4. If $A$ is unital and QD, then there exist u.c.p maps $\phi_{n}:A \rightarrow M_{k(n)}(\mathbb{C})$ which are both asymptotically multiplicative and asymptotically isometric.
Proof. Let $\phi_{n}^{'}: A\rightarrow M_{l(n)}(\mathbb{C})$ be asymptotically multiplicative and isometric c.c.p. maps. Functional calculus shows that the spectra of the matrices $\phi_{n}^{'}(1_{A})$ are contained in sets of the form $[0, \varepsilon_{n})\cup(\varepsilon_{n},1]$, where $\varepsilon_{n}\rightarrow 0$, and hence
  $$||\phi_{n}^{'}(1_{A})-P_{n}||\rightarrow 0,$$
  where $P_{n}\in M_{l(n)}(\mathbb{C})$ are the spectral projections of $\phi_{n}^{'}(1_{A})$ corresponding to $[1, 1/2]$.
Thus $\phi_{n}^{'}(1_{A})P_{n}$ is an invertible element in $P_{n}M_{l(n)}(\mathbb{C})P_{n}$ and more functional calculus shows
  $$||(\phi_{n}^{'}(1_{A})P_{n})^{-\frac{1}{2}}-P_{n}||\rightarrow 0$$
  as well. If $k(n)$ is the rank of $P_{n}$, then we get the desired u.c.p maps $\phi_{n}: A\rightarrow M_{k(n)}(\mathbb{C})$ by defining
  $$\phi_{n}(a)=(\phi_{n}^{'}(1_{A})P_{n})^{-\frac{1}{2}}\phi_{n}^{'}(a)(\phi_{n}^{'}(1_{A})P_{n})^{-\frac{1}{2}}.$$

My question:
In the second line of the proof, how does the author use the functional calculus shows that the spectra of the $\phi_{n}^{'}(1_{A})$ are  contained in sets of the form $[0, \varepsilon_{n})\cup(\varepsilon_{n},1]$, where $\varepsilon_{n}\rightarrow 0$, and then how to get
$$||\phi_{n}^{'}(1_{A})-P_{n}||\rightarrow 0 ?$$
Answer: From $\|\phi'_n(1_A)^2-\phi'_n(1_A)\,\|<\varepsilon_n$ we deduce that all spectral elements of $\phi'_n(1_A)$ satisfy the equation $|\lambda^2-\lambda|<\varepsilon_n$. As we are talking positive operators here, we get that $\sigma(\phi'_n(1_A))\subset [0,g(\varepsilon_n))\cup(1-g(\varepsilon_n),1]$, where $g$ is a function with $g\geq0$ and $\lim_{t\to0}g(t)=0$; properly, we can take
$$
g(t)=\frac{2t}{1+\sqrt{1-4t}}.
$$ There is no part above $1$ because $\phi'_n$ is completely contractive.
The inequality follows by functional calculus from the inequality $|t-1_{[1/2,1]}(t)|<g(\varepsilon_n)$ when $t\in [0,g(\varepsilon_n))\cup(1-g(\varepsilon_n),1]$: it implies that the selfadjoint operator $\phi'_n(1_A)-P_n$ has its spectrum inside $[0,g(\varepsilon_n))$.
Comment: If $f(t)=1_{[1/2,1]}(t)$ then $$t\,f(t)\geq \frac12\,f(t).$$ So , for any selfadjoint operator $A$, if you write $P=f(A)$, you have that $AP\geq\frac12\,P$. Then in the algebra $P\mathcal M P$, the element $AP$ is invertible (it is bigger than a scalar multiple of the identity $P$).
Comment: If you want. But it follows straight from $AP\geq P/2$: this implies that the spectrum of $AP$ in $P\mathcal M P$ is all to the right of $1/2$, so it doesn't contain zero.
Comment: Oh, yes, thanks for your answer. And then the author says the $\phi^{'}_{n}(1_{A})P_{n}$ is an invertible element in $P_{n}M_{l(n)}P_{n}$, why?
Comment: And I think $P$ is the identity of $PMP$, then we can compute $||AP-P||=||AP-P^{2}||\leq||A-P||||P||<1$, so $AP$ is invertible in $PMP$, is that right?

A question about functional calculus


Angular - How can I set the video src from navigator.getUserMedia?

Question: I am trying to set up a webcam stream for a video element in Angular.
    import {Component, View, bootstrap} from "angular2/angular2";

    @Component({
        selector: "home",
    })
    @View({
        template:`<video [src]="videosrc"></video>`
    })
    export default class Home {

        videosrc: string;
        constructor(){

            //setTimeout(() => {}, 2000);

            navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
            navigator.getUserMedia({video: true},(stream) => {
                this.videosrc= URL.createObjectURL(stream);
            }, (err) => console.log(err));
        }
    }

Its working only after adding the line "setTimeout(() => {}, 2000);".
Plunker
Comment: What should we see? I see the plnkr failing with a `NavigatorUserMediaError` and a black screen, but the timeout doesn't seem to solve anything
Comment: You are right I didnt explain, it should use 'navigator.getUserMedia' and and get video stream from a webcam. So you must have a webcam attached to test it.
Answer: you must bind [srcObject]  to media stream
<video id="device" [srcObject]="localSource" controls autoplay></video>

navigator.mediaDevices.getUserMedia({ audio: true, video: true })
  .then(stream => this.localSource=stream);

Answer: Changes detection needs to be triggered once you set the src url.
Wrapping the getUserMedia call into a Promise will solve your issue. You should also be able to call Lifecycle.tick() manually.
var promise= new Promise<string>((resolve, reject)=>{
          navigator.getUserMedia({video: true},(stream) => {
            resolve(stream);
          }, (err) => reject(err));
        }).then((stream)=>{
            this.videosrc= URL.createObjectURL(stream);
        }).catch((error)=>{
          console.log(error);
        });

See the updated plunker: http://plnkr.co/edit/G9Y4Rk17pNP5XwHzDNko?p=preview


I have this for my homework about moment generating functions

Question: Consider the following the continuous RVs X1, X2, Y, and Z:
X1 ~ U(10, 20),
X2 ~ U(10, 20),
Y = X1 + X2,
Z = Y + 20,
a. What is the MGF of Z?
b. Draw the pdf of Z.
c. Use the MGF of Z to get its mean.
d. Find P( Z < 50). Shade the appropriate area that corresponds to the said probability
I have arrived at an answer for A but I can't figure out the distribution which makes it hard for me to answer the following questions.
Comment: I found that Mz = ((e^10s-1/10s)^2)(e^40s). But from the table for MGF of known distributions, I can't place this particular MGF among them.
Comment: Consider the MGF at https://en.wikipedia.org/wiki/Triangular_distribution with $c-b=b-a$
Answer: If it were given that $X_1,X_2$ are independent, then you can use the basic result on the moment-generating function of the sum of two independent random variables.
Next you have
\begin{align}
& M_{Y+20} (t) =\operatorname{E}(e^{t(Y+20)}) = \operatorname{E}(e^{tY} e^{20t}) \\[10pt]
= {} & e^{20t} \operatorname{E}(e^{tY}) \text{ because $e^{20t}$ is constant, i.e. not random} \\[10pt]
= {} & e^{20t} M_Y(t).
\end{align}
Comment: yes, I have arrived at that and Mz = ((e^10s-1/10s)^2)(e^40s). Btw, sorry, I don't know how to properly write a formula here.


Interrupting a thread running a Cypher query causes exceptions

Question: I have some tasks that are run in their own threads, each one executing a method which wraps a Cypher Query that gathers some statistics and updates some nodes.  That method is marked as @Transactional (Using Spring)
Each thread executes the same query, with a different node id param for start.
Now, occasionally, some threads 'hang' or take too long to execute and I would like to be able to interrupt them.
So I wrote a class using  Executors.newSingleThreadScheduledExecutor() in order to schedule a cancel() after a certain timeout.
What is happening is that I get all sorts of exceptions, transaction related. App logs

org.neo4j.kernel.impl.nioneo.store.UnderlyingStorageException: Unable to load    position[3822] @[34398]
  Caused by: javax.transaction.xa.XAException: Logical log unable to mark 1P-commit [4]
  Caused by: java.nio.channels.ClosedByInterruptException: null
      at java.nio.channels.spi.AbstractInterruptibleChannel.end(AbstractInterruptibleChannel.java:184) ~[na:1.6.0_65]

Neo4j version is 1.9.5 embedded, running on Mac
Any ideas?
Answer: Interrupting Threads is not a good idea. Esp. with nio weird things happen.
I think it is much better to use the built-in mechanism in Neo4j for this.
Stefan Armbruster wrote a blog on how to use the "Guard" mechanism to stop long running cypher queries, see here:
http://blog.armbruster-it.de/2013/09/some-experiments-with-ratpack-and-neo4j/
Check out the "Terminate Queries" part & code.
Answer: Test case and workaround
I created an issue on github, just to see what opinion Matrix team have on this. So far I like Neo4j very much, but this is real issue for me.
https://github.com/neo4j/neo4j/issues/3977#issuecomment-74735972

I didn't like the guard solution for more reasons, so I wrote little thread class, which solves interrupted problem. It does not solve long running query problem fully because it will keep running in background, but your code will not wait for it to finish.
  I'm testing it for few days already and it feels usable.


IP address for fly.io app not recognised in MongoDB Atlas

Question: I'm trying to limit connection to my MongoDB Atlas cluster from only my fly.io app. I have its IPv4 address from the app deployment page (screenshot below)

and added it to the whitelist in MongoDB Atlas (screenshot below)

The problem is that this doesn't even appear to be enough to allow a connection from my app to my cluster. Even increasing the IP range to 184.108.40.206/23 doesn't help. I've had to allow connection from anywhere in order to get my fly app to connect. I don't have this problem if I'm trying to whitelist my own laptop to develop locally.
I should clarify that performing a dig on my app's URL does bring up the IP address in the first screenshot, so at least this confirms that the IP address is not internal to fly.io.
Can anyone explain what's happening here? Is there a way I can work around this?
Thanks in advance!
Comment: Perhaps you could limit access to the [FLYIO CIDR, `220.127.116.11/18`](https://mxtoolbox.com/SuperTool.aspx?action=ptr%3a184.108.40.206&run=toolpage).
Comment: Unfortunately I have and still no cigar :(
Comment: @SSaid did you eventually find the solution? I am running into a similar situation right now. Thanks!
Comment: I think at the time of writing this there's no way for you to do this see [here](https://community.fly.io/t/set-get-outgoing-ip-address-for-whitelisting-on-external-apis-hosts/3690/14)
Answer: I think at the time of writing this there's no way for you to do this see here
However they've given out some IP's based on a few regions that you can try your hand at
list of some outbound IP's based on location
Be warned though, these ip's can change on a whim though


Best way to get file date created from Java on a UNIX system?

Question: java.io.File doesn't provide a way to get a file's creation date.  You can get file.lastModified, but not anything like dateCreated.
Java 7 adds the excellent java.nio.file package with access to date created, but it's not out yet.
My question: what's the best way to get a file's date created from Java on a UNIX/OSX system?  I suppose it's executing a shell script, but my command line skills are pretty weak.  So if shell scripting's the way to go, if you could provide a full example I'd be very grateful.
Thanks!
Comment: First I would check you are using a file system which records the creation date as most do not. Which file system are you using?
Comment: If you are using OSX, you can google for solutions like `ls -lcT datetest.txt`  http://blog.sudosu.net/2009/file-created-date-under-os-x/
Answer: Unix doesn't have a "creation date". The only dates stored on files are modification date, which stores the time the file contents where changed; the access date, which stores the last time a file was read; and the "change date", which stores the last time the file's metadata was changed. (The metadata contains things like permission bits, ownership, etc.)
If you review the structure supported by the stat(2) API, you can see the three timespec's.
Comment: I just noticed that Darwin and FreeBSD have a fourth timespec, st_birthtimespec. Okay, so POSIX doesn't support a birthtime...
Comment: RedHat Linux does not have a st_birthtimespec in its stat structure.
Comment: Thanks.  Used stat on a file on my filesystem and sure enough, it returns a modify date but not a create date.
Answer: From the command line, the easiest way to get the creation date is with mdls. I think you'd want to do /usr/bin/mdls -name kMDItemFSCreationDate $filename (where $filename is the file you're asking about). You can specify multiple filenames, but that might make it harder to parse the output.
Comment: Thanks, that works fine on OSX!  Seems like my linux server simply doesn't store the date created, so I'll accept this answer.
Comment: @Dean: That's correct. The POSIX standard does not define a creation time, so most Linux/Unix filesystems do not store them.
Answer: You can't - it isn't stored anywhere
Answer: It actually depends on the file system, and most file systems don't provide such feature as storing a file "birth time". You need to check the filesystem.


drush cc all giving me an unlink error

Question: I found a similar issue but it will not help me since I have not changed permissions.
I am running drush cc all and getting this error...

I have logged out and back in and nothing. I have not changed permissions and I have the admin rights to the account. Any ideas on what to do?
Comment: Can you post an example of those permissions? And, which is the similiar issue?
Comment: You say: "I have the admin rights to the account".  What account is that and what exactly do you mean by "admin rights"?  Also: who owns the directory and files that produces the error?  What is written when you type the CLI command `whoami` ?
Comment: The hosting account is with blackmesh. So, whoami gives me the account name. Should I send this to them to make sure I have access to that folder?
Answer: I've seen this problem when as unprivileged user you call drush cc all and drush tries to delete cache files created by the web server process. Those files are owned by the web server user and they don't have the 'all other users" write permissions enabled (the last three permissions group).
Fixing this is a file permissions issue. One fix is to put web server user and drush user in the same group and assure that files created by the web server process are writable by its group members.
Comment: So, if I am hosted with someone like blackmesh do I need to ask them to set the permissions so I can run it properly?
Comment: To answer properly I need the file permissions, group and owner of one of the files with error and the user name you use to run drush (use whoami command).
Comment: Okay, redoing the permissions did the job. I am now able to run drush cc all without any issues. Thank you for you help!!!
Comment: If the answer is correct you may indicate it by selecting this answer as the accepted answer. See http://meta.stackexchange.com/a/5235

drush cc all giving me an unlink error


How te remove google ads from an iframe hosted on other domain

Question: I'm looking for some javascript or jquery script to remove google ads from an iframe document, which is hosted on a different domain.
Is it possible?
Comment: You can't. You can't even access the iframe in the first place, how much more the ad within it.
Answer: You cannot see Get DOM content of cross-domain iframe
Unless you have control of some script in that frame, in which case you can do some fancy postMessage stuff, but if you have control, then remove the ads there :)
Comment: If you can add script to the iframe at the source, then remove the ads there ;)
Comment: I can add script to the framed (nestes?) document. Any idea?


is it possible to integrate this function to get x(t) and y(t)?

Question: say you have a function as below;
$d^2V(t)/dt = -B^2V(t)$
B is a constant
Initial conditions $V_x(0) = V$, $V_y(0) = 0$

I can't see how to integrate to get x(t) and y(t);
I ended up with $x(t) = dVx(t)/dt = -B^2V(t)x$, when I integrated RHS with respect to dt and LHS with respect to dx. Any help here is appreciated......
EDIT: The question has been asked, here it is. How I came to the beginning equation above is in the comments section, though I used G for $B_o$ and $B$ is not same as $B_o$ also because I just used it to represent a chunk;
Comment: How are $V(t)$, $x$, and $y$ related?
Comment: from loretz force mdv/dt = qv x G , V = dr/dt, Vz = v.z = 0. Given the initial conditions, this is how I got the first equation above. d^2V(t)/dt = -[qG/m]^2V(t), and I made B = [qG/m}
Comment: ![enter image description here][1]

  [1]: http://oi62.tinypic.com/j8lma9.jpg
Answer: This is just the standard ODE for sin and cos.
Note that
$\sin'(bx)=b\cos(bx)\\
\cos'(bx) = -b\sin(bx)\\
\sin''(bx)=b\cos'(bx)=-b^2\sin(bx)\\
\cos''(bx) = -b\sin'(bx)=-b^2\cos(bx)
$.
To get $b^2$ instead of $-b^2$,
use
$\sinh$ and $\cosh$.
Comment: how do you connect the sine functions you have given to the beginning equations I posted. I took differential equations 3 years back and right now its hard to see where the sines, cosines, or sinh and cosh connect to it\
Answer: It's not totally clear to me whether your problem is to solve the equation
$$m\frac{\text d\mathbf v}{\text dt} = q\mathbf v\times\mathbf B$$
or something else. So I will assume this is the problem you are trying to solve, and I will further assume that $\mathbf B$ is a constant vector in both space and time.
Under the above assumptions, the RHS of the equation is linear in $\mathbf v$, and therefore there exists a $3\times3$ matrix, say $\star\mathbf B$ (the $\star$ here can be interpreted as the Hodge star operator) such that $\mathbf v\times\mathbf B = (\star\mathbf B)\mathbf v$. The equation then becomes
$$m\frac{\text d\mathbf v}{\text dt} = q(\star\mathbf B)\mathbf v,$$
which integrates to
$$\mathbf v(t) = e^{\frac qm\star\mathbf Bt}\mathbf v_0,$$
where $\mathbf v_0$ is the initial condition on the velocity. To get the trajectory one has then to simply integrate $\mathbf v(t)$ with the initial condition on the position to get $\mathbf r(t)$.


How to get ceil value with custom digit number in SQLite?

Question: In my database, I have prices of items, and the discount percents for the items.
Here is a sample row from the database
Name     Price     DiscountPercent
****    1000.26         17.00

Now for this row I need to get the discounted price, but with two digits after the comma, i.e. for the discounted price 830.2158 I want to get 830.21
Doing
Round((UnitPrice - (UnitPrice * DiscountPercent)/100),2)

in my select query will return 830.22 which is not what I want. I could have achieved the desired result if I could do
Round(Floor((UnitPrice - (UnitPrice * DiscountPercent)/100) * 100)/100,2)

but unfortunately there is no Floor function in SQLite.
I also tried to cast to int and then divide by 100 and Round, but it seems that SQLite casts the whole result to int, because I get 830.0
How can I do this?
Thanks in advance
Answer: Ok this one is complicated and it is basically subtracting off the 3rd decimal place.
round((UnitPrice - (UnitPrice * DiscountPercent)/100)-(((UnitPrice - (UnitPrice * DiscountPercent)/100)%1*100)%1/100),2)

Easier to read and to get the basic Idea:
round(value -((value%1*100)%1/100),2)

Comment: do you mean using
SELECT Round(Round((UnitPrice - (UnitPrice * DiscountPercent)/100) * 100 , 0)/100,2) FROM Product ?
It returns 830.22 again
Comment: Yes if you still want the `.00` after the int
Comment: unfortunately that doesn't help
Comment: How? if you want 830.00 that is the result it gives
Comment: as I mentioned above, i want 830.21
Comment: finally I did it. Here is the way i solved it, but i don't like it and still looking for a better answer

SELECT cast(cast((UnitPrice - UnitPrice * DiscountPercent/100) * 100 as int) as real) / 100 FROM Product
Answer: SELECT cast(cast((UnitPrice - UnitPrice * DiscountPercent/100) * 100 as int) as real) / 100 FROM Product


Prolog Predicate for positive and negative integers

Question: I'm currently studying for an exam in Prolog and so am trying to do some sample questions to get ready. I've been trying this one for while, the task it to create intgr/1 so that
?-intgr(X).
X=0;
X=1;
X=-1;
X=2;
X=-2;
...

What I have now is
intgr(0).
intgr(X) :- intgr(Y), (X is Y + 1 ; X is Y - 1).

However, it lists them out in a really weird way, namely:
X = 0
X = 1
X = -1
X = 2
X = 0
X = 0
X = -2
X = 3 ...

I'm just wondering what a good approach would be to change that in order to get them listed out in the right order.
Comment: I don't understand the pattern, have you got a typo here? Should `X=2; X=2` really be `X=2; X=-2` ?  (And `X is Y - 1` be `X is 0 - Y`) ?
Comment: Sorry changed the pattern now thank you! And no I had  X is Y - 1 so you can go up or down from 0, but would 0-Y work better?
Answer: Efficient:
intgr(I) :-
    integer(I),
    % Any integer will do, can stop here
    !.
intgr(I) :-
    var(I),
    (   I = 0
    % Start alternating +/- with 1
    ;   intgr_(1, I)
    ).

% Plus
intgr_(N, N).
% Minus
intgr_(N, I) :-
    % Calc negative, rather than -(N) term
    I is -N.
intgr_(N, I) :-
    % Increment into infinity
    N1 is N + 1,
    intgr_(N1, I).

Results in swi-prolog:
?- intgr(-5).
true.

?- intgr(0).
true.

?- intgr(4).
true.

?- intgr(fish).
false. % Fails quickly, as appropriate

?- intgr(I).
?- intgr(I).
I = 0 ;
I = 1 ;
I = -1 ;
I = 2 ;
I = -2 ;
I = 3 ;
I = -3 ;
...

As @TA_intern pointed out, this can be shortened (if inf is supported in between) to:
intgr_between(I) :-
    integer(I),
    % Any integer will do, can stop here
    !.
intgr_between(I) :-
    var(I),
    (   I = 0
    % Start alternating +/- with 1
    ;   between(1, inf, N),
        (   I = N
        ;   I is -N
        )
    ).

Counting up to infinity can be implemented as e.g.:
incrementing_from(Start, N) :-
    integer(N),
    !,
    integer(Start),
    % Both variables are integer
    N @>= Start.
incrementing_from(Start, N) :-
    var(N),
    integer(Start),
    incrementing_from_(Start, N).

incrementing_from_(N, N).
incrementing_from_(U, N) :-
    U1 is U + 1,
    incrementing_from_(U1, N).


Send picture taken from android to .net web application (to store it in database)

Question: I'm trying to upload some photos taken by an application in a distant database. To be clear :

I take a piture from my app
I send if to a web service (witten in .net, svc file)
The WS upload it in the database

The way i'm doing it : i'm sending the byte[] recovered from the picture that way
String url = MyAddress + "insert_img?login='"
                    + login_result + "'&epc='" + code + "'&title='" + t
                    + "'&image='" + base64EncodedString + "'&descrip='" + d
                    + "'";
            BufferedReader inStream = null;
            System.out.println(url);
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpR = new HttpGet(url);
            httpR.setHeader("Accept", "application/json");
            httpR.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(httpR);

My problem is that I have to compress A LOT the picture in order it to be send. The picture, or base64EncodedString field, is created like that :
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");

mImageView.setImageDrawable(null);
mImageView.setImageBitmap(thumbnail);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 1, baos);

byte[] outputByteArray = baos.toByteArray();

base64EncodedString = Base64.encodeToString(outputByteArray, Base64.NO_WRAP + Base64.URL_SAFE);

As you can see, the image is very very very compressed, and when I recover it it's more or less a 4-colors stamp. And if I do not compress it a lot, image is not inserted.
So first of all : Am I doing it the right way to deal ? And also, why is there no insertion when the picture is too big and how, if possible, to track the error ?
Thanks !

EDIT :
I've modified my code that way, server side :
public string insert_report(Stream stream)
    {
        string login = "";
        string epc = "";
        string title = "";
        string image = "";
        string descrip = "";
        MultipartParser parser = new MultipartParser(stream);
        Entities entities = new Entities();
        string res = "";
        if (parser != null && parser.Success)
        {
            res += parser.Filename;
            foreach (var content in parser.MyContents)
            {
                string name = content.PropertyName;
                string str = Encoding.UTF8.GetString(content.Data);
                res += "name : " + name +"---";
                res += "content : " + str+"---";

                if (name.Contains("login"))
                {
                    login = str;
                }
                if (name.Contains("epc"))
                {
                    epc = str;
                }
                if (name.Contains("title"))
                {
                    title = str;
                }
                if (name.Contains("image"))
                {
                    image = str;
                }
                if (name.Contains("descrip"))
                {
                    descrip = str;
                }
            }
        }
        res+= " res returned by server : "+ entities.insert_report(login, epc, title, image, descrip);
        entities.SaveChanges();
        return res;
    }

But there are some problems : the insert_report function return -1... How do I recover the error given by that function ?
Answer: Do you receive 414 (Request-URI Too Long) error? You should use HTTP POST method to upload your images as POST body - no Base64 encoding will be also required. Look at https://stackoverflow.com/a/7632849/2714032
Comment: I've edited my question in order you to see the two sides of the application. I'm gonna work with you suggestion, does it change anything for the called function WS side ? Thanks !
Comment: Yes, WS part also needs to be modified in order to handle multipart/form-data - http://stackoverflow.com/a/7460231/2714032
Comment: I've updated my question according to your considerations, have a look :) (since it's not working...)


async CTP: I am doing something wrong, the GUI is blocked

Question: I am making some probes with async CTP but I don't get a good result, because the GUI is blocked.
I have an WPF application with a button and a textBox for a log. Then I have this code:
private async void btnAsync01_Click(object sender, RoutedEventArgs e)
        {
            UpdateTxtLog("Enter in Button Async01: " + System.DateTime.Now);
            await metodo01Async();
            UpdateTxtLog("Exit button Async01: " + System.DateTime.Now);
        }

private async Task slowMethodAsync()
        {
            UpdateTxtLog("Enter in slowMethod: " + System.DateTime.Now);
            Thread.Sleep(5000);
            UpdateTxtLog("Exit slowMethod: " + System.DateTime.Now);
        }

If am not wrong, set a method with "sync" (click event in this case), it  let the method use the await, to return the point to execution to the method which call the actual method, then the execution return to the GUI.
So in the GUI,I click the button, then in the click event await to the slowMethod, how I use await with the slowMethod the control should be returned to the GUI, and then the GUI should not be blocked. However, the GUI is blocked and the txtLog not show any information until slowMethod finish.
Is this because slowMethod is executed in the same thread than the GUI? If I am wrong, with async normally use the same thread than the method which call the await method, but I think that the reason of the async avoid this.
How can I simulate an slowMethod without thread.Sleep? Perhaps this is the problem, because in slowMethod I sleep the thread, and the thread of slowMethod is the same than the GUI.
This makes me think that is always recommended execute in other thread the code of the async methods? If this is correct, which is the sense to use async if also I need to use task for not blocking the main thread?
When to use async and when to use tasks?
For this probes, I am following the examples in this web: http://www.codeproject.com/Articles/127291/C-5-0-vNext-New-Asynchronous-Pattern
In this example, it's used client.DownloadStringTaskAsync as slowMethod, but in my case, instead of using a WebClient, I use a dummy method, with a sleep to simulate a slowMethod. I think that is the unique difference.
Thanks.
Daimroc.
Answer: Simulate waits using await TaskEx.Delay(5000), which executes an asynchronous sleep/delay.
You may also want to read up some more on async/await. There are several good Channel9 videos; Stephen Toub, Eric Lippert, and many other Microsoft bloggers have excellent overviews. Jon Skeet's "eduasync" blog series is also good for really going deep. I've written up an async intro on my own blog, as have many others.
Here's how async and await really work, in a nutshell:

The async keyword only enables the await keyword. That is all. It does not run the method on a background thread.
await only acts asynchronously if its "awaiter" is not completed.

So in your case, btnAsync01_Click and slowMethodAsync both run on the UI thread. slowMethodAsync will run synchronously (executing Thread.Sleep), and then return to btnAsync01_Click, which awaits the already-completed task. Since the task is already completed, btnAsync01_Click just continues executing without yielding to the UI message loop.
If you replace Thread.Sleep with await TaskEx.Delay, then btnAsync01_Click will start running on the UI thread, and will call slowMethodAsync (also running on the UI thread). When slowMethodAsync awaits the delay (which is not completed), it will return an incomplete task to btnAsync01_Click. btnAsync01_Click will await that task (which is not completed), and will return to the UI loop.
When the delay expires, it will complete, and slowMethodAsync will resume (on the UI thread). When slowMethodAsync completes, its returned task will complete, and btnAsync01_Click will resume (on the UI thread).


Laravel - php eval with blade compileString

Question: I'm trying to parse a blade template string into php format and use eval() to evaluate string as php code
 $array = [
     'foo' => 'bar',
     'bar' => 'foo'
 ];
 $content = '@foreach($array as $value){{$value}}@endforeach';
 $blade = Blade::compileString($content);
 $php = eval($blade);

This is my code for testing so far and it throws exception

ParseError: syntax error, unexpected '<',
  expecting end of file

value of $blade after compileString()
<?php $__currentLoopData = $array; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php echo e($value); ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

What causes this error? Is eval() not compatible with the way compileString() is parsing blade into php?
Answer: As stated in the manual:

The code must not be wrapped in opening and closing PHP tags, i.e. 'echo "Hi!";' must be passed instead of '<?php echo "Hi!"; ?>'. It is still possible to leave and re-enter PHP mode though using the appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!<?php echo "Back in PHP mode!";'.

Your blade is wrapped in <?php tags, and the compilation fails. Remove the enclosing PHP tags, but leave the interstitial tags.


Iptables rule to block http traffic not working

Question: sudo iptables -A INPUT -p tcp --destination-port 80 -j DROP

Seems that this rule is not blocking the internet traffic comming from the subnetwork (10.0.0.*)
Blocking ssh and ftp works well..
Iptables
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    DROP       tcp  --  anywhere             anywhere             tcp dpt:ftp
2    DROP       tcp  --  anywhere             anywhere             tcp dpt:ssh
3    DROP       tcp  --  anywhere             anywhere             tcp dpt:http

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination
1    ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
2    ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination

Comment: Please share `iptables-save` output.
Comment: Try blocking ports 443 and 8080 in addition to 80.
Comment: Please show the output of "iptables -L -v" instead. Thanks.
Comment: No fix for this ? I have the same pb... I block my IP on all ports. I do get banned on SSH but port 80 is still accessible whatever I do. This is making me nuts.
Comment: What traffic do you want to block? Traffic directed at your machine or traffic going through your machine?
Answer: please chek that ipv6 is disabled. there is ip6tables. ipv6 firewall rules need to be set separately.
try to disable ipv6 and see if then the iptables rules apply:
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1


Black lines missing in the box holding the axes of a MATLAB plot

Question: When plotting on a figure in MATLAB, I have noticed that parts of the black box that holds the axes are missing (the left and bottom one):

I have tried issuing:
box off
box on

commands with no success. Do you know what I can do to get the corresponding black lines on the axes?
Note:
I am using the OpenGL renderer:
set(0,'DefaultFigureRenderer','opengl');

Comment: Can you post the exact command used to generate this figure?
Comment: Have you used `alpha` function to set transparency? I've noticed that this command causes axes to disappear.
Answer: It looks like you have known issues with OpenGL renderer:

Why do the axes box and tick marks disappear when I use transparency in a plot in MATLAB 7.5 (R2007b)?
Why does using PATCH with transparency cause the axes to disappear in MATLAB?
Why does the ALPHA commmand make the top and right borders of my figure disappear in MATLAB R2011a (7.12)?

Let us know what you did exactly to create this figure.
Comment: Have a look at this [doc](http://www.mathworks.com/support/tech-notes/1200/1201.html).
Comment: The problem was the `OpenGL renderer`. Thanks! I had this line: `set(0,'DefaultFigureRenderer','opengl');` in my `startup` file. I always thought OpenGL was better if your HW supports it. Is there any reason to **not** use it? (besides experimenting problems like the one I just did)
Answer: Try increasing the line width of the axes a bit:
set(gca, 'LineWidth', 1.2)

Also, switching from hardware (default) to software rendering may solve the problem:
opengl software

However, there may be drawbacks. Increasing the line width, e.g., changes all axes lines, including ticks.
Answer: Use the following line of code to make the black lines appear
set(gca,'Layer','top')
Answer: Being a perfectionist this bug bothered me for years! This is what seems to work, MATLAB R2013a:

I have OpenGL off (gives all kind of weird behavior): set(0,'DefaultFigureRenderer','zbuffer')
I add a box just before I plot something and right after I finish plotting:
axes(handles.MyAxes);

cla;

hold off;
box on;
hold on;

% Do your plotting...
% scatter(...);
% plot(...);
% ...

box on;

I also noticed that if the first command is plot then the bug may still be present. In this case I plot just a single point using scatter with white color (makes it invisible) and then use plot. That is, scatter(x(1),y(1),1,'MarkerEdgeColor','w','MarkerFaceColor','w') and then plot(x,y,...).

My answer in fact refers to missing box lines when plotting in a GUIDE figure. I never had this issue when using a regular figure() and then plot(...) commands.
Hope it helps!


Cannot invoke nextint() on the primitive type int

Question: So I'm learning Java and maybe he didn't explain well enough how scanners work and their limits or maybe I'm looking over something silly...  but I'm getting an error on answer = answer.nextInt(); I don't get this error for bomb but it's used pretty much the same way...
Code:
    Scanner yesNo = new Scanner(System.in);
    Scanner input = new Scanner(System.in);
    //
    //answer auto set to no. goes to first if, then asks for confirmation,
    // then check answer again and go to if, else if or else.
    //
    int answer = 0;
    while (answer != 1)
        if (answer == 0) {
            System.out.println("In how many seconds should we detonate?");
            int bomb = input.nextInt();
            //this number will be used later in else if (answer == 1)
            System.out.println("Is " + bomb + " seconds correct? 1 for yes, 0 for no");
            answer = answer.nextInt();
            //error above "Cannot invoke nextint() on the primitive type int"
            //Need this to grab a number from user to assign a new value to answer

What do? Thanks.
Comment: Um.  `answer = input.nextInt()`?
Comment: you can't call functions on a primitive, it doesn't exist.
Comment: They didn't explain that.  Maybe I just need to find a better tutorial. Thanks!
Comment: "input is being used to hold bomb though" - no. `input` only holds the next position in your typed line. Suppose you typed in `100 200`. After `input.nextInt()`, input does not remember `100`, and it has no idea about `bomb`. `bomb` remembers `100`. `input` remembers that the next time someone calls `nextInt()`, it should start scanning from position 4.
Comment: imput is being used to hold bomb though, doesn't that matter? I still need the input from bomb
Comment: No, why would that make a difference?  `input` is a `Scanner` which lets you get more and more input.
Comment: Maybe you want to get the next *random* int. To do that you must create a [random generator](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html) with `n = new Random()` and then get the next random integer with `m = n.nextInt()`.
Answer: First of all, you have one Scanner instance with paramether System.in, so it will "record" your keyboard (I assume that yesNo scanner is not used). Then, you have a int variable called "answer" which you assign zero value. Finally you have another variable called "bomb" where you will get your requested value.
As I see in your answers' comments, you're wrong in one thing: "input.nextInt()" is an int value. When you use input.nextInt(), you're sending it a message that says "Hey bro, give me the first int that this stupid human have pressed", but you aren't doing anything more. "input" is only a scanner (as it class name says) that records keystrokes.
So in fact, when you do "input.nextInt()" you'll get an int value, and when you do "bomb = input.nextInt()" or "answer = input.nextInt()" the only thing that you're doing is giving "bomb" or "answer" that int value.
Answer: int is a primitive value. It is not an Object and it has no methods.
probably you want to do
answer = input.nextInt();

Comment: I see what I did.  Must have been crosseyed that day and renamed my scanner in one area and didn't change the other.  'yesNo' should have been 'answer'.  derp.
Answer: nextInt() is a function that is part of the object type Scanner.  In order to call .nextInt() you must have an object of type Scanner.
So the line "int bomb = input.nextInt();" works fine, since "input" is an object of class Scanner.  That function runs and it returns another object, an integer, from input, which is stored in int bomb.
The line "answer = answer.nextInt();" fails to compile because "answer" is an object of class integer.  integer does NOT have a function called nextInt().
The appropriate line is "answer = input.nextInt();" using your Scanner object to return another integer to store in "answer".
Answer: int answer = 0;

answer = answer.nextInt();

You are calling nextInt() on an int. You need to call it on the scanner:
answer = input.nextInt();