text:
Q: clojure use threading macro for equation I have this equation in java that I want to translate into clojure:
limit = (int)(n*(Math.log(n) + Math.log(Math.log(n)))) + 3;

I want to avoid it turning into a sea of nested parenthesis, what is the best way of making this readable in clojure?

A: You can use let form to break the formula to simpler parts:
(defn calc-limit [n]
  (let [log (Math/log n)
        loglog (Math/log log)
        logsum (+ log loglog)]
    (-> n (* logsum) int (+ 3))))

(calc-limit 256) ; => 1861

A: I have to agree with the other answers that a let with some descriptive names is a little more enlightening to read. But if you want to do it with just a threading macro, that is possible using ìterate:
(defn calc-limit [n]
      (->> n
           (iterate #(Math/log %))
           (drop 1) ;;The first value is just n, with no logarithms applied
           (take 2) ;;Taking the 1st and 2nd iterations of Math/log on n
           (reduce +)
           (* n)
           int
           (+ 3)))

A: You can also use Graph, especially if your formulas will grow bigger and if the speed isn't that much of an issue:
(use 'plumbing.core)
(require '[plumbing.graph :as graph])

(def limit-graph
  {:log    (fnk [n]  (Math/log n))
   :loglog (fnk [log] (Math/log log))
   :logsum (fnk [log loglog] (+ log loglog))
   :limit  (fnk [n logsum] (-> logsum (* n) int (+ 3)))})

(def calc-limit (graph/compile limit-graph))

(:limit (calc-limit {:n 5}))

A: You mention the threading macro in your question's title, so I'll provide a variant primarily focused on exactly that, using let to avoid calculating (Math/log n) twice:
(let [x (Math/log n)]
  (-> (Math/log x)
      (+ x)
      (* n)
      (int)
      (+ 3)))

Side Note: Using let makes sense when

*

*you've values that have to be used more than once,

*you want to improve understandability by expressively naming intermediate results, or

*you want to improve readability by splitting up your problem into smaller parts.


text:
Q: Second label for x-axis does not appear in 3D pgfplot For the figure below, I need show two labels for the x-axis, as shown. The problem is that I need the lower Temperature label to appear where "HERE" is in the figure. I can use above to place the text above the node position but the axis label does not appear when I use below. If I omit above or below from the node position, then the upper half of the text appears on top of the axis line.
I followed the answer from this post but there is one important difference (as far as I can tell). I have set my default axis labels to be above the graph, with the secondary labels below the graph.
This is one of a series of graphs. I am "building" the graph one item at a time to orient my students. I want to temporarily add the additional x-axis label for orientation purposes. The next graph will do the same thing for a second variable (seed size). The remaining figures would have the labels only above the graph.
\documentclass[border=10pt]{article}
\usepackage{pgfplots}
    \usepgfplotslibrary{colorbrewer}
    \usepgfplotslibrary{fillbetween}
    \pgfplotsset{
        % Set `compat level to 1.11 or higher so you don't need to
        % prefix every tikz coordinate with `axis cs:'
        compat=1.14,
        3dbaseplot/.style={
                width           = 10cm,
            view            = {45}{65},
            axis on top,
            enlargelimits = false,
            domain          = 1:4,
            y domain       = 1:4,
            no markers,
            samples        = 30,
            xlabel          = {Temperature},
            ylabel          = {Seed Size},
            zlabel          = {Relative\\Abundance},
            xlabel style    = {sloped, at={(rel axis cs:0.5,1,1)}, above, sloped like x axis},
            ylabel style    = {sloped, at={(rel axis cs:0,0.5,1)}, above, sloped like y axis},
            zlabel style    = {rotate=-90, align=right},
            ticks               = none,
            smooth,
    },
    /pgf/declare function = {
        normal(\m,\s)=1/(2*\s*sqrt(pi))*exp(-(x-\m)^2/(2*\s^2));
    },
    /pgf/declare function = {
        bivar(\ma,\sa,\mb,\sb)=
            1/(2*pi*\sa*\sb) * exp(-((x-\ma)^2/\sa^2 + (y-\mb)^2/\sb^2))/2;
    }
}

\pgfmathsetmacro{\factor}{3}

\newcommand*\myaddplotX[4]{
    \addplot3+ [name path=#1,domain=#2-\factor*#3:#2+\factor*#3, color=#4] (x,4,{normal(#2,#3)});
}
\newcommand*\myaddplotY[4]{
    \addplot3+ [name path=#1,domain=#2-\factor*#3:#2+\factor*#3, color=#4] (1,x,{normal(#2,#3)});
}

\begin{document}

\begin{tikzpicture}[
    declare function = {orMuX=2.0;},
    declare function = {orMuY=3.2;},
    declare function = {blMuX=2.5;},
    declare function = {blMuY=2.7;},
    declare function = {sX=0.25;},
    declare function = {sY=0.15;},
    ]
        \begin{axis}[
            3dbaseplot,
            colormap/OrRd,
            set layers,
            ylabel={},
            samples=30,
        ]

            \myaddplotX{B}{blMuX}{sX}{white}
            \myaddplotY{C}{blMuY}{sY}{white}
            \myaddplotY{D}{orMuY}{sY}{white}
            \myaddplotX{A}{orMuX}{sX}{orange}

        \draw [dashed] (2.0-\factor*sX, 1) -- (2.0-\factor*sX, 4);
        \draw [dashed] (2.0+\factor*sX, 1) -- (2.0+\factor*sX, 4);

%% This places the text above the axis. I don't want this one.
        \node at (xticklabel cs:0.5) [above, sloped like x axis] {Temperature};

%% THIS DOES NOT APPEAR.This is the one I want.
        \node at (xticklabel cs:0.5) [below, sloped like x axis] {Temperature};

  \end{axis}
\end{tikzpicture}

\end{document}

A: I threw in the xslant just for fun.
\documentclass[border=10pt]{article}
\usepackage{pgfplots}
    \usepgfplotslibrary{colorbrewer}
    \usepgfplotslibrary{fillbetween}
    \pgfplotsset{
        % Set `compat level to 1.11 or higher so you don't need to
        % prefix every tikz coordinate with `axis cs:'
        compat=1.14,
        3dbaseplot/.style={
                width           = 10cm,
            view            = {45}{65},
            axis on top,
            enlargelimits = false,
            domain          = 1:4,
            y domain       = 1:4,
            no markers,
            samples        = 30,
            xlabel          = {Temperature},
            ylabel          = {Seed Size},
            zlabel          = {Relative\\Abundance},
            xlabel style    = {sloped, at={(rel axis cs:0.5,1,1)}, above, sloped like x axis},
            ylabel style    = {sloped, at={(rel axis cs:0,0.5,1)}, above, sloped like y axis},
            zlabel style    = {rotate=-90, align=right},
            ticks               = none,
            smooth,
    },
    /pgf/declare function = {
        normal(\m,\s)=1/(2*\s*sqrt(pi))*exp(-(x-\m)^2/(2*\s^2));
    },
    /pgf/declare function = {
        bivar(\ma,\sa,\mb,\sb)=
            1/(2*pi*\sa*\sb) * exp(-((x-\ma)^2/\sa^2 + (y-\mb)^2/\sb^2))/2;
    }
}

\pgfmathsetmacro{\factor}{3}

\newcommand*\myaddplotX[4]{
    \addplot3+ [name path=#1,domain=#2-\factor*#3:#2+\factor*#3, color=#4] (x,4,{normal(#2,#3)});
}
\newcommand*\myaddplotY[4]{
    \addplot3+ [name path=#1,domain=#2-\factor*#3:#2+\factor*#3, color=#4] (1,x,{normal(#2,#3)});
}

\begin{document}

\begin{tikzpicture}[
    declare function = {orMuX=2.0;},
    declare function = {orMuY=3.2;},
    declare function = {blMuX=2.5;},
    declare function = {blMuY=2.7;},
    declare function = {sX=0.25;},
    declare function = {sY=0.15;},
    ]
        \begin{axis}[
            3dbaseplot,
            colormap/OrRd,
            set layers,
            ylabel={},
            samples=30,
        ]

            \myaddplotX{B}{blMuX}{sX}{white}
            \myaddplotY{C}{blMuY}{sY}{white}
            \myaddplotY{D}{orMuY}{sY}{white}
            \myaddplotX{A}{orMuX}{sX}{orange}

        \draw [dashed] (2.0-\factor*sX, 1) -- (2.0-\factor*sX, 4);
        \draw [dashed] (2.0+\factor*sX, 1) -- (2.0+\factor*sX, 4);

        \coordinate (A1) at (rel axis cs: 0,0,0);
        \coordinate (A2) at (rel axis cs: 1,0,0);

  \end{axis}
  \path  (A1) -- (A2) node[midway, above, sloped, xslant=.5]  {Temperature};
  \path  (A1) -- (A2) node[midway, below, sloped, xslant=.5]  {Temperature};
\end{tikzpicture}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Downloading file via HTTPS using QNetworkAccessManager: How to authenticate? The general answer you can find everywhere is to use the Signal authenticationRequired(QNetworkReply*, QAuthenticator*), then fill the login credentials into the given QAuthenticator object.
However, this does not work in my case as that signal is never emitted. Reason: The server does not return an authorization failure but redirects me to a login page instead. So my program will just download that page.
I have found out how to catch this by checking the attribute QNetworkRequest::RedirectionTargetAttribute of the QNetworkReply.
So I can detect the redirection and ask the user for auth info.
But... where do I go from there? How do I set the authentication data? Can I manually set a QAuthenticator to my QNetworkRequest or my QNetworkAccessManager? I didn't find a way to do that anywhere, just via the above-mentioned signal/slot mechanism which does not work because it does not trigger.
Any help would be greatly appreciated!

A: From documentation,
http://qt-project.org/doc/qt-5/qauthenticator.html

QAuthenticator supports the following authentication methods:

*

*Basic

*NTLM version 2

*Digest-MD5

Since you are getting redirected to a login page, and you haven't indicated if any of the above authentication methods even works, I will assume that it does not because things like Basic authentication is sent on every request to the server. Login pages generally authenticate the client and use some sort of a cookie for future authentication. To do this,

*

*Detect login page

*Pass proper credentials to the server (based on what the form wants)

*In the QNetworkReply to the login page, look for cookies (Set-Cookie headers).

*Pass the relevant cookies back with your requests.

*If it works, you are no longer redirected to login page.

For information on cookies, you can get overview via Wikipedia, but for implementation, you need to look at the RFC 6265,
If this is incorrect, and you can use basic authentication, then that information is passed in the URL itself. Set username and password in your QUrl and if it works, you will not be redirected. http://qt-project.org/doc/qt-5/qurl.html#setPassword


text:
Q: How to get supportactionbar when my class extends ExpandableListActivity I have a class which extends ExpandableListActivity to display my data as explandable list view, now my app supporting older version till API 7 how to add ActionBar using getSupportActionBar() to this class...Please help me out
public class Facts extends ExpandableListActivity {

public void onCreate(Bundle savedInstanceState) {

    try{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.facts);

        SimpleExpandableListAdapter expListAdapter =
                new SimpleExpandableListAdapter(
                        this,
                        createGroupList(),              // Creating group List.
                        R.layout.facts_grouprow,                // Group item layout XML.
                        new String[] { "questions" },   // the key of group item.
                        new int[] { R.id.row_name },    // ID of each group item.-Data under the key goes into this TextView.
                        createChildList(),              // childData describes second-level entries.
                        R.layout.facts_childrow,                // Layout for sub-level entries(second level).
                        new String[] {"answers"},       // Keys in childData maps to display.
                        new int[] { R.id.grp_child}     // Data under the keys above go into these TextViews.
                        );
        setListAdapter(expListAdapter);     // setting the adapter in the list

    }catch(Exception e){
        System.out.println("Errrr +++ " + e.getMessage());
    }

}

now suggest me to how to achieve it.

A: Looking at the ExpandableListActivity source code, it seems like it would be easy to duplicate the same functionality in your own class and have it extend ActionBarActivity as its base class.

A: I would suggest you to use the ActionBarActivity. There you have the method getSupportActionBar.
To show your ExpandableList you can add a ListFragment from the support-v4 lib.
There is a method called setListAdapter() where you can add a ExpandableListAdapter.
Here is an example.


text:
Q: Linq to SQL: Why am I getting IDENTITY_INSERT errors? I'm using Linq to SQL. I have a DataContext against which I am .SubmitChanges()'ing. There is an error inserting the identity field:
Cannot insert explicit value for identity column in table 'Rigs' when IDENTITY_INSERT is set to OFF.
The only identity field is "ID", which has a value of 0. It's defined in the DBML as:
[Column(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]

There are a few foreign keys, and I've verified they have values that jive with the foreign tables' content.
Why would I be getting this error?
Edit: Here is the query:
exec sp_executesql N'INSERT INTO [dbo].[Rigs]([id], [Name], [RAM], [Usage], [MoreInfo], [datetime], [UID])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6)
SELECT [t0].[id], [t0].[OSID], [t0].[Monitors]
FROM [dbo].[Rigs] AS [t0]
WHERE [t0].[id] = @p7',N'@p0 int,@p1 varchar(1),@p2 int,@p3 varchar(1),@p4 varchar(1),@p5 datetime,@p6 int,@p7
int',@p0=0,@p1='1',@p2=NULL,@p3='4',@p4='5',@p5=''2009-03-11 20:09:15:700'',@p6=1,@p7=0

Clearly it is passing a zero, despite having never been assigned a value.
Edit: Adding Code:
Rig rig = new Rig();
int RigID;
try
{ // Confirmed these always contain a nonzero value or blank
    RigID = int.Parse(lbSystems.SelectedValue ?? hfRigID.Value);
    if (RigID > 0) rig = mo.utils.RigUtils.GetByID(RigID);
}
catch { }

rig.Name = Server.HtmlEncode(txtName.Text);
rig.OSID = int.Parse(ddlOS.SelectedValue);
rig.Monitors = int.Parse(txtMonitors.Text);
rig.Usage = Server.HtmlEncode(txtUsage.Text);
rig.MoreInfo = Server.HtmlEncode(txtMoreInfo.Text);
rig.RigsToVideoCards.Clear();
foreach (ListItem li in lbYourCards.Items)
{
    RigsToVideoCard r2vc = new RigsToVideoCard();
    r2vc.VCID = int.Parse(li.Value);
    rig.RigsToVideoCards.Add(r2vc);
}
rig.UID = c_UID > 0 ? c_UID : mo.utils.UserUtils.GetUserByToken(this.Master.LiveToken).ID;

if (!mo.utils.RigUtils.Save(rig))
    throw new ApplicationException("There was an error saving your Rig. I have been notified.");
hfRigID.Value = rig.id.ToString();

public static User GetUserByToken(string token)
{
    DataClassesDataContext dc = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["MultimonOnlineConnectionString"].ConnectionString);
return (from u in dc.Users
    where u.LiveToken == token
    select u).FirstOrDefault();
}

Also, I notice that when I UPDATE an existing rig (insertonsubmit), it doesn't update.  Profiler doesn't even show any queries being run.

A: Is your code setting the ID value explicitely to 0? (instead of leaving it untouched).
Update 1: As you posted on the updated version, linq2sql is clearly passing the value to the db. Here is one I haven't had any trouble with:
[Column(Storage="_CustomerID", AutoSync=AutoSync.Always, DbType="Int NOT NULL IDENTITY", IsDbGenerated=true)]
public int CustomerID

I just saw another one, and it has the same exact definition of the one you are using.
[Column(Storage="_TestID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int TestID

Update 2: Regarding updates, you are not supposed to do InsertOnSubmit for that. Just update the values and call .SubmitChanges (should be throwing an exception). On the insert it is really weird, as the property attributes you posted seems to be correct, so the Insert method linq2sql generates should be correct as well. I would try, re-adding the table on the designer again and verifying all the properties are correct.
Note that the generated insert method should look like (with a matchingRig_Insert):
private void InsertRig(Rig obj)
{
    System.Nullable<int> p1 = obj.Id;

this.Rig_Insert(/* bunch of values */, ref p1);
        obj.Id = p1.GetValueOrDefault();
    }

A: Ensure the property Auto Generated Value in your dbml for that column is set to true.  If not, LINQ will attempt to default the value based on the type.

A: My theory of what happened is as follows:

*

*You designed and created the DataBase

*You created the DB Context using LINQ TO SQL in visual Studio

*You forgot to set the auto-identity to your table

*You fixed that by going to your DataBase and setting the auto-identity

*But you forgot to recreate/update your LINQ TO SQL DB Context!!!
:D

A: If you are supplying the value of the IDENTITY column, you must add
SET IDENTITY_INSERT ON

before your SQL Statements, and
SET IDENTITY_INSERT OFF

after to turn it off.  That goes for ANY raw SQL.  If you used LINQ to create an object like:
var customer = new LinqContext.Customer;
customer.FirstName = "Bob";
customer.LastName = "Smith";

LinqContent.Customer.Add(customer);
LinqContext.SubmitChanges();

I believe that will work, forgive me if I have classes wrong.  You get the basic idea.
Edit: Oops.. Sorry, didn't read the entire question, I take it back, tired and fatigued from work...

A: seems like your ID is being assigned somewhere (even if just defaulting to 0) - would you care for posting some of your LINQ code?

A: I was having the exact same problem.
My solution was to manually make the identity INT column into a nullable INT? column in the DBML designer, not in the actual table of the DB of course. Also set the DbType to NULL instead of NOT NULL. Like so:
[Column(Storage="_TestID", AutoSync=AutoSync.OnInsert, DbType="Int NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int? TestID

This works with all DB operations. When inserting simply set the identity column to NULL rather than to 0.

A: my case, I forgot to update my dbml file after setting Id column to identity.


text:
Q: Redirect language permanently I need to delete Spanish language on a website and redirect all pages to the English version of the site. Preferrably redirect each page to the associated page in the English version (Pages are associated in the Joomla Menu).
mydomain.com/es/quienes needs to go ot mydomain.com/about
or
mydomain.com/es and mydomain.com/es/quienes need to go to: mydomain.com
Now I know I could redirect them one by one using Redirect 301 rules but is there an easier way using RewriteCond and RewriteRule
Thanks


text:
Q: Get an image to upload and display within a div Please review my Fiddle...
I have a file upload button, which works fine. You'll see it when you barely scroll down in the fiddle. The image uploads, but it uploads down at the bottom of the page, and I'm trying to get it to display within a div, immediately below the upload button.
HTML...
`<input type='file' onchange="readURL(this);" />

      (Image will display below)

`

JS...
`$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});`

A: You're using after which insert your image after the input tag and not the image.
To insert your image inside your div you need to have a selector on this div like an id:
<input type='file' onchange="readURL(this);" />

   (Image will display below)

And then do:
$('#whatever").html(img);

A: Change the src attribute of the image you already have within the div. The following code should do what you want.
`$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var reader = new FileReader();
        reader.onloadend = function() {
             $('#blah').attr('src', reader.result);
        }
        reader.readAsDataURL(file);        }
});`


text:
Q: How to remount a read-only folder as readWrite? Background:
I need to edit a file which is read only, and its parent folder is also read only. This file is located at a remote appliance. Through ssh I logged in to this as admin and I have the root access.
Command "ls -l" show the permissions of file as
"-rwxr-xr-x 1 admin root   952 Oct 30 02:01 file.sh"

and for folder
drwxr-xr-x 3 admin root

I am not as such familiar with Linux but I searched and found that these above lines mean that the admin is the owner and he/she has the read and write permission.
Someone suggested to remount the folder which contains this file.
Problem:
How will I remount it, I used
mount -o remount,rw /folde1/folder2/targetFolder
but It gave
mount: can't find /folde1/folder2/targetFolder in /etc/fstab or /etc/mtab
I looked at question How do I remount a filesystem as read/write?, but I did not understand the answer...
It said correct syntax is
sudo mount -o remount,rw /partition/identifier /mount/point

What should I give as  /partition/identifier and /mount/point? I.e. what is this /partition/identifier and /mount/point?

A: You don't need to remount anything. You must to change permissions. You can do it with this command:
sudo chmod 777 file.sh

This give all permisions to file, if you wish leave as read only for group and for rest of users you can do:
sudo chmod 644 file.sh

or
sudo chmod 755 file.sh

The first is for read-only, end the second for read and execute.

A: Problem is solved, I remounted folder by using "mount -o remount,rw /" and then edited the file, without changing any permissions, it worked.


text:
Q: Pepper not respoding to Dialog I am using Naoqi's dialogs and using multiple topics. I checked with
ALDialog.getAllLoadedTopics and ALDialog.getActivatedTopics

They both show that my topics are loaded and activated. But Pepper doesn't respond to most of the activated topics. When I enter the same text on the Dialog input on Choregraphe, pepper replies correctly but not using voice commands.

A: I guess the Speech Recognition is in a weird state ? this has happened to me before during development, and issuing a "nao restart" to reload naoqi does solve the issue.

A: For me mostly is happening when I switched between two languages in another package. To avoid add set language and speech recognition language to your target language. It should work.


text:
Q: Desestructuración en JavaScript Estoy trabajando en una RESTFULL API con node y postgresql, tengo unos problemas cuando recibo  la solicitud e intento desestructurar los parámetros en el cuerpo de la petición.
Tengo un archivo llamado main.js que contiene el siguiente código.
const express = require('express');
const morgan = require('morgan');
server = express();
const port = process.env.PORT || 3000;
server.listen(port);
server.use(morgan('dev'));
server.use(require('./rutas/router'));
server.use(express.urlencoded({extended: false}));
server.use(express.json());

const mensaje = `Servidor escuchando peticiones en el puerto ${port}`;
console.log(mensaje);

y tengo un archivo llamado router.js que maneja las rutas del servidor, el codigo es el siguiente:
const {Router} = require('express');
const router = Router();
const {Pool} = require('pg');

const pool = new Pool({
    host: 'myhost',
    user: 'myusr',
    password: 'mypasswd',
    database: 'mydb',
    port: '5432',
    connectionTimeoutMillis: 2000,
    idleTimeoutMillis: 30000,
    max: 20
});

router.get('/', function (req, res) {
    res.status(200).send('
Página principal
');
});

router.get('/productos', async(req, res) => {
    await pool.connect((err, client, release) => {
        if (err) {
            console.log('Error conectando el cliente.', err.stack);
            return res.status(400).send('Ocurrio un error en la conexión con la base de datos.');
        }
        client.query('SELECT * FROM producto', (err, result) => {
            release();
            if (err) {
                console.log('Error al ejecutar la consulta a la base de datos', err.stack);
                return res.status(400).send('Ocurrio un error al ejecutar la consulta con la base de datos');
            }
            console.log(result.rows);
            pool.end();
            return res.status(200).json(result.rows);
        });
    });
});

router.post('/productos', async(req, res) => {
    const {nombre, descripcion, precio} = req.body;
    await pool.connect((err, client, release) => {
        if (err) {
            console.log('Error conectando el cliente.', err.stack);
            return res.status(400).send('Ocurrio un error en la conexión con la base de datos');
        }
        client.query('INSERT INTO producto (nombre, descripcion, precio) VALUES($1, $2, $3)', [nombre, descripcion, precio], (err, result) => {
            release();
            if (err) {
                console.log('Error al ejecutar la consulta a la base de datos.', err.stack);
                return res.status(400).send('Ocurrio un error al ejecutar la consulta con la base de datos');
            }
            console.log(result.rows);
            pool.end();
            return status(200).json({respuesta: true, producto: {nombre: nombre, descripcion: descripcion, precio: precio}});
        });
    });
});

module.exports = router;

Mi problema está en la petición POST a la ruta /productos para almacenar la información de un producto, no puedo aplicar des estructuración en el req.body porque me toma la petición como undefined. En el main.js yo he utilizado las opciones para trabajar con urlconded y json para poder leer los datos del cuerpo de la petición pero aún así me arroja un error. He intentado de todo y no he podido dar con el problema, no quiero comenzar desde cero, aunque es un proyecto simple, porque quiero descubrir el problema y no rendirme.
Tengo entendido que existe la libreria body-parser, pero me dijeron que express trae esas funcionalidades, espero no estar equivocado, anteriormente he realizado una APIRESTFULL con los mismos métodos y me ha funcionado, pero está vez no puedo recibir el cuerpo de la solicitud.
Espero que alguien pueda ayudarme, soy nuevo trabajando con JavaScript.

A: Probaste hacerle un print al req para ver si esta llegando el payload?
Lo otro, coloca estas 2 líneas
server.use(express.urlencoded({extended: false}));
server.use(express.json());

antes del server.use(require('./rutas/router'))


text:
Q: How to make a folder's background more transparent in GNOME's Overview? In GNOME, is there anyway to make a (Overview) folder's background more transparent?
To be more clear, the red area in the following screenshot is where I want it to be more transparent:

A: Yes. You can use the Blur my Shell GNOME Shell extension.
You haven't said which Ubuntu version you use, so I will suppose that you use Ubuntu 22.04 and later. In that case, follow these steps:

*

*Install the Extension Manager by opening a terminal and running:
sudo apt isntall gnome-shell-extension-manager

*Then open Extension Manager, click on the Browse tab, search for "blur my shell" and click Install:

*After installing the extension, go to the Installed tab, look for Blur my Shell, and click the cog icon:

*After clicking the cog icon, the extension's menu will open. Click on the Overview tab on the bottom of the window, enable Application folder blur if it isn't already enabled, and select Transparent in the Application folder dialogs style, as shown in the image below:

That's it! Your application folders should now be transparent and blurred and you will also have blurred overview. The extension offers many more settings which you can adjust to your liking.


text:
Q: Set Map options after construction? I want to be able to set and change Openlayers.Map options after construction, but my results are not expected. Can anyone point out problems with my approach or suggest better way if possible?
http://dev.openlayers.org/docs/files/OpenLayers/Map-js.html#OpenLayers.Map.OpenLayers.Map
var map = new OpenLayers.Map('map');
map.options = {
                projection: 'EPSG:3112',
                displayProjection: 'EPSG:4326',
                units: 'm',
                maxExtent: new OpenLayers.Bounds(-3237313.46,-5312745.84,3019649.82,-876762.78),
                resolutions: [12288,6144,3072,1536,768,384]
                };

A: Never mind:
http://dev.openlayers.org/docs/files/OpenLayers/Map-js.html#OpenLayers.Map.setOptions
    map.setOptions({
        projection: 'EPSG:3112',
        displayProjection: 'EPSG:4326',
        units: 'm',
        maxExtent: new OpenLayers.Bounds(-3237313.46,-5312745.84,3019649.82,-876762.78),
        resolutions: [12288,6144,3072,1536,768,384]
        });


text:
Q: PHP foreach create menu from array I am currently creating a joomla component, and i am currently stuck with the menu part.
this is in my model file:
public function getMenu(){
    $menu_id = JRequest::getInt('id');

    $db = $this->getDbo();
    $query = $db->getQuery(true);

    $query->select('t.country_name,t.country_code, a.continent_name');
    $query->from('#__vectormap_countries AS t')
            ->join('LEFT', '#__vectormap_continents AS a USING(continent_id)')
            ->where('t.published = 1');

    $db->setQuery($query);

    $menu_items = $db->loadObjectList();

    return $menu_items;
}

and on the front end i have:
<?php  $menus = $this->menu ?>
<?php foreach($menus as $menu): ?>

<?php echo $menu->continent_name ?>

    <li id="<?php echo $menu->country_code ?>"><?php echo $menu->country_name ?>

<?php endforeach; ?>

and that returns:
Africa
South Africa
Africa
Mozambique
or if i print out the array this:
Array ( [0] => stdClass Object ( [country_name] => South Africa [country_code] => ZA [continent_name] => Africa ) [1] => stdClass Object ( [country_name] => Mozambique [country_code] => MZ [continent_name] => Africa ) ) 1

Now Finally the question, how would i sort it so that Africa (continent_name) not be repeated but rather have all the countries that have the continent_name of Africa list underneath it?
Keep in mind North America and such will also come in to play..
Summarized question -> How would I sort countries underneath there associated continents fond in the array.
Any Help Greatly Appreciated thanks.
how would i sort it that everything

A: The easy fix is by ORDERing your query results and then add some logic in your foreach loop
$query->order('a.continent_name ASC, t.country_name ASC');

In your foreach loop remember what the previous continent was
<?php
  $lastcontinent = "";
  foreach($menus as $k => $menu):
    if($lastcontinent != $menu->continent_name){
      if($k > 0){ // if this isn't the first continent
        // closing tags for the previous continent
        echo '

';
      }
      echo '
'.$menu->continent_name.'

';
    }
    $lastcontinent = $menu->continent_name;
    echo '
country_code.'">'.$menu->country_name.'
';
  endforeach;
?>

A: Use a foreach loop and make a new array and create continent_name as a key. Then you won't have a repetitive names.


text:
Q: How to make white color background color of  component in solid-js? I created a solid-js application that I designed in tailwindcss. I defined in the index.css file of my application a gray color which will have to be used as background color for the various screens of my application. However, I would like the base <App/> component to have a white background color unlike other components. So I wrote an App.css file which I imported into the App.jsx file and where I wrote the following code:
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  body::-webkit-scrollbar {
    @apply w-3;
  }

  body::-webkit-scrollbar-thumb {
    @apply bg-white rounded-full;
  }
}

But when I load my page, I see that the background color of the <App/> component is still gray, so I wrote the following code in my App.jsx file:
function App() {

  return (

    <Suspense fallback={<WhelpsLoader />}>
        ...

  );
}

but that didn't load anything to the background color of the component, so I modified my App.css file like so:
.App {
    background-color: #ffff;
  }

but it didn't load anything and I don't understand why because in my opinion the css code written for the <App/> component should have priority over the css code contained in the index.css file.
I also edited my App.jsx file like this:
import "./App.css";

   ...
document.querySelector('.App').style.backgroundColor = "#fff";

function App() {

  useNetworkStatus();
  return (

    <Suspense fallback={<WhelpsLoader />}>
      <AppRouter />
      <Snackbars />
    </Suspense>

  );
}

export default App;

A: Use this in your .jsx file.

document.querySelector('.App').style.backgroundColor = "#fff";

// or for entire

document.body.style.backgroundColor = "#e1e1e1";

A: You don't need the imperative API, use the style attribute on the element:
import { render } from "solid-js/web";

function App() {
  return
My Application
;
}

render(App, document.getElementById("app")!);


text:
Q: String value from mongoose document weird behaviour adding in a variable I have a mongo document called New which has a sub document called hashtags which has th value name which is a string. I am trying to add all the hashtags belongs to a new in a variable but is adding extra characters (seems that the name string value is not well decoded from the bson or something like that).
New document:
var newSchema = new Schema({
    ...
    hashtags: [{
        type : mongoose.Schema.ObjectId,
        ref: 'Hashtag'
    }]
});

Hashtag document:
    var mongoose = require('mongoose')
    var Schema = mongoose.Schema

    var hashtagSchema = new Schema({
        color:  {
            type: String,
            default: '#000000'
        },
        name:  {
            type: String
        }
    });
    var hashtag = mongoose.model('Hashtag', hashtagSchema )

    module.exports = hashtag

Snniped testing code:
    docs.forEach(noticia => {
        if(noticia.hashtags.length > 0){
            for(i in noticia.hashtags){
                if(noticia.hashtags[i] && noticia.hashtags[i].name){
                    text +=  '#' + noticia.hashtags[i].name.replace(/\s/g,'') + ' '
                }
            }
        }
    })
console.log(text)

Console output:
#Lula #toBSON #_cast #_markModified #_registerAtomic #$__getAtomics #hasAtomics #_mapCast #push #nonAtomicPush #$pop #pop #$shift #shift #pull #splice #unshift #sort #addToSet #set #toObject #inspect #indexOf #pull
I have tried to apply noticia.hashtags[i].name.replace(/\s/g,'').toString() :
    docs.forEach(noticia => {
        if(noticia.hashtags.length > 0){
            for(i in noticia.hashtags){
                if(noticia.hashtags[i] && noticia.hashtags[i].name){
                    text +=  noticia.hashtags[i].name.toString() + ' '
                }
            }
        }
    })

Console output
LulatoBSON_cast_markModified_registerAtomic$__getAtomicshasAtomics_mapCastpushnonAtomicPush$poppop$shiftshiftpullspliceunshiftsortaddToSetsettoObjectinspectindexOfpull
How I have to decode this string value?

A:
The for...in statement iterates over all non-Symbol, enumerable properties of an object.

var string1 = "";
var object1 = {a: 1, b: 2, c: 3};

for (var property1 in object1) {
  string1 += object1[property1];
}

console.log(string1);
// expected output: "123"

You are iterating over the properties of noticia.hashtags


text:
Q: MFMailComposeViewController crashing while dismissModalViewControllerAnimated in iOS5 I am using MFMailComposeViewController in my conde to provide Mail functionality but after sending mail or when i want to cancel mail it will be crashing.
below is my code:
(IBAction)FnForPlutoSupportEmailButtonPressed:(id)sender {
{
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];

        mailer.mailComposeDelegate = self;

        [mailer setSubject:@"Need help from Pluto support team"];

        NSArray *toRecipients = [NSArray arrayWithObjects:@"support@myplu.to",nil];
        [mailer setToRecipients:toRecipients];

        NSString *emailBody = @"";

        [mailer setMessageBody:emailBody isHTML:NO];

        //mailer.modalPresentationStyle = UIModalPresentationPageSheet;

        [self presentModalViewController:mailer animated:YES];

    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];
    }
} }

    (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
// Notifies users about errors associated with the interface
switch (result)
    {       case MFMailComposeResultCancelled:
                        break;
                    case MFMailComposeResultSaved:
                        break;
                    case MFMailComposeResultSent:
                        break;
                    case MFMailComposeResultFailed:
                        break;
                    default:
                        break;
    }
    [self dismissModalViewControllerAnimated:YES];
     }

I have read all blog post but no solution is found, This blog post is having good explaination about this but as per this i am not presenting my view controller in viewdidload or viewdidappear.
I'm Getting EXE_BAD_ACCESS, Following is the crash log :
**
> #0  0x00000000 in ?? ()
> #1  0x01dc5aa4 in -[UIViewController _setViewAppearState:isAnimating:] ()
> #2  0x01dc5f47 in -[UIViewController __viewDidDisappear:] ()
> #3  0x01dc6039 in -[UIViewController _endAppearanceTransition:] ()
> #4  0x01dd2e7e in -[UIViewController(UIContainerViewControllerProtectedMethods) endAppearanceTransition] ()
> #5  0x01fc8de1 in -[UIWindowController transitionViewDidComplete:fromView:toView:] ()
> #6  0x01da334b in -[UITransitionView notifyDidCompleteTransition:] ()
> #7  0x01da3070 in -[UITransitionView _didCompleteTransition:] ()
> #8  0x01da531b in -[UITransitionView _transitionDidStop:finished:] ()
> #9  0x01d23fb6 in -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] ()
> #10 0x01d24154 in -[UIViewAnimationState animationDidStop:finished:] ()
> #11 0x0163bbce in CA::Layer::run_animation_callbacks ()
> #12 0x03664fe4 in _dispatch_client_callout ()
> #13 0x03655997 in _dispatch_main_queue_callback_4CF ()
> #14 0x012c03b5 in __CFRunLoopRun ()
> #15 0x012bf804 in CFRunLoopRunSpecific ()
> #16 0x012bf6db in CFRunLoopRunInMode ()
> #17 0x030f1913 in GSEventRunModal ()
> #18 0x030f1798 in GSEventRun ()
> #19 0x01ce82c1 in UIApplicationMain ()

**
As per updated document of apple for ios 5 they mentioned :
presentModalViewController:animated:
Presents a modal view managed by the given view controller to the user. (Deprecated. Use presentViewController:animated:completion: instead.)
- (void)presentModalViewController:(UIViewController *)modalViewController animated:(BOOL)animated
Parameters

Dismisses the view controller that was presented by the receiver. (Deprecated. Use dismissViewControllerAnimated:completion: instead.)
- (void)dismissModalViewControllerAnimated:(BOOL)animated

I had tried this also but it still crashes

A: You need to keep a strong reference to MFMailComposeViewController *mailer in your class, and after you dismiss it you can null that reference. Ask me how I know this :-)
@implememtation MyClass
{
    MFMailComposeViewController *mailer;
}
...

(IBAction)FnForPlutoSupportEmailButtonPressed:(id)sender {
{
    if ([MFMailComposeViewController canSendMail])
    {
        /* USE IVAR */mailer = [[MFMailComposeViewController alloc] init];

Later on, when completely done with it, you simply "mailer = nil;" to release it.
EDIT: What I do and suggest is to use a block to the main queue to do the release. If you just use 'self.mailer = nil' then the release happens after the final delegate method has finished and you are for sure no longer using it.
EDIT2: This crash does not happen all the time on all devices - I would say its somewhat of a race condition between when you receive the final delegate method and when its finished its work. Apple does not say anything about holding a reference one way or the other - however, general practice on Apple products is to assume any object you get is "on loan" through one runLoop, and thereafter if you want to keep a reference you have to retain the object.

A: If your are having sharekit framework implemented in your code goto SHK.m and change
        [[currentView parentViewController] dismissModalViewControllerAnimated:YES];

to
        [currentView  dismissModalViewControllerAnimated:YES];

This will solve your problem.
Thanks everyone for response.
and also comment these lines
SHKSwizzle([MFMailComposeViewController class], @selector(viewDidDisappear:), @selector(SHKviewDidDisappear:));
if (NSClassFromString(@"MFMessageComposeViewController") != nil) SHKSwizzle([MFMessageComposeViewController class], @selector(viewDidDisappear:), @selector(SHKviewDidDisappear:));

A: HI you can use following code to send mail mail app will not send any email form simulator you have to install you application on device. EXE_BAD_ACCESS comes when you try to access the object they are not in memory and remamber device is case sensitive.
-(void)sendMail:(id)sender
{
    //create instance of class at runtime.
    Class mailComposer = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass != nil)
{
        // check the current device is configured for sending emails
        //if it is not configured for mail you open mail application on device.
    if ([mailClass canSendMail])
    {
        [self displayComposerSheet];
    }
    else
    {
        [self launchMailAppOnDevice];
    }
}
else
{
    [self launchMailAppOnDevice];
}

}
-(void)displayComposerSheet
 {
MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"Welcome!"];

    //recipients

NSArray *to = [NSArray arrayWithObject:@"jhon@example.com"];

[picker setToRecipients:toRecipients];

    // Attach an image
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png"];
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
[picker addAttachmentData:myData mimeType:@"image/png" fileName:@"Default"];

    // Set email body text
    //NSString *emailBody = @"......!";
    //[picker setMessageBody:emailBody isHTML:NO];

[self presentModalViewController:picker animated:YES];
[picker release];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:   (MFMailComposeResult)result error:(NSError*)error
{
message.hidden = NO;
    // Notifies users about errors associated with the interface
switch (result)
{

    case MFMailComposeResultCancelled:
        message.text = @"Canceled";
        break;
    case MFMailComposeResultSaved:
        message.text = @"Saved";
        break;
    case MFMailComposeResultSent:
        message.text = @"Sent";
        break;
    case MFMailComposeResultFailed:
        message.text = @"Failed";
        break;
    default:
        message.text = @"Not sent";
        break;
}
[self dismissModalViewControllerAnimated:YES];
}

-(void)launchMailAppOnDevice
{
NSString *recipients = @"";
NSString *body = @"";

NSString *email1 = [NSString stringWithFormat:@"%@%@", recipients, body];
email1 = [email1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email1]];
}

A: Since the stop of the stack is 0x00000000, I'm assuming some code inside UIKit is jumping to a nil function pointer. Enable Zombies and see if you get a zombie object access error. (Edit your project scheme, under Run/Debug, Diagnostics tab, check "Enable Zombie Objects")

A: try this code, this works well without crashing.. contact us method is button target selector..
    -(void)ContactUs:(UIButton*)button
    {
        Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
        if (mailClass != nil)
        {
            // We must always check whether the current device is configured for sending emails
            if ([mailClass canSendMail])
            {
                [self displayComposerSheet];
            }
            else
            {
                [self launchMailAppOnDevice];
            }
        }
        else
        {
            [self launchMailAppOnDevice];
        }

    }

-(void)displayComposerSheet
{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;

    //[picker setSubject:@"Hello from California!"];

    // Set up recipients

    NSArray *toRecipients = [NSArray arrayWithObject:@"info@imp.co.in"];
    //NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
    //NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"];

    [picker setToRecipients:toRecipients];
    //[picker setCcRecipients:ccRecipients];
    //[picker setBccRecipients:bccRecipients];

    // Attach an image to the email
    /*NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"png"];
     NSData *myData = [NSData dataWithContentsOfFile:path];
     [picker addAttachmentData:myData mimeType:@"image/png" fileName:@"rainy"];*/

    // Fill out the email body text
    //NSString *emailBody = @"It is raining in sunny California!";
    //[picker setMessageBody:emailBody isHTML:NO];

    [self presentModalViewController:picker animated:YES];
    [picker release];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    message.hidden = NO;
    // Notifies users about errors associated with the interface
    switch (result)
    {

        case MFMailComposeResultCancelled:
            message.text = @"Canceled";
            break;
        case MFMailComposeResultSaved:
            message.text = @"Saved";
            break;
        case MFMailComposeResultSent:
            message.text = @"Sent";
            break;
        case MFMailComposeResultFailed:
            message.text = @"Failed";
            break;
        default:
            message.text = @"Not sent";
            break;
    }
    [self dismissModalViewControllerAnimated:YES];
}

-(void)launchMailAppOnDevice
{
    NSString *recipients = @"";
    NSString *body = @"";

    NSString *email1 = [NSString stringWithFormat:@"%@%@", recipients, body];
    email1 = [email1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email1]];
}

A: If you are using ARC, the controller object will have been released before you call dismiss.
Retain the object somewhere besides a stack allocated variable.

A: Have you set delegate MFMailComposeViewControllerDelegate in .h file. I have faced such problem in past. And error was very minor. Please check delegate in .h file.


text:
Q: csplit produces too few output files, expecting more I have a file that contains several lines like these:
1291126929200 started 88 videolist15.txt 4 Good 4
1291126929250 59.875 29.0 29.580243595150186 43.016096916037604
1291126929296 59.921 29.0 29.52749417740926 42.78632483544682
1291126929359 59.984 29.0 29.479540161281143 42.56031951027556
1291126929437 60.046 50.0 31.345036510255586 42.682281485516945
1291126932859 started 88 videolist15.txt 5 Good 4

I want to split the files for every line that contains started (or videolist, does not matter).
The following command only produces 2 output files:
$ csplit -k input.txt /started/

However I expect a lot more, as can be seen in:
$ grep -i started input.txt |wc -l
$ 146

What would be the correct csplit command?

A: According to the Open Group specifications the csplit command accepts basic regular expressions.
Basic REGEXPs are a limited subset of full regex implementations. They support literal characters, asterisk (*), dot (.), character classes ([0-9]) and anchors (^,$). They don't support one-or-more (+) or alternation (a|b).

A: Add {*} at the end:
$ csplit -k input.txt /started/ {*}

The man page says:
{*}    repeat the previous pattern as many times as possible.

Note that some shells may interpret this as a special pattern. In that case, quote it with "{*}".
Also, make sure you use the GNU version of csplit, which is available under macOS with brew install coreutils.
Demo:
$ cat file
1
foo
2
foo
3
foo
$ csplit -k file /foo/ {*}
2
6
6
4
$ ls -tr xx*
xx03  xx02  xx01  xx00
$ csplit --version
csplit (GNU coreutils) 7.4


text:
Q: Does Meteor or Iron Router interfere with jQuery events on anchor tags? I am using a third-party theme that uses an anchor tag to toggle the visibility of a left menu on click. Everything was working fine until around the time that I started segmenting my HTML into partials and installed Iron Router. Am I probably just overlooking a bug somewhere, or does Meteor/IronRouter require that I do something specific to handle all jQuery events on anchor tags? Do I need to change all jQuery events to be aware of page updates (via on())? This particular element does not have an href= attribute and I do not expect the URL to change.

A: Iron Router intercepts click events on links so that it can handle them itself. This can certainly break the functionality of your plugin. If your theme allows to handle the change by another element, that's the perfect solution. Things like toggling menu visibility could be managed by clicking on buttons or even divs.
If changing the toggle element is not possible, you need to tell Iron Router not to intercept that particular anchor. See this question for details.

A: The key phrase here turned out to be "segmenting my HTML into partials", as my problem is not related to Iron Router. Once you start placing HTML into templates, you cannot rely on the jQuery that is written into the theme to be aware of page updates that are the very essence of Meteor. For example, my theme contains the following code:
$('.menutoggle').click(function(){
    // do things
});

This must in fact be changed to use the on() function:
$(document).on('click', '.menutoggle', function() {
    // do things
});

Or perhaps better yet, registered with my template:
Template.mypartialname.events({
   'click .menutoggle': function() {
        // do things
   }
});


text: Q: How to execute mysql query without changing the position on page My php pages are long and dynamic. So when user is at very bottom of the page, i want to execute query without changing the current position of the user at page. I have been trying to use jquery but that too is reloading page. How can i do that. Its preferable to execute query on anchor.


text:
Q: Find the object in the $scope that have a key starting with a certain string? I have a list of text field like this

<input type="text" name="option1" ng-model="option1" />

<input type="text" name="option2" ng-model="option2" />

I'd like to find all of the option* that are in the  $scope
Thank you in advance for the answer

A: I would make an array which will hold the input data and then add a loop to iterate over this array in html. You will then not need to search in scope for specific objects, you will have the array ready.
$scope.allOptions = [
    {name: 'option1', text: ''},
    {name: 'option2', text: ''}
];

And then:

<input type="text" name="{{option.name}}" ng-model="option.text" />

The problems is that I don't know the number of the text fields in the list. The application has by default two list but there is also a button that permit the user to add new options programmatically. So with Jquery i add in every text field a progressive number in the ng-model. The first ng-model=option1, the second option2, ...

I recommend to use angular then (to add another input).
$scope.addInput = function(){
    var n = $scope.allOptions.length;
    $scope.allOptions.push({name: 'option'+(n+1), text: ''});
};

<button ng-click="addInput()">Awesomeness is here</button>

A: There's a few ways to do this.
See this working jsFiddle
The first method I'm showing you would be the natural next step to the way you've done it, and would allow you to access the values as you request.
First, bind your inputs to an array, like so:

<input type="text" name="option[1]" ng-model="option[0]" />

<input type="text" name="option[2]" ng-model="option[1]" />

<input type="text" name="option[3]" ng-model="option[2]" />

Don't forget to declare your variable as an array in the controller:
$scope.option = [];

Then, in your controller, you can access them via $scope.option.
A more advanced, and simpler / easier to maintain method might be to useng-repeat, which is very powerful.  ng-repeat documentation
To use ng-repeat:
First, set up the array of objects in your controller, like so:
$scope.rOptions = [
   {name: 'option1', val: ''},
   {name: 'option2', val: ''},
   {name: 'monkey', val: ''}
];

Then, you can output the HTML with a simplified set of markup:

<input name="{{rOption.name}}" ng-model="rOption.val">

And, in your controller, you can access the values via $scope.rOption.
You can check out the fiddle above to see how these two work, and how the data can be accessed.


text:
Q: Designing the schema for a database of Spanish language words? For a project I'm working on that will help people learn Spanish, I would like to create a standalone service to handle the retrieval of data about words.  For this, I've captured and codified data for a few thousand words from Wiktionary.  Currently, this is in JSON format, but I intend to put it into a PostgreSQL db.  I am looking for advice in developing the schema of the database.
Every word has certain properties, which I have captured from Wiktionary:

*

*string

*part of speech

*meaning

*lemma (sort of like the "plain" version of the word)

Additionally, there are some properties that are unique to certain parts of speech. Specifically, verbs have a person, mood, and tense and adjectives and nouns have a gender and number.
Example: hacía

*

*string: hacía

*part of speech: verb

*meaning: to do

*lemma: hacer

*person: 1st

*mood: indicative

*tense: imperfect
I intend for the API of the service to be able to the following:

*

*Given a particular string and part of speech, return all the possible words that match it. Example: hacía, verb => imperfect indicative first person of hacer and imperfect indicative third person of hacer, along with the properties of each of those two words

*Given the unique identifier for a word, return every possible form of the word.  Example: unique id of hacía => every possible form of hacer, along with their properties.

*Given the unique identifier for a word and a list of properties, return the form of that word that meets those properties.  Example: unique id of hacía, indicative, present, first person => hago
My question:
With these intended uses and the underlying data in mind, how would you suggest I organize the db?  What other considerations are relevant, if any?
More specifically, should this database consist of a single table, with all of the properties listed below in it?  Or, alternatively, should it be two tables: a table with all of the words and a separate table with all of the lemmas, to which this table is linked?  Or, is there a third alternative I have not thought of?

A: Analysing your statements:

*

*There is a common part of properties to all the words

*In this common part, the part of speech acts like a type :  the word may have additional properties depending on the value of part of speech  -> additional properties in the same table (that may be used or not) ? or additional

*There is a unique id for each different word (string), regardless of its form

Now the brainstorming about potential inductions:

*

*(1) requires at least one Word table with all the basic properties

*(2) requires a place for additional properties:

*

*possibility (2.a): put additional properties in  the Word table, but leave them empty when they are not needed ("single inheritance" model).

*possibility (2.b): put additional properties in a separate table, with one table for each part of speech ("class table inheritance" or "concrete table inheritance" in case several parts of speech could form a hierarchy)

*possibility (2.c): put each property into a entity-attribute-value table

*possibility (2.d): create a separate table for each additional property

*Variants of (2) suggest that part of speech defines specialisations of word.  So it could be analyzed further if the different part of speech are a flat structure, or form a hierarchy

*The fact that part of speech defines specialisation with their own property raises the question if other core properties of word also could require additional properties.  But at first sight, no...

*(3) suggest that the unique id could be used to join the different tables

*(3) means that the same word could have duplicate entries in Words, each with a different meaning.  => does the different meaning affect other properties ?

*(3) means that the same word could have duplicate entries in Words, each with a different part of speech.  => does this mean that Words should be split into its lexical part (i.e. unique id and string) and its grammatical and semantic part ?

These are inductions:  just ideas that pop up based on the initial findings.  The next step would be to evaluate these to see if they are valid,  how they could be solved, and pros and cons
Then you could design.  For me, intuitively, I'd quickly restrict my choice to a class inheritance table (Lexical forms with id and string; Grammatical form with part of speech and remaining core properties; additional tables for the different part of speech) and to an Entity-field-value approach (more flexible, but more expensive).  Up to you to cross check how both approaches could satisfy your different query requirements.


text:
Q: Use different env configs per environment | Angular Typescript In Angular, I want to use different env configs per environment.
That means, if I for example deploy to the dev Enviroment, I want the Angular App to use the Dev Variables, and if I deploy to Prod I want Angular to use the prod Variables.
Is there a way to do that? For Example create a file with all the variables and then Angular just has to look in which environmnent it is in and choose the right variable.

A: just create a new typescript file  in project root directory, same directory where pacakage.json file exist,
lets say you make a file with name set-env.ts
put this code into the file
import { writeFile } from 'fs';
// Configure Angular `environment.ts` file path
const targetPath = './src/environments/environment.ts';
const targetPathProd = './src/environments/environment.prod.ts';
const envConfigFile = `export const environment = {
   production: false,
   serverURL: 'https://devenviroment.com/api',
   someOtherProperty: 'response'
};
`;
const envProdConfigFile = `export const environment = {
   production: true,
   serverURL: 'https://serverurlproduction.com/api',
   someOtherProperty: 'value'
};
`;
console.log('The file `environment.ts` will be written with the following content: \n');
console.log(envConfigFile);
writeFile(targetPath, envConfigFile, function (err) {
  if (err) {
    throw console.error(err);
  } else {
    console.log(`Angular environment.ts file generated correctly at ${targetPath} \n`);
  }
});
writeFile(targetPathProd, envProdConfigFile, function (err) {
  if (err) {
    throw console.error(err);
  } else {
    console.log(`Angular environment.prod.ts file generated correctly at ${targetPath} \n`);
  }
});

Now add this line to package.json file inside scripts tag
"config-env": "ts-node set-env.ts",
"build": "ng build"

Now when you are building your project you can simply use this command
npm run config-env & npm run build

npm run config-env command will overwrite your environment files with configurations that you have written in set-env.ts

A: Jignesh Patel, from TheCodeHub, writes it so well -
https://www.thecodehubs.com/how-to-configure-multiple-environments-in-angular/
How to use environment variables in code

src/environments/environments.ts
export const environment = {
  production: false,
  apiUrl: '/website-backend'
};

...component.ts
import { environment } from 'src/environments/environment';

export class CalculatorConfigServiceService {
    apiUrl = `${environment.apiUrl}/calculator`

...
}


text:
Q: Apply Indicator Function to List Is there an easy way to apply an indicator function to a list? i.e. I have a list with some numbers in it and I would like to return another list of the same size with, for example, ones where the positive numbers were in the original list and zeros where the negative numbers were in the original list.

A: List comprehensions!
bysign = [int(x >= 0) for x in somelist]

Here's a demo.

A: Just use a list comprehension:
>>> orig = [-3, 2, 5, -6, 8, -2]
>>> indic = [1 if x>0 else 0 for x in orig]
>>> indic
[0, 1, 1, 0, 1, 0]

A: To produce the results of your example, I probably would have done
cmp_list=map(cmp, your_list)
one_zero_list=[]
for item in cmp_list:
    if item < 0:
        one_zero_list.append(0)
    elif item==0:
        one_zero_list.append(0) #you didnt actually say what to do with 0
    else:
        one_zero_list.append(1)


text:
Q: Display Emoji character in JTable I want to display loudspeaker character in a JTable:
    @Override
    public Object getValueAt(int row, int col)
    {
        switch (col) {
            [...]
            case 2:
                String symbol = "\uD83D\uDD0A";
                return "State " + symbol;
            default:
                return "";
        }
    }

Unfortunaly i just see an square box. I'm not sure if i have to set an specific Font supporting this character or to apply an other encoding.
For Googlers looking for a solution:
I implemented a CustomRenderer for the JTable like @trashgod sugested. Examples are available here or here.

A: Yes, you'll need two things:

*

*A font containing the required glyph, loaded as shown here.

*A TableCellRenderer in which to use the font, as shown here.
Alternatively, consider a TableCellRenderer that implements the Icon interface, as shown here. The graphics context's fill(Polygon) and drawArc() methods should produce a satisfactory result.


text:
Q: Asp LinkButton doesn't work on press I want to change language with LinkButton in my project
 <asp:LinkButton ID="LinkButton1" runat="server"
PostBackUrl="~/mypage.aspx?lang=en">english</asp:LinkButton>

<asp:LinkButton ID="LinkButton2" runat="server"
PostBackUrl="~/mypage.aspx?lang=ru">русский</asp:LinkButton>

For this page I created local resources
mypage.aspx.resx
mypage.aspx.ru.resx
when I press this linkbutton nothing happens

A: try to add this code to your Page_Load event (it will be more effective if you use a base class for your pages, and put this code into that base page, so that all pages in the application will be able to switch language)
if(Request.QueryString["lang"] == "en")
{
    var english = new CultureInfo("en");
    System.Threading.Thread.CurrentThread.CurrentCulture = english;
    System.Threading.Thread.CurrentThread.CurrentUICulture = english;
}
else if(Request.QueryString["lang"] == "ru")
{
    var russian = new CultureInfo("ru");
    System.Threading.Thread.CurrentThread.CurrentCulture = russian;
    System.Threading.Thread.CurrentThread.CurrentUICulture = russian;
}

Be aware that also date formats as well as number (and currency) formats will change accordingly, if you don't force the format.


text:
Q: MiniProfiler Doesn't work I just created a new MVC 4 Basic project and added the package to the project and the needed code to the layout but nothing happened after first run.
This is the Layout:
@using StackExchange.Profiling;
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @MiniProfiler.RenderIncludes()
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

Update
I've added this code to the global.asax.cs
protected void Application_BeginRequest()
{

    MiniProfiler.Start();

}

now this code appears in the HTML code:
<script async type="text/javascript" id="mini-profiler" src="/mini-profiler-resources/includes.js?v=xwYPDDH1blvqmxgsBweNC++H7CFU3KGQ+zFcVlJPsXw=" data-version="xwYPDDH1blvqmxgsBweNC++H7CFU3KGQ+zFcVlJPsXw=" data-path="/mini-profiler-resources/" data-current-id="6da0f73c-fa89-447b-92b1-56dc532947f4" data-ids="6da0f73c-fa89-447b-92b1-56dc532947f4" data-position="left" data-trivial="false" data-children="false" data-max-traces="15" data-controls="false" data-authorized="true" data-toggle-shortcut="Alt+P" data-start-hidden="false"></script>

but the /mini-profiler-resources/includes.js?v=xwYPDDH1blvqmxgsBweNC++H7CFU3KGQ+zFcVlJPsXw= url returns a 404 error.

A: Thanks to spaceman the problem solved!
the problem was from the 404 error solved by adding this code to web.config
<system.webServer>
    <handlers>
        <add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />

A: have you added the initialise code to the global.asax file?
you need to hook into the application_beginrequest and application_endrequest methods also.
http://www.codeproject.com/Articles/516627/MiniProfilerplus-plusInstallationplusandplusSetup


text:
Q: Dynamically set the columnwidth in gridlayoutmanager I am trying to do this using recycler view with gridlayoutmanager. GridLayoutmanager takes spancount. Here I want to update the view based on the width of the text in the recycler view items.

A: It's a late answer but I wanted to achieve exactly the same stuff!
Then after several hours of research, I found this lib (I don't know why I didn't find it earlier...) by Google: FlexboxLayout who has a FlexboxLayoutManager!
How to use:
val layoutManager = FlexboxLayoutManager(context)
layoutManager.flexDirection = FlexDirection.ROW
myRecyclerView.layoutManager = layoutManager

That's all!


text:
Q: Picker does not select patch object in matplotlib in embedded pyside dialog I do have a problem with embedded matplotlib in PySide. When I try to
select an object on the window it looks that I can only select the
subplot because I do get the error
AttributeError: 'AxesSubplot' object has no attribute 'get_xdata'

When I try to capture the instance of a Line2D class on the canvas in the line
if isinstance(event.artist, Line2D)

I only can capture the AxesSubplot object, not the Line2D (nor the rectangle,nor the text)
Appreciate any assistance,
Richard
class navDialog(QtGui.QDialog, Ui_mplDialog):
    def __init__(self, parent=None):
        super(navDialog, self).__init__(parent)
        # Basic preparation for an embedded matplotlib
        self.setupUi(self)
        fig = Figure(figsize=(600,600), dpi=72, facecolor=(1,1,1),edgecolor=(1,1,1))
        #fig.set_picker(picker)

        self.canvas = FigureCanvas(fig)
        self.verticalLayout.addWidget(self.canvas)

        ax = fig.add_subplot(111, xlim=(0, 10), ylim=(0, 10),axisbg='0.3', picker = True)
        ax.set_title('Click on the points', picker=True)
        fig.set_frameon(False)
        #fig.set_alpha(self, alpha)

        self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                  QtGui.QSizePolicy.Expanding)
        self.canvas.updateGeometry()

        self.navigation_toolbar = NavigationToolbar(self.canvas, self)
        self.verticalLayout.addWidget(self.navigation_toolbar, 0)

        #self.canvas.mpl_connect('button_press_event', self.on_pick)
        self.canvas.mpl_connect('pick_event', self.on_pick)

        # Specific content
        from matplotlib.collections import PatchCollection
        from matplotlib.projections.polar import PolarAxes
        import matplotlib.path as mpath
        import matplotlib.patches as mpatches
        import matplotlib.lines as mlines

        fig = plt.figure(figsize=(5,5))
        ax = plt.axes([0,0,1,1])
        patches = []

        # add entities on a circle
        es = session.query(Entity).all()
        vpuInFocus =session.query(Entity).filter(Entity.entity_in_focus == True) \
                                        .filter(Entity.entity_class_id== 1).one()
        esQty = len(es) - 1
        center = [5,5]

        theta = 2*3.14 / esQty
        arc = 0
        rad = 3
        pos = []
        # Entity in focus
        ePatch = mpatches.Circle(center, 0.3, ec='r', color='0.7',picker=True)
        patches.append(ePatch)
        ax.text(center[0], center[1], vpuInFocus.name, ha="center",family=font, size=14)

        for e in es:
            if e.Id is not vpuInFocus.Id:
                eX = center[0] + np.sin(arc) * rad
                eY = center[1] + np.cos(arc) * rad
                pos.append([e.name, eX , eY])
                # patch form can depend on the entityclass !!!
                ePatch = mpatches.Circle([eX, eY], 0.3, ec='r',color='0.7', picker=True)
                patches.append(ePatch)
                ax.text(eX, eY, e.name, ha="center", family=font,size=14)

                line = matplotlib.lines.Line2D([center[0], eX],[center[1], eY], picker=True)  # [x1, x2], [y1, y2]
                line.set_color('1.0')
                patches.append(line)

                arc = arc + theta

        collection = PatchCollection(patches, cmap=matplotlib.cm.jet,alpha=0.4)
        ax.add_collection(collection)

    def onclick(self, event):
        print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
            event.button, event.x, event.y, event.xdata, event.ydata)

    def on_pick(self, event):
        if isinstance(event.artist, Line2D):
            thisline = event.artist
            xdata = thisline.get_xdata()
            ydata = thisline.get_ydata()
            ind = event.ind
            print 'onpick1 line:', zip(npy.take(xdata, ind),npy.take(ydata, ind))
        elif isinstance(event.artist, Rectangle):
            patch = event.artist
            print 'onpick1 patch:', patch.get_path()
        elif isinstance(event.artist, Text):
            text = event.artist
            print 'onpick1 text:', text.get_text()
        mouseevent = event.mouseevent
        msg = "X is: " + str(mouseevent.xdata) + "\nY is: " +str(mouseevent.ydata)
        print msg

So patches can't be picked! The follwoing code works fine to me.
class mplDialog(QtGui.QDialog, Ui_mplDialog):
  def __init__(self, parent=None):
    super(mplDialog, self).__init__(parent)

    # Basic preparation for an embedded matplotlib
    self.setupUi(self)

    # Context menu on system2 in focus button
    self.setContextMenuPolicy(Qt.CustomContextMenu)
    self.customContextMenuRequested.connect(self.ctxMenu)

    fig = Figure(figsize=(600,600), dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0))

    self.canvas = FigureCanvas(fig)
    self.verticalLayout.addWidget(self.canvas)

    self.axes = fig.add_subplot(111)
    self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding,
                               QtGui.QSizePolicy.Expanding)
    self.canvas.updateGeometry()
    self.navigation_toolbar = NavigationToolbar(self.canvas, self)
    self.verticalLayout.addWidget(self.navigation_toolbar, 0)

    # Specific content
    self.axes.plot([1,2,3,4,5,6,7,8,9],[50, 67, 74, 57, 57, 57, 75, 64, 96], picker=True)
    self.axes.scatter(2, 80, marker='o', picker=True)

    # Add patches (which can't be picked!)
    from matplotlib.collections import PatchCollection
    import matplotlib.patches as mpatches
    font = "sans-serif"
    patches = []
    ePatch = mpatches.Circle([5,70], ec='r', color='r', picker=True)
    patches.append(ePatch)
    ePatch = mpatches.Rectangle([7,60], 3, 10,  ec='r', color='0.7', picker=True)
    self.axes.text(7,60, "Rect name", picker=True)
    patches.append(ePatch)
    collection = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
    self.axes.add_collection(collection)

    self.canvas.mpl_connect('pick_event', self.onpick1)

def onpick1(self, event):
    #print event.artist
    if isinstance(event.artist, Line2D):
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        ind = event.ind
        print 'onpick1 line:', zip(np.take(xdata, ind), np.take(ydata, ind))
    elif isinstance(event.artist, Rectangle):  # For bar plots
        patch = event.artist
        print 'onpick1 patch:', patch.get_path()
    elif isinstance(event.artist, Text):
        text = event.artist
        print 'onpick1 text:', text.get_text(), "Obj", text
    else:   # For scatter plots
        patch = event.artist
        print 'onpick1 Circle:' #patch.get_path()


text:
Q: Adobe AIR HTML app white screen issue I have this issue for a really long time but can't find any solution.
Sometimes the application UI turns white when the app is busy (or maybe the iframe in the app is busy), and it will just happen on some of the computer. (Actually I have never met this situation on my own laptop)
Does any one know why this happen or have the solution? Thanks.

A: Once possible cause could be the fact that Adobe Air is a single threaded environment.
If your application is having to undertake a particularly resource intensive task it will continue until it has finished the job and hence, won't update the UI until after this time often resulting in the appearance of the application 'hanging'.


text:
Q: Check if two intervals overlap in R Given values in four columns (FromUp,ToUp,FromDown,ToDown) two of them always define a range (FromUp,ToUp and FromDown,ToDown). How can I test whether the two ranges overlap. It is important to state that the ranges value are not sorted so the "From" value can be higher then the "To" value and the other way round.
Some Example data:
FromUp<-c(5,32,1,5,15,1,6,1,5)
ToUp<-c(5,31,3,5,25,3,6,19,1)

FromDown<-c(1,2,8,1,22,2,1,2,6)
ToDown<-c(4,5,10,6,24,4,1,16,2)

ranges<-data.frame(FromUp,ToUp,FromDown,ToDown)

So that the result would look like:
FromUp ToUp FromDown ToDown   Overlap
      5    5        1      4    FALSE
     32   31        2      5    FALSE
      1    3        8     10    FALSE
      5    5        1      6    TRUE
     15   25       22     24    TRUE
      1    3        2      4    TRUE
      6    6        1      1    FALSE
      1   19        2     16    TRUE
      5    1        6      2    TRUE

I tried a view things but did not get it to work especially the thing that the intervals are not "sorted" makes it for my R skills to difficult to figure out a solution.
I though about finding the min and max values of the pairs of columns(e.g FromUp, ToUp) and than compare them?
Any help would be appreciated.

A: Sort them
rng = cbind(pmin(ranges[,1], ranges[,2]), pmax(ranges[,1], ranges[,2]),
            pmin(ranges[,3], ranges[,4]), pmax(ranges[,3], ranges[,4]))

and write the condition
olap = (rng[,1] <= rng[,4]) & (rng[,2] >= rng[,3])

In one step this might be
(pmin(ranges[,1], ranges[,2]) <= pmax(ranges[,3], ranges[,4])) &
    (pmax(ranges[,1], ranges[,2]) >= pmin(ranges[,3], ranges[,4]))

The foverlap() function mentioned by others (or IRanges::findOveralaps()) would be appropriate if you were looking for overlaps between any range, but you're looking for 'parallel' (within-row?) overlaps.
The logic of the solution here is the same as the answer of @Julius, but is 'vectorized' (e.g., 1 call to pmin(), rather than nrow(ranges) calls to sort()) and should be much faster (though using more memory) for longer vectors of possible ranges.

A: In general:
apply(ranges,1,function(x){y<-c(sort(x[1:2]),sort(x[3:4]));max(y[c(1,3)])<=min(y[c(2,4)])})

or, in case intervals cannot overlap at just one point (e.g. because they are open):
!apply(ranges,1,function(x){y<-sort(x)[1:2];all(y==sort(x[1:2]))|all(y==sort(x[3:4]))})


text:
Q: Find BLUE of $\gamma-\phi$ Consider the following model:
$$y_1 = \theta + \gamma + \epsilon_1$$
$$y_2 = \theta + \phi + \epsilon_2$$
$$y_3 = 2\theta + \phi + \gamma + \epsilon_3$$
$$y_4 = \phi − \gamma + \epsilon_4$$
where $\epsilon_i$ are uncorrelated having mean $\theta$ and variance $\sigma^2$. Show that $\gamma − \phi$ is estimable. What is its BLUE?
MY ATTEMPT :
I have shown $\gamma-\phi$ is estimable.
$\rightarrow$ Ok so we have to minimise $\Phi=\mathop{\mathbb{E}}(\gamma-\phi-\alpha-\beta^TY)^2$ Where $\alpha+\beta^TY$ is best linear predictor of $\gamma-\phi$. With $\beta^T=[\beta_1, \beta_2,\beta_3, \beta_4]$
Now $\Phi=\mathop{\mathbb{E}}(\beta^TY)^2+(\gamma-\phi-\alpha)^2$
For $\Phi$ to be minimum, $\hat{\alpha}=\gamma -\phi$
So $\Phi=\mathop{\mathbb{E}}(\beta^TYY^T\beta)$
Now how to find $\beta$ to minimise $Y$? (On a side note, whatever I have done is correct or are there any errors?)


text:
Q: Securing Ajax Requests in ASP.net via Authenticated Webforms I already read
Securing AJAX Requests via GUID
and
Securing an ajax request
. Now let me explain my scenario, below would be code snippet that may aid at explaining in the subject matter.
[WebMethod[EnableSession = True]
[ScriptMethod]

    public static string CreateTitle(string strTitleName)
    {
    string strResult = "Custom jSon string";
    if(Session["Authorized"] == "True" && !String.IsNullOrEmpty(strTitleName))
    {
         String strTitle = Server.HtmlEncode(strTitleName);
         InsertRecordInDB(strTitle);
         strResult = "Custom jSOn string" + EncryptMD5("record id");
    }
           return strResult;
    }

and below is the javascript call to send in the parameters. btnCreateTitle_click is the click event of the button client side. txtTitle is the textbox accepting the title name. Validators are created on the page to validate the textbox too.CreateTitle is a page method i call using scriptmanager
function btnCreateTitle_Click(evnt){
if(Page.ClientValidate()){
if($get("txtTitle")){
PageMethods.CreateTitle($get("txtTitle").value,success,failure,context);
}}}

the function success shows a growl message that title was created and shows a link with encrypted record id as query string to the url to view the details of created title.
Now the burning question,

*

*IS this secure enough?  What am i missing?

*How could i make the process more secure and faster?

A: While it is trivial to restrict any method to authenticated and authorised users, when you expose db id's in query strings you do open the possibility that an authenticated and authorised user may seek to access records that they aught not. This is particularly so when the db id's are integers or some other easily guessed identifier. Using Guids as db ids may mitigate the risk of this, though not absolutely.
What you always need to remember is DO NOT TRUST INPUT. Security through obscurity (ie encryption etc) is not a reliable technique. Your service should always verify the the current user is allowed to retrieve the records they have requested. Sometimes this is known as row level security. This can only be done programmatically.
eg instead of only determining that someone is authorised to view a record, you need to verify that they have rights in fact to access the record they are requesting.
This means you need some way of relating records to an authenticated user.
BTW: any HTTP request is validated for potentially dangerous input.
Hope this helps,


text:
Q: Area of flat surface = Half the surface area of hemisphere. Consider a sphere. Cut it in such a way that it results in two hemispheres.
My question is why the surface area of the hemisphere is twice the area of the flat surface area?
By looking at the formulas one can conclude the above fact($2$x$\pi r^2$=$2\pi r^2$), but is there any intuitive way that can explain this?


text:
Q: Uri.withAppendedPath method I want to create an SMS Android app. I read the SMS sender's name and the body of the message, then I show them in a list view. I use the following URI for reading the sender's name from the sender's number.
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(senderNumber));

What does this line of code do?

A: This filters the Contact from Phonebook based upon senderNumber
Example
/*
 * Returns contact's id
 */
private String getContactId(String phoneNumber, Context context) {
    ContentResolver mResolver = context.getContentResolver();

    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(phoneNumber));

    Cursor cursor = mResolver.query(uri, new String[] {
            PhoneLookup.DISPLAY_NAME, PhoneLookup._ID }, null, null, null);

    String contactId = "";

    if (cursor.moveToFirst()) {
        do {
            contactId = cursor.getString(cursor
                    .getColumnIndex(PhoneLookup._ID));
        } while (cursor.moveToNext());
    }

    cursor.close();
    cursor = null;
    return contactId;
}

In this example you will get data from two columns only  PhoneLookup.DISPLAY_NAME and PhoneLookup._ID based on the query.


text:
Q: Purpose of universal property of a product. I read the definition of a universal property of a product of topological spaces. Generally it says that for map $f$ from $\mathbb{X}$ to $\mathbb{Y}$ and map $g$ from $\mathbb{X}$ to $\mathbb{Z}$ there exist unique map $h$ from $\mathbb{X}$ to $\mathbb{Y}\times \mathbb{Z}$ such that projection of image of $h$ equals to image of $f$ and image of $g$. For what purpose we use this property and isn't it just $h(x)=(f(x),g(x))$ ?
Thanks.

A: It sounds like the way it was presented makes it seem tautological. Let's put it slightly differently.
Any topological space $Z$ equipped with maps $p:Z\to X$ and $q:Z\to Y$ has the universal property of being the product of the spaces $X$ and $Y$ if and only if for every pair of maps $f: W\to X$ and $g:W\to Y$ there exists a unique map $h: W\to Z$ such that $p\circ h=f$ and $q\circ h = g$.
You are completely correct that choosing $Z=X\times Y$ with $p=\pi_1$ and $q=\pi_2$ gives you something that satisfies the universal property and indeed will lead to $h(x)=(f(x),g(x))$. But we could also choose $Z=Y\times X$ with $p=\pi_2$ and $q=\pi_1$ for which $h(x)=(g(x),f(x))$. So the universal property does not (in general) uniquely identify a topological space. However, as you should prove, given two topological spaces each equipped with a pair of "projections", if both satisfy the universal property then they are homeomorphic, in fact, there exists exactly one homeomorphism that takes the "projections" of one to the "projections" of the other.
This last fact (that actually holds, suitably formulated, for all "universal properties") is very useful. Given any topological space $T$ and pair of functions $T\to X$ and $T\to Y$, if we can show that $T$ with those functions satisfies the universal property of products, then we know that $T\cong X\times Y$. $T$ may not always be obviously a set of pairs with the product topology.


text:
Q: How to insert class in HTML tag using CSS? Here is my question :
How to insert class in HTML tag using CSS? Not using JavaScript/JQuery, I know how to do using scripts. So please don't answer any if you are trying to answer it using scripts.
Here is my simple code:
Close

I want to insert a class name "modal" into this tag but using CSS. Is there any possibility? I knew about using "content" in CSS, but nothing to do with content; but here I'm talking inserting class like scripts but not with scripts.
I knew this is something called "CRAZY" but what about solution, anybody have or tried.

A: The options you have are:

*

*Injecting the class with JavaScript (or JavaScript libraries like jQuery)

*Having a server (or local server using XAMPP or similar tools ) that runs PHP / Python / something similar to render your page and fill in the class in a template

There is no way of doing this with pure CSS.

A: You cannot add classes via css. CSS is just not made for purpose to modify DOM, CSS works with existent DOM. CSS is used to style a document and to enhance its design aspects.
You would be able to do so by either:
Close

or via javascript.

A: I'm afraid it is impossible. The CSS can not change the structures of the DOM.
But, if there are more than one tag with the class close you can try to get a particular tag by nth-child().
If you tell us what really you want to do, perhaps we can try another solution.

A: It's impossible.
You can't do this with css.
Because CSS didn't design for this.
You can only do this.
<tagname class="class-name"> ... </tagname>


text:
Q: How to check compatibility of packages in setup.py wihout installation? I use a setup.py to declare the python libraries to include in the package of my solution.
Is there a way to check the libraries compatibility using setup.py without installing the package? Because for now I can detect the conflicts only when I try to install my package.
Thank you

A: I think if I were you I would try with dephell. I don't think it will be able to give you a clear answer without tweaking, but it might help you get a bit closer to the info you are looking for. For example you could try these commands:
dephell deps check --from setuppy

-- https://dephell.readthedocs.io/cmd-deps-check.html
or
dephell deps tree --from setuppy

-- https://dephell.readthedocs.io/cmd-deps-tree.html


text:
Q: Android bluetooth service name Is there any way that I can get the service name of the BT discovered device. My bluetooth discovery logis is as follows
 startdiscovery()
 {

  boolean status1 = mBluetoothAdapter.startDiscovery();

 }

 BroadcastReceiver mReceiver = new BroadcastReceiver()
  {
  if (BluetoothDevice.ACTION_FOUND.equals(action))
        {

 if(intent.hasExtra(BluetoothDevice.EXTRA_DEVICE))
            {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                            }
                     }
  }

Here i know only the "SERVICE NAME" of the discovered device in STRING FORMAT.
bluetoothclass.hasService(int) - This API takes predefined SERVICE NAMES as an input parameter and return TRUE/FALSE. I can use this API as i know only the SERVICE NAME.

A: http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getBluetoothClass() gives u the class, and then you can extract it from that.


text:
Q: Kernel restart when using simple matplotlib I would like your help with a simple issue.
I'm on spider 5.15, with matplotlib on 3.4.3, on windows 10, on python 3.8.
My problem is when I start a code with matplotlib my kernel crashes and restarts.
The simplest way to reproduce my error is:
import matplotlib.pyplot as plt
plt.plot([1,2])

I suspect the version on matplotlib and I try to downgrade it from 3.4.3 down to 3.1.
I try matplotlib.use("Agg") or ("Qt5Agg")
I try to downgrade all the versions but still did not work.


text:
Q: WPF DataGrid only calculate visible rows I remeber reading an article a couple months back about a feature or DataGrid or an extended version of DataGrid that only wires up the notifications, bindings, etc. on the rows visible to the user and a few not visible to provide quick display when showing.
I cannot find this article and my Googling is not coming up with anything.
Does anyone know what this feature is and what it is called?
The reason I am wanting to do this is because I am displaying a DataGrid with a large number of rows (1000+).  The rows are defined such that two of the cells display a combo box of possible values.  Without these combo boxes the data grid loads (executes a SQL script and converts to a DataTable bound to the DataGrid) and displays almost instantly.  When I add the combo boxes the loading takes about 10-15 seconds.  I think the article addressed this and said the performance would be better as the DataGrid is only creating the combo boxes necessary to the immediate view and not all 1000+ rows.
I am open to other suggestions on how to avoid the long wait times when adding the combo boxes to the DataGrid (requirements state the these two cells are combo boxes so removing is not an option).

A: Perhaps you're thinking of the RowVirtualization property?
... When the EnableRowVirtualization property is set to true, the DataGrid does not instantiate a DataGridRow object for each data item in the bound data source. Instead, the DataGrid creates DataGridRow objects only when they are needed ...
In other words this will improve performance by only loading into memory the rows which are being displayed. There is a limit to the number of controls a typical application can display before things start getting very sluggish. Virtualizing controls is the answer to this problem.
For example, refer to the answer to this question: Upper (reasonable) limit to number of user control instances. Even though this applies to UserControls specifically, the same concept applies to all controls.


text:
Q: No data received in push notification I'm using the following java code to send a push notification to gcm. The google server or whatever response ok HTTP code200 ,with the appropiate multicast_id  and message_id. The problem: when I try to get data of pushevent.data on my browser,  when the `notification arrives..there´s nothing on it. No data, zero.
 Why? The devtools shows : PushEvent :data {null}.
The push notification appears perfectly .But I want to show data from server to browser , Is this possible??
So sorry of my English
This is the code on the server:
public void method(){
 try {
 String apiKey = "AIzaSyB74usn5bPOiPi57DqC3mlaQHvIv5AEoWc";
        //API key provided by Google Console
        Usuario usuario = usuarioDao.findByTelefono("600112207");
        String deviceID = usuario.getRegistrationId();
        System.out.println(deviceID);
        Content content = new Content();
        //POJO class as above for standard message format
        content.addRegId(deviceID);
        content.createData("Mensaje para el usuario:",usuario.getUsuario());
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key="+apiKey);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        ObjectMapper mapper = new ObjectMapper();
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        mapper.writeValue(wr, content);
        wr.flush();
        wr.close();
        inputStream = conn.getInputStream();
        int responseCode = conn.getResponseCode();

    } catch (IOException e) {
        e.printStackTrace();
    }

//the Content class
package antia.PFC.utils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Content implements Serializable {

private static final long serialVersionUID = 4598819886093518574L;
public List<String> registration_ids;
public Map<String, String> data;
public void addRegId(String regId) {
    if (registration_ids == null)
        registration_ids = new LinkedList<String>();
    registration_ids.add(regId);
}
public void createData(String title, String message) {
    if (data == null)
        data = new HashMap<String, String>();
    data.put("title", title);
    data.put("message", message);

}
}

//the service-worker.js

//Version 0.1
'use strict';

console.log('Started', self);
self.addEventListener('install', function(event) {
self.skipWaiting();
console.log('Installed', event);
});

self.addEventListener('activate', function(event) {
console.log('Activated', event);
});

self.addEventListener('push', function(event) {
console.log('Push message', event);
if (event.data) {
console.log('Push message',event.data.json())
}
var title = 'Mensaxe Quendas';
event.waitUntil(self.registration.showNotification(title,{
body : 'Ten vostede unha solicitude de cambio',
tag :'my-tag',
}));
});


text:
Q: How to see full autocomplete method in Javascript by Netbean How can I see methods of any Object which defined in HTML tag and is called in JavaScript? Please see my issue as below:

I want to see method getContext("2d") or other methods of Canvas Object on autocomplete panel but I did not see any method of Canvas Object display on that.
So hard to remember all of method of any object of HTML, so, what is solution to fix my issue?? Please help me. Thank you


text:
Q: How do I clear a large persistent collection quickly? I have an entity Foo with a Bars collection.
This collection is quite big (say, 20,000 elements, and yes, it needs to be loaded entirely, because it's displayed in a TreeView), and the elements are generated automatically based on some parameters of the Foo that the user can change, using a WPF MVVM application (all processing occurs in the client)
After he is satisfied with the results, he hits save, and DbContext.SaveChanges() is called.
Generating Bars implies clearing the collection, then doing a bunch of calculations and adding the new elements. When this is a new, non-persistent Foo, it's no problem because I can just call foo.Bars.Clear()
The problem is, doing that with already persistent entities causes EF to set bar.Foo = null in all the elements, instead of deleting them.
My workaround goes like this:
void Regenerate()
{
    if (fooIsPersistent)
    {
        foreach (var bar in foo.Bars.ToList())
            context.Entry(bar).State = EntityState.Detached;
        deleteOnSave = true;
    }
    else
        foo.Bars.Clear();
    AddTheNewCalculatedElements()
}

void Save()
{
    if (deleteOnSave)
        context.Database.ExecuteSqlCommand("delete Bar where Foo = @Id", param);
    context.SaveChanges();
}

The problem with this solution is that it doesn't scale. Calling                     Entry(bar).State = EntityState.Detached when there are many entities loaded is even slower than just calling context.Set<Bar>().Remove(bar) and letting EF do the deletes one by one, so it defeats the purpose of the workaround.
So, my question is: Is there any efficient way to make EF believe the collection is actually empty?
Or should I do it in a completely different way?

A: Well, it was easier than I thought.
I replaced this line:
context.Entry(bar).State = EntityState.Detached;

with this one (which I thought was more or less equivalent):
((IObjectContextAdapter)context).ObjectContext.Detach(bar);

And it now completes in a reasonable time.


text:
Q: Prove that $R[x] \cong R[y]$ How do I prove that $R[x] \cong R[y]$? I understand that $R[n]$ represents the set of all polynomials in $n$ with coefficients from the commutative ring $R$, but I don't know how to even start this problem.
Any help would be great, thank you!

A: I will outline an sketch for how you might start thinking about this problem. First, recall that two sets are isomorphic if there exists an isomorphism between the two sets. Consider a polynomial in $R[x]$. How could you map this to $R[y]$? Then show that this mapping is well-defined, injective, surjective, and operation-preserving. Then, you have your explicit isomorphism, so you can say that $R[x]\cong R[y]$.


text:
Q: filter Object of arrays JavaScript Let's say I have this Object of arrays:
foo = {morning: [1,2,3,4,5], afternoon: [1,2,3,4,7]}
I want to write a function that returns this object but remove a particular value.
ex: I want to remove the number 3 in afternoon.
The function would return {morning: [1,2,3,4,5], afternoon: [1,2,4,7]}
myFunction = (partsOfDay, number) => {
  // do something
 // returns the object of arrays but without the specified value
}

How can I do that ?

A: You can do this without changing the source object using Array.reduce() and Object.entries().
The properties of the returned object will still point to the source object but the filtered array properties will be copied with Array.filter().

const foo = { morning: [1,2,3,4,5], afternoon: [1,2,3,4,7] };

const myFilter = (obj, prop, value) => Object.entries(obj).reduce((acc, [key, val]) => {
  acc[key] = key === prop && Array.isArray(val) ? val.filter(x => x !== value) : val;
  return acc;
}, {});

console.log(myFilter(foo, 'afternoon', 3));
console.log(myFilter(foo, 'morning', 3));
console.log(foo);

A: There are many ways, something like this
var partsOfDay = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

myFunction = (partsOfDay, number) => {
  var filtered = partsOfDay.filter(function(value, index, arr){
    return value != number;
  });
}

Refer for more here


text:
Q: Cannot implicitly convert type 'decimal' to 'string' I have this code in a shopping cart I am creating but I am receiving the error shown in the title.The error is showing up on this line:

A: Just call ToString to get a string representation of the decimal value:
order.Total = orderTotal.ToString("G");

Although I don't see why you would store the member Total as a string and not as a decimal too.

A: It sounds like the Order class has a Total property that's a string. Check the class definition for Order. If that's the case, I'd recommend changing the Total data type to a decimal, because having a currency value represented as a string doesn't make sense. decimal makes more sense.

A: How is your Order  class looks like ? What is the type of the Property called Total ? It looks like it is a string type. Here you are trying to set decimal value to a string type That is y you are getting that error. So you need to convert decimal to string before assigning it to a string varaiable. Use the toString() method.
order.Total = orderTotal.ToString();

As Tudor already mentioned, It is better to use Total as a decimal property as it will be easy for you to do all mathematical operations. You dont need to convert it to decimal  format every time you want to do an arithmetical operation and convert it again back to string

A: Change the type of Order.Total to Decimal.  The data type Decimal does not automatically convert to string (and visa-versa) which is why you're getting an error, plus, any subsequent calls to Order.Total would be string related, so you would not be able to use operators like Order.Total +=
Also note that any binding convenience like a DataTable's 'format' property would be ignored because the underlying architecture won't call string.ToString(format).