text:
Q: How do I send a value from a Microsoft Bot to Javascript? I need to send a string from the MessagesController in a Microsoft Framework Bot to a script written in JS. The string contains the value of a secret for a bot we are hosting which is inactive (not in use). Is there a way to send a string from an Azure hosted bot?
Edit: I have tried to create a method which returns a string but cannot retrieve it through a url (sitename.azurewebsites.net/api/messages/methodname), I cannot use Jsonresult or Actionresult as the bot isn't MVC.
More info: We have set up 5 bots which set themselves as being active (in a chat session) or inactive (not in a chat session). We know if a bot is active or not by the values set in a database. There is a stored procedure in the database which returns a direct line secret for an inactive bot. What I want to do is send this secret (string) from the database to the JavaScript so we can generate a bot dynamically. The problem is, we do not want to connect to the database from the JS on the front end, instead we want to get the secret from a bot (any bot). Therefore I would like to get a string value from the MessagesController into JavaScript from the hosted bot on azure.
Thanks
Edit2:
 public IHttpActionResult GetString()
        {
            return Ok("it worked");
        }

returns BotAuthenticator failed to authenticate incoming request!

A: You can achieve the following:

I need to send a string from the MessagesController in a Microsoft
  Framework Bot to a script written in JS.

By using the backchannel capability of the webchat channel. Based on your query I assume your are using this channel here.
To get more information about the backchannel, have a look here.
The idea is to send an event from your bot code, that will be received by the JS on the client side:
The client JavaScript also listens for a specific event from the bot. In their sample they show the ability to change a color on the client side, based on an event sent by the bot:
botConnection.activity$
    .filter(activity => activity.type === "event" && activity.name === "changeBackground")
    .subscribe(activity => changeBackgroundColor(activity.value))

You can use the following to send the secret you require and activate the right bot.


text:
Q: Insufficient permissions to access resource in nodejs Insufficient permissions to access resource
Trying to integrate access control list in my project, here assigned the userid(12345) to guest role.  while i access the url the i am getting the following error
HttpError: Insufficient permissions to access resource
            at /home/smi-user/chrysmo/node_modules/acl/lib/acl.js:649:14
            at tryCatcher (/home/smi-user/chrysmo/node_modules/bluebird/js/main/util.js:26:23)
            at Promise.successAdapter [as _fulfillmentHandler0] (/home/smi-user/chrysmo/node_modules/bluebird/js/main/nodeify.js:23:30)
            at Promise._settlePromiseAt (/home/smi-user/chrysmo/node_modules/bluebird/js/main/promise.js:579:21)
            at Promise._settlePromises (/home/smi-user/chrysmo/node_modules/bluebird/js/main/promise.js:697:14)
            at Async._drainQueue (/home/smi-user/chrysmo/node_modules/bluebird/js/main/async.js:123:16)
            at Async._drainQueues (/home/smi-user/chrysmo/node_modules/bluebird/js/main/async.js:133:10)
            at Immediate.Async.drainQueues [as _onImmediate] (/home/smi-user/chrysmo/node_modules/bluebird/js/main/async.js:15:14)
            at processImmediate [as _immediateCallback] (timers.js:383:17)
server.js
   var express = require( 'express' );
   var acl = require( 'acl' );
   var bodyParser = require('body-parser');
   var app = express();
   app.use(bodyParser.json());
   app.use(bodyParser.urlencoded({ extended: false }));
   // Or Using the memory backend
    acl = new acl(new acl.memoryBackend());

   acl.allow([
    {
    roles:['guest','member'],
    allows:[
        {resources:'blogs', permissions:'get'},
        {resources:['forums','news'], permissions:['get','put','delete']}
    ]
    },
    {
    roles:['gold','silver'],
    allows:[
        {resources:'cash', permissions:['sell','exchange']},
        {resources:['account','deposit'], permissions:['put','delete']}
    ]
    }
]);

acl.addUserRoles('12345', 'guest');

app.get( '/blogs/:id',acl.middleware(1,getuserid()),
    function( request, response, next ) {
     console.log("test");
    next();
    }
);

function getuserid(){
    return '12345';
}

// Starting the server
app.listen( 3030, function() {
    console.log( 'ACL example listening on port 3030' );
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: There is a partition of $X$ into disjoint closed sets $F, G$ such that $a\in F$ and $b\in G$ Let $X$ be a compact normal topological space and $a,b \in X$ such that they belong to different connected components of $X$.
I'm trying to prove this result used in Lemma 7 of this link.

*

*Could you have a check on my attempt?

*Could we replace the assumptions compactness and being normal by something weaker?

Theorem: There is a partition of $X$ into disjoint closed sets $F, G$ such that $a\in F$ and $b\in G$.

Proof: Let $\Gamma_a$ be the collection of all clopen sets in $X$ that contains $a$. Assume the contrary that the claim does not hold. Then $A \in \Gamma_a \implies b\in A$. This means $a,b \in A$ for all $A \in \Gamma_a$. Let $C_a$ be the connected component that contains $a$. We have $X$ is compact normal, so $C_a = \bigcap \Gamma_a$. Hence $a,b \in C_a$ which is a contradiction. This completes the proof.


text:
Q: SharePoint Import/Export Command for Library with version setting disabled I have to export a SharePoint library from a site in server A and import it to a library in server B such that only the items that are new or updated are imported to site in server B. While this can be done with "UpdateVersion" parameter set to "ignore" for export command, the problem is we don't have version setting enabled for source or destination library. How can I import only the updated items or new items? Enabling version setting is not an option. If its not possible using export/import is there any other way?

A: Finally found answer by trying.As it turns out even if you have version setting disabled for sharepoint library in source site and destination site you can import with overwrite parameter. It will update the existing item. This will work only if the "Name" field of document(in case of library) is not changed. I have also put it in detail in my blog: http://www.sp-androidgeeks.blogspot.in/2015/03/migrate-sharepoint-listlibrary.html


text:
Q: How can I Insert/Update into two related tables in one command? A database exists with two tables

*

*Data_t : DataID Primary Key that is
Identity 1,1.  Also has another field
'LEFT' TINYINT

*Data_Link_t : DataID PK and FK where
DataID MUST exist in Data_t.  Also has another field 'RIGHT' SMALLINT

Coming from a microsoft access environment into C# and sql server I'm looking for a good method of importing a record into this relationship.
The record contains information that belongs on both sides of this join (Possibly inserting/updating upwards 5000 records at once).  Bonus to process the entire batch in some kind of LINQ list type command but even if this is done record by record the key goal is that BOTH sides of this record should be processed in the same step.
There are countless approaches and I'm looking at too many to determine which way I should go so I thought faster to ask the general public.  Is LINQ an option for inserting/updating a big list like this with LINQ to SQL?  Should I go record by record?  What approach should I use to add a record to normalized tables that when joined create the full record?

A: Sounds like a case where I'd write a small stored proc and call that from C# - e.g. as a function on my Linq-to-SQL data context object.
Something like:
CREATE PROCEDURE dbo.InsertData(@Left TINYINT, @Right SMALLINT)
AS BEGIN
   DECLARE @DataID INT

   INSERT INTO dbo.Data_t(Left) VALUES(@Left)

   SELECT @DataID = SCOPE_IDENTITY();

   INSERT INTO dbo.Data_Link_T(DataID, Right) VALUES(@DataID, @Right)
END

If you import that into your data context, you could call this something like:
using(YourDataContext ctx = new YourDataContext)
{
   foreach(YourObjectType obj in YourListOfObjects)
   {
      ctx.InsertData(obj.Left, obj.Right)
   }
}

and let the stored proc handle all the rest (all the details, like determining and using the IDENTITY from the first table in the second one) for you.

A: I have never tried it myself, but you might be able to do exactly what you are asking for by creating an updateable view and then inserting records into the view.
UPDATE
I just tried it, and it doesn't look like it will work.

Msg 4405, Level 16, State 1, Line 1
  View or function 'Data_t_and_Data_Link_t' is not updatable because the modification affects multiple base tables.

I guess this is just one more thing for all the Relational Database Theory purists to hate about SQL Server.
ANOTHER UPDATE
Further research has found a way to do it. It can be done with a view and an "instead of" trigger.
create table Data_t
(
    DataID int not null identity primary key,
    [LEFT] tinyint,
)
GO

create table Data_Link_t
(
    DataID int not null primary key foreign key references Data_T (DataID),
    [RIGHT] smallint,
)
GO

create view Data_t_and_Data_Link_t
as
select
    d.DataID,
    d.[LEFT],
    dl.[RIGHT]
from
    Data_t d
    inner join Data_Link_t dl on dl.DataID = d.DataID
GO

create trigger trgInsData_t_and_Data_Link_t on Data_t_and_Data_Link_T
instead of insert
as
insert into Data_t ([LEFT]) select [LEFT] from inserted
insert into Data_Link_t (DataID, [RIGHT]) select @@IDENTITY, [RIGHT] from inserted
go

insert into Data_t_and_Data_Link_t ([LEFT],[RIGHT]) values (1, 2)


text:
Q: Why I cannot check the MS word paragraph style in Visual Studio? This is an addin to my MS word:
Public Sub Application_DocumentBeforeSave(ByVal Doc As Word.Document, ByRef SaveAsUI As Boolean, ByRef Cancel As Boolean) Handles Application.DocumentBeforeSave
    If SaveAsUI = True Then
            MsgBox(doc.Paragraphs(1).Range.Style)
     End If
End Sub

When I run this on visual studio it says "argument 'Prompt' cannot be converted to type 'String'". However, when I run
MsgBox(activedocument.Paragraphs(1).Range.Style)

on VBA inside MS word it shows me "Paper-Title", which is what I am looking for.  Can anyone help me with this on Visual Studio?

A: As @mat says, your VBA program is silently taking advantage of VBA's implicit conversions and possibly the default-property of the Style object.
According to MSDN, the Style object is this: https://msdn.microsoft.com/en-us/library/office/ff193692.aspx
It looks like you'll want the NameLocal property, so change your code to this:
Public Sub Application_DocumentBeforeSave(ByVal doc As Word.Document, ByRef saveAsUI As Boolean, ByRef cancel As Boolean) Handles Application.DocumentBeforeSave
    If saveAsUI AndAlso doc.Paragraphs.Count >= 2 Then
        MsgBox( doc.Paragraphs(1).Range.Style.NameLocal )
     End If
End Sub

Note that your program will crash if the current document has less than 2 paragraphs, so I added a bounds-check for you.

A: VBA is doing implicit conversions for you. .NET simply isn't as forgiving (although I'm not sure to what extent VB.NET allows or forbids those).
From MSDN it looks like you're passing an Object to the Prompt parameter of the MsgBox function, which wants a String.
You'll want to call .ToString() on it before you pass it to the message box.
Also I believe having Option Strict on might be helpful here.


text:
Q: get_queryset vs. get_query_set, Django 1.5 vs. 1.6 It looks like I have solved the problem by upgrading to Django 1.6. Just curious, what was going on.
I am trying to integrate OSQA alongside an existing Django app, and I am encountering some very subtle issues. Just look at that --- this is one PDB session, no multiple inheritance:
(Pdb) p type(self.get_query_set())
<class 'django.db.models.query.QuerySet'>
(Pdb) p type(self.get_queryset())
<class 'forum.models.node.NodeQuerySet'>

In Django 1.5, the default django.db.models.Manager has method all (as in MyModel.objects.all()) pointing to get_query_set() in line 128 of django/db/models/manager.py. In Django, 1.6 this same method is pointing to get_queryset, since, I guess, get_query_set became deprecated. This is line  133 of the same file, by the way.
Indeed, OSQA is broken in Django 1.5 It fails with
*** AttributeError: AttributeError("'QuerySet' object has no attribute 'filter_state'",), because in forum/views/readers.py, line 207, it does
questions = initial.filter_state(deleted=False), and there is no such function. In this case, it is passed Question.objects.all() as initial, but somehow it ends up being django.db.models.query.QuerySet instead of
forum.models.node.NodeQuerySet, which does have the required method.
(Pdb) from forum.models import Question
(Pdb) type(Question.objects.all())
<class 'django.db.models.query.QuerySet'>
(Pdb) type(Question.objects.get_queryset())
<class 'forum.models.node.NodeQuerySet'>
(Pdb) type(Question.objects.get_query_set())
<class 'django.db.models.query.QuerySet'>


text:
Q: What's the difference between x=false AND x=!x TO x=false AND x=true? This question is a follow up to this one.
What is the difference between:
let isMenuVisible = false;

burger.addEventListener('click', ()=>{
  isMenuVisible = !isMenuVisible;
  menu.style.display = isMenuVisible ? 'block' : 'none';
});

to
let isMenuVisible = false;

burger.addEventListener('click', ()=>{
  isMenuVisible = true;
  menu.style.display = isMenuVisible ? 'block' : 'none';
});

I fail to understand why the latter code failed; they seem to me equivalent (as the negation of false is true, isn't it?).

A: .In first case isMenuVisible is false so !isMenuVisible will be true;
isMenuVisible =!isMenuVisible will set the value of isMenuVisible will change on every click event
In second case instead of assigning the value through a variable true is directly assigned to isMenuVisible and the value will never toggle

A: First of all inside your burger.addEventListener the isMenuVisible = !isMenuVisible; and isMenuVisible = true is not the same thing.
isMenuVisible = !isMenuVisible; means what ever the value of isMenuVisible is now do it alternative e.g if it is true then make it false, if it is false then make it true
and
isMenuVisible=true means set it true
isMenuVisible=false means set it false

A: isMenuVisible = !isMenuVisible:

This is like flipping card. If we set isMenuVisible = false initially. After executing the above line once, isMenuVisible will be !isMenuVisible/true. After another execution, isMenuVisible will be !isMenuVisible/false.
isMenuVisible is getting alter in each execution.
isMenuVisible = true:

This is just assigning true to isMenuVisible all the time.


text:
Q: Recover images from iPhone - creating image I am following the steps from this site to recover deleted images from iPhone (I've tried other softwares, nothing has worked so far).
When I follow these steps, at the end I get the iphone.img file, the problem is that it has 0 bytes. Anybody has an idea of what am I doing wrong? Thanks!
The site is: http://www.cgsecurity.org/wiki/Recover_data_from_an_iPhone


text:
Q: Does $|a^{-n} J_0(n)|$ converge? Does the sequence $|a^{-n} J_0(n)|$ converge?
I used the approximation $J_0(n) \approx \sqrt{\frac{2}{\pi n}} \cos(n - \pi/4)$ and assume that $a > 1$. Since the sample sequence of $J_0(n)$ is weighted by a decaying exponential $a^{-n}$, I suspect this will converge, but I'm unable to confirm this.
I want to know if
$\sum_{n=1}^\infty a^{-n}|J_0(n)|$
converges for above approximation?

A: Since $a^{-n}|J_0(n)|\sim a^{-n}\sqrt{\frac 2{\pi n}}|\cos(n-\pi /4)|$, the series $\sum_{n\geq 0}a^{-n}|J_0(n)|$converges if and only if $\sum_{n\geq 1}a^{-n}\sqrt{\frac 2{\pi n}}|\cos(n-\pi /4)|$ converges. But for $n\geq 1$: $$0\leq a^{-n}\sqrt{\frac 2{\pi n}}|\cos(n-\pi /4)|\leq a^{-n}$$
so the series $\sum_{n\geq 1}a^{-n}\sqrt{\frac 2{\pi n}}|\cos(n-\pi /4)|$ converges. In particular, $\lim_{n\to\infty}\sqrt{\frac 2{\pi n}}\cos(n-\pi /4)=0$


text:
Q: Выводит в компиляторе вместо числа nan Создан список из чисел 3 5 1 9
struct Data

  {   int a;
    };

    struct List
    {   Data d;
    List *next;
    };

    int main(int argc, char** argv) {
        List *u = NULL;
        // 1 uzel
        u = new List; // obyavlenie
        u->d.a = 3;
        u->next = NULL; // ukazatel na sled element
        // dlya udobstva sozd peremennuyu-ukazatel kotoraya hranit adress posl elementa
        List *x;
        // 2 uzel
        x = u;
        x->next = new List;
        x = x->next;
        x->d.a = 5;
        x->next = NULL;
        //
        List *c;
        // 3 uzel
        c = x;
        c->next = new List;
        c = c->next;
        c->d.a = 1;
        c->next = NULL;
        //
        List *b;
        // 4 uzel
        b = c;
        b->next = new List;
        b = b->next;
        b->d.a = 9;
        b->next = NULL;
        // Vivod (prosto idem po spisku)
        while(u)
        {
            cout << u->d.a << endl;
            u = u->next;
        }

Добавлена функция подсчета среднего арифметического, но вместо числа в компиляторе выводится Average = nan:
// srednee arifm
int sum = 0, count = 0;
while(u)
{
    sum += u->d.a;
    ++count;
}
cout << "Average = " << double(sum)/count << endl;

        return 0;
    }

Почему?

A: При таком коде:
while(u)
{
    sum += u->d.a;
    ++count;
}

u в цикле не меняется, поэтому мы получим бесконечный цикл, если u != 0 либо, если u == 0 совсем не зайдем в цикл, и в дальнейшем получим деление нуля на ноль, что в результате дает значение "не является числом" (Not-a-Number, NaN).
Из википедии:
К операциям, приводящим к появлению NaN в качестве ответа, относятся:

*

*...

*деление нуля на ноль

Подробнее о делении нуля на нуль
u в Вашем коде равен нулю потому, что в цикле вывода Вы его меняете:
while(u)
{
   cout << u->d.a << endl;
   u = u->next;
}

после этого цикла u будет равен нулю.
Для исправления чуть переделаем код:
  // Vivod (prosto idem po spisku)
  List *p = u;//введем указатель, который будем использовать для прохода по списку перед выводом
  while (p) {//В цикле работаем только с p, а не с u
    cout << p->d.a << endl;
    p = p->next;
  }
  // srednee arifm
  if (u) {//Список не пуст
    int sum = 0, count = 0;
    p = u;//снова ставим p в равным u, для прохода с начала списка
    while(p)//в цикле также работаем с p, а не с u
    {
      sum += p->d.a;
      ++count;
      p = p->next;//не забываем перейти к следующему элементу
    }
    cout << "Average = " << double(sum)/count << endl;
  } else {
    cout << "Empty list" << endl;
  }

Также Вы забыли про освобождение памяти.
Но в любом случае, Ваш список - это подход, скорее, для языка C, а не для C++.

A: Если программа будет в этом цикле то очевидно что она из него не выйдет никогда.
т.к. прога его прошла значит u=nullptr; а 0/0=nan (а для флоат краш)
while(u)
{
    sum += u->d.a;
    ++count;
}
cout << "Average = " << double(sum)/count << endl;

может ты подучишь с++ перед тем как создавать проект? хотя бы про дебаггинг. а то уже 5 вопросов за 2 дня.


text:
Q: Flask object with the same lifetime as application
I am trying to build a REST API using Flask, and Neo4j. Using the official Python driver for Neo4j, it seems that I need to have a driver object that can be used to get database connections when needed.
Is there any way I can store an object in Flask that lives as long as the application is running? I am aware of the application context wherein you can pass data, but if what I understand is correct, the application context is popped from the stack for each request.

A: You can achieve this by writing your own flask extension. The example shows how to make a connection with SQLite, but you can easily adapt it for neo4j.


text:
Q: Storing values of multiple dynamic textboxes to array Textboxes are generated dynamically
public void createtxtbox(int d)
{
    int x = 0;
    int y = 0;
    txtbox = new TextBox[d*d];

    for (int u = 0; u < txtbox.Count(); u++)
    {
        txtbox[u] = new TextBox();
    }

    for (int i = 0; i < txtbox.Length; i++)
    {
        int name = i + 1;
        txtbox[i].Name = "TXT" + name.ToString();
        txtbox[i].Location = new Point(42 + (x * 31), 47 + (y * 21));
        txtbox[i].Visible = true;
        txtbox[i].Size = new Size(30, 20);
        txtbox[i].MaxLength = 1;
        txtbox[i].TextAlign = HorizontalAlignment.Center;
        this.Controls.Add(txtbox[i]);

        x++;
        if (x == d)
        {
            x = 0; y++;
        }

        }
    }

In the form the user inputs values into them and which would then be stored later in an array at exit.
The only way I know of storing textbox values to string:
txtbx = textBox.Text

EDIT:
answered it
found what went wrong with the code
thought this method was just returning null values but it was not...
private void txtboxtostring()
        {
            txtbx = new string[txtbox.Length];
            for (int i = 0; i < txtbox.Length; i++)
                txtbx[i]= txtbox[i].Text;
        }

when button is clicked array would be passed to class
 private void button1_Click(object sender, EventArgs e)
        {
            //try
            //{
                txtboxtostring();
                create = new CreateClass(title, name);
                create.Createfile(txtbx);

                this.Close();
                Menu menu = new Menu();
                menu.Show();
            //}

            //catch
            //{
            //    MessageBox.Show("Something went wrong");
            //}
        }

would be evaluated/assigned here in this method in the class
 private void Popvals(string[] t)
        {
            vals = new string [t.Length];
            for (int i = 0; i<t.Length; i++)
            { vals[i] = t[i]; }
        }

and I'm free to do what I want with the values...
well thanks to everyone that helped

A: string[] values = txtbox.Select(x => x.Text).ToArray();


text:
Q: Entity Not Mapped - Entity Model Framework I'm having a lot of difficulty with the Entity Model Framework.
I'm just learning how to use this, so please bear with me.
This is the exception, along with the line of code that it gets thrown on:

This is what the model looks like, along with the model that it inherits from

This is what the mapping details looks like: (Top of if statement was cut off)

Here's what AccountContext looks like

If I didn't provide enough information then please let me know
How do I map the "User" Entity?

A: You have a class hierarchy there and there are three different strategies for inheritance mapping: TPH, TPT and TPC.
As far as I understand in all three strategies you need to include the Base class into you DbContext:
public class AccountContext : DbContext
{
    public DbSet<BaseModel> BaseModels { get; set; }
}

This leads automatically to TPH mapping. For the other two strategies you need additional mappings either by data annotations or in Fluent API.
Edit
To query for your derived classes (like User) you can work with the OfType method, for instance:
UserDb.BaseModels.OfType<User>().ToList()

This would return all entities of type User into a list.


text:
Q: What is the value given to 'mcm'? That's the solution to the "Write a program that calculates the minimum common multiple of two numbers in C" our proffesor posted.
#include <stdio.h>
#include <conio.h>

int main() {
    int n1, n2, mcm;
    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);

    mcm = (n1 > n2) ? n1 : n2;

    while (1) {
        if (mcm % n1 == 0 && mcm % n2 == 0) {
            printf("The Minimum Common Multiple of %d and %d is %d.", n1, n2, mcm);
            break;
        }
        ++mcm;
    }
    return 0;
}

This is the same code you can find on programiz but without including the conio.h library.
What is the purpose of using the whole line where mcm gets a value?
Does it have something to do with the conio.h library?
When i wrote the code myself i just stated mcm=1; and it worked just fine.

A: It saves some cpu cycles, since you know values less than the larger of the two inputs cannot be a common multiple of the two values, so there is no need to test those values.

A: This is the Ternary Operator. To quote:

<condition> ? <true-case-code> : <false-case-code>;

The ternary operator allows you to execute different code depending on
the value of a condition, and the result of the expression is the
result of the executed code.

What is the purpose of using the whole line where mcm gets a value?

So your line of code:
mcm = (n1 > n2) ? n1 : n2;

It means:
if (n1 > n2)
    mcm = n1;
else
    mcm = n2;


text:
Q: Show Alert Message When Input Is Too Short using jQuery I am trying to display an alert message when the input is shorter than given limit, using jQuery. Unfortunately, my code isn't working, therefore, seeking your help.
Here are the codes I am using.
HTML
<input type="textarea" name="message" id="message" row="20" col="50" />
<input type="submit" name="submit" id="submit" value="Send Message" />

JavaScript
<script type="text/javascript">
    jQuery(document).ready(function($) {
        $("input:submit[name='submit']").on("click",function() {
        var msgwords = $("input:textarea[name='message']").val().replace( /[^\w ]/g, "" ).split( /\s+/ ).length;
        var minwords = 10;
            if (comwords < minwords) {
                alert("Your Comment is too short.");
            }
        });
    });
</script>

A: You want to switch if(comwords < minwords) to if(msgwords < minwords)

Here's your fully working code. Change as you want.
<script type="text/javascript">
/* Use $ instead of `jQuery`, it's nicer */
$(document).ready(function() {
    /* Reference the button ID (it's unique...) */
    $("#submit").click(function(e) {
        /* Your function to replace works nicely */
        var msgwords = $("#message").val().replace( /[^\w ]/g, "" ).split( /\s+/ ).length;
        var minwords = 10;
        if (msgwords < minwords) {
            e.preventDefault();
            alert("Your Comment is too short.");
        }
    });
});
</script>

This code references the exact ID's (you can change this once you know it's working). Your split function checking for words instead of characters also works nicely. Finally, e.preventDefault() prevents the button from submitting if the comment is too short.

I'd also like to point out that you could use either e.preventDefault(); or return false, with the latter being the equivalent of e.preventDefault(); and e.stopPropagation();. This prevents that event from propagating (or "bubbling up") the DOM.

A: There are two problems.

*

*There's no such :textarea pseudo-selector.

*comwords is not defined.

You can drop :textarea from the selector anyways. And use msgwords instead of comwords.

I would do instead:

*

*Use .form() to bind to the submit event. Plus, preventing the form submission.

*Clean up leading and trailing spaces using String#trim.

*Make use of the id attribute of your elements ;)

Along these lines:
<form>
  <input type="textarea" name="message" id="message" row="20" col="50" />
  <input type="submit" name="submit" id="submit" value="Send Message" />
</form>

jQuery(function($) {
  $("form").submit(function () {
    var minwords = 10;
    /* Trim leading and trailing spaces */
    var message = $("#message").val().trim();
    var words = message.split(/\s+/).length;
    /* Disambiguous matches for an empty string  */
    if ((message == "") || (words < minwords)) {
      alert("Your comment is too short.");
      /* Prevent form submission by returning false */
      return false;
    }
    return true;
  });
});


text:
Q: How to split the components of a column (characters) into several numeric columns (1 and 0) in R? I have a database in this form:
Num_customer    Product label
1020            TCAR Active agent
1096            Agent-Family card
1067            Senior 20 CSC units
1034            TCAR Active agent
1011            TCAR Active agent
1022            Bike Park
1020            Bike Park
And I want to separate the product label column into 6 columns (the column names will be the product types) and assign for each Num_customer , numbers 0 if the product does not match and 1 matches.
What I want to get looks like this:
Num_customer     TCAR Active agent   Agent-Family card    Senior 20 CSC units    Bike Park
1020                1                    0                   0                     1
1096                0                    1                   0                     0
1067                0                    0                   1                     0
1034                1                    0                   0                     0
1011                1                    0                   0                     0
1022                0                    0                   0                     1
My data frame is large and there are 20 product types.
I will be grateful if you can help me to solve this problem!


text:
Q: SQL Query aggregate may not appear in WHERE clause (AVG) Hi I can't find a solution how to fix this problem.
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
where p.UnitPrice > AVG(p.UnitPrice)
group by p.UnitPrice

Should be like this : AVG is 28.3 so UnitPrice higher than 28.3
ProductName                        UnitPrice
Uncle Bob's Organic Dried Pears     30,00
Northwoods Cranberry Sauce          40,00
Mishi Kobe Niku                     97,00
Ikura                               31,00
Queso Manchego La Pastora           38,00
Alice Mutton                        39,00

Having also don't work
select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
group by p.UnitPrice
having p.UnitPrice > AVG(p.UnitPrice)

A: Use a subquery instead:
select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
where p.UnitPrice > (select avg(p2.UnitPrice)
                     from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p2
                    );

A: You need to use a subquery to compute average before compare it to unit price
select p.ProductName, p.UnitPrice
from northwind.dbo.products p
where p.UnitPrice>
(
    select AVG(p2.UnitPrice)
    from northwind.dbo.products p2
    group by p2.ProductName
    having p2.ProductName = p.ProductName
)

You should ensure your product name is unique or use the product key instead of name


text:
Q: How to access .Net MVC4 Mobile application through Iphone? I have started learning MVC4, and working on simple mobile site, but I am wondering how to open that a site through iPhone. Could anyone help me with this issue? Thanks in advance.

A: Open your project in Visual Studio's, in the solution explorer right click on your solution and select "Enable IIS Express". This will make sure you are using IIS Express to test your project. Then run your app to make sure it comes up in your browser like it did before, http://localhost:2121
Now, in Windows, go to Documents or My Documents, and you should see a directory called IISExpress. Inside this there is a directory called Config. Inside Config open the file applicationhost.config. This contains the settings for every project that is run on IIS Express.
Scroll down till you find your site inside the <sites> section. It will look something like this:
<sites>
        <site name="WebSite1" id="1">
            <application path="/">
                <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
            </application>
            <bindings>
                <binding protocol="http" bindingInformation="*:2121:localhost" />
            </bindings>
        </site>
</sites>

Remove the localhost from the bindingInformation so it will look like this:
<binding protocol="http" bindingInformation="*:2121:" />

Now save the file, and restart IIS Express. The easiest way is to just restart Visual Studios.
Make sure Windows or any firewall/anti-virus programs are not blocking the port of your web application, in my example it was 2121, and you should be good to go.
What we did was to tell IIS Express that any connection to this port is to go to this site/application. So if you setup your router to forward the port to your development computer you/anyone can access your site as long as your working on it from your development system. This is nice when you make changes and just want to check with someone outside you LAN without having to deploy the site.
So now you can access the application/site from your IPhone or any other device while it is running on your development system. If your IPhone is not connected in your local area network, you will need to add the port to the port forwarding on your router as I mentioned above then access your site by your IP address colon port number. You can also add a sub-domain to a website you own (or a free online DNS system) so you can access your dev application/site by going to http://dev.somedomain.com:2121

A: I guess the easiest way to test the site you are developing is finding out your local IP and configuring your IIS to serve your development site from that IP.

A: looks little bit late anyways for other peoples. we can use iis express web server to view site from remote here is Accessing local sites from Lan IIS Express step by step guide for this problem hope this will help

A: Visual Studio's built-in "Web Development Server" does not allow remote connections.  You will need to host your application on IIS to be able to access the site from another computer or your iPhone.


text:
Q: Multiple password forms + password completion On a website I'm working we have an onsite login and a private login, the problem I'm having is that Firefox doesn't seem to be able to differentiate between these login forms.
Does anybody know how I can make clear that these are different logins?
I already tried giving the form fields different names and ids, ex: onsite_login and login but without success.
edit: my form-tags are not being mixed up, they aren't even on the same page
The two forms on the different pages
<form method="post" action="/en/login/1">
<fieldset>

        <input type="hidden" value="login" name="form"/>
        <input type="hidden" value="en" name="redirect"/>
        Username*
        <input type="text" class="input-text" maxlength="255" value="" name="onsite_username" id="onsite_username"/>
        Password*
        <input type="password" class="input-password" maxlength="255" value="" name="onsite_password" id="onsite_password"/>
        <input type="submit" value="Log in" name="submit" class="input-submit"/>

</fieldset>
</form>

and
<form method="post" action="">
<fieldset>
    <input type="hidden" value="login" name="form"/>

        Username
        <input type="text" class="input-text" value="" name="username" id="username"/>

        Password
        <input type="password" class="input-password" value="" name="password" id="password"/>

    <input type="submit" value="Aanmelden" class="input-submit"/>
</fieldset>
</form>

A: Apparently this is not possible due to the way Firefox stores its passwords.
A password-manager entry is stored with the following data

*

*The username (encrypted and secured with Firefox Master Password).

*The password (encrypted and secured with Firefox Master Password).

*The hostname of the webpage containing the login form.

*The hostname of the webpage to which the form data has been submitted.

Thus Firefox does not distinguish between the two loginfields on my page.

A: I've not yet heard about a multiple form problem in Firefox.
But it could be that Firefox mixed up your 2 login forms if there is another tag around that is not closed properly.
I've had that problem myself with
 tags and a not properly closed
 around it.

A: I'm not sure.. but try to give them a different ID like <form method="POST" action="#" id="login1">


text:
Q: Are geographic plots made with matplotlib.basemap copyrighted? I'm using python to make some plots for a paper, using matplotlib.Basemap.
The plots look similar to the first two examples in the library's example gallery.
The journal to which I'm submitting the paper worry that the map underlying the plot is copyrighted, and are reluctant to accept it. I can find no mention of copyright on plots in the copyright section on the github repo, however, I'm unsure whether checking that is sufficient to establish that the plots I produce are not copyrighted.
Does anyone know basemap plots rely on some copyrighted shapefiles or similar?

A: If the plots are or are nearly identical, then they are Copyrighted:

Copyright (C) 2011 Jeffrey Whitaker
Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notices appear in all copies and that both the copyright notices and this permission notice appear in supporting documentation.
THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

and

©2011, Jeffrey Whitaker; 2016 The matplotlib development team.

Jeffery Whitaker's 2011 claim and license allows for redistribution given the proper attribution.

The results(output) of a software program(unless stated otherwise in the EULA i.e. academic licensing), all rights belong to you. (Since the code is on github as a public open source repository, no such EULA restrictions apply)
As long as your data presented on the plots is unique, I do not see a copyright violation.
If they are not unique, give full attribution as required by license.
Infringement suits may be covered by fair use doctrine.

I would always suggest contacting a lawyer in IP matters.
None of the above should be considered legal advice, merely my informed personal opinions.


text:
Q: MIT Python course 6.00.1X Lecture 8 Converting letter grades to numeric grades by using exception clause This issue is from MIT Python course 6.00.1X, Lectrue 8. I have tried two slightly different pieces of code. Both of them are for computing the average grade of each student.
The first code does not take into account that there might be letter grades, the second code does. Actually, I expected to get lower grades for the student Wilma when running the second code. Because I set up returning 90.0 for letter grade 'A' in the second one. However, the result shows that in the second code, Wilma's average grade is even higher than the first grade,which is 25.0 compared with 17.466666666666665 in the first code.
I cannot figure out where goes wrong. I really appreciate any help and suggestion.
#the first code
def getsubjectStats(subject, weights):
    return[[elt[0], elt[1], avg(elt[1], weights)]
           for elt in subject]

def dotProduct(a, b):
    result = 0.0
    for i in range(len(a)):
        result += a[i]*b[i]
    return result

def avg(grades, weights):
    try:
        return dotProduct(grades, weights)/len(grades)
    except ZeroDivisionError:
        print('no grades data')
        return 0.0

test = [[['fred', 'flintstone'], [10.0, 5.0, 85.0]],
        [['barney', 'rubble'], [10.0, 8.0, 74.0]],
        [['wilma', 'flintstone'], [8.0, 10.0, 96.0]],
        [['dino'], []]]
weights = [.3, .2, .5]

print(getsubjectStats(test, weights))

#the second code
def getSubjectStats1(subject,weights):
    return [[elt[0], elt[1], avg1(elt[1], weights)]
           for elt in subject]
def dotProduct1(a, b):
    result = 0.0
    for i in range(len(a)):
        result += a[i] * b[i]
    return result
def avg1(grades, weights):
    try:
        return dotProduct1(grades, weights)/len(grades)
    except ZeroDivisionError:
        print('no grades date')
        return 0.0
    except TypeError:
        newgrades = [convertLetterGrade(elt) for elt in grades]
        return dotProduct1(newgrades, weights)/len(newgrades)

def convertLetterGrade(grade):
    if type(grade) == int:
        return grade
    elif grade == 'A':
        return 90.0
    else:
        return 60.0

test0 = [[['fred', 'flintstone'], [10.0, 5.0, 85.0]],
        [['barney', 'rubble'], [10.0, 8.0, 74.0]],
        [['wilma', 'flintstone'], [8.t0, 10.0, 'A']],
        [['dino'], []]]
weights0 = [.3, .2, .5]

print(getSubjectStats1(test0, weights0))

I expect:

the first one:
no grades data
[[['fred', 'flintstone'], [10.0, 5.0, 85.0], 15.5], [['barney', 'rubble'], [10.0, 8.0, 74.0], 13.866666666666667],
[['wilma', 'flintstone'], [8.0, 10.0, 96.0], 17.466666666666665], [['dino'], [], 0.0]]

the second one:
...[['wilma', 'flintstone'], [8.0, 10.0, 'A'], 16.466666666666665]...

Actually, the first one meets my expectation, but actual output of the second one is ... [['wilma', 'flintstone'], [8.0, 10.0, 'A'], 25.0]...

A: In convertLetterGrade() you are checking if grade is an int but the grade argument passed is a float. Therefore, the else condition is called and the numeric grades are converted to 60.0.
To fix, in convertLetterGrade() change
if type(grade) == int:
to
if type(grade) == int or type(grade) == float:


text:
Q: Mutt in bash script raises an error in python (flask) application I believe that the main problem here is with mutt command:
mutt -s "Title" -a $file -- "$address" < $DIR/message.txt.
If I delete it from the script, there is no error so maybe someone will find out what is going on.
This is a python application using flask. Here is the problematic method:
@app.route('/send', methods=['POST'])
def send():
start_date = '2016-10-20'
end_date = '2016-10-28'
path = os.path.dirname(os.path.realpath(__file__))
script = path + '/script.sh'
address = 'my@mail.com'
subprocess.check_call([script, start_date, end_date, address])
return json.dumps({
    'message': 'Your message is sent!'
})

Subprocess runs script :
#!/bin/bash
start_date="$1"
end_date="$2"
address="$3"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
$file="My_super_file"
out=$(R -e "rmarkdown::render('$DIR/generate_file.Rmd', output_file = $file)")
mutt -s "Title" -a $file -- "$address" < $DIR/message.txt

When the file is generated, I get such error:
[2016-10-28 16:03:06,857] ERROR in app: Exception on /send [POST]
Traceback (most recent call last):
  File "/Users/admin/anaconda2/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/admin/anaconda2/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/admin/anaconda2/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/admin/anaconda2/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/admin/anaconda2/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "Users/admin/mydemoapp/app/appdemo/views.py", line 18, in send
    subprocess.check_call([script, start_date, end_date, address])
  File "/Users/admin/anaconda2/lib/python2.7/subprocess.py", line 541, in check_call
    raise CalledProcessError(retcode, cmd)
CalledProcessError: Command '['/Users/admin/mydemoapp/app/appdemo/script.sh', '2016-10-20', '2016-10-28', u'my@mail.com']' returned non-zero exit status 1


text:
Q: DNN Error - General Exception - AbsoluteURL I have an DNN site where i get this error alot (and i mean alot) and i cant find the source to the problem!
Is there anyone who has an idea of where to start looking or how to debug this?
I cant find the fault its impossible.. :(
DNN PLATFORM
v. 09.01.01 (129)
4.6 .NET FRAMEWORK

General Exception

Site name
AbsoluteURL /Default.aspx DefaultDataProvider DotNetNuke.Data.SqlDataProvider
AbsoluteURL:/Default.aspx

DefaultDataProvider:DotNetNuke.Data.SqlDataProvider, DotNetNuke

ExceptionGUID:d1a7b7bf-b7fa-4b86-ab6d-a3efabebf994

AssemblyVersion:

PortalId:-1

UserId:-1

TabId:-1

RawUrl:

Referrer:

UserAgent:

ExceptionHash:jn6m7y6lLHEjghJrIXICAWzADhA=

Message:Value cannot be null. Parameter name: type

StackTrace:

at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.Activator.CreateInstance(Type type) at DotNetNuke.UI.Skins.Pane.IsVesionableModule(ModuleInfo moduleInfo) at DotNetNuke.UI.Skins.Pane.InjectModule(ModuleInfo module) at DotNetNuke.UI.Skins.Skin.InjectModule(Pane pane, ModuleInfo module)
InnerMessage:

InnerStackTrace:

Source:mscorlib

FileName:

FileLineNumber:0

FileColumnNumber:0

Method:

Server Name:SERVERNAME

A: The root cause of this issue is because "PortalAliasId" column in "TabUrls" table consists of value "1", by default this should be NULL instead.
https://dnnsupport.dnnsoftware.com/hc/en-us/articles/360021667014-Accessing-the-page-settings-fails-to-retrieve-content


text:
Q: Increasing JavaFX WebGL Performance I'm working on this browser in JavaFX. However.. When you visit a page that is using WebGL, the page loads but is extremely choppy and basically unusable.
So the question is, how would I increase the performance of a webpage using WebGL so the users can navigate the page smoothly?
Here's my demonstration
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

  public final class App extends Application {

  @Override
  public void start(Stage stage) throws Exception {
        Group group = new Group();
        WebView browser = new WebView();
        WebEngine engine = browser.getEngine();

        engine.load("http://rune.tools/");

        group.getChildren().add(browser);

        Scene scene = new Scene(group, Color.BLACK);

        stage.setScene(scene);
        stage.setTitle("JavaFX WebGL");
        stage.centerOnScreen();
        stage.sizeToScene();
        stage.setResizable(false);
        stage.show();
  }

  public static void main(String[] args) {
        launch(args);
  }

  }

A: JavaFX 8 doesn't support WebGL, so you can't increase WebGL performance of JavaFX, because it has nothing to increase.


text:
Q: Accept Post request to nodejs from django I am making a post request from django to nodejs
v = {}
v['id'] = 'test'
y=requests.post('http://localhost:3000',params=v)

How can I parse this data in nodejs? Below is my code, but it shows undefined.
app.post('/', function (req, res) {
    console.log(req.body.id)  //this shows Cannot read property 'id' of undefined
    res.send('hello')
})

A: note that with python-requets the POST verb expects a dictionary as data
v = {}
v['id'] = 'test'
y=requests.post('http://localhost:3000',data=v)

params is generally used by the get verb. Having said that I am not sure why you want to connect django and node in this way. Wouldn't it be easier to write the entire thing in one or the other?
Have you enabled the body parser?
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies


text:
Q: how to create factory function (returning rvalue) I wrote this piece of code:
class widget_12 {
public:
    //reference qualifiers example
    void dowork()&
    {
        std::cout << "*this is lvalue\n";
    }; // this version of dowork applies when *this is lvalue
    void dowork()&&
    {
        std::cout << "*this is rvlaue\n";
    }; // -||- *this is rvalue
    widget_12&& make_widget()
    {
        //TODO
    }
};

I want to test reference qualifiers, therefore I need to create a function that will return the rvalue of widget_12, could you show me how to do it?
I am basically trying to make this call:
make_widget().dowork();

A: Were you trying something like this?
https://godbolt.org/z/TPEWe3eKv
#include <iostream>

class widget_12 {
public:
    //reference qualifiers example
    void dowork() &
    {
        std::cout << "*this is lvalue\n";
    }; // this version of dowork applies when *this is lvalue

    void doword() &&
    {
        std::cout << "*this is rvlaue\n";
    }; // -||- *this is rvalue

    static widget_12 make_widget()
    {
        return widget_12();
    }
};

int main()
{
    widget_12 w;
    w.dowork();
    //w.doword(); // error
    widget_12::make_widget().doword();
    //widget_12::make_widget().dowork(); // error
    return 0;
}


text:
Q: Why HTML tag closing before loop automatically in PHP code I am using PHP loop to display a list of values,
My code is something like this
if($v1 != $v2){
    $k= $k + 1;
    echo '
';
}

echo '
xyz xyz
';
}

if($v1 != $v2){
    echo '
';
}

It should display result like

xyz xyz

xyz xyz

xyz xyz

but is displaying result

xyz xyz

xyz xyz

xyz xyz

 tag is automatically closing after first loop run, I am new at stackoverflow, hope you understand my issue.
Its my complete PHP code
for ($i = 0; $i < $count; $i++) {
    $j = $i + 1;
    $v2 = $v1;
    $v1 = $data3['body']['asinVariationValues'][$i]['variationName'];
    $img = $data3['body']['asinVariationValues'][$i]['variationImageURL'];
    $val = $data3['body']['asinVariationValues'][$i]['variationValue'];

    if($v1 != $v2){
        $k= $k + 1;
        echo ''. $v1 .'
';
    }

    if(!empty($img)){
        echo '

';
    }else{
        echo '
'.$val.'
';
    }

    if($v1 != $v2){
        echo '
';
    }
}

A: Your check to show the opening ul tag is the same as your check to show the closing ul tag:    $v1 != $v2, so every time the opening tag shows the closing tag will show.
Can you change the opening tag check to:
    if($i == 0){
        $k= $k + 1;
        echo ''. $v1 .'
';
    }

and the closing tag check to:
    if($j == $count){
        echo '
';
    }

This way the opening tag will only be added in the first loop, and the closing tag will only be added on the last run of the loop.


text:
Q: Private inheritance usage as described in "The C++ Programming Language" In The C++ Programming Language, 4th Edition, at §20.5.2 "Access to Base Class" (page 605), it says (regarding private inheritance):

private bases are most useful when defining a class by restricting
  the interface to a base so that stronger guarantees can be
  provided.For example, B is an implementation detail of Z .The Vector
  of pointers template that adds type checking to its Vector base
  from §25.3 is a good example.

It's not clear what Bjarne Stroustrup is trying to say here. How can be a class be defined by restricting "the interface" to a base? What does he mean by "stronger guarantees"?

A: Lets take a very simple example:
// A simple class with a *public* member
class A
{
public:
    int a;
};

// Use private inheritance
class B : private A
{
public:
    int b;
};

// Use public inheritance
class C : public A
{
public:
    int c;
};

// ...

B my_b;
my_b.a = 0;  // Invalid, the member a is private due to the private inhericance

C my_c;
my_c.a = 0;  // Valid, because the inheritance is public

The private inheritance restricts access to the members of the base class. Even if the A::a member variable is public, due to the private inheritance it becomes private in the sub-class B.

A: Let's stay with the example of the vector. A vector is just a container of Ts. Now let's say you want to build a type that behaves just like a vector, but adds some additional runtime checks. I don't have my copy of TC++PL at hand right now, so let's just make up a constraint: For example, let's say your vector is only allowed to hold even numbers. Attempting to insert an odd number will result in a runtime error. Let's call this new class even_vector and the version without the runtime checks base_vector.
even_vector provides stronger runtime guarantees than base_vector: It is guaranteed that all of its elements are even.
Assuming that your base_vector is designed to work nice as a base class (which std::vector typically does not), you might now be tempted to use public inheritance to implement even_vector in terms of base_vector. After all, the functionality is the same, you simply have some additional runtime checks in the even_vector case on top of the functionality provided by base_vector. However, if you were to use public inheritance here, you would violate the Liskov Substitution Principle: You cannot use an even_vector wherever you use a base_vector. In particular, the even_vector will break in cases where you are inserting odd numbers into a base_vector. This is bad, as now all code that is written for base_vector must account for the fact that some of the base_vectors cannot deal with odd numbers.
With private inheritance you do not have this problem: Here the fact that even_vector inherits from base_vector is a detail of the implementation. Clients cannot use even_vector where a base_vector is expected, so the problem from above does not occur, but we still get the benefits of code reuse.
That being said, using private inheritance for code reuse is a practice that is discouraged by many. An arguably better way would be to use composition here instead, that is, add a private base_vector member to even_vector instead. The advantage of that approach is that it severely reduces coupling between the two classes, as even_vector is no longer able to access any non-public parts of base_vector.

A:
how can be a class be defined by restricting "the interface" to a base?

By making the inheritance private. When the inheritance is private, the interface of the base class is restricted to the member functions and not available outside. The access specifier can be given in the list of bases:
class A : private B
//        ^^^^^^^

What does he mean by "stronger guarantees"?

Any guarantee that is not given by the base, or is a superset of a guarantee given by the base.
For example, the guarantee that "behaviour is always well defined" is stronger than "Behaviour is well defined only if input is not null". Another example: "The function does not throw" is stronger than "The function will not throw unless the copy constructor throws".

A: Allow us to look at a possible situation with interfaces to help build up the picture.
class poison {
  public:
    virtual void used() = 0;
};

class food {
  public:
    virtual void eat();
  protected:
    void poisonConsumed(poison& p);
}

class cheese : public food, private poison {
  public:
    virtual void eat() override {
      poisonConsumed(*this);
    }
  private:
    void used() override;
}

This presents cheese to the outside world as 'not a poison' - ie nothing outside the class can know that it's a poison, and it could be made 'not a poison' to no impact on anything using it.
The cheese however, can pass itself to anything expecting a poison which is then free to call used(); even though it's private in cheese.


text:
Q: dataframe match column I have this DF: Columns: df=pd.DataFrame(columns=["a","b","c","d","e","f","g"])
and this : data=["a:42","b:43","c:22","d:41","a:21","b:14" ,"c:12","e:14" ,"f:7","a:0" ,"d:1","f:3","a:6" ,"b:0","c:9","g:8"   ]
I need
for d in data:
   spli=d.split(":")
   colum=spli[0]
   value=spli[1]
   df[colum] = value

waiting for this result
["a"  "b"   "c"   "d"   "e"    "f"    "g"  ]
  42   43    22    41   nan    nan     nan
  21   14    12    nan   14     7      nan
  0    nan   nan    1    nan     3     nan
  6     0     9    nan   nan   nan      8

A: .loc can help you here:
last_c = 'z'   # Enter some ordinally large string
r = -1
for x in data:
    c,v = x.split(':')

    if c <= last_c:
        r += 1

    df.loc[r,c] = v
    last_c = c

     a    b    c    d    e    f    g
0   42   43   22   41  NaN  NaN  NaN
1   21   14   12  NaN   14    7  NaN
2    0  NaN  NaN    1  NaN    3  NaN
3    6    0    9  NaN  NaN  NaN    8
4  NaN   14    9  NaN  NaN  NaN  NaN

I added an additional line to show a new line (row) starting with something other than 'a'.

A: You need a non-empty df to set a column to a certain value.  You can create a new df for a row with all nans, and then set column values.  You can test whether you need a new row by comparing the numeric value of a, b, c ... with ord().  Append the df_row to the master df for each new row, and once at the end of the loop.  Here's one way to do it:
df = pd.DataFrame(columns=["a", "b", "c", "d", "e", "f", "g"])

data = ["a:42", "b:43", "c:22", "d:41", "a:21", "b:14", "c:12", "e:14", "f:7", "a:0", "d:1", "f:3", "a:6", "b:0", "c:9", "g:8"]

df_this_row = pd.DataFrame([[np.NAN, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN]], columns=["a", "b", "c", "d", "e", "f", "g"])
first_col, first_val = data[0].split(':')
df_this_row[first_col] = int(first_val)

for i in range(1, len(data)):
    col, val = data[i].split(':')
    prev_col = data[i-1].split(':')[0]
    if ord(col) <= ord(prev_col):
        # you are in next row, eg f was previous col, and you have col b
        df = df.append(df_this_row)
        df_this_row = pd.DataFrame([[np.NAN, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN]], columns=["a", "b", "c", "d", "e", "f", "g"])
    df_this_row[col] = int(val)

df = df.append(df_this_row).reset_index(drop=True)

print(df)
#     a    b    c    d    e    f    g
# 0  42   43   22   41  NaN  NaN  NaN
# 1  21   14   12  NaN   14    7  NaN
# 2   0  NaN  NaN    1  NaN    3  NaN
# 3   6    0    9  NaN  NaN  NaN    8

A: Is it posible to convert your data to a list of dictionary like:
data = [{"a":42,"b":43,"c":22,"d":41},
 {"a":21,"b":14 ,"c":12,"e":14 ,"f":7},
 {"a":0 ,"d":1,"f":3},
 {"a":6 ,"b":0,"c":9,"g":8}]

Then, you can create a dataframe by:
df=pd.DataFrame(data).


text:
Q: Is it possible to set the icon or launch screen in Xcode programmatically? I have an app that would get used by different clients with slight tweaks for each client, including a different icon and launch screen. Is it possible to program the app to grab those images off of a server and use them, or would I need to manually put them into each iteration of the app the normal way?

A: It is impossible to change the App Icon programmatically using only public API as well as change launch screen at runtime. You may create some kind of "fake"-launch screen, that will be the first UIViewController in your app and will dismiss automatically short after being presented.


text:
Q: Change Discord Bot (Python) game or activity I am trying to repair my Discord Bot and I cannot get any further can someone help me there?
    await client.change_presence(activity=discord.Activity(name="<hilfe for help."))

The code should change the activity but it does nothing and just gives me a error.
I don't know what to change to get it working.

A: Here it is. It have to be discord.Game not discord.Activity
@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Game('bread'))


text:
Q: Circuit to switch negative to negative, or positive to positive connection I am wondering if there is a negative to negative (and/or positive to positive) switch.  I know mechanical relays work, but I need an electronic way of doing it.  Is there a transistor that functions as such? or any other semiconductors?
Edit
I have 2 batteries, 12V  (both the same), similar to the link below.  They are connected in parallel.  I need to switch the positive and negative connections of the batteries, to break the connection. I would like to have these switched controlled by a micro-controller and for it to be electronic.
Any help is appreciated and thanks!

https://www.amazon.com/Power-Sonic-PS-1290-Rechargeable-Battery-Terminals/dp/B002L6R130/

A:
I am wondering if there is a negative to negative (and/or positive to positive) switch.

simulate this circuit – Schematic created using CircuitLab
Figure 1. A double-pole, single-throw (DPST) switch can be used to connect negative to negative and positive to positive.

I know mechanical relays work, but I need an electrical way of doing it. Is there a transistor that functions as such? or any other semiconductors?

Perhaps you mean that you are looking for an electronic solution rather than an electro-mechanical solution. The answer is yes but we don't have enough information in your question.


text:
Q: Button is set to Null and NullPointerException is generated in Android I'm trying to make an app with different intents. I've got two of the ready. I want that a button in the 1st intent makes the 2nd intent to appear.
The issue is that the button is always set to null and throws a NullPointerException when the app is run
My .java classes are:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(vocabulario);

   //....

    Button buttonVocabulary = (Button) findViewById(R.id.buttonVocabulary);
    Button holaPlayerBtn = (Button) findViewById(R.id.holaPlayerBtn);
//...
    buttonVocabulary.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view)
        {
//Se abre un nuevo Intent con el primer botón
            try
            {
                {
                    Intent myIntent = new Intent(view.getContext(), Vocabulario.class);
                    startActivityForResult(myIntent, 0);}
            } catch (Exception e) {
                e.printStackTrace();
            }
        }});

My main.xml file is:
   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:id="@+id/adViewContainer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            />

        <Button
            android:id="@+id/buttonVocabulary"
            android:text="@string/vocabulario"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:nestedScrollingEnabled="true" />
    </LinearLayout>
</LinearLayout>

In my AndroidManifest.xml there is an element that says:
<activity android:name=".Vocabulario"
        android:label="@string/vocabulario"/>

There's something I'm doing wrong. Could you help me with this issue?
Thanks in advance.

A: change
setContentView(vocabulario);

To
setContentView(R.layout.main);

A: In your onCreate method you should set the view to the layout:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ...
}

A: @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main); //set layout id

    //...
    findViewById(R.id.buttonVocabulary).setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view){
            try {
                Intent i = new Intent(view.getContext(), Vocabulario.class);
                startActivityForResult(i, 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}


text:
Q: flex popup not displayed properly In my flex application, there is a popup that behaves randomly. Most of the time the popup works correctly, but sometimes its content doesn't render correctly. Only some labels are shown on a greyish background. Screenshots:
Correct popup:

Incorrect popup:

I use the function PopUpManager.createPopUp() to create the popup.
Does anyone have any idea why this happens? Thanks for reading!


text:
Q: Process cannot access the file "project.dll" because it is being used by another process I need to deploy a wsp file in VS, but I am not able to do that because I am getting the error in my question's title, I tried doing IIS reset, restarting my development machine.
Any ideas?

A: The reason this error occurs is because the assembly is being used, just like the message says. To resolve the error, you just need to figure out what is using the assembly, and stop it from doing so.
The real question here is "Where is the assembly being used?"
If the project doesn't build in VS (click Build only, not Deploy), you know the issue is on your dev box. One fix in this instance is to go to Tools > Options > Projects and Solutions > Build and Run. Then reduce the "maximum number of parallel project builds" to 1. This will make your build slower, but can fix this issue in some instances.
If the project builds on dev, but throws the error on deploy to a remote farm, your solution is in use when you try to deploy "over it". You need to retract the solution and redeploy the new build.


text:
Q: $A^TAx = A^Tb$ is always consistent, independent of $Ax=b$? Suppose $A$ is a $m\times n$ matrix, $x$ is a vector of unknowns and $b$ is a vector of know entries. Whether $Ax=b$ is consistent or not ,But $A^TAx=B$ is always consistent.
Is that above statement correct? or Am I missing anything?

A: I will assume you mean $A^Tb$ by "B". Whether $Ax = b$ is asking if b is in the image of the linear map which is multiplication by A. If b is zero, asking for the solutions to $Ax = b$ is the same as asking what x's are in the kernel of "multiplication by A" (we call this linear map $L_A$ by the way). By multiplying both sides by $A^T$ and asking what x's solve the equation $A^TAx = A^Tb$, we should assume A is noninvertible (otherwise it is the same question as what the solutions to Ax = b are). You can also think of this as the kernel of the linear map $(L_A)^TL_A(x) - A^Tb$ (where $(L_A)^T = L_{A^T}$).Additionally,
if $A = \begin{pmatrix} 0 & 1\\ 0 & 0\end{pmatrix}$, $b = \begin{pmatrix} b_1\\b_2\end{pmatrix}$, and $x = \begin{pmatrix} x_1\\x_2\end{pmatrix}$, $A^TA = A^Tb$ iff $Ax = b$ (you should check that). So the relationship between the two equations can be more or less whatever, other than the fact that we must have $Ax = b$ implies $A^TAx = A^Tb$ (by just multiplying both sides of the first equation by $A^T$).
(also I am assuming the entries are in a subfield of the complex numbers).

A: If you are dealing with the reals (complex is similar) we have
$\mathbb{R}^m = {\cal R}A \oplus \ker A^T$.
In particular, we can decompose $b$ (uniquely) as $b=b_1+b_2$ where
$b_1 \in {\cal R}A, b_2 \in\ker A^T$.
Hence there is some $x$ such that $Ax = b_1$, and $Ax-b_1 = b_2$ and so
$A^T(Ax-b) = 0$.

A: I suppose the underlying field be $\mathbb{R}$.
It seems that you are a beginner, so this approach may be more friendly.
First is to observe that $A^TAX=0 \iff AX = 0$. (I shall leave this bit of work to you.) So if a linearly independent set $\langle X_1,X_2,\cdots,X_r\rangle$, where $r=\mathrm{rank}\;A$, spans the column space of the matrix $A$, then $\langle AX_1,AX_2,\cdots,AX_r\rangle$ spans the column space of $A^T$ as well. Since $A^Tb$ is always a vector in the column space of $A^T$, it can be derived by a linear combination of $\langle X_1,X_2,\cdots,X_r\rangle$.


text:
Q: Vetiver Error when connecting to board: Error in order(results$name) : argument 1 is not a vector Summary/Context
I am attempting to deploy a model from R to Google Cloud.
I am following these steps/tutorial from the vetiver GitHub.
I am using the sample data provided in the tutorial except I am attempting to deploy the model to Google Cloud, see code & error below:
library(parsnip)
library(workflows)
library(vetiver)
library(pins)
data(Sacramento, package = "modeldata")

rf_spec <- rand_forest(mode = "regression")
rf_form <- price ~ type + sqft + beds + baths

rf_fit <-
  workflow(rf_form, rf_spec) %>%
  fit(Sacramento)

v <- vetiver_model(rf_fit, "sacramento_rf")
v

model_board <- board_register_gcloud( name = "lead-time-model"
                                     ,bucket = "pro_lead_time_prediction_bucket" )

model_board

The error I get when I run model_board is:
Error in order(results$name) : argument 1 is not a vector

Part of my confusion is that my vetiver model object ran without issue:
v
-- sacramento_rf - <bundled_workflow> model for deployment
    A ranger regression modeling workflow using 4 features

Other error:
model_board %>% pin(v)
Error in path_tidy(.Call(fs_path_, lapply(args, function(x) enc2utf8(as.character(x))),  :
  Total path length must be less than PATH_MAX: 260

Could the problem stem from authenticating or not connecting correctly to gcloud? I have SDK installed and authenticated as well.


text:
Q: Wordpress - Upload media to different server I've split the resources on a WP site into two servers: Server A with administration files, Server B with public files. They are connected by the data base.
Are there any way that will cause media that I upload from the WP admin installation on Server A to be stored over on Server B? Whit this, that media will be served from Server B ("public site").
If possible, other than through an FTP connection, my client doesn't want a FTP in the public site :-(
Thanks in advance!

A: First, create a remote storage service where you can post the file and return a URL addressing the file on server B. Then you can use wp filters to attain the url from server A.
You can hook into this filter: "wp_handle_upload"
    apply_filters{
      'wp_handle_upload'
       array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'upload'
     )

just replace the URL to the new one


text:
Q: UISearchDisplayController the results are delayed by 3-6secs When I type letters into my Search I get lag for about 4secs and can`t do anything. Everything others work good. UISearchDisplayController find me what I want, segue works good . I am not sure if it is about memory or some mistake in my code. Can anyone help me? Thanks
My code
TableViewController.m
@implementation TableViewController

@synthesize colorsTable;
@synthesize searchBar;
@synthesize searchController;
@synthesize searchResults;

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showDetail"]) {
        {
            DetailViewController *sdvc = (DetailViewController *)[segue destinationViewController];

            if(self.searchDisplayController.active) {
                NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
                PFObject *object = [self.objects objectAtIndex:indexPath.row];

                object = (PFObject *)[[self searchResults]objectAtIndex:[[[[self searchDisplayController]searchResultsTableView]indexPathForSelectedRow]row]];
                sdvc.detailItem = object;

            }   else {

                NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
                PFObject *object = [self.objects objectAtIndex:indexPath.row];
                DetailViewController *detailViewController = [segue destinationViewController];
                detailViewController.detailItem = object;

            }

        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self performSelector:@selector(runThisMethod) withObject:nil afterDelay:1.9f];
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];

    self.tableView.tableHeaderView = self.searchBar;

    self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];

    self.searchController.searchResultsDataSource = self;
    self.searchController.searchResultsDelegate = self;
    self.searchController.delegate = self;

    CGPoint offset = CGPointMake(0, self.searchBar.frame.size.height);
    self.tableView.contentOffset = offset;

    self.searchResults = [NSMutableArray array];

-(void)filterResults:(NSString *)searchTerm {

    [self.searchResults removeAllObjects];

    PFQuery *query = [PFQuery queryWithClassName: self.parseClassName];
    [query whereKeyExists:@"MestoName"];  //this is based on whatever query you are trying to accomplish
    [query whereKey:@"MestoName" containsString:searchTerm];

    NSArray *results  = [query findObjects];

    NSLog(@"%@", results);
    NSLog(@"%u", results.count);

    [self.searchResults addObjectsFromArray:results];
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    [self filterResults:searchString];
    return YES;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (tableView == self.tableView) {
        //if (tableView == self.searchDisplayController.searchResultsTableView) {

        return self.objects.count;

    } else {

        return self.searchResults.count;

    }

}
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
    tableView.rowHeight = 90.0f;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {

    static NSString *uniqueIdentifier = @"colorsCell";

    CustomCell *cell = nil;

    cell = (CustomCell *) [self.tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];

    [cell.imagevieww setImageWithURL:[NSURL URLWithString:[object objectForKey:@"ImageURL"]]
                    placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    cell.cellTitle.text = [object objectForKey:@"MestoName"];
    cell.cellDescript.text = [object objectForKey:@"MestoSubname"];

    if (!cell) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"colorsCell" owner:nil options:nil];

        for (id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[CustomCell class]])
            {
                cell = (CustomCell *)currentObject;
                break;
            }
        }
    }

        if (tableView == self.tableView) {
            cell.cellTitle.text = [object objectForKey:@"MestoName"];
        } else {

            PFUser *obj2 = [self.searchResults objectAtIndex:indexPath.row];
            PFQuery *query = [PFQuery queryWithClassName:@"Mesta"];
            PFObject *searchedUser = [query getObjectWithId:obj2.objectId];

            NSString *boottext = [searchedUser objectForKey:@"MestoName"];
            cell.cellTitle.text = boottext;

            NSString *bootsubtext = [searchedUser objectForKey:@"MestoSubname"];
            cell.cellDescript.text = bootsubtext;

            NSString *bootimage = [searchedUser objectForKey:@"ImageURL"];
            [cell.imagevieww setImageWithURL:[NSURL URLWithString:bootimage]];

            NSLog(@"Content: %@", boottext);

        }
            return cell;

        }

@end

A: For everyone, who have the same problem. I have got already the solution. I rewrote all my code and it is finally working.
Here`s the code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {

    NSString *uniqueIdentifier = @"MainCell";
    CustomCell3 *cell = nil;
    cell = (CustomCell3 *) [self.tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];

    if (!cell) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MainCell" owner:nil options:nil];

        for (id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[CustomCell3 class]])
            {
                cell = (CustomCell3 *)currentObject;
                break;
            }
        }
    }

    if (tableView == self.tableView) {
        cell.MainTitle.text = [object objectForKey:@"CountryTitle"];
        cell.DescriptTitle.text = [object objectForKey:@"DescriptTitle"];
        [cell.FlagTitle setImageWithURL:[NSURL URLWithString:[object objectForKey:@"ImaURL"]]
                       placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    };

if(tableView == self.searchDisplayController.searchResultsTableView) {

        PFObject *searchedUser = [self.searchResults objectAtIndex:indexPath.row];
        NSString *content = [searchedUser objectForKey:@"CountryTitle"];
        NSString *desco = [searchedUser objectForKey:@"DescriptTitle"];
        cell.DescriptTitle.text = desco;
        cell.MainTitle.text = content;
        NSString *image = [searchedUser objectForKey:@"ImaURL"];

    [cell.FlagTitle setImageWithURL:[NSURL URLWithString:image]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

        };

        return cell;
    }


text:
Q: Displaying an image in html from persistent browser file storage So I saved an image into the browser LocalFileSystem and the images is accessible if I input the following link in the browser
filesystem:http://192.168.1.6:3000/persistent/downloaded-image.png

However when I put the link into a  tag, the browser can't open the image.
So when I go into the inspect elements and right click on the link as so:
http://prntscr.com/n089n5
It takes me to
http://192.168.1.6:3000/filesystem:http:/192.168.1.6:3000/persistent/downloaded-image.png

Any help would be greatly appreciated!
EDIT:
This is how I'm displaying the image
function displayImageByFileURL(fileEntry) {

    var img = document.createElement("img");
    img.src = fileEntry.toURL(); //
    document.getElementById("console").appendChild(img);
}


text:
Q: Team Provisioning Profile-signed OS X app crashes with Code Signature Invalid error I have an in-house OS X app that I want to share with my co-workers. My app uses Maps, so therefore I need to codesign it otherwise Maps feature doesn't work.
I'm signing my app with my team provisioning profile, containing Hardware UUID's of all our Macs:

We are 4 people. On my Mac and one of my friends' Mac, it runs perfectly. On the other two, they are getting a codesign error:
EXC_CRASH (Code Signature Invalid)
I've seen Mac OS X app crash with Code Signature Invalid error and Developer ID signed OS X app crashes on start with Code Signature Invalid and I'm doing everything the same as they've done there. Why are they getting invalid code signature error and how can I avoid that error (while still letting maps feature run on their device, so no codesigning is not an option)?


text:
Q: How to call a method multiple times (dynamically) in asynchronous way in node.js I am writing a script in node.js where I have method with a single parameter - id.
funcToCall(id)
{
    // some code ...

    returns a promise
}

var ids = [ list of ids] // input occurs dynamically

I will get a list of id's as input and I need to call the method with each input id in an asynchronous way. I have found a way to handle Promise.all() for the static/fixed number of method calls
const reflect = p => p.then(v => ({v, status: "fulfilled" }),
                        e => ({e, status: "rejected" }));

var arr = [ fun(id1), fun(id2), fun(id3) ];      // how to make this dynamically ?

Promise.all(arr.map(reflect)).then(function(results) {
    var success = results.filter(x => x.status === "fulfilled");
});

Is there any possible way to dynamically call the method multiples times and in an asynchronous way?
Thanks in advance!!

A: You could use .map on arrays and use Promise.all like this
function funcToCall(id) {
  return Promise.resolve(id); // this could be your promise.
}

const ids = [1, 2, 3, 4];

Promise.all(ids.map(id => funcToCall(id))).then((res = console.log(res)));


text:
Q: Hyphens after the prefixes "non-" and "anti-" in mathematics Is there a convention when to attach the prefixes non- and anti- to mathematical terms using a hyphen and when without?
One uses non-zero but also noncommutative.
Likewise for anti-. I no longer know which is correct – anti-isomorphism or antiisomorphism, anti-isometry or antiisometry.

A: As tchrist says, there's a lot of variation. I think in general:

*

*We tend to use a hyphen after "anti" when what follows begins with a vowel, especially an "i", because without it the word can be difficult to read. "Antisocial" is easy to read; "antiimigration" (to take tchrist's example) is awkward. (Similarly for other prefixes that end with a vowel, like "pre": we tend to write, for example, "premarital agreement", but "pre-employment agreement". Probably because "preemployment" looks like it should be read with "preem" as the first syllable, like preem-ploy-ment.)

*Words indicating opposition to some social or political idea tend to be written with a hyphen. That is, when there's a "pro" and an "anti" we write both with hyphens. Like "pro-gun" and "anti-gun" for the sides in the second amendment/gun control debate, "pro-Israel" and "anti-Israel" for sides in debates about that nation, etc. But words where there's not a "pro-X", more just "X" and "anti-X", tend to not use a hyphen, like "logarithm" and "antilogarithm".

*I don't have documentation on this but I suspect that newly-coined words tend to use the hyphen, but it gets dropped as the word becomes common or accepted.

A: As with most issues involving English spelling, there is no right or wrong here, only preferences that vary substantially by region, by publisher, and by writer, so much so that is easy, maybe even trivial, to find living counterexamples of any posited general rule here.
But in general, British publishers tend to be more tolerant of the hyphen than American publishers tend to be. Many American publishers forbid the hyphen except when the word following is capitalized, as in anti-American or anti-Semite, or when you would form two vowels in collision, as in anti-immigration.  (You never seem to see antiïmmigration, though; it almost looks like someone has smudged the page in this font.)
Otherwise American publishers tend to prefer versions like nonnative, nonnaturalized, nonzero, antilogarithm, antiperiodic, antisocial, antitrust.  However, with individual writers not forced to conform to any particular style guide, usage varies.


text:
Q: thinking_sphinx nested date search Let's say I've got the following scenario:
class Conference < ActiveRecord::Base
    has_many :meetings

    define_index do
        # index
    end
end

class Meeting < ActiveRecord::Base
    belongs_to :conference

    validates_presence_of :start_time
    validates_presence_of :end_time
end

I would like to search conferences based on the start time, so when I provide the start time it would return me the list of conferences which still have one or more meetings with start times after the provided time.
Is this possible with thinking_sphinx?  At the very least, how should I define my index?
EDIT
The search needs to be for Conferences (i.e. Conference.seacch)

A: class Meeting < ActiveRecord::Base
 belongs_to :conference

 ..
 define_index do
    indexes :start_time
    has conference_id
  end
end

Then
Meeting.search :conditions => {:created_at => 1.week.ago..Time.now}

http://freelancing-god.github.com/ts/en/indexing.html
http://freelancing-god.github.com/ts/en/searching.html


text:
Q: XPath filter on value I've got a ListBox with an XMLDataProvider that I want to filter on the specific value of a node.
I've tried the following but it returns the full <ITEMS> again.
<XmlDataProvider x:Key="ItemDataSource" XPath="./ITEMS[ITEM[./PROPERTY='value']]" Source="data.xml">
</XmlDataProvider>

This is the XML file:
<ITEMS>
  <ITEM>
    <PROPERTY>value</PROPERTY>
  </ITEM>
  <ITEM>
    <PROPERTY>other value</PROPERTY>
  </ITEM>
</ITEMS>

./ITEMS/ITEM[./PROPERTY/text()='value']
works but since it isn't wrapped by <ITEMS> it refuses to display the data.

A: I've found the solution using ./ITEMS/ITEM[./PROPERTY/text()='value'] I needed to unset the XPath in ItemsSource.


text:
Q: How to post the content of a file using Perl Script I am very new to Perl and badly needing for help.
I have a file.txt where I want to post its content to a webservice url.
This is the sample of my file.txt content.

Name: name1
Address: address1

Name: name2
Address: address2

Name: name3
Address: address3

And here it my post.pl (referencing from this site: http://xmodulo.com/how-to-send-http-get-or-post-request-in-perl.html)
#!/usr/bin/perl
use warnings;
use strict;
use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
my $url = "https://domain/post.php";

# set custom HTTP request header fields
my $req = HTTP::Request->new(POST => $url);
$req->content_type('application/json');

# add POST data to HTTP request body
my $post_data = '{"name":"myName", "address":"myAddress"}'; // I want to post here the content of file.txt
$req->content($post_data);
print $req->as_string;
my $resp = $ua->request($req);

    if ($resp->is_success) {
    my $message = $resp->decoded_content;
       print "\nReceived reply: $message\n";
   }
   else {
       print "HTTP POST error code: ", $resp->code, "\n";
       print "HTTP POST error message: ", $resp->message, "\n";
   }

Using above file and script, how can I possible post the contents of the file.
Thank you in advance.

A: You can use the post() method from LWP::UserAgent to make this much simpler. Underneath, it uses the POST() method from HTTP::Request::Common, so you can look there for more details about how it handles file uploads.
#!/usr/bin/perl
use warnings;
use strict;
use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
my $url = 'https://domain/post.php';

# The name of the file input field on the HTML form/
# You'll need to change this to whatever the correct name is.
my $file_input = 'file-input';

# Path to the local file that you want to upload
my $file_path = '/path/to/some/file';

my $req = $ua->post($url,
  Content_Type => 'form-data',
  Content => [
     $file_input => [ $file_path ],
  ],
);

You don't even need to open the file yourself - HTTP::Request::Common does that for you.

A: Read content from file like below.
use strict;
use warnings;
use utf8;

open my $fh, '<', '/path/to/file.json' or die "failed to open: $!";
my $content = do { local $/; <$fh> };
close $fh;

Or
use File::Slurp;
my $content = read_file('/path/to/file.json');

A: OK, firstly, I'd like to say that the format your file.txt is in, is not a very intuitive format, because it's not in any standardized format, so we can't just invoke generic libs that do CSV or JSON parsing. Anyways, what you essentially need is to build a parsing function in between.
sub parse_file {
    my ($filename) = @_;

    open(FILE, $filename) or die sprintf ("Could not open '%s' (%s)", $filename, $!));

    my $string = '';
    my @args;

    foreach my $line (<FILE>) {
        chomp($line);

        # Assumes that every record is separated by a blank line.
        if ($line) {
            my ($keyname, $value) = split(':', $line);

            # Remove empty spaces left and right
            $keyname =~ s/^\s+|\s+$//g;
            $value =~ s/^\s+|\s+$//g;

            $string = ($string)
                ? $string.', '.sprintf('"%s":"%s"', $keyname, $value);
                : sprintf('"%s":"%s"', $keyname, $value);
        }
        else {
            # When we have a blank line, store the string we have concatenated.
            push (@args, sprintf("{%s}", $string);
            $string = ''; # Reset the string for the next record
        }
    }

    close(FILE) or die sprintf ("Could not close '%s' (%s)", $filename, $!));

    return (wantarray) ? @args : \@args;
}

From the arguments that are returned from this function, you can then go
my @post_args = parse_file($path_to_your_file);
foreach my $post_arguments (@post_args) {
    # Call your HTTP request to set post_arguments and post the form
}


text:
Q: PHP: Ajax-to-PHP parameter issue Using the Ajax code, designated below, in the head of my page, ETD2.html, it'll send a parameter to a php script containing a switch statement. The problem I'm having is that in order for the switch statement to work correctly, the parameter has to include more than just a number, while for the mysql query to run, I need a variable which will be equal to the parameter, although it'll only contain the number in the variable and nothing else.
Ajax:
<script type="text/javascript">
function doAjax(ajaxFunction, str)
{
if (str=="")
  { document.getElementById("txtHint").innerHTML="";
  return; }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest(); }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText; }
  }
xmlhttp.open("GET","getuser.php?q="+str+"func="+ajaxFunction,true);
xmlhttp.send(); }
</script>

PHP:
<?php

include("dbinfo.inc.php");
$con = mysql_connect(localhost, $username, $password);
if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }

$db_selected = mysql_select_db($database, $con);
if (!$db_selected)
    {
    die('Could not connect to ' . $database . '<br />' . mysql_errno() . ': ' . mysql_error());
    }

$sFunction  = $_GET["func"];
$q=$_GET["q"];

switch($sFunction){
    case 'showCharacters':
       $result = mysql_query("SELECT * FROM `tablename` WHERE id = '" . mysql_real_escape_string($q) . "'") or die(mysql_error());
    Display Info from Database.
    break;
    case 'showTowers':
       $result = mysql_query("SELECT * FROM `tablename` WHERE id = '" . mysql_real_escape_string($q) . "'") or die(mysql_error());
    Display Info from Database.
    break;
    case 'showEnemies':
       $result = mysql_query("SELECT * FROM `tablename` WHERE id = '" . mysql_real_escape_string($q) . "'") or die(mysql_error());
    Display Info from Database.
    break;
    }
?>

I've tried a few different things, although nothing has worked yet. One thing I tried is since the parameter is made into a variable at the start of the script, I made it into a string and tried the preg_replace expression, but that still had no effect. Maybe I didn't use the correct syntax? I'm not sure. I'm not very knowledgeable about PHP, but I'm sure I'm on the right track.
The parameter is passed to the script in this format: ("Number" func= "parentelement-name") = 2func=showTowers
This is what I tried, although it didn't work.
$para =$_GET["q"];
$bres = (string)$para;
$ares = preg_replace("/[^0-9]/","", $bres);

Any help is appreciated. Please don't comment about jquery or say anything negative about how dumb my question is. If it was really that dumb, I wouldn't be asking for help.

A: You do not delimit your query variables with an ampersand, as you should. Do this:
xmlhttp.open("GET","getuser.php?q="+str+"&func="+ajaxFunction,true);
                                         ^
                                         |
ADDED! ----------------------------------/