text:
Q: Merging cells on table: error I'm want to merge twon cells of the same line on a table. I found in previous questions the multicolumn command, but it doesn't compile and I can't figure what is wrong with my code. Do I need a package? Couldn't find one. There goes the code..

\begin{frame}{Discussão: Fisiologia do andar medular}
    \begin{tabular}{c c}
        \centering
        \textbf{Lesão em NMS} & \textbf{Lesão em NMI} \\
         & \\
        \pause
        \multicolumn{2}{c}{Perda da atividade motora voluntária}\\% & Perda da atividade motora voluntária\\
        \pause
        Hiperreflexia & Hiporreflexia \\
        \pause
        Hipertonia & Hipotonia \\
        \pause
        Atrofia musc por desuso & Atrofia musc por denervação \\
        \pause
        Paralisia espástica & Paralisia flácida \\
    \end{tabular}
\end{frame}

the error message when compiling:

! Misplaced \omit.
\multispan ^^@-\omit
                   \@multispan
l.260   \end{frame}

thank you

A: Just put the \pause before the line break as follows:
\documentclass{beamer}

\begin{document}
\begin{frame}{Discussão: Fisiologia do andar medular}
    \begin{tabular}{c c}
        \centering
        \textbf{Lesão em NMS} & \textbf{Lesão em NMI} \\
         & \pause\\ %%pause before linebreak
         \multicolumn{2}{c}{Perda da atividade motora voluntária}\\% & Perda da atividade motora voluntária\\
        \pause
        Hiperreflexia & Hiporreflexia \\
        \pause
        Hipertonia & Hipotonia \\
        \pause
        Atrofia musc por desuso & Atrofia musc por denervação \\
        \pause
        Paralisia espástica & Paralisia flácida \\
    \end{tabular}
\end{frame}
\end{document}


text:
Q: How to write Mq command to display curdepth is greater than 80%of maxdepth? How to write runmqsc Mq command to display queues for curdepth is greater than 80% of maxdepth? I have tried but no luck.

A: It is not possible to do this with native MQSC commands alone.
It is possible to do this if you use MQSCX from MQGem Software and the =WHERE clause (an enhancement over the IBM MQ WHERE clause). Then you can use the following command:-
DISPLAY QLOCAL(*) =WHERE(CURDEPTH GT MAXDEPTH * 0.8)

A: As Morag said, runmqsc does not support what you want.  I posted a Java/MQ program that basically does what you want.  You can find the code here: How to display local queues where curdepth reached its maxdepth in ibm mq

redpajama_set_name: RedPajamaStackExchange


text:
Q: If $\mathbf{A} \succeq 0 \in M_n (\mathbb{C})$, why $a_{ii} a_{jj} \geq |a_{ij}|^2$? If $\mathbf{A} = [a_{ij}] \succeq 0 \in M_n (\mathbb{C})$ is positive semi-definite, why $a_{ii} a_{jj} \geq  |a_{ij}|^2$ $ \forall i,j \in \left\{ 1,\cdots,n\right\}$?
Thank you in advance

A: I'll assume it's actually $M_n(\mathbb{R})$ so I don't have to check about sesquilinearity conventions. The argument is the same, I just always forget which argument is linear and which one is conjugate linear in the complex case.
Notice that $a_{ij}=e_i^T A e_j$, where $e_i$ are the columns of the identity matrix. Then the statement is essentially a case of Cauchy-Schwarz for the "inner product" $\langle x,y \rangle = x^T A y$. I say "essentially" because this is not really an inner product because it is only positive semidefinite instead of positive definite. Nevertheless the proof of (the nonstrict form of) Cauchy-Schwarz goes through the same with this weaker assumption.

A: This is Cauchy - Schwartz inequality for the inner product $(x,y) \to \langle Ax,y \rangle$ If you denote $\langle Ax,y \rangle$ by $\langle x,y \rangle '$ then the inequality simply states that  $\langle e_i,e_j \rangle ' \leq \langle e_i,e_i \rangle '\langle e_j,e_j \rangle '$.


text:
Q: Android soap codes dont working However there are no wrongs I'm new android. I tried to use ksoap. I added these libs by a jar. I think everything is oke but my code does not work. If i comment ksoap codes everything workes. I don't understand what is the problem is? Please help me.
The codes are below:
package com.hndnn;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TermometreActivity extends Activity {
final static String NAMESPACE = "http://tempuri.org/";

    final static String METHOD_NAME = "CelsiusToFahrenheit";

    final static String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";

    final static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
    TextView txt;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txt=(TextView) findViewById(R.id.textView1);
       SoapObject Request=new SoapObject(NAMESPACE, METHOD_NAME);
        Request.addProperty("Celsius", "20");
        SoapSerializationEnvelope sse=new SoapSerializationEnvelope(SoapEnvelope.VER11);
       sse.dotNet=true;
       sse.setOutputSoapObject(Request);
       AndroidHttpTransport aht=new AndroidHttpTransport(URL);
        try {
            aht.call(SOAP_ACTION, sse);
            SoapPrimitive sonuc= (SoapPrimitive) sse.getResponse();
            txt.setText("Derece:"+sonuc);
            //txt.setText("try içinde");``

        } catch (Exception e) {
          e.printStackTrace();
          txt.setText("handan");
        }


text:
Q: Stacked pie chart - how to set inner piechart labels dependent on outer piechart I have a stacked pie chart with labels in percentage. The outer pie chart has labels as I want them to be; however, the labels for the inner chart should be based on where it falls under the outer pie chart. For example, in the image below, the percentage labels of the inner pie chart should sum up to 100% for each color of the outer pie chart. Currently, for the red outer pie chart, the inner pie chart has 11.0%, 12.0%, 7.0% which is the percentage of itself that is not taking the outer chart into account. I'd want them to display something like 35%, 38%, 27% and same for green and yellow colors of the outer pie chart where the inner chart labels are dependent upon the outer pie chart color.

Here's a reproducible example
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt

options = ['RED','YELLOW','GREEN']
color_list1 = []
color_list2 = []

for i in np.arange(100):
    color1 = random.choice(options)
    color2 = random.choice(options)
    color_list1.append(color1)
    color_list2.append(color2)

test_df = pd.DataFrame(list(zip(color_list1, color_list2)), columns =['Outer_Color', 'Inner_Color'])

outer = pd.DataFrame(test_df.groupby('Outer_Color').size())
inner = pd.DataFrame(test_df.groupby(['Outer_Color', 'Inner_Color']).size())
inner_labels = inner.index.get_level_values(1)

my_pal = {"RED": "r", "YELLOW": "yellow", "GREEN":"g"}

fig, ax = plt.subplots(figsize=(14,7))
size = 0.3

ax.pie(outer.values.flatten(), radius=1,
#        labels=outer.index,
       autopct='%1.1f%%', pctdistance=0.85, # labeldistance=0.2,
       wedgeprops=dict(width=size, edgecolor='w'),
       colors=[my_pal[key] for key in outer.index])

ax.pie(inner.values.flatten(), radius=1-size,
#        labels = inner_labels,
       autopct='%1.1f%%', pctdistance=0.7, # labeldistance=1.2,
       wedgeprops=dict(width=size, edgecolor='w'),
       colors=[my_pal[key] for key in inner_labels])

plt.show()

A: An approach you can take is to calculate the percentage of the inner wedge relative to the outer wedge and make new labels to then pass when you do ax.pie. For example:
# Construct inner labels
    inner_str_label = []  # new labels storage
    n_inside = 3  # number of inner wedges per outer wedge
    for idx, outer_value in enumerate(outer.values.flatten()):
        # Get inner values for each outer wedge
        for inner_value in inner.values.flatten()[idx*n_inside:idx*n_inside+n_inside]:
            # format for only 1 decimal place
            new_label = f"{'{0:.1f}'.format(inner_value/outer_value*100)}%"
            inner_str_label.append(new_label)

Now we can pass the new labels in ax.pie using labels:
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt

if __name__ == '__main__':

    options = ['RED', 'YELLOW', 'GREEN']
    color_list1 = []
    color_list2 = []

    for i in np.arange(100):
        color1 = random.choice(options)
        color2 = random.choice(options)
        color_list1.append(color1)
        color_list2.append(color2)

    test_df = pd.DataFrame(list(zip(color_list1, color_list2)), columns =['Outer_Color', 'Inner_Color'])

    outer = pd.DataFrame(test_df.groupby('Outer_Color').size())
    inner = pd.DataFrame(test_df.groupby(['Outer_Color', 'Inner_Color']).size())

    my_pal = {"RED": "r", "YELLOW": "yellow", "GREEN": "g"}

    fig, ax = plt.subplots(figsize=(14, 7))
    size = 0.3

    ax.pie(outer.values.flatten(), radius=1,
           #        labels=outer.index,
           autopct='%1.1f%%', pctdistance=0.85,  # labeldistance=0.2,
           wedgeprops=dict(width=size, edgecolor='w'),
           colors=[my_pal[key] for key in outer.index])

    # Construct inner labels
    inner_str_label = []  # new labels storage
    n_inside = 3  # number of inner wedges per outer wedge
    for idx, outer_value in enumerate(outer.values.flatten()):
        # Get inner values for each outer wedge
        for inner_value in inner.values.flatten()[idx*n_inside:idx*n_inside+n_inside]:
            # format for only 1 decimal place
            new_label = f"{'{0:.1f}'.format(inner_value/outer_value*100)}%"
            inner_str_label.append(new_label)

    wedges, labels = ax.pie(inner.values.flatten(), radius=1-size, labels=inner_str_label, labeldistance=0.8,
                            wedgeprops=dict(width=size, edgecolor='w'),
                            colors=[my_pal[key] for key in inner.index.get_level_values(1)])

    # Fix inner label position
    for string_label in labels:
        string_label.update({"rotation": 0, "horizontalalignment": "center", "verticalalignment": "center"})

    plt.show()

Note that this is assuming each outer wedge has the same amount of inner wedges. If the number of inner wedges was irregular, the approach would be similar but you set the number of inner wedges per outer wedges in a list:
    # Construct inner labels
    inner_str_label = []  # new labels storage
    n_inside_list = [2, 3, 2]  # number of inner wedges per outer wedge
    for idx, outer_value in enumerate(outer.values.flatten()):
        # Get inner values for each outer wedge
        n_inside = n_inside_list[idx]
        for inner_value in inner.values.flatten()[idx*n_inside:idx*n_inside+n_inside]:
            # format for only 1 decimal place
            new_label = f"{'{0:.1f}'.format(inner_value/outer_value*100)}%"
            inner_str_label.append(new_label)

Hope this helps - cheers!


text:
Q: Change surface color in Matplotlib based on a variable I have plotted a simple function as a 3D-plot using Matplotlib. Now, I want to create a colormap to color it depending on the speed as derived in the u and v functions. For that purpose, I want to use the function seen in c. How should I go about doing this? Thank you in advance.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

x = np.linspace(-2, 2, 20)
y = np.linspace(-2, 2, 20)
X, Y = np.meshgrid(x, y)
h = np.exp(-X**2 - Y**2)            # plotted function
u = -2*X*np.exp(-X**2 - Y**2)       # speed in x-direction
v = -2*Y*np.exp(-X**2 - Y**2)       # speed in y-direction
c = np.sqrt(u**2 + v**2)            # colormap derives from this

fig = plt.figure(figsize = (8, 7), facecolor='white')
ax = fig.add_subplot(projection='3d')
ax.plot_surface(X, Y, h)

plt.show()

A: Try this
from matplotlib import cm

fig = plt.figure(figsize = (8, 7), facecolor='white')
ax = fig.add_subplot(projection='3d')
surf = ax.plot_surface(X, Y, h, rstride=1, cstride=1, facecolors = cm.jet(c/np.amax(c)),
                       linewidth=0, antialiased=False)

plt.show()


text:
Q: Количество строк В текстовом файле посчитать количество строк, которые начинаются и кончаются одной и той же согласной буквой. Прошу помочь с этой программой.
A: Delphi:
var i,n:integer;s:string;
begin
n:=0;
Memo1.lines.LoadFromFile('1.txt');
for i:=0 to Memo1.Lines.Count-1 do
   begin
   s:=Memo1.Lines[i];
   if (s[1]='Согласная') and (s[Length(s)]='Согласная') then
     inc(n);
   end;
end;

A: Алгоритм простой тут:

*

*Читаете очередную строку;

*Переводите её в один регистр - например, в верхний;

*Смотрите первую букву - если она не согласная (для этого должен быть список согласных букв, с коими и сравнивать надо поочерёдно), то идём на начало, в пункт 1;

*Ищется последняя буква и сравнивается с первой. Если совпадает - прибавляем к счётчику один.


text:
Q: Using parent to call a method from the components Blazor I have this method in my components called ClearFiles(string PathName) which I currently call by clicking one of the buttons on the component, but now I'm trying to call of them at once but I cannot figure out how to do this. Calling a single ClearFiles method from the component works perfectly, but I'm not quite sure how to call all these methods at once using the parent class. I have made a button in the parent class with the name of ForceClean which I'm hoping can be pressed to call all of the components clear files function.
I create the components in the parent class using a for loop in my PageFileCleaner.razor file like this:
@foreach (var d in filters)
{
     <CompFileFilter FileFilter="d" OnDelete="Delete" ></CompFileFilter>
}

Where filters is a List of type FileFilter which is in the namespace Common.DB. This is how it is declared in the parent class:
private List<FileFilter> filters { get; set; }

And is populated with data from my database using:
        using var context = _db.CreateDbContext();
        filters = await context.FileFilters.AsNoTracking().ToListAsync();
        foreach( var filter in filters)
        {
            FileFilter f = new FileFilter();
        }

And this Parameter (in the child class) is what i use to get the values from that row in the database using FileFilter.Pathname or FileFilter.ID for example:
    [Parameter]
    public FileFilter FileFilter { get; set; }

Database / FileFilter object class:
namespace Common.DB
{
    public class FileFilter
    {
        [Key]
        public int ID { get; set; }
        public string TimerChoice { get; set; }
        public bool IsLoading;
        public string PathName { get; set; } = "";
        public string Extension { get; set; }
        //public string[] extensionList { get; set; }
       ...
    }
}

The clear files function is in my component/child CompFileFilter.razor file (took the code out for this example because its over a hundred lines of code). I'm creating the components in the parent class and each one will have this ClearFiles() method.
public async Task ClearFiles(string PathName)
{
     filtering code...
}

How can I loop through my components from the parent class and call all of there ClearFiles() method?

A: You can use a dictionary and store the reference of each CompFileFilter component. Then use the references to call the ClearFiles method. You can use the ID property of FileFilter for the dictionary keys.
PageFileCleaner.razor
@foreach (var d in filters)
{
    <CompFileFilter @key="d.ID" @ref="_fileFilterRefs[d.ID]" FileFilter="d" OnDelete="Delete"></CompFileFilter>
}

@code {
    private Dictionary<int, CompFileFilter> _fileFilterRefs = new Dictionary<int, CompFileFilter>();

    private async Task ForceClean()
    {
        // Execute ClearFiles one at a time.
        foreach (var item in _fileFilterRefs)
        {
            await item.Value.ClearFiles();
        }

        // Or execute them in parallel.
        //var tasks = _fileFilterRefs.Select(item => Task.Run(item.Value.ClearFiles));
        //await Task.WhenAll(tasks);
    }
}

ClearFiles method doesn't need PathName parameter. You can get the PathName from the FileFilter parameter.
CompFileFilter.razor
@code {
    [Parameter]
    public FileFilter FileFilter { get; set; }

    public async Task ClearFiles()
    {
        var pathName = FileFilter.PathName;
        // filtering code...
    }
}

Edit:
You should manually update the _fileFilterRefs dictionary whenever you remove an item from filters list to keep them synchronized. E.g.
private void Delete(FileFilter fileFilter)
{
    _filters.Remove(fileFilter);

    _fileFilterRefs.Remove(fileFilter.ID);
}

You should clear the _fileFilterRefs dictionary whenever you set the filters list to a new list. E.g.
private async Task RefreshFilters()
{
    _fileFilterRefs.Clear();

    _filters = await filterService.GetFileFilters();
}

But you don't have to do the same thing when you add a new item to the filters list (_filters.Add(...)). In that case it's handled automatically.
In summary:

*

*filters.Add(new FileFilter()) -> do nothing.

*filters.Remove(fileFilter) -> remove fileFilter.ID key from
_fileFilterRefs

*filters = new List() -> clear _fileFilterRefs before setting the list

https://github.com/dotnet/aspnetcore/issues/17361#issuecomment-558138782


text:
Q: What is variable stand-alone $this means in a method in CodeIgniter I am confused about what does the stand-alone variable $this actually means in some CodeIgniter functions. I understand $this with the arrow, but I don't know how to use $this in a function. For example,
function update_entry()
{
    $this->title   = $_POST['title'];
    $this->content = $_POST['content'];
    $this->date    = time();

    $this->db->update('entries', $this, array('id' => $_POST['id']));
}

A: Literally, you can't use $this inside a function.
$this is a pseudo variable that refer to this object, or rather to a class instance.
You can use it inside a method, not inside a function.
Your misunderstanding, however, is totally legitimate, because in php methods are declared through... function keyword! The only syntax difference is that a "function" inside a class is a method, whereas a function outside a class is... a function.
Example:
<?php
    class MyClass
    {
        public $var = 'Hello';

        /* echo() is a MyClass method */
        function echo()
        {
            echo $this->var;                     // <-- $this inside class: valid
        }
    }

    echo $this;                                  // <-- $this outside class: NOT valid

    /* test() is a function */
    function test()
    {
        echo $this;                              // <-- $this inside function: NOT valid
    }
?>

$this refer to an instance of the class, so, in this example:
$obj = new MyClass();
$obj->test();                                    // <-- Output: "Hello"
$obj->var = "Hello World";
$obj->test();                                    // <-- Output: "Hello World"

$obj2 = new MyClass();
$obj2->test();                                   // <-- Output: "Hello"
$obj2->var = "Hello Baby";
$obj2->test();                                   // <-- Output: "Hello Baby"

$this is a reference to object $obj or $obj2, not to the generic declared class: to refer to the current class instead of object you have to use self instead of $this.
In other words, you have to use $this for non-static members and self for static members.

*

*See more about Basic class syntax

Edit:
You remain confused when "$this" stand alone in a method.
See this example:
class Called
{
    public $var = 'Hello Baltimora';

    function echo( $obj )
    {
        echo $obj->var;
    }
}

class Caller
{
    public $var = 'Hello San Francisco';

    function echo( $obj )
    {
        $obj->echo( $this );
    }
}

$called = new Called();
$caller = new Caller();

$caller->echo( $called );

In the class Caller, method echo pass $this (reference to own instance) to a different class method ( Called->echo, instantiated as $called ): inside called method, the Caller instance ($caller) is assigned to $obj variable and use to retrieve his $var variable.
So, $caller->echo( $called ) will output "Hello San Francisco".


text:
Q: Installing CLD libary on windows and bind to Python I have a need to make use of Chromium's Compact Language Detector library within a Python script.
AFAIK, there are two projects that leverage this library, but I have been having troubles with getting either of them set up on a Windows 7 machine.
I had some similar problems with Mike McCandless Original Project (GoogleCode), but I then spotted Matt Sanford fork on the same Project (github).  For the purpose of this question, I will focus on Matts project, as it seems to have been updated more often (but happy to get an answer that works for either project).

*

*Downloaded the project as a zip, and extracted to my local drive.

*Ran vcvarsall.bat from CMD

*Then ran the build.win.cmd batch file.  This ran ok.

*Copied the resulting libcld.lib to ports/python/cld.lib

*Tried running the setup.py but it returns with the following against line 12.
exceptions.TypeError: init() keywords must be strings
++EDIT++
Found this issue:

setup.py fails on Windows. The hackish solution to fix this is to make
  pkgconfig return the dict {'define_macros': [('WIN32',None)],
  'libraries': packages}

Im a bit of a rookie, but not entirely sure on the steps to implement this hack.  Can anyone give me some slightly more verbose steps?

A: Try this patch (works for me):
diff --git a/ports/python/setup.py b/ports/python/setup.py
index e1950c3..889f21a 100644
--- a/ports/python/setup.py
+++ b/ports/python/setup.py
@@ -9,7 +9,10 @@ def pkgconfig(*packages, **kw):

 module = Extension('cld',
                    ['pycldmodule.cc'],
-                   **pkgconfig('cld'))
+                   define_macros=[('WIN32', None)],
+                   libraries=['libcld'],
+                   include_dirs=['..\\..\\'],
+                   library_dirs=['..\\..\\'])

 setup(name='cld',
       version='0.031415',


text:
Q: Bridge 5Ghz to 2.4ghz in WiFi router Bridge 5Ghz to 2.4Ghz... Our office building updated their network with APs but they removed 2.4Ghz in the process and some of our devices only have 2.4Ghz.
If I receive the 5Ghz into our WiFi router, can I bridge that to 2.4Ghz? Or would it be received to WiFi router via 5Ghz, out to Switch/Router via Ethernet, into a different WiFi Router to Bridge Ethernet to 2.4Ghz?
I don't want to bother the landlord to get the third party company to "turn on" the 2.4Ghz, as we are positive they would charge for such a hard thing. (Sarcasm).

A: You cannot bridge an access point (AP) on 2.4 GHz to a station (STA) on 5 GHz, because by default your WLAN uses 3-address mode. so your building AP on 5 GHz doesn't work with MACs "behind" your STA MAC.
You can bridge LAN to an AP on 2.4 GHz, assuming you can connect your WiFi router somehow with a LAN to the building router (no WLAN in between allowed, it must be a LAN port on the building router/switch).
If bridging doesn't work, you can still route and NAT from the 5 GHz WLAN BSS: Your 2.4 GHz "private" WLAN BSS will have a different subnet, and will look like a single IP address to the building router. Which means you can establish connections from your WLAN BSS to the rest of the building, but the rest of the building won't be able establish connections to anything in your WLAN BSS.
It depends on the firmware of your router if you can actually configure it for any of the above scenarios. If you can install an alternative firmware on it, like OpenWRT, you'll definitely will be able to.

A: There are three more options:

*

*use a WiFi Extender that can send out a 2.4 GHz signal as well (not sure if they are still available)

*bridge the 5GHz to LAN and attach a a 2.4GHz AP to the LAN (e.g. via an WiFi extender that has an Ethernet port or simple Windows machine that brides the the WLAN and Ethernet network card).

*if you have access to a Ethernet port or the Ethernet switch itself just connect a regular 2.4GHz AP.
You don't need a router as a separate device unless you want to create a new subnet, use NAT etc.


text:
Q: PyQt - How to set QComboBox in a table view using QItemDelegate I am trying to display a combo box in my table, so that I can set the selected index from the table model, as with the other cells in the table. I have pieced this together from other examples but still cannot understand how the interaction works to set the selected index of the QComboBox.
This is the simplest example I can come up with to demonstrate the problem. If anyone can demonstrate how to set the index automatically from model data? Also how to use the 'currentIndexChanged' signal, as this seems to fire almost continuously whenever it is repainted? Thanks.
# The following tells SIP (the system that binds Qt's C++ to Python)
# to return Python native types rather than QString and QVariant
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtCore, QtGui

class TableModel(QtCore.QAbstractTableModel):
    """
    A simple 5x4 table model to demonstrate the delegates
    """
    def rowCount(self, parent=QtCore.QModelIndex()): return 5
    def columnCount(self, parent=QtCore.QModelIndex()): return 4

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if not index.isValid(): return None
        if not role==QtCore.Qt.DisplayRole: return None
        return "{0:02d}".format(index.row())

class ComboDelegate(QtGui.QItemDelegate):
    """
    A delegate that places a fully functioning QComboBox in every
    cell of the column to which it's applied
    """
    def __init__(self, parent):

        QtGui.QItemDelegate.__init__(self, parent)

    def paint(self, painter, option, index):

        self.combo = QtGui.QComboBox(self.parent())
        self.connect(self.combo, QtCore.SIGNAL("currentIndexChanged(int)"), self.parent().currentIndexChanged)

        li = []
        li.append("Zero")
        li.append("One")
        li.append("Two")
        li.append("Three")
        li.append("Four")
        li.append("Five")

        self.combo.addItems(li)

        if not self.parent().indexWidget(index):
            self.parent().setIndexWidget(
                index,
                self.combo
            )

class TableView(QtGui.QTableView):
    """
    A simple table to demonstrate the QComboBox delegate.
    """
    def __init__(self, *args, **kwargs):
        QtGui.QTableView.__init__(self, *args, **kwargs)

        # Set the delegate for column 0 of our table
        # self.setItemDelegateForColumn(0, ButtonDelegate(self))
        self.setItemDelegateForColumn(0, ComboDelegate(self))

    @QtCore.pyqtSlot()
    def currentIndexChanged(self, ind):
        print "Combo Index changed {0} {1} : {2}".format(ind, self.sender().currentIndex(), self.sender().currentText())

if __name__=="__main__":
    from sys import argv, exit

    class Widget(QtGui.QWidget):
        """
        A simple test widget to contain and own the model and table.
        """
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)

            l=QtGui.QVBoxLayout(self)
            self._tm=TableModel(self)
            self._tv=TableView(self)
            self._tv.setModel(self._tm)
            l.addWidget(self._tv)

    a=QtGui.QApplication(argv)
    w=Widget()
    w.show()
    w.raise_()
    exit(a.exec_())

A: You're using paint method incorrectly. It should be used when you want to change displaying behavior of the view. Also creating new widget each time you want to paint it is very expensive. But you want to change editing behavior so you need to change entire logic of your program.
See the fixed code. Below I'll expain the changes.
1. First of all, we need to make the first column editable. You can do it by reimplementing QAbstractItemModel::flags:
def flags(self, index):
    if (index.column() == 0):
        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled
    else:
        return QtCore.Qt.ItemIsEnabled

2. By default the item editor is created when user performs a double click on item. If you want to show all comboboxes by default, you can use openPersistentEditor:
for row in range(0, self._tm.rowCount()):
    self._tv.openPersistentEditor(self._tm.index(row, 0))

Note that you should also open editors for newly created cells (if any).
3. Now back to our delegate. We need to implement createEditor method that will be automatically called by the view when an editor is requested for a cell:
def createEditor(self, parent, option, index):
    combo = QtGui.QComboBox(parent)
    li = []
    li.append("Zero")
    li.append("One")
    li.append("Two")
    li.append("Three")
    li.append("Four")
    li.append("Five")
    combo.addItems(li)
    self.connect(combo, QtCore.SIGNAL("currentIndexChanged(int)"),
                 self, QtCore.SLOT("currentIndexChanged()"))
    return combo

Note that connect is below appends because we need to avoid currentIndexChanged signals on initialization.
4. Implement setEditorData method that will be called by the view when model data has been changed. Also it will be called once when an editor is initialized.
def setEditorData(self, editor, index):
    editor.blockSignals(True)
    editor.setCurrentIndex(int(index.model().data(index)))
    editor.blockSignals(False)

Again, we want to avoid signals that are not caused by the user, so we use blockSignals.
5. In the slot we simply emit commitData signal that will cause the view to call the setModelData of our delegate:
@QtCore.pyqtSlot()
def currentIndexChanged(self):
    self.commitData.emit(self.sender())

6. Implement setModelData method:
def setModelData(self, editor, model, index):
    model.setData(index, editor.currentIndex())

7. Your model needs to support data changing. So we should implement setData method of the model:
def setData(self, index, value, role=QtCore.Qt.DisplayRole):
    print "setData", index.row(), index.column(), value
    # todo: remember the data


text:
Q: Constant value calculation I have an hpp file with following code:
const float PixelsPerMeter = ConfigManager->Get<float>("koef", 100.0f);

inline const float Meters2Pixels(float meters) { return meters * PixelsPerMeter; }
inline const float Pixels2Meters(float pixels) { return pixels / PixelsPerMeter; }

const float ScreenArea = Pixels2Meters(ScreenSizeX) * Pixels2Meters(ScreenSizeY);

It worked before, but now ScreenArea = inf somehow. I use it from static function. I put a breakpoint in that function and print out the value of PixelsPerMeter(100.0), ScreenSizeX and ScreenSizeY. Everything is okay, but ScreenArea is calculated wrong.
When I write directly Pixels2Meters(ScreenSizeX) * Pixels2Meters(ScreenSizeY) instead of using ScreenArea constant everything works.
How it could be?

A: I think, the problem is with your global variable, to be precise with its initialization.
If by the  time the  variable has not been dynamically initialized when you call Pixels2Meters(), the variable PixelsPerMeter is statically initialized to zero, so the function Pixels2Meters() returns inf which very much implies PixelsPerMeter is zero.
But you put break points, the story could be slightly different; it is analogous to Heisenberg uncertainty principle, in the sense that when you want to see the value of PixelsPerMeter by putting breakpoints, it shows you different value than the value when there is no breakpoints.
Also note that since the variable is declared const, without extern keyword, the variable has internal linkage, which means you will have different copy of this variable in each translation unit, in case if it declared in a header file which you include in several source files. The variable's behavior is as if it is declared static.
Another important point to be noted is that this variable is initialized twice: the first initialization is called static initialization which happens at compile-time, and second initialization is called dynamic initialization which happens at runtime. In case of static initialization, the variable is initialized to zero, and that is the value which is being used which is causing the problem. To know more about it, read this:

*

*What is dynamic initialization of object in c++?
You should also read about this:

*

*static initialization order fiasco

A: When the static function is initialised is a bit complicated and may depend on system/compiler.
You probably have an issue that the  ConfigManager() isn't initialised before the static function you are using it in.


text:
Q: Cannot set reactive property on undefined, null, or primitive value bootstrap Vue modal please I need help with this error, app.js:108639 [Vue warn]: Cannot set reactive property on undefined, null, or primitive value: .
I'm working with bootstsrap vue modal and having this error. Here is my code snippet below
Firstly here is my template snippet

    Add Staff

    <form ref="form" @submit.stop.prevent="handleSubmit">

    </form>

Now here is my script
import { BButton, BModal, VBModal } from "bootstrap-vue";

export default {

    components: {
        BButton,
        BModal
    },

    directives: {
        'b-modal': VBModal
    },

    data() {
        return {
            staffs: {},
            nameState: null,
            emailState: null,
            phoneState: null,
            job_titleState: null,

            info: {
                name: '',
                email: '',
                phone: '',
                job_title: ''
            },

            showModal: false
        }
    },

    methods: {
        getStaffs() {
            axios.get("api/user").then(({data }) => (this.staffs = data));
        },
        // createStaff () {
        // this.form.post('api/user')
        //     .then(({ data }) => { console.log(data) })
        // },
        checkFormValidity() {
            const valid = this.$refs.form.checkValidity()
            this.nameState = valid
            return valid
        },
        resetModal() {
            this.info = ''
        },
        handleOk(bvModalEvt) {
            // Prevent modal from closing
            bvModalEvt.preventDefault()
            // Trigger submit handler
            this.handleSubmit()
        },
        handleSubmit() {
            // Exit when the form isn't valid
            if (!this.checkFormValidity()) {
                // return
                console.log(this.info)
            }
            // Hide the modal manually
            this.$nextTick(() => {
              this.$bvModal.hide('modal-prevent-closing')
            })
        }
    },

    created() {
        this.getStaffs();
    },

    mounted() {
        console.log('Component mounted.')
    }

};

I just wanted to be sure my code is correct before doing the validation.
Thanks in advance

A: I tried to implement your code into a snippet, and there is one thing with your code that causes an error. It's because you are setting this.info to an empty string, not the object that already is in the data property.
Also, check your b-vue version, which you are using. It may cause warning issues.
I tried not to change your code and simulate your issue as I could understand. Please let me know If I wrote the code with the wrong purpos

new Vue({
  el: "#app",
  data: function() {
    return {
      staffs: {},
      nameState: null,
      emailState: null,
      phoneState: null,
      job_titleState: null,

      info: {
        name: '',
        email: '',
        phone: '',
        job_title: ''

      },

      showModal: false
    }
  },
  methods: {
    getStaffs() {
      this.staffs = {}
    },
    checkFormValidity() {
      const valid = this.$refs.form.checkValidity()
      this.nameState = valid
      return valid
    },
    resetModal() {
      this.info = {
        name: '',
        email: '',
        phone: '',
        job_title: ''

      }
    },
    handleOk(bvModalEvt) {
      // Prevent modal from closing
      bvModalEvt.preventDefault()
      // Trigger submit handler
      this.handleSubmit()
    },
    handleSubmit() {
      // Exit when the form isn't valid
      if (!this.checkFormValidity()) {
        // return
        console.log(this.info)
      }
      // Hide the modal manually
      this.$nextTick(() => {
        this.$bvModal.hide('modal-prevent-closing')
      })
    }
  },
  created() {
    this.getStaffs();
  },
  mounted() {
    console.log('Component mounted.')
  }
});
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" />

    Add Staff

      <form ref="form" @submit.stop.prevent="handleSubmit">

      </form>


text:
Q: return ajax result from callback function I have two callbacks one of them should return boolean value and other do an ajax call. but can't get result from the second one.
I've read some explanation of how to return the response from an asynchronous call but can't get any result.
there is my code :
    if( $.fn.wizard ) {
        $('#wzd-enrollment').wizard({
            //some code

            onStepLeave: function (wizard, step){
                //in this function i have always to return a boolean value to move to the next step or not
                var result;
                result = doAjax(wizard, step);
                console.log(result); //always log undefined
                return result;
            }
        });

        function doAjax(wizard, step){
            if(step.id == 'step-1' ){
                //some code
                $.ajax({
                    type: "GET",
                    dataType: 'json',
                    url: s_url,
                }).done(function( data ) {
                    //some code
                    return true;

                }).fail(function(jqXHR, textStatus, errorThrown){
                    //some code
                    return false;
                });
            }else{
                return true;
            }
        }
    }

A: You should do the doAjax function on document.ready.
There is no need to do this on step leave.
Check the code below
var s_url = ''; // fill out your url here
// save the result in a var
var resultStep1 = true;

if( $.fn.wizard ) {
    $('#wzd-enrollment').wizard({
        //some code

        onStepLeave: function (wizard, step){
            var result2 = false;
            return checkResult(step);
        }
    });
}

function doAjax(){
    //some code
    $.ajax({
        type: "GET",
        dataType: 'json',
        url: s_url,
    }).done(function( data ) {
        //some code
        resultStep1 = true;

    }).fail(function(jqXHR, textStatus, errorThrown){
        //some code
        resultStep1 = false;
    });
}

function checkResult(step) {
    if(step.id == 'step-1' ){
        return resultStep1;
    }
    else {
        return true;
    }
}

// get the result on page load
$(document).ready(function() {
    doAjax();
});

A: This is the code that fits my last answer:
<input type="button" value="Next" id="wizard_next_button" style="display: none" />
<input type="button" value="Next" id="your_next_button" style="display: block" />
<script>
var s_url = ''; // fill out your url here
// save the result in a var
var result = true;

if( $.fn.wizard ) {
    $('#wzd-enrollment').wizard({
        //some code

        onStepLeave: function (wizard, step){
            return result;
        }
    });
}

function doAjax(callback){
    if($("#wizard").steps("getCurrentIndex") == 'step-1' ){
        //some code
        $.ajax({
            type: "GET",
            dataType: 'json',
            url: s_url,
        }).done(function( data ) {
            //some code
            if ( typeof(callback) == 'function' ) {
                callback(true);
            }

        }).fail(function(jqXHR, textStatus, errorThrown){
            //some code
            if ( typeof(callback) == 'function' ) {
                callback(false);
            }
        });
    } else {
        if ( typeof(callback) == 'function' ) {
            callback(true);
        }
    }
}

// get the result on page load
$("#your_next_button").click(function() {
    doAjax(function(retval) {
        result = retval;
        $("#wizard_next_button").trigger('click');
    });
});
</script>


text:
Q: $_POST inside query PHP I have a $_post with a value that I need to put inside a PHP query. have tried alot of different ways, but cant get it to work.
Ideas ?
$result = $xpath->query('/stickers/sticker[id=2]/text');

I need to change [id=2] to this $_POST['textBoxID']

A: You need to use double quotes or concatenation. Single quotes cause your variables to be taken as literals. Double quotes will allow them to be interpolated.
$result = $xpath->query("/stickers/sticker[$_POST[textBoxID]]/text");

or
$result = $xpath->query("/stickers/sticker[{$_POST['textBoxID']}]/text");

or
$result = $xpath->query('/stickers/sticker['.$_POST['textBoxID'].']/text');

A: Will $_POST['textBoxID'] just be the numerical value? if so you can do this:
$result = $xpath->query('/stickers/sticker[id='.$_POST['textBoxID'].']/text');

Or if $_POST['textBoxID'] will be the whole id=x do this:
$result = $xpath->query('/stickers/sticker['.$_POST['textBoxID'].']/text');

Read more here: http://php.net/operators.string

A:
You want either a
$thePost = $_POST['textBoxID'];
$result = $xpath->query('/stickers/sticker'.$thePost.'/text');

or
$thePost = $_POST['textBoxID'];
$result = $xpath->query('/stickers/sticker[id='.$thePost.']/text');


text:
Q: How to add new node in specific node on xml by php dom I want to insert new node to specific node but I have no idea how to do it
number.xml
<numbers>
   <number>1</number>
   <number>2</number>
   <number>3</number>
   <number>4</number>
   <number>5</number>
</numbers>

number.php
<?php
$xml = new DOMDocument();
$xml->formatOutput=true;
$xml -> load('number.xml');
$xml_subnumber = $xml->createElement("subNumber");
$xml_subnumber_text = $xml->createTextNode("3.3");
$xml_subnumber->appendChild($xml_subnumber_text);
//something here (I have no idea.)
$xml->save("number.xml") or die("Error");
?>

and I want the xml file seem like this...
<numbers>
   <number>1</number>
   <number>2</number>
   <number>3
     <subNumber>3.3</subNumber>
   </number>
   <number>4</number>
   <number>5</number>
</numbers>

A: You need to find the number element node and append the new node to it. Here is XPath for that.
/numbers/number[3] will return the third number element node. It will return it in a list, because expressions could return several nodes or no nodes. This way the result type always stays the same.
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;

$xml->loadXml(
  '<numbers>
   <number>1</number>
   <number>2</number>
   <number>3</number>
   <number>4</number>
   <number>5</number>
  </numbers>'
);
$xpath = new DOMXpath($xml);

foreach ($xpath->evaluate('/numbers/number[3]') as $thirdNumber) {
  $subNumber = $thirdNumber->appendChild(
     $xml->createElement("subNumber")
  );
  $subNumber->appendChild($xml->createTextNode("3.3"));
}

echo $xml->saveXml();

Output:
<?xml version="1.0"?>
<numbers>
   <number>1</number>
   <number>2</number>
   <number>3<subNumber>3.3</subNumber></number>
   <number>4</number>
   <number>5</number>
</numbers>


text:
Q: UITableView Layout issue, (Content Inset) UINavigationController -> UITabBarController -> UIViewController -> UITableView
I have an UINavigationController with an UITabBarController as its rootViewController, Then put an UITableView in one of the tab(UIViewController)
When i switch to one of the tabController which contains an UITableView, The first cell of the tableView under navigation bar. If i push another view controller, then pop back, the tableview relayout right. How to make it layout right on start.

A: do your layout in viewWillAppear can solve the problem

A: I solved it. This is the issue of topLayoutGuide, Fix it (Swift) by override the topLayoutGuide property
override var topLayoutGuide:UILayoutSupport {
    get { return (self.parentViewController?.topLayoutGuide)! }
}

override var bottomLayoutGuide:UILayoutSupport {
    get { return (self.parentViewController?.bottomLayoutGuide)! }
}

(Objective C)
(id<UILayoutSupport>) topLayoutGuide {
return self.parentViewController.topLayoutGuide;

}

*

*(id) bottomLayoutGuide {
return self.parentViewController.bottomLayoutGuide;
}

*(void) viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
//NSLog is required here, just invoke the getter, don't know why in Objective C getter is not invoked by default
NSLog(@"%@", self.topLayoutGuide);
}

*(void) viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
//NSLog is required here, just invoke the getter, don't know why in Objective C getter is not invoked by default
NSLog(@"%@", self.topLayoutGuide);
}


text:
Q: Adding Count Value to "qplot" histogram I am wondering how I can add the count value to the histogram graph which is plotted by qplot?
    qplot(cluster_name$km.out1.cluster, geom="histogram",binwidth = 0.5,
main = "Histogram for clusters Number", xlab = "cluster number", fill=I("blue")) +
  theme(plot.title = element_text(hjust = 0.5))

I tried to add
+ stat_bin(aes(y=..count..,label=..count..), geom="text", vjust=-.5, binwidth = 0.5)

however, this command will add a bunch of zeros on the x axis which is not what I want. I tried to remove label but got an error message. Please see picture of the result, below:

A: To prevent zero counts being labelled you can add an ifelse statement to stat_bin or geom_text which sets the label to an empty string for zero counts.
Using mtcars as example data try this:
library(ggplot2)

qplot(mtcars$mpg, geom="histogram",binwidth = 0.5,
      main = "Histogram for clusters Number", xlab = "cluster number", fill=I("blue")) +
  theme(plot.title = element_text(hjust = 0.5)) +
  stat_bin(aes(y=..count..,label = ifelse(..count.. > 0, ..count.., "")), geom="text", vjust=-.5, binwidth = 0.5)


text:
Q: Redirecting XMLHTTP request - Javascript I have a web page that has a too much content and javascript. When the page loads it makes multiple requests using Ajax and XMLHttp to load data. Is there a way to hook up all these requests and direct them to a different server.
For example the webpage fetches data from www.apple.com/data and www.mango.com/data after it is loaded. Is is possible to insert a script somewhere in the webpage which automatically changes any request made to www.orange.com/data.
Waiting for answer. Thanks

A: You can add a global handler to the ajaxSend event, the event will be triggered right before the ajax request being sent out. So you can check the request uri, apply some filtering logic, and then redirect the request by abort the original and resend it.
Below is an example
$(document).ajaxSend(function(e, xhr, opt) {
    if (opt.url.indexOf("www.apple.com") !== -1) {
        // abort the request
        xhr.abort();
        // change the uri to www.orange.com
        opt.url = opt.url.replace("www.apple.com", "www.orange.com");
        $.ajax(opt);
    }
});

A: Ok. So I followed Anthony C's answer and it did actually work. But the problem with his solution is that it only works with Ajax requests not XMLHttpRequests (I am not sure why, I am a beginner at this topic.) However digging on his idea of creating a hook I came across a similar post here How to get the URL of a xmlhttp request (AJAX). The code provided a way to fetch the requested URL for each request. So by a little tweak to the code I managed to come up with this:-
XMLHttpRequest.prototype.open = (function(open) {
  return function(method,url,async) {
      var uri=getLocation(url);// use get location function to convert requested url string into readable url
      if(uri.hostname!="orange.com"){
          url="https://orange.com" + url;
      }
      open.apply(this,arguments);
    };
})(XMLHttpRequest.prototype.open);

var getLocation = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};

This code at top of the page allows me to change the host name of all XMLHttpRequests that are not directed towards orange.com. Though I am sure there are better ways to write this code as well but since I am not an expert over javascript this will suffice my need for the time.


text:
Q: Subquery that accesses main table fields combined with LIMIT clause in Oracle SQL I got a table Users and a table Tasks. Tasks are ordered by importance and are assigned to a user's task list. Tasks have a status: ready or not ready. Now, I want to list all users with their most important task that is also ready.
The interesting requirement that the tasks for each user first need to be filtered and sorted, and then the most important one should be selected. This is what I came up with:
SELECT Users.name,
    (SELECT *
        FROM (SELECT Tasks.description
              FROM Tasks
              WHERE Tasks.taskListCode = Users.taskListCode AND Tasks.isReady
              ORDER BY Tasks.importance DESC)
        WHERE rownum = 1
    ) AS nextTask
    FROM Users

However, this results in the error
ORA-00904: "Users"."taskListCode": invalid identifier

I think the reason is that oracle does not support correlating subqueries with more than one level of depth. However, I need two levels so that I can do the WHERE rownum = 1.
I also tried it without a correlating subquery:
SELECT Users.name, Task.description
FROM Users
LEFT JOIN Tasks nextTask ON
    nextTask.taskListCode = Users.taskListCode AND
    nextTask.importance = MAX(
        SELECT tasks.importance
        FROM tasks
        WHERE tasks.isReady
        GROUP BY tasks.id
    )

This results in the error
ORA-00934: group function is not allowed here

How would I solve the problem?

A: One work-around for this uses keep:
SELECT u.name,
       (SELECT MAX(t.description) KEEP (DENSE_RANK FIRST ORDER BY T.importance DESC)
        FROM Tasks t
        WHERE t.taskListCode = u.taskListCode AND t.isReady
       ) as nextTask
FROM Users u;

A: Please try with analytic function:
with tp as (select t.*, row_number() over (partition by taskListCode order by importance desc) r
            from tasks t
            where isReady = 1 /*or 'Y' or what is positive value here*/)
select u.name, tp.description
  from users u left outer join tp on (u.taskListCode = tp.taskListCode)
  where tp.r = 1;

A: Here is a solution that uses aggregation rather than analytic functions. You may want to run this against the analytic functions solution to see which is faster; in many cases aggregate queries are (slightly) faster, but it depends on your data, on index usage, etc.
This solution is similar to what Gordon tried to do. I don't know why he wrote it using a correlated subquery instead of a straight join (and don't know if it will work - I've never seen the FIRST/LAST function used with correlated subqueries like that).
It may not work exactly right if there may be NULL in the importance column - then you will need to add nulls first after t.importance and before ). Note: the max(t.description) is needed, because there may be ties by "importance" (two tasks with the same, highest importance for a given user). In that case, one task must be chosen. If the ordering by importance is strict (no ties), then the MAX() does nothing as it selects the MAX over a set of exactly one value, but the compiler doesn't know that beforehand so it does need the MAX().
select u.name,
       max(t.description) keep (dense_rank last order by t.importance) as descr
from   users u left outer join tasks t on u.tasklistcode = t.tasklistcode
where  t.isready = 'Y'
group by u.name


text:
Q: RFC 4035 dnssec zone apex term im reading RFC 4035 which has to do with DNSSec, and there's a term which is causing me trouble to get, which is the following - Zone Apex -, perhaps i sound like a rookie, but every help on this is very welcome. Thanks!!

A: If you have a zone foo.bar.com, there are two places that have records for the exact name foo.bar.com: the zone's own name servers, and the parent zone's name servers. The first of those is in the zone itself, and referred to as the "zone apex". The other one is in the parent zone (sort of).
These two places with the same name have overlapping but not identical information in them. The parent zone has NS and DS records for foo.bar.com. The zone apex has NS, SOA, DNSKEY and RRSIG records for foo.bar.com. In the context of DNSSEC, the distinction between them is quite important, since it is between the parent zone's information and the zone apex that the cryptographic validation of the delegation happens.
If you want a much more long-winded attempt to explain this, you can have a look here.


text:
Q: Organizing retrieved JSON data from YQL Hello fellow developers,
I recently had given up on a project involving AJAX request due to CORS but I finally found a work around in YQL. I have finally figured out how to retrieve my JSON data.  Now I am trying to figure out how I can access this data and organize it in the way that I want. Here is my code currently.
var errormsg = "There was an ERROR I am sorry";
var requestURL = "https://www.tip.it/runescape/json/hiscore_user?old_stats=1&rsn="

$(document).ready(function() {
    $('#retrievestats').click(function() {
        var RSname = document.getElementById('Userinputform').value.toLowerCase();
        getUserData(RSname)
    });
});

function getUserData(RSname, callback) {
    var yql = 'https://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + requestURL + RSname + '"') + '&format=json&diagnostics=false&callback=?';

    if (!RSname) {
        alert('Please enter a username');
        return false;
    }

    $.getJSON(yql, function(data){
        console.log(data);
    });
}

As you can see, I can successfully view my data in the console of my browser but it looks as if it is all I can do. Is there any way for me to organize/separate the data? Currently the JSON gives me information in such a way
"orig_rsn":"zezima","rsn":"zezima","stats":{"overall":{"level":1280,"exp":12426850},"attack":{"level":71,"exp":815941},"defence":{"level":70,"exp":737635},"strength":{"level":70,"exp":737679},"constitution":{"level":69,"exp":697918},"range":{"level":43,"exp":53916},"prayer":{"level":46,"exp":68845},"magic":{"level":43,"exp":54901},"cooking":{"level":77,"exp":1560984},"woodcutting":{"level":73,"exp":1002436},"fletching":{"level":68,"exp":657325},

I guess what I am asking is how can I take that JSON data, and use it to dynamically replace the values in the table below according to their names

                    Fishing
                    1
                    1

                    Firemaking
                    1
                    1

                    Crafting
                    1
                    1

                    Smithing
                    1
                    1

A: A simple solution is using jQuery and creating your HTML using template function.
 var data = {
   "orig_rsn":"zezima",
   "rsn":"zezima",
   "stats": {
     "overall": {"level":1280,"exp":12426850},
     "attack":{"level":71,"exp":815941},
     "defence":{"level":70,"exp":737635},
     "strength":{"level":70,"exp":737679},
     "constitution":{"level":69,"exp":697918},
     "range":{"level":43,"exp":53916},
     "prayer":{"level":46,"exp":68845},
     "magic":{"level":43,"exp":54901},
     "cooking":{"level":77,"exp":1560984},
     "woodcutting":{"level":73,"exp":1002436},
     "fletching":{"level":68,"exp":657325}
   }
 }

 $(document).ready(function() {

   var createRow = function(skill, level, exp){
     return   "
" +
              "" + skill +"	" +
              "" + level + "	" +
              ""+exp+"
";
   };

   var createTable = function(data){
       var html = "
Skill	Level	               experience	"
       for(var propt in data.stats){
         var skill = data.stats[propt];
         html+=createRow(propt,skill["level"],skill["exp"]);
       }
       html+="
";
       return html;
   };

    $("#container").html(createTable(data));
 });

Of course, there are other ways using modern JS frameworks. But, if you want to use jQuery, that is it!
Pluker Example


text:
Q: Snowflake External Table Have a question regarding the Snowflake External Table. As we now the External Tables still a preview feature and still not a General Available. Hence have guys used External table in your production environment and you see any issue ? Snowflake do not recommend to use Preview feature in Production. Any thoughts?

A: External table feature is publicly available feature as per documentation
https://docs.snowflake.com/en/user-guide/tables-external-intro.html


text:
Q: Android Mobile Unable to connect local devices or internet at some regular intervals I bought new D-Link DIR-X1560 router. Sometimes in my mobile I lose internet connection. I can't even open router local home website (http://192.168.1.1). And this is happening to recently bought mi box 4k.
I gave static ip to mi box to fix. But even giving static ip in my mobile not working. This happens 2 to 3 hrs. every other day. Everything is fine while using old dir 860 router.


text:
Q: I have problems with Realtek rtl8723be on my HP, hq tre laptop. Need to restore to default values? I got this trouble with WIFI connection. At the beginning just turn off when my laptop was on for 2 or 3 hours, and i needed to reboot.
But, i tried to fix it and just become worst. I follow this steps:  https://www.taringa.net/+linux/realtek-8723be-wifi-ubuntu-solucionado_v6xou and my WIFI turn off. Don't work anymore.
I tried other solutions of the HP official page, but nothing works. Please,if there exists some way to return to got 2 or 3 hours of connection, just let me know. I really need (or can) return to default values for WIFI?
What information you need to help me? Also let me know.
I adjunt my wifi-info-script
https://paste.ubuntu.com/p/4MGsPCzpJd/
The response to sudo modprobe rtl8723

modprobe: ERROR: could not insert 'rtl8723be': Required key not available

The response to 'sudo updatedb && locate rtlwifi_new'
https://paste.ubuntu.com/p/TFW8WRwk6Q/
Thanks :D


text:
Q: "Riffle" two strings I have two strings, e.g.,  s1="A|P|Q|Z" and s2="r|ss|t|yy", where "|" is meant to be a separator. I would like to get the result as another string s=Ar|Pss|Qt|Zyy by joining the corresponding parts of the two strings s1 and s2 as indicated by the separators. What would be a simple way to do this?

A: Try this:
StringSplit[{s1, s2}, "|"] // Transpose // StringRiffle[#, "|", ""] &


text:
Q: Can't call razorpayX api using axios I'm trying to call razorpayX payout api in nodejs express using axios as npm package does not support it. but  API is responding with 401 error code.
my code:
  const data = {
      account_number: accountNumber,
      fund_account_id: razorPayFundAccountId,
      amount: deductAmount,
      currency: 'INR',
      mode: 'IMPS',
      purpose: 'vendor bill',
      queue_if_low_balance: true,
      reference_id: id,
      narration: ' fund transfer',
      notes: {
      },
    };
    const config = {
      method: 'post',
      url: 'https://api.razorpay.com/v1/payouts',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Basic ${Buffer.from([process.env.RAZORPAY_KEY] +
          ':' + process.env.RAZORPAY_SECRET)
          .toString('base64')}`,
        [process.env.RAZORPAY_KEY]: process.env.RAZORPAY_SECRET,
      },
      data: data,
    };
    return new Promise((resolve, reject) => {

      axios(config)
        .then((response) => {
          resolve(response.data);
        })
        .catch((error) => {
          console.log('Razorpay error');
          console.log(error);
          resolve(error);
        });
    });

error response:

response: {
status: 401,
statusText: 'Unauthorized',
headers: {
date: 'Thu, 07 Apr 2022 08:28:37 GMT',
'content-type': 'application/json',
'content-length': '165',
connection: 'close',
'cache-control': 'max-age=0, must-revalidate, no-store, nocache, private',
expires: 'Fri, 01 Jan 1990 00:00:00 GMT',
pragma: 'no-cache',
'strict-transport-security': 'max-age=3160000; includeSubDomains',
'uber-trace-id': '9572e4438ca96d4a24c7f968d06:26570acafb867:000000000000:1',
'www-authenticate': 'Basic realm="Razorpay"',
'x-frame-options': 'SAMEORIGIN',
'x-pam': '0',
'x-xss-protection': '1; mode=block'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'https://api.razorpay.com/v1/payouts',
data: '{"account_number":"1110067123","fund_account_id":"fa_JQrqTdSR...","amount":10,"currency":"INR","mode":"IMPS","purpose":"vendor
bill","queue_if_low_balance":true,"reference_id":"80ef2b6f3335734","narration":"Riod
fund transfer","notes":{}}'
},

please help with this


text:
Q: How can I change where Steam games save data? In my Documents folder I have "\Klei\DoNotStarveTogether", "\My Games\Far Cry Primal", and "Square Enix\JustCause3" that are folders made automatically by the games. I'd like to move these folders to the same place. For Don't Starve Together I was able to go into the launch settings in steam and enter
'"-persistent_storage_root "C:\Users\USER\Documents\Game Saves\Klei"'
which successfully moved the save data.
Is there any way to do this for other games?

A: You can't do that, or rather Steam has no option that forces all games to save in the same directory.
Unfortunately or fortunately, each game creates and handles its own folders. Some games, like Don't Starve Together, have set up arguments to let the user decide where they'd like to store save data, but Steam has no universal way to change which folders are used by a game.

A: in similar fashion to what SteamMover does to your Steam games, you should be able to move the folder and setup a link to the new location, you would still need a shortcut (of sorts) in the original location.
You can use steam mover for this purpose just point its source to your mydocuments folder and destination to the new parent folder.
Or use the built in windows cmd "mklink" - Creates a symbolic link.
    MKLINK [[/D] | [/H] | [/J]] Link Target

    /D      Creates a directory symbolic link.  Default is a file
            symbolic link.
    /H      Creates a hard link instead of a symbolic link.
    /J      Creates a Directory Junction.
    Link    Specifies the new symbolic link name.
    Target  Specifies the path (relative or absolute) that the new link
            refers to.

Move the save folder to the new location eg d:\NEWsaveFolder
then at "command prompt" type
mklink /J c:\OLDsaveFolder d:\NEWsaveFolder

a special shortcut will be created in the original location to the new one and not take up any space.


text:
Q: How to make material  become readonly with custom directive? I want to make <input> which using material matInput to become readonly using my custom directive. The directive isControlReadonly will be used to set readonly based on security criteria. The problem is it works on <input> but has no effect on <input matInput>
So.. this first input works, the second doesn't:
  <!-- this works -->
  <input type="input" formControlName="test_field" isControlReadonly>

  <!-- this doesn't works -->
  <mat-form-field appearance="standard">
     <mat-label>Name</mat-label>
     <input matInput type="input" formControlName="customer_name" isControlReadonly>
  </mat-form-field>

This is the directive:
import { Directive, ElementRef, OnInit, ViewChildren } from '@angular/core';
import { SecurityService } from './security.service';

@Directive({selector: '[isControlReadonly]'})
export class IsReadonlyDirective implements OnInit {

  constructor(
    private elementRef: ElementRef,
    private securityService: SecurityService
  ) { }

  ngOnInit(): void {
    var ro = !this.securityService.user.canEdit
    this.elementRef.nativeElement.setAttribute('readonly', ro)
  }

Please help how to make that custom directive works with matInput?
Edit Note: I don't want to set readonly from reactive form since directive is much cleaner code. I don't want to add logic to my component, I want the logic in the directive since it is centralized and will be used on all forms.
Thanks

A: EDIT: provided disable solution before.
To make a input readonly move your logic to "ngAfterViewInit"
Here is a working example for your directive:
@Directive({selector: '[isControlReadonly]'})
export class IsReadonlyDirective implements OnInit, AfterViewInit {

  constructor(
    private elementRef: ElementRef,
    private control: NgControl,
    private securityService: SecurityService
  ) { }

  ngAfterViewInit(): void {
   var ro = !this.securityService.user.canEdit
   this.elementRef.nativeElement.setAttribute('readonly', ro)
  }
}

A: Your directive works fine for all kind of inputs but in case of mat-input, the readonly attribute is set by your directive is overridden by Angular Material's own readonly @Input.
Refer Mat-Input's source code here : Mat-Input Readonly @Input for more info
So what you can do is get your code execution of setting attribute out of the stack and hand it over to event loop. This way your code shall be executed after Angular's manipulations. And the most common way to accomplish that is setTimeout with 0 sec delay
setTimeout(() => {
      this.elementRef.nativeElement.setAttribute('readonly', ro)
    });

Here is a working BLITZ


text:
Q: Can't find a valid editor for this file extension I've changed Extensions.txt in
Program Files (x86)\Adobe\Adobe Dreamweaver CS5.5\Configuration

And I've changed MMDocumentTypes.xml in
Program Files (x86)\Adobe\Adobe Dreamweaver CS5.5\Configuration\Document Types

But I'm still getting "Can't find a valid editor for this file extension".

A:
 in dreamwaver just go to
 Edit > Preferences > File Types/Editors
 you will find .js .asa .css .inc .txt .as .asc .asr .htaccess .htpasswd
 add your extension at the end to be like this
 .js .asa .css .inc .txt .as .asc .asr .htaccess .htpasswd .lng
 my additional extension here was .lng file.
 it really saved me a lot of time.thanks

A:
in dreamwaver just go to  Edit > Preferences > File Types/Editors
  you will find .js .asa .css .inc .txt .as .asc .asr .htaccess
  .htpasswd  add your extension at the end to be like this

This worked like a charm. Wish I would have found this two hours ago.

A: Dreamweaver's configuration work with the user folder taking precedence. Typically, at least one of the files that you mention have copies in the user's configuration folder. So if they are present they will be used not the ones in the application configuration folder.
The Adobe technote that describes how to add a file extensions ( http://kb2.adobe.com/cps/164/tn_16410.html ) lists the user configuration folder under the edits to the Extensions.txt file. Also, while that technote states to edit the MMDocumentTypes.xml file in the application folder, make sure you don't have a copy in your user folder. There are some circumstances where there will be a copy in the user folder and if so, you have to make changes to the user configuration folder copy, not the application configuration folder version.


text:
Q: Red5 can't locate Java on Cygwin I'm setting up a Red5 server on Cygwin
I get this
/usr/share/red5$ sh red5.sh
Running on  CYGWIN_NT-6.1-WOW64
Unable to locate Java. Please set JAVA_HOME environment variable.

However, I can also do this:
    javac -version and get javac 1.7.0, so I know that's installed, at least.
I can also go into the emacs .bash_profile and see that I've added this to the bottom:
export PS1='\w\$ '
export EMACS_HOME=~/emacs-22.3
export JAVA_HOME =/cydrive/c/Program\ Files/Java/jdk1.6.0_32
export PATH=$PATH:$EMACS_HOME/bin:$JAVA_HOME/bin
export PATH=$PATH:$EMACS_HOME/bin

So what's missing?

I edited .bash_profile to be this:
export PS1='\w\$ '
export EMACS_HOME=~/emacs-22.3
export JAVA_HOME=/cydrive/c/Program\ Files/Java/jdk1.6.0_32/
export JAVA_HOME=$( cygpath -d "$JAVA_HOME" )
export PATH=$PATH:$EMACS_HOME/bin:$JAVA_HOME/bin
export PATH=$PATH:$EMACS_HOME/bin

And I get this error
cygpath: cannot create short name of D:\cygwin\cydrive\c\Program Files\Java\jdk1.6.0_32\

A: export JAVA_HOME=/cydrive/c/Program\ Files/Java/jdk1.6.0_32/
I just misspelled cydrive, when it should have been cygdrive.


text:
Q: How to Create Database for Storage Room i wanted to create via Excel or Oracle a database for a Storage room that is filled with all kinds of Computer parts and stuff.
I never created something like that, so i wanted to know if you could help me out giving me an advice how to create a database for a beginner
It should be possible to  insert and remove parts or even update them
Hope my question is readable and understandable.
Thanks

A: A simple option to do that - not only the table so that you could write your own DML statements (to insert, update or delete rows) - but to create a nice application - is to use Oracle Application Express (Apex).
Depending on database version you use, it might already be installed by default. If not, ask your DBA to install it.
Alternatively, create a free account on apex.oracle.com; you'll get limited space (more than enough to do what you want to do).
In Application Builder, use the Excel file you have as a "source" which will then be used by Apex's wizard to create a table in the database, as well as application, true GUI which works and looks just fine.

If you don't have anything at all, not even an Excel file, well ... that's another problem and requires some more work to be done.

*

*you have to know what you want (OK, a storage room)

*is a single table enough to contain all information you'd want to collect?

*

*if so, which columns (attributes) do you want to collect?

*if not (for example, you'd want to "group" items), you'd need at least two tables which will be related to each other by the means of master-detail relationship, which also means that you'll have to create a foreign key constraint

*which datatypes are appropriate for certain attributes? You wouldn't store item names into number datatype, right? Nor should you put dates (when item entered the storage room) as a string in varchar2 column, but into a date datatype column

*etc.

Basically, YMMV.


text:
Q: GRPC connecting over TOR Hi I am trying to connect via GRPC to a server over TOR
Currently I use the following code to connect to the clearnet version of the server but now I would like to do the same over TOR in JAVA.
 OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress(host, port)
        .connectionSpec(new ConnectionSpec.Builder(OkHttpChannelBuilder.DEFAULT_CONNECTION_SPEC)
        .tlsVersions(ConnectionSpec.MODERN_TLS.tlsVersions().toArray(new TlsVersion[0]))
        .build());

      ManagedChannel channel = builder.build();

      stub = LightningGrpc
       .newStub(channel)
       .withCallCredentials(new MacaroonCallCredential(macaroon));

Is it just a matter of using the onion address and port? I tried removing TLS but then I get an "UNAVAILABLE" error.
thanks


text:
Q: JQuery's ajax post request does not work as it's supposed to be The page's link is: localhost/mysite/create-user
This is the code:
        <form class="form-horizontal" name = "signUp1F" id = "signUp1F">
            <input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = "Doctor, Trainer, Human Resource etc.">
            <input type="hidden" name="neoid" id="neoid" value="<?php echo $neoid; ?>" />
            <button id = "plus" class="btn btn-success">Plus</button>

        </form>

The jquery code:

The purpose is this: user enters a skill value to the input, clicks the Plus button, an ajax request is sent to add the skill to the database. And the code that handles this request is on localhost/mysite/add-skill.
But things go wrong. When I click the "plus" button, it goes to the page localhost/mysite/create-user?pskil=php&neoid=53. What can possibly make this direction? I've been working on this issue for almost 2 hours and I cannot manage to handle it.

A: The issue is that your button tag submit your form. Here is a updated JavaScript source that you can use. jQuery got a built in preventDefault() method for events. This will for an example prevent the button to submit the form.

Tryout: http://jsfiddle.net/3A7Mg/1/


text:
Q: Does anyone else feel that iterator syntax sugar is a must have in a modern language? I work with C# professionally and I write code like this all the time.
private IEnumerable<Something> GetAlotOfSomething()
{
    if (somethingA.IsReady)
        yield return somethingA;
    if (somethingB.IsReady)
        yield return somethingB;
    if (somethingC.IsReady)
        yield return somethingC;

    // ... More complex logic
}

var specialSomethings =
    GetAlotOfSomething()
    .Where(s => s.IsSpecial);

Then one day I have to write a bit of VB6 or JScript and I end up writing so much boilerplate just to get things done. Anyone thoughts?

A: Iterators (generators etc) are certainly great features that I use a lot.  I don't qualify them as necessary, but I will certainly choose languages that have them when I get a choice.

A: They're... Handy.
But you can always just write your own if necessary. The big wins come from standard library / framework support.


text:
Q: Diagonal Matrix Proof
Prove that a diagonal matrix is positive definite if and only if all
  its diagonal entries are positive. Also write down and identify its
  associated inner product. (I can't use eigenvalues to prove this
  because I haven't learned them yet).

My attempt:
In order to be positive definite, matrix K must be symmetric and satisfy positivity. Since we have a diagonal matrix and all its diagonal entries are positive its determinant will be positive as well as its leading coefficient, but how can I show all this information formally using a proof?

A: If $K$ is diagonal, it is of the form $K=\mathrm{diag}(k_1,k_2,\ldots,k_n)$ for some real $k_i$. Let $x=(x_i)$ be a real $n\times 1$ vector; then
$$x^TKx = \sum_{1\leq i\leq n} k_i x_i^2$$
is the inner product associated with $K$.
Since $K$ is positive definite, we have that $x^TKx>0$ for all nonzero $x$. Suppose that some diagonal entry $k_{d}\leq 0$.  Then if we take an $x$ such that $x_d=1$ and other components of $x$ are zero, then $x^TKx = k_{d}x_d^2 <0$. This contradicts the fact that $K$ is positive definite.
The converse should be fairly easy and proceed along similar lines.
Note:$K$ need not be symmetric to be positive definite.


text:
Q: Mountebank using wrong predicate and ignoring the value in contains I tried their documentation, but it's very "basic", so hope somebody here can spot my issue? I got 2 predicates, one with the wrong user, one with the right user.
The user's base64 is sent via post-body, but it seems the contains of Mountebank is simply ignoring it and choosing a predicate with another contains value... why is that?
my request is with dX...2g=:
"body":"{\"auth\":\"dXNlcjpmYWxzY2g=\"}"

but Mountebank matches a predicate with dX...Gln:
using predicate match: [{
   "equals":{"method":"POST","path":"/new"},
   "contains":{"body":"{\"auth\":\"dXNlcjpyaWNodGln\""}
}]

The contains doesn't match, and still it's using that predicate,
even though my stubs do contain a matching predicate, but it is not used:
{
  "path": "/new",
  "predicates": [{
    "equals": {
      "method": "POST",
      "path": "/new"
    },
    "contains": {
      "body": "{\"auth\":\"dXNlcjpyaWNodGln\""
    }
  }],
  "responses": [{
    "is": {
      "statusCode": 200,
      "body": {}
      }
    }
  }]
}
,
{
  "path": "/new",
  "predicates": [{
    "equals": {
      "method": "POST",
      "path": "/new"
    },
    "contains": {
      "body": "{\"auth\":\"dXNlcjpmYWxzY2g=\""
    }
  }],
  "responses": [{
    "is": {
      "statusCode": 401,
      "body": {}
      }
    }
  }]
}

Is my syntax wrong? It's matching the first predicate, even though it does not contain dXNlcjpmYWxzY2g=
It does work using equals, I'm just curious why contains isn't.

A: The trick seemed to be use and, which is odd, but the solution would be:
"predicates": [{
  "and": [
    { "equals": { "method": "POST", "path": "/new" }},
    { "contains": { "body": "{\"auth\":\"dXNlcjpyaWNodGln\"" }}
  ]
}],


text:
Q: What are the interior, boundary, exterior and cluster points of $\{(x,y) | 0 < xy \le 1\}$ in $\mathbb R^2$ The $xy$ is really confusing me for some reason. My thought the interior points are $[0,1]$ and the exterior points is the compliment of $[0,1]$ but I'm not sure.

A: $0<xy$ means you are restricted to the first and third quadrant! $xy \leq 1$ means you are on or under the $y=\frac{1}{x}$ hyperbola for $x>0$ and on or above the hyperbola for $x<0$. Hope this helps you to draw the set correctly in $\mathbb{R^2}$.


text:
Q: Sql Server 2005 Restore Failing Running sql server 2005 I have database A. I am trying to restore from a backup of A to database B. I want to retain the database A and create a new testing database B from a previous set of data.
I tried to create B and restore from the .bak AND restore database to B from management studio.
The error is...

TITLE: Microsoft SQL Server Management
Studio
Restore failed for Server
  '195448-APP2'.
  (Microsoft.SqlServer.Smo)
For help, click:
  http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.1399.00&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476
------------------------------ ADDITIONAL INFORMATION:
System.Data.SqlClient.SqlError: The
  backup set holds a backup of a
  database other than the existing 'B'
  database. (Microsoft.SqlServer.Smo)
For help, click:
  http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.1399.00&LinkId=20476
------------------------------ BUTTONS:
OK

I found this snippet which I am hesitant to use and want to ask if it would solve my problem of changing the location of the mdf and ldf during the process of restoring the database or does it replace database A's items altogether.
ALTER DATABASE AdventureWorks
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
RESTORE DATABASE AdventureWorks
FROM DISK = 'C\:BackupAdventureworks.bak'
WITH MOVE 'AdventureWorks_Data' TO 'C:\Data\datafile.mdf',
MOVE 'AdventureWorks_Log' TO 'C:\Data\logfile.ldf',
REPLACE

[http://blog.sqlauthority.com/2007/04/30/sql-server-fix-error-msg-3159-level-16-state-1-line-1-msg-3013-level-16-state-1-line-1/][1]
and for me I would make it...
RESTORE DATABASE B
FROM DISK = 'C:\backupofA.bak'
WITH
MOVE 'B' TO 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\B.mdf',
MOVE 'B_log' to 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\B_log.ldf',
REPLACE

What I don't know is if it will affect database A at all. I am hoping the replace refers files associated with B.
or if it should be
RESTORE DATABASE B
FROM DISK = 'C:\backupofA.bak'
WITH
MOVE 'A' TO 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\B.mdf',
MOVE 'A_log' to 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\B_log.ldf',
REPLACE

If anyone could help me with the error and/or confirm this fix I would be very grateful as it is not my database I'm playing with.
Thanks.

A: You could simply use the Copy Database Wizard.
If you wanna do it like pros and use T-SQL the RESTORE .. MOVE ... REPLACE will do what you expected: move the two files at the locations you intend and replace database B with content from the backup. A will be unaffected.

A: I would use the wizard if I were you: In Sql Server Management Studio right click on "Databases" and select "Restore Database...". This dialog / wizard will do exactly what you are asking - simply select the source .bak file(s) / Database that you want to restore from, enter the name of the database you want to restore to and hit "Ok".
Some notes - if you enter the name of a database that doesnt yet exist (it sounds like this is what you want to do), it will create that database for you. If you enter the name of an existing database it will attempt to restore to that database. If you attempt to restore to an existing database from a backup made of a different database it will fail, however you can force the Sql Server to overwrite the existing database by going to "Options" and checking the "Overwrite the existing database" checkbox.
Also, if you are restoring a backup of an existing database to create a new second copy of that database you may find that the wizard fails as its attempting to create a database using the same database file paths as the ones currently in use by the source database. To fix this you need to click on "Options" and change all of the "Restore As" file paths to files that dont yet exist.
You can also get this wizard to generate an SQL script instead of actually performing the actual restore (click on the "script" button at the top), which is handy if you want learn how to do this sort of thing in raw SQL instead.

A: It is possible to restore a database from sql server 7, sql server 2000 to sql server 2005.
It can be achieved by using restore and with replace command
use master

restore database mydatabase from disk ='c:\mybackup.bak' with replace

It is easy to take a backup in sql server using this script without any external tools.
Check out Restore with Example.

A: drop database b first. then do the restore.


text:
Q: Get a DriveItem resource from shared folder by path all.
I have a problem to get DriveItem by a path from OneDrive service.
The first request: GET me/drive/root/children
      "remoteItem": {
    "id": "EF8A24CC458790DF!106",
    "parentReference": {
      "driveId": "ef8a24cc458790df",
      "driveType": "personal"
    }
  }

The second request: drives/ef8a24cc458790df/items/EF8A24CC458790DF!106/children
{  "value": [
{
  "parentReference": {
    "driveId": "ef8a24cc458790df",
    "driveType": "personal",
    "id": "EF8A24CC458790DF!106",
    "name": "src",
    "path": "/drives/ef8a24cc458790df/root:/onedriveapi/src"
  },
} ] }

But request: /drives/ef8a24cc458790df/root:/onedriveapi/src failed with code "itemNotFound".
This has to work:
https://github.com/OneDrive/onedrive-api-docs/blob/live/docs/rest-api/api/driveitem_get.md
Where is my mistake?

A: It is bug in API.
For non-owner cases, a direct path from the root is not allowed.
https://github.com/OneDrive/onedrive-api-docs/issues/908


text:
Q: 404 Not Found JS and CSS I have a portlet deployed on my Liferay/Tomcat server. The portlet.xml is calling the init param "/index.html". This file renders fine on my portal.
I have /css and /js folders on the same level as my index.html, under the /docroot.
I link them like this:
<script type="text/javascript" src="js/somejs.js"></script>
<link rel="stylesheet" type="text/css" href="css/mystyles.css">

The file structure:
 /docroot/
        /css/
        /js/
        index.html

However, I'm getting these 404's
"NetworkError: 404 Not Found - http://localhost:8080/web/guest/js/somejs.js"
"NetworkError: 404 Not Found - http://localhost:8080/web/guest/css/mystyles.css"

My folders won't get recognized unless I type this explicitly link my portlet like this:
<script type="text/javascript" src="MyPortlet/js/somejs.js"></script>

This is undesirable, as the name of the portlet may change in the future and I'll have to rename all <script>'s and <link> references.
Any ideas fix this issue? Does I need a global context path?

A: Solution1 (quick fix) : Add below code in your JSP
<script src="<%=renderRequest.getContextPath()%>/js/somejs.js"></script>
<link   href="<%=request.getContextPath()%>/css/mystyles.css" rel="stylesheet"/>

Solution 2 (Liferay recommended) : add below code in liferay-portlet.xml and let Liferay load the css & js files.
<header-portlet-css>/css/mystyles.css</header-portlet-css>
<footer-portlet-javascript>/js/somejs.js</footer-portlet-javascript>

But i would suggest keep your all js and css file into theme and access from there


text:
Q: Nonincreasing and nondecreasing sequences in Hausdorff metric For every metric space $(X,d)$ we have the Hausdorff metric space $(\mathcal{H}(X),H)$ that assosiates with it, where $\mathcal{H}(X)$ is the space of nonempty compact subsets of $X$ and $H$ is the hausdorff metric.
As part of a fractals seminar I'm working on I want to use that any nonincreasing sequence of subsets in $\mathcal{H}(X)$: $A_1\supseteq A_2 \supseteq...$ is a Cauchy sequence.
Similarly, I want to show somthing similar for nondecreasing subsets, though since this clearly doesn't hold (take $([0,n])_{n\in\mathbb{N}}$) I though to add the condition that all elements of the sequence are contained in some compact subset.
Though I'm pretty sure that those statements should be true, I'm having trouble with proving them. Maybe it's just that I get confused with all the max-min stuff.
Are those 2 statments true or am I missing some condition?
Could you help me prove them? If they are both true, and the proofs are similar, please proof one and leave the other as an exercise.
Thanks

A: I think that for the nonincreasing sequence, you can actually show that the sequence converges toward $\cap A_n$ (suppose it does not and then you get a sequence $x_{k_n}\in A_{k_n}$ where $(k_n)$ is strictly increasing and $d(x_{k_n},\cap A_n)>r_0>0$). You get that $(x_{k_n})$ up to extraction converges in $A_1$ and eventually is in all $A_n$ hence the limit must be in $\cap A_n$ contradicting $d(x_{k_n},\cap A_n)>r_0$ for all $n\in \mathbb{N}$.
For the second statement, you might be right. I think that if $(A_n)$ is a non decreasing sequence of compact included in $K$ compact then you can show that the limit of $(A_n)$ will be :
$$\overline{\bigcup A_n} $$
This is compact because it is a closed subset of $K$.


text:
Q: Finding orthonormal basis from orthogonal basis The following is example C.5 from Appendix C (Linear Spaces Review) of Introduction to Laplace Transforms and Fourier Series, Second Edition, by Phil Dyke:

Example C.5 Show that $\{\sin(x),\cos(x)\}$ is an orthonormal basis for the inner product space $V=\{a\sin(x)+b\cos(x); a,b\in\mathbb R, 0\le x\le\pi\}$ using as inner product $$\langle f,g \rangle = \int_0^1 fg dx, \qquad f,g\in V$$
  and determine an orthonormal basis.
Solution $V$ is two dimensional and the set $\{\sin(x),\cos(x)\}$ is obviously a basis. We merely need to check orthogonality. First of all, $$\begin{align}\langle\sin(x),\cos(x)\rangle=\int_0^\pi\sin(x)\cos(x)\,dx&=\frac{1}{2}\int_0^\pi\sin(2x)\,dx\\ &=\left[-\frac{1}{4}\cos(2x)\right]_0^\pi \\ &=0.\end{align}$$ Hence orthogonality is established. Also, $$\langle\sin(x),\sin(x)\rangle=\int_0^\pi\sin^2(x)\,dx=\frac{\pi}{2}$$ and $$\langle\cos(x),\cos(x)\rangle=\int_0^\pi\cos^2(x)\,dx=\frac{\pi}{2}.$$ Therefore $$\left\{\sqrt{\dfrac{2}{\pi}}\sin(x),\sqrt{\dfrac{2}{\pi}}\cos(x)\right\}$$ is an orthonormal basis.

I understand that, for orthonormality, we require that $\| \mathbf{a} \| = 1$. However, I'm unsure of how the orthonormal basis was found at the bottom of the proof?
I would appreciate it if people could please take the time to clarify this.

A: As mentioned in the comments to the main post, $\lVert \sin(x) \rVert = \sqrt{\langle \sin(x), \sin(x) \rangle} = \sqrt{\frac{\pi}{2}}$. We then divide the orthogonal vectors by their norms in order convert them into orthonormal vectors. This gets us the orthonormal basis mentioned in the textbook excerpt.


text:
Q: BigQuery external table over GCS path with partitions I have some data stored in GCS bucket in the following path:
gcs://my-bucket/my_data/subfolder1/subfolder2/**.csv.gz

I intent to create an external table mapping to my_data and want the external table is able to partition the data by different level of subfolders. Note that subfolder1 or subfolder2 don't have a hive partition prefix, i.e, not in the format of prefix=value.
If I would write some pseudo code in Athena syntax, it would be something like below:
CREATE EXTERNAL TABLE `my_data`(
   --Column specs go here---
)
PARTITIONED BY (
  `partition_0` string,
  `partition_1` string)
ROW FORMAT DELIMITED
  FIELDS TERMINATED BY ','
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'gcs://my-bucket/my-data/'
TBLPROPERTIES (...)

As a result of the pseudo code, the table will consists of two partition columns in addition to columns defined in the column spec.

*

*partition_0

*partition_1

Queries filtering on these two columns will then benefits from partition pruning.
Would anyone please advise if this possible in BigQuery. If yes, how I should go about it in SQL?


text:
Q: Do you know of any Java bytecode interpreters? i am looking for a Java interpreter not a JVM (no JIT)
till now i have checked

*

*llvm vmkit

*gij (from gcj)

*jikesrvm (JVM)

*Kaffe (JVM)

However, as i only need an interpreter i would prefer to find something simpler and smaller (in LOCs) preferably written in C/C++

A: JamVM, if you don't mind the simple code-copying JIT in the last version. "Code-copying" probably means a simple way avoiding switch statement.
See http://jamvm.sourceforge.net/


text:
Q: ctrl+tab functinality in WPF If you press ctrl+tab in the .NET IDE, it shows all the active files and their images. Can anybody tell me how to implement this functionally using WPF?

A: My guess would be to use a Grid control and probably a custom control that can show an Image alongside some text (probably use a Label or TextBlock). You can then enumerate your open files and create one control for each, placing it into the columns and rows of the Grid.
Give it a try and tell us how you get on. It would be great to see you post back with your solution or a link to your solution. Good luck!


text:
Q: How to use removeChild method?

const toDoForm = document.querySelector(".todo__form"),
      toDoInput = document.querySelector(".todo__input");
      toDoList = document.querySelector("li");

let toDoArray = [];

function addToDoList() {
  toDoForm.addEventListener('submit', event => {
    toDoArray.push(toDoInput.value);
    toDoList.innerHTML += `<ul>${toDoArray[toDoArray.length-1]}</ul>`;
    event.preventDefault();
    toDoInput.value = "";
  });
}

function clearList() {
  const toDoUl = document.querySelector("ul");
  toDoForm.addEventListener('click', event => {
    toDoArray = [];
    toDoUl.parentNode.removeChild(toDoUl);
  });
}

function init() {
  addToDoList();
  clearList();
}

init();

To-Do List

  <form class="todo__form">
    <input class="todo__input" type="text">
    <input class="todo__submit" type="submit" value="Submit">
    <input class="todo__clear" type="button" value="Clear">
  </form>

I'm making a to-do list with javascript and i tried to use removeChild method to clear to-do list but when i run the code, it keeps getting an error like this -> Uncaught TypeError: Cannot read property 'parentNode' of null at HTMLFormElement. How can i solve it?

A: The query document.querySelector("ul"); is returning undefined because there is no ul element in the HTML. Try changing the div to ul tag

A: First, I thought you want remove one item at a time, then I made some changes which may be useful but you if you don't need it, you could remove delete function.
For adding an item, you enter a job name, for example 'Job1' an then press "Submit" button.
For deleting an item, you enter a job name, for example 'Job1' an then press "Delete" button.
Press 'Clear' to clear all items.
JavaScript:

HTML:

To-Do List

        <form class="todo__form">
            <input class="todo__input" type="text">
            <input class="todo__submit" type="submit" value="Submit">
            <input class="todo__delete" type="button" value="Delete">
            <input class="todo__clear" type="button" value="Clear">
        </form>

A: First, you need to change

 to

. You can get help from w3school link.
There is a StackOverflow answer about this issue Stackoverflow. You can check that.


text:
Q: How to make css reverse animation? I want to animate a DIV element and change it's background and text color. Then change it back to original colors. So CSS below sets background green and text color white. How do I animate switching colors back, e.g. white background and black text? So first 2 seconds it's changing to green/white and next 2 seconds white/black.
.myClass {
    background-color:           #4caf50;
    -webkit-animation-name:     anim1;  /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 2s;     /* Safari 4.0 - 8.0 */
    animation-name:             anim1;
    animation-duration:         2s;
    color:                      white;
    font-weight:                bold;
}

@-webkit-keyframes anim1 {
    from {background-color: white;}
    to {background-color: #4caf50;}
}

@keyframes anim1 {
    from {background-color: white;}
    to {background-color: #4caf50;}
}

A: You can Control your animation with defining percentage for it's @keyframes.
change animation duration to 4s and change background-color at 50% and change it back again.
try this:
.myClass {
background-color:           #4caf50;
-webkit-animation-name:     anim1;  /* Safari 4.0 - 8.0 */
-webkit-animation-duration: 4s;     /* Safari 4.0 - 8.0 */
animation-name:             anim1;
animation-duration:         4s;
color:                      white;
font-weight:                bold;
}

@-webkit-keyframes anim1 {
0% {background-color: white;}
50% {background-color: #4caf50;}
100% {background-color: white;}
}

@keyframes anim1 {
0% {background-color: white;}
50% {background-color: #4caf50;}
100% {background-color: white;}
}


text:
Q: Wordpress, Custom Taxonomies Broken Every Install I just created my first proper theme and I'm having trouble working out the last bug, I have a custom 'portfolio' post type with its own custom taxonomy (portfolio-category). However, every/any time I install the theme on a different install of wordpress (all latest 3.5) the taxonomie is broken, does not display where it is supposed to. This is after adding new 'portfolio categories' and saving.
Pastebin of my taxonomy code from functions.php and the code I call it in (for an isotope filter).
If anyone could help me I'll love them forever <3
Thanks!
Sorry, forgot pastebin link http://pastebin.com/eVqndBZP

A: You forgot the pastebin link but by past experience you probably just need to go to permalinks and press save.
Also see http://codex.wordpress.org/Rewrite_API/flush_rules


text:
Q: Why does not the weight decrease in an ascending and accelerating lift? My textbook says that weight of a person in a lift that is accelerating in upward direction increases.
But,why is it so?
The acceleration of lift and the acceleration due to gravity are in opposite direction.
Hence,weight of the person should be $m(a-g)$(where $m$ is the mass of the person,$a$ is the acceleration of lift and $g$ is the acceleration due to gravity.
Then,where is my serious conceptual flaw?
I have checked Why do we weigh less when falling? I donot find satisfactory explanation of my query there.

A: To weigh nothing, you must be experiencing no acceleration. An object in free fall under the influence of a gravity field experiences no weight, so within its own frame of reference it has no acceleration, although an outside observer would see it accelerating downward. This discrepancy is because, according to Einstein, gravity curves space-time. One can correctly say that a stationary object in a gravity field is accelerating less downward (or more upward) than one in free fall. If "no weight" equals "no acceleration", then the stationary object must be in continuous upward acceleration (because of space-time curvature). So, the upward-accelerating elevator is increasing the total acceleration on its contents, causing them to weigh more than they would if stationary, which is what we observe.

A: You asked if there's a serious flaw in the assumptions that you're making. The flaw is that Newton's law hold, in its simplest form, in an inertial frame only. So, if you have a lift which is going up with an acceleration $-a$, then you've to introduce a fictitious acceleration $a$ on the body. I have assumed the downward direction to be positive.
So, the net acceleration downward is $a+g$. Always think about the acceleration on the body, rather than on the frame. Once you agree with this, you have the weight being equal to $m(a+g)$, and hence it has increased by $ma$

A: As the lift accelerates upward, the reaction force supplied by the floor of the lift upwards to your feet must oppose both your weight and the upwards acceleration of the lift. This is the apparent weight you feel.

A: There is mass as in F=m X a , and then there is weight. Weight is what m is for the standard g of gravity and is usually  measured on a calibrated weighing scale. On the scale in an accelerator the force the body exerts will be the mg of gravity plus the a*m of the equal and opposite force to the one exerted by the scale on the body. Thus the scale which is calibrated with only gravitational forces will show a larger weight.
Do not confuse mass with weight.

A: The confusion comes from people using two different definitions of weight:

*

*The force on an object by gravity.  This is the official meaning of weight in physics.  (You can elaborate this definition further, but it does not matter for this discussion.)

*The reading when an object is placed on a scale.  This is what most lay persons would call weight.  In physics, scale reading would be a better name.
When people weigh themselves on their bathroom scale, these two amounts are the same.  That's because the Earth is essentially an inertial reference frame.  Suppose you weigh 700 N; your weight and the scale reading are both 700 N.
However, in an accelerating reference frame, these two amounts can differ.  In an upwardly-accelerating lift, your scale reading will be larger than your weight.  Let's say your weight is still 700 N but the scale now reads 1000 N.
Now consider the forces acting on you.  There is the force of gravity, pulling downward -- in fact, it's your weight!  So we have 700 N downward.  There is also the scale under you, pushing upward; by the 3rd Law, it's amount is the scale reading.  So this is 1000 N upward.
What is your net force?  700 N downward + 1000 N upward = 300 N upward.
Your acceleration can be calculated using your mass and the 2nd Law $F_{net}=ma$.  The 2nd Law also tells us that the direction of your acceleration is the same as the direction of the net force.  In the previous paragraph, we found that the net force is upward.  So your acceleration must be upward.
And this exactly matches the direction of the elevator's acceleration.
You can perform a similar analysis of a downwardly-accelerating lift, and you will find that Newton's Laws are obeyed when the scale reading is less than the weight.
Sorry it's a late answer, but hope this helps.