text:
Q: How do I find the days between two dates in JavaScript or jQuery datepicker? I am using jQuery datepicker. In my application, I have startDate and endDate date ranges.
If my date range is less than a week(7 days), I need to disable some day textbox's. Please see the image below
Expected output:

I can able to get the number of days difference between to dates like this;
var startDate = $('#startDate').datepicker('getDate');
var endDate = $('#endDate').datepicker('getDate');
//find difference between start and end date
var noOfDays = Math.ceil((startDate - startDate) / (1000 * 60 * 60 * 24));

If noOfDays is less than 7 days, I need to disable the day textbox according to the date range. For that I need list days between date ranges.
According to my example image Mon and Sun should be disabled.
['Tue','Wed','Thu','Fri','Sat'] or corresponding UTC day values ['1','2','3','4','5'] should be enabled.
Can anyone guide me to get day values?

A: Try this :
month is start from 0.
var from = new Date(2016, 11, 29);
var to = new Date(2016, 11, 31);
var DAYS = ['Sun', 'Mon', 'Tu', 'Wed', 'Th', 'Fri', 'Sat'];

var d = from;
while (d <= to) {
    alert(DAYS[d.getDay()]);
    d = new Date(d.getTime() + (24 * 60 * 60 * 1000));
}


text:
Q: Delete one row from a table. My code deletes the whole table I'm trying to delete only one row, but sometimes nothing happens, and sometimes the whole table (but the headers) are deleted.
// This is the code I'm using in my php file:

      #
      Name
      Email
      Delete

My code for jquery, with the code below, I insert one row in the table:
counter = counter + 1;
$("#tb_people").find('tbody')
  .append($('
')
    .append($('')
      .append($('')
        .text(counter)
      )
    )
    .append($('')
      .append($('')
        .text($("#inputPerson").val())
      )
    )
    .append($('')
      .append($('')
        .text($("#inputEmail").val())
      )
    )
    .append($('')
      .append($('Delete'))
    )
  );

And here is the code I'm using to delete one row. Using any of the two options below, it happens the same:
$(".deleteLink").on("click", function(){
   $(this).closest('tr').remove();
   return false;
});

And here another way:
$(".deleteLink").on("click", function(){
    var tr = $(this).closest('tr');
    tr.css("background-color","#FF3700");
    tr.fadeOut(400, function(){
       tr.remove();
    });
    return false;
});

If I add the symbol # to the link (href), nothing happens:
.append($('Delete'))

A: You need to use a delegated event handler as the .deleteLink element is dynamically appended to the page after it has been loaded. Try this:
$("#tb_people").on('click', '.deleteLink', function(e) {
   e.preventDefault();
   $(this).closest('tr').remove();
});

A: You can delete a Record by using effects like fading out the record from the table.Try this
$(document).ready(function() {
    $("#sample tr").click(function() {
        //change the background color to red before removing
        $(this).css("background-color","#FF3700");

        $(this).fadeOut(400, function(){
            $(this).remove();
        });
    });});

A: I am not sure but you can delete this below method in your every row
Delete

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pytorch: Disable only nn.Dropout() without using model.eval() nn.Dropout() can be disabled by using model.eval().However by using .eval(), nn.BatchNorm1d() are also disabled. Because the distributions between train and test sets are different, I'd like to disable only Dropout for generating data by GAN.
Is there any way to disable only Dropout after training?
Here is the generator model in my GAN.
class Generator(nn.Module):
def __init__(self, num_input=2, noise_dim=1, num_output=5, hidden_size=128):
    super(Generator, self).__init__()

    self.fc_in = nn.Linear(num_input+noise_dim, hidden_size)
    self.fc_mid = nn.Linear(hidden_size+num_input+noise_dim, hidden_size)
    self.fc_out = nn.Linear(2*hidden_size+num_input+noise_dim, num_output)

    self.bn_in = nn.BatchNorm1d(hidden_size)
    self.bn_mid = nn.BatchNorm1d(hidden_size)

    self.dropout = nn.Dropout()

    self.relu = nn.ReLU()

def forward(self, y, z):
    h0 = torch.concat([y,z],axis=1)
    h1 = self.relu(self.bn_in(self.fc_in(h0)))
    h1 = self.dropout(h1)
    h1 = torch.concat([h0,h1],axis=1)
    h2 = self.relu(self.bn_mid(self.fc_mid(h1)))
    h2 = self.dropout(h2)
    h2 = torch.concat([h1,h2],axis=1)
    x = self.fc_out(h2)
    return x

A: The answer in the comment is right, you can run eval() on single modules.
But... why do you think you need to keep the BatchNorm active after training? By default, in eval mode it will use the running average/std computed during training (which is a good thing, and makes the model give the same outputs regardless of the batch size or the content of the batch). The outputs should be closer to the ones in training when the batchnorm is in eval mode. Sometimes it's beneficial to recompute the batch norm mean/std after the training (but still later using the whole model in eval mode afterwards). There are some rare cases when you might want to use it in train mode, but make sure that it's what you want.


text:
Q: Missing access token under ./auth/me using Easy Auth I'm creating an Azure Static Web App with the built-in (Easy Auth) authorization to the Azure AD. This works well, but I would also like to authorize access to user-specific data in another API (AWS, but I have registered also this as an app in Azure AD). My thought was to do this with an access token, but heading to the /.auth/me only gives me the following information:

identityProvider
userId
userDetails
userRoles: [
"authenticated",
"anonymous"
]
claims: aud, iss, iat, nbf, exp, aio, c_hash, name, nonce, .../objectidentifier, preferred_username, rh, .../nameidentifier, .../tenantid, uti, ver

The available cookies are: AppServiceAuthSession. AppServiceAuthSession1 and StaticWebAppsAuthCookie
I have set "accessTokenAcceptedVersion": 2 in the Azure AD app, as well as
enabling both access and id tokens.
My staticwebbapp.config.json has this in it (with <TENANT_ID> and <API_AD_APP> replaced) :
    "identityProviders": {
      "azureActiveDirectory": {
        "registration": {
          "openIdIssuer": "https://login.microsoftonline.com/<TENANT_ID>/v2.0",
          "clientIdSettingName": "AZURE_CLIENT_ID",
          "clientSecretSettingName": "AZURE_CLIENT_SECRET"
        },
        "login": {
          "loginParameters": [
            "scope=openid profile email offline_access api://<API_AD_APP>/user_impersonation",
            "response_type=code id_token"
          ]
        }
      }
    }
  },

In the API app AD I have set added the user_impersonation scope under "Expose an API", and authorized my main AD app to use it.
Is it possible to get hold of the access cookie this way, or do I have to switch to requesting it using MSAL instead?
EDIT:
There is now an issue about enabling this functionality:
https://github.com/Azure/static-web-apps/issues/794


text:
Q: Dealing with lag in XNA + lidgren I am experimenting with lidgren in XNA and I'm having some issues with the 'lag'.
I've downloaded their XNA sample and noticed that even their sample lags.  The thing is, the movement is not smooth on the other side, and I'm trying this on a LAN (on the same computer actually) not over the internet.
Has any had the same issues as regards unsmooth movement due to a lagging connection with lidgren and XNA ?

A: The sample you linked directly sets the position to whatever it receives from the network, this is a bad idea for a multiplayer game!
What you should do in a real game is interpolate between the local position and the remote position. So, your receive method would look a little like this:
void Receive(packet)
{
    unit.RemoteX = packet.Read_X_Position();
    unit.RemoteY = packet.Read_Y_Position();
}

This has no affect on the local position on the unit, instead in your update method (every frame), you move the local position towards the remote position:
void Interpolate(deltaTime)
{
    difference = unit.RemoteX - unit.LocalX
    if (Math.Abs(difference) < threshold)
        unit.LocalX = unit.RemoteX
    else
        unit.LocalX += difference * deltaTime * interpolation_constant
}

You then display the "local" position of the unit, this achieves lagless movement like so:

*

*If the unit position is almost at the remote position, it will jump to the remote position (however, it will jump such a tiny distance that it won't look laggy).

*If the difference is too big to jump, then move slowly towards the position you should be in.

Since the unit moves smoothly towards where it should be, it looks like there is no lag at all!
The interpolation constant controls how fast the local and remote positions will converge:

*

*0: Ignore network updates

*Small: Snap into place very quickly (possibly look laggy)

*Large: Slide slowly into place, looks smooth but may feel unresponsive

You need to choose a compromise somewhere in between these options.
There are some other things to consider when implementing this kind of system, for example you often want an upper limit on how far apart units can be from their remote position otherwise the local and remote state can become "unstuck" in some situations. If they are too far apart (which should never happen except in cases of extreme lag) you can either halt the game and tell the user it's too laggy, or jump the unit straight into position, which will look laggy but at least the game will continue.
Addendum: Rereading this answer, it occurs to me that an enhancement would be to track time differences. If you know (roughly) what the lag is in the system, then you know that when you receive a packet with a remote position in you know roughly how far into the past that packet is from. If you send remote velocity too, you can predict where the object is now (assuming constant velocity). This may make the difference between estimated local state and true remote state smaller in some games, in other games (where you have lots of changing velocities) it might make things worse.

A: I've been looking at writing a multiplayer fps game, starting with a demo of just moving some cubes around and replicating the position/rotations on another machine, which is in a spectator mode.
I'm using your code sample above and it's working well (I've had to tweak the interpolation constant higher than 1 to make it look smooth).
I've seen a few interpolation examples which take into account the time difference between the current time and the time stamp on the received message.
I see this code does not use the time difference, so interpolation will take as long as it needs to, to get to the target value (or at least within the threshold value to then snap into position). My question is, is there any advantage to this?
Many thanks.


text:
Q: Authenticate that a user has logged in with MSAL/Azure AD and serve them a token for my separate API? I have an api written in GO that, at the moment, serves an authorization token based on a username and password. (Without MSAL)
I am trying to implement MSAL logins with Microsoft accounts. I have setup my angular frontend to log a user in to an Azure AD app registration. Would it be possible to authenticate that they have successfully logged in to the Azure AD, and serve them one of my tokens (unrelated to msal) from my GO API?
The username that they use to login with MSAL also exists in my backend, the flow would be something like this;
User logs in with MSAL -> my frontend makes a request to golang backend with username -> golang verifies that this username has logged in with MSAL -> backend serves a token for this user
It appears golang integration with MSAL is limited, so not sure how possible this is.
Thanks.

A: What you can do is acquire an access token for your API in the front-end from Azure AD. For this you will either register the API in Azure AD or use the same app registration. Either way, you should add a scope in the Expose an API page in the registration. Your front-end can then use that scope's id to get the needed token.
Your API can then have an endpoint that validates the access token, and issues the local token. The access token will contain the user's username for example, if you want to map to that. A more robust way would be to map to the user's object id (also in the token) since it is immutable, unlike the user email.
For token validation, you should be able to use a generic JWT validation library. Also remember to check for that scope in the token that you defined to properly authorize the request.


text:
Q: How i can get html tag from component in React I need to set addEventListener on button, this is how my component looks like
import { Component } from "react";

class AddPass extends Component{
    render(){
        let btn1 = document.querySelectorAll('.btn1')
        console.log(btn1)
        return

Password generator

            <input type="password" id='addPass'></input>
            <button className="btn1"></button>

    }
}
export default AddPass

this is code in index.js file
ReactDOM.render(

    <App/>

,
  document.querySelector(".app")
);

btn1 is null, and i don't know why

A: You shouldn't be mixing native JS element methods with React as React has it's own process for updating the DOM. Here's some documentation on how to get properly started with React.
What you should be doing is adding listeners to the elements in the JSX and passing them handlers that can then, in your example, add changes in the input value to state, or log the state when you click the button.
Note: I've used a functional component rather than a class in this simplified example as they're a little easier to understand.

const { useState } = React;

function Example() {

  const [ input, setInput ] = useState('');

  function handleInput(e) {
    setInput(e.target.value);
  }

  function handleClick(e) {
    console.log(`Password: ${input}`);
  }

  return (

      <input type="password" onChange={handleInput} />
      <button onClick={handleClick}>Click</button>

  );

};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);


text:
Q: When to run regression test suite vs full test suite for mobile apps?
   I have some prior experience in regression test suite vs full automation suite testing, but when it comes to mobile apps, what are the best practices? For mobile apps. are the following correct?

*

*Smoke or BAT tests are needed when regression test suite takes a long time and developers need immediate feedback. Then smoke runs as part of every check-in?

*Regression test suite is the ideal one to run against every check-in but if takes long, it should run at least nightly? Should it be a fixed set or changed dynamically per release as per what you think needs to be "regressed"?

*Full suite should be run once prior to release, but in which environment - is it against dev or QA environments (or) against staging or pre-prod? If it is not suitable for staging or pre-prod, should I then run regression against stage or pre-prod?

How will above strategy change if some part of app has to be manually tested (either not automatable or work in progress)?
How does the above change for normal web projects?
Thanks.
Paddy

A: Good question.
At first, i would recommend to look into these 2 blog posts which i wrote around mobile test automation - in general, i believe that the context of your tests should be derived from the most sensitive changes you are making to your mobile app. If e.g. you changed the Login area in your app - it is definitely relevant to assure that you 1st develop new tests (unit/functional) to cover these changes + execute
1) https://mobiletestingblog.com/2016/05/07/7-mobile-test-automation-best-practices/
2) https://mobiletestingblog.com/2016/02/11/tests-to-include-within-automation-suite/
If you have some kind of dashboard to show trending across latest mobile app builds where you see the added value from defect perspective to your existing test suite you should leverage this data as well
Hope that helps.


text:
Q: Copy files to another package folder (root, su) I have my application's package (com.my.package) and i'd like to be able to copy some files (a.txt, b.txt and c.txt) to another package (data/data/com.another.package/files). Now i've tried a few things i found, but none worked. Any help please?

A: You need to get the Runtime and use the cat command.
Runtime.getRuntime().exec("su cat filepath1 > filepath2");

A: Runtime.getRuntime().exec("su cat filepath1 > filepath2");

creates an empty file for me too. I have to use su -c instead
Runtime.getRuntime().exec("su -c cat filepath1 > filepath2");


text:
Q: SQL CE DB doesn't read on Windows 6.5 device when building on Win 7 - Win 8 I seem to have the same issue as another user here SQLServerCE SDF file on Windows 7 however the advice from that thread hasn't resolved my issue.
This relates to SQL Server CE v3.1 (DLL Version 3.0.5300.0) whereby I am able to build the SDF file using a utility on a Windows XP 32 bit machine but using the same compiled code and DLL's on both my Win 7 Dev Machine & a Standalone Win 8 Machine it will not allow the database to be queried correctly on the device.
Say for example.
SELECT Name FROM USERS WHERE Name = 'Joey'

Should return 1 result from the DB. If it was compiled on the windows XP machine it will work, if it is compiled on a Windows 7 / 8 machine it wont be read and the result set is 0.
This some odd behaviour as not all queries are effected. If the same table is queried with a different where clause, the result is different. Checking the file directly in VS 2005 or using a utility I wrote to read out .SDF files, I can see the query works fine on both Windows 7 / 8.
It would appear this only becomes an issue once the SDF file is copied to the Windows 6.5 device. This has the same DLL's as the application that built the file SQL Server CE v3.1 (DLL Version 3.0.5300.0).
I have checked and can see it's not down to the x64 / x32 architecture as it's the same result when building on a 32 bit or 64 bit Win 7 or Win XP machine.
From the last post I did see some breif but helpful info from MS (http://blogs.msdn.com/b/sqlservercompact/archive/2009/04/01/after-moving-the-database-from-one-platform-to-other-the-first-sqlceconnection-open-takes-more-time.aspx)
I am looking for a resolution to this, but any additional information would help such as... how to check the DLL version running on the device (like the Modules) window in Visual Studio would really help.

A: If you ever have such misfortune to have to use an early version of SQL Server CE (< 3.0.5300.0) then this is an interesting issue. Whilst it was a limitation at the time it's taken a while to work through to a resolution.
I re-checked over everything on the device. Now whist the installer package had the right DLL included in it for 3.0.5300.0 these were not copied to the application directory "$\DEVICE\Program Files\My Application". In order for me to be able to compile the database on Windows 7 /8 and have that database work on a Windows 6.5 device I had to manually ensure that the correct files were in both the desktop application and on the windows device.
The files I included in both applications were as follows:-

*

*sqlceca30.dll

*sqlcecompact30.dll

*sqlceer30EN.dll

*sqlceme30.dll

*sqlceoledb30.dll

*sqlceqp30.dll

*sqlcese30.dll

*System.Data.SqlServerCe.dll

They have a version of 3.0.5300.0 and date modified of 22/12/2006 and I sourced them from "C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v3.1", when compiling under any earlier version (for me anyway) failed.
Hope it helps anyone else who might get stuck with this as I didn't see much out there.


text:
Q: Removing a gap in vertical lines in a table How I can resolve this table problem. It cut a part of vertical line.
\documentclass{article}
\usepackage{amsmath}
\usepackage{array}
\usepackage[italian]{babel}
\usepackage{float}
\begin{document}

\begin{table}[H]
    \centering
    \begin{tabular}{>{\centering}m{0.22\textwidth}|>{\centering}m{0.20\textwidth}|>{\centering}m{0.20\textwidth}|>{\centering}m{0.20\textwidth}}
             & $x=10$ & $x=100$ & $x=1000$\tabularnewline[0.2em]
            \hline \\
            $y=\log_{10}x$ & $1$ & $2$ & $3$\tabularnewline[0.5em]
            $y=x^2$ & $10^2$ & $10^4$ & $10^6$\tabularnewline[0.5em]
            $y=10^x$ & $10^{10}$ & $10^{100}$ & $10^{1000}$
    \end{tabular}
\end{table}
\end{document}

A: You should remove \\ after \hline as suggested by David Carlisle in the comment. If you want to add some vertical space after the 1st horizontal line, you can follow this answer by Mico. Combining these two, the code is as follows:
\documentclass{article}
\usepackage{amsmath}
\usepackage{array}
\newcommand\Tstrut{\rule{0pt}{2.6ex}}         % = `top' strut
\usepackage[italian]{babel}
\usepackage{float}
\begin{document}

\begin{table}[H]
    \centering
    \begin{tabular}{>{\centering}m{0.22\textwidth}|>{\centering}m{0.20\textwidth}|>{\centering}m{0.20\textwidth}|>{\centering}m{0.20\textwidth}}
             & $x=10$ & $x=100$ & $x=1000$\tabularnewline[0.2em]
            \hline
            $y=\log_{10}x$\Tstrut & $1$\Tstrut & $2$\Tstrut & $3$\Tstrut\tabularnewline[0.5em]
            $y=x^2$ & $10^2$ & $10^4$ & $10^6$\tabularnewline[0.5em]
            $y=10^x$ & $10^{10}$ & $10^{100}$ & $10^{1000}$
    \end{tabular}
\end{table}
\end{document}

A: Your problem is \hline\\ which could be
\hline &&& \\[-1.5ex]

(experiment the value). In general it's best to use ex units for vertical spacing.
I propose three realizations of the table, in decreasing order of ugliness.
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[italian]{babel}
\usepackage{amsmath}
\usepackage{array}
\usepackage{booktabs}

\begin{document}

\begin{center}

\begin{tabular}{
  w{c}{0.22\textwidth}|
  w{c}{0.20\textwidth}|
  w{c}{0.20\textwidth}|
  w{c}{0.20\textwidth}
}
& $x=10$ & $x=100$ & $x=1000$ \\
\hline
&&&\\[-1.5ex]
$y=\log_{10}x$ & $1$ & $2$ & $3$ \\[1ex]
$y=x^2$ & $10^2$ & $10^4$ & $10^6$ \\[1ex]
$y=10^x$ & $10^{10}$ & $10^{100}$ & $10^{1000}$
\end{tabular}

\end{center}

\begin{center}

\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}}cccc@{}}
\toprule
& $x=10$ & $x=100$ & $x=1000$ \\
\midrule
$y=\log_{10}x$ & $1$ & $2$ & $3$ \\
\addlinespace
$y=x^2$ & $10^2$ & $10^4$ & $10^6$ \\
\addlinespace
$y=10^x$ & $10^{10}$ & $10^{100}$ & $10^{1000}$ \\
\bottomrule
\end{tabular*}

\end{center}

\begin{center}

\setlength{\tabcolsep}{1em}
\begin{tabular}{@{}lccc@{}}
\toprule
Funzione & \multicolumn{3}{c@{}}{Valore di $x$} \\
\cmidrule{2-4}
& $10$ & $100$ & $1000$ \\
\midrule
$y=\log_{10}x$ & $1$ & $2$ & $3$ \\
\addlinespace
$y=x^2$ & $10^2$ & $10^4$ & $10^6$ \\
\addlinespace
$y=10^x$ & $10^{10}$ & $10^{100}$ & $10^{1000}$ \\
\bottomrule
\end{tabular}

\end{center}

\end{document}

Avoid [H]; if there is no caption, a center environment suffices. If there's a caption, let the environment float.

I left "y=", but I consider it bad mathematical usage.

A:
\documentclass{article}
\usepackage{amsmath}
\usepackage{array}
\usepackage[italian]{babel}
\usepackage{float}
\begin{document}

\begin{table}[H]
\centering
\begin{tabular}{>{\centering}m{0.22\textwidth}|>{\centering}m{0.20\textwidth}|>{\centering}m{0.20\textwidth}|>{\centering}m{0.20\textwidth}}
     & $x=10$ & $x=100$ & $x=1000$\tabularnewline[0.2em]\hline
     & & &\tabularnewline[0.2em]
    $y=\log_{10}x$ & $1$ & $2$ & $3$\tabularnewline[0.5em]
    $y=x^2$ & $10^2$ & $10^4$ & $10^6$\tabularnewline[0.5em]
    $y=10^x$ & $10^{10}$ & $10^{100}$ & $10^{1000}$
\end{tabular}
\end{table}
\end{document}

A: You can't put \\ after \hline. If you want to add space after \hline, you can add \noalign{\vskip1mm}. This will break the vertical rule. However, if you use {NiceTabular} instead of {tabular}, the rules won't be broken (with nicematrix, the rules are drawn with PGF/Tikz after the construction of the array).
\documentclass{article}
\usepackage{amsmath}
\usepackage{array}
\usepackage[italian]{babel}
\usepackage{float}
\usepackage{nicematrix}

\begin{document}

\begin{table}[H]
\centering
\begin{NiceTabular}{>{\centering}m{0.22\textwidth}|>{\centering}m{0.20\textwidth}|>{\centering}m{0.20\textwidth}|>{\centering}m{0.20\textwidth}}
     & $x=10$ & $x=100$ & $x=1000$\tabularnewline[0.2em]
    \hline
    \noalign{\vskip1mm}
    $y=\log_{10}x$ & $1$ & $2$ & $3$\tabularnewline[0.5em]
    $y=x^2$ & $10^2$ & $10^4$ & $10^6$\tabularnewline[0.5em]
    $y=10^x$ & $10^{10}$ & $10^{100}$ & $10^{1000}$
\end{NiceTabular}
\end{table}
\end{document}

You need several compilations (because nicematrix uses PGF/Tikz nodes under the hood).


text:
Q: Nuget server will corrupt my file's encodgin on local TFS when i push a package in nuget server (on a local TFS), it will corrupt file's encoding. of course if i open my index.cshtml in notepad it will show me utf-8 encoding but VS can't show unicode characters in run time and i have to open the cshtml file in notepad and saveAs it by utf-8 encoding.

A: Do you mean that VS can not show the unicode characters correctly, but they can be showed correctly in VS after saving the file with utf-8 encoding?
In order to run UTF-8, you need a Byte Order Mark (BOM) sometimes called a signature. According to the description in this MSDN article:

Unicode characters are now supported in identifiers, macros, string
and character literals, and in comments. Universal character names are
also now supported.
Unicode can be input into a source code file in the following
encodings:

*

*UTF-16 little endian with or without byte order mark (BOM)

*UTF-16 big endian with or without BOM

*UTF-8 with BOM

For the love of all things decent, do NOT use "UTF-8 with BOM!"
You can try to recreate the nuget package in VS with the utf-8 encoding files, then publish it to the server, then try it again. While please note below things:

*

*Use the UTF-8 character encoding for the *.nuspec

*Do not save your *.nuspec files with a Byte Order Mark (BOM). A BOM
is neither required nor recommended for UTF-8, because it can lead to
several issues.

*Specify the UTF-8 encoding in the first line of your *.nuspec files
like so: <?xml version="1.0" encoding="utf-8"?>.
Also reference this thread: UTF-8 without BOM


text:
Q: Join on Id in Variant (Array) Snowflake I have two tables t1 and t2 created as follows:
Create Tables
CREATE TABLE t1(
    id integer AUTOINCREMENT START 1 INCREMENT 1,
    name varchar(10) DEFAULT RANDSTR(10, random()),
    id_array variant,
)

CREATE TABLE t2(
    id integer AUTOINCREMENT START 1 INCREMENT 1,
    name varchar(10) DEFAULT RANDSTR(10, random())
)

Goal
I am looking to join t2 to t1 if the id of the record exists in the t1 variant array.
What I've Tried
I came across the ARRAY_CONTAINS function which looked perfect. But with the following I am receiving no results:
SELECT t1.id, t2.name
FROM t1, t2
WHERE ARRAY_CONTAINS(t1.id_array, array_construct(t2.id))

How Do I Get This?
Any suggestions on how to achieve the following result?
t1 record:
{id: 1, name: 'A-123', ids_array: '["1", "2"]'}

t2 records:
{id: 1, name: 'test'},
{id: 2, name: 'test2'}

Desired Result
{id: 1, name: 'A-123', joined_name: 'test'},

{id: 1, name: 'A-123', joined_name: 'test2'}

A: ARRAY_CONTAINS expects the following parameters: variant and array:
SELECT t1.id, t2.name
FROM t1, t2
WHERE ARRAY_CONTAINS(t1.id_array, array_construct(t2.id))

should be rather:
SELECT t1.id, t2.name
FROM t1
JOIN t2
  ON ARRAY_CONTAINS(t2.id::variant, t1.id_array)

A: So to debug what's happening I added more and more line to the below SQL, but the short story is you have the parameters to ARRAY_CONTAINS back to front:
WITH t1(id, name, ids_array) AS (
    SELECT column1, column2, SPLIT(column3,',') FROM VALUES
        (1, 'A-123', '1,2')
), t2(id, name) AS (
    SELECT column1, column2 FROM VALUES
        (1, 'test'),
        (2, 'test2')
)
SELECT t1.id
    ,t2.name
    ,t2.id
    ,t1.ids_array
    ,ARRAY_CONTAINS('1'::variant, t1.ids_array) as const_1
    ,ARRAY_CONTAINS('2'::variant, t1.ids_array) as const_2
    ,t2.id::text::variant as v1
    ,ARRAY_CONTAINS(v1, t1.ids_array) as it_works
FROM t1, t2

gives:

ID
NAME
ID
IDS_ARRAY
CONST_1
CONST_2
V1
IT_WORKS

1
test
1
[    "1",    "2"  ]
TRUE
TRUE
"1"
TRUE

1
test2
2
[    "1",    "2"  ]
TRUE
TRUE
"2"
TRUE

so now using the correct form:
WITH t1(id, name, ids_array) AS (
    SELECT column1, column2, SPLIT(column3,',') FROM VALUES
        (1, 'A-123', '1,2')
), t2(id, name) AS (
    SELECT column1, column2 FROM VALUES
        (1, 'test'),
        (2, 'test2')
)
SELECT t1.id
    ,t2.name
FROM t1, t2
WHERE ARRAY_CONTAINS(t2.id::text::variant, t1.ids_array)

we get:

ID
NAME

1
test

1
test2


text:
Q: Cohort analysis in a long time-series dataset: how do I retain people who move in and people who move out of the cohort? I need help with a dataset that contains individuals between 0-17 years of age between the years 1997-2019. The dataset is in a long format, thus, there's multiple rows for each individual. I follow cohorts of people of a certain age at a certain time (e.g., newborns at year 1997, newborns at year 1998, 1-year olds at year 1997 etc), and look at the retantion-rate over time.
So for example, the newborn-cohort in 1997, how many of these people are still in the same town (and are alive) for each following year? So far all fine.
Now, I want to look at the individuals in each cohort that does not stay in the cohort. So for each year I want
a) a summary of people moving out/dying, and
b) a new df containing all these people for the whole time-serie (1997-2019), as well as
c) people moving out and later on also moving back in (which makes them join the cohort again).
I asked a similar question recently (Retain observations that hasn't occured in the year before in a long time-series dataset in R)
where I got an answer using split(), setdiff() and a for()-loop to succeed. It worked out well, but I can't figure out how to write the code to give me the results described above.
Edit: I added some example-code of what code I used to create my cohorts:
###The following codes gives me newborn cohorts per year and
follows each cohort over time
#Flag newborns in the long dataset and keep only those individuals
that #at one of the years has been 0 years old
output_long_newborn %<>%
  arrange(ID, Year) %>%
  group_by(ID) %>%
  mutate(
  flag_newborn2 = case_when(
    Age==0 ~ 1,
    TRUE ~ 0
  )) %>%
mutate(
  flag_newborn = case_when(
    sum(flag_newborn2) > 0 ~ 1,
    TRUE ~ 0
  )) %>%
filter(flag_newborn==1) %>%
ungroup()

#Create cohort-df for newborns
users_1997_2019_newborn <- output_long_newborn %>%
  arrange(Year, ID) %>%
  group_by(ID) %>%
  slice_min(Year, n = 1) %>%
  dplyr::rename(cohort = Year)

 #Create final df
  cohort_1997_2019_newborn <- output_long_newborn %>%
  group_by(Year, ID) %>%
  distinct() %>%
  left_join (users_1997_2019_newborn, by = 'ID') %>%
  xtabs(~ cohort + Year, data = .)```

That's step one. Now, I want to go on with a, b and c above, that is to keep the individuals that for each cohort and for each year move out permanently and the ones that move out and move back into the cohort. I have tried using the code provided in the earlier question but without success.
Edit #2: So, running the code above could result in a dataset similar to the following:
library(dplyr)
set.seed(123)
df <- tibble(
  id = c(1, 2, 3, 4, 5,     # first year
         1, 2, 3, 5, 6, 7,  # 4 moves out, 6,7 move in
         2, 3, 4, 6, 7, 8  # 1,5 moves out, 4,8 move in
     ),
  year = c(rep(2009, 5),
       rep(2010, 6),
       rep(2011, 6)),
  age = c(0, 0, 0, 0, 0,
      1, 1, 1, 1, 0, 0,
      2, 2, 2, 1, 1, 0) # extra column
    )

This is where the problem occurs, since I filter out only individuals that are 0 years old at one or another point in time. So when running code calculating differences between years, people that have no prior age will always be seen as new joiners. I think I somehow need to isolate each cohort and compare each year for each cohort. But I am not sure.


text:
Q: Paramagnet: working with molar quantities I am currently working through A Modern Course in Statistical Physics by Linda E. Reichl. (2nd edition)
I am working on problem 2.13 which discusses a paramagnet.
The equation of state is given as $$m = \dfrac{DH}{T}$$
where m is the molar magnetisation, H is the magnetic field, D is a constant and T is temperature.
The molar heat capacity at constant magnetisation is given as constant: $c_{m} = c$
I am having trouble working with molar quantities.
The textbook states $C_{X, n} = \left(\dfrac{{\partial}U}{{\partial}T}\right)_{X, n}$, therefore $c_{x} = \left(\dfrac{{\partial}u}{{\partial}T}\right)_{x}$
and $\left(\dfrac{{\partial}U}{{\partial}X}\right)_{T, n}$ = $\left(\dfrac{{\partial}u}{{\partial}x}\right)_{T}$
where a lower case letter indicates we are dealing with a molar quantity ($U/n = u$).
I tried do derive the following analogously:
$C_{M, n} = T\left(\dfrac{{\partial}S}{{\partial}T}\right)_{M, n}$, therefore $c_{m} = T\left(\dfrac{{\partial}s}{{\partial}T}\right)_{m}$
And $\left(\dfrac{{\partial}S}{{\partial}M}\right)_{T, n}$ = - $\left(\dfrac{{\partial}H}{{\partial}T}\right)_{M, n}$ = $\left(\dfrac{{\partial}s}{{\partial}m}\right)_{T}$ where the first equality is a Maxwell relation
I have therefore worked out:
$\left(\dfrac{{\partial}s}{{\partial}T}\right)_{m} = c/T$
and $\left(\dfrac{{\partial}s}{{\partial}m}\right)_{T} = -m/D$
I then integrated both equations to get $s(T, m) = c\ln(T) - \dfrac{m^{2}}{2D}$
This however isn't the correct answer. I am assuming I have made an error using molar quantities, however as far as I can tell I haven't done much more than repeat what the textbook says. Could someone explain why the textbook's equalities hold whereas mine don't ?
Edit : The correct answer is $$s(T, m) = (c+m^{2}/2D)\ln\left(\dfrac{T(c+m^{2}/2D)}{u_{0}}\right)$$

A: I think your answer is correct, the only thing that you need is to write the entropy in terms of its natural variables (for this case $U=U(S,M,N)$ or $u=(s,m)$). I mean, for getting the entropy that is supposed to be the correct one, the internal energy must have a 'magnetic' contribution, which is not the case, as you can easily prove by calculating $\left(\frac{dU}{dM}\right)$ at constant $T$ using that $c_m=$ constant.
On the other hand, all your molar quantities are right you haven't made any mistake. You can see Thermal physics by Morse for more details on paramagnetic substance (although they assume that $C_M=F(T)$, all the calculations are quite similar to the ones needed to solve problem 2.13). Hope this be useful, even though your question has been posted long ago.


text:
Q: Filtering rows in datatable I have two ComboBox's that each represent a column in my DataTable. The ComboBox's are automatically populated by the values in those columns. I want to load in my DataTable, then select what I want to filter in the ComboBox's and only show rows containing the value from combobox1 representing column1 and combobox2 representing column2
I tried using DataTable.Select but I get an error saying it can't find the column. I am using a mysql connector to fill the DataTable.
I also tried this How to make C# DataTable filter but I can't find out why it won't recognize GridFieldDAO dao = new GridFieldDAO();
Can someone point me in the right direction?
Here's my code so far.
try
        {
            DataView FserieView = new DataView(DS1);
            FserieView.RowFilter = "Model = " + cmbFilterFseries1.Text;
            dataGridFserie.DataSource = FserieView;
        }
        catch (Exception error)
        {
            MessageBox.Show("The following error occurred: " + error.Message, "Report error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {

        }

Getting an error that the column could not be found.

A: Got it working by using DataTable.Select.  I forgot the '' marks which threw the error.


text:
Q: jquery to loop through each row and divide two of the row values into each other I have a table that has some inputs populated by jquery.
I want to divide the jquery value by the user inputted qty.
I am trying to do this with a function called qtypercheckas below:
function qtypercheck(){
     //for each table row
        // var lineqty= input[name^="product"] divide input[name^="checkedsizes"]
        //set value of input[name^="qtypercheck"]=lineqty
}

the complete fiddle can be seen here http://jsfiddle.net/emL6x/36/
if I try loop through the table with $('.authors-list tr').each(function(){ the loop is not one per row so unsure.
to summarize, need to populate the cubespercheck field with the result of qty / checkedsizes
Thanks as always.

A: I'd ditch the qtypercheck() function and just add a line to your countchecks() function:
function countChecks() {
    $('.authors-list tr').each(function () {
        var count = 0;

        var hdn = $(this).find('input[name^="checkedsizes"]');
        count = $(this).find(':checkbox:checked').length;
        hdn.val(count);
        if(count>0) $(this).find('input[name^="qtypercheck"]').val($('input', this).eq(1).val() / count);
    });
   // qtypercheck();
}

jsFiddle example


text:
Q: ScalaFX multiple childrens Backend:
I have an observable collection of strings:
val list = new ObservableBuffer[String]

UI:
And I want to put this list after title in VBox:
new VBox {
  children = Seq(
    new Label("My awesome title"),
    list    //Doesn't work
  )
}

How to make this work?

A: Solved with:
new VBox {
  children = Seq(
    new Label("My awesome title"),
    new StackPane{
      children = new ListView[String] {
        items = list
      }
    }
  )
}

Is there better solution?


text:
Q: Empty sharepoint online folder I am looking for a way to automatically empty a folder in sharepoint online once a day. I think the best way to do this is using a powershell script from a local server. I tried to search this on google but then I can only find how to delete a folder. But I want to delete all the content within a folder and not the folder itself. Does anyone know a good solution or powershell script for this?

A: Oke i got a working powershell script from the URL that Theo provided: [https://www.sharepointdiary.com/2018/05/sharepoint-online-delete-all-files-in-document-library-using-powershell.html][1]
the script looks like this:
#Load SharePoint CSOM Assemblies
#Download Sharepoint CSOM Assemblies from https://www.microsoft.com/en-us/download/details.aspx?id=42038
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Variables for Processing
$SiteURL = "https://tenantname.sharepoint.com/sites/TestTeam"
$LibraryRelativeURL = "/sites/TestTeam/Shared Documents/TEST/TestFolder"

Try {
#Get Credentials to connect
$Cred = Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials

#Get the Library and Files
$Folder=$Ctx.Web.GetFolderByServerRelativeUrl($LibraryRelativeURL)
$Ctx.Load($Folder)
$Files = $Folder.Files
$Ctx.Load($Files)
$Ctx.ExecuteQuery()

#Iterate through each File in the Root folder
Foreach($File in $Files)
{
    #Delete the file
    $Folder.Files.GetByUrl($File.ServerRelativeUrl).Recycle() | Out-Null
    Write-host -f Green "Deleted File '$($File.Name)' from '$($File.ServerRelativeURL)'"
}
$Ctx.ExecuteQuery()

#Process all Sub Folders
$SubFolders = $Folder.Folders
$Ctx.Load($SubFolders)
$Ctx.ExecuteQuery()
Foreach($SubFolder in $SubFolders)
{
    #Exclude "Forms" and Hidden folders
    If( ($SubFolder.Name -ne "Forms") -and (-Not($SubFolder.Name.StartsWith("_"))))
    {
        #Delete the folder
        $Folder.Folders.GetByUrl($SubFolder.ServerRelativeUrl).Recycle()| Out-Null
        Write-host -f Green "Deleted Folder '$($SubFolder.Name)' from '$($SubFolder.ServerRelativeUrl)'"
    }
    $Ctx.ExecuteQuery()
}
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}


text:
Q: How to fill password in Linux using expect? I have an executable binary which when runs asks for a share password that's common to that service. I want to automate the password filling by using the shell script 'expect' and 'send' feature. I want to know what exactly to fill in the expect. The prompt spans across the multiple lines. Should I fill in the last line or entire message.
Shareserver or network failure -1: please enter keys locally.
Recovering key, 1 share required.
Please enter a share password:

Currnetly i'm doing
./My_binary_to_execute.tst
expect "Please enter a share password:"
send "share_pwd"

I'm not getting the password filled and i'm prompted again. What's the exact usuage? Please don't worry about security. The password is shared and known to the organisation and the binary too is not a critical one.

A: You should expect the last line.
There is different reasons why your script is not working.
Maybe it is because you do not send carriage return after your password:
send "share_pwd\r"

Or maybe your binary opens another shell, which expect does not see.


text:
Q: What does it mean in node.js by http.ClientRequest implements an interface? I was reading the documentation for http.ClientRequest and it says... "The request implements the Writable Stream interface. This is an EventEmitter." What does this mean? Does it mean that http.ClientRequest gets all of the methods and events that both Writable Stream and EventEmitter get and the arguments it will accept are the same as EventEmitter (event, listener)?
If this is correct, then how is it that in the example code for http.request... within the callback function of http.request there is a line that says res.on('data', ...)? The documentation says that this res parameter implements http.ClientRequest, but when I checked, the 'data' event is listed for stream.Readable but not stream.Writable.
Here is the example code from the url:
var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

A: The first answer is YES, according the http://nodejs.org/api/stream.html#stream_stream ,
    All streams are instances of EventEmitter.
About the second question,

The documentation says that this res parameter implements http.ClientRequest,

Nope. The returned object(that's req) is an instance of the ClientRequest which implements writable stream, in the sample code the data event is bound to res which is readable stream. The doc said:
http.request() returns an instance of the http.ClientRequest class.

Don't confuse the request with response. :)


text: Q: Uploading image location in PHP form I am trying to make a form in php that uploads an image from mobile. The name of the image is stored in mysql database for retrieval. The code is working fine. I wanted to know if I can store the location of the image that is stored in the phone. I want to store the location in mysql database table column.


text:
Q: Value just available after second function call I have the following function and it's working great but now I need the value out of the function to use it for another purpose.
But my problem is that I always have to execute the function twice to get a value in the outer part of the function (var valueOutOfFunction).
var valueOutOfFunction = [(String)]()
func loadQuery(com:@escaping( [(Int, String)] -> ())){
    var arrayOfTuples = [(Int, String)]()
    db.collection("Data").whereField("age", isGreaterThanOrEqualTo: 1).whereField("age", isLessThanOrEqualTo: 50).whereField("gender", isEqualTo: "F").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
                 for (index, document) in querySnapshot!.documents.enumerated() {
                 arrayOfTuples += [(index, document.documentID)]
                 }
        }
        com(arrayOfTuples)
    }
}

Then I am calling it here:
loadQuery { arr in
  self.valueOutOfFunction = arr // Has a value in the first execution
}

print (valueOutOfFunction) //Executing the first time there is no value in the variable, the second time it have a value.

Why is it just on the second attempt available and what could be a solution for this problem ?
Thanks!

A: That is because the valueOutOfFunction is happening inside of that closure which is being called asynchronously to the print statement. Additionally, you are executing the completion outside of the else statement which may be firing before your for loop completes. What you want to do is control the flow from within the closure itself like so:

// move com(arrayOfTuples) up into the else block but outside of the for loop

func handleQuery() {
    loadQuery { doStuffWithResult($0) }
    // This line will run before the first line of doStuffWithResult
    // It would be best to end the function logic at loadQuery
}

func doStuffWithResult(_ arrayOfTuples: [(Int, String)]) {
    print(arrayOfTuples)
    // Do other work here
}

What you're looking into is control flow. You want to execute X if Y has occurred and Z if !Y right?
I would recommend looking into swift's result type. This will help you manage control flow with closures.
An example:
typealias QueryResult = [(Int, String)]

enum QueryErrors: Error {
    case couldNotFind
}

func loadQuery(_ result: @escaping (Result<QueryResult, Error>) -> Void) {
    db.collection("Data").whereField("age", isGreaterThanOrEqualTo: 1).whereField("age", isLessThanOrEqualTo: 50).whereField("gender", isEqualTo: "F").getDocuments() { (querySnapshot, err) in
        guard let documents = querySnapshot?.documents.enumerated() else {
            // I think enumerated will give you an array of tuples... if not add this to the end of that line. After enumerated but before else
            // enumerated().compactMap { ($0, $1) }
            result(.failure(err ?? QueryErrors.couldNotFind))// passes back Firebase error if it exists or default error if it doesn't
            return
        }
            result(.success(documents))
    }
}

// how it works

loadQuery() { result in
    switch(result) {
    case .success(let arr): print(arr)
    case .failure(let error): print(error)
    }
}


text:
Q: increment text input on modal returning 1,3,6,10,15 Trying to implement an autoincrement function on a modal form with text inputs on top of a Goggle map.
The problemn is that my text field adds up all the sums of the values, so that I get the following incremented values when my field starts with a value = '0': 1,3,6,10,15,21,28,...
I just want to have a simple increment by 1: 1,2,3,4,5,...
Here how my code looks like:
HTML input on modal form
 <input type="text" class="form-control" id="num" value='0'>

Part of JS displaying Google Maps Api v3
       //Add listener to map, to insert new Marker with modal
    google.maps.event.addListener(map, "dblclick", function(event){
      marker = new MarkerWithLabel ({
          position: event.latLng,
          map: map,
          icon:mmcross,
          draggable: true,
            labelContent: '',
            labelAnchor: new google.maps.Point(15,33),
            labelClass: "labels", // the CSS class for the label
            labelInBackground: false
        });

      map.setCenter(event.latLng);

          //Open Modal Form to insert data
      google.maps.event.addListener(marker, 'click', function() {
          $('#myModal').modal('show');
          $('#myModal').on('shown.bs.modal', function() {
             $("#num").get(0).value++
          });
      });

   });

A: OK I had to remove the second $('#myModal') call to get it work:
google.maps.event.addListener(marker, 'click', function() {
   $('#myModal').modal('show');
   $(function() {
       $("#num").get(0).value++
  });
});


text:
Q: How to get the element by css of the pdf icon, protractor testing I have a pdf image inside the anchor tag.I need to get the element and with that I need to click on the pdf link. Tried with element by Id but getting element not visible but it is visible.Kindly help in getting the element through css,struck in this for nearly 2 days.

{{'check.ant.label'|text}}

{{'check.bed.label'|text}}

{{'check.hin.label'|text}}

A: Did you try with css Selector? If it is hard to find a unique ID, try right click on the inspect element of the pdf link and click on Copy Unique Selector and try to click on it.
element(by.css('paste your Unique Selector here')).click();

Hope this helps. :)

A: In a simple case, this is just:
element(by.id("checkPdfLink")).click();

But, since you are getting the "Element not visible" error, there could be several reasons for that. One, is that you may need to actually do something to make the element visible - open up a menu, or a dropdown. The other reason, could be the timing problem. Wait for the link to become clickable before clicking:
var EC = protractor.ExpectedConditions;
var pdfLink = element(by.id("checkPdfLink"));
browser.wait(EC.elementToBeClickable(pdfLink), 5000);  // wait up to 5 seconds

pdfLink.click();


text:
Q: Python Json Decoding array to string I'm trying to parse some Json, my code goes like this:
Json = '{"status":"Success", "resultsMethod":"database", "lastScrape":"2012-05-28 00:03:52", "domainCount":"45", "remoteAddress":"www.digg.com", "remoteIpAddress":"64.191.203.30", "domainArray":[["567gu.com", ""], ["64.191.203.30", ""], ["64.191.203.30.", ""], ["bellacor.com", ""], ["blogs.vancouversun.com", ""], ["da-dk.chinathin.com", ""], ["dads.new.digg.com", ""], ["deathofaclown.com", ""], ["digg-inc.com", ""], ["digg.bokefu.com", ""], ["digg.com", ""], ["digg.com.", ""], ["diggcontest.com", ""], ["diggcorp.com", ""], ["diggentertainment.com", ""], ["diggriver.com", ""], ["e.digg.com", ""], ["evercleancanada.com", ""], ["feeds.digg.com", ""], ["feeds.gawker.com", ""], ["feeds.paidcontent.org", ""], ["firthfamily.net", ""], ["m.digg.com", ""], ["media.digg.com", ""], ["new.digg.com", ""], ["rfcoron.no-ip.org", ""], ["rss.digg.com", ""], ["samtesta.com", ""], ["services.digg.com", ""], ["shopzilla.com", ""], ["theultimatebathrooms.com", ""], ["tmpnetwork.com", ""], ["www.567gu.com", ""], ["www.businesswire.com", ""], ["www.calibex.com", ""], ["www.digg-inc.com", ""], ["www.digg.com", ""], ["www.freshnews.org", ""], ["www.iconfactory.com", ""], ["www.istoleyoursite.com", ""], ["www.lethargy.org", ""], ["www.pheedcontent.com", ""], ["www.stuff.co.nz", ""], ["www.tr.im", ""], ["www.xkan.cn", ""]]}'

obj = json.loads(Json)
for key, value in obj.iteritems():
    print key,value

This above example print this :
status Success
domainArray [[u'567gu.com', u''], [u'64.191.203.30', u''], [u'64.191.203.30.', u''], [u'bellacor.com', u''], [u'blogs.vancouversun.com', u''], [u'da-dk.chinathin.com', u''], [u'dads.new.digg.com', u''], [u'deathofaclown.com', u''], [u'digg-inc.com', u''], [u'digg.bokefu.com', u''], [u'digg.com', u''], [u'digg.com.', u''], [u'diggcontest.com', u''], [u'diggcorp.com', u''], [u'diggentertainment.com', u''], [u'diggriver.com', u''], [u'e.digg.com', u''], [u'evercleancanada.com', u''], [u'feeds.digg.com', u''], [u'feeds.gawker.com', u''], [u'feeds.paidcontent.org', u''], [u'firthfamily.net', u''], [u'm.digg.com', u''], [u'media.digg.com', u''], [u'new.digg.com', u''], [u'rfcoron.no-ip.org', u''], [u'rss.digg.com', u''], [u'samtesta.com', u''], [u'services.digg.com', u''], [u'shopzilla.com', u''], [u'theultimatebathrooms.com', u''], [u'tmpnetwork.com', u''], [u'www.567gu.com', u''], [u'www.businesswire.com', u''], [u'www.calibex.com', u''], [u'www.digg-inc.com', u''], [u'www.digg.com', u''], [u'www.freshnews.org', u''], [u'www.iconfactory.com', u''], [u'www.istoleyoursite.com', u''], [u'www.lethargy.org', u''], [u'www.pheedcontent.com', u''], [u'www.stuff.co.nz', u''], [u'www.tr.im', u''], [u'www.xkan.cn', u'']]
lastScrape 2012-05-28 00:03:52
remoteAddress www.digg.com
resultsMethod database
remoteIpAddress 64.191.203.30
domainCount 45

I really would like to have domainCount, RemoteIpAddress and RemoteAddress shown first and last but not least; Have a normal string list for the domainArray key.
In this example, domainArray key correspond to a list that is shown like this: [[u'567gu.com', u''],
I would like to have a list like this:
DomainArray :
ellacor.com
blogs.vancouversun.com
da-dk.chinathin.com
etc, etc.

Any help would be greatly appreciated !
Thanks

A: obj = json.loads(Json)
print("DomainCount: %d" % obj['domainCount'])
print("DomainArray: %s" % '\n'.join(e[0] for e in obj['domainArray'])
# etc

A: try:
    import simplejson as json
except ImportError:
    import json

s = '{"status":"Success", "resultsMethod":"database", "lastScrape":"2012-05-28 00:03:52", "domainCount":"45", "remoteAddress":"www.digg.com", "remoteIpAddress":"64.191.203.30", "domainArray":[["567gu.com", ""], ["64.191.203.30", ""], ["64.191.203.30.", ""], ["bellacor.com", ""], ["blogs.vancouversun.com", ""], ["da-dk.chinathin.com", ""], ["dads.new.digg.com", ""], ["deathofaclown.com", ""], ["digg-inc.com", ""], ["digg.bokefu.com", ""], ["digg.com", ""], ["digg.com.", ""], ["diggcontest.com", ""], ["diggcorp.com", ""], ["diggentertainment.com", ""], ["diggriver.com", ""], ["e.digg.com", ""], ["evercleancanada.com", ""], ["feeds.digg.com", ""], ["feeds.gawker.com", ""], ["feeds.paidcontent.org", ""], ["firthfamily.net", ""], ["m.digg.com", ""], ["media.digg.com", ""], ["new.digg.com", ""], ["rfcoron.no-ip.org", ""], ["rss.digg.com", ""], ["samtesta.com", ""], ["services.digg.com", ""], ["shopzilla.com", ""], ["theultimatebathrooms.com", ""], ["tmpnetwork.com", ""], ["www.567gu.com", ""], ["www.businesswire.com", ""], ["www.calibex.com", ""], ["www.digg-inc.com", ""], ["www.digg.com", ""], ["www.freshnews.org", ""], ["www.iconfactory.com", ""], ["www.istoleyoursite.com", ""], ["www.lethargy.org", ""], ["www.pheedcontent.com", ""], ["www.stuff.co.nz", ""], ["www.tr.im", ""], ["www.xkan.cn", ""]]}'
obj = json.loads(s)

printorder = ['domainCount', 'remoteIpAddress', 'remoteAddress', 'lastScrape', 'resultsMethod', 'status', 'domainArray']
for var,val in ((var, obj.get(var)) for var in printorder):
    if var == 'domainArray':
        val = ''.join('\n  {}'.format(domain[0]) for domain in val)
    var = '{}:'.format(var)
    print('{:<20} {}'.format(var, val))

results in
domainCount:         45
remoteIpAddress:     64.191.203.30
remoteAddress:       www.digg.com
lastScrape:          2012-05-28 00:03:52
resultsMethod:       database
status:              Success
domainArray:
  567gu.com
  64.191.203.30
  64.191.203.30.
  bellacor.com
  blogs.vancouversun.com
  da-dk.chinathin.com
  dads.new.digg.com
  deathofaclown.com
  digg-inc.com
  digg.bokefu.com
  digg.com
  digg.com.
  diggcontest.com
  diggcorp.com
  diggentertainment.com
  diggriver.com
  e.digg.com
  evercleancanada.com
  feeds.digg.com
  feeds.gawker.com
  feeds.paidcontent.org
  firthfamily.net
  m.digg.com
  media.digg.com
  new.digg.com
  rfcoron.no-ip.org
  rss.digg.com
  samtesta.com
  services.digg.com
  shopzilla.com
  theultimatebathrooms.com
  tmpnetwork.com
  www.567gu.com
  www.businesswire.com
  www.calibex.com
  www.digg-inc.com
  www.digg.com
  www.freshnews.org
  www.iconfactory.com
  www.istoleyoursite.com
  www.lethargy.org
  www.pheedcontent.com
  www.stuff.co.nz
  www.tr.im
  www.xkan.cn


text:
Q: Subsetting a data.frame Probably an easy one.
I have a data.frame with three columns: cluster, groupand id. Each
set.seed(1)
df <- data.frame(cluster=letters[sample(length(letters),1000,replace=T)],
                 group=LETTERS[1:2][sample(2,1000,replace=T)],
                 id=1:1000)

Each cluster can be represented by either one or more groups, where each group can be represented by one or more ids.
I'm looking for a fast way to subset df retaining only rows whose clusters have both groups are represented.
This is pretty slow for my real data dimensions:
library(dplyr)

do.call(rbind,lapply(unique(df$cluster),function(l){
  if(length(unique(dplyr::filter(df,cluster == l)$group) == 2)){
    return(dplyr::filter(df,cluster == l))
  } else{
    return(NULL)
  }
})

Is there a faster way to do this with dplyr?


text:
Q: What is use of ! sign in property declaration in a Component I found the following code on angular docs. just want to understand the use of ! in the property declaration.
 @ViewChildren(Pane) panes !: QueryList<Pane>;`

this statement is used as follows
export class ViewChildrenComp implements AfterViewInit {
  @ViewChildren(Pane) panes !: QueryList<Pane>;

  }

A: @ViewChildren(Pane) panes !: QueryList<Pane>
About ! this is an operator in typescript called Non-Null Assertion Operator this operator takes a typed variable and removes the undefined and null types from it. In other words, it doesn't let your variable get null or undefined type. if you don't use it, you will get a compile error when strictNullChecks flag is on. it means when the flag is off the compiler does not check for undefined and null types assignments.
in order to enable this flag, you must set it true in  tsconfig.json
  {
    "compilerOptions": {
      ...
      "strictNullChecks": true,
      ...
     }
  }

In this case After Enable the flag if you don't use '!' when there is no pane directive in the component, you will get an error.
In order to make it more clear I have already prepared an example here
And if you need more information check this link

A: It's an assertion that this field is not null even it's not explicity initialized.
Check this out: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator


text:
Q: Windows 7 Explorer clearing history So i have alot(more than on screenshot) of "Favorites" in pop up menu of explorer (right click on explorer icon on taskbar) Screenshot
Also i am using "Most visited" (i think on english it is)
But sometimes windows just clearing this! It saves all history of browsing and favorites everywhere except for pop up menu!
Any suggestion please?


text:
Q: Why does this sometimes mean base? Given
public class Animal
{
    public Animal()
    {
        Console.WriteLine("Animal constructor called");
    }
    public virtual void Speak()
    {
        Console.WriteLine("animal speaks");
    }
}

public class Dog: Animal
{
    public Dog()
    {
        Console.WriteLine("Dog constructor called");
        this.Speak();
    }
    public override void Speak()
    {
        Console.WriteLine("dog speaks");
  base.Speak();
    }
}

this.Speak() calls Dog.Speak().  Remove Speak() from dog and suddenly this.Speak() calls Animal.Speak().  Why does this behave this way?  In other words, why does this mean base or this?
To me, an explicit call to base.Speak() makes more sense.  Especially when speak is not virtual, surprisingly Speak() is still called when virtual is removed.  I understand IS-A relationships from an OO sense, but I can't wrap my head around this specific problem in C#.  This gets especially annoying when people write God class UI's (practically every business does).  I'm looking for "Speak()" inside "this" when I should be looking at "base".

A: Its not that. Its that if there is a speak method within dog, then it is an override of the base method. If it isn't there, then calling dogInstance.Speak will look for the Speak() method in any of Dog's base classes.

A: Subclases automatically inherit behavior from their base classes.  If you don't do anything other than inherit Dog from Animal then this.Speak() and base.Speak() both reference the version of Speak() that was implemented in Animal.
Where special things start happening is if Dog overrides Speak().  This is not possible unless Speak() is virtual.  (The virtual keyword doesn't control inheritance, it controlls overriding.)
Only when Dog overrides Speak() does base.Speak() do something special: In that case, calling Speak() (or this.Speak()) will execute Dog's implementation, because it overrides Animal's implementation.  This is where base becomes useful: it allows you to get around this behavior by specifying that you want to execute the base class's implementation rather than the override.
A common use of this style is in constructors.  For example:
public class Animal
{
    private readonly string _name;
    public Animal() : this("Animal") { }
    protected Animal(string name) { _name = name; }
    public void Speak() { Console.WriteLine(_name + " speaks"); }
}

public class NamedAnimal : Animal
{
    public NamedAnimal(name) : base(name) { }
}

// usage:
(new Animal()).Speak();  // prints "Animal speaks"
(new NamedAnimal("Dog")).Speak();     // prints "Dog speaks"

In this example, NamedAnimal doesn't have access to the _name field, but it is still able to set it indirectly by calling the base class's constructor.  But the base class's signature is the same as one in the base class, so it has to be specified using base.
With non-constructors it's also useful to get at behavior that's not otherwise accessible.  For example, if Animal.Speak were virtual then we could use an override to tack behavior onto it rather than simply replacing it:
public class NamedAnimal : Animal
{
    public NamedAnimal(name) : base(name) { }
    public override Speak()
    {
        Console.Write("The animal named ");
        base.Speak();
    }
}

// usage:
(new NamedAnimal("Dog")).Speak();  // Writes "The animal named Dog speaks"

A: This is one of the very fundamental points of OO. If you don't provide an override, then the parent method is used.
Also, even if you remove virtual, Dog.Speak is called because you're not accessing this polymorphically.

A: this means this and nothing else.
Just in your first example you have an override for Speak(..) function, so this call that one.
In second case, istead, there is no any override, so it "climbs" on derivation tree and pick the first suitable function. In your case that one is Speak(..) of the Animal.

A: VB.Net has the MyClass keyword to do just that (as opposed to the My keyword, which is the equivalent of this in C#).  Unfortunately, there is no MyClass equivalent keyword in C#.


text:
Q: Manifest validation fails when I try to add 'Extensions' to the App element I have been trying to connect and authenticate my application to facebook but it's shows a failure message when I am trying to add Extensions element to it. The error message says,
"Manifest validation fails: Exception: The element 'App' has invalid child element 'Extensions'. List of possible elements expected: 'IconPath'."
Though it is clearly narrated in the tutorial,
http://facebooksdk.net/docs/phone/config/.
Any help is really appreciated. Thanks.
EDIT: It is a Windows Phone 8.1 Silverlight application.

A: Post it after <tokens></tokens> tag, this works for me
<Tokens>...</Tokens>
<Extensions>
   <Protocol Name="fb<your app id>" NavUriFragment="encodedLaunchUri=%s" TaskID="_default" />
   <Protocol Name="msft-<your guid as configured on Facebook portal>" NavUriFragment="encodedLaunchUri=%s" TaskID="_default" />
</Extensions>


text:
Q: Best way to clone existing DB for Junit tests? I have to clone tables from an existing database somehow in order to run unit tests.   The ideal solution would be something - a Maven plugin or Spring bean - that would clone the database tables into a HSQL database, which I could then hit with my JUnit tests.
What is the most straightforward way to do this?

A: Download DBUnit. http://dbunit.sourceforge.net/
Export a dataset from your existing DB to XML.
In your suite, import the dataset into HSQL.
You're going to want to get to know DBUnit if you intend to unit test an app whose behavior is tightly coupled with its persistence layer (e.g. anything written in ORM).


text:
Q: Need to generate custome url for bit.ly? Hi I am a web application in ROR and shortening url using bit.ly. whenever i create an url using bit.ly i could custom url like http://bit.ly/19Mk8Oj now i want to remove bit.ly and needs to add my own custom url like ferdy.ly/sdf2323 how to do that?
when i Google about this and found the following url http://support.bitly.com/knowledgebase/articles/76741-how-do-i-set-up-a-custom-short-domain-. now i have a registered domain for this from http://libyanspider.com/m and need help to integrate the custom domain with my bitly account? and my application is a feedback engine wherein we are charging user for subscription so i choose business account and received a mail from bit.ly that per month i need to pay $1995.. is custom domain name in bit.ly will cost this much?

A: what you want is a url shortener algorithm.
Simple explanation with least efforts:
Have a table that you would store your URLs in for lookup, and the id should be auto-incremented(This is default with AR in Rails), convert the id to base 36 with ruby
6788999.to_s(36) #=> "41ifb"
Then you can have a URL as:
foo.com/41ifb
When the request for the shortened URL hits the controller(which you can basically even use bare Routing for) convert the param to an integer:
"41ifb".to_i(36) #=> 6788999
This is a simple basic URL shortener service


text:
Q: Mocking multiple Vector with @Spy and @InjectMocks I am writing a JUnit Test where I need to inject mocks of 2 Vectors as follows:
@AllArgsConstructor
public abstract class AbstractMyObject {
    @Autowired
    private Vector<String> firstVector;

    @Autowired
    private Vector<String> secondVector;

    public abstract void  absFunc();

    public void doThis() {
        System.out.println(firstVector);
        System.out.println(secondVector);
    }
}

@Component
public class MyObject extends AbstractMyObject {
    public MyObject(final Vector<String> firstVector, final Vector<String> secondVector) {
        super(firstVector, secondVector);
    }
    @Override
    public void absFunc() {

    }
}

public class TestClass {
    private static String[] array1 = {"Hello", "World"};
    private static String[] array2 = {"junit", "mockito"};

    @Spy
    private Vector<String> firstVector = new Vector<>(Arrays.asList(array1));

    @Spy
    private Vector<String> secondVector = new Vector<>(Arrays.asList(array2));

    @InjectMocks
    private MyObject myObject;

    private void initMocks() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test1() {
        initMocks();
        myObject.doThis();
    }
}

The output of running this test is: [Hello, World]
How do I make sure that both the vectors are correctly assigned?
I could not find any examples or documentation about using @Qualifier with Spy and InjectMocks.

A: I was calling super() from the base class which is incorrect. Since the members were @Autowire-d there is no need for super().


text:
Q: Angular did n't show response data Here is backend function

 userDetail : function(req,res){
    User.findOne().where({id : req.userID}).exec(
      function findOneCB(err, result) {
        if (err) {
          sails.log.error("Error Occurred : "+ err);
        }
        if(result != undefined ){

          Account.find().where({userID: req.userID},{StatusCode :"Successful"}).exec(
            function findCB(err, accounts) {
              if (err) {
                sails.log.error("Error Occurred  : "+ err);
              }
              if(accounts != undefined ){

                var sendData={
                  userData:result,
                  accountData :accounts
                };
                console.log(sendData);
                res.json(sendData);
              }
            });
        }
      });
  }

Here is frontend resource function

(function (){
    "use strict";
    angular.module('userAccounts').factory('userAccountsResource',[
        "$resource","$http",userAccountsResource]);

    function userAccountsResource($resource,$http){
        return {
            getApprovedAccounts:function(){
                return $resource('api/account/approvedBankAccounts');
            },
            getUserDetail : function(){
                return $http.get('api/user/userDetail');
            }
        }

    }
})();

resource function call on controller

 vm.userDetail= userAccountsResource.getUserDetail();

backend send response data is

{ userData:
   { email: 'thusitha@gmail.com',
     userName: 'thusithz',
     userRole: 'Standard',
     selectedAccountList:
      [ { accountName: 'HSBC name',
          CFIXID: 'HSBC_CFIXID',
          id: '563c4d7e802127d51b3d80c7',
          StatusCode: 'Pending' },
        { accountName: 'NSB plus',
          CFIXID: 'NSB_CFIXID',
          id: '563c4de1802127d51b3d80c8',
          StatusCode: 'Pending' } ],
     createdAt: '2015-11-06T05:10:18.690Z',
     updatedAt: '2015-11-06T05:52:24.820Z',
     verifyCode: '1446786618698FfL2_gHGexhOb_JQ',
     pincode: '1111',
     id: '563c363aa45b2d841afc63ab' },
  accountData:
   [ { TimeStamp: '1446797352',
       TransactionID: 'LGPS201511613253518097',
       SecretTransactionKey: 'HSBC_CFIXID03636867',
       ReplyID: '35753',
       StatusCode: 'Successful',
       StatusDescription: 'Authentication Failed',
       Tags: '',
       ReturnURL: '',
       userID: '563c363aa45b2d841afc63ab',
       accountName: 'HSBC plus',
       CFIXID: 'HSBC_CFIXID',
       VerificationCode: 'LGPS3309914431991402',
       createdAt: '2015-11-06T07:55:35.229Z',
       updatedAt: '2015-11-06T07:55:35.229Z',
       id: '563c5cf7463ef3eb0aeaf57a' } ] }

but  {{vm.userDetail}} did n't show any thing

it shown {{}}
why is that..? function is properly link to the back end function and it return correct response but why is that it shown {{}} like that

A: When making a asynchronous call, if the request is not wrapped in $http you must notify angular that the model has changed so the view can sync.
Try to add $scope.$apply() when you recieve the response from the server


text:
Q: Multiple sorting by alphabet and hexadecimal in perl I want to sort an array by hex number and alphabet, but I have no idea how. My array looks something like this:
my @array = (
    "{John}{1} is a boy", "{Emily}{a} is a girl", ..., "{Alba}{f} is a brand"
);

I want to first sort the name in first {} by alphabet and then sort by second {} by hex number regardless of the word behind.
my @sorted = sort { $a <=> $b } @array;
my @sorted1 = sort { hex $a <=> hex $b } @sorted;
print "@sorted1\n";

I try something like this, but it does not work. How do I sort the array the way I described above?

A: sort {
   my @a_keys = $a =~ /\{([^{}]*)\}/g;
   my @b_keys = $b =~ /\{([^{}]*)\}/g;

   $a_keys[0] cmp $b_keys[0]
      ||
   hex($a_keys[1]) <=> hex($b_keys[1])
}

A: I hope it's obvious why your code didn't work.
my @sorted = sort { $a <=> $b } @array;
my @sorted1 = sort { hex $a <=> hex $b } @sorted;

Two problems here. Firstly, your second sort is just going to overwrite the first. The first sort you're running is completely pointless. Your code has exactly the same effect as:
my @sorted1 = sort { hex $a <=> hex $b } @array;

And secondly, you're sorting by the wrong things. Your first sort is sorting by the whole string and the second one sorts by the whole string passed through the hex() function (and given that your strings aren't valid hex strings, that's not a good idea).
Let's address the two issues separately.
What does it actually mean to sort by two different things? Usually, it implies a hierarchy in the sorts - one will be more important than the other. It means "sort by this and if two records have the same value as each other for that, then sort them by this secondary value". In your case, you're probably saying "sort by the string between the first pair of braces and if two records have the same value there, then sort by the hex value between the second pair of braces". The second sort value is a "tie-breaker" when the first sort value is the same in two records.
And Perl's sort is great for multi-level sorts like this. When you write a sort expression, it needs to return -1, 0 or 1. It returns -1 or 1 if the two values you're comparing are different and 0 if they are the same. And, as 0 is a false value to Perl, that makes it easy to stack sorts on top of each other.
my @sorted = sort {
   sort_expression_1
     or
   sort_expression_2
} @array;

If sort_expression_1  returns -1 or 1, then that's true and the Boolean expression "short-circuits" at that point. If the two values are the same, then sort_expression_1 returns 0 and the Boolean expression goes on to evaluate sort_expression_2.
So what do we actually want to sort by? Well, we need to extract the strings between the braces and sort by those. Something like this, perhaps:
my @sorted = sort {
  # Extract the sortable bits into arrays
  my @a_bits = $a =~ /\{(.+?)}/g;
  my @b_bits = $b =~ /\{(.+?)}/g;

  # Compare the strings
  $a_bits[0] cmp $b_bits[0]
    or
  # If the strings are the same, compare the hex numbers
  hex($a_bits[1]) <=> hex($b_bits[i])
} @array;

For more efficient sorting, you can use the "Schwartzian Transform" which breaks out the bits you want to sort by before starting the actual sort.
my @sorted =
  map { $_->[0] }
  sort { $a->[1] cmp $b->[1] or hex($a->[2]) <=> hex($b->[2]) }
  map { [ $_, /\{(.+?)}/g ] } @array;


text:
Q: ASP .NET Core MVC JQuery AJAX - problem with getting data to view via controller api using ajax When the line getJSON is executed and there is routing to for example: https://localhost:44338/ArticleApi/GetNextArticles?id=12&quantity=2&filterName=Odziez
I get error:

Failed to load resource: the server responded with a status of 404 ()

Cannot find this page on localhost
GetNextArticles method in my ArticleApiController:
 [HttpGet("{id}/{count}/{filterName}")]
    public IEnumerable<Article> GetNextArticles(int id, int count, string filterName)
    {
        return _articleRepository.GetNextArticles(id, count, filterName);
    }

in my view (.cshtml file):
 $.getJSON('@Url.Action("GetNextArticles", "ArticleApi")' + "?id=" + last + "&quantity=" + quantity + "&filterName=" + filterCategory, function(data, status) {

                    for(var index in data) {etc...}}

GetNextArticles method:
public IEnumerable<Article> GetNextArticles(int id, int count, string filterName)
    {
        List<Article> articles = new List<Article>();

        var categoryId = _context.Categories.Where(c => c.CategoryName == filterName).Select(c => c.CategoryId).FirstOrDefault();

        for (int i = 0; i < count; i++)
        {

            var foundArticles = _context.Articles.Where(a => a.CategoryId == categoryId && a.ArticleId == id + i + 1).ToList();

            if (foundArticles.Count() == 0)
            {
                return articles;
            }

            var article = foundArticles[0];

            if (article != null)
            {

                article.Category = _context.Categories.Find(article.CategoryId);

                articles.Add(article);
            }
            else
            {
                var nextArticles = _context.Articles.Where(a => a.CategoryId == categoryId && article.ArticleId <= id + i + 100).ToList();

                if (nextArticles.Count != 0)
                {
                    id = nextArticles.Min(a => a.ArticleId);

                    articles.Add(nextArticles.Where(a => a.ArticleId == id).First());
                }
                else
                {
                    break;
                }
            }
        }

        return articles;
    }

A: According to the error, you could validate the names of the parameters that you are sending. Reviewing the code I realize that one of them is sent with the name "quantity" and in the controller you call it "count"

A: If you use [HttpGet("{id}/{count}/{filterName}")] in your Api, The Url passed into this api must be https://localhost:44338/ArticleApi/GetNextArticles/Id/count/filterName.
So, If you don't want to change the $.getJSON(..){...} in the View, You can change the api like:
    [HttpGet]
    public IEnumerable<Article> GetNextArticles([FromQuery]int id, int count, string filterName)
    {
        return _articleRepository.GetNextArticles(id, count, filterName);
    }

You can see the Api works fine and it can be loaded in Swagger as well


text:
Q: joing the rows into together using mysql I want to join multiple row values from table.
Table name:Item
    ID |            item_id |     Value
    1               43          item1
    2               44          item2
    3               44          item3
    4               44          item4
    5               45          item5
    6               45          item6

ID's are unique (primary key)
What I am looking to output is a mysql query is something to which gives this output as given below
Output:
  ID |            item_id |     Value
    1               43          item1
    2               44          item2,item3,item4
    3               44          item2,item3,item4
    4               44          item2,item3,item4
    5               45          item5,item6
    6               45          item5,item6

kindly requesting to give some suggestions

A: Try this query:
SELECT t1.ID, t1.item_id, t2.Value
FROM item t1
INNER JOIN
(
    SELECT item_id, GROUP_CONCAT(Value) AS Value
    FROM item
    GROUP BY item_id
) t2
    ON t1.item_id = t2.item_id

Follow the link below for a running demo:
SQLFiddle

A: You can use self join with subquery of group_concat
SELECT    i.ID, i.item_id, subquery.`new_value` as value
FROM item i
JOIN (
    SELECT item_id, GROUP_CONCAT(`Value`) as new_value
    FROM item
    GROUP BY item_id;
)as subquery
ON  subquery.item_id = i.item_id;

A: You can use below query.
SELECT GROUP_CONCAT(value) FROM Item GROUP BY item_id;

A: Try this Query
  SELECT t1.ID, t1.item_id,
      (
        SELECT GROUP_CONCAT(t2.Value) FROM item AS t2
        WHERE t1.item_id = t2.item_id
        GROUP BY t2.item_id
      ) AS Value
 FROM item AS t1

Demo http://sqlfiddle.com/#!9/bbc20/18/0


text:
Q: .click function working without arguments, but not working with arguments I have this function which was working:
$('#buttFurniture').click(onFilterCLick);

but then i decided to add some argument to the function and it stopped working:
$('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture));

full function:
function onFilterCLick(arrFull,arrCurrent) {
    $('#buttFurniture').css("background-color", "#F1F1F1");
    $('#buttCars').css("background-color", "#F1F1F1");
    $('#buttGames').css("background-color", "#F1F1F1");
    $('#buttFurniture').css("color", "black");
    $('#buttCars').css("color", "black");
    $('#buttGames').css("color", "black");

    $(this).css("background-color", "#656565");
    $(this).css("color", "white");

    if (jQuery.inArray(arrCurrent[0], arrFull)) {
        console.log("asdasd");
    }
}

A: The solution: Use bind to assign arguments when passing functions:
 $('#buttFurniture').click(onFilterCLick.bind($('#buttFurniture'), arrOutput, arrFurniture));

Explanation: In javascript, functions are what's known as first class objects - that means they can be passed around as variables, like other primitives (numbers, booleans etc.), but also as arguments to functions.
In this regard, it's important to note a key difference in passing a function as a variable, and invoking a function. For example, consider the following function:
var myFunc = function () {
    return 0;
}

Now, note the difference between these two statements:
typeof myFunc // "function"
typeof myFunc() // "number"

As you can see, the first is a reference to the function itself, and the second is the invocation of that function - a subtle but key difference.
Your click handler expects a function as it's argument, and NOT a function invocation (or the result of a function being called). That's why you must use bind: bind allows you to pass the function itself, but also gives you the ability to pre-fill the arguments of the function you're passing.
In brief, the bind() function (in your case) takes 3 arguments - the first argument, in every bind() function, is the this parameter - setting this to your selected element is necessary, so that your $(this) invocation has the right context. The other arguments are where you pre-fill the rest of your function's parameters.
Hope this helps!

A: You can use the callback function of click event to call another function with parameter.
$('#buttFurniture').click(function () {
    onFilterCLick(arrOutput, arrFurniture)
});

A: I would recommend to use the .bind(null,func_arguments) method as described by @JonathanBrooks when you don't use the $(this) inside the function definition since this would refer to window object.
However, if you want to select the context as 'this' then I would recommend you to use like this:
function onFilterCLick(elem,arrFull,arrCurrent) {
  //now you can use elem to refer $(this)
  elem.css("background-color", "#656565");
}

And use the anonymous function for the click event like this:
$('#buttFurniture').click(function(){
    onFilterCLick($(this),arrOutput,arrFurniture);
});

A working code example here

A: It doesn't work because you're calling
onFilterCLick(arrOutput, arrFurniture)  in $('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture));
not passing onFilterCLick as handler for click event.

A: In case if #buttFurniture is generated after the DOM is ready
function onFilterCLick(arrOutput, arrFurniture) {
    console.log(arguments);
    console.log($(this));
    $(this).toggleClass('red-border');
};

$('#buttFurniture').on('click', function (evt) {
    evt.preventDefault();
    var holder = onFilterCLick.bind(this);
    holder('argOne', 'argTwo');
});

.bind(this) will override this inside function scope if you want to select same element that you clicked.
UPDATE
I've updated the example, sorry for untested code, here is the fidle
also read this article for better bind understanding ;)
This also will work.
var holder = onFilterCLick.bind(this, 'argOne', 'argTwo');
holder();

I hope this will help you.


text:
Q: Wrapping the HTML Control on Windows Mobile I'm writing an app (C++ with VS20050 for Windows Mobile, which wraps the HTML
Control (that is, I'm creating a DISPLAYCLASS window).
I want to be able to create a HTML page, and by using JavaScript on
the page, cause a function in my app to be executed.  Almost like JNI
in Java.
What I have been doing is, on the page, executing the line
document.location.href="myapp:myfunc";
and my app looks for "myapp:" when my app receives NM_BEFORENAVIGATE
from the control.  This seems to work (emphasis on the word "seems.")
Something that breaks as a result of this is that the javascript code
on the page breaks at the point that I attempt to submit the form on
the page.
I'd appreciate any advice.
Regards,
Brian

A: Are you trying to call JS->Java ? If so, you can start with an ActiveXControl which can use JNI to call Java.


text:
Q: Sharing ASP.NET Authentication between two applications I have two web applications ASP.NET running on the same web server IIS 7.5/.NET 4.0.
The first app makes async calls through jquery to the second app, which acts as web service backend (connected to a database server).
The two applications will be installed in intranet context, so I want to use integrated "Windows Authentication".
In both Web.config I have:
<authentication mode="Windows" />

<authorization>
    <deny users="?" />
</authorization>

<identity impersonate="true" />

If I open a browser and I access a test page it's ok on both web apps: the browser asks for a user/password pair and IIS allows the page to be downloaded.
But if I access a test page of the first web app, which makes an async request to a web service installed on the second app, a 401 error code is returned. So it seems that the authentication is lost between the two applications.
I tried also machineKey but nothing...
Any idea ?
Any help is appreciated, thanks in advance.
Alex

A: You are probably trying to make an async request to a different domain, which isn't allowed.
You can get around this by creating a "proxy" call to the web service.  You make the async call to your local asp.net application, which makes the call to the web service on your behalf.  This avoids the same origin policy restriction discussed in the link above.
Another option, since you have control of the application on both ends, would be to look at JSONP.  I don't have a lot of experience with it, but I have seen it used for making async calls across domains.
Good luck!


text:
Q: "which" command is not showing anything on standard output When I run the which command it shows nothing.
I ran all these, and none gave output.
$ which /tool/
$ which RED*.pdf
$ which anime
$ which -a anime
$ info which
$ which -a
$ which -a Downloads
$ which Downloads
$ which doc
$ which media
$ which /media
$ which

$ su -
# which
# which doc
# logout

$ which --help
Illegal option --
Usage: fusrfbinfwhich [-a] args
$ which info
/usr/bin/info
$ which help
$ which cd
$ info which
$ which -a info
/usr/bin/info
$ which -a
$ which -a list.txt

A: From man which:
NAME
       which - locate a command

SYNOPSIS
       which [-a] filename ...

DESCRIPTION
       which returns the pathnames of the files (or links) which would be executed
       in the current environment, had its arguments been given as commands in a
       strictly POSIX-conformant shell. It does this by searching the PATH for
       executable files matching the names of the  arguments. It does not follow
       symbolic links.

I wouldn't expect which to give any output - as the man page says, you need a filename that is a command.
Try running which ls.
It could be you want to know where a command is - for that you need whereis.
$ whereis ls
ls: /bin/ls /usr/share/man/man1/ls.1.gz

A: In my case myscript.sh was working fine buy which (nor whereis) wasn't returning any output:
$ which myscript.sh
$

From which manual:

DESCRIPTION
which  returns the pathnames of the files (or links) which would be executed in the current environment, had its arguments been given as commands in a strictly POSIX-conformant shell.  It does this by searching the PATH for executable files matching the names of the arguments. It does not canonicalize path names.

I fix it changing the ~ (tilde) to $HOME on $PATH:
export PATH="$PATH:$HOME/myprgms"

Now also whereis -l show my added folder.
See this answer for more about the difference between ~ and $HOME.

A: A good start would be:
man which

NAME
   which - shows the full path of (shell) commands.

None of the examples provided in your screenshot is a command that could return a path. E.g. cd is a build in command.
I don't understand what you are expecting to get with
which /tool/

etc.
,but it seems which is not the tool to achieve the result you expect.

A: There are a few similar commands that have drastically different methods and outputs:
/usr/bin/which  Locate the binary path of an executable.
$ which ssh
/usr/bin/ssh

/usr/bin/whereis Search standard Linux locations for source, binary, and manuals for the specified name.
$ whereis ssh
/usr/bin/ssh

/usr/bin/find Search the current or specified path recursively for matching strings.
(cd /usr/bin && find . ssh)
...
./things_it_checked
...
ssh

/usr/bin/grep  Search text/files/paths for a string.
(cd /usr/bin && ls * | grep ssh)
ssh
ssh-add
ssh-agent
ssh-keygen
ssh-keyscan


text:
Q: Trigger number counter on scroll I have this simple query for a number counter and I was hoping someone could show me how to trigger it on scroll? Id like it to trigger when the div is within say 500px for the top of the browser.
Also, is there any way I can have a comma in the number? For example "18,000". If I add the comma in it seems to break the script (still leaning jQuery).

$('.counter').each(function() {
  var $this = $(this),
      countTo = $this.attr('data-count');
  $({ countNum: $this.text()}).animate({
    countNum: countTo
  },
  {
    duration: 5000,
    easing:'linear',
    step: function() {
      $this.text(Math.floor(this.countNum));
    },
    complete: function() {
      $this.text(this.countNum);
      //alert('finished');
    }
  });
});

0


text:
Q: Book where a knight and lady swap bodies with dogs using magic collars I can remember a book, possibly a short story, where the protagonist is a knight who is sent on a quest to help a noble lady deal with a tyrannical uncle.
The key mechanic of the plot was that the lady's family had the magic of swapping their spirit with another creature using collars with a spell stitched into them. The knight is introduced to this and the knight and the lady swap places with hunting hounds that the lady's family breed.
Some other things I can remember are that the hounds' spirits inhabit their owners' bodies while they are swapped and there is an incident where they are attacked and the hound/humans try to fight by biting their assailants and that the uncle is using the same magic with a bear.
The setting was possibly Arthurian, magic was unusual. The rough outline of the plot that I can remember is that the Knight is pried away from a feast accepting a quest to help a Lady that nobody else was interested in doing, possibly because of the feast and/or the impoverished nature of her domain. The Knight and the Lady travel to the Lady's kingdom with the Knight intending to return for the next feast in a year with the tales of his exploits. There is a romantic sub-plot between the Knight and Lady. They reach the kingdom, confront the Uncle and some sort of conflict. The Uncle controlling the bear was taboo and somehow risky for him, possibly because of the strong experience of being a bear. The bear was chained and its ribs broken, so it was sort of safer as it was kept as a dancing bear by the Lady's family, but unleashed by the Uncle to further his ambitions.
I read this around 20 years ago, but the book is probably older. It would likely have been a YA novel, or some sort of collection.

A: This is one of the short stories in 'Merlin's Dreams', by Peter Dickinson (1988). This is an unusual book, that deserves to be better known.
The book opens with Merlin being imprisoned by Nimue (because he is going mad, and can no longer control his powers) and then continues as a collection of short stories—some based on his memories, but mostly based on his dreams, which are themselves affected by the medieval legends of Merlin himself!
In the story in question, the heroine's father was murdered by the uncle's beast (actually a wolf) and when she and her champion return to challenge him they eventually discover that the uncle has himself been murdered by a more dangerous villain, the trusted family steward, who has learned how to manipulate a bear.


text:
Q: Two constructors, which is default? Okay I got a pretty simple assignment.
I got these two constructors for class Person:
Person( const string &, const string &, const string & );
Person( const string &, const string &, const string &,
const string & );

I got 4 default values
which of these are going to be the default constructor? is it always the one with most arguments or how does it work?

A: According to the C++ Standard

4 A default constructor for a class X is a constructor of class X that
  can be called without an argument.

From your post it is not clear what default values you are speaking about. Neither of your declarations is the default constructor.
If you are speaking about default arguments as in the declaration
Person( const string & = "", const string & = "", const string & = "",
const string & = "" );

Then this declaration is a declaration of the default constructor because it can be called without any explicitly specified argument.
It is interesting to note that the same constructor can be a default constructor and a non-default constructor at the same time. At least the C++ Standard does not say anything that forbids this.
For example
struct A
{
   A( int x );
   int x;
};

A a1; // error: there is no default constructor

A::A( int x = 0 ) : x( x ) {}

A a2; // well-formed there is a default constructor.

A: Neither of these two constructors is the default one.
A default constructor is one that you could invoke with no parameters - either because

*

*the constructor has no arguments, or

*all of its parameters have default values.

Both constructors in your example require that parameters be passed to them, so neither of them is a default one.

A: A default constructor is a constructor that either has no arguments or it has some but all of them provide default values. In your case, if both of your constructors have all of their arguments with default values, then a call like
Person p;

will be ambiguous. Think about it: which one is to be called?

A: A default constructor is a constructor that either has no arguments, or if it has arguments, all the arguments have default values. So neither one of these could qualify as default constructor.

A: Both the constructors will be matched only when the signature of the call statement matches. The default constructor is always the constructor with no arguments
Person(){}

A: If you ask which could be called; that depends on how you create object.
For example;
1 - First is called
Person person = new Person("a","b","c");

2 - Second is called
Person person = new Person("a","b","c","d");


text:
Q: Tomcat 404 error after swapped META-INF/context.xml file I have Tomcat 8 installed on CentOS 7 x64
I had it set up correctly so I could go to Tomcat's manager app. I then swapped /META-INF/context.xml to a different context.xml file. After changing the context.xml file I got a "404".
The problem is that after changing the context.xml back to the original shape I am still getting the "404" (even though the only thing that had changed was the context.xml file and this file was now back in the original state).
I have tried restart tomcat, reboot server,...
The logs aren't showing any errors and catalina.out is showing that the manager app is being deployed when tomcat is starting.
My question is this, what part of tomcat is storing this broken state? I would have thought that going back to the original, working context.xml would make my tomcat work again, so what could that file have changed about tomcat that is being persisted even after restarting tomcat?


text:
Q: jQuery UI - when dropped out of droppable return to original position I use JQ.UI
I want to drag some img
if it's dropped out of a droppable area, I want it to return to its original position.

A: From the jQuery UI page for Draggable:
$( ".selector" ).draggable({ revert: true });

//getter
var revert = $( ".selector" ).draggable( "option", "revert" );

//setter
$( ".selector" ).draggable( "option", "revert", true );

You can use true, false, valid or invalid.
In your case, you want $( ".selector" ).draggable({ revert: 'invalid' }); so that any drops on invalid locations (not droppables) cause a revert.

A: You can use the revert option with a value of invalid to send the draggable back to where it came from if it's dropped anywhere other than on a valid droppable:
$("#someID").draggable({
    revert: "invalid"
});


text:
Q: Rotating a wheel? I have read here a few examples about that, but couldn't make it work.
I have some UIView called Wheel , in which i want to rotate while touch and drag.
It should work like a real wheel, so if i touch at some point it will NOT rotate to that point, only when i drag my finger, i will get rotation .
I tried this,but i get a full rotation for every little move i do. I would like to ADD the angel to the view, not ROTATE to the new angel ..
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self];

    CGPoint center=wheel.center;

    float xLeg = fabs(center.x - touchPoint.x);
    float yLeg = fabs(center.y-touchPoint.y);
    float angle = atan(xLeg / yLeg);

    NSLog(@"%f",angle);
      wheel.transform = CGAffineTransformMakeRotation( angleInDegree );

}

A: This should do the trick. Notice how I store the first touch point in touchesBegan:withEvent:. This allows me to subtract the first touch point from every touch point I get while dragging, and thus gives me the real angle I need to rotate.
EDIT
I've done some adjustments, so that it is now smooth and regular even after several touches.
Demo

WheelViewController.m
@interface WheelViewController () {
    CGPoint startPoint;
    CGFloat startAngle;
    CGFloat endAngle;
}

@end

@implementation WheelViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    startPoint = [touch locationInView:self.view];
    startAngle = [self angleForTouchPoint:startPoint] - endAngle;

    NSLog(@"\r\nStart angle: %f", startAngle);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    CGFloat touchAngle = [self angleForTouchPoint:touchPoint];

    NSLog(@"Touch angle: %f", touchAngle);

    self.wheel.transform = CGAffineTransformMakeRotation(fmodf(touchAngle - startAngle, 2 * M_PI));
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    endAngle = [self angleForTouchPoint:touchPoint] - startAngle;

    NSLog(@"End angle: %f", endAngle);
}

- (CGFloat)angleForTouchPoint:(CGPoint)touchPoint {
    CGPoint center = self.wheel.center;

    float xLeg = touchPoint.x - center.x;
    float yLeg = touchPoint.y - center.y;

    float angle = fmodf(atan(yLeg/xLeg), (2 * M_PI));

    if (xLeg < 0) {
        angle += M_PI;
    }

    return angle;
}