text:
Q: What is the best way to compare two product / assembly versions Let us say that a product has an assembly version number of 1.5.4537.56784.  There are plenty of examples of how to retrieve this on SO and in most cases (if you simply want to display the information to the end user) then a default string representation is fine.
I now find myself wanting to compare this assembly number with another (this time most definitely stored as a string as it's in a text file online (but in the same format)) to determine whether the version number stored online is the same as the version number retrieved from the executing assembly or it is in fact greater. The term greater is important, not just different but actively greater.
A simple string compare ought to determine if they are the same but I don't think it would determine greater than.  So what type ought I consider changing these stings to in order to make the greater than comparison.  Or have I missed something obvious with string comparisons.

A: Split your values by . into an Integer array or list, whichever you prefer. Then use a simple If x > y  comparison for each position in the collection.
Dim myAssemblyVersion = "1.5.4537.56784"
Dim theirAssemblyVersion = "1.5.4827.1"

Dim myIntegers = myAssemblyVersion.Split(".")
Dim theirIntegers = theirAssemblyVersion.Split(".")

Dim isTheirsgreater As Boolean = False
For i = 0 To myIntegers.Count - 1
    If theirIntegers(i) > myIntegers(i) Then
        isTheirsgreater = True
    End If
Next

A: I would say the best way to compare versions is to use the comparison operators provided by the System.Version class. You can create a new instance of Version using the string you found in the text file online. Then you can use the GreaterThan operator to compare it to the version of your application.
Dim textVer As String = "1.5.4537.56784"
Dim onlineVer As New Version(textVer)
Dim myVer As Version = Reflection.Assembly.GetExecutingAssembly.GetName.Version

If onlineVer > myVer Then
    'Version found online is greater than mine
End If


text:
Q: Web api routing, URL not working I'm currently trying to create my own Web-Api for a cryptocurrency tracker I am making.
I want to get the values from a db. The technology here is MVC5.
I have a db that contains my wallet value with a time/date attached to it, I then have an api method here:
namespace Crytocurrency_Web___Main.Controllers
{
[RoutePrefix("WalletValue")]
public class WalletValueController : ApiController
{
    readonly ApplicationDbContext dbContext = new ApplicationDbContext();

    [Route("GetAllValues")]
    [HttpGet]
    public List<WalletValue> GetAllValues()
    {
        return dbContext.Wallet.ToList();
    }
  }
}

but when I go to the address
    localhost:51833/WalletValue/GetAllValues  I get the error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /WalletValue/GetAllValues

Here is the route config file too:
public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

here is document breakdown of where the controller is stored
Solution -> Controllers -> WalletValueController
Scaffolded WebAPi:
  public class WalletValuesController : ApiController
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: api/WalletValues
    public IQueryable<WalletValue> GetWallet()
    {
        return db.Wallet;
    }

    // GET: api/WalletValues/5
    [ResponseType(typeof(WalletValue))]
    public IHttpActionResult GetWalletValue(int id)
    {
        WalletValue walletValue = db.Wallet.Find(id);
        if (walletValue == null)
        {
            return NotFound();
        }

        return Ok(walletValue);
    }

    // PUT: api/WalletValues/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutWalletValue(int id, WalletValue walletValue)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != walletValue.Id)
        {
            return BadRequest();
        }

        db.Entry(walletValue).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!WalletValueExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/WalletValues
    [ResponseType(typeof(WalletValue))]
    public IHttpActionResult PostWalletValue(WalletValue walletValue)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Wallet.Add(walletValue);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = walletValue.Id }, walletValue);
    }

    // DELETE: api/WalletValues/5
    [ResponseType(typeof(WalletValue))]
    public IHttpActionResult DeleteWalletValue(int id)
    {
        WalletValue walletValue = db.Wallet.Find(id);
        if (walletValue == null)
        {
            return NotFound();
        }

        db.Wallet.Remove(walletValue);
        db.SaveChanges();

        return Ok(walletValue);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool WalletValueExists(int id)
    {
        return db.Wallet.Count(e => e.Id == id) > 0;
    }

A: Your Route attribute isn't being used. You have to enable attribute routing for Web API with this (in WebApiConfig.cs):
public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Web API routes
        config.MapHttpAttributeRoutes();
    }
}

You can also add this to enable attribute routing for your non-API controllers (in your RegisterRoutes method):
routes.MapMvcAttributeRoutes();

Once you do that, you can remove the route.MapRoute line if you want.
That should make it work as you have it.
But note that you can put [RoutePrefix("WalletValue")] on WalletValueController, then you just need to put [Route("GetAllValues")] on your action. That saves you from having to put WalletValue/ on every action.

redpajama_set_name: RedPajamaStackExchange


text:
Q: If $\det(AB)=4$ then find the value of $\det(BA)$
Let $A$ be a $2 \times 3$ matrix with real entries and let $B$ be a $3 \times 2$ matrix with real entries.
If $\det(AB)=4$ then find the value of $\det(BA)$.

My attempt:
I am aware that $\det(AB)=\det(BA)$ when $A$ and $B$ are of same order. But how to do this?

A: $A: \mathbb{R}^2 \rightarrow \mathbb{R}^3$ and hence the image of $A$ in $\mathbb{R}^3$ is at most a subspace of dim 2. Since $\det(AB) \neq 0$, it follows that the image of $A$ is of dimension 2. Since $B: \mathbb{R}^3 \rightarrow \mathbb{R}^2$, the image of $BA$ can not have dimension more than 2 and hence rank($BA$) < 3. Thus $\det(BA) = 0$


text:
Q: Bug with Revival badge Over on Pro Webmasters, I was just awarded the Revival badge for my answer here: Bulletin board software with voting capability for each post
But mine was not the first answer as you can see, so unless I'm mistaken I should not have got that badge. There were also some older "me too!" type answers that have been deleted, so perhaps that caused the bug, even though there is at least one remaining answer that is older.

A: Yours is not the first answer ever, but it is the first answer to get two upvotes, which is what the Revival badge is all about:

Answered more than 30 days later as first answer scoring 2 or more.

Emphasis added.


text:
Q: oAuth: calling out to another Salesforce org I am doing callout from one salesforce org to another saleforce org to get access token but i am getting this error {"error":"unsupported_grant_type","error_description":"grant type not supported"}
I tried using my domain url as well, didnt worked
In connected app i have following access
Access and manage your data (api)
Provide access to your data via the Web (web)
Perform requests on your behalf at any time (refresh_token, offline_access)
Allow access to your unique identifier (openid)
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setHeader('Content-Type','application/x-www-form-urlencoded');
req.setEndpoint('https://xxx.salesforce.com/services/oauth2/token');
String CLIENT_ID = 'xyz';
String CLIENT_SECRET = 'xyz';
req.setBody('grant_type=code' + '&client_id='+CLIENT_ID +
        '&client_secret='+CLIENT_SECRET + '&redirect_uri=https://xxx.my.salesforce.com/');
Http http = new Http();
HTTPResponse response = http.send(req);
System.debug('Body ' + response.getBody());
System.debug('Status ' + response.getStatus());
System.debug('Status code ' + response.getStatusCode());

Please help. Thanks in advance.

A: response_type=code corresponds to the authorization grant type (flow) in oAuth. In Salesforce universe this is known as a Web Server flow. All oAuth flows follow a prescribed sequence of steps. This particular flow involves a redirect with an authorization code which you then exchange for an access token (see docs). The snippet of code you posted is not obtaining an authorization token. Instead you're attempting to get the access token as the first step and that won't work in this specific flow.
For Salesforce-to-Salesforce calls with no user "present" (user's identity is not required for authorization), JWT Bearer flow is the recommended option. A Named Credential can issue a JWT out of the box and exchange it for the access token. See the JWT Token Exchange option and related explanation in this answer for more details on how it works.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MyJWT/some_path');
req.setMethod('POST');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());


text:
Q: Multiple jQuery Tooltips Interfering With Each Other I use the following code to have different tooltips, but only 1 tooltip per element.
They work just fine, if I only use 1 of them. But all together like this, they don't work properly (show up in the wrong location, with the wrong class, etc)
    var options = {
        show: true,
        hide: false,
        position: {
            using: function(position, feedback){
                $(this).css(position);
                $(this).addClass(feedback.horizontal);
                $(this).addClass(feedback.vertical);
            }
        }
    }

    //¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
    // Top
    //¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
    options.position.my     = 'center bottom';
    options.position.at     = 'center top-' + space;
    options.tooltipClass    = 'vertical';
    //...
    $('.jui-tooltip-top').tooltip(options);

    //¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
    // Left
    //¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
    options.position.my     = 'right center';
    options.position.at     = 'left-' + space + ' center';
    options.tooltipClass    = 'horizontal';
    //...
    $('.jui-tooltip-left').tooltip(options);

    //¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
    // Right
    //¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
    options.position.my     = 'left center';
    options.position.at     = 'right-' + space + ' center';
    options.tooltipClass    = 'horizontal';
    //...
    $('.jui-tooltip-right').tooltip(options);

    //¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
    // Bottom (Default)
    //¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬
    options.position.my     = 'center top';
    options.position.at     = 'center bottom+' + space;
    options.tooltipClass    = 'vertical';
    //...
    $('.jui-tooltip').tooltip(options);

HTML (examples)
...
...
...

What I figured out by now, when using all together, only the last one (bottom) always works. With the others, I then does not matter whether I provide the options or not.
--
How can I make them work all together?

A: try just marking all your tooltips with the data-toggle="tooltip" and then activating them all with one line of jquery.
$(function () {

    ...

    $("[data-toggle='tooltip']").tooltip(options);
});

To achieve different positions using this technique, use the data-* pattern on the elements that have the tooltips and specify the position that way.  I believe its data-placement="center top" or something like that.
Tooltip on top center

This way you dont need a different set of options for every placement, you can set a default placement in your options, and then override on elements that need a custom placement.

A: Solved it, by "cloning" the options. They were interfering with each other, even after initialization.
$('.jui-tooltip-top').tooltip($.extend(true, {}, options, {
    position: {
        my: 'right center',
        at: 'left-' + space + ' center'
    },
    tooltipClass: 'horizontal'
}));

// etc


text:
Q: How to test whether variance explained by first factor of PCA differs across repeated measures conditions? Context:
I have a study where six numeric variables are measured in each of two repeated measures experimental conditions (n = 200). Lets call the conditions $A$ and $B$ and the variables $A_1, A_2,..., A_6$ and $B_1, B_2,..., B_6$. Theoretically, I expect that in condition $B$ more variance in the variables should be explained by the first factor of  a principal components analysis (PCA).
Typical values would be:

*

*First factor of PCA on $A_1, ..., A_6$ accounts for 30% of variance

*First factor of PCA on $B_1, ..., B_6$  accounts for 40% of variance.

Questions:

*

*How can I test whether this difference is statistically significant?

*How could this be implemented in R?

A: Just one (maybe silly) idea. Save 1st principal component scores variable for condition A (PC1A) and 1st principal component scores variable for condition B (PC1B). The scores should be "raw", that is, their variances or sum-of-squares equal to their eigenvalues. Then use Pitman's test to compare the variances.

A: Did I get your answer right? - You want to test if there is statistically significant difference between the two conditions?
Perhabs vegan::adonis() is something for you? Don´t know if that´s what your looking for.
It works on the distance-matrix and compares distances within a condition are bigger then between conditions. For example in a NMDS you would see a clear separation of the two conditions.
Here is some example Code:
df <- data.frame(cond = rep(c("A", "B"), each = 100),
 v1 <- jitter(rep(c(20, 100), each = 100)),
 v2 <- jitter(rep(c(0, 80), each = 100)),
 v3 <- jitter(rep(c(40, 5), each = 100)),
 v4 <- jitter(rep(c(42, 47), each = 100)),
 v5 <- jitter(rep(c(78, 100), each = 100)),
 v6 <- jitter(rep(c(10, 100), each = 100)))

# PCA
require(vegan)
pca <- rda(df[ ,-1], scale = TRUE)
ssc <- scores(pca, display = "sites")
ordiplot(pca, type = "n")
points(ssc[df$cond == "A", ], col = "red", pch = 16)
points(ssc[df$cond == "B", ], col = "blue", pch = 16)

# NMDS
nmds <- metaMDS(df[ ,-1], distance = "euclidian")
nmsc <- scores(nmds, display = "sites")
ordiplot(nmds, type = "n")
points(nmsc[df$cond == "A", ], col = "red", pch = 16)
points(nmsc[df$cond == "B", ], col = "blue", pch = 16)

# use adonis to test if there is a difference between the conditions
adonis(df[ ,-1] ~ df[ ,1], method = "euclidean")
## There is a statistically significant difference between the two conditions

A: Permutation test
To test the null hypothesis directly, use a permutation test.
Let the first PC in condition $A$ explain $a<100\%$  of variance, and the first PC in condition $B$ explain $b<100\%$ of variance. Your hypothesis is that $b>a$, so we can define $c=b-a$ as the statistic of interest, and the hypothesis is that $c>0$. The null hypothesis to reject is that $c=0$.
To perform the permutation test, take your $N=200+200$ samples from both conditions, and randomly split them into conditions $A$ and $B$. As the splitting is random, there should be no difference in explained variance after that. For each permutation, you can compute $c$, repeat this process many (say, $10000$) times, and obtain the distribution of $c$ under the null hypothesis of $c_\mathrm{true}=0$. Comparing your empirical value of $c$ with this distribution will yield a $p$-value.
Bootstrapping
To obtain the confidence interval on $c$, use bootstrapping.
In the bootstrapping approach, you would randomly select $N=200$ samples with replacement from the existing samples in $A$ and another $N=200$ from $B$. Compute $c$, and repeat it many (again, say, $10000$) times. You are going to obtain a bootstrapped distribution of the $c$ values, and its percentile intervals are going to correspond to the confidence intervals of the empirical value $c$. So you can estimate the $p$-value by looking at what part of this distribution lies above $0$.
The permutation test is a more direct (and probably less relying on any assumptions) way to test the null hypothesis, but the bootstrap has an added benefit of yielding a confidence interval on $c$.

A: This is only an outline of idea. The proportion of variance is defined as
$$\frac{\lambda_1}{\lambda_1+...+\lambda_6},$$
where $\lambda_i$ are the eigenvalues of covariance matrix. Now if we use instead the eigenvalues of correlation matrix then $\lambda_1+...+\lambda_6=6$, since the sum of eigenvalues of a matrix is equal to the trace of the matrix, and for correlation matrices the trace is the sum of ones.
So if we use the correlation matrices we need to test hypotheses about the difference of two maximal eigenvalues of sample correlation matrices. It is certainly possible to find in the literature the asymptotic distribution of the maximal eigen-value of correlation matrix. So the problem then reduces to some sort of paired or unpaired t-test.


text:
Q: Use correlated subquery over multiple columns DB-Fiddle
CREATE TABLE logistics (
    id int primary key,
    campaign VARCHAR(255),
    event_type VARCHAR (255),
    date_offered VARCHAR (255),
    date_ordered VARCHAR (255),
    date_delivered VARCHAR (255),
    date_recorded VARCHAR (255),
    date_completed VARCHAR (255),
    quantity_offered VARCHAR(255),
    quantity_ordered VARCHAR(255),
    quantity_delivered VARCHAR(255),
    quantity_recorded VARCHAR(255),
    quantity_completed VARCHAR(255)
);

INSERT INTO logistics
(id, campaign, event_type,
date_offered, date_ordered,
date_delivered, date_recorded, date_completed,
quantity_offered, quantity_ordered,
quantity_delivered, quantity_recorded, quantity_completed
)
VALUES
("1", "C001", "offered", "2019-04-10", NULL, NULL, NULL, NULL, "500", NULL, NULL, NULL, NULL),
("2", "C001", "ordered", NULL, "2019-04-16", NULL, NULL, NULL, NULL, "450", NULL, NULL, NULL),
("3", "C001", "stored", NULL, NULL, "2019-04-18", NULL, NULL, NULL, NULL, "465", NULL, NULL),
("4", "C001", "stored", NULL, NULL, NULL, "2019-04-20", NULL, NULL, NULL, NULL, "440", NULL),
("5", "C001", "stored", NULL, NULL, NULL, NULL, "2019-04-22", NULL, NULL, NULL, NULL, "445"),

("6", "C002", "offered", "2019-08-15", NULL, NULL, NULL, NULL, "600", NULL, NULL, NULL, NULL),
("7", "C002", "ordered", NULL, "2019-09-03", NULL, NULL, NULL, NULL, "700", NULL, NULL, NULL),
("8", "C002", "stored", NULL, NULL, "2019-09-05", NULL, NULL, NULL, NULL,  "690", NULL, NULL),
("9", "C002", "stored", NULL, NULL, NULL, "2019-09-08", NULL, NULL, NULL, NULL, "692", NULL),

("10", "C003", "offered", "2019-10-24", NULL, NULL, NULL, NULL, "300", NULL, NULL, NULL, NULL),
("11", "C003", "ordered", NULL, "2019-10-28", NULL, NULL, NULL, NULL, "250", NULL, NULL, NULL),
("12", "C003", "stored", NULL, NULL, "2019-10-31", NULL, NULL, NULL, NULL, "320", NULL, NULL),

("13", "C004", "offered", "2019-11-05", NULL, NULL, NULL, NULL, "800", NULL, NULL, NULL, NULL),
("14", "C004", "ordered", NULL, "2019-11-14", NULL, NULL, NULL, NULL, "870", NULL, NULL, NULL),
("15", "C004", "stored", NULL, NULL, "2019-11-16", NULL, NULL, NULL, NULL, "740", NULL, NULL),

("16", "C005", "offered", "2019-12-17", NULL, NULL, NULL, NULL, "240", NULL, NULL, NULL, NULL),
("17", "C005", "ordered", NULL, "2020-01-12", NULL, NULL, NULL, NULL, "250", NULL, NULL, NULL),
("18", "C005", "stored", NULL, NULL, "2020-01-16", NULL, NULL, NULL, NULL, "226", NULL, NULL),

("19", "C006", "offered", "2020-01-09", NULL, NULL, NULL, NULL, "100", NULL, NULL, NULL, NULL),
("20", "C006", "ordered", NULL, "2020-01-23", NULL, NULL, NULL, NULL, "105", NULL, NULL, NULL),

("21", "C007", "offered", "2020-02-17", NULL, NULL, NULL, NULL, "900", NULL, NULL, NULL, NULL),
("22", "C008", "offered", "2020-02-25", NULL, NULL, NULL, NULL, "400", NULL, NULL, NULL, NULL);

The table above displays the purchasing process of different campaigns.
The first three process steps are defined by the event_types offered, ordered and stored.
Once a campaign has reached the process step stored the process continues with different dates called date_completed, date_recorded and date_delivered. Basically, those dates are sub_events from the event_type stored.
The hierarchy of those events is like this:
event_type = stored > ordered > offered
date = date_completed > date_recorded > date_delivered

Now, I want to extract the campaigns based on their highest event_type or - in case they already have reached the event_type stored - based on their highest date according to the defined hierarchy. The result should look like this:
campaign    event_type        date                quantity
C001         stored         2019-04-22              445
C002         stored         2019-09-08              692
C003         stored         2019-10-31              320
C004         stored         2019-11-16              740
C005         stored         2020-01-16              226
C006         ordered        2020-01-23              105
C007         offered        2020-02-17              900
C008         offered        2020-02-25              400

With reference to this question I tried to modify the query like this:
SELECT
campaign,
event_type,
coalesce(date_offered, date_ordered) as main_event_date,
coalesce(date_delivered, date_recorded, date_completed) as sub_event_date,
coalesce(quantity_offered, quantity_ordered) as main_event_quantity,
coalesce(quantity_delivered, quantity_recorded, quantity_completed) as sub_event_quantity
FROM logistics lg
WHERE lg.id = (SELECT lg2.id
                        FROM logistics lg2
                        WHERE lg2.campaign = lg.campaign
                        ORDER BY field(lg2.event_type, 'stored', 'ordered', 'offered')
                                 field(lg2.sub_event_date, 'date_completed', 'date_recorded', 'date_delivered')
                         LIMIT 1
                        );

However, I don't know how I should you use the field function once the campaign is in the event_type stored because there is no sub_event column for the dates?

A: You can use a subquery and group te data by campaign:
SELECT campaign,MAX(event_type) AS event_type,
CASE WHEN MAX(sub_event_date)>MAX(main_event_date) THEN MAX(sub_event_date) ELSE MAX(main_event_date) END  AS event_date,
CASE WHEN MAX(sub_event_date)>MAX(main_event_date) THEN MAX(sub_event_quantity) ELSE MAX(main_event_quantity) END AS event_quantity
FROM (
SELECT
campaign,
event_type,
coalesce(date_offered, date_ordered) as main_event_date,
coalesce(date_delivered, date_recorded, date_completed) as sub_event_date,
coalesce(quantity_offered, quantity_ordered) as main_event_quantity,
coalesce(quantity_delivered, quantity_recorded, quantity_completed) as sub_event_quantity
FROM logistics lg) l
GROUP BY campaign

A: DB-Fiddle
The solution is as the following:
Step 1: Create an aggregated_sub_table called AGR_logistics which adds  an additional column called sub_event_type to the original table:
CREATE TABLE AGR_logistics

SELECT
id,
campaign,
event_type,
 (CASE
  WHEN event_type = "stored" AND quantity_delivered IS NOT NULL THEN "delivered"
  WHEN event_type = "stored" AND quantity_recorded IS NOT NULL THEN "recorded"
  WHEN event_type = "stored" AND quantity_completed IS NOT NULL THEN "completed"
  ELSE NULL END) AS sub_event_type,
date_offered,
date_ordered,
date_delivered,
date_recorded,
date_completed,
quantity_offered,
quantity_ordered,
quantity_delivered,
quantity_recorded,
quantity_completed
FROM logistics;

Step 2: Run a correleated subquery as described here over AGR_logistics:
SELECT
id,
campaign,
event_type,
sub_event_type,
coalesce(date_offered, date_ordered, date_delivered, date_recorded, date_completed) as event_date,
coalesce(quantity_offered, quantity_ordered, quantity_delivered, quantity_recorded, quantity_completed) as event_quantity
FROM AGR_logistics AGR_01
WHERE AGR_01.id = (SELECT AGR_02.id
                   FROM AGR_logistics AGR_02
                   WHERE AGR_02.campaign = AGR_01.campaign
                   ORDER BY
                     field(AGR_02.event_type, 'stored', 'ordered', 'offered'),
                     field(AGR_02.sub_event_type, 'completed', 'recorded', 'delivered')
                   LIMIT 1
                   );


text:
Q: Cloud Formation Template errors I am beginning to learn Cloud Formation Templates and I am running into issues when I validate the template in AWS Cloud Formation -> Create new stack. I am writing the templates using the CloudFormation plugin in Pycharm. These are a couple of the error messages that I get when validating in CloudFormation:
1/10/2022, 5:41:06 PM - Template contains errors.: Template format error: YAML not well-formed. (line 27, column 16)
1/10/2022, 5:40:06 PM - Template contains errors.: Template format error: YAML not well-formed. (line 24, column 12)
Below is my simple code:
AWSTemplateFormatVersion: "2010-09-09"
# Description:
Resources:
  #Create the VPC
  MyCustomVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: '10.3.0.0/16'
      EnableDnsHostnames: true
      EnableDnsSupport: true
      Tags:
        - key: Name
          value: !Sub '${AWS::StackName}-application-vpc-acg'
  # Create the Subnets
  PublicSubnetA:
    Type: AWS::EC2::Subnet
    Properties:
      CidrBlock: '10.3.0.0/24'
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Select [ 0, !GetAZs]
      Tags:
        - Key: Name
          Value: !Sub '${AWS::StackName}-public-subnet-A'
      VpcId: !Ref MyCustomVPC

  PublicSubnetB:
    Type: AWS::EC2::Subnet
    Properties:
      CidrBlock: '10.3.1.0/24'
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Select [1, !GetAz]
      Tags:
        - Key: Name
          Value: !Sub '${AWS::StackName}-public-subnet-B'
      VpcId: !Ref MyCustomVPC

  #Create Internet Gateway
  MyInternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - key: Name
          Value: !Sub '${AWS::StackName}-Internet-Gateway

  #Attach Internet Gateway to VPC
  MyIGWAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref MyInternetGateway
      VpcId: !Ref MyCustomVPC

Any help to point me in the right direction is greatly appreciated.
Thank you!

A: There are many issues, such as spelling mistakes, missing parentheses, wrong functions. The correct version is:
AWSTemplateFormatVersion: "2010-09-09"
# Description:
Resources:
  #Create the VPC
  MyCustomVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: '10.3.0.0/16'
      EnableDnsHostnames: true
      EnableDnsSupport: true
      Tags:
        - Key: Name
          Value: !Sub '${AWS::StackName}-application-vpc-acg'
  # Create the Subnets
  PublicSubnetA:
    Type: AWS::EC2::Subnet
    Properties:
      CidrBlock: '10.3.0.0/24'
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Select [ 0, !GetAZs ""]
      Tags:
        - Key: Name
          Value: !Sub '${AWS::StackName}-public-subnet-A'
      VpcId: !Ref MyCustomVPC

  PublicSubnetB:
    Type: AWS::EC2::Subnet
    Properties:
      CidrBlock: '10.3.1.0/24'
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Select [1, !GetAZs ""]
      Tags:
        - Key: Name
          Value: !Sub '${AWS::StackName}-public-subnet-B'
      VpcId: !Ref MyCustomVPC

  #Create Internet Gateway
  MyInternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: !Sub '${AWS::StackName}-Internet-Gateway'

  #Attach Internet Gateway to VPC
  MyIGWAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref MyInternetGateway
      VpcId: !Ref MyCustomVPC


text:
Q: How do I add an unknown amount of unknown modules in Dagger 2? I have several modules that I don't know at compile time (think "plugins"). They all implement a "tag" interface MyModule: public interface MyModule {}
I've instantiated them thanks to ServiceLoader and @AutoService.
How do I add them all to my component builder?
The Dagger 2 authors seem to think that this question is relevant to StackOverflow. I don't believe that it is, because it looks like a missing use case, but well, I give them the benefits of the doubt here and post it.
I know I could use Guice or Dagger 1, but as said in the ticket to the Dagger 2 team; I don't want any reflection (bar ServiceLoader), and Dagger 1 is now deprecated. Also, recommends switching to Dagger 2 (which is why I'm trying to upgrade my Dagger 1 project to Dagger 2).

A: This is impossible as it stands, and is also outside of Dagger 2's charter. See the opening sentence of the project overview (emphasis mine):

Dagger is a fully static, compile-time dependency injection framework for both Java and Android.

When you're asking for your object graph to handle arbitrary marker-interface modules, you're precluding Dagger from knowing which @Provides methods it will have access to, which deprives Dagger of the ability to inspect and wire up your component at compile time. So, for Dagger to support your use case as you've stated it, it would have to reverse a number of core architectural decisions and advantages of compile-time inspection and code generation. Though I'm not on the Dagger team, I imagine this would make it a poor fit for the foreseeable future, which I imagine is part of the reason your issue was marked Working As Intended.
That said, there are number of ways you could use multiple coexisting components (one per plugin) to use static analysis and code generation in the core application, while supporting an arbitrary number of plugins. For instance, if your plugins have a predictable set of dependencies, you can create a new PluginModule(PluginFactory... factoriesToSupport), which would offer a @Provides Set<Plugin> createPluginSet(Dep1 dep1, Dep2 dep2) to iterate across the plugin factories and return you a set of plugins. In addition, if the plugin dependencies represent a large proportion of your top-level Component and your build graph supports it, you could inject the Component itself into the @Provides method, and then let your individually-built PluginFactory instances defer to their own (static-analyzed code-generated) Dagger components to produce the plugin instances. In short, as long as you're in Dagger, you'll need to play by Dagger's compile-time analysis rules, but within those constraints you can still likely come to a workable solution.


text:
Q: Should I authorize users based on their SID or their Windows Username? I am creating a C# DotNet Application that authorizes users using their windows active directory ID.
Windows users have 2 unique identifiers

*

*The Username (e.g. MyDomain\someuser)

*The SID (e.g. S-1-5-21-1695517229-881958489-217698969-1001
QUESTION: In my back end should I authorize users based on their SID or Windows Username?
What's the best practice?
Here are my thought so far:

*

*The SIDs are unique but some newbie can delete and create a new Active Directory ID. This will cause the user to have different SID and unable to login

*As for the username, I'm worried it can be spoofed. Not sure if such is possible though.

A:
I'm worried it can be spoofed

What do you mean by "spoofed"? You're going to be connecting to only one domain, and only one account on any domain can have the same username.
Even if you decide to authenticate by SID, you're not going to ask the user for their SID, so you'll have to translate the username into the SID anyway, which means you're still authenticating with a username.
But remember you don't just authenticate with a username. You authenticate with a username and password.
Everything else in the world uses a username and password, including Windows itself. So use that.


text:
Q: How do I set the Banshee context menu to move to trash instead of delete from drive? I am using Banshee as my media player.  When I right click a track, the context menu has a 'delete from drive' option.  When I use this, it deletes the file.  I would like for the file to be sent to trash (recycle bin) instead.  Is there a way to do this, or a plugin or extension for this?

A: Unfortunately, there's currently no way to do this within Banshee. I don't know of any extensions that add this functionality -- it may be out of the scope of an extension.
It has been reported to the Banshee team, though, so if you're interested in staying up-to-date with the issue, it's tracked here: https://bugzilla.gnome.org/show_bug.cgi?id=545937


text:
Q: Error in program with structures and pointers (Structures, C++) I have a structure , which contains three variables under the object list.-Names, registration nos, amount.
struct vendor
{
   int reg, amt;
   char add[30];
}list[10];

I have made a function to find the minimum amount(amt) ,using the referencing concept.
 int low(vendor *p, int n)
   {
int i;
min = (p->amt);
for(i =1;i<n;i++)
{
    if(min > *(p->amt))
    {
        min = *(p->amt);
    }
    p++;
}
return min;
 }

In the main I have included the syntax:
 low(list, n);

I am getting an error:
Invalid argument of unary '*' operator.

I have tried using the dot operator also  and is not working.
This is my first program in pointers in structs with functions.
Can you please point out the error in the code.
Thank You very much
Anupam
(Update) the full code:
 #include <iostream>

 using namespace std;

 struct vendor
     {
     int reg, amt;
     char add[30];
     }list[10];

int low(vendor *p, int n)
     {
       int i;
       min = (p->amt);
       for(i =1;i<n;i++)
     {
       if(min > (p->amt))
       {
        min = (p->amt);
       }
         p++;
     }
      return min;
    }

 int main()
{
   int i;
   int fa;
   int n,fr;
   cin >> n;
   for(i =0;i<n;i++)
    {
       cin >>list[i].reg>>list[i].add>>list[i].amt;
      // Enter reg no. , address and amount.
       }

   low(list, n); // Calling function

    for(i = 0;i<n;i++)
    {
       if(fr == list[i].amt)
    // This is to check for position of least amount.
    // For printing the reg no. and address of least amt.
       {
          fa = i;
     }
 }

   cout << fr <<"\n" << fa <<endl;
   // print the reg no. and address of least amt.

  }

Errors:
   Overloaded function with no contextual type information.
   Invalid operands of types <unresolved overloaded function
    Cannot resolve overloaded function

A: p is a pointer to a vendor. *p is a vender. p->amt is an int.
So when you want the amt of an object that is pointed to by p you can do it in one of two ways: p->amt or (*p).amt
You fix your code by using p->amt or (*p).amt. *p->amt or *(p->amt) are invalid.

A: p is a object of vendor which type is pointer . "->" is used to use pointer object . So use p->amt .
you can also use (*p).amt .
Updated Answer :
decleration of min is missing .  please use this :
int min = p->amt ;

or use this :
int min = (*p).amt;

A: The declaration for min is missing in low() function.
int min = (p->amt);

This should help you compile your code.


text:
Q: Quiz: Convert into binary numbers, overlay arrays in JavaScript I have solved the following quiz in JavaScript, and attached the quiz and my solution below.
I did not feel right solving the problem because I knew I was missing how to recall functions!
Can anyone help me rewrite the code in a simpler way using the method of recalling functions?
or any one of the simplest ways is welcome!
QUIZ :
Given three inputs : two arrays with the same length containing decimal numbers and the number of their lengths,
convert the numbers in the two arrays into binary numbers, like so:
01001
10100
11100
10010
01011

11110
00001
10101
10001
11100

then, combine the two arrays by overlapping one over the other, making a new array having 1s from each array,
(1 overlays 0), like so:
11111
10101
11101
10011
11111

as the last step, convert this array into a format having #s-and spaces under condition of (# = 1, space = 0)
at last, you should get this as output >
[ '#####', '# # #', '### #', '#  ##', '#####' ]

MY SOLUTION:
function solution(n, arr1, arr2) {
    var convArr1 = arr1.map(function(numten) {
        return numten.toString(2);
    })
    var convArr2 = arr2.map(function(numten) {
        return numten.toString(2);
    })
    var newArr1 = convArr1.map(function(binNum) {
        if (binNum.length != n) {
            let zero = '0';
            for (let i = 1; i < n - binNum.length; i++) {
                zero = zero + 0;
            }
            binNum = zero + binNum;
            return binNum;
        } else {
            return binNum;
        }
    })
    var newArr2 = convArr2.map(function(biNum) {
        if (biNum.length != n) {
            var zero = '0';
            for (let i = 1; i < n - biNum.length; i++) {
                zero = zero + '0';
            }
            biNum = zero + biNum;
            return biNum;
        } else {
            return biNum;
        }
    })
    // console.log(newArr1, newArr2);
    var answer = ["", "", "", "", ""];
    var element = "";
    function compare(a, b) {
        for (var i = 0; i < a.length; i++) {
            if (a[i] === '1' || b[i] === '1') {
                answer[i] = answer[i] + '#';
            } else {
                answer[i] = answer[i] + ' ';
            }
        }
    }
    var compareArr = [];

    for (var i = 0; i < n; i++) {
        var numInArr1 = newArr1[i];
        var numInArr2 = newArr2[i];
        compare(numInArr1, numInArr2);
    }
    return answer;
}

console.log(solution(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28]));

A: Here is an easier solution to the problem :)

function solution(num, inputOne, inputTwo) {
  return Array(num).fill(0).map(function(un, index) {
    return (inputOne[index] | inputTwo[index]).toString(2).replace(/0/g, ' ').replace(/1/g, '#');
  });
}

console.log(solution(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28]));

A: In JavaScript, we can use bit operations on decimal numbers, then parse them back into binary via the .toString(2) function:

function solution(n, arr1, arr2) {
    return Array.from(arr1.keys())
        .map(i => {
            const num = arr1[i] | arr2[i];
            const padded = "0".repeat(n) + num.toString(2);
            const binary = padded.substr(padded.length - n);
            return binary.split("")
                .map(c => c === "0" ? " " : "#")
                .join("");
        });
}
console.log(solution(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28]));
// Out:
// ["#####", "# # #", "### #", "#  ##", "#####"]

A: What you call '1 overlays 0' is a binary operator. The | operator (pronounce 'OR')  takes the binary representations of 2 decimal numbers  and then compares each binary digit (= each bit) to produce a 1 if one of the bits or both of them is equal to 1.
You were asking about a way to 'recall' or reuse the function that was used to convert arr1 to also convert arr2. But both conversions aren't really needed. To use the | operator no conversion of the decimal numbers is necessary because that's what the computer internally uses anyway.
You can try this...
function solution (n, arr1, arr2) {

    result = arr1.map(function (element, index) {
      // take the element and the relative element of the other array
      // and use the binary OR operator
      return element | arr2[index];
    }).map(function (element) {
      // make a string of the required number of spaces ...
      // and add our binary pattern of replacements for 1's and 0's
      binary = " ".repeat(n) + element.toString(2).replace(/1/g,'#').replace(/0/g,' ');

      // truncate to return only the last n bits
      return binary.slice(-n);

    });
    return result;
}

console.log(solution(5, [9, 20, 28, 18, 11], [30, 1, 21, 17, 28]));

A lot happens to the same arr1 array. That's why I wrote the .mapcalls one right after the other. This is called method chaining. The first map method takes arr1 and then produces a new array. Of course that array also has a .map method we can call. The first map is used to combine arr1 and arr2. The second map call is used to convert the result into an array with our patterns of # and SPACE.
In the first map call our callback function takes an extra parameter:
arr1.map(function (element, index) {
      // take the element and the relative element of the other array
      // and use the binary OR operator
      return element | arr2[index];
})

We need the index number of each element that is mapped over because we need the same element inside the arr2 array.


text:
Q: Kendo Grid Datasource Update 0:N child table rows I have a requirement to update multiple tables using a Kendo grid. The grid is using a Kendo datasource to read and update remote data via service calls(OData/Entity Framework).

*

*Currently the grid can read/write data from say Table_A.

*Table_A can has a one to many relation with Table_B. I'm able to retrieve the Table_B items during read using $expand: {'Table_B'}

*On edit row item, I need to update the N items in Table_B as well. I tried updating the child items available in the model(data.Table_B.results) but I get a 413 error saying Request Entity Too Large.

So when editing a grid item, is it possible to:

*

*Update the parent and child rows in a single update?

*Or is it possible update the parent row first and then update the child rows

I have searched for examples but can't find any so far. Any ideas or examples?

A: The 2 options are both ok.
For the first one, the Batch feature is needed, that is, wrapping several requests in to one multi-part http request.
For the second, it is quite straightforward, and several requests need to be sent, for example:

*

*PUT/PATCH ~/odata/Orders(1)

*PUT/PATCH ~/odata/Orders(1)/OrderLines(1)

*PUT/PATCH ~/odata/Orders(1)/OrderLines(2)

If you just start to use OData, I recommend to start from OData v4, as from this version it became a standard of OASIS several weeks ago. Here are some samples for your reference: https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/


text:
Q: How to reorder rows in Postgresql I've got the following table

And I have to change the order of the rows in an unpredictable way for example:

*

*Set the position of the row with id = 1 after the row with id = 3 and preserve the ordering of the other rows.

*Add new row at position 3 right after row with id = 2.

*Delete row from
position 4

What is the best solution for this problem?

A: There is no solution, because table rows in PostgreSQL don't have a fixed position in the table. Every UPDATE will change the position, and every new row will be inserted wherever there happens to be enough room.
Even if there are no modifications, sequential scans of the table don't necessarily start at the beginning.
The way to order rows is to use an appropriate ORDER BY clause with SELECT.


text:
Q: node.js - GET [[hostname]]/socket.io/1/ - 404 (Not Found) Socket.io doesn't seem to be serving up its socket.io.js file with connect.
here is my server.js code:
    var app = require('http').createServer(handler),
  io = require('socket.io').listen(app),
  xml2js = require('xml2js'),
  parser = new xml2js.Parser(),
  fs = require('fs');

// creating the server ( localhost:8000 )
app.listen(8080);

// on server started we can load our client.html page

function handler(req, res) {
      console.log('liccy');

  fs.readFile(__dirname + '/', function(err, data) {
    if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}

// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
  console.log(__dirname);
  // watching the xml file
  fs.watch(__dirname + '/example.xml', function(curr, prev) {
    // on file change we can read the new xml
    fs.readFile(__dirname + '/example.xml', function(err, data) {
      if (err) throw err;
      // parsing the new xml data and converting them into json file
      parser.parseString(data);
    });
  });
  // when the parser ends the parsing we are ready to send the new data to the frontend
  parser.addListener('end', function(result) {

    // adding the time of the last update
    result.time = new Date();
    socket.volatile.emit('notification', result);
  });
});

and my html code:
    <script src="/node/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
   <script>
    // creating a new websocket
      var socket = io.connect('http://betty.dev');
      // on every message recived we print the new datas inside the #container div
      socket.on('notification', function (data) {
        $('.test').html(data.test.sample[0]);
        $('time').html('Last Update:' + data.time);
      });
    </script>

And my xml file:
   <?xml version="1.0" encoding="ISO-8859-1"?>
<test>
    <sample>Hi 1!</sample>
</test>

I'm getting this error when trying to load the page:
info  - socket.io started
   debug - client authorized
   info  - handshake authorized HPdjzW_pVy49g0bD6azs
   debug - setting request GET /socket.io/1/websocket/HPdjzW_pVy49g0bD6azs
   debug - set heartbeat interval for client HPdjzW_pVy49g0bD6azs
   debug - client authorized for
   debug - websocket writing 1::
/Users/user/webserver/betty/www/node

fs.js:1051
    throw errnoException(process._errno, 'watch');

Not sure what is the problem :/

A: here is the fix to my problem:
var app = require('http').createServer(handler),
    io = require('socket.io').listen(app),
    fs = require('fs'),
    homeFile = __dirname + '/home',
    jsonFile = __dirname + '/home/data';
app.listen(8080, 'test.dev');

function handler(req, res) {
    fs.readFile(homeFile, function(err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading home');
        }

        res.writeHead(200);
        res.end(data);
    });
}

io.sockets.on('connection', function(socket) {
    fs.watchFile(jsonFile, function (curr, prev) {
            console.log('the current mtime is: ' + curr.mtime);
            console.log('the previous mtime was: ' + prev.mtime);

        fs.readFile(jsonFile, function(err, data) {
            if (err) throw err;

            var data = JSON.parse(data);
            socket.emit('notification', data);
        });
    });
});

A: Try this URL in the browser:
<script src="/socket.io/socket.io.js"></script>

(No, this URL does not correspond to a file on disk, but that's OK. socket.io will server the browser JS correctly).
It's also not necessary or advisable to make your node_modules folder available to the browser.
Update
OK, so after you fixed the URL in your <script> tag, you now have a successful socket.io websocket connection. Yay! Now, your fs code is throwing an exception. For one thing, if you want readFile to return a string and not a buffer, you need to pass an encoding:
fs.readFile(__dirname + '/example.xml', 'utf8', function(err, data) {

Update 2
So fs.watch is throwing an exception. Probably your path to example.xml doesn't correctly match the real filesystem. You are logging __dirname. Do things match up properly? Are you sure?


text:
Q: Get the log for last 10 minutes from nginx access log I want to filter the log written in the last 10 minutes in the access.log file of Nginx on Ubuntu 16.04. I tried using the below line but only the log for that minute is filtered.
awk -v d1="$(date --date="-10 min" "+%d/%b/%Y:%H:%M")" -v d2="$(date "+%d/%b/%Y:%H:%M")" '$0 > d1 && $0 < d2 || $0 ~ d2' /usr/local/nginx/logs/access.log

This is the date format for the logs that are written:
12/Apr/2018:12:49:03
Any help would be greatly appreciated.

A: The problem is that nginx logs don't have the date at the beginning of the file:
thinking of this you get to this (mine was the 5th element on the line, notice the $4 )
sudo awk -v d1="$(date --date '-10 min' '+%d/%b/%Y:%T')" '$4 > d1' /var/log/nginx/access.log
then again the issue is having the unrelated square bracket at the beginning:
So  removing the square bracket gives you something functioning:
sudo awk -v d1="$(date --date '-10 min' '+%d/%b/%Y:%T')" '{gsub(/^[\[\t]+/, "", $4);}; $4 > d1' /var/log/nginx/access.log
I have simplified the example a bit to demonstrate the issue but you can always  add back the upper boundaries checks if you wish to.


text:
Q: iPad back to previous view terminates the application while works perfectly on iPhone I tried many ways to show navigation bar but it wont work for me. So I put Back button in secondViewController and it works perfectly for me on iPhone but terminates app on iPad.
 - (IBAction)back:(id)sender {

        [self.view endEditing:YES];
        if ([[UIDevice currentDevice]userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {

            LuanchViewController* SVC = [[LuanchViewController alloc] initWithNibName:@"LuanchViewController_iPhone" bundle:nil];
            [self presentViewController:SVC animated:YES completion:nil];
        }
        if ([[UIDevice currentDevice]userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            [self.view endEditing:YES];

            LuanchViewController* SVC = [[LuanchViewController alloc] initWithNibName:@"LuanchViewController_iPhone" bundle:nil];
            [self presentViewController:SVC animated:YES completion:nil];
        }

        [self dismissModalViewControllerAnimated:YES];
        }

Error :-
2013-10-16 18:44:42.775 iOS-test-harness[7095:c07] -[ViewController back:]: unrecognized selector sent to instance 0xa2accb0
2013-10-16 18:44:50.193 iOS-test-harness[7095:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController back:]: unrecognized selector sent to instance 0xa2accb0'
*** First throw call stack:
(0x2c18012 0x1e8ce7e 0x2ca34bd 0x2c07bbc 0x2c0794e 0x1ea0705 0xdd42c0 0xdd4258 0xe95021 0xe9557f 0xe946e8 0xe03cef 0xe03f02 0xde1d4a 0xdd3698 0x2e51df9 0x2e51ad0 0x2b8dbf5 0x2b8d962 0x2bbebb6 0x2bbdf44 0x2bbde1b 0x2e507e3 0x2e50668 0xdd0ffc 0x240d 0x2335)
libc++abi.dylib: terminate called throwing an exception

A: It seems to be that you have a Class ViewController (mostly a superclass of LuanchViewController) and it is call a method back which is not in the implementation.

A: This looks like an unwind segue action method. If you are using storyboards and you have a different storyboard for iPhone and iPad (which is the default) you probably need to make sure the iPad storyboard has the correct view controller classes set in each scene.


text: Q: Location of Amplifier for Signal Integrity Let's say I have a photodiode that outputs a current with respect to incident light on the die. If this photodiode will be located 12 inches or so away from the control board, would it be better for signal integrity to filter and amplify this signal (transimpedance amp) close to the sensor (as in a small PCB with wire harness) or does it not matter? I do know that current is more immune to noise (i.e. 4-20mA systems). To me it might make sense to locate the amp closer, since the long lead could degrade the original signal?


text:
Q: Java functional interface I am new to Java8 and I read a couple of things about this topic on the Internet. For the moment I am trying to figure out what functional interfaces are. I've found some examples, but I do not understand why the interface Skip is a functional one, since it has 2 defined methods. I hope that someone can explain me a bit. The code is:
 @FunctionalInterface
 public interface Sprint
 {
     public void sprint(Animal animal);
 }

 @FunctionalInterface
 public interface Skip extends Sprint
 {

      public default int getHopCount()
      {
         return 10;
      }

      public static void skip(int speed) {}
 }

A: Your Skip interface has only one abstract method (default and static methods don't count) - the sprint method inherited from the Sprint interface. Therefore it is a functional interface.

A: The best way to think about it is: would it make sense to express an instance of this interface as a single lambda? This is true when there is exactly one abstract method in your interface.
Sprint has the method sprint(), which is abstract. A lambda for this interface would look something like:
Sprint sprint = animal -> {
    animal.doThingOne();
    animal.doThingTwo();
}

Skip has a static method and a default method. static methods aren't anything to do with instances; this is the meaning of static in Java. Additionally, default methods don't have to be implemented in subclasses as a default implementation is already provided. This means that a lambda only has to implement the abstract method in Skip (sprint() again, inherited from Sprint) to be valid. Example:
Skip skip = Animal::doThingThree; // Equivalent to: animal -> animal.doThingThree()

As static and default methods don't have to be implemented by a lambda, you can have as many as you want and still have a functional interface.


text:
Q: Spring transaction propagation - Service vs DAO I have a Service class like below:
@Service("MyService")
public class MyService {
    @Autowired
    MyDao dao;

    public void process() {
        getFromDao();
        // getMoreFromDao();
        // process();
        // if all good, then
        doStuff();
    }

    public void getFromDao() {
        // do some stuff
        dao.getData();
    }

    @Transactional(transactionManager="simpleDatasourceTxMgr", propagation=Propagation.REQUIRED)
    public void doStuff() {
        dao.saveData(1);
        dao.saveData(2);
        dao.saveData(3);
   }
}

The DAO called is:
@Repository
public class MyDao {

    @Autowired
    @Qualifier("myjdbcTemplate")
    NamedParameterJdbcTemplate jdbcTemplate;

     public void saveData(obj a) {
        jdbcTemplate.execute("Query", ...);
    }
}

I want my doStuff() method in the service class to run within a transaction and rollback everything if there is an exception in the saveData() method. But this is not running in transaction.
If I add @Transaction to a DAO method looks like it runs in separate transaction. Is this correct?
Update: I have added a process() method to my Service and I call getFromDao() and doStuff() from process(). process() is called from the controller. So looks like if I make the service class @Transactional, then everything executes within a transaction. But I don't want getFromDao() to execute in transaction.
We use just JDBC and no Hibernate.

A:
You can place the @Transactional annotation before an interface
  definition, a method on an interface, a class definition, or a public
  method on a class. However, the mere presence of the @Transactional
  annotation is not enough to activate the transactional behavior. The
  @Transactional annotation is simply metadata that can be consumed by
  some runtime infrastructure that is @Transactional-aware and that can
  use the metadata to configure the appropriate beans with transactional
  behavior. In the preceding example, the
  element switches on the transactional behavior.

Or if you want annotations you can enable it with

It is not sufficient to tell you simply to annotate your classes with
  the @Transactional annotation, add @EnableTransactionManagement to
  your configuration, and then expect you to understand how it all
  works. This section explains the inner workings of the Spring
  Framework's declarative transaction infrastructure in the event of
  transaction-related issues.

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html


text:
Q: Converting matrix to an array in C How can I copy the elements from a matrix,entered by user,to an array? I tried this, but it didn't work:
             #include<stdio.h>
              int main(){
              int m[20][20],a[400],c=0;//max dimensions;
              scanf("%d %d",&M,&N);//dimensions of matrix;
              for(i=0;i<M;i++{
                  for(j=0;j<N;j++{
                  scanf("%d", &m[i][j]);
                      for(c=0;c<M*N;c++)
                      a[c]=m[i][j];
                   }}}

A: Don't know why you want to store both the matrix format and the array format, but anyway here is a code that should do the trick with also the data output to show the result:
#include <stdio.h>
#include <stdlib.h>

#define R 20 //max rows
#define C 20 //max columns

int main() {
    int m[R][C]; //matrix
    int a[R*C];  //array
    int r, c;    //user matrix size
    int i, j;    //iterators

    printf("insert row size: ");
    scanf("%d", &r);
    printf("insert column size: ");
    scanf("%d", &c);
    if(r > R || c > C) {
        printf("Invalid sizes");
        return -1;
    }

    for(i = 0; i < r; i++) {
        for(j = 0; j < c; j++) {
            printf("insert value for row %d column %d: ", i + 1, j + 1);
            scanf("%d", &m[i][j]);
            a[(c * i) + j] = m[i][j];
        }
    }
    for(i = 0; i < r; i++) {
        for(j = 0; j < c; j++) {
            printf("%d ", m[i][j]);
        }
        printf("\n");
    }
    for(i = 0; i < r * c; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");

    return 0;
}

Note that I also added some checks for the user data, avoiding to generate a matrix bigger that the maximum size. Also you don't need separate loops but it can be done all together.
Also please post a code that is compilable and can be run, as explained here: https://stackoverflow.com/help/how-to-ask


text:
Q: Getting ScreenRenderException while running OfBiz I am new to OfBiz.while running it in eclipse...I got the following in eclipse console...
Httpd started on port: 9989
Sessiond started on port: 9990
2014-02-04 12:57:37,538 (main) [ BeanShellContainer.java:100:INFO ] Started BeanShell telnet service on 9989, 9990
2014-02-04 12:57:37,538 (main) [ BeanShellContainer.java:101:INFO ] NOTICE: BeanShell service ports are not secure. Please protect the ports
2014-02-04 12:57:45,824 (org.ofbiz.service.jms.JmsListenerFactory@6ec213ad) [ JmsListenerFactory.java:75 :INFO ] JMS Listener Factory Thread Finished; All listeners connected.

after this I am trying to open url https://localhost:8080/webtools as mentioned in the tutorial but i am experiencing the following error message in the browser
:ERROR MESSAGE:
org.ofbiz.widget.screen.ScreenRenderException: Error rendering screen [component://common/widget/CommonScreens.xml#GlobalDecorator]: java.lang.IllegalArgumentException: Template location is empty (Template location is empty)

Help me to fix this...Thank You

A: That error usually happens when you run the ant build without any additional command and then execute the application

>ant

You can install the demo or a new installation, to install the demo run:

>ant load-demo

OR to install the new one run:

>ant run-install

if you need to clean before a new installation run:

>ant clean-all

With the information and templates loaded the application should work now, run from eclipse or with the command

startofbiz

Hope it helps
Regards


text:
Q: Getting all records from Elasticsearch using Java API I am trying to get all the records from Elasticsearch using Java API. But I receive the below error

n[[Wild Thing][localhost:9300][indices:data/read/search[phase/dfs]]];
  nested: QueryPhaseExecutionException[Result window is too large, from
  + size must be less than or equal to: [10000] but was [10101].

My code is as below
Client client;
try {
    client = TransportClient.builder().build().
            addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
    int from = 1;
    int to = 100;
    while (from <= 131881) {
        SearchResponse response = client
                .prepareSearch("demo_risk_data")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setFrom(from)
                .setQuery(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("user_agent", "")))
                .setSize(to).setExplain(true).execute().actionGet();
        if (response.getHits().getHits().length > 0) {
            for (SearchHit searchData : response.getHits().getHits()) {
                JSONObject value = new JSONObject(searchData.getSource());
                System.out.println(value.toString());
            }
        }
    }
}

Total number of records currently present are 131881 ,so I start with from = 1 and to = 100 and then get 100 records until from <= 131881. Is there are way where I can check get records in set of say 100 until there are no further records in Elasticsearch.

A: Yes, you can do so using the scroll API, which the Java client also supports.
You can do it like this:
Client client;
try {
    client = TransportClient.builder().build().
            addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

    QueryBuilder qb = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("user_agent", ""));
    SearchResponse scrollResp = client.prepareSearch("demo_risk_data")
        .addSort(SortParseElement.DOC_FIELD_NAME, SortOrder.ASC)
        .setScroll(new TimeValue(60000))
        .setQuery(qb)
        .setSize(100).execute().actionGet();

    //Scroll until no hits are returned
    while (true) {
        //Break condition: No hits are returned
        if (scrollResp.getHits().getHits().length == 0) {
            break;
        }

        // otherwise read results
        for (SearchHit hit : scrollResp.getHits().getHits()) {
            JSONObject value = new JSONObject(searchData.getSource());
            System.out.println(value.toString());
        }

        // prepare next query
        scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
    }
}


text:
Q: jQuery file upload restrict upload to one file I know this question has been asked dozens of times but I can't seem to find a solution that will work for me.
I am trying to restrict the jQuery UI version of Blueimps jQuery File Upload to one file but with no success.
I have modified the input on the form to
<input type="file" name="file">

I have changed the following options:
maxNumberOfFiles: 1
singleFileUploads: false
limitMultiFileUploads: 1

Despite the settings above the script still allows the user to add multiple files and although it displays a message saying they have exceeded the upload limit, it still uploads all of the files.
Ideally I would like the list to clear whenever a new file is added so if a second file is added it simply replaces the existing file in the list.
I have tried adding $("table tbody.files").empty(); as a call back to the add function but all this does is remove the previous file from the visible list, when the user clicks upload it still uploads all the files the user has added.


text:
Q: How to stick vertical text nav bar to right without gaps? I can't figure out a way to stick the navigation bar to right without 'gaps'. I tried different margins like 0px but it didn't work either. I'm trying to achieve this navigation interface
My HTML and CSS :

html,
body {
  height: 100%;
  margin: 0;
}

nav {
  -webkit-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  transform: rotate(90deg);
  float: right;
}

.navitem {
  float: left;
  margin-right: 20px;
}

.greeting {
  position: fixed;
  right: 0px;
  margin-right: 200px;
  background-color: #000000;
  padding: 0 10px 0 10px;
}

.greetext {
  color: #ffffff;
  line-height: 5px;
}
<!DOCTYPE html>

  <link rel="stylesheet" href="./styles/main.css" />

ahoy matey!

WORK

SKILLS

ABOUT

CONTACT

A: Try it this way - ul instead of H2's:

  <link rel="stylesheet" href="./styles/main.css" />

ahoy matey!

WORK

SKILLS

ABOUT

CONTACT

Styles:
html,
            body {
                height: 100%;
                margin: 0;

            }

            nav {

                float: right;
            }

            .navitem {
                display: block;
                margin-right: 20px;
-webkit-writing-mode: vertical-rl;
        -ms-writing-mode: tb-rl;
                writing-mode: vertical-rl;
                padding: 20px;

            }

            .greeting {
                position: fixed;
                right: 0px;
                margin-right: 200px;
                background-color: #000000;
                padding: 0 10px 0 10px;
            }

            .greetext {
                color: #ffffff;
                line-height: 5px;
            }
        }


text:
Q: React-Leaflet with Gatsby I am having troubles trying to fix that React-Leaflet / Leaflet expects window to be defined and causes the Gatsby build npm run build to fail.
Error message:
WebpackError: window is not defined

  - leaflet-src.js:230
    ~/leaflet/dist/leaflet-src.js:230:1

  - leaflet-src.js:7 version
    ~/leaflet/dist/leaflet-src.js:7:1

  - leaflet-src.js:10 Object.exports.__esModule
    ~/leaflet/dist/leaflet-src.js:10:2

  - AttributionControl.js:5 Object.<anonymous>
    ~/react-leaflet/lib/AttributionControl.js:5:1

  - index.js:26 Object.exports.__esModule
    ~/react-leaflet/lib/index.js:26:1

  - map.js:2 Object.exports.__esModule
    src/pages/map.js:2:1

The Gatsby docs lists a few possible scenarios or solutions. https://www.gatsbyjs.org/docs/debugging-html-builds/#fixing-third-party-modules
So by trying to follow the examples listed, I have tried adding in the gatsby-node.js
gatsby-node.js
exports.modifyWebpackConfig = ({ config, stage }) => {
  if (stage === 'build-html') {
    config.loader('null', {
      test: /react-leaflet/,
      loader: 'null-loader',
    })
  }
}

Both test: /leaflet/ and test: /react-leaflet/
But that spits out a WebpackError: Minified React error #130

I would really appreciate any help in getting rid of these build errors.
Thanks very much.

The steps and the code

*

*$ gatsby new leaflet

*$ cd leaflet && npm install

*Install the package and dependencies$ npm install react-leaflet leaflet react react-dom

*Created src/pages/map.js

*Copy / paste the simple example from https://github.com/PaulLeCam/react-leaflet/blob/master/example/components/simple.js
map.js
import React, { Component } from 'react'
import { Map, TileLayer, Marker, Popup } from 'react-leaflet'

export default class SimpleExample extends Component {
  state = {
    lat: 51.505,
    lng: -0.09,
    zoom: 13,
  }

  render() {
    const position = [this.state.lat, this.state.lng]
    return (
      <Map center={position} zoom={this.state.zoom}>
        <TileLayer
          attribution="&copy OpenStreetMap contributors"
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={position}>
          <Popup>
            A pretty CSS3 popup.
 Easily customizable.
          </Popup>
        </Marker>
      </Map>
    )
  }
}

A: I would use the modifyWebpackConfig code that you have. The minify error is because now that react-leaflet is an empty module, when it tries to build any page using react-leaflet components it will cause an error. You'll have to wrap your maps in a check to see if window is available. This way it will get skipped in server side rendering.
In React it would look something like this.
render() {
    if (typeof window !== 'undefined') {
        return (
            <Map {...options}>

            </Map>
        )
    }
    return null
}

A: Just a heads up to future readers as per Oct 2019 Gatsby version; API have changed a little from the OPs version.
gatsby-node.js

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === 'build-html') {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /react-leaflet|leaflet/,
            use: loaders.null(),
          },
        ],
      },
    })
  }
}

A: After upgrading gatsbyjs configuration I had to change my webpack configuration to the following:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === "build-html" || stage === "develop-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /react-leaflet|leaflet/,
            use: loaders.null(),
          }
        ]
      }
    })
  }
};

The two stages you need to modify is

*

*"build-html

*"develop-html"


text:
Q: Filter by multiple parameters on Access form I have a MS Access form that I want to filter the database based on a SQL statement.
The form will use multiple parameters, but I want it so that not all fields are required to perform the filter.
An example would be: User wants to query only by Date and Product and leave Customer and Analysis blank.
These are the fields in the form:

So far I have tried the following statements and using "LIKE" but it is returning blank results. I have only tried with two fields and it isn't working.
Public Sub Command121_Click()

Dim task As String

task = "select * from SageOrderLines_Live where [PromisedDeliveryDate] = " & Format(Me.DateFrom, "\#dd\/mm\/yyyy\#") & " AND [CustomerAccountNumber] LIKE "" & Me.CustomerAccount & """

DoCmd.ApplyFilter task

End Sub

A: Using LIKE without wildcard might as well be = sign.
Use of quote delimiters is incorrect - really need another quote on each side.
" AND [CustomerAccountNumber] LIKE """ & Me.CustomerAccount & "*"""
Or make it easier to read and use apostrophe instead of doubled quotes.
" AND [CustomerAccountNumber] LIKE '" & Me.CustomerAccount & "*'"


text:
Q: Why do i get error when i use x+ but not when +x in this code? x = 2
if x == 2:
    print x
else:
    x +

i get error like
print x +
        ^
SyntaxError: invalid syntax

A: +x calls __pos__(self) and is therefore a valid python statement; x + y is an expression that needs two operands (see binary arithmetic expressions); x + is invalid.

A: This is the unary operator +, which is like writing -x but doesn't really do anything. See this article for more information.

A: In +x, + is an operator that works on a single number, such as -x and ~x. You can refer the bottom table on  https://docs.python.org/2/reference/expressions.html.
However, in x +, + is an operator for two numbers. In your code, the second number is not provided, so you got an error.
You can check this answer
What's the purpose of the + (pos) unary operator in Python? for why we need +x in Python.


text:
Q: Display date of a given weekday based on CalendarWeek I am working on a power app that would be somekind of a weekly  TimeSheet, let`s say.
Each row is a project and each column is a day/date from the week.
The user will be able to choose a calendar week.
Based on the chosen calendar week each column should change it`s header to the dates in this week.
e.g If CW 1 2020 => First column should change to 30.12.2019, second column to 31.12.2019, etc.
Basically what I need is formula that will get the CW and the weekday num (e.g CW 1, weekday 1) and calculate the date.
Thank you!

A: Week Number
RoundDown((RoundUp(selec.SelectedDate-Date(Year(selec.SelectedDate-Weekday(selec.SelectedDate-1)+4);1;3);0)+
Weekday(Date(Year(selec.SelectedDate-Weekday(selec.SelectedDate-1)+4);1;3))+5)
/7;0)

Weekday
Weekday( Now() )


text:
Q: Unable to set gopath I have got go lang installed version 1.6.1/i386.  Using UBUNTU 16.04.
Whenever am trying to download gomobile tool using
go get golang.org/x/mobile/cmd/gomobile  it gives an error saying

cannot download: gopath not set

I have tried looking for solutions online but nothing seems to work, maybe am doing it wrong.

A: Got it to work with windows instead. If anyone else looking for how to set gopath on windows:- http://www.wadewegner.com/2014/12/easy-go-programming-setup-for-windows/


text:
Q: CakePHP External Link I have a website that has links which, if clicked, should open a new tab and load that particular website.
I've tried using this example:
<?php echo $this->Html->link('CakeBook', 'http://cakephp.org', array('class'=> 'myclass', 'target'=>'_blank')); ?>

The problem is it isn't even clickable. I'm using CakePHP 2.5.5


text:
Q: Delay Javascript Loading It is very important my page load quickly.  After loading I have a very javascript file that is not "needed" for anything until 10 seconds after page load.  How can I best load the external sheet without slowing down initial page load?
setTimeout(function(){
    //import Javascript
},500);

How would I import the javascript?
Would this even speed up page load?
Would some other technique work?
I'm not interested in analysis of whether this is "worth it."
(note: I am actually doing this in the context of a chrome extension, I don't think it will matter dramatically)

A: try this :
function loadJs(url) {
    var script = document.createElement('script');
    script.src = url;
    document.documentElement.firstChild.appendChild(script);
}

call the function  by
loadJs("your-script.js");

to load JS after a set time,
setTimeout(function(){
    loadJs("your-script.js");
},500);

you can also call it when all other components are loaded
window.onload = function() {
  loadJs("your-script.js");
}

A: Use the async attribute so that your script doesn't block the rendering of the page.
<script src="path/script.js" async></script>
And if your really don't want the script execute after the page is loaded, then you can also wrap your code in window.onload. This way the downloading of the script won't block rendering of the page and your code won't be executed until after the page loads.
https://developers.google.com/web/fundamentals/performance/critical-rendering-path/adding-interactivity-with-javascript?hl=en

EDIT:
Another alternative that would be even better (if your browser supports it) would be defer, since it actually waits until the whole DOM is loaded, instead of async which only makes the loading of the script parallelized. Therefore:
<script src="path/script.js" defer></script>

A: Just like most analytic scripts, such as that from Google, they normally go bottom of the page so it doesn't interfere with the loading of the viewable contents.  I don't think there is much to gain by timing exactly the loading vs sequencing the content/any resources loading.  This is one of the many techniques, without knowing exactly what goes on in your code.
You can look into this article, https://varvy.com/pagespeed/defer-loading-javascript.html.

A: Keep your scripts right before </body> and put all of your JavaScript in a single file.  Avoid loading several .js files.  That's it.


text:
Q: Wrong form is being displayed in a Django project I have a django project I created. This django project is split into two apps, the user and common. I have a method in the user app that allows the user to submit a form which will create a new Django user. Once the form is submitted and process I want to redirect the user to the testing page in the common app and display a html template that says testing page. Everything is working, the form is being processed and the redirect is occuring. I know this because the url changed to the expected url which will display the html testing page. For some reason, even though the url is transfering to the correct one, the html template being displayed is actually the signup form html template not the correct template.
Here is the code from the common app:
views.py
# testing method
def test(request):
    return render(request, 'common/test.html')

urls.py:
urlpatterns = [
    url(r'^test/$', views.test, name='test'),
]

test.html:
{% extends "base.html" %}

{% block standard %}

testing page

{% endblock %}

here is the redirect from the users app:
this is in the signup def after the user has been created
return redirect('test')

here is the entire signup method:
# have a user signup and create his account
def Signup(request):
    # check to see if form is submitted
    if request.method == "POST":
        # grab the form and information
        form = SignupForm(request.POST)
        # validating form
        if form.is_valid():
            # grab the form content
            cd = form.cleaned_data
            username = cd['username']
            password = cd['password']
            verify = cd['verify']
            email = cd['email']
            # check if passwords match
            if password == verify:
                # create safe passwords
                secure_password = make_password(password)
                # save username in sessions
                # request.session['username'] = username
                return redirect('test')
            else:
                # redirec to original forms
                message = "Passwords did not match"
                # users form
                form = SignupForm()
                # everything required for the template
                parameters = {
                    'message':message,
                    'form':form,
                }
                # display html template
                return render(request, 'user/Signup.html', parameters)
    else:
        # the signing up form
        form = SignupForm()
        message = "Please fill out the entire form"
        # everything that needs to be passed to html template
        parameters = {
            'form':form,
            'message':message,
        }
        # render the template
        return render(request, 'user/Signup.html', parameters)


text:
Q: Index / Aggregate formula with Search I have a sample data (1,2,3,4) on A2:D2 columns and on F1, I have (1,3), and on G1 (2,3,4).
I was suggested to use this formula
=INDEX($A2:$D2,AGGREGATE(15,6,ROW($A2:$D2)/ISNUMBER(SEARCH(TEXT($A2:$D2,"000,"),F$1&",")),1))
on F2, and G2 which is supposed to give the matching values on F2 and G2 respectively. Since both values (1,3) match, the result should be (1,3) on F2, and (2,3,4) on G2.
So basically this formula is supposed to work like index/match formula but instead of single values, it works on comma separated 2 or 3 values.
When I try to use the formula I keep getting #NUM! error. Can I get a little help to make this formula work, please?
Thanks.
Note: I am open to alternative solutions, but if it requires VBA, it has to be with a user defined formula. Without UDF, it is not useful for me.

A: A UDF should look like this
Option Explicit
Function MultFind(r As Range, s As String) As String

Dim c As Range
Dim result As String

For Each c In r
   If InStr("," & s & ",", "," & c & ",") <> 0 Then result = result & c & ","
Next c

If Len(result) > 0 Then result = Left(result, Len(result) - 1)

MultFind = result

End Function

Called as
=MultFind($A2:$D2,F1)

Edit
Here it is with optional parameter for delimiter:
Option Explicit
Function MultFind(r As Range, s As String, Optional delimiter As String = ",") As String

Dim c As Range
Dim result As String

' Check each cell in range against search string

For Each c In r
    If InStr(delimiter & s & delimiter, delimiter & c & delimiter) <> 0 Then result = result & c & delimiter
Next c

' Delimiter may be more than one character

If Len(result) > 0 Then result = Left(result, Len(result) - Len(delimiter))

MultFind = result

End Function


text:
Q: Is Running Minecraft Server on Linux (Lubuntu) Possible? I want to run Minecraft, and started with a Raspberry Pi, but now I've moved onto my dedicated file server trying to use that instead but with the same lack of success.
No matter what version of Java (openjdk version "11.0.11") I manage to get running it's never enough for the latest Minecraft server version (currently 1.17). I've run a Minecraft server on my Lubuntu machine before, but this time it's all fallen flat as no java version is good enough for it.
I just want to know if it's even possible to get it running. If it is I'll persist.

A: Sure it's possible. You did it yourself already. I have a Minecraft server chugging away right now.
From this Minecraft Server Tutorial:

*

*For Minecraft Server 1.16 and below: Install the package openjdk-8-jdk-headless

*For Minecraft Server 1.17 and above: Install the package openjdk-16-jdk-headless
Both packages are available in all currently-supported releases of Ubuntu in the Universe pocket. Most folks already have Universe enabled, so it's a simple matter of...
sudo apt install <packagename>
sudo apt install /path/to/downloaded/server.jar

...however some folks don't have Universe enabled, so two extra steps are needed.
sudo add-apt-repository universe
sudo apt update
sudo apt install <packagename>
sudo apt install /path/to/downloaded/server.jar

You asked only about Java, so the answer is only about Java.
You did not ask about other steps to setup, launch, and backup the server. If you had, I would have simply pointed you to that linked tutorial. It has everything you need.

A: It is not dependent on Linux distros, rather the Java Runtime Environment. As far as I know, Java 8 and up is enough for Minecraft servers, so it sound like configuration or installation issue rather than something with about OS or Minecraft itself.
Can you open up the terminal and run the command java <path_to_mc_server.jar>? If so, what is the output, possibly the error you get? Knowing that would be much helpful.
Edit: Most common error I see is not adding the java executable path (the install path) to the PATH environment variable. If you want it to be click-to-run, that steps more or less mandatory in Linux.
To accomplish that, you can check this link for more info.

A: So I did get this working in the end.
As someone commented, I was using the default Raspberry Pi OS to build the server, but it doesn't easily support Java 16. However, the Ubuntu build for the Raspberry Pi does support Java 16. I was so single-minded on getting the server built I couldn't see the wood for the trees.
So for anyone else who is trying to get Minecraft working on a Raspberry Pi 4, here's what I did:

*

*Using the Raspberry Pi imager select other general purpose OS, then Ubuntu.

Raspberry Pi Imager screen

*Once you've setup and configured the OS (including updates and adding to your network) run sudo apt install openjdk-16-jdk-headless

*Create a folder for Minecraft sudo mkdir Minecraft

*Go to that directory and run the following: sudo wget https://papermc.io/api/v2/projects/paper/versions/1.17/builds/31/downloads/paper-1.17-31.jar

*That will download the current version (as of 22/06/2021) of the Paper Minecraft Server. Then run sudo java -Xmx2048M -Xms2048M -jar paper-1.17-30.jar nogui
There are a few more steps once you've run that but there are better tutorials about running a Minecraft server (although not for anything that requires Java 16)
I hope that saves someone the amount of frustration the server caused me.
Cheers

A: Java matters not the OS , if the os supports java, it is possible to have a server
Use JAVA 16 for above 1.17
Use JAVA 8 for 1.16 and below


text:
Q: Can I optimize these functions? I have 3 functions (they are minimalized so they might be difficult to read) listed below - i0, t0, and is.
is() and t0() both pull data from the DOM with this line
  var c=document.forms[a].elements;

would it be better to pull the data from the DOM in i0(), and then pass it to is() and t0()?
That way I would only pull data from the DOM once, but then I would need an extra variable to store it in an pass it to the two functions.
i0():
function i0()
  {
  if(t0())
    {
    var a=is('f0');
    s0('bi0.php',a,s2);
    }
  }

t0:
function t0()
  {
  var a=document.forms['f0'].elements;
  a1="Please enter your credentials";
  a2="That email is not registered";
  a3="Incorrect credentials - Reset your password?";
  if(c0(a,a1,'fb1')&&c2(a[1],a2,'fb1')&&c3(a[2],a3,'fb1'))
    {
    return 1;
    }
  else
    {
    return 0;
    }
  }

is():
function is(a)
  {
  var b='';
  var c=document.forms[a].elements;
  for(i=0;i<c.length;i++)
    {
    if(c[i].name)
      {
      if(c[i].type=='checkbox'&&c[i].checked==false)
        {
        b+=c[i].name+"=NULL&";
        }
      else
        {
        b+=c[i].name+"="+c[i].value+"&";
        }
      }
    }
    b=b.slice(0,-1);
  return b;
  }

A: function i0(a){
    t0() && (a=is('f0'), s0('bi0.php', a, s2)); // just so I can use the comma like this
}

// or

function i0(){
    t0() && s0('bio.php', is('f0'), s2);
}

function t0(){
    var a = document.forms['f0'].elements,
       a1 = "Please enter your credentials",
       a2 = "That email is not registered",
       a3 = "Incorrect credentials - Reset your password?";

    return +( c0(a,a1,'fb1') && c2(a[1],a2,'fb1') && c3(a[2],a3,'fb1') );
}

function is(a){
    var b = '',
        c = document.forms[a].elements;

    for( var i=0, l=c.length; i<l; i++ ){
        c[i].name
            ? c[i].type == 'checkbox' && !c[i].checked && b += c[i].name + '=NULL&'
            : b += c[i].name + '=' + c[i].value + '&';
    }
    return ( b = b.slice(0, -1) );
}

to answer your actual question, yes doing a single select on document.forms['f0'].elements will make things slightly faster in some browsers, but it's a micro-optimization that I suspect will only be faster in old browsers (IE6) due to the hash-lookup.

A: You can change your for loop like this to make it faster, albeit a slight optimization
(Comparison to 0 is faster than comparing to other numbers):
for(i = c.length;i > 0;--i)
{
if(c[i].name)
  {
  if(c[i].type=='checkbox'&&c[i].checked==false)
    {
    b+=c[i].name+"=NULL&";
    }
  else
    {
    b+=c[i].name+"="+c[i].value+"&";
    }
  }
}

A: I assume you are talking about optimize in time.
Long way: Everything can be optimized.
Short way: Any optimization in this kind of code will be extremely low
Anyway, function is() is very similar to JQuery serialize call and it has been optimizated. Have you considered to use it?


text:
Q: Соединение между клиентом и сервером WPF C#.NET У меня две программы Клиент программа и Сервер программа написанные на WPF C#.NET. Сервер программа будет стоять на Dedicated Server.
1. Мне хочется понять, как мне быть если я хочу знать через одного клиента  что другой онлайн, для этого подойдет сокет TcpClient? Если да, то это нормально чтоб он постоянно был подключен вить в какойто момент я подключюсь к клиенту(клиент к клиентy) и начну передовать данные (1кб - 5кб размер, 1/1сек до 20/1сек пакетов).
2. Но скажем у меня клиентов много пускай 10к, все они будут подключены к одному TcpListener соккету? Или на каждую тысячу по TcpListener?
3. Ну и как быть если скажем если у меня несколько Dedicated Server серверов(Europe, Asia, USA) как объединить все сервера между собой.
спасибо за любую помощь.

A: *

*Клиентам нужно периодически опрашивать сервер на предмет изменений (если их много то можно использовать RabbitMq), на котором при подключении автоматом оповещаются все заинтересованные объекты. В любом случае надо подключаться к серверу чтобы узнать статус нужного клиента и его IP. TcpClient  вполне подойдет для этих целей.

*Тут однозначного ответа нет, может и один TcpListener, а может и несколько "висящих" на разных IP адресах, а может стоять балансироващик, который распределяет запросы по серверам в зависимости от их загруженности. В любом случае обычно при подключении к TcpListener, запускается отдельный поток для работы с клиентом.

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


text:
Q: How to instruct pip to install a requirement with --no-binary flag I have an app that I want to package which is dependent on protobuf. It is essential that protobuf be installed as such:
pip install protobuf --no-binary=protobuf protobuf

How can I include this inside my setup.py install_requires?
Note: My requirements mandate that this process automatically goes through setup.py.
I am aware of this and this
Thus, I've tried including such things in install_requires or requirements.txt to no luck:
#requirements.txt
protobuf
--no-binary=protobuf

How can I provide the --no-binary=protobuf protobuf (which I know are pip flags) to the installation of protobuf when I'm packaging my app?
Update:
What I want is for the protobuf package to be installed the way I mentioned when I install my package this way:
`pip install my_package.whl`

A: Install with a requirements.txt file
I guess you can simply add the flag on the same line. This worked for me:
# requirements.txt

protobuf --no-binary protobuf
pandas

With this requirements.txt, protobuf is installed without binaries, whereas pandas is still installed with .whl.
By running pip install -r requirements.txt, you will have something like:
$ pip install -r requirements.txt
Collecting pandas
  ...
Collecting protobuf
  Using cached protobuf-3.17.3.tar.gz (228 kB)
Skipping wheel build for protobuf, due to binaries being disabled for it.
Installing collected packages: protobuf, pandas
    Running setup.py install for protobuf ... done
Successfully installed pandas-1.1.5 protobuf-3.17.3

Automatic install inside a packaged library
If you want to include the dependency to protobuf with no binary, and you are packaging your library with a setup.py file, you can include package@http://link/to/package.tar.gz inside the install_requires argument of setup.
from setuptools import setup, find_packages

setup(
    name='your package`,
    version='0.1',
    packages=find_packages(),
    install_requires=[
        'click',
        'pyyaml',
        'protobuf@https://github.com/protocolbuffers/protobuf/releases/download/v3.17.3/protobuf-python-3.17.3.tar.gz'
    ]
)

This solution's drawback is that it also specifies the the version of the dependency.
Hope this helps !


text:
Q: Assign a class other than .sticky for sticky posts WordPress automatically adds a class called .sticky to posts that are marked as a sticky post. The front-end framework Foundation uses a .sticky class to make items stick to the page which presents an obvious conflict.
The ideal solution would be to modify the WordPress class. Is it possible to change the class that WordPress assigns to sticky posts to something other than .sticky?

A: Try this please and include it in your functions.php
function change_sticky_class($classes) {
  if (in_array('sticky', $classes, true)) {
    $classes = array_diff($classes, array("sticky"));
    $classes[] = 'wp-sticky';
  }
  return $classes;
}
add_filter('post_class','change_sticky_class');


text:
Q: Kotlin coroutine unit test fails with "Module with the Main dispatcher had failed to initialize" While running unit test for kotlin suspend method which uses withContext(Dispatchers.Main) the test method fails with below exception:
My coroutine lib versions are kotlinx-coroutines-core:1.1.1 and kotlinx-coroutines-android:1.1.1
Example:
suspend fun methodToTest() {
        withContext(Dispatchers.Main) {
           doSomethingOnMainThread()
                val data = withContext(Dispatchers.IO) {
                    doSomethingOnIOThread()
                }
        }
    }

Also, when I remove the withContext(Dispatchers.Main) it works fine.
java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing(MainDispatchers.kt:79)
at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.isDispatchNeeded(MainDispatchers.kt:54)
at kotlinx.coroutines.DispatchedKt.resumeCancellable(Dispatched.kt:373)
at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:25)
at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:152)
at kotlinx.coroutines.BuildersKt.withContext(Unknown Source)

A: now you can add this to your test :
Dispatchers.setMain(Dispatchers.Unconfined)

or other dispatcher.. it's experimental but it works!

A: In my case I had set the main coroutines dispatcher for unit testing and still saw some errors of that from time to time.
I've added to the build.gradle as in here:
android {
  // ...
  testOptions {
    unitTests.returnDefaultValues = true
  }
}

and I don't see that error anymore.

A: UPDATED 2023
Add the following dependency on your gradle. Documentation here
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version"

Add the following Custom TestRule as a utility for your tests
// Reusable JUnit4 TestRule to override the Main dispatcher
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(
    private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()
) : TestWatcher() {
    override fun starting(description: Description) {
        Dispatchers.setMain(testDispatcher)
    }

    override fun finished(description: Description) {
        Dispatchers.resetMain()
    }
}

In your test do the following
@get:Rule
val mainDispatcherRule = MainDispatcherRule()

OLD ANSWER
When running tests e.g for ViewModel that launch coroutines you are most likely to fall into the following exception

java.lang.IllegalStateException: Module with the Main dispatcher had
failed to initialize. For tests, Dispatchers.setMain from
kotlinx-coroutines-test module can be used

The reason behind this is the lack of Looper.getMainLooper() on the testing environment which is present on a real application. To fix this you need to swap the Main dispatcher with TestCoroutineDispatcher
Make sure you have a coroutine-test dependency on your Gradle file

"org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutine_version"

SOLUTION 1 - Not scalable
Define the following on your test class -> Annotate your class with @ExperimentalCoroutinesApi
val dispatcher = TestCoroutineDispatcher()

@Before
fun setup() {
    Dispatchers.setMain(dispatcher)
}

@After
fun tearDown() {
    Dispatchers.resetMain()
}

Note: You can also pass Dispatchers.Main as constructor dependency for your repositories as CoroutineDispatcher in case you have one. It is recommended not to hardcode your dispatchers on repositories/viewmodels etc WATCH-THIS PLEASEEEEEEEE
Why not scalable: You will need to copy and paste the same code on each test class
SOLUTION 2 - Scalable [Use This - It is used by Google]
In this solution, you create the custom rule. Add a utility class on your test package
    @ExperimentalCoroutinesApi
    class MainCoroutineRule(
        private val dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
    ) : TestWatcher(), TestCoroutineScope by TestCoroutineScope(dispatcher) {
        override fun starting(description: Description?) {
            super.starting(description)
            Dispatchers.setMain(dispatcher)
        }

        override fun finished(description: Description?) {
            super.finished(description)
            cleanupTestCoroutines()
            Dispatchers.resetMain()
        }
    }

If you want explanations on the utility class above, refer to this CODE-LAB
On your test class just add this the following lines and you will be good to go:
    @get:Rule
    val coroutineRule = MainCoroutineRule()

I think you can see why this is scalable if you have a lot of test classes.
SOLUTION 3 [I hope you don't reach here]
You can also use Dispatchers.Unconfined LINK

A coroutine dispatcher that is not confined to any specific thread. It executes the initial continuation of a coroutine in the current call-frame and lets the coroutine resume in whatever thread that is used by the corresponding suspending function, without mandating any specific threading policy. Nested coroutines launched in this dispatcher form an event-loop to avoid stack overflows.

You can add it as follows
    @Before
    fun setup() {
        Dispatchers.setMain(Dispatchers.Unconfined)
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
    }

Happy coding . . . .

A: This is thrown because Dispatcher.Main is missing. It is Android based and therefore cannot be used for unit tests. The solution lies in the documentation by the Coroutines team. Below is an example that solved my problem and is included in the documentation.
class SomeTest {

    private val mainThreadSurrogate = newSingleThreadContext("UI thread")

    @Before
    fun setUp() {
        Dispatchers.setMain(mainThreadSurrogate)
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
        mainThreadSurrogate.close()
    }

    @Test
    fun testSomeUI() = runBlocking {
        launch(Dispatchers.Main) {  // Will be launched in the mainThreadSurrogate dispatcher
            // ...
        }
    }
}

What you should note is newSingleThreadContext("UI Thread") and Dispatchers.setMain(mainThreadSurrogate) which is called before any tests in order to create a Main Dispatcher.

A: You don't have access to Dispatchers.Main in unit testing
See https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/
Dispatchers.Main Delegation part explains in detail what you need to do.

A: I got the same issue and I found the solution here kotlinx.coroutines
the solution is to use Coroutines version 1.1.0 I try it and Now it work perfectly
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.0"

A: TestCoroutineDispatcher is now deprecated. the suggested way is to use UnconfinedTestDispatcher like below
    // Reusable JUnit4 TestRule to override the Main dispatcher
@ExperimentalCoroutinesApi
class MainDispatcherRule(
    private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(),
) : TestWatcher() {
    override fun starting(description: Description) {
        Dispatchers.setMain(testDispatcher)
    }

    override fun finished(description: Description) {
        Dispatchers.resetMain()
    }
}

refer Setting the Main dispatcher