text:
Q: Import Error - No module named numpyio Anyone know how to solve this error?
Exception Type: ImportError
Exception Value: No module named numpyio

See my python code, my imports:
from scipy.io.numpyio import fwrite, fread

Can you help me??

A: This is becase the scipy.io.numpyio module was removed sometime aftey SciPy 0.7 (see, for example, this thread). From the SciPy Input/Output Cookbook page you can instead use the functions numpy.fromfile and numpy.nadarray.tofile (see under the heading "Raw binary").

A: While the numpy.ndarray.fromfile() allows you to specify the binary format to read (e.g. 'f' for float), the .tofile() function doesn't have such binary options. This is a highly inconvenient inconsistency for those of us who need to write binary files in a specific format for other software to read. Unfortunately this problem seems to be ignored by the development community as there seems to be no open ticket.
I have created a simple replacement function using the array module. The basic code goes something like this:
def fwrite(filename, formatstring, ndarray):
    arr = array.array(formatstring, ndarray.flatten())
    f = open(filename, 'w')
    arr.tofile(f)
    f.close()

So far that seems to work. Obviously this could/should be embellished with error checkes etc.

A: From the archives:

The I/O functions for numpy arrays have been moved to numpy where it made, or removed when they provided duplicate functionality. Use numpy.load and numpy.save for reading writing arrays in numpy's own .npy format, loadtxt/savetxt for ascii.


text:
Q: preserve and pass dynamically generated html table created in javascript to php when submit button is clicked I have to submit a dynamically generated html table that is created using javascript and pass this table to a php mail function when  submit button is clicked  ,I would like to know whether its possible to preserve the dynamically generated table in javascript when the form has any errors also when submit button is clicked and the dynamically generated table is lost .
I am a beginner and i have fared till making a dynamically generated javascript table with delete  , now i need to pass this table to a php submit button  and then can only proceed further
Any help will be grateful since  time is short for me right now pls help.
the code is as follows
To add rows to a table
function addRow(){

var a =document.getElementById("sociallink").value;
    var b =document.getElementById("socialemail").value;
    var c =document.getElementById("socialpass").value;

var media=document.getElementById('media');

if ( media.selectedIndex  ==  "1" )
{
    media_type = "facebook";
}

var table = document.getElementById("dataTable");

var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= media_type;
row.insertCell(2).innerHTML= a;
row.insertCell(3).innerHTML=b;
row.insertCell(3).innerHTML=c;

table.style.display ="block";

}

php echoing html is as follows
    $form ="<form action='./form3.php'  method='post'  name='seoform'>

                   Remove Media
                       Media
                                Media Link
                                 Media Email
                                 Media Password

 <input type='submit' name='seoformbtn' value='Register'  />

 </form> ";

    echo $form;

A: You can store the markup for the table created in an hidden input which is then sent along when the form is submitted.
Add a hidden textarea to your form
<textarea id="table-markup"></textarea>

CSS:
#table-markup{
   display: none;
}

give your table an id like so:

.....

var tableMarkup = document.getElementById("table");
document.getElementById("table-markup").value = tableMarkup.innerHTML;

Now when the form is submitted this will be sent along with it..
I recommend using the POST method to send your form data (depending upon your table markup)

A: To store the table is simple
lets say your table is

......

var tbl = $('#tableid').html();
// to complement previous answer, then you put in hidden field
$("#table-markup").val(tbl);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting Text to appear at different times
Is there a way to get the parts of this code to show up in this order:

*

*The coefficients circled in blue.

*The conditions circled in red.

*The binomial coefficients circled in green.

*The equations underneath circled in black.

*The equations circled in purple.
This is the code I am using:
\documentclass{beamer}
\usepackage{mathtools} % for 'cases*' environment
\newcommand\hstrut{\hphantom{{} + 1\binom{k}{2} {}}} % horizontal spacer
\begin{document}
\begin{frame}
\[
a(n,3)=
\begin{cases*}
  1 \binom{k+2}{2} + 4 \binom{k+1}{2} + 1 \binom{k}{2} = 3k^2+3k+1
    & if $n$ is $6k$  \\
  1 \binom{k+2}{2} + 5 \binom{k+1}{2} \hstrut = 3k^2+4k+1
    & if $n$ is $6k+1$\\
  2 \binom{k+2}{2} + 4 \binom{k+1}{2} \hstrut = 3k^2+5k+2
    & if $n$ is $6k+2$\\
  3 \binom{k+2}{2} + 3 \binom{k+1}{2} \hstrut = 3k^2+6k+3
    & if $n$ is $6k+3$\\
  4 \binom{k+2}{2} + 2 \binom{k+1}{2} \hstrut = 3k^2+7k+4
    & if $n$ is $6k+4$\\
  5 \binom{k+2}{2} + 1 \binom{k+1}{2} \hstrut = 3k^2+8k+5
    & if $n$ is $6k+5$\\
\end{cases*}
\]
\begin{align*}
&\textstyle 1 {{k+2}\choose{2}}  + 4 {{k+1}\choose{2}} + 1 {{k}\choose{2}} \\
\pause  &= 1((k+2)(k+1)) + 4((k+1)k) + 1(k(k-1)) \\
\pause  &= 2(3k^2+3k+1)
\end{align*}
\end{frame}
\end{document}

A: It is still true that one should not use $$ ... $$ nor \choose. Also, \pause does not work in an align environment, but it does work in an eqnarray environment, which some users do not like. Anyway, neither of them is needed here. Other than that, you can uncover parts of equations with \uncover. Since there is a lot of repetition, one may create macros. As these are "junk macros", one may want to keep them local with \begingroup...\endgroup. Since we define them in frame, one can either make the frame fragile or use four (!) # fences.
\documentclass[10pt,fleqn]{beamer}
\usepackage{mathtools}
\begin{document}
\begin{frame}[t]
\frametitle{Uncovering an equation}
\begingroup
\newcommand\Coeff[1]{\uncover<2->{####1}}%
\newcommand\Binom[2]{\uncover<4->{\binom{####1}{####2}}}%
\newcommand\Sth[2]{\uncover<7->{=3k^2+####1k+####2}}%
\newcommand\If[1]{\uncover<3->{\text{ if $n$ is }####1}}%
\[
a(n,3)=%
\left\{\begin{array}{@{}l@{}l@{}}
  \Coeff{1} \Binom{k+2}{2}
  \Coeff{+4} \Binom{k+1}{2} \Coeff{+1} \Binom{k}{2} &\Sth{3}{1}\If{6k}\\
  \Coeff{1} \Binom{k+2}{2} \Coeff{+5} \Binom{k+1}{2}  &\Sth{4}{1}\If{6k+1}\\
  \Coeff{2} \Binom{k+2}{2} \Coeff{+4} \Binom{k+1}{2}  &\Sth{5}{2}\If{6k+2}\\
  \Coeff{3} \Binom{k+2}{2} \Coeff{+3} \Binom{k+1}{2}  &\Sth{6}{3}\If{6k+3}\\
  \Coeff{4} \Binom{k+2}{2} \Coeff{+2} \Binom{k+1}{2}  &\Sth{7}{4}\If{6k+4}\\
  \Coeff{5} \Binom{k+2}{2} \Coeff{+1} \Binom{k+1}{2}  &\Sth{8}{5}\If{6k+5}\\
\end{array} \right.
\]
\endgroup
\uncover<6->{\begin{multline*}
 1 \binom{k+2}{2}  + 4 \binom{k+1}{2} +
1 \binom{k}{2}\\
\quad = 1((k+2)(k+1)) + 4((k+1)k) + 1(k(k-1)) \\
  = 2(3k^2+3k+1)
\end{multline*}}
\end{frame}
\end{document}


text:
Q: php session_start() is working in WP enging but not worked in live site I have a site which has wp engine for work. I have added php session_start() in wp engine and its worked fine. But my live not working with php session_start();. Live site created session but after redirecting its session has been blank, may session has destroyed. But same functionality using in live and staging site, then why not working session in live site? I have many answer in this forum and I am also implement this code, but not working. How can I solve this issue?
add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');

function myStartSession() {
    if(!session_id()) {
        session_start();
    }
}

function myEndSession() {
    session_destroy ();
}

A: Assuming your live site too in WP Engine which unfortunately not supports PHP sessions due to their specific cache setup. You can read more here - https://wpengine.com/support/cookies-and-php-sessions/. WP Engine cache might be disabled in your staging environment and that's why PHP sessions working.
Solution: You need to switch to PHP cookies (or) disable WP Engine cache.


text:
Q: SubItems of ListView are not displayed in winforms I am creating a winforms application in visual studio 2017, I am populating a ListView using a
 List<KeyValuePair<string, string>>

Examples of the data are:
 List<KeyValuePair<ABC, 123>>
 List<KeyValuePair<ABC, 456>>
 List<KeyValuePair<ABC, 789>>
 List<KeyValuePair<DEF, 123>>
 List<KeyValuePair<DEF, 233>>

I try to diplay this in a ListView, where I would like to have sometihng like this:

*

*ABC

*

*123

*456

*789

*DEF

*

*123

*233

Where the ABC and the DEF are selectable only. I try to write a code to do this, but unfortunately it only displays the ABC and DEF without the subitems.
The code I wrote is:
         workOrderClusters = GetItac.FilterWorkOrderClusters();
        // GetItac.FilterWorkOrderClusters() is a
        List<KeyValuePair<string,string>>
        string current; string previous,
        foreach (var workOrderCluster in workOrderClusters)
        {
            current = workOrderCluster.Key;
            if (current != previous)
            {
                var listViewItem = new ListViewItem(workOrderCluster.Key);
                foreach (var cluster in workOrderClusters)
                {
                    if (cluster.Key == current)
                    {
                        listViewItem.SubItems.Add(cluster.Value);
                    }
                }
            }
            previous = current;
            listView1.Items.Add(listViewItem);

My question is, is there anyway to make the ListView display as expected ?

A: ListView shows sub items if it's in Details view and it has some columns.
Let's say you have the following data:
var list = new List<KeyValuePair<string, int>>(){
    new KeyValuePair<string, int>("ABC", 123),
    new KeyValuePair<string, int>("ABC", 456),
    new KeyValuePair<string, int>("ABC", 789),
    new KeyValuePair<string, int>("DEF", 123),
    new KeyValuePair<string, int>("DEF", 233),
};

To convert your data structure to ListView items you can first group data based on the key:
var data = list.GroupBy(x => x.Key).Select(x => new
    {
        Key = x.Key,
        Values = x.Select(a => a.Value)
    });

Then add items and sub items to the control:
foreach(var d in data)
{
    var item = listView1.Items.Add(d.Key);
    foreach (var v in d.Values)
        item.SubItems.Add(v.ToString());
}

And then setup ListView to show them:
listView1.View = View.Details;
var count = data.Max(x => x.Values.Count());
for (int i = 0; i <= count; i++)
    listView1.Columns.Add($"Column {i+1}");

Note
As also mentioned in the comments, probably TreeView is more suitable to show such data. In case you want to add that data to TreeView, after grouping data you can use the following code:
foreach (var d in data)
{
    var node = treeView1.Nodes.Add(d.Key);
    foreach (var v in d.Values)
        node.Nodes.Add(v.ToString());
}


text:
Q: "Jupyter is not recognized" error after activating a new environment in Python I'm using Jupyter as my notebook for Python. I need to switch to another drive and change from the 64-bit version of Python that I downloaded to the 32-bit version (to be compatible with Microsoft Access and pyodbc). I'm using How can I have two different environments within Anaconda? (both Python 3.7, one 32bit and one 64bit) as a guide.
For this I just open the Anaconda prompt to enter the new drive secured by a VPN:
P:

After setting up the correct directory I change the environment in anaconda by running this in the Anaconda Prompt:
conda create -n py32 python=3.7 -c https://repo.anaconda.com/pkgs/main/win-32 --override-channels

Then I activate it in Anaconda Prompt
conda activate py32

However at this point, I try to open the Jupyter Notebook from the Anaconda prompt using:
jupyter notebook

but I get an error saying " 'jupyter' is not recognized as an internal or external command, operable program or batch file". I'm wondering if anyone has any tips for getting around this problem or why 'jupyter' isn't recognized anymore.


text:
Q: How to handle this error Incorrect syntax near the keyword 'Table'." Im creating an application for my brother that will help him at work, I have created a C# form which should pass the data onto a sql table but i receive the error.
Dont know what to do further.
The code that im using is from the video https://www.youtube.com/watch?v=TIAOr2S6-SY&feature=youtu.be
I tried other methods that didnt help me to understand to no avail. Im trying to get into coding and would appreciate help.
"System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.'"

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using System.Data.SqlClient;

    namespace WindowsFormsApp2
    {
        public partial class Form1 : Form
        {
            SqlConnection con=new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\lerro\OneDrive\Documents\DatabaseAmal.mdf;Integrated Security=True;Connect Timeout=30");

            public SqlConnection Con { get => con; set => con = value; }

            public Form1()
            {
                InitializeComponent();
            }

            private void label1_Click(object sender, EventArgs e)
            {

            }

            private void label2_Click(object sender, EventArgs e)
            {

            }

            private void label5_Click(object sender, EventArgs e)
            {

            }

            private void label9_Click(object sender, EventArgs e)
            {

            }

            private void button4_Click(object sender, EventArgs e)
            {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into Table values ('" +textBox1.Text+ "','" +textBox5.Text+ "','" + textBox2.Text + "','" +textBox3.Text + "','" +textBox4.Text + "','" +textBox6.Text + "','" +textBox4.Text + "','" +textBox7.Text + "','" +comboBox1.Text + "','" +textBox8.Text + "','" +textBox9.Text + "','" +dateTimePicker2.Text + "','" +textBox10.Text + "','" +comboBox2.Text + "','" +comboBox3.Text + "','" +comboBox4.Text + "','" +textBox14.Text + "','" +textBox11.Text + "','" +textBox12.Text + "','" +textBox13.Text + "','" + BrowseTextbox.Text + "','" + pictureBox1.Text + "','" + textBox15.Text + "','" +dateTimePicker1.Text + "')";
            cmd.ExecuteNonQuery();
            con.Close();

                MessageBox.Show("record inserted successfully");

            }

         private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Image Files(*jpg; *.jpeg; *.gif; *.bmp;)|*jpg; *.jpeg; *.gif; *.bmp;";
            if (open.ShowDialog() == DialogResult.OK)
            {
                BrowseTextbox.Text = open.FileName;
                pictureBox1.Image = new Bitmap(open.FileName);

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = String.Empty;
            textBox2.Text = String.Empty;
            textBox3.Text = String.Empty;
            textBox4.Text = String.Empty;
            textBox5.Text = String.Empty;
            textBox6.Text = String.Empty;
            textBox7.Text = String.Empty;
            textBox8.Text = String.Empty;
            textBox9.Text = String.Empty;
            textBox10.Text = String.Empty;
            textBox11.Text = String.Empty;
            textBox12.Text = String.Empty;
            textBox13.Text = String.Empty;
            textBox14.Text = String.Empty;
            textBox15.Text = String.Empty;
            pictureBox1.Image = null;
            comboBox1.Text = String.Empty;
            comboBox2.Text = String.Empty;
            comboBox3.Text = String.Empty;
            comboBox4.Text = String.Empty;
            BrowseTextbox.Text = String.Empty;

        }

            private void comboBox2_SelectedIndexChanged(object sender,
    EventArgs e)
            {

            }
        }
    }

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Incorrect syntax near the keyword 'Table'."

A: As you can see in the video he calls his table in the testing database
Table1

but in your Insert statement you write your table is
table

If you followed the video the must stay
 cmd.CommandText = "insert into Table1 values

or else some name you have choosen instead of Table1


text:
Q: How to add numbers to bars with D3.js? I've created a chart and it works fine, but I can't find out how to add numbers to columns. Numbers appear only if I hover the columns.
Tried different variants:
svg.selectAll("text").
data(data).
enter().
append("svg:text").
attr("x", function(datum, index) { return x(index) + barWidth; }).
attr("y", function(datum) { return height - y(datum.days); }).
attr("dx", -barWidth/2).
attr("dy", "1.2em").
attr("text-anchor", "middle").
text(function(datum) { return datum.days;}).
attr("fill", "white");

A link to my example: https://jsfiddle.net/rinatoptimus/db98bzyk/5/

A: Alternate idea to @gerardofurtado is to instead of a rect append a g, then group the text and rect together.  This prevents the need for double-data binding.
var bars = svg.selectAll(".bar")
  .data(newData)
  .enter().append("g")
  .attr("class", "bar")
  // this might be affected:
  .attr("transform", function(d, i) {
    return "translate(" + i * barWidth + ",0)";
  });

bars.append("rect")
  .attr("y", function(d) {
    return y(d.days);
  })
  .attr("height", function(d) {
    return height - y(d.days) + 1;
  })
  .style({
    fill: randomColor
  }) // color  bars
  .attr("width", barWidth - 1)
  .on('mouseover', tip.show)
  .on('mouseout', tip.hide);

bars.append("text")
  .text(function(d) {
    return d.days;
  })
  .attr("y", function(d) {
    return y(d.days);
  })
  .attr("x", barWidth / 2)
  .style("text-anchor", "middle");

Updated fiddle.

A: When you do this:
svg.selectAll("text")

you are selecting text elements that already exist in your SVG. In an enter selection, it's important selecting something that doesn't exist:
svg.selectAll(".text")
    .data(newData)
    .enter()
    .append("svg:text")
    .attr("x", function(datum) {
        return x(datum.name) + x.rangeBand()/2
    })
    .attr("y", function(datum) {
        return y(datum.days) - 10;
    })
    .attr("text-anchor", "middle")
    .text(function(datum) {
        return datum.days;
    })
    .attr("fill", "white");

Here is your fiddle: https://jsfiddle.net/c210osht/

A: You could try using the d3fc bar series component, which allows you to add data-labels via the decorate pattern.
Here's what the code would look like:
var svgBar = fc.seriesSvgBar()
    .xScale(xScale)
    .yScale(yScale)
    .crossValue(function(_, i) { return i; })
    .mainValue(function(d) { return d; })
    .decorate(function(selection) {
      selection.enter()
        .append("text")
        .style("text-anchor", "middle")
        .attr("transform", "translate(0, -10)")
        .text(function(d) { return d3.format(".2f")(d); })
        .attr("fill", "black");
    });

Here's a codepen with the complete example.
Disclosure: I am a core contributor to the d3fc project!


text:
Q: Merge Word Documents in Document Library There is need where I need to merge Word documents saved in a Document Library. I was looking for out of the box solution but did not come across one.
Please provide custom C# solution if there exists one.
Has any one succeed in implemention.

A: I am working on this kind of a solution currently.  You will need to create a custom feature in order to achieve this. You can use the OpenXML DLL for this purpose. This DLL will allow you to merge the documents.
The following steps shall help you to develop:

*

*download the word files locally

*create a new word file that will hold the merged files.

*upload the merged file to the document library

Use the following code for merging the files:
 //creates word file -- accepts complete file path with name as param
 void createWordFile(string fileName)
    {
        using (WordprocessingDocument document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
        {
            MainDocumentPart mainPart = document.AddMainDocumentPart();
            mainPart.Document = new Document(new Body());
        }
    }

    //merges files with page break
    //params : source and destination file paths and unique value for AltChunkId
    public void MergeDocumentWithPagebreak(string sourceFile, string destinationFile, string AltChunkID)
    {
        try
        {
            using (WordprocessingDocument myDoc = WordprocessingDocument.Open(sourceFile, true))
            {
                string altChunkId = AltChunkID;
                MainDocumentPart mainPart = myDoc.MainDocumentPart;
                //Append page break
                Paragraph para = new Paragraph(new Run((new Break() { Type = BreakValues.Page })));
                mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
                //Append file
                AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                using (FileStream fileStream = File.Open(destinationFile, FileMode.Open))
                    chunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
                mainPart.Document.Save();
            }
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }

    }

    //uploads word file to the folder in the document set
    public void UploadFile(string newFileName, string folderURL)
    {
        SPFolder ds = SPContext.Current.Web.GetFolder(folderURL);

        using (FileStream strm = new FileInfo(newFileName).Open(FileMode.Open))
        {
            byte[] data = new byte[strm.Length];
            strm.Read(data, 0, (int)strm.Length);

            String fileToBeUploaded = System.IO.Path.GetFileName(newFileName);
            ds.Files.Add(fileToBeUploaded, data, true);
            ds.Update();
        }
    }

These functions will help you solve the issue.


text:
Q: System of initial value problems with initial conditions at different $t_0$ In all the references I checked the standard initial value problem for an ODE is stated as:
\begin{equation}
\begin{cases}
y'=F(y,t)\\
y(t_0)=y_0
\end{cases}
\end{equation}
for some $F:\mathbb{R}^{n+1}\to\mathbb{R}^n$, and under hypotheses on $F$ one can conclude existence, uniqueness, etc.
My question is: is there a standard way to address the problem:
\begin{equation}
\begin{cases}
y'=F(y,t)\\
y_i(t_i)=y_{0,i}, \quad i=1,\ldots, n
\end{cases}
\end{equation}
where the "initial condition" is not given for the same $t_0$ for all the components of $y$, but at different $t_is$? where by address I mean, to begin with, check existence and uniqueness conditions.

A: The equation $y^{\prime\prime}=-y$ has general solutions $y=C\sin(t)+D\cos(t)$. Even though your question is about first order ODE, since it allow $y$ to be vector we can convert this problem into a first order vector ODE where the components are $y$ and $\dot{y}$
So the initial value problem $y(0)=0$ has general solutions $y=C\sin(t)$. In particular, for all such solutions, $y^{\prime}(\frac{\pi}{2})=0$. When converted to the first order vector ODE, this mean $\dot{y}(\frac{\pi}{2})=0$. So the initial value problem with different starting points $y(0)=0,\dot{y}(\frac{\pi}{2})=1$, in particular, is unsolvable.
Hopefully this explains why existence of solution is not a simple matter when you have different starting points for different coordinates.


text:
Q: php click to sort ordering I've a table with columns that are sorted descending when the header is clicked once, however I'd like to invert the ordering when clicked again.
How do I update the variable $sort when the a tag is clicked each time, or is there a better way of trying to do this?
$orderBy = array('one','two','three');

$sort = "DESC";
$order = 'column1';

if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}

$query = "SELECT column1, column2, column3 ORDER BY $order $sort LIMIT 20";

HTML

1

2

3

A: Two ways:
PHP way - it's ok, but reloads the data at every request.
<?php
// the very top of the page: start a session to remember the previous options
session_start();
if (!isset($_SESSION["order"]))
  $_SESSION["order"] = array("col" => false, "dir" => false);
// set defaults
$dir = 0;
$col = "column1";
$orderBy = array("column1", "column2", "column3");
$orderDir = array("DESC", "ASC");
// check $_GET data
if (isset($_GET["orderBy"]) && in_array($_GET["orderBy"], $orderBy)) {
  $col = $_GET["orderBy"];
}
// check if same col is clicked as last time
// if it is the same => change the order, if not => use default
if ($_SESSION["order"]["col"] == $col) {
  // 1 becomes 0, 0 becomes 1
  $dir = 1 - $_SESSION["order"]["dir"];
}
// remember current options
$_SESSION["order"]["col"] = $col;
$_SESSION["order"]["dir"] = $dir;
// set the order
$sort = $orderDir[$dir];
// set the correct query
$query = "SELECT column1, column2, column3 ORDER BY $col $sort LIMIT 20";

The Javascript way:

*

*use the PHP to provide the data, but not to sort it (remove the links from the table head)

*print the HTML table

*load at the end of HTML a script that sorts the table data on the client side - there are a lot of plugins... example: very simple plugin: sorttable.js (it's old but very simple and good)

A: in_array()  Checks if a value exists in an array
use it :
$orderBy = array('column1','column2','column3');


text:
Q: Using Bootstrap4 with gulp-sass I have installed bootstrap and jquery using node.
"devDependencies": {
  "babel-preset-es2015": "^6.24.1",
  "babel-register": "^6.26.0",
  "bootstrap": "^4.0.0",
  "del": "^3.0.0",
  "gulp": "^4.0.0",
  "gulp-sass": "^3.2.0",
  "jquery": "^3.3.1"
}

The project structure:
project /
├── node_modules /
├── src /
│   ├── scss /
│   │   ├── _bootswatch.scss
│   │   ├── _variables.scss
│   │   ├── styles.scss

The styles.scss has this content taken from the example
@import "variables";
@import "bootswatch";
@import "~bootstrap/scss/bootstrap";

The gulpfile.babel.js has this function to build the css from scss:
const extRes = () => {
    return gulp.src('src/scss/styles.scss')
        .pipe(sass())
        .pipe(gulp.dest('public/css'));
};

And although PhpStorm doesn't complain that it can't find ~bootstrap/scss/bootstrap, the build process fails because gulp-sass doesn't look in the node_modules.
messageOriginal: File to import not found or unreadable: ~bootstrap/scss/bootstrap.
Parent style sheet: C:/Entwicklung/2018/project/src/scss/styles.scss
relativePath: src\scss\styles.scss
domainEmitter: [object Object]
domain: [object Object]
domainThrown: false

I've also tried to use includePaths for gulp-sass, but I couldn't find a way to specify it so that the build process works.
Somebody give me a little help, please.
Update 1:
Meanwhile I have solved the problem, but PhpStorm now complains that it doesn't know bootstrap. Is it possible to bring both solutions together?
The current styles.scss:
@import "variables";
//@import "~bootstrap/scss/bootstrap";
//noinspection CssUnknownTarget
@import "bootstrap";
@import "bootswatch";

The current gulpfile.babel.js:
const extRes = () => {
    return gulp.src('src/scss/styles.scss')
        .pipe(sass({
            includePaths: ['node_modules/bootstrap/scss/'],
            outputStyle: 'expanded'
        }))
        .pipe(prefix('last 2 versions'))
        .pipe(gulp.dest('public/css'));
};

A: Normally you need to mark the directory configured as Incude path (node_modules/bootstrap/scss) as Resource root (Mark directory as/Resource root) to make such imports work. But it's not that easy if node_modules are concerned, as the whole folder is excluded, and all dependencies from package.json are added to javascript libraries and thus can't be marked/unmarked as roots...
You can try the following:

*

*in File | Settings | Languages & Frameworks | JavaScript | Libraries, disable/delete the <project_name>/node_modules library

*in Project tool window, select node_modules/bootstrap, Mark directory as/Not excluded

*select node_modules/bootstrap/scss folder, Mark directory as/Resource root


text:
Q: preg_match for string - string Say I have an array:
$length =['pre-tied','self-tie','large','small'];

How would the preg_match command look like If I wanted to get values of 'string-string' format from the specific array?
foreach($length as $size)
 if(preg_match("/^[A-Z,-,A-Z]$/i",$size))
    do something

or
foreach($length as $size)
 if(preg_match("/^[A-Z,-,A-Z]$/i",$size));
    do something

Actually, I think the second one does not even make sense but since I am new to regular expressions I cannot be sure..

A: When approaching regular expressions, the way I tackle these problems is starting from the very specific and looking for patterns and making it very general.
Simplest match:
 /^pre-tied$/

Matches e-t of pre-tied
 /^[A-Za-z]-[A-Za-z]$/

Then if you are trying to match single-hyphen words, use one of the repeating operators (+, *)
 /^[A-Za-z]+-[A-Za-z]+$/

We can even make the regular expression more complex, like in this similar question, but I think the final regular expression that I came up with should match both words in that array.


text:
Q: Create XML from Excel Table I need some help here, im new at this trying to create XML files from an excel table. I am having some dificulties trying to pass the values from the table do the final XML file.
My table is this:
Table
Code snippet:
Sub ParserXML()

...

Set wb = oExcel.Workbooks.Open(Work_path & "xxxx")
Set ws = wb.Sheets(1)
Row_count = ws.UsedRange.Rows.count

For i = 2 To Row_count

    DIM_NAME = ws.Cells(2, 19).Value
    EFFECTIVE_END_DATE = ws.Cells(2, 20).Value
    EFFECTIVE_START_DATE = ws.Cells(2, 21).Value
    Value = ws.Cells(2, 22).Value
    XMLFile.Write ("<STRING_INDEX DIM_NAME= """ & DIM_NAME & """ EFFECTIVE_END_DATE= """ & EFFECTIVE_END_DATE & """  EFFECTIVE_START_DATE= """ & EFFECTIVE_START_DATE & """  VALUE=""" & Value & """/>" & vbNewLine)

Next

...

End Sub

For now im receiving the same number of lines on XML as the table has, but just with the values of the first row.
Can someone help please. Thank you

A: Its working now! :)
Here is the code:
Set wb = oExcel.Workbooks.Open(Work_path & "\xxxxx.xlsx")
Set ws = wb.Sheets(1)
Row_count = ws.UsedRange.Rows.count

For i = 2 To Row_count

DIM_NAME = ws.Cells(i, 19).Value
EFFECTIVE_END_DATE = ws.Cells(i, 20).Value
EFFECTIVE_START_DATE = ws.Cells(i, 21).Value
Value = ws.Cells(i, 22).Value
XMLFile.Write ("<STRING_INDEX DIM_NAME= """ & DIM_NAME & """ EFFECTIVE_END_DATE= """ & EFFECTIVE_END_DATE & """  EFFECTIVE_START_DATE= """ & EFFECTIVE_START_DATE & """  VALUE=""" & Value & """/>" & vbNewLine)

Thanks anyway!


text:
Q: Can't read folder names for some directories using "ls" in terminal I can't decipher the folder names when using ls. The file names are good. The problem is the green highlight (color surrounding the text) which makes it unreadable. I tried changing the text color in preferences, but that doesn't work. It only appears for some folders. For some directories, though, the folder list appears normally. Attaching both for reference. I don't know what's wrong.
Images for reference:
ls in some directory:

ls in my home directory:

A: The green background appears when the permissions of a directory allow write access for others.
One simple option is to omit coloring and use classification markers to differentiate entries:
ls --color=none -F

Alternatively, change the color for ls. The settings are stored in the $LS_COLORS variable. Use echo $LS_COLORS to take a look. It stores colon-separated color settings for specific cases of files or directories.
The entry of interest is ow=34;43 which stands for "other writable directory" and the color codes of foreground (34=blue) and background (42=green).
Maybe change it to 1;97;45 for a bold white font on purple background?
To do so, add an entry to your shell-rs-file, Assuming bash it would be in ~/.bashrc as:
export LS_COLORS="${LS_COLORS}ow=1;97;45:"

In case the original LS_COLORS does not end with a colon, use
 export LS_COLORS="${LS_COLORS}:ow=1;97;45:"

instead. I.e. ensure that the entries are separated by a colon.
Re-source it via . ~/.bashrc and run the ls-command.
Maybe just test it in a terminal beforehand by just running the export command and ls.
More details in this very nice answer on Askubuntu.


text:
Q: How to login the page using after hashing password i have hashed the password when a user will register ...but when i am trying to login the page it is showing that username or password is wrong...
Here is below the hashing code
// Get values from form
$fullname=$_POST['userid'];
$username=$_POST['username'];
$email=$_POST['uemail'];
$password=$_POST['passid'];
$birthdate=$_POST['birthdate'];
$country=$_POST['mytextarea'];
$hash = hash('sha256', $password);

function createSalt()
{
    $text = md5(uniqid(rand(), true));
    return substr($text, 0, 3);
}

$salt = createSalt();
$password = hash('sha256', $salt . $hash);
// Insert data into mysql
$sql="INSERT INTO tbl_registration(`fullname`,`username`,`email`,`password`,`birthdate`, `country`) VALUES('{$fullname}', '{$username}', '{$email}', '{$password}', '{$birthdate}', '{$country}' )";
$result=mysql_query($sql);

Here is below i am using the login code...
// userName and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1 ){
    if(crypt($password, $row['Password']) == $row['Password'])
    {
        header("location:index.php");
        exit();
    }
}
else {
    //echo "Wrong Username or Password";
    header("Location:login.php?errorMssg=".urlencode("Wrong Username or Password"));
}

So what i will do now..

A: Your are comparing the hashed/salted password with the text-password.
For example:
5a44e87906e4e5dbf7991d5784fd56f14dc426aafbd8dbb7b1e0953e1399f2ad is not equals foo
Note: mysql functions are deprecated. You should use PDO or other. You code can be written a little bit cleaner.  If you need a better explanation, I can help you with it.
edited hashing code:
// Get values from form
$fullname=$_POST['userid'];
$username=$_POST['username'];
$email=$_POST['uemail'];
$password=$_POST['passid'];
$birthdate=$_POST['birthdate'];
$country=$_POST['mytextarea'];
$hash = hash('sha256', $password);

function createSalt()
{
    return '2123293dsj2hu2besdbsjdsd';
}

$salt = createSalt();
$password = hash('sha256', $salt . $hash);
// Insert data into mysql
$sql="INSERT INTO tbl_registration(`fullname`,`username`,`email`,`password`,`birthdate`, `country`) VALUES('{$fullname}', '{$username}', '{$email}', '{$password}', '{$birthdate}', '{$country}' )";
$result=mysql_query($sql);

edited login code:
// userName and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$salt = createSalt();
$hash = hash('sha256', $mypassword);
$mypassword = hash('sha256', $salt . $hash);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1 ){
    if(crypt($password, $row['Password']) == $row['Password'])
    {
        header("location:index.php");
        exit();
    }
}
else {
    //echo "Wrong Username or Password";
    header("Location:login.php?errorMssg=".urlencode("Wrong Username or Password"));
}

function createSalt()
{
    return '2123293dsj2hu2besdbsjdsd';
}

A: Here is some illustration, but notice this is not a suggestion or good practice.
Lets say you have database table with minimal field Id, username, password. So when you take the input value from password field you encrypt it using any method you choose.
Example: $password = sha1($_POST['password']); in this case user entering the value 'abcdef'. Because it was encrypting using sha1 you got the value turning from abcdef to 1f8ac10f23c5b5bc1167bda84b833e5c057a77d2
Then you save this to database, so inside your database password column you have value 1f8ac10f23c5b5bc1167bda84b833e5c057a77d2.
Now when the user want to login he/she entering abcdef <= this is what you got from the input field. So, before you compare the value from the database vs input, again you have to turn the value provided by input to sha1 encryption.
$password = sha1($_POST['password'];

Now you got the value encrypted, so it was same type data to compare. Move forward, lets compare it.
$query = "SELECT * FROM tableName WHERE (username='$username' AND password='$password')";
$result = mysqli_query($conn, $query);
if (@mysqli_num_rows($result) == 1)
{
   //if one database row (record) matches the input start the session, fetch the record and insert the three values in an array
    session_start();
    $_SESSION = mysqli_fetch_array($result, MYSQLI_ASSOC);
    header("Location: any/where/you/like");
}
else
{
    // No match was made
    $errors[] = 'Sorry no record match with the data you have submitted';
}

I think thats the very basic to compare encrypted value. Once again this is just illustration & not a solution or suggestion.

A: You should really switch to the PHP function password_hash(). Neither the SHA-256 algorithm and especially not a static salt are appropriate to hash passwords.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

If you are interested in more information, have a look at my tutorial about safely storing passwords.


text:
Q: Ito's formula but not given $\mu$ and $\sigma$ I have a little question from one of my worksheets(the solution I was given was almost not even a solution, super brief).

let $f(t,x)=t\cos(x)$. Use Ito's formula to calculate $df(t,W_t)$.

Well, Ito's formula is $df=(\frac{\partial f}{\partial t}+\mu \frac{\partial f}{\partial x}+\frac{\sigma^2}{2} \frac{\partial ^2 f}{\partial x^2})dt + \sigma \frac{\partial f}{\partial x}dW_t$ if I am correct. I can calculate each partial derivative wrp to $f$ but what of $\mu$ and $\sigma$?Do I just leave them as some constant which is unknown?
The solutions simply gives me the derivatives and then it only says "Now apply Ito's formula" and over. Doesn't show me the final result/answer as to what $df$ becomes under Ito.
Can someone tell me if there is a way to find $\mu$ $\sigma$ given only $f$? Or do I really just leave it like so.
Thank you

A: Itô's formula, as you've written it, is to compute $df(t, X_t)$ where $X_t$ is a process satisfying $dX_t = \sigma\, dW_t + \mu \,dt$.
So in your case, take $\mu = 0$ and $\sigma = 1$, so that $X_t = W_t$.


text:
Q: subsubsection without subsection but restart numbers in next section Well I have a problem that look like this

1.First section
   1.first subsubsection
   2.second subsubsection
   2.Second section
   3.third subsubsection

how do i fix like

1.First section
   1.first subsubsection
   2.second subsubsection
   2.Second section
   1.another first subsubsection

this?

A: Why do you want a subsubsection without a subsection???
If it is just a one-off then \setcounter{subsubsection}{0} will reset it, if it is a general feature then (a) something is very wrong: you should not need to do this and (b) you can do
\makeatletter
\@addtoreset{subsubsection}{section}
\makeatother


text:
Q: What am I doing wrong in align-items code? I am trying to align the img and text vertically but align-items is not working. I am using a bootstrap template. When I inspect the section it says "display: block;". Can that be the reason? You can see my code below:
html;

About Us

          About text...

css;
.about h3 {
  font-weight: 600;
  font-size: 32px;
  margin-bottom: 24px;
}

#about .container {
  align-items: center;
}

A: Hi,
align-items Css Property. Works only with display: grid and display: flex
Otherwise it's not working. You can add display: flex property with !important declaration. But It can change the col-lg-6 desgin
Or you can use position: absolute to align items vertically. But it isn't best practice
With Display flex
.about h3 {
  font-weight: 600;
  font-size: 32px;
  margin-bottom: 24px;
}

#about .container {
  display: flex !important;
  align-items: center;
}

With Position absolute
.about h3 {
  font-weight: 600;
  font-size: 32px;
  margin-bottom: 24px;
}

#about .container {
  position: relative;
  align-items: center;
}
#about .container * {
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}

A: You can try;
#about .container {
      vertical-align: middle;
      text-align: center;
    }

A: You can try to add the custom class to the container and then add some extra styling to achieve this.

.about h3 {
  font-weight: 600;
  font-size: 32px;
  margin-bottom: 24px;
}

.about-container {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center
}

#about .container {
  align-items: center;
}

About Us

          About text...


text:
Q: Repeat x-axis values using myplotlib I have below data and I want to plot the graph with repeating x-axis.
| 30 |  | 0.650297475 |
| 40 |  | 0.657665519 |
| 50 |  | 0.669169975 |
| 60 |  | 0.695916956 |
| 50 |  | 0.680254894 |
| 40 |  | 0.663912144 |
| 30 |  | 0.653692469 |
| 20 |  | 0.644423894 |
| 10 |  | 0.637784575 |
|  0 |  | 0.626213656 |
| 10 |  | 0.637769063 |
| 20 |  | 0.643006988 |
| 30 |  | 0.646742206 |
| 50 |  | 0.668539731 |
| 60 |  | 0.694959931 |
| 50 |  | 0.679511669 |
| 40 |  | 0.6633013   |
| 30 |  | 0.653026313 |
| 20 |  | 0.644970369 |
| 10 |  | 0.63772925  |
|  0 |  | 0.626494163 |
| 20 |  | 0.643006456 |
| 30 |  | 0.646692806 |
| 40 |  | 0.656562469 |
| 50 |  | 0.668683988 |
| 60 |  | 0.695289806 |
| 50 |  | 0.680420325 |
| 40 |  | 0.663145675 |
| 30 |  | 0.654077156 |

I am trying to plot it using myplotlib
x=range(len(x_axis))
fig = plt.figure()
ax = plt.gca()
ax.ticklabel_format(useOffset=False)
ax.set_xticks(x_axis, minor=True)
CH1 = ax.plot(x, y_axis)
ax.legend([parameter])#,bbox_to_anchor=(1.05, 1),loc=2, borderaxespad=0
fig.savefig("plotfile_get_Vendor_version_here"+".png")
plt.close(fig)

But the x-axis values are terminating at 30.
I understand this is because of range function. Is there anyway I can fix this.
I would be really helpful for the support.
Regards,
Pavan

A: You need ax.set_xticks() to set the tick positions and ax.set_xticklabels() to actually print the ticks. Try:
import numpy as np
import matplotlib.pyplot as plt

# the data:
x_axis = np.array(
    [ 30.,  40.,  50.,  60.,  50.,  40.,  30.,  20.,  10.,   0.,  10.,
      20.,  30.,  50.,  60.,  50.,  40.,  30.,  20.,  10.,   0.,  20.,
      30.,  40.,  50.,  60.,  50.,  40.,  30.])
y_axis = np.array(
    [ 0.65029748,  0.65766552,  0.66916997,  0.69591696,  0.68025489,
     0.66391214,  0.65369247,  0.64442389,  0.63778457,  0.62621366,
     0.63776906,  0.64300699,  0.64674221,  0.66853973,  0.69495993,
     0.67951167,  0.6633013 ,  0.65302631,  0.64497037,  0.63772925,
     0.62649416,  0.64300646,  0.64669281,  0.65656247,  0.66868399,
     0.69528981,  0.68042033,  0.66314567,  0.65407716])

x=range(len(x_axis))

fig, ax = plt.subplots(1, 1)
ax.set_xticks(x) # set tick positions
# Labels are formated as integers:
ax.set_xticklabels(["{:d}".format(int(v)) for v in x_axis])
ax.plot(x, y_axis)

fig.canvas.draw() # actually draw figure
plt.show() # enter GUI loop (for non-interactive interpreters)

Alternatively you could try something like this


text:
Q: in gradle build.gradle file - how can i check if a project exists? Let's say in a build.gradle file I want to do something like:
ext.sharepointBuildDir = project(":MainProject:sharepoint").buildDir.path
But in certain configurations that project may not exist.
How can I check "does a gradle project exist"?

A: You can use a findProject method, which is according to it's description

Locates a project by path. If the path is relative, it is interpreted relative to this project.
Returns: The project with the given path. Returns null if no such project exists.

So, you can simply use it as follows:
if (findProject(':MainProject:sharepoint') != null) {
    println 'project exists'
} else {
    println 'project does not exist'
}


text:
Q: Drag and drop prevent multiple item to move at the same time I've got, in a UIScrollview, multiple custom subviews which inherit from UIView and which are draggable. Everything works fine with it except that i'm able to drag two or more subviews at the same time. The gesture recognizer are attached to my custom subviews and implemented inside this class.
Is there any way to prevent this behavior ?
EDIT : I've already tried to add in the delegate
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}

But it's not working since all the subviews handle themselves their own gesture recognizer.

A: The GestureRecognizerDelegate protocol has a function to specify whether multiple gesture recognizers can act simultaneously. I don't know if that works in your case but it is worth a try:
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return false
}

A: I know it is an old question but I came across the same problem where I want only one item to be draggable at same time. You can loop through all your draggable subviews and update their properties as below.
           subiew.isExclusiveTouch = true
    subview.isMultipleTouchEnabled = false

Now only one subview will be draggable at same time.


text:
Q: Get the value of anchor using jquery

    <<

        1
        2
        3
        4
        5
        …
    33

    >>

My question is how to get the value 33 using jquery.

A: $('.paginate_button').last().text()

looks like you have updated the question, which makes the answer incorrect, so below is my updated answer.
$('#myTable_reports_view_paginate span > a.paginate_button').last().text()

A: Use :last selector , to avoid next use :not()

alert($('a.paginate_button:not(.next):last').text())

  <<

                        1
                        2
                        3
                        4
                        5
                        …
  33

  >>

You can also use last() and not()

alert($('a.paginate_button').not('.next').last().text())

  <<

                        1
                        2
                        3
                        4
                        5
                        …
  33

  >>

A: Try this
$('.paginate_button:contains("33")').text()


text:
Q: How to know if app uses C2DM? Do you have concrete step to know if an app is using C2DM?
According to c2dm website;
"What Does the User See?
When mobile device users install an applications that include C2DM, they will get a permission from Android Market informing them that the application includes C2DM. They must approve the use of this feature to install the application."
This is the permission in the Manifest file of the C2DM app;
<permission
    android:name="com.example.jumpnote.android.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.example.jumpnote.android.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

Specifically i want to confirm if Skype, Talk, eBuddy uses C2DM, do you know the answer?
Does C2DM has equivalent display in;
In Settings > Applications > Manage applications > All> Talk > Permission ?

A: You have answered your own question. You can tell if an app contains C2DM by checking the permissions it requests.


text:
Q: How to connect Angular 2 with MySql Database using Nodejs? I started new project for Retail Shop, I need to connect Angular 2/5 with MySQL Database using Node or any other method. I need Examples for Select, Create, Delete, Update. for now i need to create Login Page.

A: Well connecting Angular???
First learn that Angular, front end, does never connect to any database directly (not counting a New England db or LocalStorage as Database).
You need node or any other server side technology and then serve a REST API for providing data to your front end applications. SO actually your front end app in Angular is a complete separate application and your server side application will only connect to DB, handle logic and serve a REST API.
I use Sequelize for easy connecting and writing queries in JSON syntax.
Some more resources:
https://www.sitepoint.com/user-authentication-mean-stack/
https://medium.com/of-all-things-tech-progress/starting-with-authentication-a-tutorial-with-node-js-and-mongodb-25d524ca0359
Full Example app: http://jasonwatmore.com/post/2017/02/22/mean-with-angular-2-user-registration-and-login-example-tutorial

A: The only way you can do that is through http requests to the nodeJs server, since Angular runs in the web browser, while node runs on a server (javascript execution environment).
To create an Http service in Angular you can follow this link. In this way the nodejs server will be able to receive the data and be able to process them through a connection to mysql.

A: Angular is for your front end.
If you want Angular like syntax / Typescript for the back-end / server, have a look at: nest.
Nest (NestJS) is a framework for building scalable Node.js server-side applications.


text:
Q: Do I need to delete an static std::map? In some classes I have an static std::map with pointers inside. My question is if I need to delete at the end of the program or this memory is automatically freed. My concern is if the pointers stored inside are correctly deleted through our destructors when std::map is deleted.
Thanks.

A: If the map contains pointers that were allocated with new (or new[], or malloc), then each pointer needs a corresponding delete (or delete[], or free).
The map's destructor wont know what to do with a bald pointer.  Consider using a smart pointer that has appropriate move semantics like a boost smart pointer or if you've got a very new compiler, one of the C++0x smart pointers.  However, do not use the current standard's std::auto_ptr, inside of STL containers.  See this thread for why.
Edit:
As Billy ONeal pointed out, boost::ptr_map is also designed exactly for this purpose.

A: If I understand the situation correctly, you don't delete the map itself. But you probably need to delete the objects the map is pointing to. It would probably be a really good idea to use a smart pointer such as Boost shared_ptr in your map instead of native pointers. Then the objects would be cleaned up automatically.
Edit:
Using Boost ptr_map might be an even better idea.

A: The memory is "automatically freed", in the sense that the entire process memory is freed, but the destructors of the objects pointed to will not be called. This can cause a resource leak, if you use RAII.

A: std::map never calls delete on it's members. Assuming you're working with a relatively recent operating system, the OS will reclaim the memory occupied by the members on process termination, but the destructors will not run.

A: If you have a map of pointers, then the answer is 'no', your destructors will not be called, but 'yes', the memory will be freed at the end of process execution. All memory allocated by a process is always freed by the Operating System when a process exits (even if it crashes), but destructors might not be called.

A: A memory "leak" is where memory is unintentionally not deleted over a period of time, and ends up reducing as the process continues. If it is a type of process that runs for a very long period of time, eg a server that is rarely restarted, this can be a major problem.
Memory leak detectors will pick up on any memory that is allocated and not deleted by a programming call, so valgrind, etc. will report this as a leak.
It is as well to check your code with programs like valgrind, and therefore the less that "gets in the way", the easier it will be to spot real leaks. Therefore my advice is not do just let the system clean up the memory, or singletons, etc, for you when you have allocated a pointer with new (or malloc or new[]).
You can have a "clean-up" routine to do this. Just have an object in the scope of your map that has a deleter (as it will be deleted when it exits) that will clean up the pointers in the map. As you need your object to be deleted first it should be declared later than the map.

A: Like in any case of storage class which stores pointers: you are responsible to deallocate memory they point to. Storage class is responsible only to clean its own resources. Relying on reclaiming memory by OS at the process termination is a bad practice.


text:
Q: How to run a modern userscript on Internet Explorer? I've found it's pretty easy to take a Greasemonkey-type userscript and turn it into extensions/addons for Chrome, Safari, and Firefox. And of course one can run them natively in Chrome, and simply in Firefox using the Greasemonkey addon.
I'm now exploring whether I can run my userscript on IE at all. I tried the ancient Trixie and the bloatwarish ie7pro, but neither run the script correctly. They partially work, but also appear to reload the script many times on the same page, continually inserting the items that should only appear once.  The oft-mentioned Greasemonkey for IE now appears defunct, its domain name (gm4ie.com) having been parked and full of ads.
I've dug in w/ search a bit, looking for information about how to develop IE extensions (e.g. this).  But I've had no luck finding anyone talking about getting a userscript to run inside of an addon.  At the least it looks like javascript might not be available w/in those environments, necessitating a complete rewrite in C#.
Are there any Greasemonkey-type addons I haven't listed above?  Is it possible to convert a javascript userscript into an IE extension?


text:
Q: Install MySQL Automatically on WIN, Linux, macOS I want to use MySQL for an electron app in production and thus, if the client machine doesn't has MySQL already installed on it, then the app will not be able to function. So, is there any way to execute a auto-install MySQL script that installs MySQL on the client machine, even if its not already installed.
Since the app has to be cross-platform, so I am looking for a standard or minimum effort procedure (to speed up the process) to achieve the above, during first-time-app-startup on Windows7+, Ubuntu 14+ and macOS.
I found the following ways to auto-install:

*

*Windows : Link

*Linux & macOS: Create a bash script that runs before first-time-startup of the app. (Although, it will check whether MySQL instance is already present on the machine or not)
Looking for a better option than the above mentioned ones.

A: You may wish to consider the BitNami MySQL distribution; I have always used their VMs when I went after their products, but stand-alone installers are offered for most platforms (including Linux).
(Edit: It seems that the installer for MySQL is offered only for Linux x64)


text:
Q: Como podria validar que los datos que recibido por un texbox sean numeros, sin utilizar ningun metodo en c# hola buenas tardes comunidad, quisiera hacer una validacion de datos pero no me funciona la validación de la manera que la estoy haciendo pues solo me toma un valor como verdadero, y los demás los lee como distinto. lo que quisiera hacer es recorrer ese estring e ir comprobando que si cada caracter de rut_ es igual al que tengo en mi string numeros pero no me funciona, y no puedo usar ningún método para validar. Es un trabajo para la universidad. les agradecería su ayuda
string rut_ = "263285p5-7";
string numeros = "1234567890";
char[] rutDatosNumericos= new char[8];
int longitud= rutDatosNumericos.Length;
int largo= rut_.Length;
string subRut_="0";
Console.WriteLine(largo);
string rutdatos="";
bool validar = false;

for(int i = 0; i <=rutDatosNumericos.Length-1; i++)
{
    rutDatosNumericos[i] = (char)rut_[i];
    Console.WriteLine(rutDatosNumericos[i] + "\n");
}
if(largo<10)
{
    Console.WriteLine("Falta un numero");
    subRut_+= rut_;
    Console.WriteLine(subRut_);

}
else if (largo == 10)
{
    subRut_ = rut_;
    Console.WriteLine("caracteres completos");
    Console.WriteLine(subRut_);
}
Console.WriteLine("Valor del rut actual: "+ subRut_);

for (int i = 0; i <= rutDatosNumericos.Length-1 ; i++)
{

    if (subRut_[i] == numeros[i] +1)
    {
        rutDatosNumericos[i] = (char)subRut_[i];
        Console.WriteLine("Dato guarddo " + rutDatosNumericos[i]);
    }
    else
    {
        Console.WriteLine("No es un numero");
    }
}

A: Para validar sin usar ningún método puedes usar el índice de la tabla ASCII. Me explico:
Todos los caracteres en la tabla ASCII tienen asignado un número/codigo único, por lo que si intentas comparar si el carácter es menor o mayor que el otro depende en realidad estás comparando los números asignados si son mayores o menores.

Por lo tanto, puedes hacer una validación mirando si está dentro del rango:
        string rut_ = "263285p5-7"; //entrada
        char inicio = '0';//carcater inicial del rango a buscar
        char final = '9';//caracter final del rango a buscar

        string rutanumerica = ""; //salida

        for (int i = 0; i <= rut_.Length - 1; i++)//tantas vueltas como caracteres d'entrada
        {

            if (rut_[i] >=inicio && rut_[i]<=final)//comparamos char con char = índice char por índice de char
            {
             rutanumerica+=rut_[i];
                Console.WriteLine("Dato guarddo " + rut_[i]);
            }
            else
            {
                Console.WriteLine("No es un numero " + rut_[i]);
            }
        }
        Console.WriteLine("Resultado:" + rutanumerica);
        Console.ReadLine();

Resultado:


text:
Q: Is there a way to rename the uploaded file without saving it? I tried looking into other solutions, however they suggest either:

*

*to save the file with a different name with saveAs()

*to change the file name once the file is saved with Move() or Copy()
In my case I need to rename it without saving it. I tried changing the file.FileName property, however it is ReadOnly.
The result I'm trying to get is:
public HttpPostedFileBase renameFiles(HttpPostedFileBase file)
{
    //change the name of the file
    //return same file or its copy with a different name
}

It would be good to have HttpPostedFileBase as a return type, however it can be sacrificed if needed.
Is there a way to do this through memory streams or anything else? I appreciate any help, thank you for taking your time to read this. :)

A: Short Answer: NO
Long Answer:
You can rename a file only if file exists on File System.
The files uploaded are not files at all - when you access them using Request.Files.  They are streams.    The fileName property is readonly because of the same reason.
There is no name associated with stream.
As per documentation, FileName property

Gets the fully qualified name of the file on the client.

A: Well, I finally found a way that's really simple - I guess I was overthinking this a bit. I figured I'll just share the solution, since some of you might need it. I tested it and it works for me.
You just have to create your own class HttpPostedFileBaseDerived that inherits from HttpPostedFileBase. The only difference between them is that you can make a constructor there.
    public class HttpPostedFileBaseDerived : HttpPostedFileBase
    {
        public HttpPostedFileBaseDerived(int contentLength, string contentType, string fileName, Stream inputStream)
        {
            ContentLength = contentLength;
            ContentType = contentType;
            FileName = fileName;
            InputStream = inputStream;
        }
        public override int ContentLength { get; }

        public override string ContentType { get; }

        public override string FileName { get; }

        public override Stream InputStream { get; }

        public override void SaveAs(string filename) { }

    }
}

Since constructor is not affected by ReadOnly, you can easily copy in the values from your original file object to your derived class's instance, while putting your new name in as well:
HttpPostedFileBase renameFile(HttpPostedFileBase file, string newFileName)
{
    string ext = Path.GetExtension(file.FileName); //don't forget the extension

    HttpPostedFileBaseDerived test = new HttpPostedFileBaseDerived(file.ContentLength, file.ContentType, (newFileName + ext), file.InputStream);
    return (HttpPostedFileBase)test; //cast it back to HttpPostedFileBase
}

Once you are done you can type cast it back to HttpPostedFileBase so you wouldn't have to change any other code that you already have.
Hope this helps to anyone in the future. Also thanks to Manoj Choudhari for his answer, thanks to I learned of where not to look for the solution.


text:
Q: Anything equivalent for @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) in seam? I need to have a @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) and in a non EJB enviroment, how can we get the same using @Transactional in Seam?
Is any of the values the same as REQUIRES_NEW?
REQUIRED,
MANDATORY,
SUPPORTS,
NEVER

Or is there maybe some other annotation for this?

A: As you say, you would use  @Transactional for non EJB environments, which comes with the 4 types you listed.
I vaguely remember that I read something about a new type "REQUIRES_NEW" in the developer mailing-list, which I found here:
Only problem is that it seems as if the patch never made it into trunk, I have 2.2.1.CR1 on my machine and TransactionPropagationType reads like this:
    public enum TransactionPropagationType
{
   REQUIRED,
   MANDATORY,
   SUPPORTS,
   NEVER;
...
   }


text:
Q: Is this a bug of the sklearn logistic regression? I am new here, so excuse me for any mistakes.
So, I have the following problem: I am simulating a logistic regression data set with a single independent variable (X) and a response variable Y. Then I create two design matrices: One containing X and the other containing X and X, i.e. twice the same variable. Then I fit two models using the two different design matrices. Obviously the coefficient estimates should be "identical", that is intercept_1 = intercept_2 and coef_1 = sum(coef_2). But this is not the case. Also a likelihood ratio test should return a p-value = 1, but this is also not the case. Why is this happening?
My code:
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
from scipy.stats import chi2
N = 100
X = np.random.randn(N)
XX = np.array([X, X]).T
probs = np.exp(X)/(1+np.exp(X))
Y = np.random.binomial(1, probs, N)
myLogReg = LogisticRegression(solver = 'newton-cg', max_iter=1000, fit_intercept=True, random_state=1)
myLogReg.fit(X.reshape(-1, 1), Y)
y_prob = myLogReg.predict_proba(X.reshape(-1, 1))
currentMinusTwoLogLik = 2*len(Y)*log_loss(Y, y_prob)
print(myLogReg.intercept_)
print(myLogReg.coef_)
print("")
myLogRegUpdateCandidate = LogisticRegression(solver = 'newton-cg', max_iter=1000, fit_intercept=True, random_state=1)
myLogRegUpdateCandidate.fit(XX, Y)
y_probCandidate = myLogRegUpdateCandidate.predict_proba(XX)
candidateMinusTwoLogLik = 2*len(Y)*log_loss(Y, y_probCandidate)
print(myLogRegUpdateCandidate.intercept_)
print(myLogRegUpdateCandidate.coef_)
print("")
print(chi2.sf(currentMinusTwoLogLik-candidateMinusTwoLogLik, 1))


text:
Q: Update canvas before function returns When you are inside a JavaScript function and want to update the canvas element then the update takes place only when the function returns. Sometimes one wishes to update the canvas and keep the function running. Is there a way to accomplish this?

A: In general: no, there is no straightforward way to do that, because the browser blocks every ui event until its scripting routines have terminated. This includes updating the canvas (and even closing the browser window e.g. when a script gets to an infinite loop, you may have seen that somewhere before).
Anyway, a more or less ugly way to do this, is using a setTimeout at the point where you want your canvas to be updated:
function reactOnSomething(){
    doSomeStuff();
    drawMyCanvas();
    setTimeout(function(){
       goOnWithOtherStuff();
    }, 20);
}


text:
Q: Создать массив годов в диапазон от 18 до 100 лет Как создать массив годов в диапазон от 18 до 100 лет, который расчитывается так: первый элемент массива текущий год - 100 лет, последний элемент текущий год - 18 лет

A: Если я правильно понял задание тогда так:

function createArrayYers(currentYer){
  const start = currentYer - 100;
  const end = currentYer - 18;
  const arr = [];

  for (let i = start; i <= end; ++i){
    arr.push(i);
  }

  return arr;
}

console.log(createArrayYers(2022));

A: Я в своем проекте на typescript реализовал такой генератор массивов:
const generateArray = (count:number, builder: (index:number) => any) => {
    return Array.apply(undefined, Array(count)).map((e, i) => builder(i));
}

Первый параметр count:number - это количество элементов, которые нужно сгенерировать. Второй параметр builder, который имеет тип (index:number) => any, то есть, функция, принимающая параметром число - индекс нынешней итерации и возвращает значение с любым типом.
Использовать вот так, например, нагенерировать массив с числами от 1 до 100:
const numbers= generateArray(99, (i) => i+1);

Далее, уже для своих условий используйте такой генератор.


text:
Q: Why clustering metrics are worse while adding some features? I am facing something unexpected at first sight and would like to know if you could share some insights.
Basically, I have performed a clustering on both qualitative and quantitative data using the gower distance as dissimilarity metric (with daisy()), which I fed into the agglomerative clustering function hclust(), setting the complete linkage option. To evaluate the clustering performance, I used the function cluster.stats() which raises many metrics like the squared sum of distance within cluster, average silhouette width,... But I used mainly the within sum of squares.
My issue is the following: while adding some features to my input table for clustering, I expected the WSS to be lower (or at least around the same values) because I have more chance for a better discrimination of individuals. It turns out that the other way around: the WSS is lots higher.
My opinion: the more features into it, the more chance the individuals to be considered as different and the bigger the distances. As a result, I also need more clusters to reach the same performance level. What do you think? If my opinion is true, then I would need to calculate like a feature importance score to get rid of useless features. Any recommendation on how to do it?
Other information: quantitative data were scaledfor equal variance.
I cannot provide you with the data as its private.

A: You cannot compare SSQ value or distances with different feature sets (or data, for that matter).
It's trivial to see when you consider the definition. It's a sum over different columns... If you add more columns, the sum cannot decrease.
This holds for almost any such measure, that comparing different feature sets or otherwise different data does not work. They are just heuristics, not objective measures of quality.
What you could do is to always compute the measures on the entire data (all features). Then an algorithm given more columns will likely find a "better" clustering than one given fewer columns. But that again is to be expected...


text:
Q: Path to a text file in a complex hierarchy Inside my solution, I have a folder called "Server". This folder contains a project called "InvestmentAdvisory", which contains the folders Report/Languages/. Inside Languages are a class "Translation", and a CSV file. The class is supposed to load the CSV file.
The namespace of the class "Translation" is like:
 "Server.Modules.InvestmentAdvisory.Report.Languages"

After the application is built, the CSV file ends up in:
 MyApplication\Main\Source\InvestmentAdvisory.Services.Implementation\bin\Debug\Report\Languages\

How do I find the relative path to the CSV from the inside of my Translation class?

A: Sorry if i'm miss understanding but if you need the directory of your application you can get the path by using
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

A: Assuming that your assembly/exe outputs will be in
MyApplication\Main\Source\InvestmentAdvisory.Services.Implementation\bin\Debug
You can use the relative path:
.\Report\Languages\CsvFileName.csv

The easiest approach would be to keep the csv file in the output folder.

*

*Add the csv to project

*Select the csv file and in properties window
(Press F4 to open the window if not present), set Copy To Output
Directory (Always/If Newer).
Then you would not need a path as long as the assembly/exe are all in the same folder i.e. output folder.


text:
Q: How should I modify this segment of .bst code? Could you tell me how to modify this code segment so that the in-text citation always use "et al" for 2 or more authors? This code segment is taken from apacite.bst.
FUNCTION {tentative.cite.num.names.field}
{ 'field :=
 field num.names$  'numnames :=
 numnames #3 <
   {   %
       % 1 or 2 names: always cite all of them.
       numnames  'cite.num.names.full  :=
       numnames  'cite.num.names.short :=
   }
   { numnames #6 <
        {  %
           % 3-5 names: cite all of them the first time,
           % only the first name later times
          numnames  'cite.num.names.full  :=
          #1        'cite.num.names.short :=
        }
        {  %
           % 6 or more names: cite only the first name
          #1  'cite.num.names.full  :=
          #1  'cite.num.names.short :=
        }
      if$
   }
 if$
}


text:
Q: Google Rich Snippets Not Working I'm working on a website for a friend (www.texasfriendlydds.com) and am trying to give them an edge with Rich Snippets that Google allegedly loves. It's a defensive driving school with 10 locations in the Austin area. I've placed the schema.org code within the address of each location, but while searching 'defensive driving austin' - I do not see any of the locations listed. I have 10 of the following code for each location(different address for each):

  Texas Friendly Defensive Driving

      13201 Ranch Road 620

      Austin TX 78750

      4.6 stars - based on 24 reviews

    Free meal w/ $40 tuition

    <meta itemprop="openingHours" content="Thursdays 3:30pm - 9:30pm">Thursdays 3:30pm - 9:30pm

In addition, at the bottom of the page, I aggregate all the reviews in attempt to get organic search rich snippet star-ratings to no avail. I've compared my code directly with the following site:
- http://www.microdatagenerator.com/aggregate-rating-schema-generator/
They were exactly the same (minus the values). You can find their snippets by Googling 'aggregate rating schema' and find the 2nd listing with rich snippet stars and 956 ratings. At one point I read that you need to show proof of your ratings, but this site doesn't do that and they have them.
I've used the Google Structured Data Testing Tool (https://developers.google.com/structured-data/testing-tool/) and everything comes out peachy. So why in the world am I not seeing any results from this?

A: We (Google) don't accept rich snippets for homepages; rich snippet annotations should be placed on leaf pages.


text:
Q: Chain map with one-sided inverse between isomorphic chain complexes quasi Suppose that $C_\bullet$ and $D_\bullet$ are finitely generated isomorphic chain complexes. Let $f:C_\bullet\rightarrow D_\bullet$ a chain map with a one-sided inverse. Is it true that f is a quasi-isomorphism?

A: I think $f$ is even an isomorphism of complexes.
I take it that the complexes are complexes of abelian groups.
Since $C$ and $D$ are isomorphic, we may assume that $f$ is a morphism of complexes from $C$ into itself. There are two cases: $f$ has a right inverse, or $f$ has a left inverse.
In the former case, each $f_i\colon C_i\rightarrow C_i$ is a surjective endomorphism of a finitely generated abelian group. Such an endomorphism is necessarily an isomorphism. It follows that $f$ is an isomorphism of complexes.
Suppose, therefore, that $f$ has a left inverse $g$. The preceding observation applies to $g$, and $g$ is an isomorphism. Since $g\circ f=\mathrm{id}$, one deduces that $f$ is an isomorphism as well.
The same conclusion holds if each $f_i$ has a one-sided inverse, instead of $f$ having a one-sided inverse i.e., if $g$ is not necessarily a morphism of complexes. Proof by similar arguments.


text:
Q: Batch File - Choice Options - Setting Default Option In my example batch file below, I have a few options for the user to select from. In addition, I would like to set a default option. For example, I'd like the user to be able to hit hit [ENTER] and it select the default option (of my choosing) from my list (let's say option 1).
Thanks for the help!
@ECHO OFF
:selector
set input=
ECHO 1. Option 1
ECHO 2. Option 2
ECHO 3. Option 3
set /p input=Select an option number above:
if %input%==1 goto 1
if %input%==2 goto 2
if %input%==3 goto 3

@REM Invalid Choice Message
@echo Not a valid choice
goto selector

:1
echo you picked 1
pause
goto end

:2
echo you picked 2
pause
goto end

:3
echo you picked 3
pause
goto end

:end

A: change set input=    to set input=1


text:
Q: How to deeply merge two object values by keys Trying to see if there is any javascript library functionality that can merge the values for a specific key of two json objects
var x ={ "student-marks":{'math':1,'physics':5} };
var y ={ "student-marks":{'chemistry':3,'history':2} };

using $.extend and $.merge giving below results
$.extend({},x,y)  leads to  { "student-marks":{'chemistry':3,'history':2} }

$.merge(x,y) leads to { "student-marks":{'math':1,'physics':2} }

what I am looking for is { "student-marks":{'math':1,'physics':5, 'chemistry':3,'history':2} }

A: The new spread operator from the ES2018 provides some nice way to do this:

function combine(...list){
  return list.reduce(
     (a,b)=>{
       return {...a,...b}
     }
  )
}

// work as expected with simple objects
console.log(
  combine(
    {x:3,z:1},
    {x:4,m:4},
    {a:1},
    {b:2}
));

// is not a good recursive solution
console.log(
  combine(
    {x:3,z:1,child:{c:1}},
    {x:4,m:4,child:{d:3}},
    {a:1},
    {b:2}
));

This was the best recursive solution that I could get

function combine_recursive(...list) {
    return list.reduce(
        (a,b) => {
            // for non objects return b if exists or a
            if ( ! ( a instanceof Object ) || ! ( b instanceof Object ) ) {
                return b !== undefined ? b : a;
            }
            // for objects, get the keys and combine them
            const keys = Object.keys(a).concat(Object.keys(b));
            return keys.map(
                key => {
                    return  {[key]: combine_recursive(a[key],b[key])}
                }
            ).reduce(
                (x,y) => {
                    return {...x,...y}
                }
            );
        }
    )
}

// testing recursive and the priority
console.log(
  combine_recursive(
    {x:3,z:1,child:{c:1,k:1}},
    {x:4,m:4,child:{d:3,k:2}},
    {a:1},
    {b:2}
));

// using the example of the question
var x ={ "student-marks":{'math':1,'physics':5} };
var y ={ "student-marks":{'chemistry':3,'history':2} };
console.log( combine_recursive(x,y) );

A: You want a deep extend
$.extend(true, {}, x, y);

See the docs for jQuery.extend([deep], target, object1[, objectN])

A: The simple javascript function without depending jQuery will help you to merge two JSON object which has nested objects.
function mergeJSON(source1,source2){
    /*
     * Properties from the Souce1 object will be copied to Source2 Object.
     * Note: This method will return a new merged object, Source1 and Source2 original values will not be replaced.
     * */
    var mergedJSON = Object.create(source2);// Copying Source2 to a new Object

    for (var attrname in source1) {
        if(mergedJSON.hasOwnProperty(attrname)) {
          if ( source1[attrname]!=null && source1[attrname].constructor==Object ) {
              /*
               * Recursive call if the property is an object,
               * Iterate the object and set all properties of the inner object.
              */
              mergedJSON[attrname] = mergeJSON(source1[attrname], mergedJSON[attrname]);
          }

        } else {//else copy the property from source1
            mergedJSON[attrname] = source1[attrname];

        }
      }

      return mergedJSON;
}

A:     https://gist.github.com/samad-aghaei/7250ffb74ed80732debb1cbb14d2bfb0

/**
This script can merge two multi dimensional associative array/objects in javascript by comparing given object with its reference and
will remove additional given keys, adding missed parameteres and also validating values without overhead. Also it will return the default values if no input presented with re-usable reference!
Tested on IE8 and greater.
**/
var module = (function(){
    //To make our reference variable onchangable, have to put it into a function which is fster and more efficient than "JSON.parse(JSON.stringify(VARIABLE))"
    var _defs = function(){
            return {
                   //string, number and boolean are actually regex based validation keys on input values.
                a: ["string", 'Defaul value for "a"'],
                b: ["number", 300],
                c: ["boolean", true],
                d: {
                  da: ["boolean", true],
                  db: ["string", 'Defaul value for "db"'],
                  dc: {
                    dca: ["number", 200],
                    dcb: ["string", 'Default value for "dcb"'],
                    dcc: ["number", 500],
                    dcd: ["boolean", true]
                  },
                  dce: ["string", 'Default value for "dce"'],
                },
                e: ["number", 200],
                f: ["boolean", 0],
                g: ["", 'This is an internal extra parameter']
            }
        }

        var _validation = {
                number: function (defaultValue, userValue) {
                  if(/^[0-9]+$/.test(userValue)) //Only numbers allowed
                    return userValue;
                  else return defaultValue;
                },
                string: function (defaultValue, userValue) {
                  if(/^[a-zA-Z\s]*$/.test(userValue)) //Only A to Z case insentitive with space aloowed.
                    return userValue;
                  else return defaultValue;
                },
                boolean: function (defaultValue, userValue) {
                  if(typeof userValue === 'boolean') //True or False or 0 ,1
                    return userValue;
                  else return defaultValue;
                }
        }

        var _uniqueMerge = function(opts, _ref){
                for(var key in _ref)
                    if (_ref && _ref[key] && _ref[key].constructor && _ref[key].constructor === Object)
                      _ref[key] = _uniqueMerge((opts ? opts[key] : null ), _ref[key] );
                    else if(opts && opts.hasOwnProperty(key))
                      _ref[key] = _validation[_ref[key][0]](_ref[key][1], opts[key]); //or without validation on user enties => ref[key] = obj[key]
                    else _ref[key] = _ref[key][1];
                return _ref;
        }
        var _get = function(inputs){
            return _uniqueMerge(inputs, _defs());
        }
        return {
            options: function(){
            return _get(arguments[0] || null); // for more safety and control on number of input variables! used --> ( arguments[0] || null )
            }
        }
})();

//How to use it:

input_one = {
    a : "Hello World",
  //b : ["number", 400], //User missed this parameter
    c: "Hi",
    d : {
        da : false,
        db : "Hellow! World", // ! is not allowed
        dc : {
            dca : 10,
            dcb : "My String",
            dcc: "3thString",
            dcd : false
      },
      dce: "ANOTHER STRING",
    },
    e: 40,
    f: true,
    z: 'x'
};
console.log( JSON.stringify( module.options(input_one), null ,2 ) );
//Output:
/*
{
  "a": "Hello World",
  "b": 300,
  "c": true,
  "d": {
    "da": false,
    "db": "Defaul value for \"db\"",
    "dc": {
      "dca": 10,
      "dcb": "My String",
      "dcc": 500,
      "dcd": false
    },
    "dce": "ANOTHER STRING"
  },
  "e": 40,
  "f": true,
  "g": "This is an internal extra parameter"
}
*/
input_two = {
    a : 32,
  //b : ["number", 400], //User missed this parameter
    c: "Hi",
    d : {
        da : false,
        db : "HelloWorld",
        dc : {
            dca : 10,
            dcb : "My String",
            dcd : false
      },
      dce: 73,
    }
};
console.log( JSON.stringify( module.options(input_two), null ,2 ) );
//output
/*
{
  "a": "Defaul value for \"a\"",
  "b": 300,
  "c": true,
  "d": {
    "da": false,
    "db": "HelloWorld",
    "dc": {
      "dca": 10,
      "dcb": "My String",
      "dcc": 500,
      "dcd": false
    },
    "dce": "Default value for \"dce\""
  },
  "e": 200,
  "f": 0,
  "g": "This is an internal extra parameter"
}
*/
//Empty input will return the default values!
console.log( JSON.stringify( module.options(), null ,2 ) );
//Output
/*
{
  "a": "Defaul value for \"a\"",
  "b": 300,
  "c": true,
  "d": {
    "da": true,
    "db": "Defaul value for \"db\"",
    "dc": {
      "dca": 200,
      "dcb": "Default value for \"dcb\"",
      "dcc": 500,
      "dcd": true
    },
    "dce": "Default value for \"dce\""
  },
  "e": 200,
  "f": 0,
  "g": "This is an internal extra parameter"
}
*/

A: A bit less verbose.
answer = { "student-marks": Object.assign(x['student-marks'], y['student-marks']) }

*

*warning this has side-effects on x.


text:
Q: Show edges only on hover I exported to a Sigma.js template from Gephi. I want the edges to be shown only when you hover over the node. I added this in network/config.json but it is not helping:
  "drawingProperties": {
  **"drawEdges": false,**
  "defaultEdgeType": "curve",
  "defaultHoverLabelBGColor": "#002147",
  "defaultLabelBGColor": "#ddd",
  "activeFontStyle": "bold",
  "defaultLabelColor": "#000",
  "labelThreshold": 10,
  "defaultLabelHoverColor": "#fff",
  "fontStyle": "bold",
  "hoverFontStyle": "bold",
  "defaultLabelSize": 14
}

network/js/main.js :
var a = sigma.init(document.getElementById("sigma-canvas")).drawingProperties(drawProps).graphProperties(graphProps).mouseProperties(mouseProps);

PS: I don't know javascript

A: I was able to do it
configProps={
drawEdges: false
};

var a = sigma.init(document.getElementById("sigma-canvas")).drawingProperties(drawProps).graphProperties(graphProps).mouseProperties(mouseProps).configProperties(configProps);

PS: I know nothing about js


text:
Q: how to change value of a button on click I am trying to change the value of a button when onclick. so far I am able to get that working but i would like it to change back to the original value when click again. any suggestions?
my code:
{if $activity_count > "0"}
<input onclick="change()" type="button" class="rbutton" value="Show/Hide" id="show_act" />

{literal}
  <script>
   function change()
 {
  document.getElementById("show_act").value="Hide/Show";

}
 </script>
{/literal}

{else}
      {/if}

A: Set a flag:
var state = true;

Then modify your change function to toggle the state and do the appropriate update based on the state:
function change()
{
  var textValue = state ? "Hide/Show" : "Show/Hide";   // select the value based on the state
  document.getElementById("show_act").value=textValue; // apply the value
  state = !state;                                      // toggle the state for the next click
}

Here is a live example: http://jsfiddle.net/7kxA8/

A: Try this:
document.getElementById("show_act").value = (document.getElementById("show_act").value == "Show") ? "Hide" : "Show";

This one line code is enough within change() function.

A: Here is an example that will have a button that says hello and goodbye when it is clicked.  The variable is a bit challenging to call with the variable as document.getElementById("show_act").  In this case, the submit button has an ID called "show_act" so be sure you keep track of what you name it.  Good luck in your programming!
<script>
function change(id,text1,text2){
    if(document.getElementById(id).value == text1) document.getElementById(id).value = text2;
    else document.getElementById(id).value = text1;
}
</script>
<input onClick="change('show_act','Show','Hide');" type="button" class="rbutton" value="Show" id="show_act" />

A: You can try this:-
function change()
{
var element = getdocument.ElemnetById .("show_act");
 element.setAttribute("clicked",true);
if(element.getAttribute("clicked") === 'true'){
element.value="Show/Hide";
element.removeAttribute("clicked")
}else {
element.value="Hide/Show";
}
}


text:
Q: Has Apple completely dropped support of the COM API for iTunes? Apple used to provide a COM-based SDK for iTunes on Windows. This could be found via https://developer.apple.com/downloads/ and a search for iTunes COM. It appears as if the download has been removed.
The API hasn't been updated in years, so pulling it from the download section makes sense.
Is there any official communication from Apple, that the iTunes COM API has been discontinued?
Update
Apple started distributing iTunes via the Microsoft App Store. It seems that  the version distributed there does not allow COM communication at all, because of sandboxing. An official confirmation would be appreciated.


text:
Q: imbalanced-learn: how is the threshold calculated in the instance hardness threshold method? I am looking at the source code of the InstanceHardnessThreshold transformer from imbalanced-learn, here: https://github.com/scikit-learn-contrib/imbalanced-learn/blob/12b2e0d/imblearn/under_sampling/_prototype_selection/_instance_hardness_threshold.py#L167
And I am wondering how exactly the threshold is calculated and what the rationale is?

A: After discussing with the maintainers of the imbalanced-learn package, this is what I learned:
The threshold is determined as follows:
threshold = np.percentile(
            probabilities[y == target_class],
            (1.0 - (n_samples / target_stats[target_class])) * 100.0,
)

where n_samples is the number of samples desired in the final dataset from the majority class and target_stats[target_class] is the total number of the majority class present in the original dataset.
We need to find a probability threshold such that the number of samples above that threshold agrees with the number of samples requested in sampling_strategy. By default, it will be the number of samples in the minority class, unless the users declares otherwise.
Instance hardness is the probability of an observation being miss classified. In other words, it is 1 - probability of the class.
The idea is that the probabilities given by the estimator are related to the certainty for a sample to belong to the class. Therefore, a percentile of 0.0 would mean that we select all samples while a percentile of 1.0 mean that we will select a single sample (the one with the maximum probability). So the threshold corresponds to select the N most certain samples to belong to class C as seen per the estimator. N is defined by the sampling_strategy parameter (e.g., the expected balancing ratio).
This method may return more observations than those requested by the user. This is mentioned in the documentation.


text:
Q: Origin and evolution of "hapless" I would like to know what the origin of hapless is.
For example,

He is a hapless person

means

He is an unfortunate person.

Has it got anything to do with the fact that hapless people live their lives with no good things hap-pening to them? Was there hapful or a similar word back in the times?

A: This is right; hap is a root that appears in many English words and its original meaning is indeed that of "good luck".  It is traced back to Old Norse (the language spoken by the Viking invaders who entered the English scene during the 9th century.
In Old Norse, you would have these two words:

*

*happ good luck, good fortune.

*óhapp bad luck, bad fortune.

So that hapless is a synonym for ill fated.
This root appears in many English words.

*

*happy of course, since good luck brings happiness.  This is common in various languages: for instance in German, "glücklich" means both happy and fortunate.

*perhaps: by any chance.  There used to be also mayhaps, now archaic.

*to happen, here good luck is closer to the more neutral sense of chance.

*haphazard, which has a connotation of risk because you leave something to chance.

*a mishap, an unlucky accident.

*more recently coined words are happenstance (from happening + circumstance) or happenchance.

In Old English you would find gehaep for "convenient,suitable".

A: "Hapless" came from the word "hap", which means:

one's luck or lot.

Thus, "hapless" would mean luckless, or unfortunate, unlucky.
Etymonline.com:

"unfortunate," c.1400, from hap (n.) in the sense "good luck" + -less.

Although "hap" has the meaning of "occurrence, happening, event", "hapless" came from "hap"'s meaning of "luck", not it's other meaning(the above).


text:
Q: VR 360 video playback in Unity app is constantly choppy, not at all smooth on Oculus Quest 2 I'm building a simple 360 monoscopic video player app in Unity for Oculus Quest 2. The video is 4096x2048 30fps mp4 which plays very smoothly in the Oculus TV app but inside my app, it's constantly choppy as if it were 15fps or lower. I have tried many encoding options, tried using the AVPro demo plugin but no luck.
I followed this tutorial: https://learn.unity.com/tutorial/play-360-video-with-a-skybox-in-unity
Any help is very much appreciated!

A: It was the mismatch between the 30 fps video and the default 72 Hz display refresh rate of the Quest 2. I set the frequency to 90 with this line of code
Unity.XR.Oculus.Performance.TrySetDisplayRefreshRate(90f);

...and now the video plays smoothly.


text:
Q: IE7, IE8 support for css3 media query I have tried :
@media screen and (max-width:1024px) {
.sidebar{width:630px;}
}

to get the fix for IE7 and 8 but its not working, where as it works for IE9 and other browsers. Is there a different way of writing this. I have tried to include the css3mediaqueries js as well but no success.
Is there any support at all for IE7 and IE8?

A: Include this meta tag in the .
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Internet Explorer 8 or older doesn't support media query. You can use media-queries.js or respond.js to add media query support in IE.

I think this two links will help you.

*

*http://cssmatter.com/blog/ie7-and-ie8-support-for-css3-media-query/

*http://webdesignerwall.com/tutorials/responsive-design-in-3-steps/comment-page-2
Update
css3-mediaqueries-js is moved on github

A: In general, the steps to resolve are a combination of JS plugins, conditional comments and a testing environment.
I have successfully used respond.js for media query support, you can download it from github.
- use conditional comments to avoid adding this in modern browsers

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

sdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdfsdf sdf sdfsdf sdf

A: I have not tried the css3-mediaqueries.js! Maybe you give respond.js a try. This actually works for IE 6-8 which natively do not support Media Queries (see Can I use ...).
Anyway, why would you still support IE 7 nowadays?
Each system still running an IE 7 may be updated to IE 8. And also the fallback for modern CSS3 layout features like Flexbox is much easier cause of IE 8 support for 'display: table-xy' (which is not supported by IE 7).
Personally I do not use any Shims/ Polyfills for the basic layout because in my opinion it is counterproductive to make the CSS layout depending on Javascript support.

A: To my knowledge, I think media queries are not supported for IE7 and IE8.
See here
Just came across this thread, there may be workaround for this.
Original Post here: IE8 support for CSS Media Query


text:
Q: How to reduce redundant code during error checking
NOTE: The restriction is that I cannot use exceptions (the code is eventually compiled with exceptions disabled - not under my control). The project is a real-time 3D graphics application.

I am using my own error class (I had posted a question regarding that not too long ago) which each class uses. Very simple, all it does it records an error during a function call. The function returns that error and it can also be checked by calling SomeClass->GetLastError(). If it is NO_ERROR (all enums) then we can proceed, although we can chose to ignore it (for example if a particular object does not load, we can ignore it, put an ugly pink box in its place and flag an error). A function CreateScene() is called when a State is created which then proceeds to call various functions that are responsible for creating the scene. All these functions might potentially return an error. So what I then have is something like this:
if (CreateGrid() != NO_ERROR)
{
  mCore->Terimate();
  mLog->Error("\n[FATAL] Initialization Failed, check error log");
  return;
}
if (SomeOtherFunc() != NO_ERROR)
{
  mCore->Terimate();
  mLog->Error("\n[FATAL] Initialization Failed, check error log");
  return;
}

The functions called might have different function signatures, so the arguments can be different although the return type is always an integer. I have quite a few calls like the one above so I wrote a #define for it which takes in the function as the parameter and is exactly the same as the code above. So now, the above code looks like:
CALL_FUNC(CreateGrid());
CALL_FUNC(SomeOtherFunc());

The define is undefined once I am done with it. Anyway, this is the only idea I could come up with. Even though it has an ugly #define the resulting code is clean. Is there a better technique that I should be using here?
Thanks

A: Assuming you really don't care which function fails or can determine which one failed by some means other than testing the return value,
if (CreateGrid() != NO_ERROR || SomeOtherFunc() != NO_ERROR)
{
    // Handle error
}

A: The correct answer is "use exceptions" but it sounds like reasons beyond your control are preventing you using the ideal solution.  Here's my alternative: consider goto - considered harmful by some, but perfectly legitimate for C-style error checking.  Below is an example, note that all the error handling is in one place, and you know the error code in the error handler, which gains you some of the advantages of exceptions, without actually using exceptions.
int ret;

if ((ret = CreateGrid()) != NO_ERROR)
    goto Error;

if ((ret = SomeOtherFunc()) != NO_ERROR)
    goto Error;

// ...

Error:
mCore->Terminate();
mLog->Error("\n[FATAL] Initialization Failed, check error log");
// Note that here, 'ret' stores the value of the last error code.
// This may be useful for further diagnostics at this point, and you
// probably want to log it too.
return;