text:
Q: Calling a function with AJAX I'm not sure how to explain this completely, but I hope this will make sense.
I have a function that I've made that calculates the remaining amount to spend to qualify for free delivery when the basket value total falls within certain thresholds.
The basket value is updated with AJAX every time a product is added to the basket.
The add to basket button appears in an AJAX generated modal.
I need my function to be called on every page refresh and also every time a product is added to the basket when the AJAX generated add to basket button is clicked. I'm trying to do all of this with the below, but it doesn't seem to work correctly. One of the problems is that the event fires multiple times when the add to basket button is clicked and another is that the basket total is updated after the event and so the total isn't calculated correctly.
Can anyone explain how I would tidy all off this up?
function totalBag() {
   var standardDeliveryLow = 49.99;
   var standardDeliveryHigh = 64.99;
   var expressDeliveryLow = 65.00;
   var expressDeliveryHigh = 99.99;
   var bagValue = $('#basket-value').text();
   var bagTotal = Number(bagValue.replace(/[^0-9\.-]+/g,""));

   if (bagTotal >= standardDeliveryLow && bagTotal <= standardDeliveryHigh) {
       var standardDifference = parseFloat(Math.round((standardDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
       $('

£'+ standardDifference +' from standar delivery

').insertAfter('.breadcrumbs');
   } else if (bagTotal >= expressDeliveryLow && bagTotal <= expressDeliveryHigh) {
      var expressDifference = parseFloat(Math.round((expressDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
      $('

£'+ expressDifference + ' from express delivery

').insertAfter('.breadcrumbs');
   } else {
     return false;
   }
}

$(document).on('ajaxSuccess', function(e) {
  $('[name="AddItemToBasket"]').on('click', function() {
    $('body').bind('ajaxSuccess.custom', function() {
     totalBag();
     //alert('this works');
     $(this).unbind('ajaxSuccess');
  });
 });
});

totalBag();

A: EDIT: Have fixed the issue where text was duplicating. Also have added comments for more understanding.

Had a check at the link you specified and tried the following modified code.
As per @ADyson, have removed the click event, which is fixing the multiple event firing.
Regarding your other problem, the total is updated after the event, yes the HTML is getting updated after the ajaxSuccess is triggered. Hence have used the ajaxSuccess event itself to get the basket amount and use it in totalBag fn.
It seems to be working. Kindly confirm:
//Adding empty div so that we can just update the value later
$(document).on('ready', function(){
    $('

').insertAfter('.breadcrumbs');
})

function totalBag(bagTotal) {
   var standardDeliveryLow = 49.99;
   var standardDeliveryHigh = 64.99;
   var expressDeliveryLow = 65.00;
   var expressDeliveryHigh = 99.99;
   //var bagValue = $('#basket-value').text();
   //var bagTotal = Number(bagValue.replace(/[^0-9\.-]+/g,""));

   //Using a variable to store the calculated amount with text
   var innerHTML = "";
   if (bagTotal >= standardDeliveryLow && bagTotal <= standardDeliveryHigh) {
       var standardDifference = parseFloat(Math.round((standardDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
       innerHTML= "
£"+ standardDifference +" from standar delivery
";
   } else if (bagTotal >= expressDeliveryLow && bagTotal <= expressDeliveryHigh) {
      var expressDifference = parseFloat(Math.round((expressDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
      innerHTML= "
£"+ expressDifference +" from express delivery
";
   } else {
     return false;
   }
   //Updating the placeholder with new contents
   $(".delivery-message").html(innerHTML);
}

//Gets triggered after every Ajax Success.
//e -> event object, xhr -> The Ajax object which has request and response details,
//settings -> The settings we used to trigger Ajax, including the request URL
$(document).on('ajaxSuccess', function(e, xhr, settings) {
    //Checking if the request is of Adding Item to Basket
    if(settings.url.indexOf("AddItemToBasket") !== -1){
        //Getting the response and parsing it
        var resp = xhr.responseText;
        var respObj = JSON.parse(resp);
        //Checking if response is success i.e., item added to cart successfully
        if(respObj.success){
            //Getting the updated Basket value and calling totalBag
            var bagTotal = respObj.basket.subTotal;
            totalBag(bagTotal);
        }
    }

});
totalBag(0);


text:
Q: Prove by induction $\sum_{i=1}^n 3i(i+4) = \frac{(n)(n+1)(2n+13)}{2}$ In this problem I have to prove the following equation using mathematical induction:
$$\sum_{i=1}^n 3i(i+4) = \frac{(n)(n+1)(2n+13)}{2}$$
So far I've proved that $P_1$ is true, and written $P_k$ as $$15+36+63+...+3k(k+4)= \frac{(k)(k+1)(2k+13)}{2}$$
I then attempt to solve $P_{k+1}$. I start by using $P_k$ and substituting it into the equation to get $$\frac{(k)(k+1)(2k+13)}{2}+(3k+1)(k+5)=\frac{(k+1)(k+2)(2k+14)}{2}$$
I then multiply $(3k+1)(k+5)$ by $\frac{2}{2}$ to get $$\frac{(k)(k+1)(2k+13)(3k+1)(2k+10)}{2}=\frac{(k+1)(k+2)(2k+14)}{2}$$
Here its obvious that the LHS isnt going to be equal to the RHS, seeing as the LHS would have $k^5$ amd the RHS would have $k^3$. Any ideas?

A: There are three silly mistakes here: First off, your expression on the RHS should be $\frac{(k+1)(k+2)(2k+15)}{2}$ since.
Secondly you somehow made the addition into multiplication here
$$\frac{(k)(k+1)(2k+13)}{2}+(3k+1)(k+5)=\frac{(k+1)(k+2)(2k+14)}{2}$$
And finally as Bernard said you should have a $3(k+1)=3k+3$ instead of $3k+1$ in your inductive step.
Try again starting from here
$$\frac{(k)(k+1)(2k+13)}{2}+(3k+3)(k+5)=\frac{(k+1)(k+2)(2k+15)}{2}$$
and comment if you need more help.

A: Alternatively, prove a very useful identity: $$\sum_{k=0}^n\,\binom{k}{r}=\binom{n+1}{r+1}$$ for all integers $n,r\geq 0$.  Then, note that
$$3k(k+4)=6\binom{k}{2}+15\binom{k}{1}\,.$$
You can prove it by induction on $n$, or using some kind of combinatorial arguments.
Then, we have
$$\begin{align}
\sum_{k=1}^n\,3k(k+4)&=\sum_{k=0}^n\,3k(k+4)=6\,\sum_{k=0}^n\,\binom{k}{2}+15\,\sum_{k=0}^n\,\binom{k}{1}=6\binom{n+1}{2+1}+15\binom{n+1}{1+1}
\\&=6\binom{n+1}{3}+15\binom{n+1}{2}=(n+1)n(n-1)+\frac{15(n+1)n}{2}\\&=\frac{n(n+1)\big(2(n-1)+15\big)}{2}=\frac{n(n+1)(2n+13)}{2}\,.\end{align}$$

Here is another proof, using the well known sum
$$\sum_{k=0}^n\,k^2=\frac{n(n+1)(2n+1)}{6}\text{ for all integer }n\geq 0\,.$$
Note that $$\sum_{k=1}^n\,3k(k+4)=3\,\sum_{k=1}^n\,\big((k+2)^2-4\big)=3\,\left(\sum_{k=1}^n\,(k+2)^2-\sum_{k=1}^n\,4\right)\,.$$
That is,
$$\sum_{k=1}^n\,3k(k+4)=3\,\left(\sum_{k=3}^{n+2}\,k^2-4n\right)=3\,\left(\sum_{k=0}^{n+2}\,k^2-5-4n\right)\,.$$
Now, plugging in $\sum_{k=0}^{n+2}\,k^2=\frac{(n+2)(n+3)(2n+5)}{6}$ yields
$$\sum_{k=1}^n\,3k(k+4)=3\,\left(\frac{(n+2)(n+3)(2n+5)}{6}-5-4n\right)\,.$$
The rest is just some work with simple algebraic manipulations.

A: Only a comment!!! $\,\,$ (because your question is answered by others)
The simplest method and without induction comes from Discrete Mathematics.
$\displaystyle \sum\limits_{k=1}^n (ak^2 + bk) = \sum\limits_{k=1}^n (a (k+1)^{\underline{2}} + (b-a)k^{\underline{1}}) = a \frac{(n+2)^{\underline{3}}}{3} + (b-a)\frac{(n+1)^{\underline{2}}}{2} $
where $\,x^{\underline{n}}=x(x-1)...(x-n+1)$
Note: It looks similar to integration.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Page Rendering Java Bean Adobe CQ5 This is the current working code I have in a JSP file. The code simply accesses a bundles service interface to retrieve and update user information into a MYSQL database. I have read that using scriptlets is bad practice and that using Java Beans is good practice.
My question is how (with some code examples) I can create a TraineesDataRenderer Java bean, that will allow me to stop using scriptlet code to render the database contenet, whilst also using the 'sling.getService' method, that references the TraineeService interface, supplied by my OSGI bundle.
<%@include file="/libs/foundation/global.jsp"%>
<%@ page import= "java.util.Iterator"%>

<html>
 <head>
  <title></title>
 </head>
<body>

   <%-- References an OSGI bundles interface through sling --%>
   <% com.netbuilder.trainees.bundle.TraineesService trainee = sling.getService(com.netbuilder.trainees.bundle.TraineesService.class); %>

   <%-- references method from an OSGI bundle to update database --%>
   <% trainee.updateTraineesData("Ben", "Brown", "ben@mail.com", 1, 1, 1, "999"); %>

   <%-- Reads and displays the data from the database --%>
   <%
      Iterator<String> iterator = trainee.readTraineesData("all").iterator();
          while (iterator.hasNext()) {
             out.println(iterator.next());
         }
   %>
</body>
</html>


text:
Q: How do I build a Play project with Hudson? I have a project that's using the Play framework, and the corporate standard is that all projects should be built by Hudson. However, I cannot find out how to do this, as Hudson does not follow any Java standards, and requires the framework installed at the computer it runs on. I have tried to build the project with Maven (if I had managed this, adding it to Hudson should be quite simple), but I have failed to make it work. I tried the Play Maven module, but Maven claims it does not find the external repo that is listed (http://nexus.infin-it.fr/content/groups/public). This might be because I am behind a firewall. I also tried the recipe listed here, but the local maven build fails because it is unable to find org.playframework:play:1.1:jar.
Has anyone done this and can provide a howto?

A: It can be done without installing the Play framework on the Hudson server, but it is quite complicated:

*

*Put the play libraries (play.jar and its dependencies) in a Maven repository

*Create a pom.xml for your project, configured with:

*

*theses libraries as dependencies

*your project specific dependencies (project lib directory)

*the java sources folder of your project (in the maven-compiler-plugin): "app"

If your project is simple (no module dependencies), this pom allows you to build the play project java sources using Maven.

If your project has module dependencies, you will have to add the dependencies jar in your pom dependencies.
To do that, you will have to create jar files from the modules if they don't have packaged jars (to get the "CRUD" class of the CRUD module for example).

A: You can find some help on this page I wrote :
http://blog.infin-it.fr/2010/12/15/play-framework-integration-continue-retour-dexperience/
Even if it's in French, I put my Ant stuff and the Play's pom I wrote.
At work we managed to integrate our Play applications with Bamboo.
It should not be difficult with my files.

A: Just looked at the repository, that you linked (http://nexus.infin-it.fr/content/groups/public). And guess what, I found the play-1.1.jar. However, the artifact ID is: org.play:play:1.1:jar and not org.playframework

A: In theory, you could put the full Play zip on your build or in in your repository, and then use Hudson to kick off an Ant script to download Play to the Hudson agent, unzip it, and then run commands on it.  It's a little clunky, but it should work.


text:
Q: Wireguard NAT to eth1 I'm trying to do something that I think should be pretty simple. The goal is to have all traffic from my home network go over a Wireguard VPN. I have 3 devices:

*

*ISPs modem/router combo. This should be the internet gateway.

*Ubuntu 20.04 box (Raspberry Pi 4). This is the Wireguard client.

*Netgear WiFi router. This is just for WiFi.

Ubuntu's eth0 is connected to the ISP Modem as a DHCP client, eth1 (a USB NIC) is connected to the WiFi routers WAN port.
The part I'm having trouble figuring out is what to do to get the Ubuntu box to act as a WAN gateway as far as the WiFi router is concerned, but with all traffic routed over the Wireguard interface (which is working and shows up as vpn in ifconfig). I've tried figuring it out myself, but every article/site I read gets me more confused...
My understanding is that Wireguard is layer 3, so I can't bridge. So I'll have to set up double NAT (or triple, if I let the WiFi router do its own routing). Is this the right idea? So I would want to:

*

*Set up NAT  between the vpn interface and eth1 interface.

*Possibly set up a DHCP server on eth1 and point the WiFi router to that so that it's just an AP. Otherwise, triple NAT?

Thanks!


text:
Q: Custom mapping in Dapper I'm attempting to use a CTE with Dapper and multi-mapping to get paged results. I'm hitting an inconvenience with duplicate columns; the CTE is preventing me from having to Name columns for example.
I would like to map the following query onto the following objects, not the mismatch between the column names and properties.
Query:
WITH TempSites AS(
    SELECT
        [S].[SiteID],
        [S].[Name] AS [SiteName],
        [S].[Description],
        [L].[LocationID],
        [L].[Name] AS [LocationName],
        [L].[Description] AS [LocationDescription],
        [L].[SiteID] AS [LocationSiteID],
        [L].[ReportingID]
    FROM (
        SELECT * FROM [dbo].[Sites] [1_S]
        WHERE [1_S].[StatusID] = 0
        ORDER BY [1_S].[Name]
        OFFSET 10 * (1 - 1) ROWS
        FETCH NEXT 10 ROWS ONLY
    ) S
        LEFT JOIN [dbo].[Locations] [L] ON [S].[SiteID] = [L].[SiteID]
),
MaxItems AS (SELECT COUNT(SiteID) AS MaxItems FROM Sites)

SELECT *
FROM TempSites, MaxItems

Objects:
public class Site
{
    public int SiteID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public List<Location> Locations { get; internal set; }
}

public class Location
{
    public int LocationID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public Guid ReportingID { get; set; }
    public int SiteID { get; set; }
}

For some reason I have it in my head that a naming convention exists which will handle this scenario for me but I can't find mention of it in the docs.

A: You can map a column name with another attribute using the ColumnAttributeTypeMapper.
See my first comment on the Gist for further details.
You can do the mapping like
public class Site
{
    public int SiteID { get; set; }
    [Column("SiteName")]
    public string Name { get; set; }
    public string Description { get; set; }
    public List<Location> Locations { get; internal set; }
}

public class Location
{
    public int LocationID { get; set; }
    [Column("LocationName")]
    public string Name { get; set; }
    [Column("LocationDescription")]
    public string Description { get; set; }
    public Guid ReportingID { get; set; }
    [Column("LocationSiteID")]
    public int SiteID { get; set; }
}

Mapping can be done using either of the following 3 methods
Method 1
Manually set the custom TypeMapper for your Model once as:
Dapper.SqlMapper.SetTypeMap(typeof(Site), new ColumnAttributeTypeMapper<Site>());
Dapper.SqlMapper.SetTypeMap(typeof(Location), new ColumnAttributeTypeMapper<Location>());

Method 2
For class libraries of .NET Framework >= v4.0, you can use PreApplicationStartMethod to register your classes for custom type mapping.
using System.Web;
using Dapper;

[assembly: PreApplicationStartMethod(typeof(YourNamespace.Initiator), "RegisterModels")]

namespace YourNamespace
{
    public class Initiator
    {
        private static void RegisterModels()
        {
             SqlMapper.SetTypeMap(typeof(Site), new ColumnAttributeTypeMapper<Site>());
             SqlMapper.SetTypeMap(typeof(Location), new ColumnAttributeTypeMapper<Location>());
             // ...
        }
    }
}

Method 3
Or you can find the classes to which ColumnAttribute is applied through reflection and set type mappings. This could be a little slower, but it does all the mappings in your assembly automatically for you. Just call RegisterTypeMaps() once your assembly is loaded.
    public static void RegisterTypeMaps()
    {
        var mappedTypes = Assembly.GetAssembly(typeof (Initiator)).GetTypes().Where(
            f =>
            f.GetProperties().Any(
                p =>
                p.GetCustomAttributes(false).Any(
                    a => a.GetType().Name == ColumnAttributeTypeMapper<dynamic>.ColumnAttributeName)));

        var mapper = typeof(ColumnAttributeTypeMapper<>);
        foreach (var mappedType in mappedTypes)
        {
            var genericType = mapper.MakeGenericType(new[] { mappedType });
            SqlMapper.SetTypeMap(mappedType, Activator.CreateInstance(genericType) as SqlMapper.ITypeMap);
        }
    }

A: There are more than one issues, let cover them one by one.
CTE duplicate column names:
CTE does not allow duplicate column names, so you have to resolve them using aliases, preferably using some naming convention like in your query attempt.

For some reason I have it in my head that a naming convention exists which will handle this scenario for me but I can't find mention of it in the docs.

You probably had in mind setting the DefaultTypeMap.MatchNamesWithUnderscores property to true, but as code documentation of the property states:

Should column names like User_Id be allowed to match properties/fields like UserId?

apparently this is not the solution. But the issue can easily be solved by introducing a custom naming convention, for instance "{prefix}{propertyName}" (where by default prefix is "{className}_") and implementing it via Dapper's CustomPropertyTypeMap. Here is a helper method which does that:
public static class CustomNameMap
{
    public static void SetFor<T>(string prefix = null)
    {
        if (prefix == null) prefix = typeof(T).Name + "_";
        var typeMap = new CustomPropertyTypeMap(typeof(T), (type, name) =>
        {
            if (name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
                name = name.Substring(prefix.Length);
            return type.GetProperty(name);
        });
        SqlMapper.SetTypeMap(typeof(T), typeMap);
    }
}

Now all you need is to call it (one time):
CustomNameMap.SetFor<Location>();

apply the naming convention to your query:
WITH TempSites AS(
    SELECT
        [S].[SiteID],
        [S].[Name],
        [S].[Description],
        [L].[LocationID],
        [L].[Name] AS [Location_Name],
        [L].[Description] AS [Location_Description],
        [L].[SiteID] AS [Location_SiteID],
        [L].[ReportingID]
    FROM (
        SELECT * FROM [dbo].[Sites] [1_S]
        WHERE [1_S].[StatusID] = 0
        ORDER BY [1_S].[Name]
        OFFSET 10 * (1 - 1) ROWS
        FETCH NEXT 10 ROWS ONLY
    ) S
        LEFT JOIN [dbo].[Locations] [L] ON [S].[SiteID] = [L].[SiteID]
),
MaxItems AS (SELECT COUNT(SiteID) AS MaxItems FROM Sites)

SELECT *
FROM TempSites, MaxItems

and you are done with that part. Of course you can use shorter prefix like "Loc_" if you like.
Mapping the query result to the provided classes:
In this particular case you need to use the Query method overload that allows you to pass Func<TFirst, TSecond, TReturn> map delegate and unitilize the splitOn parameter to specify LocationID as a split column. However that's not enough. Dapper's Multi Mapping feature allows you to split a single row to a several single objects (like LINQ Join) while you need a Site with Location list (like LINQ GroupJoin).
It can be achieved by using the Query method to project into a temporary anonymous type and then use regular LINQ to produce the desired output like this:
var sites = cn.Query(sql, (Site site, Location loc) => new { site, loc }, splitOn: "LocationID")
    .GroupBy(e => e.site.SiteID)
    .Select(g =>
    {
        var site = g.First().site;
        site.Locations = g.Select(e => e.loc).Where(loc => loc != null).ToList();
        return site;
    })
    .ToList();

where cn is opened SqlConnection and sql is a string holding the above query.

A: The below code should work fine for you to load a list of sites with associated locations
var conString="your database connection string here";
using (var conn =   new SqlConnection(conString))
{
    conn.Open();
    string qry = "SELECT S.SiteId, S.Name, S.Description, L.LocationId,  L.Name,L.Description,
                  L.ReportingId
                  from Site S  INNER JOIN
                  Location L ON S.SiteId=L.SiteId";
    var sites = conn.Query<Site, Location, Site>
                     (qry, (site, loc) => { site.Locations = loc; return site; });
    var siteCount = sites.Count();
    foreach (Site site in sites)
    {
        //do something
    }
    conn.Close();
}


text:
Q: Problem with Exclusions when Floor is used Plot[Floor[Sin[x]], {x, -Pi, Pi}, PlotLabel -> Floor[Sin[x]],  Frame -> True, GridLines -> Automatic,  GridLinesStyle -> Directive[LightGray, Dashed],  FrameTicks -> {Automatic, {Table[x, {x, {-Pi, 0, Pi}}], None}},  ExclusionsStyle -> {Dotted, Red}, PlotRange -> {{-Pi, Pi}, {-1, 1}}]

which gives

While I expect something like this, espeacially when x=Pi/2, for example, should be 1.

A: It misses it due to sampling. You can see this by asking to explicitly sample Pi/2
Plot[Floor[Sin[x]], {x, -Pi, Pi},
 PlotPoints -> {50, {Pi/2}},
 PlotLabel -> Floor[Sin[x]],
 Frame -> True,
 GridLines -> Automatic,
 GridLinesStyle -> Directive[LightGray, Dashed],
 FrameTicks -> {Automatic, {Table[x, {x, {-Pi, 0, Pi}}], None}},
 ExclusionsStyle -> {Dotted, Red},
 PlotRange -> {{-Pi, Pi}, {-1, 1.1}}]

Just adding more sample points did not help, it kept missing Pi/2. One way around this is to make 2 plots and use Show
f[x_] := If[Mod[x, Pi/2] != 0, Null, Sin[x]]
data = Table[{x, f[x]}, {x, -Pi, Pi, Pi/10}];
p1 = ListPlot[data, PlotStyle -> Red];

p2 = Plot[Floor[Sin[x]], {x, -Pi, Pi},
   PlotLabel -> Floor[Sin[x]],
   Frame -> True,
   GridLines -> Automatic,
   GridLinesStyle -> Directive[LightGray, Dashed],
   FrameTicks -> {Automatic, {Range[-Pi, Pi, Pi/2], None}},
   ExclusionsStyle -> {Dotted, Red},
   PlotRange -> {{-Pi, Pi}, {-1, 1.1}}];
Show[p2, p1]

May be there is a better way without using 2 plots, but I could not figure it out.


text:
Q: Alternatives for "I told you so." Sometimes, "I told you so" is expected by the target. What if we want to surprise them with another famous phrase which would deliver the same message, perhaps with more intensity. Sometimes, "I told you so" doesn't quite say it, maybe because we wish it carried more weight.
What are other possibilities? A single word, or phrase or idiom maybe.

A: Other possibilities:

Don't say I didn't warn you!
Now do you believe me!?
What did I tell you!?
You just had to do it anyway, didn't you?
You should have listened to me...
How many times did I tell you not to do that?
You're a bit of a slow learner, aren't you?
You just won't be told, will you?

A: In the words of the great and fictitious nutcase, Sheldon Cooper, from The Big Bang Theory episode entitled 'The 21 Second Excitation':

"Under normal circumstances I'd say I told you so. But, as I have told you so with such vehemence and frequency already the phrase has lost all meaning. Therefore, I will be replacing it with the phrase, I have informed you thusly."

See Youtube clip here.

A: I have used «voilà» (or «voila») in comparable situations. It may be loosely translated as «there you go» and thus seems right for the occasion. It has the advantage of being very concise and the disadvantage of being rather French, and it may not necessarily carry more weight if it is not understood. However, it does imply that you knew that a particular event would occur and, possibly, that you had warned the addressee.

A: To convey a stronger meaning the following come to mind:

*

*It serves you right!!

*You have made the bed    ( now lie in it)!!

*That will teach you!!

A: I think "what did I say?" conveys that meaning.

A: Duh! would be a single word answer.
duh |də, do͝o| exclam. informal
used to comment on an action perceived as foolish or stupid, or a statement perceived as obvious: I left the keys in the ignition—duh! | Leopold correctly informs him that the opera is in Italian (duh!).

A: A new phrase which I have been hearing lately:
"Can someone please answer that phone, because I called it."


text:
Q: what is difference between http.get( ) method and var request = require('request') I am new to the node JS ,In the nodeJS exercise no.8 of learnyounode ,my solution produces the same require result.I am confused when to use http.get and Request
goal:
Write a program that performs an HTTP GET request to a URL provided to you
  as the first command-line argument. Collect all data from the server (not
  just the first "data" event) and then write two lines to the console
  (stdout).
The first line you write should just be an integer representing the number
  of characters received from the server. The second line should contain the
  complete String of characters sent by the server.
official solution
var http = require('http')
var bl = require('bl')

http.get(process.argv[2], function (response) {
    response.pipe(bl(function (err, data) {
        if (err)
            return console.error(err)
        data = data.toString()
        console.log(data.length)
        console.log(data)
    }))
})

my solution
var request=require('request')
request(process.argv[2],function(err,response,body){
console.log(body.length);
console.log(body);
})

A: From nodeJS documentation:

Since most requests are GET requests without bodies, Node.js provides
  this convenience method. The only difference between this method and
  http.request() is that it sets the method to GET and calls req.end()
  automatically. Note that response data must be consumed in the
  callback for reasons stated in http.ClientRequest section.

So, what exactly that means, is that you could do it your way without any problem. But request is not a module shipped with node itself, it is a module to make http(s) requests easier on the developers. So I'm guessing here, that you are learning NodeJS and not using third-parties should be the way to go.

A: I'm not familiar with request but it's seems like it's just a npm package that wraps the functionality of the standard library. You can use both but I would suggest reading through the documentation of http.get and request and if you find the standard library function (http.get) sufficient for your needs I don' t see a reason you should use the request package.


text:
Q: Узнать сразу несколько свойств блока Здравствуйте,как правильно указать параметр метода css
$("#div_1").css(["font-family","text-align"])
$("#div_1").css("font-family","text-align")
$("#div_1").css({"font-family","text-align"})

А то эти три варианта не работают.
Спасибо!


text:
Q: Javascript to convert UTC to local time does not work in Chrome I have written some Javascript to convert a database datetime in UTC format into local datetime.  It works fine in Firefox and IE, but does not work in Chrome (for some reason it adds 3 hours to the times).  Here is my code, any advice would be very appreciated :)
EDIT : The datetime is passed into my first function in the format '2014-06-21 20:00:00'
    function convertUTCTimeToLocal(utc24HrDateTime) {

    //first convert from 24hr to 12hr clock
    var twentyFourHrTime = convertDateToTime(utc24HrDateTime);
    var twelveHrTime = convert24hrTo12Hr(twentyFourHrTime);
    var twelveHrDateTime = convert12HrToDateTime(utc24HrDateTime, twelveHrTime);
    var utc12HrDateTime = twelveHrDateTime + ' UTC';
    var date = new Date(utc12HrDateTime);
    var dayMonthTimeOnly = convertToDayMonthTimeOnly(date);
    return dayMonthTimeOnly;
}

function convert24hrTo12Hr(time) {
    // Check correct time format and split into components
    time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

    if (time.length > 1) { // If time format correct
        time = time.slice(1);  // Remove full string match value
        time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
        time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    return time.join(''); // return adjusted time or original string
}

function convertDateToTime(fixtureDate) {
    var d = new Date(fixtureDate);       // now
    var y = d.getFullYear();  // the full year (4 digits)
    var m = d.getMonth() + 1; // 0-based month

    var dt = d.getDate();     // 0-based day of the month
    dt = dt < 10 ? '0' + dt : dt; // add a preceding 0 to numbers less than 10

    var h = d.getHours();     // 0-based hours
    h = h < 10 ? '0' + h : h; // add a preceding 0 to numbers less than 10

    var mn = d.getMinutes();      // minutes
    mn = mn < 10 ? '0' + mn : mn; // add a preceding 0 to numbers less than 10

    return h + ':' + mn;
}

function convert12HrToDateTime(fixtureDate, twelveHrTime) {
    var d = new Date(fixtureDate);       // now
    var y = d.getFullYear();  // the full year (4 digits)
    var m = d.getMonth() + 1; // 0-based month

    var dt = d.getDate();     // 0-based day of the month
    dt = dt < 10 ? '0' + dt : dt; // add a preceding 0 to numbers less than 10

    return m + '/' + dt + '/' + y + ' ' + twelveHrTime;
}

function convertToDayMonthTimeOnly(fixtureDate) {
    var d = new Date(fixtureDate);       // now
    var y = d.getFullYear();  // the full year (4 digits)
    var m = d.getMonth() + 1; // 0-based month

    var dt = d.getDate();     // 0-based day of the month
    dt = dt < 10 ? '0' + dt : dt; // add a preceding 0 to numbers less than 10

    var h = d.getHours();     // 0-based hours
    h = h < 10 ? '0' + h : h; // add a preceding 0 to numbers less than 10

    var mn = d.getMinutes();      // minutes
    mn = mn < 10 ? '0' + mn : mn; // add a preceding 0 to numbers less than 10

    return dt + '/' + m + ' ' + h + ':' + mn;
}

A: Looking at the data returned from the ajax call in the page http://brasil2014.azurewebsites.net/Team/Brazil I was able to reproduce the observation using the following test (written using QUnit):
test("convertUTCTimeToLocal", function(assert) {
    var expected = "12/6 22:00",
        actual = convertUTCTimeToLocal("2014-06-12T20:00:00");
    assert.equal(actual, expected);
});

(My time zone is GMT+1, but with daylight savings, hence I am expecting the time to be offset +2 hours).
I was able to further drill down the problem using the following test case:
test("convertDateToTime", function(assert) {
    var expected = "20:00",
        actual = convertDateToTime("2014-06-12T20:00:00");

    assert.equal(actual, expected);
});

Changing the first lines of the function convertDateToTime to:
function convertDateToTime(fixtureDate) {
    var d = new Date(fixtureDate);       // now
    console.log(d);
    ...
}

showed me that the value of d already was converted from UTC to local time.
Some investigation showed that the underlying cause is the fact that JavaScript engines are free to interpret the date in any timezone it wants. See the following answer for more details.
Using this knowledge I rewritten and simplified the the code as follows:
function convertUTCTimeToLocal(fixtureDate) {

    function zeroPad(num) {
        return num<10 ? '0'+num : num;
    }

    var d = new Date(fixtureDate + "Z"),
        m = d.getMonth() + 1,
        dt = zeroPad(d.getDate()),
        h = zeroPad(d.getHours()),
        mn = zeroPad(d.getMinutes());
    return dt + '/' + m + ' ' + h + ':' + mn;
}

The following test case shows that it works correctly on both Chrome and Firefox:
test("convertUTCTimeToLocal", function(assert) {
    var expected = "12/6 22:00",
        actual = convertUTCTimeToLocal2("2014-06-12T20:00:00");
    assert.equal(actual, expected);
})


text:
Q: Search docker images by sha256 Is that possible to search docker images by sha256?
Suppose that nginx:latest and nginx:stable-alpine-perl are the same image (I mean if I pull nginx:latest, it has perl inside too (let us suppose) with the following output:
root@saeed:/# docker pull nginx:stable-alpine-perl
stable-alpine-perl: Pulling from library/nginx
8663204ce13b: Pull complete
d953079a3046: Pull complete
ea6555c01322: Pull complete
cbc136171839: Pull complete
d0f7b76a6d37: Pull complete
8f7ff84fa6b0: Pull complete
Digest: sha256:a20f8020221340e9fa8f83b4d8e611b04d34731b36dfa8528c5bc45066d3ecce
Status: Downloaded newer image for nginx:stable-alpine-perl
docker.io/library/nginx:stable-alpine-perl
root@saeed:/# docker images --digests | grep nginx | grep a20f8020221340e9fa8f83b4d8e611b04d34731b36dfa8528c5bc45066d3ecce
nginx                                 stable-alpine-perl   sha256:a20f8020221340e9fa8f83b4d8e611b04d34731b36dfa8528c5bc45066d3ecce   40b7e6d681dd   3 weeks ago     57.8MB

The current version is 1.20.2.
Suppose around two months later I want to check what image I did exactly pull.
The only information I have is sha256:a20f8020221340e9fa8f83b4d8e611b04d34731b36dfa8528c5bc45066d3ecce, but two months later's nginx:latest's sha256 is different.
Is there a way to search and find images by sha256?
I searched but found nothing unfortunately.

A: Looking at dockerhub documentation there seems to be an endpoint dedicated for this operation called "Get Image tags".
https://docs.docker.com/docker-hub/api/latest/#tag/images/operation/GetNamespacesRepositoriesImagesTags
General gist is that provided you know the namespace, repository, and sha256 digest of an image, you can extract all the tags that are assigned to that particular image. Sadly, the endpoint is behind docker hub's authentication requirement.
In case you're running your own registry, the following answer should be useful to you https://stackoverflow.com/a/68473409/6523288


text:
Q: How to determine if the wifi is disconnected from the command line? Ubuntu version: 20.04
Shell: bash
Kernel version: 5.8.0-53-generic #60~20.04.1-Ubuntu
I have a PC which runs a cryptocurrency workload 24/7, and it must be connected to wifi. I have noticed that at least once in a day, the wifi goes down and it does not automatically reconnect. The wifi icon just goes off with a question mark as shown below.

I have to manually run a network-manager restart (as shown below) to fix the issue.
sudo service network-manager restart

Until I find a permanent fix I am thinking a running a script every 5 minutes which will check if the wifi is down, and if it is down it will run a network-manager restart. How do I determine if the wifi is down from command line?

A: Failing to find another solution, you can try something similar to this:
tail -f /var/log/syslog | grep --line-buffered ' wlo1: CTRL-EVENT-DISCONNECTED ' \
| while read line
do
  echo "Caught: $line"
  echo "Restarting network-manager..."
  sudo service network-manager restart
done

You can modify the string in grep to something that matches your system.

A: The command-line tool nmcli has a connectivity check with the below command:
    nmcli networking connectivity

From man pages
   connectivity [check]
       Get network connectivity state. The optional check argument tells NetworkManager to
       re-check the connectivity, else the most recent known connectivity state is displayed
       without re-checking.

       Possible states are:

       none
           the host is not connected to any network.

       portal
           the host is behind a captive portal and cannot reach the full Internet.

       limited
           the host is connected to a network, but it has no access to the Internet.

       full
           the host is connected to a network and has full access to the Internet.

       unknown
           the connectivity status cannot be found out.

When you run nmcli networking connectivity command, it returns any of the below values:
none, portal, limited, full, unknown
You can prepare your script according to the value you required.


text:
Q: Format text file for the LOAD DATA INFILE command I'm working in a company where I have this project to create a web application based on the products my company is making.
There is an inside server which contains all the data from my company. What I have to do is parse the data the oracle server is retrieving. It is retrieving .lst files which can be easily translated to .csv using Excel or some php packages.
I successfully imported the Clients table into my MySQL database using the LOAD DATA INFILE command. But I'm running some issues when I want to parse the Articles table.
The columns/values aren't necessarily separated by semi-colons. To parse the data I'll have to say for example :

*

*The first 6 characters are the Article ID

*The next 35 characters are the description of the article

and so on...
Is there a way I could achieve this when using the LOAD DATA INFILE command, or should I format the file correctly using PHP then use this command and if so what could be the best approach?
Thanks guys, I hope I made myself clear since english isn't my primary language. :P
Edit : those are rows.
51016 51016 BOITE ORANGINA 33cls CASHS   "24"                               040430024000330  0000000000            1       01000000550009000                   000000NNNNNN caisse         0000003750000000000001230
51019 51019 BOITE OASIS ORANGE CASHS  "24" 33cl                             040430024000330  0000000000            1       01000000550009000                   000000NNNNNN caisse         0000003670000000000001230

The first line is getting parsed correctly while the second isnt.The double quote after 24 is being put into the next column. I just wanted to know if it was possible to do something about it, like deleting the double quotes.
A previous developer created an application to manage the articles, clients from the company. Unfortunately he cannot help me anymore but here is a ligne that describe a row.
import_a;Code_article;6;designation;35;designation2;35;Code_famille;2;Code_sousfamille;4;unite_condition;3;contenance;6/1000;Champ_vide;2;degre;4/10;champ_vide_6;6;Code_emballage;4;Champ_vide2;8;validite;1;Champ_vide3;7;code_tva;2;taux_tva;9/100;poids;6/1000;champ_vide4;19;montant_droits;6/1000;valide;1;rupture;1;edit_tarif;1;pre_commande;1;gratuit_autorise;1;trans_port;1;Champ_libre;1;caisse;15;prix_revient;9/100;stock;6/1;Champ_vide5;5;code_fournisseur;11/1

import_a => It's the filename you can just ignore that.
Then you have the name of the column followed by the number of characters. For example Code_articles is composed of 6 characters and so on.
You can also just ignore the duplicate ID Key at the beginning. But in total there should be 31 columns.

A: You can use this perl script to start your testing. The most important thing is the adjust the $def line according to your real data, until your get the correct result.
#!/usr/bin/perl

$input_file = "/tmp/a.lst";
$output_file = "/tmp/a.csv";
$testing = 1;  #testing, print out directly first 100 lines

# we are using tab (#9) for the output csv file
$delim   ="\t";

# output column header
$output_header = 1;

$defs= "import_a;Code_article;6;Code_article2;6;designation;29;designation2;35;Code_famille;2;Code_sousfamille;4;unite_condition;3;contenance;6/1000;Champ_vide;2;degre;4/10;champ_vide_6;6;Code_emballage;4;Champ_vide2;8;validite;1;Champ_vide3;7;code_tva;2;taux_tva;9/100;poids;6/1000;champ_vide4;19;montant_droits;6/1000;valide;1;rupture;1;edit_tarif;1;pre_commande;1;gratuit_autorise;1;trans_port;1;Champ_libre;1;caisse;15;prix_revient;9/100;stock;6/1;Champ_vide5;5;code_fournisseur;11/1";

my @input_fields, @input_fieldwidths, @input_fieldwidth_max, $input_field_no =0;
@defs= split(";",$defs);
$total_defs=$#defs;
$total_cols = 0;
$total_width = 0;

for($x=0; $x<$total_defs /2; $x++)
{
  push(@input_fields, $defs[$x*2+1]);
  $width = $defs[$x*2+2];
  if($width=~/(.*)\/(.*)/){
    $mw= $1;
    $xw= $2;
  }
  else{
    $mw = $width;
    $xw= 0;
  }
  $total_width += $mw;
  push(@input_field_widths,$mw);
  push(@input_field_widths_max, $xw);
  $total_cols ++;
}

if($testing){
  for($x=1; $x<$total_cols; $x++)
  {
    print "$input_fields[$x]: $input_field_widths[$x]\n";
  }
}

open(INPUT, $input_file) || die "Can not open input file";
open(OUTPUT, ">$output_file" ) || die "Can not open output file";

# this is the csv head
if($output_header){
  print OUTPUT "$input_fields[0]";
  for($x=1; $x<$total_cols; $x++)
  {
    print OUTPUT "\t$input_fields[$x]";
  }
  print OUTPUT "\n";
}

$lines=0;

foreach $l (<INPUT>)
{
  chop($l);
  $pos =0;
  for($f=0; $f < $total_cols; $f++)
  {
    $val = substr($l, $pos, $input_field_widths[$f]);
    print OUTPUT $delim if($pos);
    print $delim if($pos && $testing);
    print OUTPUT $val;
    print $val if($testing);
    $pos +=  $input_field_widths[$f];
  }
  print OUTPUT "\n";
  print "\n" if($testing);
  $lines++;
  if($testing && $lines>100) { last;};
}

print $lines , " lines transformed\n";

close(INPUT);
close(OUTPUT);

Edit: for a comma separated quoted csv format:
#!/usr/bin/perl

$input_file = "/tmp/a.lst";
$output_file = "/tmp/a.csv";

# we are using tab (#9) for the output csv file
$delim   =";";
$testing = 1;  #testing, print out directly first 10 lines
$quote   ="'";

# output column header
$output_header = 1;

$defs= "import_a;Code_article;6;Code_article2;6;designation;29;designation2;35;Code_famille;2;Code_sousfamille;4;unite_condition;3;contenance;6/1000;Champ_vide;2;degre;4/10;champ_vide_6;6;Code_emballage;4;Champ_vide2;8;validite;1;Champ_vide3;7;code_tva;2;taux_tva;9/100;poids;6/1000;champ_vide4;19;montant_droits;6/1000;valide;1;rupture;1;edit_tarif;1;pre_commande;1;gratuit_autorise;1;trans_port;1;Champ_libre;1;caisse;15;prix_revient;9/100;stock;6/1;Champ_vide5;5;code_fournisseur;11/1";

my @input_fields, @input_fieldwidths, @input_fieldwidth_max, $input_field_no =0;
@defs= split(";",$defs);
$total_defs=$#defs;
$total_cols = 0;
$total_width = 0;

for($x=0; $x<$total_defs /2; $x++)
{
  push(@input_fields, $defs[$x*2+1]);
  $width = $defs[$x*2+2];
  if($width=~/(.*)\/(.*)/){
    $mw= $1;
    $xw= $2;
  }
  else{
    $mw = $width;
    $xw= 0;
  }
  $total_width += $mw;
  push(@input_field_widths,$mw);
  push(@input_field_widths_max, $xw);
  $total_cols ++;
}

if($testing){
  for($x=0; $x<$total_cols; $x++)
  {
    print "$input_fields[$x]: $input_field_widths[$x]\n";
  }
}

open(INPUT, $input_file) || die "Can not open input file";
open(OUTPUT, ">$output_file" ) || die "Can not open output file";

# this is the csv head
if($output_header){
  print OUTPUT "$input_fields[0]";
  for($x=1; $x<$total_cols; $x++)
  {
    print OUTPUT "\t$input_fields[$x]";
  }
  print OUTPUT "\n";
}

$lines=0;

foreach $l (<INPUT>)
{
  chop($l);
  $pos =0;
  for($f=0; $f < $total_cols; $f++)
  {
    $val = substr($l, $pos, $input_field_widths[$f]);
    print OUTPUT $delim if($pos);
    #print $delim if($pos && $testing);
    print OUTPUT $quote, $val, $quote;
    if($testing){
      print $input_fields[$f] , "=", $val, "\n";
    }
    $pos +=  $input_field_widths[$f];
  }
  print OUTPUT "\n";
  print "\n" if($testing);
  $lines++;
  if($testing && $lines>0) { last;};
}

print $lines , " lines transformed\n";

close(INPUT);
close(OUTPUT);


text:
Q: Is there any guarantee about the evaluation order within a pattern match? The following
(&&) :: Bool -> Bool -> Bool
False && _ = False
True && False = False
True && True = True

has the desired short-circuit property False && undefined ≡ False. The first clause, which is non-strict in the right argument, is guaranteed to be checked before anything else is tried.
Apparently, it still works if I change the order and even uncurry the function
both :: (Bool,Bool) -> Bool
both (True,False) = False
both (True, True) = True
both (False, _) = False

Prelude> both (False, undefined)
False

but is this actually guaranteed by the standard? Unlike with the order of clauses, the order of evaluation of the patterns is not so clear here. Can I actually be sure that matching (True,False) will be aborted as soon as (False,_) is determined, before the snd element is evaluated at all?

A: Yes, it is guaranteed that evaluating the expression both (False, undefined) will not diverge since matching on data constructors is guaranteed to match left-to-right against the components of the constructor and the pattern fails as soon as some sub-pattern fails. Since the first element of the tuple is False, the pattern will fail for both (True, ...) branches as soon as the first element fails to match.
Per the Haskell 2010 Report, section 3.17.2, which gives an informal semantics of pattern matching:

*Matching the pattern con pat1 … patn against a value, where con is a constructor defined by data, depends on the value:

*

*If the value is of the form con v1 … vn, sub-patterns are matched left-to-right against the components of the data value; if all matches succeed, the overall match succeeds; the first to fail or diverge causes the overall match to fail or diverge, respectively.

*If the value is of the form con′ v1 … vm, where con is a different constructor to con′, the match fails.

*If the value is ⊥, the match diverges.

Since the tuple syntax is just a special-case syntactic sugar for a data constructor, the above applies.
For a fuller treatment of pattern matching, see section 3.17.3 of the Haskell 2010 Report, which gives a formal semantics of pattern matching (specifically, figure 3.2 pertains to this question).
Another resource of interest is the paper Pattern-driven Reduction in Haskell which specifies the semantics as an interpreter (written in Haskell) of an abstract syntax representation of Haskell's concrete syntax (the function mP in figure 3, page 7 is relevant to the question).


text:
Q: Best way to get user permission So I'm making a small site for fun and learning. Now I use PHP and PDO.
What I'm wondering is whats the best way to do so I can see what permission the user have. Instead of making queries on every page like on a user page to see if user have permission to edit it, and then a query in forum to see if they can delete posts etc. This seems very bad. So I wonder what is the best way? Should I put a session for everything? Right now this is how I do in my login:
// if we found a match
if ($row) {
    $_SESSION['id'] = $row['id'];
    header("Location: index.php");
    exit;
}

groups
  id | title | can_edit_users | can_ban_users | can_delete_post...
  1    Member        0               0                0

  id | title | can_edit_users | can_ban_users | can_delete_post...
  2     Mod          0               0                1

  id | title | can_edit_users | can_ban_users | can_delete_post...
  3    Admin         1               1                1

users
id | group_id | username | password

A: I would load the entire permission flags for the given title of logged in user. You can also use bitmask to represent many fields in one numeric digit.


text:
Q: Wix: Cannot upgrade from 'single user' installation to 'all user' installation My WIX script upgraded older installations correct until I changed it to an all-user installation.
Now an upgrade results in 2 items in the Windows add/remove programs list.
With the older versions, the shortcuts were added to:
C:\Users\xxx1\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\xxx2.
This was not correct.
After I added  to the Wix script, the shortcuts were added to:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\xxx2.
This is correct. But now an upgrade is not working anymore (double entries in Windows Add/remove).
I tried several thinks like:

*

*Setting the "ALLUSERS" flag after uninstall. No success.

*Manually trying to deinstall the previous version. Could not get it working

*Forcing administrator Privileges by using: InstallPrivileges="elevated" AdminImage="yes" InstallScope="perMachine". No success.

Question: How can I upgrade correct (or deinstall before installation) after I changed my Wix script from 'single user' to 'all user'?

A: correct. That's a Windows Installer limitation.
Even if MSI could do this, it couldn't reach out to the X number of other users on the machine that might need to have their per-user removed.
https://learn.microsoft.com/en-us/windows/win32/msi/major-upgrades

If an application is installed in the per-user installation context,
any major upgrade to the application must also be performed using the
per-user context. If an application is installed in the per-machine
installation context, any major upgrade to the application must also
be performed using the per-machine context. The Windows Installer will
not install major upgrades across installation context.


text:
Q: Table displaying wrong in Firefox, table goes horizontal? I'm having trouble with a table that has images, and all is great browsing with Chrome and IE but the trouble starts with Firefox. The table instead going vertically goes horizontal from the second row and so for. Can anybody tell me what is the problem and how can I fix this? Here is a link to the page.

A: For one, you have two tds in the top row and only one in the rest.
Also, what is this!? No opening tr.

Fix these errors and your issue will probably be resolved.

A: It's a difference between the interface of the different browsers.  Unfortunatly, browsers do not have a standardized version so we can develop one application that works on all, but instead they build them based on their own standards so web developers run into this problem a lot.  The only way to "fix" this is to detect the kind of browser you are operating in, and switch the way you output the code based on that.

A: You should remove 'display' style from your table rows:
None of comments below solved my issue.

A: Set rowspan="1", that was the solution in this case


text:
Q: Node and npm is not recognized after install node using nvm First I installed nvm.
then I tried nvm-v and it gives me the version.
After that I installed node.js nvm install 6.10.0
It also succeeded.
But when I try to npm-v node-v both are not recognized.
I thinks the installed path isn't recognized by the system.
How do I resolve this error?
When I try nvm use 6.10.0 it gives me this error

I'm using Windows 8.1

A:
Note: nvm does not support Windows (see #284). Two alternatives exist, which are neither supported nor developed by us:
   - nvm-windows
   - nodist

source: nvm readme

A: I believe you should use NVM versions 8.* ones. That should solve the problem. I am using Windows only.
If you face issues, you can follow up below steps.

*

*Go to Control Panel, Add or Remove Programs. Repair NodeJS.

*Go to CMD ( Command Line ), run ng serve or npm install to verify.

*If still issue, run nvm off

*Then run  ng serve or npm install

*Run nvm on

*Now run ng serve or npm install. It should work now.

A: Please try these links. Many people found that it helps. Note, NVM must be installed before NodeJS.
TechBrij & Microsoft Docs


text:
Q: Вывести полное название товаров в SQLite+Python user_request=input("Введите название товара: ")
db=sqlite3.connect("ostatki.db")
cur=db.cursor()
result=cur.execute(f"SELECT ostatki_tovarov FROM  ostatki_tovatov WHERE nazvanie_tovara MATCH
(?)",(user_request,))
for i in result:
    print(f"{user_request}:{i}")

db.close()

Есть такой код.
Мне нужно когда юзер вводить например такой запрос "Травертин", ответ должен быть:

*

*Травертин внутренний 50 кг

*Травертин фасадный 20 кг

и так далее. То есть вывести полное название товара.
А сейчас на выходе:

*

*Травертин 50 кг

*Травертин 20 кг.

Спасибо.


text:
Q: How can I pass a specific list variable to a Get and Set function? How can I pass on a specific global list variable to the following Get and Set functions?
Assume there is a @{Files} list with multiple xxxx.txt files.
Assume @{Files}[0] has dinosaur.txt
Get the File Version
[Arguments] @{Files}[??]    # Not sure about this
Run Keyword If  File is present
... ${time} = OperatingSystem.Get Modified Time @{Files}[]
... ${dateonly} = Split String ${time}  ${SPACE}
... ${Version} = @{dateonly}[0]
ELSE
... ${Version} = MISSING
[Return]  ${Version}

Set a dinosaur file version test case
  ${Version} = Get the File Version @{Files}[0] # Is this right ???
  Set test variable ${Version}

A: List variables have two ways to use. When referenced as ${mylist} we are referencing the underneath Python object (a variable of type List). When we use @{mylist} we are expanding all the elements from that list.
The following code is a fully working example reproducing your original code (you only need to create a file named dinosaur.txt):
*** Settings ***
Library         OperatingSystem
Library         Collections
Library         String

*** Test Cases ***
Test Files Versions
  @{Files}=  Create List  dinosaur.txt  bird.txt  dog.txt  cat.txt
  ${Version}=  Get the File Version  ${Files[0]}
  Log  Version of file, ${Files[0]} is ${Version}
  FOR  ${file}  IN  @{Files}
    ${file_version}=  Get the File Version  ${file}
    Log  Version of file, ${file} is ${file_version}
  END
  Set Test Variable  ${Files}
  Set a dinosaur file version test case
  Log  Version of file, ${Files[0]} is ${Version}

*** Keywords ***
Get the File Version
  [Arguments]  ${File}
  ${file_is_present}=  File is present  ${File}
  IF  ${file_is_present}
      ${time}=  OperatingSystem.Get Modified Time  ${File}
      @{dateonly}=  Split String  ${time}  ${SPACE}
      ${Version}=  Set Variable  ${dateonly[0]}
  ELSE
      ${Version}=  Set Variable If  not ${file_is_present}  MISSING
  END
  [Return]  ${Version}

Set a dinosaur file version test case
  ${Version}=  Get the File Version  ${Files[0]}
  Set test variable  ${Version}

File is present
  [Arguments]  ${File}
  ${result}=  Run Keyword And Return Status  File Should Exist  ${File}
  Return From Keyword  ${result}


text:
Q: Does an ODE written using GNU gsl outperform Mathematica's NDSolve? Would an ODE solver written in C perhaps using the GSL library have significant speed advantages compared with Mathematica 8.0 NDSolve? How would it fair in terms of accuracy?
My understanding is that compiled code could in principle be faster, but that these days NDSolve uses a lot of compiled code itself already somehow?
Also are there any options for using things like MathLink or Mathematica's compile function to speed solving an ODE up?

A: NDSolve and other numerical functions in Mathematica automatically compile your operand (e.g. the RHS of an ODE) to an intermediate "bytecode" language (the same one used by the Compile function). If you like you can specify CompilationTarget -> "C" and the function will be compiled all the way to C code and linked back in to Mathematica... You can see the generated C code yourself in this previous question on the Mathematica Stack Exchange:
https://mathematica.stackexchange.com/questions/821/how-well-does-mathematica-code-exported-to-c-compare-to-code-directly-written-fo/830#830
Of course, it's always possible in principle to hand-write a faster algorithm... But there are a lot of things to optimize that Mathematica will do automatically. You probably don't want to be responsible for manually optimizing the computation of a sparse matrix of partial derivatives in an optimization problem for example.

A: Mathematica's focus is on usability. They do use numerical libraries. So the speed would be the same as the best available library or worse (in almost all cases). for example, i heard they use eigen for matrix stuff.
the other thing that you should consider is that although they optimize functions that they provide, your own functions are not optimized. so the derivative that you calculate at each step would be faster in c.
to my friends that decide between mathematica and c++, i tell to go with mathematica since they should focus on getting results fast rather than building the fastest code.


text:
Q: CloudKit - How to share multiple records and retrieve shared records? I watched last WWDC 2016 What's New with CloudKit to understand how to share records with other users using CKShare
Single record sharing:
I am able to share and retrieve a single record
i.e if xyz@gmail.com has created and shared a single record to abc@gmail.com
Multiple records sharing:
let's say there are 10 records and xyz@gmail.com wants to share to  abc@gmail.com. I am facing the issue when user xyz@gmail.com shares multiple records to user abc@gmail.com
What I have tried so far:
First I created 3 note records:
Note1
Note2 ( set parent as Note1 )
Note3 ( set parent as Note1 )
I shared Note1 ( Parent record ) with below code:
CODE - Share record
let controller = UICloudSharingController { controller,
        preparationCompletionHandler in

        let share = CKShare(rootRecord: self.parentRecord!)
        share[CKShareTitleKey] = "note" as CKRecordValue
        share.publicPermission = .readOnly

        let operation = CKModifyRecordsOperation(
              recordsToSave: [self.parentRecord!, share],
              recordIDsToDelete: nil)

        operation.perRecordCompletionBlock = { (record, error) in
            if let error = error {
                print("CloudKit error: \(error.localizedDescription)")
            }
        }

        operation.modifyRecordsCompletionBlock = { records, recordIDs, error in

            if error != nil {
                print(error?.localizedDescription ?? "Error")
            } else{
                print("Success")
                preparationCompletionHandler(share,CKContainer.default(), error)
            }
        }

        CKContainer.default().privateCloudDatabase.add(operation)

    }

    controller.availablePermissions = [.allowPrivate, .allowReadOnly]
    controller.delegate = self
    present(controller, animated: true)

and retrieved shared-note with below code:
CODE - Read data from shared-note
func application(_ application: UIApplication, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShareMetadata) {
    let acceptSharesOperation = CKAcceptSharesOperation(
        shareMetadatas: [cloudKitShareMetadata])

    acceptSharesOperation.perShareCompletionBlock = {
        metadata, share, error in
        if error != nil {
            print(error?.localizedDescription)
        } else {

            let operation = CKFetchRecordsOperation(
                recordIDs: [cloudKitShareMetadata.rootRecordID])

            operation.perRecordCompletionBlock = { record, _, error in

                if error != nil {
                    print(error?.localizedDescription)
                }

                if let shareRecord = record {
                    DispatchQueue.main.async() {
                        // Shared record successfully fetched. Update user
                        // interface here to present to user.
                        print("\(shareRecord["id"]!)") // id of note
                        print("\(shareRecord["text"])") // text of note
                        print("Shared record successfully fetched")
                    }
                }
            }

            operation.fetchRecordsCompletionBlock = { (recordsWithRecordIDs,error) in
                if error != nil {
                    print(error?.localizedDescription)
                }else {
                    if let recordsWithRecordIDs = recordsWithRecordIDs {
                        print("Count \(recordsWithRecordIDs.count)")
                    }
                }
            }
            CKContainer.default().sharedCloudDatabase.add(operation)
        }
    }

    CKContainer(identifier: cloudKitShareMetadata.containerIdentifier)
        .add(acceptSharesOperation)
}

Above method gives only parent note data ( root/parent only )
Queries:
1) How to fetch other children note records? ( I used term children for understanding purpose )
2) Do I need to check every time whether there are new shared records or not
As I haven't found any good tutorials and the source from official Apple docs. Would you suggest me the approach to share and retrieve multiple records?
Thanks in advance..!

A: I believe Thunk's answer is incorrect, since you should not have to fetch any records with the parent reference to a given record. First, where would you search? The child records of the CKShare root record do not appear in your shared database and you don't have access to the other user's private zone. Luckily, CloudKit will push to you all child records referenced by the CKShare's root record. The following approach will also solve the second problem, you will be notified of any and all future changes automatically!
The key is to simply add a CKDatabaseSubscription to the shared database in the CloudKit container. Let's assume you are the client. Anytime another user share's a record with you, the CKShare record and the underlying root record referenced by the share are both situated in a custom zone in that user's private database. When you accept the share (triggering an application delegate method userDidAcceptCloudKitShareWith), the same CKShare and underlying record are now visible to you, except that they are both visible in your shared database. If you have subscribed to the shared database, the subscription will kick in and notify you right after you accept the share. Now you can fetch all changes in the shared database using CKFetchDatabaseChangesOperation. In the recordZoneWithIDChangedBlock, the CKRecordZoneID of the sharing user's custom zone will be given. You use this to trigger a CKFetchRecordZoneChangesOperation (be sure to perform this operation in the shared database!), which returns the CKShare, the underlying root record, and all records that have a parent reference to the underlying referenced record.
So with a simple database subscription you can automatically trigger and download all shares, root records, and children!

A: Regarding question 1, to find the records that have references to the parent, you'll need to create a query that checks the reference field for rootRecordID. This page from Apple has a section discussing retrieval options with code examples.
https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloudKitQuickStart/AddingReferences/AddingReferences.html
Regarding question 2, you could constantly poll the server for updated records, but Apple discourages that in one of the WWDC videos since it generates a lot of network traffic (and thus burns through your monthly quota). I suggest adding a subscription notice on the CKshare. That way, you'll be notified when you need to fetch records.


text:
Q: ANTLR trying to create a lexer rule that goes up to, but not including, some symbols I'm using ANTLR4 to parse text adventure game dialogue files written in Yarn, so mostly free form text and loads of island grammars, and for the most part things are going smoothly but I am having an issue excluding certain text inside the Shortcut mode (when presenting options for the player to choose from).
Basically I need to write a rule to match anything except #, newline or <<. When it hits a << it needs to move into a new mode for handling expressions of various kinds or to just leave the current mode so that the << will get picked up by the already existing rules.
A cut down version of my lexer (ignoring rules for expressions):
lexer grammar YarnLexer;

NEWLINE : ('\n') -> skip;

CMD : '<<' -> pushMode(Command);
SHORTCUT : '->' -> pushMode(Shortcut);

HASHTAG : '#' ;

LINE_GOBBLE : . -> more, pushMode(Line);

mode Line;
LINE : ~('\n'|'#')* -> popMode;

mode Shortcut ;
TEXT : CHAR+ -> popMode;
fragment CHAR : ~('#'|'\n'|'<');

mode Command ;
CMD_EXIT : '>>' -> popMode;

// RULES FOR OPERATORS/IDs/NUMBERS/KEYWORDS/etc
CMD_TEXT : ~('>')+ ;

And the parser grammar (again ignoring all the rules for expressions):
parser grammar YarnParser;

options { tokenVocab=YarnLexer; }

dialogue: statement+ EOF;

statement : line_statement | shortcut_statement | command_statement ;

hashtag : HASHTAG LINE ;

line_statement : LINE hashtag? ;

shortcut_statement : SHORTCUT TEXT command_statement? hashtag?;

command_statement : CMD expression CMD_EXIT;
expression : CMD_TEXT ;

I have tested the Command mode when it is by itself and everything inside there is working fine, but when I try to parse my example input:
Where should we go?
-> the park
-> the zoo
-> Peter's house <<if $metPeter == true >>

ok shall we take the bus?
-> :<
-> ok

<<set $daySpent = true>>

my issue is the line:
-> Peter's house <<if $metPeter == true >>

gets matched completely as TEXT and the CMD rules just gets ignored in favour by far longer TEXT.
My first thought was to add < to the set but then I can't have text like:
-> :<

which should be perfectly valid. Any idea how to do this?

A: Adding a single left angle bracket to the exclusion list creates a single corner case that is easily handled:
TEXT : CHAR+ ;
CMD  : '<<' -> pushMode(Command);
LAB  : '<'  -> type(TEXT) ;

fragment CHAR : ~('\n' | '#' | '<') ;


text:
Q: Resolving Errno 13 Permission denied I'm trying to use the stockfish chess engine to make board evaluations through python-chess but getting permission errors.
mac os, python 3.7, Ipython through Conda 4.9.2
Here is the result with just the last line of the traceback:
import chess.engine
engine = chess.engine.SimpleEngine.popen_uci("/Applications/Stockfish.app")
...
PermissionError: [Errno 13] Permission denied: '/Applications/Stockfish.app'

I have successfully used chmod to set permissions but am still getting the error.
Please help, quite stuck on this one.

A: First, Stockfish.app is the desktop app of stockfish on Mac, not the Stockfish engine. So you need to use the engine. You can find old engines here (https://www.dropbox.com/sh/75gzfgu7qo94pvh/NlXX-QLGu6), but for the last engine, you need to install it using HomeBrew : brew install stockfish. See https://stockfishchess.org/download/ for more informations.
Second, in a terminal window, type chmod +x the_stockfish_engine_path
to disable the permission restriction.


text:
Q: Npgsql.PostgresException (0x80004005): 42601: syntax error at or near "INCLUDE" I m working  with PostgresSql & EF core 3.1. I created an index for one of my entity as follow
builder.HasIndex(e => e.MerchantId).IncludeProperties(e=>e.TemplateType);

in migration file i can see the below
migrationBuilder.CreateIndex(
                name: "IX_EmailTemplates_MerchantId",
                table: "EmailTemplates",
                column: "MerchantId")
                .Annotation("Npgsql:IndexInclude", new[] { "TemplateType" });

When run update-database I m getting the below Error.
Failed executing DbCommand (24ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE INDEX "IX_EmailTemplates_MerchantId" ON "EmailTemplates" ("MerchantId") INCLUDE ("TemplateType");
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (24ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE INDEX "IX_EmailTemplates_MerchantId" ON "EmailTemplates" ("MerchantId") INCLUDE ("TemplateType");
**Npgsql.PostgresException (0x80004005): 42601: syntax error at or near "INCLUDE"**

Any one can help me on this error ?


text:
Q: Как получить параметры картинки до её загрузки? Возможно ли как-то получить высоту и ширину картинки до её загрузки(с сервера на клиент), но без использования PHP и прочего back-end?

A: Можешь эмулировать загрузку картинки, а потом получать ширину и высоту:

function getImgSize(imgSrc) {
  var newImg = new Image();

  newImg.onload = function() {
    var height = newImg.height;
    var width = newImg.width;
    console.log('Ширина:' + width + ' Высота:' + height);
  }

  newImg.src = imgSrc;
}

getImgSize('https://pixel.nymag.com/imgs/daily/science/2017/04/10/10-nature-outdoors.w710.h473.jpg');

A: Честно говоря, это как с бубном танцевать и ждать дождя. Вот как вы себе представляете, получение размеров фото до его загрузки?
Но все же могу предложить пару вариантов:

*

*Вы можете указать на сайте где вы грузите картинку, что размеры должны быть такими-то например 512х512;

*Создать что-то вроде буфера, где и конкретно измерять размер фото а после сверять их с вашими данными;

Каким образом вы собираетесь это сделать, ещё и без языков? Интересно какое у вас мнение, на этот повод? А мы уже и поможем вам, додумать до конца. ;)
P.s. Вы может хотите как на сайтах вроде Вконтакте или Ютуб, где вам пишут что - изображение не подходит?


text:
Q: 3000VA UPS Battery advice I am planning to upgrade my current UPS (BN1500M2, here) to a bigger 3000VA so that it can handle power outage longer (at least an hour for 300W load). I found these two UPS (SMX3000RMLV2U, SRT3000XLA). Here is a comparison between the three:
https://www.apc.com/shop/us/en/tools/compare-products/30nbq/BN1500M2%7CSMX3000RMLV2U%7CSRT3000XLA/300
My first question is, what is the difference between "line interactive" with "double conversion online" topology. The two newer ones support sine waveform output. "SRT3000XLA" is 1000$ more expensive than "SMX3000RMLV2U". I also found this page on generations of APC smart UPS.

Edit: The PowerChute software is showing the load ~300W when all equipment are attached. Each APC product has a page where at the end of the page, you can find "Run time for load" (one example here). I use 300 to get an estimate on the run time.

Edit: I found a very good article that explains the two topologies.
Is "SMX3000RMLV2U" suitable for my small home network? These are attached to my UPS:

*

*Two laptops

*One ultra-wide monitor

*One power-hungry desktop PC (Intel core i9-10980XE, Nvidia 3080 GPU)

*One sound-bar

*One NAS

*Two network switches

*Cable Modem

*Google Nest Mesh WiFi


text:
Q: php classe: problem getting value from function into a member variable I have a function that gets a value from the database and returns it. I call the function to store it into a member variable but I get the following error:
Parse error: parse error, expecting `','' or `';'' in I:\wamp\www\deposit\classes\Site.php on line 14

This is the line that causes the error
public static $depositmoney = self::get_balance();

And this is the function that gets the value from the database
    public static function get_balance()
    {
        global $link, $usertable, $userid, $useridentify;

        //query current balance
        $cb = mysqli_fetch_object(mysqli_query($link, "SELECT deposit FROM ".$usertable." WHERE ".$userid."=".$useridentify.""));
        return $cb->deposit;

    }//end of function get_balance().

all of this code is in the same class. Anyone an idea of what's causing the error?

A: Class properties may not be declared with run-time information.
public static $depositmoney = self::get_balance();

The above will not work.
See the PHP Manual on Class Properties: (emphasis mine)

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

You could create a getter for $depositmoney and have it initialize the value if it is currently unset:
public static function getDepositMoney()
{
    if(self::$depositmoney === NULL) {
        self::$depositmoney = self::get_balance();
    }
    return self::$depositmoney;
}

However, I suggest to get rid of the  static and use instance methods and properties instead to track the state. You will also want to get rid of the global stuff and inject dependencies through the constructor, setters or during the method invocation. That decreases coupling and will make the code more maintainable.


text:
Q: mock function, and references to this function I need to mock a function and all references which point to this function.
Example:
import mock

def do(msg):
    print(msg)

def foo():
    do('foo')

bar=foo

with mock.patch(__name__ + '.foo', lambda *args: do('mocked')):
    foo()
    bar()

the output is:
mocked
foo

But in my case I need to mock the real function, not just the name which points to the function implementation.
Background: I want to patch https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.PROTECT
How can I get the desired output without using "bar".
mocked
mocked

A: Rather than mocking foo, you could simply mock do instead.
with mock.patch(__name__ + '.do', lambda *args: print("mocked")):
    foo()
    bar()


text:
Q: No module named http_client error when trying to run django with django rest framework I am trying to create a simple API using django rest framework. In the view i have the following code.
    from django.shortcuts import render
from moviestash.models import Movie
from moviestash.serializer import MovieSerializer
from rest_framework import generics

#List all movies and add movies
class MovieList(generics.ListCreateAPIView):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer

#Get a movie and delete a movie
class MovieDetail(generics.RetrieveDestroyAPIView):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer

when i run the server and try to go to any url i get the following error.
Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 1.6
Python Version: 2.7.0
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'moviestash',
 'south',
 'rest_framework')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:
File "N:\Python\venvs\rest_api\lib\site-packages\django\core\handlers\base.py" in get_response
  101.                 resolver_match = resolver.resolve(request.path_info)
File "N:\Python\venvs\rest_api\lib\site-packages\django\core\urlresolvers.py" in resolve
  318.             for pattern in self.url_patterns:
File "N:\Python\venvs\rest_api\lib\site-packages\django\core\urlresolvers.py" in url_patterns
  346.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "N:\Python\venvs\rest_api\lib\site-packages\django\core\urlresolvers.py" in urlconf_module
  341.             self._urlconf_module = import_module(self.urlconf_name)
File "N:\Python\venvs\rest_api\lib\site-packages\django\utils\importlib.py" in import_module
  40.         __import__(name)
File "N:\Python\movies_api\movies_api\urls.py" in <module>
  10.     url(r'^movies/', include('moviestash.urls')),
File "N:\Python\venvs\rest_api\lib\site-packages\django\conf\urls\__init__.py" in include
  26.         urlconf_module = import_module(urlconf_module)
File "N:\Python\venvs\rest_api\lib\site-packages\django\utils\importlib.py" in import_module
  40.         __import__(name)
File "N:\Python\movies_api\moviestash\urls.py" in <module>
  3. from . import views
File "N:\Python\movies_api\moviestash\views.py" in <module>
  4. from rest_framework import generics
File "N:\Python\venvs\rest_api\lib\site-packages\rest_framework\generics.py" in <module>
  8. from rest_framework import views, mixins
File "N:\Python\venvs\rest_api\lib\site-packages\rest_framework\views.py" in <module>
  14. from rest_framework.response import Response
File "N:\Python\venvs\rest_api\lib\site-packages\rest_framework\response.py" in <module>
  8. from django.utils.six.moves.http_client import responses

Exception Type: ImportError at /
Exception Value: No module named http_client

When i go into the django shell and i can perform the following import with no issue from django.utils.six.moves import http_client. Also after i import http_client i also performed a dir(http_client) and i can see the responses object, but for some reason when i try to import using from django.utils.six.moves.http_client import responses i get an ImportError: No module named http_client. This is very frustrating to say the least.

A: It looks like you are hitting issue 2969. It should work if you upgrade from Django 1.6 to 1.6.11. However, please note that 1.6 is now end of life and does not receive security fixes, so ideally you should upgrade to the latest supported version of Django or the latest LTS.


text:
Q: House wide automation network: CAN or Ethernet? I am half-way through building my home automation system. As an electronic engineer/software developer a lot of this has been rolled myself from scratch and I will hopefully be starting to blog more and build up/publish my story and workings once complete.
I am now at the point of lighting automation. I have approximately 30 wall switches running a prototype touch sensor faceplate and I need to now connect these back to my Win7 Embedded automation computer. I also need to connect about 30-40 dimmers and relays.
As far as I can see I have a couple of options for protocols both at physical/application level and really am looking for any comments or advice on the below options, plus if anyone has any other suggestions.
Right now, all controllers are running off ARM M3 processors and I have both Ethernet and CANopen stacks available. The system needs to be "multi master" and ideally support both event driven (e.g. someone presses a button) and process driven (querying a sensor every 30 seconds, or asking a specific node a question).
CANopen

*

*Multi-master and automatic error correction/collision avoidance

*Process, service and event options for messages

*Can be complicated to "virtually wire" up device. Lots of configuration potentially required

*Cheap to implement in hardware, relatively scalable. Limit of 127 devices on a bus. Daisy-chain network.

Ethernet

*

*Multicast UDP, or broadcast? Not sure which is more appropriate

*Probably have to roll my own messaging protocol or API on-top to handle all the types of events I require, not sure about event driven actions

*Star network, BUT could support PoE which is nice

*More expensive in hardware

*Much more expandable in software (potentially infinite number of devices, etc).

Has anyone got any comments or thoughts on which may be the best route to proceed? I have a feeling Ethernet may be the way but worry there is far more implementation required in software.
Thanks

A: Although you could use Ethernet and implement a TCP/IP Stack on each controller, and surely use UDP to broadcast sensor readings/commands/etc. I would recommend the use of CAN for the following factors:

*

*Easier to Implement/Code

*Very, very lightweight. You can integrate with smaller controllers. A MCP2515 can be used if the MCU doesn't have CAN.

*You could use CAT5/CAT6 and use the spare wires and carry 24V or 36V to power the nodes.

*The small message frame can be easily fitted inside a sub-1Ghz RF frame if you decide to extend the Bus over RF. You just need to code a CAN to RF gateway, maybe using el-cheapo RFM69 modules.

There's a blog that explore the use of CAN bus for similar use, might worth checking it out: talk2.wisen.com.au
Anyway, if you decide go with Ethernet, UDP would be better so you don't need to worry much with node addressing.
All the best!

A: CAN is much simpler because is a revisited RS232 / RS485 but limited in number and functions. Wiring is standard serial and is much simpler than LAN. LAN and Wifi are surely much better because more functions are available, obviously prices are higher. Wifi could have the advantage of not requiring other cables than the power ones. Many cheap interface like Velleman ones are connected with RS485 or CAN but WIFI and LAN are way better if you like to develop your controlled devices.


text:
Q: How to display last whole post on the homepage I try to show on my homepage only the last post, in complete version.
I tried numerous methods unsuccessfully.
I tried in particular to create a specific template: "front-page.php", in which I put this code:
<?php
        global $post;
        $args = array( 'posts_per_page' => 1 );
        $lastposts = get_posts( $args );
        foreach ( $lastposts as $post ) :
          setup_postdata( $post ); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

            <?php the_content(); ?>
        <?php endforeach;
        wp_reset_postdata(); ?>

But only title and a link "more" appears.
I also tried in the settings to put for the homepage the "last posts" and the number of post to 1, it works, but the problem is that my pages of archive shows no more than one post.
Yet, I would like the last whole post on the homepage, and the titles of 10 last ones posts in the pages of archive.
Do you know what to do?

A: Just before the line of the_content(), add this:
$more = "";

This will set the 'more' flag to false, so the entire post should be displayed.


text:
Q: java.lang.IllegalArgumentException at org.apache.xbean.asm5.ClassReader.(Unknown Source) with Java 10 I Started getting the following error anytime I try to collect my rdd's. It happened after I installed Java 10.1 So of course I took it out and reinstalled it, same error. I then installed Java 9.04 same error. I then ripped out python 2.7.14, apache spark 2.3.0 and Hadoop 2.7, same error. Does anyone have any one have any other reasons why I keep getting the error?
>>> from operator import add
>>> from pyspark import SparkConf, SparkContext
>>> import string
>>> import sys
>>> import re
>>>
>>> sc = SparkContext(appName="NEW")
2018-04-21 22:28:45 WARN  Utils:66 - Service 'SparkUI' could not bind on port 4040. Attempting port 4041.
>>> rdd = sc.parallelize(xrange(1,10))
>>> new =rdd.collect()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\spark\spark-2.3.0-bin-hadoop2.7\python\pyspark\rdd.py", line 824, in collect
    port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
  File "C:\spark\spark-2.3.0-bin-hadoop2.7\python\lib\py4j-0.10.6-src.zip\py4j\java_gateway.py", line 1160, in __call__
  File "C:\spark\spark-2.3.0-bin-hadoop2.7\python\pyspark\sql\utils.py", line 63, in deco
    return f(*a, **kw)
  File "C:\spark\spark-2.3.0-bin-hadoop2.7\python\lib\py4j-0.10.6-src.zip\py4j\protocol.py", line 320, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: java.lang.IllegalArgumentException
        at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source)
        at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source)
        at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source)
        at org.apache.spark.util.ClosureCleaner$.getClassReader(ClosureCleaner.scala:46)
        at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:449)
        at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:432)
        at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:733)
        at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103)
        at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103)
        at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:230)
        at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:40)
        at scala.collection.mutable.HashMap$$anon$1.foreach(HashMap.scala:103)
        at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:732)
        at org.apache.spark.util.FieldAccessFinder$$anon$3.visitMethodInsn(ClosureCleaner.scala:432)
        at org.apache.xbean.asm5.ClassReader.a(Unknown Source)
        at org.apache.xbean.asm5.ClassReader.b(Unknown Source)
        at org.apache.xbean.asm5.ClassReader.accept(Unknown Source)
        at org.apache.xbean.asm5.ClassReader.accept(Unknown Source)
        at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:262)
        at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:261)
        at scala.collection.immutable.List.foreach(List.scala:381)
        at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:261)
        at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:159)
        at org.apache.spark.SparkContext.clean(SparkContext.scala:2292)
        at org.apache.spark.SparkContext.runJob(SparkContext.scala:2066)
        at org.apache.spark.SparkContext.runJob(SparkContext.scala:2092)
        at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:939)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
        at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
        at org.apache.spark.rdd.RDD.collect(RDD.scala:938)
        at org.apache.spark.api.python.PythonRDD$.collectAndServe(PythonRDD.scala:153)
        at org.apache.spark.api.python.PythonRDD.collectAndServe(PythonRDD.scala)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.base/java.lang.reflect.Method.invoke(Unknown Source)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:282)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.base/java.lang.Thread.run(Unknown Source)

>>> print rdd.getNumPartitions()
12
>>>
>>> print(new)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'new' is not defined
>>> sc.stop()

A:
Does anyone have any one have any other reasons why I keep getting the error?

Current Apache Spark versions don't support Java 9 or later. The support for these (or later versions) is planned for 3.0 release.
For the time being to run Spark you'll have to use JDK 8.
Source:

*

*time for Apache Spark 3.0?

*SPARK-24417 Build and Run Spark on JDK11

A: The issue can be resolved by updating Java to version 8, and modifying to JDK 8. The problem goes away with this configuration:

*

*JAVA JDK: jdk-8u92-windows-x64

*java version 1.8.0_181

The above is for your reference


text:
Q: When is jQuery .map useful without .get? The .map() function in jQuery returns a jQuery object:
var $collection = $(selector).map(extractSomeValue)

Most often, what is desired is a plain array of the mapped values:
var extractedArray = $collection.get()

In fact, ALL the use cases and examples I have found always pair .map() with .get(), including jQuery's own documentation.
What is the use case for working with the $collection as is? Why doesn't .map() simply return the array if that's what everyone uses it for?
EDIT: To be clear, I am referring only to jQuery.fn.map, not jQuery.map (aka $.map), since the latter is well-defined to operate only on non-jQuery objects and sensibly return a plain array.

A: Imagine you already have a jQuery object that contains a elements with ids as href. Now you want all target elements. This is where .map()can get handy:
var $list = $('a[href^=\\#]');
...
//somewhere else
var $targetElements = $list.map(function() {
       return $(this.href)[0];
});
$targetElements.addClass('newClass');

Or you want to create new elements based on the old ones:
var $links = $('a');
...
var $list = $links.map(function() {
       return $('
URL: ' + this.href + '
')[0];
});
$list.appendTo($myUl);

They may be not the most useful examples, I know, but they illustrate my point. You have list of elements and want another list of elements that somehow relate to the original elements. Or you create new elements based on the old ones. Using .map() you get a ready to use jQuery object.

A: The first thing to note, jQuery.fn.map is not the same as jQuery.map, which returns a plain array even if you apply it to a jQuery object.
In jQuery itself they sometimes chain jQuery.fn.map and jQuery.fn.filter. So map over a jQuery collection returns another jQuery collection, and they can call jQuery.filter on it without having to extend the result of map.
I thought it's just a side-effect of the implementation, but no, they do it on purpose, jQuery.fn.map internally calls jQuery.map and pushes the result onto the stack of matched elements.
Off of the top of my head, I can't see a really good use case for this feature. But you can, for example, return 0 or many nodes at once in your map function, and all these node will be put in a nice linear collection:
$elements.map(function() {
    return [document.createElement('div'),
            document.createElement('span')];
});

A: I may be confused (as evidenced by multiple edits), but my current understanding is that .map() returns a jQuery Object, which wraps a simple array, and provides other "helper" jQuery methods. It sounds like these helper functions are only really useful if the wrapped array is an array of DOM nodes. $.fn.get() will essentially unrwap the array for you. Therefore, I would think that you would NOT use get(), if your map function retuned actual DOM nodes rather other value types.
An (untested and probably a bit incorrect) example:
var $example = $('#foo').map(function() {
    if ($(this).innerHTML == "bar") {
        return this;
    }
});

From: http://ajpiano.com/when-to-use-jquerys-map-methods/

When you use jQuery.fn.map, the result is a jQuery object - an array of values with a set of functions made available by jQuery. Usually the array contains DOM nodes, but after using $.fn.map, it's just an array of arbitrary values. Most people are familiar with using .get(index) to access the DOM node at a selected index, but when .get() is called with no arguments, it returns the entire underlying array. This means you can't call jQuery methods on it anymore, but you can call Array.join, or any other Array method, which was probably the reason you wanted an array to begin with. So go out and .get() it!

A: Map is useful when you must retrieve some property of a set of selected elements as an [].
For example, lets say I wanted to get the hrefs of the following a elements:
Something
Something
Something
Something

I would need to use map in this situation:
var arr = $("a").map(function(i,e){
    return e.href;
});

A: The fact that .map() returns a jQuery object rather than a plain array may be useful when you want to keep using jQuery methods over the new collection. Here is an example (try it in your browser console) :
var $collection = $('#qinfo p:even').map(function () {
    return $(this).text();
});

var ucfirst = $collection.map(function () {
    return this.replace(/^./, function (fst) {
        return fst.toUpperCase();
    });
}).get();

var prefixed = $collection.map(function () {
    return 'prefix-' + this;
}).get();

console.log($collection.get());
console.log(ucfirst);
console.log(prefixed);

However, as mentionned in the comments, I assume that it's mainly a matter of code presentation. That said, .map() allows you to take advantage of function chaining. For that matter, we could go even further by wrapping .map() into a plugin. This way make things more readable and easily reusable :
$.fn.ucfirst = function () {
    return this.map(function () {
        return this.replace(/^./, function (fst) {
            return fst.toUpperCase();
        });
    });
};

$collection.ucfirst().each(function () {
    console.log(this.toString());
});

A thing to note though, .ucfirst() is intended to work with collections of strings, which is out of the scope of the original purpose of jQuery.


text:
Q: How to filter String in where clause I would like to extract the string using where clause in SAP HANA.For an example,these are 3 strings for name column.
123._SYS_BIC.meag.app.qthor.cidwh_eingangsschicht.backend.dblayer.l2.checks/MasterData_Holdings.
153._SYS_BIC.meag.app.qthor.centralAdministration.backend.dblayer.l2.checks/AuditAndSecurities.
meag.app.qthor.centralAdministration.backend.dblayer.l2.checks/GeneralLedger

After filter the name column using where clause, output in the name column would be shown only the last portion of the string. So, output will be like this. That means whatever we have, just remove from the beginning till '/'.
"MasterData_Holdings"
"AuditAndSecurities"
"GeneralLedger"

A: You can try using the REPLACE_REGEXPR
I'm not familiar myself with Hana but the function is pretty straight forward and it should be:
select REPLACE_REGEXPR('.+/(.+)' IN fieldName WITH '\1' OCCURRENCE ALL) as field
...
where
... -- your filter

Be aware that this regex '.+/(.+)' will eat everything until the last / so for instance if you have ....checks/MasterData_Holdings/Something it will return only Something


text:
Q: Flutter flip widget from side not middle I'm trying to create a animation for widgets which would make them flip. I've found snippets online but they all flip the middle, I want to flip from the extreme left or right

A: It's a simple fix. If you already have a Transform widget that can do the image above, the alignment property of the widget is probably set to Alignment.center, change this to Alignment.centerLeft or Alignment.centerRight to flip from right to left or left to right respectively
...
child: Transform(
          transform: Matrix4.identity()...,
          alignment: Alignment.centerLeft,
          child: ...,
        ),
);


text:
Q: CD/ DVD Silverlight SQLite App Does anyone have experience in developing a standalone app with Silverlight using SQLite database? App should be distributed on CD or DVD for Windows OS and has to have autorun, with possibility to install .NET Framework if needed.
How difficult is to develop that kind of app for someone who has two years experience in Asp.NET web forms apps?
Thanks in advance for your answers.

A: Please double-check what your goals are:

*

*SQLite does not run on Silverlight, or at least there aren't widely used ports of it available in any form

*Silverlight can't install .NET Framework, and in fact does not even require it


text:
Q: Visual Studio 2012 Nuget "The remote name cannot be resolved" I can't get any packages through NuGet as Visual Studio. The remote name that cannot be resolved is for an old proxy at a our company, but I'm using a direct to internet connection here. Is there a way to change the internet settings in Visual Studio to not use a proxy at all? I've tried nslookup and the IP matches that from the internet and another linux machine on the same network.
VS was installed behind the proxy server using that gateway, so we're getting to the disk through the post, reinstall point.
All other internet functions are working correctly and I can get nuget.org through a browser.
Thanks,
James

A: The problem was that the global Internet explorer options were still locked to use the old VPN. In VS2012 go to Environment/ Web server and change your settings there to not use a VPN. You will also have to look at the LAN settings too.


text:
Q: Android wear activity onKeyDown is not getting called This is not a duplicate but a specific case to Android wear. I am trying to make Android wear app do something when certain gestures are performed. But I realized that the onKeyDown() event is not called at all. Any help or info I this regard is useful. Here is my simple code snippet.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gesture_ema);

    Log.d(TAG, "Inside on create");

    //Show prompt window on top always
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON +
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

    //Prompt vibrator
    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    if (vibrator != null) {
        vibrator.vibrate(VIBRATION_PATTERN_INTENSE, -1);
    }

   // mTextView = (TextView) findViewById(R.id.text);

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
    Log.d(TAG, "Inside keydown");
    switch (keyCode){
        case KeyEvent.KEYCODE_NAVIGATE_NEXT:
            Toast.makeText(this, "NAVIGATE_NEXT", Toast.LENGTH_LONG).show();
            Log.d(TAG, "NAVIGATE_NEXT");
            vibrator.cancel();
            return true;
        case KeyEvent.KEYCODE_NAVIGATE_PREVIOUS:
            Toast.makeText(this, "NAVIGATE_PREVIOUS", Toast.LENGTH_LONG).show();
            Log.d(TAG, "NAVIGATE_PREVIOUS");
            vibrator.cancel();
            return true;
    }

    return super.onKeyDown(keyCode, event);
}

EDIT
I first thought the problem was solved due to a permission I added. But that permission was deprecated and it had nothing to with this case. Then as someone in the comments suggested switching on the gestures, I realized there are places where the tilt gesture is actually used. One is to tilt and wake up the watch, which is controlled by Wear OS app. The second is in wear settings called enable gesture. This is a required step as it also goes through a calibration tutorial. Therefore, this thing doesn't have the permission as such and has to be done manually. Once I enabled that and completed the tutorial, the keydown event was getting called. Thanks everyone :-)