text:
Q: Why can't I use a
A: Add .fn.:
alert(jQuery.fn.jquery);
// or
alert($.fn.jquery);

Or try using jQuery as a function:
alert(jQuery().jquery);
// or short:
alert($().jquery);

Michael pointed out another one:
alert(jQuery.prototype.jquery);
// so we can also add
alert($.prototype.jquery);

If you want your code to work:
// add somewhere before:
jQuery.extend(jQuery, {jquery: jQuery.fn.jquery});

// Than this should work just fine:
alert(jQuery.jquery);
alert($.jquery);

Extend JQuery object ($ or jQuery) by .jquery equal to jQuery.fn.jquery.
As you can see we can add any properity to jQuery. Let's do jQuery.version:
$.extend($,{version:$().jquery});

A: If you want version you need
jQuery.fn.jquery

A: You can do
jQuery.fn.jquery
You can also do
jQuery.prototype.jquery


text:
Q: Line output with awk There is a command and its output:
ps aux --sort=-%cpu | head -2 | sort -r

root         1  0.0  0.0    904   520 ?        Sl   12:09   0:00 /init
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND

How to print only the first line with awk? or only second lane like this:
root         1  0.0  0.0    904   520 ?        Sl   12:09   0:00 /init

or this:
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND

A: ps aux --sort=-%cpu | awk 'NR==1'

ps aux --sort=-%cpu | awk 'NR==2'

No need for head or sort.

redpajama_set_name: RedPajamaStackExchange


text:
Q: adding multiple files on page with file attribute I wanted to have one single input type of file to add multiple files on page and found below code from: http://the-stickman.com/web-development/javascript/upload-multiple-files-with-a-single-file-element/
but i am pretty new to JavaScript and having issue to extend it, what I need is when it add file to page it should add a new input of type text where I can pass title for that file .
I tried this but its showing me a pop-up window when I add a new file element and input is not beside file.
http://jsfiddle.net/4JPzL/
Below an image example how I wants it to look like

Thanks for any help.
EDIT FIX:
Never mind i have fixed it here (cant answer my own question so here it goes...):
http://jsfiddle.net/4JPzL/2/
Regards

A: Never mind i have fixed it here:
http://jsfiddle.net/4JPzL/2/


text:
Q: Group items in a list based on two properties using LINQ I have a Column class as below:
public class Column
{
    public int LocId { get; set; }
    public int SecId { get; set; }
    public double StartElevation { get; set; }
    public double EndElevation { get; set; }
}

And a list of Column objects:
List<Column> Columns = new List<Column>();

For example:
Columns:
{
    Column1: { LocId = 1 , SecId = 1, StartElevation = 0, EndElevation = 160 }
    Column2: { LocId = 1 , SecId = 1, StartElevation = 160, EndElevation = 320 }
    Column3: { LocId = 1 , SecId = 2, StartElevation = 320, EndElevation = 640 }
    Column4: { LocId = 2 , SecId = 1, StartElevation = 0, EndElevation = 160 }
    Column5: { LocId = 2 , SecId = 2, StartElevation = 160, EndElevation = 320 }
}

I want to apply the below algorithm to the above list using Linq.
Go through the Columns list and:

*

*(A) Choose a list of items that have the the same LocId.

*(B) Then from that list choose another list of items that have the same SecId.
This will give me a list hopefully which I will perform other things on it.
So applying the above algorithm on the data above will be like this.
                                       Columns List
                ---------------------------------------------------------
               | Column1     Column2     Column3     Column4     Column5 |
                ---------------------------------------------------------
                                            |
                                            |
                                           (A)
                                            |
                                            |
                        --------------------------------------------
                        |                                          |
                GroupBasedOnLocId                         GroupBasedOnLocId
                        |                                          |
                  -----------                                 -----------
                  | Column1 |                                 | Column4 |
                  | Column2 |                                 | Column5 |
                  | Column3 |                                 -----------
                  -----------                                      |
                       |                                           |
                      (B)                                         (B)
                       |                                           |
          -------------------------                   -------------------------
          |                       |                   |                       |
          |                       |                   |                       |
 GroupBasedOnSecId        GroupBasedOnSecId  GroupBasedOnSecId        GroupBasedOnSecId
          |                       |                   |                       |
          |                       |                   |                       |
       Column1                 Column3             Column4                 Column5
       Column2

How can I accomplish this using LINQ?

A: Use .GroupBy with composite key.
Sample code:
List<Column> Columns = new List<Column>
{
   new Column { LocId = 1 , SecId = 1, StartElevation = 0, EndElevation = 160 },
   new Column { LocId = 1 , SecId = 1, StartElevation = 160, EndElevation = 320 },
   new Column { LocId = 1 , SecId = 2, StartElevation = 320, EndElevation = 640 },
   new Column { LocId = 2 , SecId = 1, StartElevation = 0, EndElevation = 160 },
   new Column { LocId = 2 , SecId = 2, StartElevation = 160, EndElevation = 320 }
};

foreach (var group in Columns.GroupBy(c => new { c.LocId, c.SecId }))
{
    Console.WriteLine("group: LocId = {0}, SecId = {1}", group.Key.LocId, group.Key.SecId);
    foreach(Column column in group)
        Console.WriteLine("  item: StartElevation = {0}, EndElevation = {1}", column.StartElevation, column.EndElevation);
}

You can transform the group any way you want:
foreach (var res in Columns.GroupBy(c => new { c.LocId, c.SecId })
                           .Select(g => new
                           {
                               g.Key.LocId,
                               g.Key.SecId,
                               MinStartElevation = g.Min(c => c.StartElevation),
                               MaxEndElevation = g.Max(c => c.EndElevation)
                           }))
{
    Console.WriteLine("LocId = {0}, SecId = {1}, MinStartElevation = {2}, MaxEndElevation = {3}",
        res.LocId, res.SecId, res.MinStartElevation, res.MinStartElevation);
}

A: If you want a two-level grouping as your diagram indicates, you need to use GroupBy twice:
var grouping = columns
  .GroupBy(col => new { col.LocId, col.SecId }) // create groups by LocId+SecId
  .GroupBy(group => group.Key.LocId); // re-group by LocId only

Then you'll have a sequence of groups, each group having a having an int key (that's the LocId) and consisting of a sequence of other groups, each one having a composite key of both LocId and SecId, and consisting of a sequence of columns (matching those LocId and SecId).
You can then access the two-level grouping by foreach-ing over each level. For example:
foreach (var locGroup in grouping) {
  Console.WriteLine("LocId: " + locGroup.Key)

  foreach (var secGroup in locGroup) {
    Console.WriteLine("  SecId:" + secGroup.Key.SecId)
      Console.WriteLine("  Min StartElevation: {0}",
        secGroup.Min(col => col.StartElevation);
      Console.WriteLine("  Max EndElevation: {0}",
        secGroup.Max(col => col.EndElevation);

      foreach (var column in secGroup) {
        Console.WriteLine("    {0} -> {1}", column.StartElevation, column.EndElevation);
      }
    }
  }
}

Or, if you want to be able to find a specific node in the tree, you can use ToDictionary and ToLookup:
var lookup = columns
  // group columns by LocId
  .GroupBy(col => col.LocId)
  // create a dictionary from the groups to find them by LocId,
  // where the value of each entry is a lookup of its own columns by SecId
  .ToDictionary(
     locGroup => locGroup.Key,
     locGroup => locGroup.ToLookup(col => col.SecId));

Then you could do things like:
var locId = "123";
var locGroup = lookup[locId];
Console.WriteLine("LocId {0} has {1} sub-groups", locId, locGroup.Count);
Console.WriteLine("LocId {0} has {1} total columns", locId,
  locGroup.Sum(secGroup => secGroup.Count()));

var secId = "456";
var secGroup = locGroup[secId];
Console.WriteLine("LocId {0}, SecId {1} has {2} columns",
  locId, secId, secGroup.Count());

A: Here is a solution that uses LINQ Query Syntax. (Query syntax and Method Syntax are semantically identical, but many people find query syntax simpler and easier to read.)
// Declare and then populate the LINQ source.
List<Column> columns = new List<Column>();

var query =
    from column in columns
    group column by new {column.LocId, column.SecId} into g
    orderby g.Key.LocId, g.Key.SecId
    select new
    {
        LocId = g.Key.LocId,
        SecId = g.Key.SecId,
        Columns = g
    };

Below you'll find a complete demonstration program for this LINQ query using the data you provided. I've preceded the demo program with its expected output. Also see the live demo.
Expected Output
LocId:1, SecId:1
  StartElevation:0, EndElevation:160
  StartElevation:160, EndElevation:320
LocId:1, SecId:2
  StartElevation:320, EndElevation:640
LocId:2, SecId:1
  StartElevation:0, EndElevation:160
LocId:2, SecId:2
  StartElevation:160, EndElevation:320

Program
using System;
using System.Collections.Generic;
using System.Linq;

class LinqGroupDemo
{
    static public void Main(string[] args)
    {
        var query =
            from column in GetSource()
            group column by new {column.LocId, column.SecId} into g
            orderby g.Key.LocId, g.Key.SecId
            select new
            {
                LocId = g.Key.LocId,
                SecId = g.Key.SecId,
                Columns = g
            };

        foreach (var key in query)
        {
            Console.WriteLine("LocId:{0}, SecId:{1}",
                              key.LocId,
                              key.SecId);

            foreach (var column in key.Columns)
            {
                Console.WriteLine("  StartElevation:{0}, EndElevation:{1}",
                                  column.StartElevation,
                                  column.EndElevation);
            }
        }
    }

    static private List<Column> GetSource()
    {
        return new List<Column>
        {
            new Column { LocId = 1 , SecId = 1, StartElevation = 0, EndElevation = 160 },
            new Column { LocId = 1 , SecId = 1, StartElevation = 160, EndElevation = 320 },
            new Column { LocId = 1 , SecId = 2, StartElevation = 320, EndElevation = 640 },
            new Column { LocId = 2 , SecId = 1, StartElevation = 0, EndElevation = 160 },
            new Column { LocId = 2 , SecId = 2, StartElevation = 160, EndElevation = 320 }
        };
    }
}

public class Column
{
    public int LocId { get; set; }
    public int SecId { get; set; }
    public double StartElevation { get; set; }
    public double EndElevation { get; set; }
}

A: Use GroupBy:
var results = columns
    .GroupBy(column => column.LocId)
    .Select(group => group.GroupBy(c => c.Sec.Id));


text:
Q: DB2 error in stored procedure when using "scroll" cursor I want to use scroll cursor in my DB2 stored procedure, so that I could do absolute position. But after I declare a srcoll cursor like
DECLARE cursor1 SCROLL CURSOR WITH RETURN for ....

the deploy would return errors as

An unexpected token "SCROLL" was found following "".  Expected tokens may include:  "FOR".. SQLCODE=-104, SQLSTATE=42601, DRIVER=3.68.61.

The procedure is really simple btw, you can assume it only has this cursor declaration and return.
I googled a lot, still couldn't figure it out why, kind of rookie question, please help show some pointers, million thanks!


text:
Q: How to write Test class for this below code public List<HistoryTimelineObject> processTimelineItem(id recordId, Integer pageNo, Integer pageSize){
    List<HistoryTimelineObject> wrappedCase = new List<HistoryTimelineObject>();

    List<Case> t = [SELECT Id, Subject, AccountId, CreatedDate, CreatedBy.Name
    FROM   Case
    WHERE  Applicant__c = :recordId
    LIMIT :pageSize
    OFFSET :pageNo];
    if(t != null){
        for(Integer i = 0, CaseSize = t.size(); i < CaseSize; i++){
            wrappedCase.add(new HistoryTimelineObject().setActor(t[i].CreatedBy.Name)
                    .setHeader(t[i].Subject)
                    .setDate(t[i].CreatedDate.format())
                    .setIconName('standard:case')
                    .setIconColour('put the colour in here'));

        }
    }

    return wrappedCase;
}

A: You have to create a Case object and insert in your test class method. Call the above method from test class method. Assure that case value inserted and the data your passing in the parameter to call above method are same.
For further reference for test class,
[https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm]


text:
Q: Can't kill Mongodb server from outside the running terminal Beginner alert! I'm using express.js with mongodb and I set up a mongodb server in a terminal window through
mongod -dbpath *path name*

I accidentally closed the text editor without killing the terminal window that had the server running, so when I tried to set up a new server somewhere else it said that there was already a server running and wouldn't let me start another. I can't figure out how to close the last server because I can't go back to the terminal that it was running from and kill the terminal with control+c.
Is there a way to kill all mongodb servers from outside the terminal window that it's running?

A: Try this command
mongod --dbpath /path/to/your/db --shutdown

You can follow this official page for more info -
https://docs.mongodb.com/manual/tutorial/manage-mongodb-processes/


text:
Q: Having with sub-query vs just joining onto table? Working on some SQL today I came across a query that is using HAVING with a sub-query. I found it a bit odd as the table in the sub-query only contains one column of values and I figured it would just be simpler to join on that table.
Note the [F Types] table is a single column of unique values.
Example of what I found:
SELECT ST.COL1, ST.COL2, ST.COL3
FROM SOME_TABLE ST
HAVING ST.TYPE In (Select [Type] from [F Types]);

I was thinking that this would do the same thing and probably be better:
SELECT ST.COL1, ST.COL2, ST.COL3
FROM SOME_TABLE ST
JOIN [F Types] FT
    ON ST.TYPE = FT.Types

I just wanted to make sure I was not missing something as I don't see why one would use HAVING here.
What if any is the differenct between the 2 examples?

A: either way works, I think joins are technically faster

A: Mostly, a join is used when you actually want additional columns data which are present in the other table to be joined
While, a subquery is used as a lookup reference on some table to refer the data meaning just for reference
Adding to the above difference Join could be still costly imagine with a huge set of records which takes a lot while referring only via subquery would be more costly on performing a join.

A: You would use WHERE, not HAVING.  HAVING is for aggregation queries.  So your question is about:
SELECT ST.COL1, ST.COL2, ST.COL3
FROM SOME_TABLE ST
WHERE ST.TYPE In (SELECT f.[Type] FROM [F Types] f);

This is often preferable to the JOIN query.  You do not have to worry about duplicates in [F Types] resulting in duplicate rows in the result set.
SELECT ST.COL1, ST.COL2, ST.COL3
FROM SOME_TABLE ST
WHERE EXISTS (SELECT 1 FROM [F Types] f WHERE f.[Type] = ST.TYPE);

This readily takes advantage of an index on [F Types]([Type]) and is often the fastest approach (although all three should be comparable).
All this said, nothing is wrong with the JOIN.  Just under some circumstances it can produce unwanted duplicates.
Often, this is written using EXISTS rather than IN:


text:
Q: Trying to make a Clickable Home Button in my OS So I'm making a GUI for my Cosmos OS. I made a little home button but I don't Know how to make it clickable. The code I tried (below) didn't work Because for example "Mouse doesn't have a Definition for Buttons".
if (Mouse.Buttons == Mouse.MouseState.Left && Mouse.y >= 600) //No need to check x
{
     ifMouseClicked();
}

Does this have to do with my mouse driver or not? I Really need help so please let me know if there is another was of doing this or if there's a fix. Here's the full code of my home button. I'm not sure if I should include the mouse code too but let me know
for (uint w = 0; w < 30; w++)
            {

                for (uint h = 0; h < 30; h++)
                {

                    uint x = w;

                    uint y = 600 - h;

                    driver.SetPixel(x, y, 0xFFFFFF); //SetPixel(x,y,color)

                    if (Mouse.Buttons == Mouse.MouseState.Left && Mouse.y >= 600) //No need to check x
                    {
                        ifMouseClicked();
                    }

                }
            }

Here is the link to the Mouse Driver I used https://mega.nz/file/puoTlCaC#p1BPMlQKMhEQDlw5h-3PBDT47cZI2lsbGOv2OmWCO7I
and here is the code to activate everything
Cosmos.HAL.Drivers.PCI.Video.VMWareSVGAII driver = new Cosmos.HAL.Drivers.PCI.Video.VMwareSVGAII();
driver.SetMode(800, 600);
driver.Clear(0x255);

Mouse m = new Mouse(800, 600); // Note that you'll have to specify the screen
resolution (width and height).
bool OK = true; // Directly using true will cause debugging issues, and even if you disable it, (to make the GUI not lag) it's still very useful to just
disable the GUI.
while (OK)
{
   uint Width = 800;
   uint Height = 600;
   m.Draw(driver); // Draws the mouse with the specified driver
   driver.Update(0, 0, Width, Height); // Updates the screen as a whole to reduce flicker.
}


text:
Q: Wordpress site migration - Collation error I'm trying to migrate my wordpress website via Akeeba Backup For Wordpress. Unfortunately, as soon as I try to install the database, I get the following error:
   Unknown collation: 'utf8mb4_unicode_520_ci'

The database collation is utf8mb4_unicide_ci and the MySQL version is 5.5.52.
I read here that one has to change the database system from "None" to "MYSQL40". But there is no such setting in the Akeeba control panel.
Did I miss something?

A: See this
It seems that collation is only available for mySql 5.6+. I guess you are on 5.6-.

A: You might be able to open your SQL dump file in a text editor and do a search for "utf8mb4_unicode_520_ci" and replace it with "utf8mb4_general_ci".
Re-save your dump as a different file, and give the import a try. It's possible this might screw up some complex character encoding, but it's worth trying this simple fix first.

A: Instead of Akeeba, you could try the Duplicator plug-in to effect the migration. I've been using it for a long time and it works like a charm:
https://wordpress.org/plugins/duplicator/
(After installing the plug-in, generate a Duplicator package via the plug-in's menu on wp-admin dashboad.
Once the package is generated, download the two package files - installer.php and the archive/zip file - to some folder on your PC. Next, upload these two files to the live site's web root where you wish to create/migrate the site. Next, open the following link in your browser:
http://{your_domain}/installer.php
and follow on-screen instructions. Your site should get created and everything should work fine.)


text:
Q: The variable x in this integral I was trying to find the volume of a torus, and I got everything right except for the x variable that the book uses and I have no idea where they got that x from. Can someone explain this to me? (Note the x with the red ring on it))

A: Good question! :) The way to look at that $x$ value, is it is the radius of the torus at the point of integration. You are doing integration by means of shells, which has a general form of:
$$\int 2\pi x*y(x)dx$$
Imagine peeling the paper label off a can, and laying it flat. It has height $y$, and length $2\pi r$, where $r$ is the radius of the can. Thus, it has surface area of: $2\pi yr$. If you integrate (add up) all the concentric paper shells that would fit inside the can, you obtain the volume of the can itself ($\pi r^2y$).
Let's verify this:
$$V=\pi r^2 y = \int_0^r 2\pi x*y(x)dx = 2\pi\int_0^rx*ydx=2\pi y \left[\frac{x^2}{2}\right]_0^r=\pi y r^2$$


text:
Q: Elementary Bayesian probability problem. Manufacturer produces TVs probability of a malfunction in TV is $p$. There are 3 different quality checks in the factory with probability of finding malfunction equal to $p_i$ for $i=1,2,3$ every TV goes only through one  quality check and it's assigned to it at random. Later at the retailer warehouse there is another quality check with the probability of finding malfunction equal to $p_0$.
i) find the probability that TV with malfunction will get to the store? (i.e. goes through both checks)
ii) Assuming TV got to the store already what is the probability that it has a malfunction?
I described to events:
$A$- TV gets to the warehouse
$B$- TV lands in the store
Then: $$P(A\cap B)=P(B|A)P(A)=P(A|B)P(B)$$
but $P(A|B)$ is a probability that I goes through the first check if it goes through second check but the second check occurs only if it passes the first one so it must be equal $1$ but then $P(A\cap B) = P(B)$ what makes completely no sense. Later I thought that since these two events occur one after the other it's like throwing a dice twice so they are independent hence $P(A\cap B)=P(B)P(A)$ this makes more sense on the other hand it seems like if it passed the first test it should have bigger odds passing second one.
I feel like I have completely no intuition when it comes to this probability problems. Could some one clarify it for me please?
Edit: By probability of finding malfunction I mean probability of finding malfunction given that particular TV has one.


text:
Q: Из андроида отправить пароль открытым видом, а на хостинге хранить в закодированном виде Можно ли из андроида отправлять пароль открытым видом, а на хостинге  закодировать посредством php и хранить в базе данных?, так безопасно?

A: По порядку:

*

*"Можно ли отправить?" - можно. "так безопасно?" - нет! Перехватить пароль по пути по типу MITM не составляет каких либо трудностей

*Закодировать на хостинге? - Зачем тогда уже кодировать? Ну если только на всякий случай. Тут бы по хорошему сразу его кодировать или работать с токенами и так далее, про способы авторизации можно почитать и выбрать для себя приемлемый способ


text:
Q: How to search in polynomial hash table in ascending order in C? I there guys,
i'm developing a small program in C, that reads strings from a .txt file with 2 letters and 3 numbers format. Like this
AB123

I developed a polynomial hash function, that calculates an hash key like this
hash key(k) = k1 + k2*A² + k3*A^3... +Kn*A^n

where k1 is the 1º letter of the word, k2 the 2º (...) and A is a prime number to improve the number of collisions, in my case its 11.
Ok, so i got the table generated, i can search in the table no problem, but only if i got the full word... That i could figure it out.
But what if i only want to use the first letter? Is it possible to search in the hash table, and get the elements started by for example 'A' without going through every element?

A: In order to have more functionality you have to introduce more data structures. It all depends on how deep you want to go, which depends on what exactly you need to code to do.
I suspect that you want some kind of filtering for the user. When user enters "A" it should be given all strings that have "A" at the start, and when afterwards it enters "B" the list should be filtered down to all strings starting with "AB".
If this is the case then you don't need over-complicated structures. Just iterate through the list and give the user the appropriate sublist. Humans are slow, and they won't notice the difference between 3 ms response and 300 ms response.

A: If your hash function is well designed, every place in the table is capable of storing a string beginning with any prefix, so this approach is doomed from the start.
It sounds like what you really want might be a trie.


text:
Q: What termios settings cause endpoint to get garbled serial? I have two endpoints. One is Windows Subsystem for Linux (Ubuntu) and the other is a small AR9331 router (running OpenWRT and has 16550 chip). They are connected over a USB-to-Serial connection.
Sending from AR9331 to WSL works as expected.
WSL Console:
~/openwrt_master$ cat /dev/ttyS5

HELLOTOALL

HELLOTOALL

HELLOTOALL

AR9331 Console:
root@OpenWrt:~# echo "HELLOTOALL" > /dev/ttyATH0
root@OpenWrt:~# echo "HELLOTOALL" > /dev/ttyATH0
root@OpenWrt:~# echo "HELLOTOALL" > /dev/ttyATH0

Sending from WSL to AR9331 does not work as expected, it appears garbled or out of order.
WSL Console:
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5
~/openwrt_master$ echo "ILIKECHICKEN" > /dev/ttyS5

AR9331 Console:
ILIKECHICKEN

IKECHICKEN

ILIKECHICKEN

I

ILIKECHICKEN

I

ILIKECHICKEN

I

ILIKECHICKEN

IKECHICKEN

ILIKECHICKEN

AR9331 TTY settings:
root@OpenWrt:~# stty -F /dev/ttyATH0 -a
speed 115200 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; discard = ^O; min = 1; time = 0;
-parenb -parodd -cmspar cs8 hupcl -cstopb cread clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff
-iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
-isig -icanon iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt
echoctl echoke -flusho -extproc

WSL TTY settings:
~/openwrt_master$ stty -F /dev/ttyS5 -a
speed 115200 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = <undef>; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q;
stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; discard = ^O; min = 1; time = 0;
-parenb -parodd -cmspar cs8 hupcl -cstopb cread clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon ixoff -iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke -flusho -extproc

I tried messing with canonical mode, but it did not appear to change anything.


text:
Q: Embedding a Powerpoint show into a C# application I want to be able to embed a powerpoint presentation into a C# form (WinForms). Basically we have a 52' monitor, and the idea is that in one corner we will have a PPT on loop, and then the other 3 corners will be displaying information from the program itself.
I had expected this to be straightforward, but it seems I am mistaken.
I had been advised to use the WebBrowser control, but this doesn't work and instead treats the powerpoint file as a download, i.e. gives me a "Save, Open" dialog.
Any suggestions?
AK

A: You can just run PowerPoint, get the windows handle, and set a new parent window using the SetParent function.

All you need is the name of the window class of the PowerPoint window, but thanks to Spy++, this is no big deal.

Here's a screenshot of PowerPoint running 'inside' of a custom application:

Full example (taken from here and modified for PowerPoint):
public partial class Form1 : Form
{
    public Form1()
    {
        this.Size = new System.Drawing.Size(800, 600);
        this.TopMost = true;
        this.Text = "My Application";
        this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
        Func<bool> run = () =>
            Window.Find(hwnd =>
            {
                var cn = Window.GetClassName(hwnd);
                var res = (cn == "PPTFrameClass");
                if (res)
                {
                    this.Controls.Clear();
                    Window.SetParent(hwnd, this.Handle);
                    Window.SetWindowPos(hwnd, new IntPtr(0), -8, -30, this.Width + 10, this.Height + 37, 0x0040);
                }
                return res;
            });

        new Button { Parent = this, Text = "Start" }
            .Click += (s, e) =>
            {
                if (run() == false)
                    MessageBox.Show("Open PowerPoint");
            };
    }
}

public static class Window
{
    public static bool Find(Func<IntPtr, bool> fn)
    {
        return EnumWindows((hwnd, lp) => !fn(hwnd), 0) == 0;
    }
    public static string GetClassName(IntPtr hwnd)
    {
        var sb = new StringBuilder(1024);
        GetClassName(hwnd, sb, sb.Capacity);
        return sb.ToString();
    }
    public static uint GetProcessId(IntPtr hwnd)     // {0:X8}
    {
        uint pid;
        GetWindowThreadProcessId(hwnd, out pid);
        return pid;
    }
    public static string GetText(IntPtr hwnd)
    {
        var sb = new StringBuilder(1024);
        GetWindowText(hwnd, sb, sb.Capacity);
        return sb.ToString();
    }

    delegate bool CallBackPtr(IntPtr hwnd, int lParam);

    [DllImport("user32.dll")]
    static extern int EnumWindows(CallBackPtr callPtr, int lPar);

    [DllImport("user32.dll")]
    static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

    [DllImport("User32", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndParent);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int W, int H, uint uFlags);
}

A: A PowerPoint viewer that is an embeddable Active/X control should be the way to go - you can try this (apparently it does not work - see comments) or this
See this for embedding Active/X controls in Windows Forms applications
If the window where you plan to display the PowerPoint does not change size you could also convert the PowerPoint slides into bitmaps, and then just display the bitmaps

A: I really have no idea wether it is possible to embed a ppt-viewer in winforms. I do have one other suggestion for you: Use the browser control (or download one for webkit if you want better html5 support) and use a js library like impress.js to present the presentation. Just a thought.

A: Originally posted by @danish, here.
See this link. You can also display the ppt in a WebBrowser control. This might also be useful.
Basically it allows you to open ppt as well, in a WebBrowser Control that you can embed easily. Let me know if you need more information about it.


text:
Q: R function for finding at least 2 words that match between 2 strings (applied over 2 vectors of strings)? I have 2 set of strings. Char and Char2 for this example. I am trying to find if Char includes at least 2 words from Char2 (any two words can match). I have yet to get to the "at least 2 words" part, but I must first figure out the matching of any word in each string. Any help would be greatly appreciated.
I have tried using the stringr package a couple of different ways. Please see below. I tried using similar solutions to what Robert answered with in this question: Detect multiple strings with dplyr and stringr
shopping_list <- as.data.frame(c("good apples", "bag of apples", "bag of sugar", "milk x2"))
colnames(shopping_list) <- "Char"

shopping_list2 <- as.data.frame(c("good pears", "bag of sugar", "bag of flour", "sour milk x2"))
colnames(shopping_list2) <- "Char2"

shop = cbind(shopping_list , shopping_list2)
shop$Char = as.character(shop$Char)
shop$Char2 = as.character(shop$Char2)

# First attempt
sapply(shop$Char, function(x) any(sapply(shop$Char2, str_detect, string = x)))

# Second attempt
str_detect(shop$Char, paste(shop$Char2, collapse = '|'))

I get these results:
sapply(shop$Char, function(x) any(sapply(shop$Char2, str_detect, string = x)))
  good apples bag of apples  bag of sugar       milk x2
        FALSE         FALSE          TRUE         FALSE

str_detect(shop$Char, paste(shop$Char2, collapse = '|'))
FALSE FALSE  TRUE FALSE

However I am looking for these results:
FALSE TRUE TRUE TRUE
1) FALSE because only 1 word matches
2) TRUE because "bag of" in both
3) TRUE because "bag of" in both
4) TRUE because "milk x2" in both

A: Here is a function that could help
match_test <- function (string1, string2) {
  words1 <- unlist(strsplit(string1, ' '))
  words2 <- unlist(strsplit(string2, ' '))
  common_words <- intersect(words1, words2)
  length(common_words) > 1
}

Here is an example
string1 <- c("good apples" , "bag of apples", "bag of sugar", "milk x2")
string2 <- c("good pears" , "bag of sugar", "bag of flour", "sour milk x2")
vapply(seq_along(string1), function (k) match_test(string1[k], string2[k]), logical(1))
# [1] FALSE  TRUE  TRUE  TRUE


text:
Q: Finding a data source for demographics by zip code does anyone know specific data sources that would provide demographics such as age or income by zip code? I was able to find specific regions like NYC or other locations but not all in one source. I checked the census data as well but was not successful in finding it there.

A: I know this is a little late, but there is an API available with a lot of demographic-related data by ZIP code.  In case anyone else is looking:
https://rapidapi.com/aptitudeapps/api/zip-code-master/details


text: Q: While I'm installing swagger js doc npm, Issue? I tired to install swaggerjs doc npm but npm install fails and says build failed....what can I do to install swagger js doc??I'm using node version 14....is there any option to use swagger in Api???


text:
Q: Why new visual studio take string literals as pointer to constant? I have this constructor for my class student.
student::student( char* rollno ,   char* name , date dob) :
    rollno(rollno), name(name),dob(dob)
{
}

When I write
student s1( "l1f18bscs0322" , "usama" , { 13,7,1998 });
in main, it accepts it in my university I think because its using Visual studio 2013, but It gives error
in home as I am using visual studio 2019. It says no instance of constructor matches the argument list it takes value in double quotes as pointer to constant. What will be the alternate to pass values to this constructor? Because even If I change my constructor protype to constant to pointer so it will give new error that I cannot initialize my non constant members with constant.

A: Because it is!
The type of a string literal, in C++, is const char[N] (where N is the length of the string including its null terminator). That decays to const char*, not char*.
In earlier versions of C++ (pre-2011), you were permitted to "forget" the const for compatibility with C, though doing so was deprecated (and attempting to "modify" the literal had undefined behaviour). Since then you must write it.
You've upgraded to a version of Visual Studio that enforces this rule, possibly only because its default C++ standard is C++11 or later.
It's a good thing; add the const.
If your course material uses char* here, it is out-of-date, and was always "wrong" in a sense.

even If I change my constructor protype to constant to pointer so it will give new error that I cannot initialize my non constant members with constant

You need to do the same thing to your member variables.


text:
Q: Multiple Producers and Multiple Consumers Java Semaphore Blocking Queue We are trying to do multiple producers and multiple consumers around a semaphore lock queue. We are running into the issue of having more items produced than I told it to produce. Can someone please help me figure out where we are going wrong? Thanks.
package prog2;

import java.util.Scanner;

public class prog2 {

public static void main(String[] args) throws Exception {

    Scanner scanner = new Scanner(System.in);
    System.out.println("Input number of producers threads, number of consumer threads, size of the buffer, and the number of items to be produced.");
    System.out.println("Format Ex: 4 5 10 1000");
    String input = scanner.nextLine();
    String[] numbers = input.split(" ");

    int num_producers, num_consumers, size_buffer, num_items, num_consumed, num_produced;
    num_producers = Integer.parseInt(numbers[0]);
    num_consumers = Integer.parseInt(numbers[1]);
    size_buffer = Integer.parseInt(numbers[2]);
    num_items = Integer.parseInt(numbers[3]);

    ProducerConsumer implementation = new ProducerConsumer(size_buffer, num_items);

    for(int producer_count = 0; producer_count < num_producers; producer_count++){ //creating multiple producers
                Producer p = new Producer(implementation);
                p.start();
    }

    for(int consumer_count = 0; consumer_count < num_consumers; consumer_count++){ //creating multiple consumers
                Consumer c = new Consumer (implementation);
                c.start();
    }

    System.out.println("Number of Produced items: " + implementation.num_produced + " Number of Consumed items: " + implementation.num_consumed);

    }
}

package prog2;

public class Producer extends Thread{

protected ProducerConsumer implementation;

public Producer (ProducerConsumer implementation){
    this.implementation = implementation;
}

@Override
public void run(){
        try{
            while(implementation.done_processing != true){
                implementation.put();
            }
        }catch(InterruptedException e){
        }
}
}

package prog2;

public class Consumer extends Thread{

protected ProducerConsumer implementation;

public Consumer (ProducerConsumer implementation){
    this.implementation = implementation;
}
  @Override
  public void run(){
    try{
        while(implementation.done_consuming != true){
            implementation.get();
        }
    }catch(InterruptedException e){
    }
}
}

package prog2;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;

class ProducerConsumer {
//Queue Creation
private final BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
private final Random theRandom = new Random();
//Semaphore Creation
static Semaphore semProd = new Semaphore(1);
static Semaphore semCon = new Semaphore(0);

public boolean done_processing = false;
public boolean done_consuming = false;
public int num_items = 0;
private int size_buffer = 0;
public int num_produced = 0;
public int num_consumed = 0;

public ProducerConsumer (int size_buffer, int num_items){
    this.size_buffer = size_buffer;
    this.num_items = num_items;
}

public void write_producer_log (String data) throws IOException{
    File f1 = new File ("producer-event.log");
    if(!f1.exists()){
        f1.createNewFile();
    }
    FileWriter fileWriter = new FileWriter(f1.getName(),true);
    try (BufferedWriter bw = new BufferedWriter(fileWriter)) {
        bw.write(data);
        bw.newLine();
    }
}

public void write_consumer_log (String data) throws IOException{
    File f1 = new File ("consumer-event.log");
    if(!f1.exists()){
        f1.createNewFile();
    }
    FileWriter fileWriter = new FileWriter(f1.getName(),true);
    try (BufferedWriter bw = new BufferedWriter(fileWriter)) {
        bw.write(data);
        bw.newLine();
    }
}

public void put() throws InterruptedException {
    semProd.acquire();
    try {
        if(num_produced >= num_items){
            done_processing = true;
        }
            if (queue.size() == size_buffer) {
                return;
            }

            int number = theRandom.nextInt();
            boolean isAdded = queue.add(number);
            num_produced++;
                Timestamp timestamp = new Timestamp(System.nanoTime());
                String log_entry = timestamp + " Producer " +
Thread.currentThread().getId() + " " + num_produced + " " + number +"\n";
              try{
                write_producer_log(log_entry);
              }catch (IOException e){

              }
    }
    finally {
            semCon.release();
    }

}

public void get() throws InterruptedException {
    semCon.acquire();
    try {
        if(num_consumed >= num_items){
            done_consuming = true;
        }
            if (queue.isEmpty()) {
                return;
            }

            Integer value = queue.take();
            num_consumed++;
                Timestamp timestamp = new Timestamp(System.nanoTime());
                String log_entry = timestamp + " Consumer " +
Thread.currentThread().getId() + " " + num_consumed + " " + value +"\n";
              try{
                write_consumer_log(log_entry);
              }catch (IOException e){

              }
    }
    finally {
        semProd.release();
    }
}
}

A: In class prog2, you should use thread.join to wait all producer and consumer finish their jobs before printing num_produced and num_consumed:
public class prog2 {

    public static void main(String[] args) throws Exception {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Input number of producers threads, number of consumer threads, size of the buffer, and the number of items to be produced.");
        System.out.println("Format Ex: 4 5 10 1000");
        String input = scanner.nextLine();
        String[] numbers = input.split(" ");

        int num_producers, num_consumers, size_buffer, num_items, num_consumed, num_produced;
        num_producers = Integer.parseInt(numbers[0]);
        num_consumers = Integer.parseInt(numbers[1]);
        size_buffer = Integer.parseInt(numbers[2]);
        num_items = Integer.parseInt(numbers[3]);

        ProducerConsumer implementation = new ProducerConsumer(size_buffer, num_items);
        Producer[] producers = new Producer[num_producers];
        Consumer[] consumers = new Consumer[num_consumers];

        for (int producer_count = 0; producer_count < num_producers; producer_count++) { //creating multiple producers
            producers[producer_count] = new Producer(implementation);
            producers[producer_count].start();
        }

        for (int consumer_count = 0; consumer_count < num_consumers; consumer_count++) { //creating multiple consumers
            consumers[consumer_count] = new Consumer(implementation);
            consumers[consumer_count].start();
        }

        for (int producer_count = 0; producer_count < num_producers; producer_count++) {
            producers[producer_count].join();
        }

        for (int consumer_count = 0; consumer_count < num_consumers; consumer_count++) {
            consumers[consumer_count].join();
        }

        System.out.println("Number of Produced items: " + implementation.num_produced +
                " Number of Consumed items: " + implementation.num_consumed);
    }
}

In class ProducerConsumer,

*

*You should declare below variables with keyword volatile, so the
reader threads can always get the updated value:

*

*done_processing

*done_consuming

*num_produced

*num_consumed

*You should use Semaphore.tryAcquire(long timeout, TimeUnit unit) instead
Semaphore.acquire(), which will prevent threads being blocked when
done_consuming = true or done_processing = true.

*You should return immediatly when done_consuming = true or
done_processing = true, instead continuing execute.

Here is the code of ProducerConsumer without log:
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

class ProducerConsumer {
    //Queue Creation
    private final BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
    private final Random theRandom = new Random();
    //Semaphore Creation
    static Semaphore semProd = new Semaphore(1);
    static Semaphore semCon = new Semaphore(0);

    public volatile boolean done_processing = false;
    public volatile boolean done_consuming = false;

    public int num_items = 0;
    private int size_buffer = 0;

    public volatile int num_produced = 0;
    public volatile int num_consumed = 0;

    public ProducerConsumer(int size_buffer, int num_items) {
        this.size_buffer = size_buffer;
        this.num_items = num_items;
    }

    public void put() throws InterruptedException {
        if (semProd.tryAcquire(100, TimeUnit.MILLISECONDS)) {
            try {
                if (num_produced >= num_items) {
                    done_processing = true;
                    return;
                }
                if (queue.size() == size_buffer) {
                    return;
                }
                int number = theRandom.nextInt();
                boolean isAdded = queue.add(number);
                num_produced++;
            } finally {
                semCon.release();
            }
        }
    }

    public void get() throws InterruptedException {
        if (semCon.tryAcquire(100, TimeUnit.MILLISECONDS)) {
            try {
                if (num_consumed >= num_items) {
                    done_consuming = true;
                    return;
                }
                if (queue.isEmpty()) {
                    return;
                }
                Integer value = queue.take();
                num_consumed++;
            } finally {
                semProd.release();
            }
        }
    }
}

Test results:
Input number of producers threads, number of consumer threads, size of the buffer, and the number of items to be produced.
Format Ex: 4 5 10 1000
4 5 10 1000
Number of Produced items: 1000 Number of Consumed items: 1000

Input number of producers threads, number of consumer threads, size of the buffer, and the number of items to be produced.
Format Ex: 4 5 10 1000
10 20 30 10000
Number of Produced items: 10000 Number of Consumed items: 10000


text:
Q: When you enter a moderator tag in the body, it isn't formatted In the tags bar, the moderator only tags have different formatting, as do the required tags:

But when you use the [tag:tagname] markdown, it doesn't format it at all on the per-site meta sites.
Ask Ubuntu:

Stack Overflow:

English Language & Usage:

It does, however format them on this main Meta:

Is there any reason for this difference?

A: You need to prepend meta- to the tag keyword, like this:
[meta-tag:status-completed] = status-completed
[meta-tag:status-declined] = status-declined
[meta-tag:status-deferred] = status-deferred
[meta-tag:status-bydesign] = status-bydesign
That way, those tags are related to Meta and not counted as main site tags.


text:
Q: Can we make sense of $\frac{\partial f(x_1, x_2, \dots, x_n)}{\partial g(x_1, x_2, \dots, x_n)}$? Let $f, g \in \mathbb R^n \rightarrow \mathbb R$. Is there some way to make sense of the expression:
$$\frac{\partial f(x_1, x_2, \dots, x_n)}{\partial g(x_1, x_2, \dots, x_n)}$$
I want some way to measure "how much $f$ changes along $g$" --- I'm not sure what a reasonable definition of this. Here is one that came to mind.
Let us define $\frac{\partial f}{\partial g}\big(t \big)$: At each point $t \in \mathbb R^n$, we first compute $g'(t) \in \mathbb R^n$. Now, we compute the directional derivative of $f$ along $g'(t)$:
$$
\frac{\partial f(x_1, x_2, \dots x_n)}{g(x_1, x_2, \dots x_n)} (t) : \mathbb R^n \rightarrow \mathbb R\equiv (\nabla_{g'(t)} f)(t) = \lim_{h \rightarrow 0} \frac{f(t + hg'(t)) - f(t)}{h}$$

*

*Is this a well-known idea? If so, what is it called?

*My problem with this is that it returns a scalar at each point: what I am actually interested in is to find a new function which tells me "how to move $f$ infinitesimally so we can make it closer to $g$.

The given definition above clearly generalizes to any manifold: all I need is a directional derivative, which I do possess on a manifold: Can we say something interesting about this in a larger setting?

A: The construction you described doesn't actually work on manifolds - $g'(t)$ (or $dg$ as we would normally write) is not a tangent vector, but a cotangent vector; so the directional derivative $\nabla_{dg} f$ doesn't make sense without a metric (or some other additional structure) to identify $TM$ with $T^* M$.
It also doesn't seem to have the right behaviour to be casually called "$\partial f / \partial g$" - for example, $\nabla_{dg} f$ would double if you doubled $g$, which is the opposite scaling behaviour to what the notation would suggest.
Remember that partial derivatives are only defined in terms of a whole coordinate system - if you're given the two coordinate systems $(x,y)$ and $(x,z=y-x),$ the expression $\partial f/\partial x$ will have different values depending on whether you're holding $y$ or $z$ fixed! Thus I'm unsure how to interpret the intended spirit of "$\partial f/\partial g$".

Is this a well-known idea? If so, what is it called?

Not commonly enough to have a name; but it's a simple enough expression that you'll find it cropping up in equations here and there in vector calculus (as $\nabla g \cdot \nabla f$) and Riemannian geometry (as $\nabla_{\operatorname{grad}g}f$). The interpretation isn't really close to what you're looking for, however - it's just "the rate of change of $f$ in the direction $\nabla g$ (or vice versa).

what I am actually interested in is to find a new function which tells me "how to move f infinitesimally so we can make it closer to g".

I'm unsure how to interpret this - to me, the way to "move" a scalar function is to deform it by another scalar function (e.g. deform $f$ to $f + \epsilon \phi$ for a parameter $\epsilon$), in which case what you're describing would just be the scalar $g - f$? If you could formalize what you're asking for here (or at least give more of a geometric description) there might be something more useful to say.

A: I think $\frac{\partial f(x_1, x_2, \dots, x_n)}{\partial g(x_1, x_2, \dots, x_n)}$ should be able to predict small changes in $f$, given small changes in $g$. Now, if all we're given is a small change $dg$, then that's just $ \nabla g\cdot \vec{dr}    $. Even knowing $\nabla{g}$ at the point, we can't invert this dot product to get back $\vec{dr}$. Without knowing $\vec{dr}$, we can't predict the change in $f$, which is $\nabla f\cdot \vec{dr}$. So in this sense, the derivative is not define-able.


text:
Q: Why is this code printing aa0 as an element in set although aa is not a substring of ab? strong text
#include <iostream>
#include<set>
#include <string>
#include <string_view>
#include <boost/algorithm/string.hpp>
using std::string;
using std::cout;
using std::cin;
using std::endl;
int main()
{
     long int t;
     cin>>t;
     while(t--)
    {
        string s1,s2,x,a,b,f;
        cin>>s1>>s2>>x;
        std::set<string> s;
        int n,m,A;
        n=s1.length();
        m=s2.length();
        for(int i=0;i<n;i++)
        {
            a=s1.substr(0,i+1);
            if(boost::algorithm::contains(x, a));
            {
                s.insert(a+"0");
            }
            for(int j=0;j<m;j++)
            {
                b=s2.substr(0,j+1);
                if(boost::algorithm::contains(x,b))
                {
                    s.insert("0"+b);
                }
                f=a+b;
                if(boost::algorithm::contains(x,f))
                {
                    s.insert(f);
                }
            }

        }
        cout<<(s.size())+1<<endl;
            for (auto it = s.begin(); it !=
                             s.end(); ++it)
        cout << endl << *it;
    /*A=boost::algorithm::contains(x,"aa0");
        cout<<A;*/
    }
    return 0;
}

**Given 3 strings S1, S2 and X, find the number of distinct ordered pairs of strings (P,Q) such that :
String P+Q is a substring of X.
String P is some prefix of S1 (possibly empty).
String Q is some prefix of S2 (possibly empty).
A substring of a string is a contiguous subsequence of that string. For example, "chef" is a substring of "codechef", but "def" is not. Also, an empty string is a substring of any string.
A prefix of a string S is a substring of S that occurs at the beginning of S. For example, "code" is a prefix of "codechef", but "chef" is not. Also, an empty string is a prefix of any string.**
**My approach-slicing the string s1 and s2 using substr function and then checking whether there are substring of x using a algorithm or boost function
i have used s.insert(a+"0") it just signifies that a is a prefix of s1 string and we have taken null prefix i.e. ""  from s2. Same s.insert(""+b) means null prefix from string s1 and b prefix from s2 and so on.
****Problem - It is giving wrong output for one inputset dont know why. Debug it and see the pic https://i.stack.imgur.com/zUm5O.png **

A: I cleaned up your main function a little and removed boost usage (since you don't really need it here). I've also removed your namespace declarations as that is a bad idea. Lastly, I replaced your boost usage with a simple string::find. You can find the live example here.
The output is :
4

0b
a0
ab

The updated main() is below with your example set, instead of using std::cin.
#include <iostream>
#include <set>
#include <string>

int main()
{
     long int t{1};
     while(t--)
    {
        std::string s1{"aa"},s2{"bb"},x{"ab"},a{""},b{""},f{""};
        std::set<std::string> s;
        int n,m,A;
        n=s1.length();
        m=s2.length();
        for(int i=0;i<n;i++)
        {
            a=s1.substr(0,i+1);
            if(x.find(a) != std::string::npos)
            {
                s.insert(a+"0");
            }
            for(int j=0;j<m;j++)
            {
                b=s2.substr(0,j+1);
                if(x.find(b) != std::string::npos)
                {
                    s.insert("0"+b);
                }
                f=a+b;
                if(x.find(f) != std::string::npos)
                {
                    s.insert(f);
                }
            }

        }
        std::cout<<(s.size())+1<<std::endl;
            for (auto it = s.begin(); it !=
                             s.end(); ++it)
        std::cout << std::endl << *it;
    /*A=boost::algorithm::contains(x,"aa0");
        cout<<A;*/
    }
    return 0;
}


text:
Q: How to determine the installed webpack version Especially during the transition from webpack v1 to v2, it would be important to programmatically determine what webpack version is installed, but I cannot seem to find the appropriate API.

A: If using Angular CLI v7+, the webpack version is printed in the output of ng version:
-> ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 7.0.6
Node: 11.0.0
OS: darwin x64
Angular: 7.1.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... http, language-service, material, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.10.6
@angular-devkit/build-angular     0.10.6
@angular-devkit/build-optimizer   0.10.6
@angular-devkit/build-webpack     0.10.6
@angular-devkit/core              7.0.6
@angular-devkit/schematics        7.0.6
@angular/cli                      7.0.6
@ngtools/webpack                  7.0.6
@schematics/angular               7.0.6
@schematics/update                0.10.6
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.19.1

A: webpack 4 now offers a version property that can be used!

A: In CLI
$ webpack --version

webpack-cli 4.1.0

webpack 5.3.2

In Code (node runtime)
process.env.npm_package_devDependencies_webpack // ^5.3.2

or
process.env.npm_package_dependencies_webpack // ^5.3.2

In Plugin
compiler.webpack.version // 5.3.2

A: Put webpack -v into your package.json:
{
  "name": "js",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack -v",
    "dev": "webpack --watch"
  }
}

Then enter in the console:
npm run build

Expected output should look like:
> npm run build

> js@1.0.0 build /home/user/repositories/myproject/js
> webpack -v

4.42.0

A: For those who are using yarn
yarn list webpack will do the trick
$ yarn list webpack
yarn list v0.27.5
└─ webpack@2.6.1
Done in 1.24s.

A: Just another way not mentioned yet:
If you installed it locally to a project then open up the node_modules folder and check your webpack module.
< /node_modules/webpack/package.json
Open the package.json file and look under version

A: Version Installed:
Using webpack CLI: (--version, -v  Show version number [boolean])
webpack --version

or:
webpack -v

Using npm list command:
npm list webpack

Results in name@version-range:
<projectName>@<projectVersion> /path/to/project
└── webpack@<version-range>

Using yarn list command:
yarn list webpack

How to do it programmatically?
Webpack 2 introduced Configuration Types.

Instead of exporting a configuration object, you may return a function
  which accepts an environment as argument. When running webpack, you
  may specify build environment keys via --env, such as --env.production
  or --env.platform=web.

We will use a build environment key called --env.version.
webpack --env.version $(webpack --version)

or:
webpack --env.version $(webpack -v)

For this to work we will need to do two things:
Change our webpack.config.js file and use DefinePlugin.

The DefinePlugin allows you to create global constants which can be
  configured at compile time.

-module.exports = {
+module.exports = function(env) {
+  return {
    plugins: [
      new webpack.DefinePlugin({
+        WEBPACK_VERSION: JSON.stringify(env.version) //<version-range>
      })
    ]
+  };
};

Now we can access the global constant like so:
console.log(WEBPACK_VERSION);

Latest version available:
Using npm view command will return the latest version available on the registry:

npm view [<@scope>/]<name>[@<version>] [<field>[.<subfield>]...]

For webpack use:
npm view webpack version

A: npm webpack --version
works for me and it throws something like:
PS C:\Users\alfon\OneDrive\Escritorio\sandbox\fimusicv4\with-redux-app> npm webpack --version
npm WARN config global --global, --local are deprecated. Use --location=global instead.
8.5.5


text:
Q: jQuery if valid show icon else show invalid icon I'm trying to do the following, If one or more inputs have "woocommerce-invalid" class display error "red cross" icon else if all fields are completed display success "green tick".
I've tried with this, It added "checkout-tick-one" but would add/remove class if was valid or not.
$(".checkout-profile input").each(function () {
    if ($(this).hasClass("woocommerce-invalid")) {
        $('.symbol').addClass('checkout-cross-one');
        $('.symbol').removeClass('checkout-tick-one');
    } else {
        $('.symbol').addClass('checkout-tick-one');
        $('.symbol').removeClass('checkout-cross-one');
    }
});

I need it to work with the following.
.on('blur change', '.input-text, select', function () {
    var $this = $(this);
    var $parent = $this.closest('.form-row');
    var validated = true;

    if ($parent.is('.validate-required')) {
        if ($this.val() == '') {
            $parent.removeClass('woocommerce-validated').addClass('woocommerce-invalid woocommerce-invalid-required-field');

            validated = false;
        }
    }

    if ($parent.is('.validate-email')) {
        if ($this.val()) {

            /* http://stackoverflow.com/questions/2855865/jquery-validate-e-mail-address-regex */
            var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);

            if (!pattern.test($this.val())) {
                $parent.removeClass('woocommerce-validated').addClass('woocommerce-invalid woocommerce-invalid-email');
                validated = false;
            }
        }
    }

    if (validated) {
        $parent.removeClass('woocommerce-invalid woocommerce-invalid-required-field').addClass('woocommerce-validated');
    }
})

So if one, two or three inputs had invlaid classes the symbol will show tick or cross depening if correct or not.
I also just tried, it seems to work but when i click on another field the icon changes even through another field has the invalid class.
.on('blur change', '.input-text, select', function () {
    var $this = $(this);
    var $parent = $this.closest('.form-row');
    var validated = true;
    if ($parent.is('.validate-required')) {
        if ($this.val() == '') {
            $parent.removeClass('woocommerce-validated').addClass('woocommerce-invalid woocommerce-invalid-required-field');
            $('.symbol').addClass('checkout-cross-one');
            $('.symbol').addClass('checkout-tick-one');
            validated = false;
        }
    }
    if ($parent.is('.validate-email')) {
        if ($this.val()) {
            /* http://stackoverflow.com/questions/2855865/jquery-validate-e-mail-address-regex */
            var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);

            if (!pattern.test($this.val())) {
                $parent.removeClass('woocommerce-validated').addClass('woocommerce-invalid woocommerce-invalid-email');
                $('.symbol').addClass('checkout-cross-one');
                $('.symbol').addClass('checkout-tick-one');
                validated = false;
            }
        }
    }
    if (validated) {
        $parent.removeClass('woocommerce-invalid woocommerce-invalid-required-field').addClass('woocommerce-validated');
        $('.symbol').addClass('checkout-tick-one');
        $('.symbol').removeClass('checkout-cross-one');
    }
})

A: JS
if ($('input').hasClass('woocommerce-invalid')) {
    $('#someDiv').addClass('red-cross');
} else {
    $('#someDiv').addClass('green-tick');
}

CSS
.red-cross{
    background-image: url('red-cross.png');
}
.green-tick{
    background-image: url('green-tick.png');
}

A: Try this :
If input hasClass woocommerce-invalid then in if condition addClass to element for which you want to display red cross icon. But for that you need to add image in class which you adding.
if($('input').hasClass('woocommerce-invalid')) {
    // logic here
} else {
    // logic here
}

A: jQuery:
$('form')
   .removeClass('invalid')  // remove 'invalid' class from forms
   .filter(':has(.woocommerce-invalid)')  // find forms which have an element with class '.woocommerce-invalid'
   .addClass('invalid');  // add 'invalid' class to these forms

CSS
form { background:url(green-tick.png) 100% 50% no-repeat; }
form.invalid { background-image:url(red-cross.png); }

jsfiddle:
http://jsfiddle.net/Pp6wB/1/


text:
Q: How do I fix the 404 page with my Java app? My project works perfect locally but when deploying to a live server, I'm getting a 404 error when trying to access '/connect'. Any help would greatly be appreciated as I'm new at this language. Here is what my web.xml looks like:
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>ConnectController</servlet-name>
    <display-name>ConnectController</display-name>
    <description></description>
    <servlet-class>com.hyperx.web.ConnectController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ConnectController</servlet-name>
    <url-pattern>/connect</url-pattern>
  </servlet-mapping>
</web-app>

Here is the class path and code:

Here is the pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.hyperx</groupId>
  <artifactId>trustpilot-app</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>trustpilot-app Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
       <groupId>com.eclipsesource.minimal-json</groupId>
       <artifactId>minimal-json</artifactId>
       <version>0.9.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>trustpilot-app</finalName>
  </build>
</project>

A: It is very difficult to diagnose the problem without more information. Are you using maven to build the application (there is pom.xml)? Show the pom.xml content. The IDE reports a problem on package level - most probable cause is that src/main/java is not a source folder. Which indicates that maven is not building a war. I would suggest to extract the build artifact (war) and see if the com.hyperx.web.ConnectController class is there. Check the log files of the web server to see if the deployment is successful.

A: So I changed hosting providers for this and it worked perfectly. Must have been something related to that server config.  Thanks all for your help.


text:
Q: Selecting a 30 EOD records from an hourly set in MySQL I'm a novice mySQL dev and I'm trying to tackle something a little tricky. I have a table full of hourly records that are timestamped on 'created'.
I need to write a query that will pull 30 records from the table where each record is the last record of the day for the 30 days starting from NOW().
I subsequently need to do the same for 24 weeks and 12 months but I assume once I have 1 query ironed out for the days, I can figure out the rest.
Thanks in advance

A: This isn't hard if you use an appropriate aggregate query.
Assuming your table is records and your DATETIME or TIMESTAMP column is called time_stamp.
Try this:
SELECT DATE(time_stamp) AS the_day,
       MAX(time_stamp) AS eod_timestamp
  FROM records
 WHERE time_stamp >= CURDATE() - INTERVAL 30 DAY
 GROUP BY DATE(time_stamp)

This gets the latest (MAX) time_stamp for each day in the table for the last 30 days.
If you want to locate the exact rows in records that have those end-of-day timestamps, you can join this aggregate query to the records table like so.
 SELECT eod.the_day, r.whatever, r.whatever, r.whatever
   FROM records AS r
   JOIN (
        SELECT DATE(time_stamp) AS the_day,
              MAX(time_stamp) AS eod_timestamp
         FROM records
        WHERE time_stamp >= CURDATE() - INTERVAL 30 DAY
        GROUP BY DATE(time_stamp)
        ) AS eod ON r.time_stamp = eod.eod_timestamp

Notice that the ON clause in the query pulls out the rows from records that have the end-of-day timestamps.  If more than one record has the same end-of-day timestamp, this query will get them all.


text:
Q: Whats the difference between DevOpenHelper and OpenHelper? Whats the difference between DaoMaster.DevOpenHelper and DaoMaster.OpenHelper?
Did not found any explanation when to use what.

A: This is greendao's generated DaoMaster class.
public static abstract class OpenHelper extends SQLiteOpenHelper {

    public OpenHelper(Context context, String name, CursorFactory factory) {
        super(context, name, factory, SCHEMA_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        createAllTables(db, false);
    }
}

/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
    public DevOpenHelper(Context context, String name, CursorFactory factory) {
        super(context, name, factory);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        dropAllTables(db, true);
        onCreate(db);
    }
}

As you can see in the comment:

Drops all table on Upgrade! Use only during development.

I feel like it's pretty self-explanatory.
Also note, that OpenHelper is abstract class, and DevOpenHelper is an implementation of it.


text:
Q: Как правильно перенять функции аудио записи из проекта Captura. Запись микрофона и фонового звука сразу в один файл Столкнулся с проблемой, так как уровень знаний C# низковат.
Есть проект на Github - под названием Captura (Ссылка на Проект).
Выполняю работу по переносу функции записи аудио с микрофона и с плэйбека одновременно в один файл. Программа это делает без создания временных файлов. Запись аудио производит сразу в файл.
На данный момент перенёс библиотеки "Captura.Audio" и "Captura.NAudio", но не могу продвинуться дальше, как мне запустить весь процесс записи и остановить его в нужный момент. Я не могу понять где лежит этот код. Хочу взять только его, без лишнего.
Буду Вам очень благодарен, если поможете прям очень разжёвано, детально и по пунктам.
Суть моего проекта:
Записать разговор с Скайпа или Вайбера так, что бы было слышно меня и собеседника.


text:
Q: get attribute name based on slug I have a page listing articles based on categories.
The category is filtered from the slug in the url.
I want to display a tag in the template with the category name.
With get_context_data I am able to retrive the slug and use it as {{categoryslug}} But how do I get the name of the category given the slug?
Model.py
class Category(models.Model):
    name = models.CharField(max_length=50,unique=True, blank=True)
    slug = models.SlugField(max_length=100,unique=True, blank=True)

def __str__(self):
    return self.name

class Article(models.Model):

    title= models.CharField(max_length=40, blank=True)
    category = models.ForeignKey('Category', on_delete= models.PROTECT, related_name="pcat", blank=True)

    def __str__(self):
        return self.title

View.py
class ListArticleView(ListView):
    model = Article
    context_object_name = "listcat"
    template_name = "myapp/categories.html"
    paginate_by = 5

def get_queryset(self):
    return Article.objects.filter(category__slug=self.kwargs['cat_slug'])

def get_context_data(self, **kwargs):
    context=super(ListArticleView,self).get_context_data(**kwargs)
    context['categoryslug']=self.kwargs['cat_slug']
    return context

URLS.py
path(('/<cat_slug>'), views.ListArticleView.as_view(), name='some_categories'))


text:
Q: org.springframework.dao.CannotAcquireLockException for select sql query I am getting org.springframework.dao.CannotAcquireLockException for select statment. Not sure why spring is trying to put lock for select query.
I am using NamedParameterJdbcTemplate and performing queryforlist. Its all select statements so we are not using and transactions. This database is shared so it might possible there are other application who are writing or performed lock but my app is just read.
This is MS SQL Server.
I am getting exception after 3 secs so looks like spring is trying to get lock and waited for 3 sec and then throws exception.
Below is full exception.
org.springframework.dao.CannotAcquireLockException: PreparedStatementCallback; SQL [select id ticketDBId from fpscdb002_ws_004.incident where ticket_number = ?]; Lock request time out period exceeded.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Lock request time out period exceeded.
    at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:259)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:660)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:695)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:722)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:772)
    at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.queryForObject(NamedParameterJdbcTemplate.java:211)
    at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.queryForMap(NamedParameterJdbcTemplate.java:238)
    at com.abc.servicedesk.fp.dao.FPBaseDAO.getTicketDbId(FPBaseDAO.java:44)


text:
Q: Complex TSQL MultiRow Insert with OutPut I have a temp table as follows
DECLARE @InsertedRows TABLE (RevId INT, FooId INT)

I also have two other tables
Foo(FooId INT, MyData NVarchar(20))
Revisions(RevId INT, CreatedTimeStamp DATETIME)

For each row in Foo, I need to a) insert a row into Revisions and b) insert a row into @InsertedRows with the corresponding Id values from Foo and Revisions.
I've tried writing something using the Insert Output Select as follows:
INSERT INTO Revisions (CURRENT_TIMESTAMP)
OUTPUT Inserted.RevId, Foo.FooId INTO @InsertedRows
SELECT FooId From Foo

However, Foo.Id is not allowed in the Output column list. Also, the Id returned in the SELECT isn't inserted into the table, so that's another issue.
How can I resolve this?

A: You cannot reference the FROM table in an OUTPUT clause with an INSERT statement. You can only do this with a DELETE, UPDATE, or MERGE statement.
From the MSDN page on the OUTPUT clause (https://msdn.microsoft.com/en-us/library/ms177564.aspx)

from_table_name Is a column prefix that specifies a table included in
  the FROM clause of a DELETE, UPDATE, or MERGE statement that is used
  to specify the rows to update or delete.

You can use a MERGE statement to accomplish what you are asking.
In the below example, I changed the tables to be all variable tables so that this could be run as an independent query and I changed the ID columns to IDENTITY columns which increment differently to illustrate the relationship.
The ON clause (1=0) will always evaluate to NOT MATCHED. This means that all records in the USING statement will be used to insert into the target table. Additionally the FROM table in the USING statement will be available to use in the OUTPUT statement.
DECLARE @Foo TABLE (FooId INT IDENTITY(1,1), MyData NVarchar(20))
DECLARE @Revisions TABLE (RevId INT IDENTITY(100,10), CreatedTimeStamp DATETIME)
DECLARE @InsertedRows TABLE (RevId INT, FooId INT)

INSERT INTO @Foo VALUES ('FooData1'), ('FooData2'), ('FooData3')

MERGE @Revisions AS [Revisions]
USING (SELECT FooId FROM @Foo) AS [Foo]
ON (1=0)
WHEN NOT MATCHED THEN
INSERT (CreatedTimeStamp) VALUES (CURRENT_TIMESTAMP)
OUTPUT INSERTED.RevId, Foo.FooId INTO @InsertedRows;

SELECT * FROM @Foo
SELECT * FROM @Revisions
SELECT * FROM @InsertedRows

Table results from above query
@Foo table
+-------+----------+
| FooId |  MyData  |
+-------+----------+
|     1 | FooData1 |
|     2 | FooData2 |
|     3 | FooData3 |
+-------+----------+

@Revisions table
+-------+-------------------------+
| RevId |    CreatedTimeStamp     |
+-------+-------------------------+
|   100 | 2016-03-31 14:48:39.733 |
|   110 | 2016-03-31 14:48:39.733 |
|   120 | 2016-03-31 14:48:39.733 |
+-------+-------------------------+

@InsertedRows table
+-------+-------+
| RevId | FooId |
+-------+-------+
|   100 |     1 |
|   110 |     2 |
|   120 |     3 |
+-------+-------+


text:
Q: OAuth token returning with null properties after storing in Keychain So I've just recently started working with iOS development and am using the PodioKit library to interface with Podio. After authenticating with the server using an email and password, it returns an OAuth token. This has the required data, refresh token, etc.
To keep the user logged in between uses of the app, the OAuth token is supposed to get saved to the keychain, then accessed again on app startup. I've been using JNKeychain to store them in the keychain, and that seems to be working okay. However, when I retrieve the token from the keychain, the data is not the same, meaning that PodioKit throws a "Refresh token missing" error any time I try to do anything. You can see the difference in these NSLog outputs.
Before saving to Keychain:
2014-01-23 15:40:38.069 PodioKPITest[377:60b] oauthToken: <PKOAuth2Token: 0x16d59390>
2014-01-23 15:40:38.071 PodioKPITest[377:60b] oauthToken.refData: {
    id = 1883826;
    type = user;
}
2014-01-23 15:40:38.072 PodioKPITest[377:60b] oauthToken.refreshToken: d9a59577e0574d20bdbc739ccfcf61ce
2014-01-23 15:40:38.073 PodioKPITest[377:60b] oauthToken.accessToken: 53909cabac874fb78fcca7eda87a4e84
2014-01-23 15:40:38.079 PodioKPITest[377:60b] oauthToken.expiresOn: 2014-01-23 12:40:38 +0000
2014-01-23 15:40:38.080 PodioKPITest[377:60b] oauthToken.transferToken: (null)

After loading from Keychain:
2014-01-23 15:41:00.509 PodioKPITest[389:60b] oauthToken: <PKOAuth2Token: 0x14d42cb0>
2014-01-23 15:41:00.512 PodioKPITest[389:60b] oauthToken.refData: (null)
2014-01-23 15:41:00.514 PodioKPITest[389:60b] oauthToken.refreshToken: (null)
2014-01-23 15:41:00.516 PodioKPITest[389:60b] oauthToken.accessToken: (null)
2014-01-23 15:41:00.521 PodioKPITest[389:60b] oauthToken.expiresOn: 2014-01-23 04:40:38 +0000
2014-01-23 15:41:00.523 PodioKPITest[389:60b] oauthToken.transferToken: (null)

Does anyone have any idea why this is happening? Is there a better/more correct place to be storing a token than in the Keychain? Hopefully I've explained myself okay!

A: Yes, the keychain is the right place to store the token since it will be encrypted.
I tried the exact same thing you did with Podio and JNKeychain and for me it did work. Which version of PodioKit and JNKeychain are you using? it seems the the unarchiving fails to restore those property values in your case.
PKOAuth2Token *token = [[PKOAuth2Token alloc] initWithAccessToken:@"access1234"
                                                     refreshToken:@"refresh1234"
                                                    transferToken:@"transfer1234"
                                                        expiresOn:[NSDate dateWithTimeIntervalSinceNow:3600]
                                                          refData:@{@"ref": @"somedata"}];

// Test archiving
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:token];
PKOAuth2Token *archivedToken = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"Restored access token from archive %@", archivedToken.accessToken);

// Test keychain
NSString *keychainKey = @"AuthToken";
[JNKeychain saveValue:token forKey:keychainKey];
PKOAuth2Token *keychainToken = [JNKeychain loadValueForKey:keychainKey];
NSLog(@"Restored access token from keychain: %@", keychainToken.accessToken);

The above prints:
2014-01-23 21:07:22.719 App[17202:70b] Restored access token from archive access1234
2014-01-23 21:07:22.723 App[17202:70b] Restored access token from keychain: access1234

You could always try an alternative keychain wrapper library, like FXKeychain.


text:
Q: python import - import .json file from parent directory I am attempting to import a config.json file into my python script. I have the following python script from a co-worker of mine that does stuff.:
myscript.py
import datetime
import sys
import json

from config import config
...

...and I have the following directory structure:
Project
 |
 +-- config
 |  |
 |  +-- config.json
 |
 +-- scripts
 |  |
 |  +-- myscript.py

I cannot change the directory structure, and I shouldn't change the import statement either, as this is actually a co-workers script that I need to run locally. When I run python3 myscript.py, I receive the following error:
ModuleNotFoundError: no module named 'config'

I am actually not surprised by the error, because I'm not setting a relative path to config. I feel like the import should be from ../config import config, however this is not how my co-worker did it. Also, from ../config import config did not work either.
How can I import config.json without changing the import statement or the directory structure? Perhaps I can add /config to my path?


text:
Q: ListView horizontal like Gallery or any another in place of gallery? I want to implement the horizontal list view as same like gallery. I am getting the images for assets folder and show in gallery like. Gallery just debricated in the android jelly bean so I does not want to use this. Is there any solution that I can use the in place of gallery.

A: <HorizontalScrollView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:scrollbars="none"
     android:isScrollContainer="true">

<ImageView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />
</HorizontalScrollView>


text:
Q: What is the enumerable argument for in Object.create? In what usages of Object.create do you want to set enumerable to true?

A: A property of an object should be enumerable if you want to be able to have access to it when you iterate through all the objects properties. Example:
var obj = {prop1: 'val1', prop2:'val2'};
for (var prop in obj){
  console.log(prop, obj[prop]);
}

In this type of instantiation, enumerable is always true, this will give you an output of:
prop1 val1
prop2 val2

If you would have used Object.create() like so:
obj = Object.create({}, { prop1: { value: 'val1', enumerable: true}, prop2: { value: 'val2', enumerable: false} });

your for loop would only access the prop1, not the prop2. Using Object.create() the properties are set with enumerable = false by default.


text:
Q: Understanding a linear (Ehresmann) connection on a vector bundle I am trying to read this mathematical introduction to Gauge theory and got stuck on the following:
Suppose $\pi : E \rightarrow M$ is a fibre bundle with fibre $F$ and a connection represented by the vertical and horizontal projections $\pi_p^v$ and $\pi_p^h$ for all $p \in E$.
Now specializing to vector bundles the article states that a connection on $E$ "is linear if $\pi_p^h$ varies affinely with $p$ in a fixed fiber $F_{\pi(p)}$, and the canonical zero section of $E$ is horizontal."
I seem to be unable to wrap my head around what that is supposed to mean.
Unfortunately I have not even found a reference on when a section is supposed to be horizontal!
My guess goes like this: Let $\sigma$ be a section of $E$. Then call $\sigma$ horizontal whenever
\begin{equation}
\pi_{\sigma(x)}^v \left ( \mathrm{Im} \; \mathrm{d} \sigma(x) \right ) = \{0\} \qquad \forall x \in M
\end{equation}
The first part is troubling me even more, because it makes me feel I have to interpret the expression
\begin{equation}
\pi_p^h - \pi_q^h
\end{equation}
as the result of a linear map $R$ acting on $(p - q)$ for arbitrary $p$ and $q$ in the same fibre. But I do not see how this could be possible without somehow identifying $T_p E$ and $T_q E$. And what would the codomain of $R$ be?

A: All the notations come from the paper linked in your question, especially p.27 & p.28
You are right about what is an horizontal section. Locally it means that $s$ is a horizontal section if for all $X\in\mathfrak{X}(U)$ we get for all $x\in U$
$$\pi^{v}_{s(x)}(\text{d}s_x(X_{x}))=0$$
If you look at the canonical zero section $0_U:x\to (x,0)$ we get $(\text{d}0_U)_{x}:\xi\to (\xi,0)$, so $\Gamma(x,0)=0$.
If you look now at the affine condition, it means an affine dependency of $\pi^{h}_p$ for $p\in\pi(p)=x$. In the paper linked, a way of identifying all the distinct $TE_p$ locally on $U$ with $p=(x,f)$ is given, by identifying $TE_{(x,f)}$ with $T_xU\times F$, for all distinct $f$, that is to say for all distinct $p$ in the same fiber.
In that case, $\Gamma(x,f)$ is identified with a linear map $T_xU\to F$, and $\pi^h_{(x,f)}(\xi,y)=(\xi,-\Gamma(x,f)\xi)$ must depend the affine way of $f$, and since $\Gamma(x,0)=0$, must depend linearly of $f$, which means exactly $$\Gamma(x)\in\text{Hom}(F,\text{Hom}(T_xU,F))\cong\text{Hom}(T_xU,F^*\otimes F)$$


text:
Q: Find where "Debug assertion failed" error occured I have written a C# application that uses a native mfc library as COM component. This program is running on the server machine to monitor some hardware devices. Although most of the time the application is work properly, Sometimes I'm getting "C++ Debug assertion failed" message box.
I want to know how can I debug my application and see the call stack of my source code when the assertion failed error appear. I have my C# app source code, but the problem is the assertion occurred in unmanaged code. When I attached visual studio debugger to the app, nothing appeared when the assertion failed error was raised!

A: AFAIK you can only debug this if you have the source code of the COM component. Once you've opened that project attach the debugger to the process that will call/load the DLL of the COM component.


text:
Q: How can you use npx create-react-app with templates in a private registry? I'm trying to use npx create-react-app with a --template from a private NPM registry, for example:
npx create-react-app example-app --template @private/mytemplate

I've added a .npmrc file to the root directory that points to the private registry. I've ensured this is setup correctly because I'm able to install private NPM packages without any problems.
However, when I run thecommand it defaults back to the normal NPM registry and I receive an error that my private template package doesn't exist:
404 Not Found - GET https://registry.npmjs.org/@private/mytemplate

If I update the NPM registry manually through npm config set registry [my registry] then I receive an error that create-react-app doesn't exist.
Is there a way to use create-react-app from the public registry and point to a template stored in my private registry in a single command? Or in other words, how can you use npx create-react-app with templates stored in a private registry?

A: I was able to figure this out. Instead of changing my registry with npm config set registry [my registry] I just needed to alias the registry for my specific private packages.
This was done by running:
npm config set @mypackagename:registry [my registry]

The @mypackagename:registry was the key point of confusion where "registry" is the actual value and not a placeholder.


text: Q: How to segment the parts of the face eg the cheeks I am trying to segment the cheeks in a face image. I've tried image segmentation but that segments the whole face and removes the background. I have also tried contouring but I can't seem to locate the contours in the image. Can anyone help me?


text:
Q: colors not showing at print how can i do so that when printing my html page it keeps the colors (print to pdf)

                Elev
                Session navn
                Spørgsmål
                Svar
                Rigtigt svar
                Dato

                        test
                        testing
                        test
                        test
                        test
                        test

                    <button class="btn btn-block btn-default" onclick="deactivate">Deaktiver</button>

                #3

the idea is that i get the data from my database, and gets displayed in the table above. if the row is correct then it turns green by adding the success class to the row. and danger if its wrong (red and green).
this is beeing displayed great when just browsing the webpage. how ever when i try to print it. then the background colorering is off. how can i fix this?

A: You can't print the table colors because bootstrap has a css @media print rule that prevents this. At one time, I had known a great fix I found elsewhere on the internet but when I upgraded my bootstrap version, I removed it by accident. (Hence, why I found my way here.) If you look inside your bootstrap.css file (Bootstrap Version 3.3.4, not the minimized file bootstrap.min.css) between lines 196-269 you will find the rule that does this.
196  @media print {
197  *,
198  *:before,
199  *:after {
200  background: transparent !important;
...
264  }
265  .table-bordered th,
266  .table-bordered td {
267  border: 1px solid #ddd !important;
268  }
269  }

One option would be to remove the rule entirely or remove the pragmatic lines. Problem with option one is this media rule also does things like removes the navbar and text shadows, so probably best to go with option two. I inserted my modified version of the rule below, it might still need some fine tuning and will vary if you're using a different version of bootstrap.
@media print {
    *, *:before, *:after {
        -webkit-box-shadow: none !important;
        box-shadow: none !important;
        text-shadow: none !important;
    }
    a, a:visited {
        text-decoration: underline;
    }
    a[href]:after {
        content: " (" attr(href) ")";
    }
    abbr[title]:after {
        content: " (" attr(title) ")";
    }
    a[href^="#"]:after, a[href^="javascript:"]:after {
        content: "";
    }
    pre, blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }
    thead {
        display: table-header-group;
    }
    tr, img {
        page-break-inside: avoid;
    }
    img {
        max-width: 100% !important;
    }
    p, h2, h3 {
        orphans: 3;
        widows: 3;
    }
    h2, h3 {
        page-break-after: avoid;
    }
    select {
        background: #fff !important;
    }
    .navbar {
        display: none;
    }
    .btn> .caret, .dropup> .btn> .caret {
        border-top-color: #000 !important;
    }
}

I removed lines 200, 201, and 255-268. If you prefer to use the minimized version of bootstrap, you will need to either find the same lines there or minimize your non-minimized one. There are websites online that can do this for you, as well as many IDEs will usually have a built-in minimizer.

A: The printing of background colours is a browser setting, not something that can be controlled with code.
There are plenty of knowledge base articles for the respective browsers outlining the process to enable this:
Internet Explorer > https://support.microsoft.com/en-us/kb/296326
Google Chrome > https://productforums.google.com/forum/#!topic/chrome/rywToswM-EY
Mozilla Firefox > https://support.mozilla.org/en-US/kb/how-print-websites#w_advanced-tips

A: Added the following css, and it worked
tr.success td {
    background-color: #dff0d8 !important;
    -webkit-print-color-adjust: exact;
}

tr.danger td {
    background-color: #f2dede !important;
    -webkit-print-color-adjust: exact;
}


text:
Q: Replying with multiple answers in Akka I have a communication to one Actor:
val future = ask(foo, Bar())(1 seconds).mapTo[Row]
val result = Await.result(future, 1 seconds)

This works fine as long as I only send one Row back from foo. How would I reply with multiple Rows:
sender() ! Row()
sender() ! Row()

subsequently in foo?

A: As others have mentioned in the comments, the ask pattern will only work if you send all the rows as a single message. Using akka-stream is a great solution for building a processor for this:
val barActor = system.actorOf(Props(new BarActor()))

def runQuery(): Future[Seq[Row]] = {
  // complete when EndOfQuery message is received
  val runnableGraph = Source.actorRef[DataProtocol](Int.MaxValue, OverflowStrategy.fail)
    .takeWhile(elem => {
      elem match {
        case _:Row => true
        case _ | EndOfQuery => false
      }
    })
    .toMat(Sink.seq[DataProtocol])(Keep.both)

  // keep both the ActorRef and the Future[DataProtocol]
  val (actor, future) = runnableGraph.run()

  // issue query to actor
  barActor ! Query(actor)

  // only Row messages were emitted:
  future.map(_.asInstanceOf[Seq[Row]])
}

val data = Await.result(runQuery(), Duration.Inf)

As you mentioned in your question, you'll need a stop message.

A: You can respond only with one object. What about reponding a list?
class Foo extends Actor {
  def receive = {
    case Bar(): sender() ! List.of(Row(), Row())
  }
}

val future = ask(foo, Bar())(1 seconds).mapTo[List[Row]]
val result = Await.result(future, 1 seconds)

val row0 = result(0);
val row1 = result(1);

A: I'm not 100% sure what you are hoping to accomplish, without more context. I suspect that @lasekio's answer is likely exactly what you are looking for.
But if you are looking for an asynchronous streaming solution, that is, if you want to process rows as they come in, rather than wait until they are all available (perhaps because there are more rows than will fit in memory - millions/billions), then, well, then you should use Akka Streams. But since it seems like you are against that, here's an alternative that is pure Akka + Futures:
The actor will be returning the row, plus a future of the next row. Since you need a way to indicate that there are no more rows, I'm wrapping the result in an Option in my example, where Some contains the Row and future of next Row, while None means there are no more rows. You can also create a separate type, or use null, just something that clearly indicates that there is no further data. On the actor side, you'd do:
case _: Bar =>
  if (/*... there are more rows...*/) sender() ! Some((Row(), (context.self ? Bar()))
  else sender() ! None

On the consumer side:
def consumeRows(rowsFut: Future[Option[(Row,Future[_])]]): Unit = {
  rowsFut.foreach {
    _.foreach {
      case (row: Row, nextRowsFut: Future[Option[(Row,Future[_])]]) =>
        // Do something with row
        println(row)
        consumeRows(nextRowsFut)
  }
}
val rowsFut = ask(foo, Bar())(1 seconds).mapTo[Option[(Row,Future[_])]]
consumeRows(rowsFut)