text:
Q: What's the full answer for "When did you last read a book?" I checked the thread with the similar question, but answers were simple such as two months ago, last week etc. I get the context, just find the structure of a full answer tricky. Is it possible to answer this question using a word last? What's appropriate/correct?

*

*Last (,) I read a book two days ago.

*I read a book two days ago last.

*I last read a book two days ago.

*Last time I read the book two days ago.

*I read the book two days ago last time.

A: You would use sentence 3
You could also say:
The last time I read a book was two days ago
There is no difference between these in meaning and people will use both
Technically, you could say( and might hear people say) something similar to  sentence 1:
"Last I read a book was two days ago"
This would be far less common and sounds a bit odd but would be clearly understandable.
This wording is commonly used in the phrase "Last I heard..." to mean "the lastest news I got was"
For example:
"(The) Last I heard, he was still going to enter the race"


text:
Q: Unit Testing JsonResult anonymous type in .Net Core UPdated: Solution at bottom
In .net core JsonResult does not have a "Data" property.
Many of the existing answers us that property to retrieve the needed values for unit testing.
I can't seem to wrap my head around the problem here:
        public async Task<IActionResult> GetIndividualPerformanceMetrics(string npi)
    {
        var metrics = new List<PhysicianMetric>();
        var overallRank = new OverallPhysicianRank();
        var userNPI = User.GetSingleClaimValueByType(Constants.ClaimTypes.Npi);
        npi = string.IsNullOrWhiteSpace(npi) ? userNPI : npi;
        if (npi != null)
        {

            if (await _authorizationService.AuthorizeAsync(User, "IsMetricSupportTeam")
                || User.GetAllClaimsByType(Constants.ClaimTypes.Npi).Any(n => n.Value == npi))
            {
                metrics = (await _physicianMetrics.GetAllByNPIAsync(npi)).ToList();
            }
        }
        return Json(new { metrics });
    }

And in my unit test I'm doing the following:
            _physicianMetrics.Setup(pm => pm.GetAllByNPIAsync(validNPI))
            .ReturnsAsync(new List<PhysicianMetric>(){_physicianMetric});

        var anonymousDefinition = new { metrics = new List<PhysicianMetric>() };

        //Act
        var result = await (performanceMetricsController.GetIndividualPerformanceMetrics(validNPI)) as JsonResult;
        var obj = JsonConvert.DeserializeAnonymousType(result.Value.ToString(), anonymousDefinition);
        //Assert
        Assert.AreEqual(validNPI, obj.metrics[0].NPI);

The JsonResult is returning with the mocked repository values, but I can't seem to write the test so that I can ensure the JsonResult data is the data returned by the repository query. The deserialization fails with the following error:
"Invalid character after parsing property name. Expected ':' but got: =. Path '', line 1, position 10. "
I just need to validate the JsonResult values.
Please Help.
Solution:  (Thanks Chris Pratt)
I didn't realize that the JsonResult had not yet serialized the object, and that the JsonResult.Value was the pure anonymous type.  I just used reflection to call out the list of objects that I needed and was good to go:
        var result = await (performanceMetricsController.GetIndividualPerformanceMetrics(validNPI)) as JsonResult;
        var metrics = result.Value.GetType().GetProperty("metrics")?.GetValue(result.Value, null) as List<PhysicianMetric>;

        //Assert
        _physicianMetrics.Verify(pm => pm.GetAllByNPIAsync(validNPI), Times.Once);
        Assert.AreEqual(validNPI, metrics[0]?.NPI);

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL Join with the wrong results I have a quick question regarding a JOIN.
Here is my query:
SELECT
products.name AS name,
products.last_scanned AS last_scanned,
products.last_scanned AS last_changed,

ph.price AS price,
ph.mirror_price AS mirror_price,
ph.change_date AS change_date,

ph.dioPlusZapPrice AS dioPlusZapPrice,
ph.dioPlusSitePrice AS dioPlusSitePrice,

ph.inkDepotZapPrice AS inkDepotZapPrice,
ph.inkDepotSitePrice AS inkDepotSitePrice,

ph.misradiaZapPrice AS misradiaZapPrice,
ph.misradiaSitePrice AS misradiaSitePrice,

ph.netPrintZapPrice AS netPrintZapPrice,
ph.netPrintSitePrice AS netPrintSitePrice,

img1.image_blob AS dioPlusImage,
img2.image_blob AS inkDepotImage,
img3.image_blob AS misradiaImage,
img4.image_blob AS netPrintImage

FROM
price_history ph

LEFT JOIN products ON products.productID=ph.productID

LEFT JOIN imagedata img1 ON img1.id = ph.imagename_dioPlus
LEFT JOIN imagedata img2 ON img2.id = ph.imagename_inkDepot
LEFT JOIN imagedata img3 ON img3.id = ph.imagename_misradia
LEFT JOIN imagedata img4 ON img4.id = ph.imagename_netPrint

ORDER BY ph.change_date DESC

The result of this query is:
Brother MFC-L2700DW|2015-06-26 15:47|2015-06-26 15:47|949|949|2015-06-26 15:47|949|949|969|999|0|0|0|0|[BLOB - 217.9 KiB]|[BLOB - 217.9 KiB]|NULL|NULL

which displays the same blob.
This is my imagadata table:
+----+-----------+------------+---------------------------------------+
| ID | image_blob         | ID | imagename                            |
+----+-----------+-----+----------------------------------------------+
|  1 | [BLOB - 19.5 KiB]  |  1 | a5052c6e-1120-4ece-994d-2cdac7e7baa4 |
|  2 | [BLOB - 217.9 KiB] |  2 | 1ed6f935-a44a-4f07-9c6b-fa51da5d4bdb |
|  3 | [BLOB - 217.9 KiB] |  3 | 8acced70-17ae-4a65-8466-6b910c674869 |
+----+-----------+----+-----------------------------------------------+

As you can see from the image, This is wrong since the ID is different in imagedata.

A: You have 2 rows with identical values:
2 - [BLOB - 217.9 KiB];
3 - [BLOB - 217.9 KiB];

So if row in price_history table containt such data:
imagename_dioPlus imagename_inkDepot
2                 3

it will output
[BLOB - 217.9 KiB] [BLOB - 217.9 KiB]

no matter that they have different ids. Trouble is they have same descriptions.


text:
Q: How to create / Write STDF file with python? I'm Trying to convert .txt data file to STDF (ATE Standard Test Data Format, commonly used in semiconductor tests) file.
Is there any way to do that?
Are there any libraries in Python which would help in cases like this?
Thanks!

A: You can try Semi-ATE STDF library:
It supports only ver. 4. You can use conda-forge or pypi to install it.

A: It is of course possible since Python is Turing complete.  However, you should use one of the available open source or commercial libraries to handle the STDF writing if you are not familiar with STDF. Even one mis-placed byte in the binary output will wreck your file.
It is impossible to say whether an existing tool can do this for you because a text file can have anything in it.  Your text file will need to adhere to the tool's expectations of where the necessary header data (lot id, program name, etc.), test names and numbers, part identifiers, test results and so on will be in the text file.


text:
Q: Combining graphs using Statsd & Graphite In Statsd client, how do I combine two graphs to show it as a single one?

Like this?

A: I'm just playing around with graphite and statsd right now, so I am no expert, but I might be missing something here...why would you combine it in statsd?  It seems you would want it to be combined in the Graphite UI, which will let you combine multiple stats onto a single graph.  In fact, I think you could create a graph with both of these metrics present and then save the graph to "My Graphs" to pull up later.
As far as statsd is concerned, you are just writing out two separate metrics, one being a counter called NumWarnings and another called Deployed. To get a graph like the one above, I supposed you'd need to assign an arbitrary value to Deployed as a counter for each deployment (100 seems like a good number).

A: For people discovering this later: with graphite if you drag a graph with the mouse and hold it over another one for a few seconds, a green box will appear saying "Drop to Merge". Drop the graph when that appears and it will merge the two graphs into one.


text:
Q: If $f:[0,1] \to [0,1] $ is continuous, $f(0) =0 $, $f(1) = 1$, and $f^n(x) \triangleq f \ \circ \cdots \circ f(x) \equiv x $, then $f(x) \equiv x$ If a mapping $f:[0,1] \to [0,1] $ is continuous, $f(0) =0 $, $f(1) = 1$, and $f^n(x) \triangleq f \ \circ \cdots \circ   f(x) \equiv x $, then $f(x) \equiv x$
The mapping $f$ is injective as $f(x) = f(y)$ implies $ x = f^n(x) =f^n(y) = y$. Thus $f$ is increasing.
For all $y$ in the interal $[f(0),f(1)]$, there is a unique $x_1$ such that $f(x_1) = y$. Assume that $x_1<y$; in this case $f(x_1) < f(y)$ and also $x_1 < f(x_1)$. Since $f$ is bijective, there is a unique $x_2$ such that $f(x_2) = x_1$.
We cannot have either $x_2 = x_1$ or $x_1 < x_2$. If the second case were true, then $f(x_1) < f(x_2) = x_1 < f(x_1)$.
Proceeding in this manner, we find a sequence of numbers $\{x_n\}$ such that $x_{n+1} < x_n$ and $f(x_{n+1}) = x_n$.
I wanted to use the nested interval principle but the intervals $[0,x_n]$ have not been shown to become arbitrarily small. Perhaps using a theorem on the sequence of numbers and the fact that $\{x_n\}$ has a limit.

A: Suppose by contradiction and WLOG the existence of $x_0$ such that $f(x_0)<x_0$.
As you noticed, $f$ is a bijection, and has to be strictly increasing.
Therefore, iterating yields $f^n(x_0)<f^{n-1}(x_0)$, hence $x_0<f^{n-1}(x_0)$.
Consequently,by my initial assumption, $f(x_0)<f^{n-1}(x_0)$.
Applying $f$, $f^2(x_0)<x_0$.
Applying $f$ on the latest inequality yields $f^3(x_0)<f(x_0)$.
With my initial assumption this implies $f^3(x_0)<x_0$.
This goes on (by induction) to $f^n(x_0)<x_0$.
$$\text{Contradiction}$$


text:
Q: Brackets-like Quick Edit feature for Visual Studio Code Brackets editor (and Dreamweaver too) from Adobe has a feature called Quick Edit which allows inline modification in the related pieces of code across various files without opening those files in a separate tab. Moreover, if you created a class for the tag, but did not describe it in CSS, then Quick Edit will prompt you to create a new rule with this class. This feature seems very handy and it will be nice to have in VSC as well. Whether there is such feature
in VSC?
You can see a screenshot here:
https://discourse-cdn-sjc1.com/business6/uploads/github_atom/114/9b11a0df3ac8c756.jpg

A: There is a Peek feature that looks like what you are looking for.
You can use it by pressing Alt + F12 (Option + F12 on macOS, Ctrl + Shift + F10 on Linux).
Since you need it for CSS, you need to install this plugin for Peek.


text:
Q: Cisco ASA SSL VPN options? Disclaimer: I am not a network admin so I may be wrong here but I thought asking here would help.  I'm a developer mainly on the .net framework as well as helping get a mobile intranet app working.
Because this app is only allowed to be used on our network I can easily run this app on our wireless network connection within our building.  All is fine and dandy but we'd also like to be able to run this mobile app at say a customer plant using VPN software.
I thought surely this could be easy as we exclusively use Samsung s4 phones so I thought I'd download Cisco's Samsung any connect software to allow us to VPN...its right on the play store.
Sure enough it doesn't work.  I mention it to our network admin who says not possible since we have old technology that doesn't support SSL.  He mentions we'd have to upgrade all of our hardware, the firewall, etc. to get this to work.
We really need VPN on our phones not only for this app but other internal apps, etc.
He did mention the following:
We can't upgrade the software on our ASA, because we don't have enough memory for the new version.  (the asa is very old).  We can't add more memory, so we would have to get a new firewall, which I have been told I cannot do.
In addition he also mentioned:
The Samsung AnyConnect client uses SSL to connect.  With the current (old) version of software that our firewall is running, the SSL connections are unreliable.  We need different hardware in order to upgrade our firewall, which we are unable to attain at this time.  This is the same reason that Windows 8 clients are not able to connect.
I am curious hence me asking.  vpns seem to be fairly simple to setup.  What other options do I have aside from making this a public site or web service that consumes this data over the internet as this is a complete no no.
What can we do to make this work without that much effort or cost.

A: Cisco ASA firewalls all support SSL VPN.
Depending on the edition and version of the firewall (Cisco ASA 5505, 5510, 5520, etc.), there's a limit to the number of simultaneous SSL VPN users that can connect.
Please see this Cisco licensing reference guide.

*

*Please find out which version of Cisco ASA firewall you have.

*RAM for Cisco firewalls is relatively cheap.

*If this is an ASA 5505, you'll want 512MB RAM.

*If not, a newer ASA5505 unit will be ~$500 and should have the requisite RAM for your 5-10 user needs.

*The ballpark price of the necessary licensing for an ASA 5505 is under $200 (maximum 12, I think).

*If you have an ASA 5510, you have more than enough RAM for this.

*Ballpark price for a group of Anyconnect SSL VPN licenses (250) is $250 for an ASA 5510 - L-ASA-AC-E-5510= and L-ASA-AC-M-5510=
Edit:
The barrier to entry here is low, and it's really a matter of getting assistance from someone who's familiar with this. You ASA software can be updated. I don't think there are any ASA5510 units out there that are incapable of running version 8.4 of the ASA software. Going to the newer 9.x software may require RAM modification on your specific unit, but again, the cost is low.
AnyConnect Licensing for Dummies...

A: If there is an existing Cisco non-ssl VPN, then your Samsung S4's probbaly already support it natively. It should be an IPSec Xauth PSK. You'll have to ask them for the appropriate group name and PreShared Key.
settings->WIRELESS & NETWORKS->More...->VPN->+->Type: IPSec Xauth PSK


text:
Q: How to remove border from jqplot charts It would be helpful if someone could tell me how to remove the top and right border from jqplot charts. I have tried the grid properties but it is an all or null option and individual border value cant be controlled. Is there any other property which can set the value for individual border line.

A: For bar charts and line charts, use the following options:
grid: {
   drawGridlines: false,
   background: 'transparent',
   borderColor: 'transparent',
   shadow: false
}

For Donut charts, use :
grid: {
  borderWidth:0,
  shadow:false
}


text:
Q: I'm not sure how to break out of a loop when I finish sorting linked list So what I am trying to do is to sort linked list. I'm stuck on breaking out of the loop where it seems that it never escapes. From examples I found all I had to do is to check if next value would be null, so what am I doing wrong?
Also, since I can't figure out why this won't brake out of loop, does this code seems like should do linked list sorting correctly?
    public void sortFirst() {
        do
        {
            if (first.iData >= first.next.iData)
            {
                int iTempData = first.iData;
                double dTempData = first.dData;

                first.iData = first.next.iData;
                first.dData = first.next.dData;

                Link newLink = new Link(iTempData, dTempData);
                newLink.next = first;
                first = newLink;
            }
        }
        while (first.next != null);
    }

A: Well, right off the bat, you have a logic problem in your last 3 lines:
            Link newLink = new Link(iTempData, dTempData);
            newLink.next = first;
            first = newLink;

Here, you set newLink.next = first.  Therefore it isn't null.  Next you set first = newLink.  So you can quickly see that first.next will never be null.
From what I can tell in your loop, you are not actually shifting nodes around in your list,
but only data within the nodes.  In which case, you only need to move the data around:
            int iTempData = first.iData;
            double dTempData = first.dData;

            first.iData = first.next.iData;
            first.dData = first.next.dData;

            first.next.iData = iTempData;
            first.next.dData = dTempData;

(and remove the last 3 lines which create the new node and insert it incorrectly in the list).
Of course, that is a little ugly.  The cool things with linked lists is that you can simply move the nodes around in your list, so you would do something like the following:
    current = head;
    prev = null;
    while( current != null && current.next != null ){
        next = current.next;

        if( current.iData > next.iData ) {
            // need to swap nodes
        if( prev == null ) {
            // special head case
            head = next;
            current.next = head.next;
            head.next = current;
            }
        else
        {
            prev.next = next;
            current.next = next.next;
            next.next = current;
        }
    }

    // increment pointer
    prev = current;
    current = current.next;
}


text:
Q: How can I have named entities in asciidoctor? I'm using asciidoctor with the docbook backend for books. In the past I wrote DocBook, which allows me to declare named entities that I use throughout the book:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE book [
<!ENTITY class     "Galactic TOP SECRET">
<!ENTITY project   "World Domination">
<!ENTITY product   "Illuminati Mind Control Chemtrail Spray System CSS-2020">
]>
<book ...>
     ...
     What about our &class; &project;?
     Is our &product; working?
     ...
</book>

:-)
I haven't found a way to tell asciidoctor to insert the DOCTYPE declaration between the XML processing instruction and the <book> element. So I resorted to --no-header-footer and prepending the header and footer lines. Is there a better way to do this? Something like a named entity definition directive? An include mechanism?

A: Do you have to use Docbook entity declarations? Asciidoctor has "attributes" that can serve the same purpose: https://asciidoctor.org/docs/user-manual/#attributes
For example, you can define an attribute within your document:
:class: Galactic TOP SECRET

Then later in your document, you can use the attribute:
"Billy, come up to the front and address the {class}." said the teacher.

When you transform your document to Docbook, you would see:
<simpara>"Billy, come up to the front and address the Galactic TOP SECRET."
said the teacher.</simpara>

If you do have to use Docbook entity declarations, you might use some XSL to transform the XML you get into the XML you want.


text:
Q: Select in MySQL with priority I've table data looks like this:

How do in SQL if I want to select data with limit 5 and show by priority type=image as much as 70% and type=text as much as 30%?

A: Please try this query :
(SELECT * FROM `tablename` where `type` = 'text' limit 0,2) UNION (SELECT * FROM `tablename` where `type` = 'image' limit 0,5)

It return something like this ,
+--------+-------+------------+
| id     |  type | value      |
+--------+-------+------------+
|   1    | text  | text1      |
|   2    | text  | text2      |
|   4    | image | image1.jpg |
|   5    | image | image2.jpg |
|   6    | image | image3.jpg |
|   7    | image | image4.jpg |
|   8    | image | image5.jpg |
+--------+--------------------+

A: To do this in one query will require running totals and will be fairly complex.  A nicer solution might be to do two separate queries and then aggregate the results set together using a UNION:
SELECT * FROM yourTable
WHERE type='text'
ORDER BY RAND()
LIMIT 3
UNION ALL
SELECT * FROM yourTable
WHERE type='image'
ORDER BY RAND()
LIMIT 7

I am returning 10 rows because 30% and 70% of 5 does not give a whole number.  I am also eschewing the case where there might be fewer than 3 or 7 records for types of text and image, respectively, which would throw off your desired ratio.


text:
Q: Is it possible to create a partially applied function with named parameter? This function is provided
def foo( a: String = "bar", b: Int = 1, c: String = "default" ): String

Is there a way to create a partial function String => String without specifying a and b? My approach foo( c = _: String ) does unfortunately not compile. Are there any alternatives?

A: As noted by Travis this works:
def foo( a: String = "bar", b: Int = 1, c: String = "default" ): String = s"$a$b$c"
val fooc = (c: String) => foo(c = c)
fooc("myc")
//> res0: String = bar1myc


text:
Q: Find if an artifact exists in remote repository How do I check if an artifact exists in a remote repository using gradle?
I haven't been able to find any plugins for gradle that accomplish this.
I've had an idea of creating a function in build.gradle that checks if the url of the repository exists. But this doesn't seem like the right way of doing it.
Boolean ifExists = new URL(url).openConnection().with {
        requestMethod = 'HEAD'
        connect()
        responseCode == 200
}

Any suggestions would be much appreciated.

A: Using Kotlin DSL you may check if the artifact exists in any of registered repositories in the following way:
import com.github.kittinunf.fuel.httpGet

buildscript {
    dependencies {
        "classpath"("com.github.kittinunf.fuel:fuel:2.3.1") // you may use any other HTTP-client if you want
    }
}

tasks {
    register("checkDependencies") {
        doFirst {
            project.configurations["implementation"].dependencies.forEach { dependency ->
                project.repositories.forEach { repository ->
                    val repositoryURL = (repository as MavenArtifactRepository).url
                    val artifactURL = "$repositoryURL${dependency.group?.replace('.', '/')}/${dependency.name}/${dependency.version}/${dependency.name}-${dependency.version}.jar"
                    val (_, response, _) = artifactURL.httpGet().response()
                    println("$dependency: ${response.statusCode}")
                }
            }
        }
    }
}

A: It doesn't appear there is an official Gradle plugin to support checking for an artifact's existence. However, you should be able to accomplish this by executing a curl command in a Java process:
Curl flags explanation:

-I flag for headers only.

-s for silent mode. (No prog meter or error messages)

Your command may look slightly different than the one below if you need to authenticate to the artifact resource, but I am assuming you have already accounted for that in your url:
String curlCommand= "curl -I -s " + url + " | grep HTTP";
Process process = Runtime.getRuntime().exec(curlCommand);
process.getInputStream();

If your artifact is found, the process will print "HTTP/1.1 200 OK"
Otherwise, "HTTP/1.1 404 Not Found"

A: not sure if this helps, https://github.com/ben-manes/gradle-versions-plugin. you can rewire to specify the unstable versions that you'd like to discard.
or force this by always looking at the latest versions
https://github.com/patrikerdes/gradle-use-latest-versions-plugin


text:
Q: Get Device Model in windows Phone 8.1 Runtime is there a way to retrieve friendly device model in  windows phone 8.1?
EasClientDeviceInformation a = new EasClientDeviceInformation();
 String b = a.SystemProductName; // RM-994 not lumia 1320
this Api doesn't return device friendly name.

A: No way to get a friendly name like Lumia 1320 directly from the API, you need to use https://github.com/ailon/PhoneNameResolver to convert the name from API (RM-994) to the friendly name.


text:
Q: XMPP framework error: socket closed by remote peer I am trying to connect to the ejabbered server with no SSL:
BOOL success;

if (![AppDelegate.xmppStream isConnected])
    success = [AppDelegate.xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error];

but, the server returns the error

socket closed by remote peer

In the:
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error

I tried the following:
xmppPing = [XMPPPing new];
xmppPing.respondsToQueries = YES;
[xmppPing activate:xmppStream];

Also:
xmppAutoPing = [XMPPAutoPing new];
xmppAutoPing.pingInterval = 0.5;
[xmppAutoPing activate:xmppStream];

Also:
xmppStream.keepAliveInterval = 0.5;

But the error still exists. Is it something that I missed?
Log shows that connection accepted but returns the error:

(<0.455.0>:ejabberd_listener:281) : (#Port<0.2757>) Accepted
  connection {{111,111,111,111},55012} -> {{222,222,222,222},5222}


text:
Q: Dashes vs underscores in URLs for SEO What do search engines presently prefer us to use as word separators in URLs: dashes or underscores? Should I use http://example.com/dash-underscore
or http://example.com/dash_underscore?

A: Search engines tend to treat them differently. Google likes to treat two words joined by an underscore as a single word, but dashes are considered to be seperating puntuation. Try it out yourself!
I tried search for search_engine and search-engine. The first gave me pages and urls with that exact phrase, the second was a more general search, treating the dash - like a space.

A: A lot of the blog sites nowadays build URL slugs using dashes as opposed to underscores as it is a lot easier to read so I wouldn't be surprised if search engines score dashes higher on the results than underscores.

A: Use hyphens.
I have asked several SEO consultants and they always say to use hyphens in URLs for separate words. That seems in line with practices on most commons sites I've looked at.


text:
Q: A problem on ordinal arithmetic. Let $0 < \alpha \leq \beta$ be ordinals. Could anyone advise me on how to prove there exists $\delta $ and $\xi$ such that $\xi < \alpha$ and $\alpha \ . \delta  + \xi = \beta?$(ordinal operations).
Thank you for your attention.

A: Use transfinite induction on $\beta$ to show first that $\alpha\cdot\beta\ge\beta$. This shows that there is a least $\gamma$ such that $\alpha\cdot\gamma\ge\beta$. Argue that either you have equality, or else $\gamma$ has to be a successor. In the latter case, if $\gamma=\delta+1$, we then have $\alpha\cdot\delta<\beta<\alpha\cdot\delta+\alpha$, and conclude: Consider the least $\xi$ such that $\alpha\cdot\delta+\xi\ge\beta$, and argue that we have equality, and therefore $\xi<\alpha$.
You can analyze the argument above a bit, and see that in fact we have also established uniqueness of the pair $(\delta,\xi)$.


text:
Q: How to parameterise .wsf scripts for telnet sessions? I want to automate a task for a telnet session on Windows so that I can run it multiple times using different values.
I have a .wsf script for doing that task for one time with hard coded values.
How can I parameterise the values of a .wsf script.
Is there any way for parameterizing, like using excel where I can store all the variables and pass them dynamically to the script?

A: <?xml version="1.0" ?><job><script language="VBScript">
<![CDATA[

Set a = WScript.Arguments
Dim i
i = 0
While a.length > i
    WScript.Echo WScript.Arguments(i)
    i = i + 1
Wend

]]>
</script></job>

and run it as wscript.exe myfile.wsf param1 "pa r a m 2" param3


text:
Q: fields comparison in org-tables I want to check wheather a column and a row is the same like this:
    |   | A | B | C |
    -----------------
    | A | X | 0 | 0 |
    | B | 0 | X | 0 |
    | C | 0 | 0 | X |

If I use the following formula:
    #TBLFM: @<<$<<..@>$> = if ($1==@1,X,0)
then I get the following:
    |   | A | B | C |
    -----------------
    | A | X | A = B ? X : 0 | A = C ? X : 0 |
    | B | B = A ? X : 0 | X | B = C ? X : 0 |
    | C | C = A ? X : 0 | C = B ? X : 0 | X |

Any ideas whats going wrong?

A: Your formula is comparing symbols, so A==A is always true. But the result for A==B is the whole symbolic expression.
Adding quotes to your row/column headers treats them as strings:
|   | A | B | C |
|---+---+---+---|
| A | X | 0 | 0 |
| B | 0 | X | 0 |
| C | 0 | 0 | X |
#+TBLFM: @<<$<<..@>$> = if ("$1"=="@1",X,0)


text:
Q: Notion of Present Can't I sync all watches in spacetime and call this time slice the present? In Carlo Rovelli's book he tried to explain that the notion of the present is local only, which I could not follow.

A: This is a nuanced topic, and one that is the subject of a lot of philosophical debate, much of which appears ill-informed.
The statement that 'the notion of the present is local' is analogous to the notion of horizontal being local. Within a given distance it makes sense on Earth to talk about the horizontal, but what is horizontal in an East-West direction for me in England will seem tilted by 15 degrees from the perspective of someone in New York. It is not possible to define a plane which is 'horizontal' for everyone.
Of course, the answer to the conundrum is that there is a (roughly) spherical surface of the Earth, and 'horizontal' at any given point on the surface means a tangent to the surface at that point. The disagreements only arise if you project the tangents too far.
Wherever you meet someone on the surface of the Earth you will both agree that you are together on the the same physical level. However, if one of you uses a coordinate system in which the Z direction is normal to the Earth in London, and another uses a coordinate system in which the Z direction is normal to the Earth in New York, you will attribute conflicting values of height to the point at which you are standing.
The same is true of the present. At any point in the universe, regardless of their respective frames of reference, two observers who meet will always agree that they are together in 'the present'. However, depending on their frames of reference they will have different values for the date and time of their meeting. One might say it is noon on Wednesday, and the other might says it is 10.37 on Friday, but they are just using different time coordinates to label the same event.
You cannot project a plane through a point on your time access and claim it represents the present everywhere any more than you can project a plane through your Z axis and claim it represents the horizontal everywhere.

A: In special relativity, you can pick an inertial reference frame, and then in that frame you can do essentially what you describe: place clocks all over space (not spacetime) and synchronize them all. The synchronization can be done by various equivalent methods, such as transporting clocks slowly or Einstein synchronization.
In general relativity, this doesn't work anymore for a general spacetime. It works only in a static spacetime, which is one that is not changing over time and is not rotating. In a non-static spacetime, Einstein synchronization is not transitive, so synchronizing clock A with clock B and B with C does not mean that A is synchronized with C.

A: The "present" in general relativity is a thorny topic. It's already no bouquet of roses in special relativity, but there is at least a fairly simple theorem for it.
Two events are causally related if there exists a causal curve (timelike or null) linking them. If no such curve exists, we say that these two events are synchronous. A synchronization is a foliation of our spacetime by achronal spacelike hypersurfaces (ie : we have a time function $\mathfrak{t} : M \to \mathbb{R}$ such that $\mathfrak{t}^{-1}(t) = \Sigma_t$, $\Sigma_t$ a spacelike hypersurface), for which we say that if two events evaluate to the same value under this time function, then they are synchronous.
Given some inertial observer $\gamma$, there exists, for Minkowski space, an objective way of performing a synchronization of our spacetime using only physical processes. If, for every $p_\tau \in \gamma$, such that $\gamma(\tau) = p_\tau$, our observer emits light rays in all directions (each of them labelled by time of emission and angles $\theta, \phi$), then by a theorem of Weyl, you can find a synchronization for every point. If the signal $(\tau_1, \theta, \phi)$ is reflected by another point and returns to our observer $\gamma_0$ at $\tau_2$, then we say that this point (let's call it $p_{\tau_1\tau_2\theta\phi}$) is synchronous with a point of $\gamma_0$ somewhere between $p_{\tau_1}$ and $p_{\tau_2}$. The exact point we get is given by the Reichenbach synchronization :
\begin{equation}
\tau = \tau_1 + \varepsilon(\tau_2 - \tau_1)
\end{equation}
with $\varepsilon \in (0,1)$. Those all roughly correspond to every possible spacelike straight lines crossing $\gamma_0$. In particular, the standard synchronization we usually use is the Einstein synchronization, $\varepsilon = 1/2$. This corresponds to the notion that, in this coordinate system, light is measured as $c$ (other Reichenbach conventions, light has on average the speed of light but its "coordinate speed" is faster or slower depending on how it travels). Given this, we can assign to every point of Minkowski space an angle, time, and a distance from the Synge formula :
$$\| p \| = \sqrt{(t - t_1)(t - t_2)}$$
Which basically just means that it is at a distance far enough that this distance divided by the time for the trip is the speed of light (with $c = 1$ here).
Now let's consider the case of curved spacetime. Immediately things go back, for a very wide variety of reasons.

*

*A light signal sent at local time $\tau_1$ can come back before $\tau_1$ due to bad causal behaviour.

*A future-pointing light signal may come back as a past-pointing light signal (it will come back in such a way that it seems to actually be emitted again by the original observer!)

*Two points may be separated in such a way that the return signal will never come back, due to horizons.

*If our manifold has a cut locus, two different null geodesics can end on the same point.

There are many reasons why things can go bad. Not all of them make it impossible to perform such a thing, but it is most certainly a much less trivial affair than before. I'll go over a few techniques, simplifications and mitigating factors.
First, some ground rules : we'll pick the most physically reasonable type of spacetime with respect to causality. In other words, a globally hyperbolic spacetime. This way, we know that a synchronization exists at least in principle. A globally hyperbolic spacetime is characterized by the existence of Cauchy surfaces, ie achronal spacelike hypersurfaces such that every causal curve intersects each such surfaces exactly once. This is equivalent to the previously mentioned time function $\mathfrak{t}$, and in this case we have $\mathfrak{t}^{-1}(t) = \Sigma_t$ being a Cauchy surface.
The synchronization of two points is then simply that $p$ and $q$ are synchronous if $\mathfrak{t}(p) = \mathfrak{t}(q)$. This notion is somewhat arbitrary of course : just like in special relativity, there are many different foliations of the spacetime we could do with different synchronous surfaces. This isn't much of a problem but a much bigger problem we have is that we only have an abstract definition, and not any measurable quantities here.
First let's see how the exchange of light signals work here : take our main observer $\gamma_0$ again here, with $p_1, p_2 \in \gamma_0$. A null geodesic $\ell_1$ is sent from $p_1$ to $q$, the point we wish to analyze, and $q$ sends back another one $\ell_2$ to $p_2$. If we switch the time-orientation of $\ell_1$ (so that we have a past-oriented null geodesic from $q$ to $p_1$), this means that both $p_1$ and $p_2$ are in the light cone of $q$. To be more specific, $p_1 \in J^-(q)$ and $p_2 \in J^+(q)$. Unless $q \in \gamma_0$, this means further that there is a section of $\gamma_0$ between $p_1$ and $p_2$ that is not causally related to $q$ : there exists a point between $p_1$ and $p_2$ which is simultaneous to $q$.
This is good news but not great news either. If $p_1$ and $p_2$ were to be proven to be on the boundary of $J(q)$, then we could pick any synchronization we wish, but proving that this is so may not be possible. Let's for now consider a few simpler cases, such as local synchronizations and static ones.
As is well known, in any spacetime there exists a local neighbourhood called the normal neighbourhood in which the exponential map is a homeomorphism : for any point $p$, we have a normal neighbourhood $N_p$ such that, for any point $q \in N_p$, then there exists a vector $v$ in $p$'s tangent space such that
$$q = \exp_p(v)$$
The exponential map basically states that we have a family of geodesics $\gamma_{p,v}$ starting at $p$ ($\gamma_{p,v}(0) = p$) and with initial tangent $v$ ($\dot{\gamma}(0) = v$) such that $\exp_p(v) = \gamma_{p,v}(1)$. In such a neighbourhood, two points are connected by a unique geodesic. Overall, we have the very practical fact that this neighbourhood is the image of a subset of the tangent space (ie, Minkowski space). So let's consider a causally convex (ie any causal curve between two points of $N_p$ is entirely within $N_p$) normal neighbourhood around our observer $\gamma_0$. From the exponential map we can simply directly apply the Reichenbach synchronization in the tangent space and map it to $N_p$, giving us locally a synchronization.
The issue here is fairly obvious : we typically don't know how far the exponential map extends. This could be the entire universe or a space smaller than the Planck scale for all we know, although it's commonly accepted that our spacetime is close enough to Minkowski space that we can trust such an approximation over fairly large distances.
Now let's consider something a bit more general. From before, we've seen that a synchronization always exists, and we could try to work backward from it, ie : take a time function $\mathfrak{t}$, a Cauchy surface $\Sigma_t$, an observer $\gamma_0$, and from this consider the light cone of the point $q$ on $\Sigma_t$ we're considering. Our two points of emission and reception are in $J^\pm(q)$, and we know that those points are not necessarily on the boundary of the light cone. Therefore, all we can really say about our synchronization is
$$t = t_1 + \varepsilon(x) (t_2 - t_1)$$
Our synchronization parameter could be any continuous function $\varepsilon : M \to (0,1)$.
Now to help out a bit, we'll have to consider something a bit excessive. Let's imagine now that our observer $\gamma_0$, at every instant, sends a light signal to every spacetime point, and every spacetime point reflects it back. This allows us the benefit of knowing that, for a sufficiently small neighbourhood of $\gamma_0$, we can use some manner of Einstein synchronization and work from there.
Now given a time function $\mathfrak{t}$ on $M$, this induces a foliation not only by Cauchy surfaces, but also by timelike geodesics. Let's consider our observer as one of those geodesics, and every point we synchronize as lying on one of them. Every light clock trip hitting $q$ is therefore parametrized only by its time of emission (or reflection at $q$, or reception, as those are all related) and by the position of the geodesic on the initial Cauchy surface, so that if $q \in \gamma_{y}$, where $\gamma_y(0) = y$, then we'll refer to it as the trip $\ell_{t_1, y} = \ell_1(p_1 \to q) \cup \ell_2(q \to p_2)$. There may be more than one such light trip (indeed an example using the Minkowski cylinder $\mathbb{R} \times S$ is easy to construct), but more importantly, there is a unique such shortest trip : the light trip obtained by connecting $q$ with $p_1$ and $p_2$ on the horismos $H(q)$ (the surface of the light cone) has a unique set of times $t_1$ and $t_2$ such that this is the shortest possible such trip.
So the information we have are :

*

*The time of emission $t_1$

*The time of reception $t_2$

*Angular data of the emission $\theta, \phi$

*A unique identifier of our object (this is important to make sure we found the correct shortest signal)

It can be shown that using the Einstein synchronization blindly with such data will not work. Even in Minkowski space with an accelerated observer, the coordinates generated by such a process will not be a bijection for our spacetime. What we can do though is to use all the data generated by all our observers to generate a local vector field around each observer. The time function will be such that $d\mathfrak{t}$ is normal to all the local basis defined by our synchronizations.
This is not a very realistic process, of course. We can't really fill the universe with infinitesimal observers, and having our spacetime filled with light beams coming from an infinity of sources, each encoding infinitely many data, is a bit of a stretch of the notion of "test field". But given a reasonable approximation of this process, we can define synchronizations up to some level of confidence.

A: The notion of 'the present' presupposes a notion of simultaniety and Einstein pretty much deconstructed this notion in his paper on special relativity when he promoted the constancy of the speed of light to a universal principle. This deconstruction is pushed even further when he developed his theory of General Relativity. And it is to this what Rovelli is referring to when he says the present can only be defined locally.
However, all is not lost for 'the present'. It's notorious that both QM and GR do not get along well. And Smolin in his book, Time Reborn, suggests that their different understanding of time is one of the major stumbling blocks. He suggests that QM shows that time is 'open'. And obviously the time just before time is open is the present.
It's worth recalling that Einstein had a famous debate with the then very famous French philosopher Bergson on the nature of time, which on all accounts the then even more famous physicist won. Bergson defined time through his notion of duration which he defines as:

Duration is essentially a continuation of what no longer exists into what does exist. This is real time, perceived and lived. Duration therefore implies consciousness and we place consciousness at the heart of things for the very reason that we credit them with a time that endures.


text:
Q: Copying Data from Oracle to Postgres We have a daily process that pulls all data out of a number of tables in an Oracle database and imports them into a Postgress (EnterpriseDB) database - Version 8.4.
We are currently using a java application to select * from each table, change the keywords (date, timestamp, etc) and then import them into the Postgres Database.
Are there any tools available in Postgres that would provide a more efficient manner of doing this?  I should note that there are CLOBs that are being transported over.

A: There is Ora2Pg, which is intended as a one-time-migration tool, but it might work in your case as well.  I think of it as an Oracle-to-PostgreSQL pg_dump.


text:
Q: In .NET, when implementing an implicit conversion operator, is it possible to access the object being assigned to? For example, if I have an object such as:
public class MyObject
{
    public MyObject(int initialValue)
    {
        this.InitialValue = initialValue;
        this.CurrentValue = initialValue;
    }

    public int InitialValue { get; set; }

    public int CurrentValue { get; set; }

    public static implicit operator MyObject(int someValue)
    {
        MyObject result = new MyObject(someValue);
        return result;
    }
}

Would it be possible to, in the implicit cast, keep the initial value if there was one and only update the current value?
The idea would be to do something like this:
MyObject test = 4; // Both InitialValue and CurrentValue are now 4.
test = 5; // InitialValue is 4 but CurrentValue is now 5.

It's a long shot and I don't think it would be possible but if anyone out there has any brilliant ideas to achieve this I'd appreciate it.
Thanks!

A: You can cast without making any assignment. One example of this would be when calling a function:
void SomeFunction(MyObject passedValue) { /* ... */ }

Could be called via your implicit cast like this:
SomeFunction(5);

And no assignment ever takes place.
Even when assignments do occur, remember that you assign to variables, not to objects. In a sense, the object you're asking for in this case is really the result variable.


text:
Q: Getting the next element Jquery I created a link which when the user click into, I want to alert the next element content. Below, you can see that the class "link" is the link itself. My goal is to get the content of the "book", "paper", "drinks", and "videos" class just by using the $(this) method.
This is a Link
This is a book
This is a paper
This is a book	'
This is a videos	'

I've done doing something like the code below, but it seems it couldnt reach the classes since 'a' is not of a siblings of these classes because they are wrap with  which their original parents. Is there any way to handle this?
$('a').click(function(){
               var books = $(this).siblings('.book').html();
                   var paper = $(this).siblings('.paper ').html();
                   var drinks = $(this).siblings('.drinks').html();
                   var videos= $(this).siblings('.videos').html();

                  alert(books);
            });

A: Here's an example of what I guess you're trying to do:
$('a').click(function (e) {
    var next = $(this).parent().next().html()
    //alert(next);
    console.log(next);
});

for more info: http://jsfiddle.net/juaning/7tDKZ/

A: You can just crawl up to a common ancestor like this...
$('a').click(function(){
    var books = $(this).closest("tr").find(".book").html();
});


text:
Q: PrincipalContext throwing object reference not set to instance  var path = abcdev.xyz.com:636;
 PrincipalContext context = new PrincipalContext(ContextType.Domain, path)

 Error:Object reference not set to an instance of an object.

   at System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties)
   at System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval()
   at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, ContextOptions options, String userName, String password)
   at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name)
   at Authenticate(String userName, String password) in c:~\LdapRepository.cs:line 43
   at xyz.Web.LdapController.Login(LdapViewModel model) in C:~\Controllers\LdapController.vb:line 29

The PrincipalContext is working fine for all the clients except one ..I am able to connect to the path = abcdev.xyz.com:636 using Softerra LDAP but not sure why its throwing null object reference ...I have tried abcdev.xyz.com:636/dc=xyz,dc=com -- error server cannot be connected
The url given by client -- ldaps://abcdev.xyz.com:636
The client has verified tht our IP is white Listed So not sure what different should I try for this one client.


text:
Q: Angular component opacity does not work anymore when using Bootstrap In my Angular application, I have two components, A and B, the first is a toggle button and the second is a form. B component subscribes to the state of the A component using a service in order to set its CSS according to the observed toggle state. For example, if the A component is set to state 'leftPressed', the component B reacts to this state setting its own CSS to 'enable' (through [ngStyle]) in order to make the form usable by the user, instead if the A component is set to the state 'rightPressed' the B component sets its own CSS to 'disable'. This is the code of the CSS disable style:
.disable {
  opacity: 30%;
  pointer-events: none;
}

This strategy will opacize the form and make the same form not clickable by the user.
My problem is that this thing worked until I introduced in my project Bootstrap in order to make my application more responsive (I have just placed these two buttons in the div-row-col scheme according to the Bootstrap modus operandi), but the strange thing is that only the opacity does not work on the B component but the 'mouse-event: none' worked as expected.
How can it be possibile that a CSS, in that case, is valued partially? The only thing I know is that if I roll back putting those components in my previous HTML without Bootstrap code, everything works fine.
Update with more code:
This is the code of my HTML component in which is declared more components

  <app-button-search-city-polygon-component></app-button-search-city-polygon-component>
  <app-search-city-bar [ngClass]="[cityBarStyle]"></app-search-city-bar>
  <app-clear-polygon-bar [ngClass]="[polygonBarStyle]"></app-clear-polygon-bar>
  <app-button-search-centers-or-operators></app-button-search-centers-or-operators>
  <app-validate-and-search-button></app-validate-and-search-button>

    <app-button-search-city-polygon-component></app-button-search-city-polygon-component>

    <app-search-city-bar [ngClass]="[cityBarStyle]"></app-search-city-bar>

    <app-clear-polygon-bar [ngClass]="[polygonBarStyle]"></app-clear-polygon-bar>

    <app-button-search-centers-or-operators></app-button-search-centers-or-operators>

    <app-validate-and-search-button></app-validate-and-search-button>

This is the CSS of this component:
.searchBar {
  background-color: #eeeeee;
  padding-top: 15px;
  display: flex;
  justify-content: center;
}

.cityBarDisabled {
  opacity: 30%;
  pointer-events: none;
}

.polygonBarDisabled {
  opacity: 30%;
  pointer-events: none;
}

.cityBarEnabled {

}

.polygonBarEnabled {

}

This is the TS code:
import {AfterViewInit, Component, OnInit} from '@angular/core';
import {Subscription} from 'rxjs';
import {ToggleCityPolygonService} from '../../_service/toggleCityPolygonService/toggle-city-polygon.service';

@Component({
  selector: 'app-search-bar',
  templateUrl: './search-bar.component.html',
  styleUrls: ['./search-bar.component.css']
})
export class SearchBarComponent implements OnInit {

  state = '';

  cityBarStyle = '';
  polygonBarStyle: '';

  constructor(private toggleCityPolygonService: ToggleCityPolygonService) {

  }

  ngOnInit(): void {
    this.toggleCityPolygonService.getCityPolygonStateObs().subscribe(v => {this.state = v[''];
    // console.log('i\'m gettin value: ' + v);
    if (v === 'searchByCity') {
      // @ts-ignore
      this.polygonBarStyle = 'polygonBarDisabled';
      this.cityBarStyle = 'cityBarEnabled';
    } else {
      if (v === 'searchByPolygon'){
        this.cityBarStyle = 'cityBarDisabled';
        // @ts-ignore
        this.polygonBarStyle = 'polygonBarEnabled';
      }
    }
    })
  }

}

The 'toggleCityPolygonService' is the service which holds the 'cityPolygonState' that change between two values when the user click on the relative toggle button which can assume only two states: 'searchByCity' and 'searchByPolygon'

A: Opacity takes value 0.1 - 1. Try changing opacity: 30% to opacity: 0.3;
https://www.w3schools.com/css/css_image_transparency.asp

A: This is not the issue caused by Bootstrap. It's because of css optimiser (cssnano) on production build.
To avoid this, you can use the values between 0 and 1.
In your case, you can use 0.3 instead 30%.
opacity: 0.3; // opacity: 30%;

MDN guild on opacity
Issue reported on GitHub


text:
Q: How to set stylesheet for multiple buttons but not all I'm using a .qss file to set stylesheet for QPushButton I want to give some buttons a different style than other buttons... Is there any way to do this? Maybe something like
QPushButton#thisbutton{
...
}

A: for a normal QButton you can do it like you write above:
QPushButton{ color: blue}

if you can, then extend with inheritance the button and do:
MyNewButtonClass{color: red}

or you can directly with the name of the object directly:
QPushButton#okButton { color: gray }

update:
you can ofcourse set the style of buttons without duplicating the sheet...you just do:
QPushButton#okButton, QPushButton#acceptButton, QPushButton#cancelButton
{
    color: green
}

A: In QT Designer, add a custom property and call it class:

Set the value for this:

In a CSS style sheet set formatting for this class:

That's it!


text:
Q: R function/loop: when a numeric variable falls below a value (ex. 40), how long does it take to get back above 40? I am attempting to create a reproducible/automated function in R that captures the "recovery rate" of a specific numeric variable. This variable "SNR_kHz" varies between -17 and 77 kHz, but also has a categorically related variable called "SNRLevel" with the levels "Low SNR", "Avg SNR", and "High SNR" that I created. "Low SNR" is the same as "SNR_kHz" values below 40. My data is a mixture of numeric, date-time, and categorical data with a lot of NA's due how the data was inherently collected and joined, and consists of a total of ~3000 observations with only ~300 observations that align. I have already binned the data as much as possible and removed NA's where appropriate. One important note is that there are two microphone channels that tell me what the SNR_kHz is ("F.SNRChannel" 1 and 2), and these two channels will always have differing kHz recordings. Channel 1 has shown the lowest kHz values, while Channel 2 seems more stable. I would like to treat these two channels as a single entity if possible as they are physically located right next to each other and as most discrepancies can be due to malfunctions as opposed to actual different kHz recordings. For instance, if "F.SNRChannel 1" falls below 40 kHz, I want the loop to start even if "F.SNRChannel 2" has a kHz value around 70. Below is an image of my dataset "example" and at the bottom of this post is the dput() output of the first 30 rows of my dataset.
Here is an image of the dataset and its headers
While SNR-kHz drops below 40kHzs, I want to to grab the relative humidity and temperature ("Humidmean" and "Tempmean" columns) and the date-time ("binned" column). My date-time column is in the format "2020-08-01 00:06:00." I want to "break" the loop when SNR_kHz gets back above 40 and take note of the date-time, humidity, and temperature again. Typically, when SNR_khz falls below 40, it takes numerous hours or even days to recover above 40 again. I am trying to find the average "time" it takes to do this recovery while also grabbing what the relative humidity and temperature is when the recovery happens. Then I would probably want to take the average of these relative humidity and temperature for all of the loops to infer how long it takes for SNR_khz values to recover for this particular dataset and site.
I have played around with the functions "for", "repeat", "while", "print", "for" "break" and creating new variables inside the loop for what the date-time is when the SNR values drop below 40 (e.g. "start) and what the date-time is when the SNR values are above 40 again (e.g. "end") to use "difftime(end-start)" as a function inside the loop to no avail. Here is an example of code I have tried:
repeat{

    if(example$SNRLevel=="Low SNR")
      start<-print(example$binned)
      print(example$Humidmean)

    if(example$SNRLevel!="Low SNR")
      {
      break
      end<-print(example$binned)
      }
      print(difftime(start-end, tz="America/Chicago", units="hours"))
  }

Here is the dput() output of my dataset:
>dput(example[495:535, ])
structure(list(binned = structure(c(1597578360, 1597578360, 1597579560,
1597622760, 1597623960, 1597623960, 1597625160, 1597626360, 1597627560,
1597628760, 1597629960, 1597631160, 1597632360, 1597633560, 1597634760,
1597635960, 1597637160, 1597638360, 1597639560, 1597640760, 1597641960,
1597643160, 1597644360, 1597645560, 1597646760, 1597647960, 1597649160,
1597650360, 1597651560, 1597652760, 1597653960, 1597655160, 1597656360,
1597657560, 1597658760, 1597659960, 1597661160, 1597662360, 1597663560,
1597664760, 1597664760), tzone = "America/Chicago", class = c("POSIXct",
"POSIXt")), precipsum = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0), Humidmean = c(64.3, 64.3, 66, 48.8,
53.1, 53.1, 54.05, 51.4, 55.1, 59.85, 59.6, 57.7, 56.85, 58.8,
59, 59.2, 57.8, 59.1, 59.45, 62.2, 63.5, 65, 66, 67.6, 67.75,
70.2, 70.9, 71.8, 74.6, 74.1, 76.5, 74.1, 77, 76.3, 78.3, 81.7,
90.95, 100, 100, 100, 100), Pressmean = c(980.35, 980.35, 980.5,
978.6, 978.7, 978.7, 978.6, 978.7, 978.5, 978.6, 978.6, 978.7,
978.55, 978.6, 978.7, 978.55, 978.6, 978.7, 978.85, 978.8, 979,
979.2, 979, 979, 979.2, 979.2, 979.1, 979.05, 979.2, 979.2, 978.75,
978.5, 978.4, 978.15, 978.1, 977.9, 977.7, 977.8, 977.6, 977.95,
977.95), Tempmean = c(21.6, 21.6, 21.6, 28.5, 27.9, 27.9, 27.5,
27.5, 27.3, 26.75, 26.5, 26.4, 26.35, 26, 25.7, 25.45, 25.8,
24.9, 24.7, 24.4, 24.3, 23.9, 23.6, 23.3, 23.3, 23.1, 23, 22.85,
22.3, 22.5, 21.9, 22.2, 21.7, 22.05, 22, 21.3, 20.45, 19.7, 19.3,
19.05, 19.05), F.SNRChannel = structure(c(1L, 2L, NA, NA, 1L,
2L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 1L, 2L), .Label = c("Channel 1", "Channel 2"), class = "factor"),
    SNR_40kHz = c(2, 65, NA, NA, 0, 65, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 73, 63),
    HumidLevel = c("Avg Humid", "Avg Humid", "Avg Humid", "Low Humid",
    "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid",
    "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid",
    "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid",
    "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid",
    "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid",
    "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid", "Avg Humid",
    "Avg Humid", "High Humid", "High Humid", "High Humid", "High Humid",
    "High Humid", "High Humid"), SNRLevel = c("Low SNR", "Avg SNR",
    NA, NA, "Low SNR", "Avg SNR", NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "High SNR", "Avg SNR"
    ), RainPresence = c("No rain", "No rain", "No rain", "No rain",
    "No rain", "No rain", "No rain", "No rain", "No rain", "No rain",
    "No rain", "No rain", "No rain", "No rain", "No rain", "No rain",
    "No rain", "No rain", "No rain", "No rain", "No rain", "No rain",
    "No rain", "No rain", "No rain", "No rain", "No rain", "No rain",
    "No rain", "No rain", "No rain", "No rain", "No rain", "No rain",
    "No rain", "No rain", "No rain", "No rain", "No rain", "No rain",
    "No rain")), row.names = c(NA, -41L), groups = structure(list(
    binned = structure(c(1597578360, 1597579560, 1597622760,
    1597623960, 1597625160, 1597626360, 1597627560, 1597628760,
    1597629960, 1597631160, 1597632360, 1597633560, 1597634760,
    1597635960, 1597637160, 1597638360, 1597639560, 1597640760,
    1597641960, 1597643160, 1597644360, 1597645560, 1597646760,
    1597647960, 1597649160, 1597650360, 1597651560, 1597652760,
    1597653960, 1597655160, 1597656360, 1597657560, 1597658760,
    1597659960, 1597661160, 1597662360, 1597663560, 1597664760
    ), tzone = "America/Chicago", class = c("POSIXct", "POSIXt"
    )), .rows = structure(list(1:2, 3L, 4L, 5:6, 7L, 8L, 9L,
        10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
        21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L,
        32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40:41), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), row.names = c(NA, -38L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))


text:
Q: Knp menu translations According to knp, this should be how you can easily add translations to your menu. It ain't working for me.
My menu class:
public function createMainMenuLeft(array $options)
    {
        $menuLeft = $this->factory->createItem('root', array('childrenAttributes' => array('class' => 'left')));

        $menuLeft->addChild('test', array('route' => 'test_route'))
            ->setExtra('translation_domain', 'AppBundle');

        return $menuLeft;
    }

In AppBundle/Resources/translations/messages.en.yml I have
test: nothing

However, my menu still has the label 'test' not the value from the translations file. Am I missing something here?
My locale is set in config.yml to en.

A: After some research I found the way to do it inside the documentation from the bundle, not the one from symfony. The template hast to be overwritten. Source


text:
Q: Up a Directory Script? I've been trying to create a bash script that can move up a directory. I created this script, but when ran it does not execute anything. I tried adding a print statement to it, and that does work. Is there a certain way I should be executing this?
Script:
#!/usr/bin/zsh
DIR=$1
NUM=$PWD
for ((c=1; c <= DIR; c++))
do
    echo $NUM
    cd $NUM/..
done

A: If I understand, you like to move a directory up in the directory tree.

This is a script make aliases in .bashrc Like: alias up1='cd../' alias up2='cd../../' and so on, I limit the depth 9. If you Run it multiple times the script only crate the not existing entrys. May I will able to make it delete entry if you give less depth then script would manage this alias.
Not exactly you looking for but since script running in they own instance you cannot make them affect your current shell. Also after this script create aliases you need re authenticate or open a new shell, from that point they will work till you not delete the alias entry from .bashrc.
#!/bin/sh

[[ ! $# == 1 ]] && echo "Only one parameter accepted" && exit 1
[[ $( echo $1 | grep -c ^[1-9]$ ) -eq 0 ]] && echo "parameter must be between 1 and 9" && exit 1

cdcommand=""
for (( i = 1 ; i <= $1 ; i++ )); do
        cdcommand=$(echo $cdcommand | sed 's/^/\.\.\//g')
                [[ $( cat ~/.bashrc | grep -c "alias up$i='cd $cdcommand' ") == 0 ]] &&
                echo "alias up$i='cd $cdcommand' "  >> ~/.bashrc
done


text:
Q: Unable to locate CodeIgniter model I'm trying out codeigniter for the first time on a MAMP deployment however I'm unable to load a model into a controller. The end result is always...

Unable to locate the model you have specified: second_model

Controller - welcome.php
class Welcome extends CI_Controller {

public function index()
{
    $this->load->model('second_model');
    $this->load->view('welcome_message');
}
}

Model - second_model.php
class Second_model extends Model {
public function __construct()
{
    // model constructor
    parent::__construct();
}

}

A: You should be extending CI_Model rather than Model
So:
class Second_model extends CI_Model {

    public function __construct()
    {
        // model constructor
        parent::__construct();
    }

}


text:
Q: Another limit on the fine structure constant - based on a formula by Lubos Motl This paper by Hod entitled "Gravitation, thermodynamics and the fine-structure constant" (PDF) starts from a formula on black hole resonance frequencies.  If you follow the references through, Lubos Motl has also derived this formula in L. Motl, Adv. Theor. Math. Phys. 6, 1135 (2003). Now Hod claims that the formula and the third principle of thermodynamics, taken together, imply that
$$\alpha > \frac {{\rm ln} \,3}  {48 \, \pi}$$
This is a very good limit, because it means that $\alpha > 1/137.26$ - which is very close to the real value $1/137.036$. Is Hod's argument correct?

A: The fine-structure constant cannot be derived from considerations about gravity and thermodynamics only because it's a constant determining the strength of a particular non-gravitational force, electromagnetism, which is mediated by a spin-one boson, the photon.
Quite generally, almost all expert physicists will surely agree with me that no such simple derivation of the fine-structure constant – which ignores the detailed spectrum of quantum fields we know in Nature – may exist. Also, the fine-structure constant with the value $\alpha \sim 1/137.036$ is an "accidental" outcome of some running of constants from the high scales to the low ones. You may check that 7 years later, Hod's paper has 0 citations.
He makes some assumptions that make be "morally right" but they cannot be taken literally. In particular, he assumes that the black holes have to be strictly "heavier than the Planck mass". While the lightest black holes are of order the Planck mass, the precise numerical coefficient in front of the Planck mass may be any number of order one, so no specific numerical constant on the right hand side may be correctly derived.
Moreover, I don't really believe that the statement that Hod derives is correct. He says that the dimensionless coupling can never be smaller than a number of order one. Well, I think that the string vacua with $\alpha\sim 1/150$ almost certainly exist and are logically consistent and consistent with quantum gravity, thermodynamics, and its third law. Inequalities of the form "the coupling can't be smaller than a universal constant of order one" just aren't true, so they cannot be proven.
Maybe I should mention some question about the credit. Shahar Hod's interpretations may be invalid but he is an extremely playful and prolific discoverer of various numerological formulae. So the insight that the number in the quasinormal frequencies seems to be a simple multiple of $\ln 3$ was his insight and he gave some numerical evidence it was true.
I only proved that the number was indeed precisely $\ln 3$, first in my paper based on continued fraction and then using the monodromy method in the complex plane in a paper we wrote with Andy Neitzke. The proof was mine or ours, the conjecture was his. In our paper – and in papers by many – it was also argued that the far-reaching interpretations of Shahar Hod and others, such as Olaf Dreyer who introduced the jargon of loop quantum gravity, don't work, e.g. because the predictions for other kinds of black holes are ruled out by the calculations of quasinormal modes of these other black holes.
While I said that his derivation of the inequality for the fine-structure constant isn't right, I must also say that efforts to derive similar inequalities or estimates are thriving these days and some of the similar attempts look intriguing and justified. Similar inequality "electromagnetism is stronger than something" follow from the weak gravity conjecture of ours. There are also heuristic efforts to derive the value of the fine-structure constant from the multiple critical point conjecture. Like Hod's paper, the approach based on this conjecture may say something about the low-energy values of constants, regardless of their apparent high-energy origin. It's because the multiple critical point conjecture is a new principle that says something about the phases how they should be observable at long distances.


text:
Q: Is it possible to profile my code using CoffeeScript for Node.js? I know I can profile with --prof when running node myfile.js, but what if I run coffee myfile.coffee? Let's assume I can't just compile to .js, because there are A LOT of dependences in the file.
How can I run a v8 profiler?

A: Try --nodejs PARAM. See coffee --help.

A: Looks like you can pass the --nodejs command line parameter to coffee and anything after that will get passed directly to node. Thanks to https://twitter.com/#!/oluwie who doesn't want to take credit but told me the answer


text:
Q: Print PDF using Java page not scale correctly Hi I want to print a pdf file with size 100x100 (
//this is JAVA code to make the page
PDRectangle myPageSize= new PDRectangle(100, 100);
PDPage myPage= new PDPage(myPageSize);

) but when I try to print this the page seems to have margin and not fully scaled. Below is the code to print using JAVA Print API. Also I use PDFBox library to make my PDF.
  PDFPrintable printable = new PDFPrintable(document, Scaling.STRETCH_TO_FIT);
  PrinterJob job = PrinterJob.getPrinterJob();
  job.setPrintable(printable);
  job.print();

Also I use this (printer).
I expect to fit the PDF file to whole paper size (100mm x 100mm) using my thermal printer.


text:
Q: How to take screenshot at the point where test fail in Espresso? I am looking for a way to take a screenshot of device after test failed and before get closed.

A: @Maragues answer ported to Kotlin:
Helper classes:
package utils

import android.graphics.Bitmap
import android.os.Environment.DIRECTORY_PICTURES
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.runner.screenshot.BasicScreenCaptureProcessor
import androidx.test.runner.screenshot.ScreenCaptureProcessor
import androidx.test.runner.screenshot.Screenshot
import org.junit.rules.TestWatcher
import org.junit.runner.Description
import java.io.File
import java.io.IOException

class IDTScreenCaptureProcessor : BasicScreenCaptureProcessor() {
    init {
        mTag = "IDTScreenCaptureProcessor"
        mFileNameDelimiter = "-"
        mDefaultFilenamePrefix = "Giorgos"
        mDefaultScreenshotPath = getNewFilename()
    }

    private fun getNewFilename(): File? {
        val context = getInstrumentation().getTargetContext().getApplicationContext()
        return context.getExternalFilesDir(DIRECTORY_PICTURES)
    }
}

class ScreenshotTestRule : TestWatcher() {
    override fun finished(description: Description?) {
        super.finished(description)

        val className = description?.testClass?.simpleName ?: "NullClassname"
        val methodName = description?.methodName ?: "NullMethodName"
        val filename = "$className - $methodName"

        val capture = Screenshot.capture()
        capture.name = filename
        capture.format = Bitmap.CompressFormat.PNG

        val processors = HashSet<ScreenCaptureProcessor>()
        processors.add(IDTScreenCaptureProcessor())

        try {
            capture.process(processors)
        } catch (ioException: IOException) {
            ioException.printStackTrace()
        }
    }
}

Usage:
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import utils.ScreenshotTestRule

@RunWith(AndroidJUnit4::class)
@LargeTest
class DialogActivityTest {

    @get:Rule
    val activityRule = ActivityTestRule(DialogActivity::class.java)

    @get:Rule
    val screenshotTestRule = ScreenshotTestRule()

    @Test
    fun dialogLaunch_withTitleAndBody_displaysDialog() {
        // setup
        val title = "title"
        val body = "body"

        // assert
        onView(withText(title)).check(matches(isCompletelyDisplayed()))
        onView(withText(body)).check(matches(isCompletelyDisplayed()))
    }

}

Libraries declared in app's build.gradle:
androidTestImplementation "androidx.test.espresso:espresso-core:3.1.1"
androidTestImplementation "androidx.test.espresso:espresso-intents:3.1.1"
androidTestImplementation "androidx.test.ext:junit:1.1.0"
androidTestImplementation "androidx.test:runner:1.1.1"
androidTestImplementation "androidx.test:rules:1.1.1"

This setup saves a screenshot every time a test finished in the folder: /sdcard/Android/data/your.package.name/files/Pictures
Navigate there via Android Studio's Device File Explorer (on the right sidebar)
If you like to save screenshots only for failed tests, override the failed method of TestWatcher instead of the finished

A: Writing a custom TestWatcher like the other answers explained is the way to go.
BUT (and it took us a long time to notice it) there is a caveat: The rule might fire too late, i.e. after your activity was already destroyed. This leaves you with a screenshot of the device's home screen and not from the failing activity.
You can solve this using RuleChain: Instead of writing
@Rule
public final ActivityTestRule<MainActivity> _activityRule = new ActivityTestRule<>(MainActivity.class);

@Rule
public ScreenshotTestWatcher _screenshotWatcher = new ScreenshotTestWatcher();

You have to write:
private final ActivityTestRule<MainActivity> _activityRule = new ActivityTestRule<>(MainActivity.class);

@Rule
public final TestRule activityAndScreenshotRule = RuleChain
        .outerRule(_activityRule)
        .around(new ScreenshotTestWatcher());

This makes sure that the screenshot is taken first and then the activity is destroyed

A: Easiest way that I found:
@Rule
public TestRule watcher = new TestWatcher() {
  @Override
  protected void failed(Throwable e, Description description) {
    // Save to external storage (usually /sdcard/screenshots)
    File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
        + "/screenshots/" + getTargetContext().getPackageName());
    if (!path.exists()) {
      path.mkdirs();
    }

    // Take advantage of UiAutomator screenshot method
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    String filename = description.getClassName() + "-" + description.getMethodName() + ".png";
    device.takeScreenshot(new File(path, filename));
  }
};

A: Another improvement to previous answers. I'm using the experimental Screenshot API
public class ScreenshotTestRule extends TestWatcher {

  @Override
  protected void failed(Throwable e, Description description) {
    super.failed(e, description);

    takeScreenshot(description);
  }

  private void takeScreenshot(Description description) {
    String filename = description.getTestClass().getSimpleName() + "-" + description.getMethodName();

    ScreenCapture capture = Screenshot.capture();
    capture.setName(filename);
    capture.setFormat(CompressFormat.PNG);

    HashSet<ScreenCaptureProcessor> processors = new HashSet<>();
    processors.add(new CustomScreenCaptureProcessor());

    try {
      capture.process(processors);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

I've created CustomScreenCaptureProcessor because BasicScreenCaptureProcessor uses /sdcard/Pictures/ folder and I encountered IOExceptions on some devices when creating the folder/image. Please note that you need to place your processor in the same package
package android.support.test.runner.screenshot;

public class CustomScreenCaptureProcessor extends BasicScreenCaptureProcessor {
  public CustomScreenCaptureProcessor() {
    super(
        new File(
            InstrumentationRegistry.getTargetContext().getExternalFilesDir(DIRECTORY_PICTURES),
            "espresso_screenshots"
        )
    );
  }
}

Then, in your base Espresso test class just add
@Rule
public ScreenshotTestRule screenshotTestRule = new ScreenshotTestRule();

If you wish to use some protected folder, this did the trick on an emulator, tho it didn't work on a physical device
@Rule
public RuleChain screenshotRule = RuleChain
      .outerRule(GrantPermissionRule.grant(permission.WRITE_EXTERNAL_STORAGE))
      .around(new ScreenshotTestRule());

A: I made some improvements on this answer. No need to add an extra dependency for UiAutomator and it also works below api level 18.
public class ScreenshotTestWatcher extends TestWatcher
{
   private static Activity currentActivity;

   @Override
   protected void failed(Throwable e, Description description)
   {
      Bitmap bitmap;

      if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
      {
         bitmap = getInstrumentation().getUiAutomation().takeScreenshot();
      }
      else
      {
         // only in-app view-elements are visible.
         bitmap = Screenshot.capture(getCurrentActivity()).getBitmap();
      }

      // Save to external storage '/storage/emulated/0/Android/data/[package name app]/cache/screenshots/'.
      File folder = new File(getTargetContext().getExternalCacheDir().getAbsolutePath() + "/screenshots/");
      if (!folder.exists())
      {
         folder.mkdirs();
      }

      storeBitmap(bitmap, folder.getPath() + "/" + getFileName(description));
   }

   private String getFileName(Description description)
   {
      String className = description.getClassName();
      String methodName = description.getMethodName();
      String dateTime = Calendar.getInstance().getTime().toString();

      return className + "-" + methodName + "-" + dateTime + ".png";
   }

   private void storeBitmap(Bitmap bitmap, String path)
   {
      BufferedOutputStream out = null;
      try
      {
         out = new BufferedOutputStream(new FileOutputStream(path));
         bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
      }
      catch (IOException e)
      {
         e.printStackTrace();
      }
      finally
      {
         if (out != null)
         {
            try
            {
               out.close();
            }
            catch (IOException e)
            {
               e.printStackTrace();
            }
         }
      }
   }

   private static Activity getCurrentActivity()
   {
      getInstrumentation().runOnMainSync(new Runnable()
         {
            public void run()
            {
               Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(
                     RESUMED);
               if (resumedActivities.iterator().hasNext())
               {
                  currentActivity = (Activity) resumedActivities.iterator().next();
               }
            }
         });

      return currentActivity;
   }
}

Then include the following line in your test class:
@Rule
public TestRule watcher = new ScreenshotTestWatcher();

A: A compilation of the other suggestions, comments and some of my own. I was having issues with the screenshot not being taken within the TestWatcher failed function. Instead using a custom FailureHandler, since it was only mentioned and no example provided, here goes...
class ScreenshotRule : TestWatcher() {

    override fun starting(description: Description) {
        super.starting(description)
        setFailureHandler(
            CustomFailureHandler(getInstrumentation().targetContext, description)
        )
    }
}

class CustomFailureHandler(targetContext: Context, description: Description) : FailureHandler {

    private val delegate: FailureHandler
    private val device = UiDevice.getInstance(getInstrumentation())
    private val directory = "/sdcard/Pictures/screenshots/failures"
    private val testClassName = description.className
    private val testMethodName = description.methodName

    init {
        delegate = DefaultFailureHandler(targetContext)
    }

    override fun handle(error: Throwable, viewMatcher: Matcher<View>) {
        val snapshot = File("$directory/$testClassName", "$testMethodName.png")
        snapshot.parentFile!!.mkdirs()
        device.takeScreenshot(snapshot)

        delegate.handle(error, viewMatcher)
    }
}

I have this Rule ordered after my 'GrantPermissionRule' and 'activityScenarioRule'
Also couldn't trust the Environment dirs Environment.getExternalStorageDirectory() or targetContext.getExternalFilesDir(Environment.DIRECTORY_SCREENSHOTS) so just providing my own to the sdcard/Pictures/screenshots.
Maybe someone can help improve the use of MediaStore...


text:
Q: Cant get offset of div this is my getoffset js code to get div width and left
  var objRedPacketDivStyle = document.getElementById("styRedPacketAppear");
        var objOffset = objRedPacketDivStyle.offset();
        var intWidth = objOffset.offsetWidth;
        var objWidthStart = objOffset.offset.left;
        var objWidthEnd = objWidthStart + intWidth;
        alert(objWidthStart + objWidthEnd);

and here is my div and css

#styRedPacketAppear {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 98;
pointer-events: none;
}

A: This isn't working as .offset() is a jQuery method. Since you don't have jquery you need to use vanilla javascript to achieve this.
You can use:

*

*element.offsetWidth: "returns the layout width of an element as an integer." - MDN

*element.offsetLeft: "returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node." - MDN
Using these two properties will resolve your issue:

var objRedPacketDivStyle = document.getElementById("styRedPacketAppear");
// Remove this: var objOffset = objRedPacketDivStyle.position.offset();
var intWidth = objRedPacketDivStyle.offsetWidth;
var objWidthStart = objRedPacketDivStyle.offsetLeft;
var objWidthEnd = objWidthStart + intWidth;
alert(objWidthStart + objWidthEnd);
#styRedPacketAppear {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 98;
  pointer-events: none;
}

A: The offsetTop property returns the top position (in pixels) relative to the top of the offsetParent element.
The returned value includes:
-the top position, and margin of the element
-the top padding, scrollbar and border of the offsetParent element.

#test {
  top: 100px;
  margin: 10px;
  padding: 10px;
  width: 300px;
  position: fixed;
  border: 5px solid black
}

var testDiv = document.getElementById("test");
document.getElementById("demo").innerHTML = testDiv.offsetTop;

Result-offsetTop is: 110


text:
Q: How to change the config file location of a virtual directory? I need to publish my web application like below
1.root application(http://test.smt.com)
2.virtual directory(http://test.smt.com/console)
my root application contains virtual dir
Root

  Folder 1(with 1.config)
  Folder 2(with 2.config)
  Folder 3(with 3.config)
  Folder 4(with 4.config) // I've created this directory as virtual dir

root.config

Now the issue i'm getting is "Parser error"
I know that Root application access root.config also the virtual dir access 4.config
can we change the virtual directory to access its root.config only not 4.config?

A: finally i found a soln
need not to create a separate virtual dir in IIS.
I just entered http://test.smt.com/Folder4 (Folder 4 which is named as console dir)
it works for me... i'm happy....


text:
Q: Get the RGB value of a specific pixel live How would I be able to get the RGB value of a pixel on my screen live with python? I have tried using
from PIL import ImageGrab as ig
while(True):
    screen = ig.grab()
    g = (screen.getpixel((358, 402)))
    print(g)

to get the value but there is noticeable lag.
Is there another way to do this without screen capturing? Because I think this is the cause of lag.
Is there a way to drastically speed up this process?
is it possible to constrain the ig.grab() to 358, 402 and get the values from there?

A: You will probably find it faster to use mss, which is specifically designed to provide high speed screenshot capabilities in Python, and can be used like so:
import mss

with mss.mss() as sct:
    pic = sct.grab({'mon':1, 'top':358, 'left':402, 'width':1, 'height':1})
    g = pic.pixel(0,0)

See the mss documentation for more information. The most important thing is that you want to avoid repeatedly doing with mss.mss() as sct but rather re-use a single object.

A: The following change will speed up it by 15%
pixel = (358, 402)
pixel_boundary = (pixel + (pixel[0]+1, pixel[1]+1))
g = ig.grab(pixel_boundary)
return g.getpixel((0,0))

Runtime:

*

*proposed: 383 ms ± 5.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

*original: 450 ms ± 5.31 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


text:
Q: Conditional Join in Hibernate Here is what I am doing:
Their is table MEDIA against this their are multiple entries in MEDIA_TAGS table. So based on some user input for media tags I have to fetch the MEDIA table records. So here I have to join the tables MEDIA and MEDIA_TAGS only when their is input for the media tags.
Since it is legacy system I cant modify the existing mapping in hbm file.
I wanted to know if their is any functionality in Hibernate to add the join on some another table based on certain condition or dynamic input.
Does this possible with predefined filters or is their any way to achieve this in hibernate mapping.  Any pointers on this greatly help me.

A: I used hibernate criteria.createAlias(.. to solve this problem.


text:
Q: Laplace transform and Fourier transform of kernel Suppose $p_t(x)=\frac1{\sqrt{2\pi t}}e^{-\frac{x^2}{2t}}$ is the Gaussian density. $p_t(x)$ is also the Green kernel of the heat equation in 1D: $(\partial_t-\frac12\Delta)u=0$. The Fourier transform of $p_t(x)$ is $\hat p_t(\xi)=e^{-\frac{t}2|\xi|^2}$. Then the Laplace transform at 1 has the special bound
$$\int_0^\infty e^{-t}|\hat p_t(\xi)|^2dt=\int_0^\infty e^{-t}e^{-t|\xi|^2}dt\lesssim \frac1{1+|\xi|^2}. $$
In this bound, we see that this integration decay as $|\xi|^{-2}$ when $|\xi|\to\infty$. Note also that the Laplace transform is closely related to resolvent of the operator $\Delta$.
Suppose now that we replace $\Delta$ by a "nice" (symmetric) operator $A$ with symbol $\psi(\xi)$. What are the characteristics of $A$ so that we have a similar bound
$$\int_0^\infty e^{-\lambda t}|e^{-t\psi(\xi)}|^2dt\lesssim \frac1{1+|\xi|^a} $$
for some $\lambda>0$ and $a>0$. Is there a method to identify the decay rate $a$?
PS: I know this is probably well known in semigroup theory, but I couldn't find any exact reference.


text:
Q: Subquery returns more than one row error when one row is returned I am currently doing some SQL magic and wanted to update the stock in my companies ERP program. However if I try to run the following query I get the error mentioned in the title.
update llx_product lp
set stock = (select sum(ps.reel)
             from llx_product_stock as ps, llx_entrepot as w
             where w.entity IN (1)
               and w.rowid = ps.fk_entrepot
               and ps.fk_product = lp.rowid
             group by ps.rowid)

The subquery by itself returns just one row if used with a rowid for the product.
select sum(ps.reel)
from llx_product_stock as ps, llx_entrepot as w
where w.entity in (1)
  and w.rowid = ps.fk_entrepot
  and ps.fk_product = 7372
group by ps.rowid

Any help would be appreciated

A: I would suggest writing the query as:
update llx_product lp
    set stock = (select sum(ps.reel)
                 from llx_product_stock ps join
                      llx_entrepot w
                      on ps.fk_product = lp.rowid
                 where w.entity in (1) and
                       w.rowid = ps.fk_entrepot
                );

An aggregation query with no group by cannot return more than one row.  It is unclear how your version is returning more than one row because the key used in the group by also has an equality comparison.  Perhaps there is some type conversion issue at play.
But in any case, without the group by, you cannot get the error you are currently getting.

A: For anyone wondering the solution to my issue was a very simple query, Gordon pointed in the right direction and I made it harder than it should be.
update llx_product lp
left join llx_product_stock ps on lp.rowid = ps.fk_product
set lp.stock = ps.reel


text:
Q: How do I make an output file for the "time" command? I'm sorry if this seems like a trivial question as I'm very new to linux.
Anyway, I need to record the time for executing a shell script I made.
time ./executable_file <input_here> > time_elapsed.txt

But obviously this only gets the output of the script I made. Any way on how to do this?
update: So what I did was do the GNU version to get an output file for it. It worked now.


text:
Q: Opengl - Compiling shaders on a different thread For opening a thread I am using SDL2 and for opengl I am using glew.
In my program, I have a thread in which I load and initialize all my resources. After doing a bit of research online I learned that a GLContext is only viable for the thread it was created on.
I could create another GLContext on my second thread, but then I won't have access to all the compiled shaders on my first thread.
Any ideas?


text:
Q: Why do I have a filled HttpContext when COnfigureAwait(false) is used? First of all, I've seen this question: ConfigureAwait(false) not making HttpContext NULL as expected but I still can't explain what's happening.
Here I have two methods:
public async Task<ActionResult> Contact2()
{
    var h = new HttpClient();
    var sc = SynchronizationContext.Current;
    HttpContext.Session["x"] = "d";

    var s = await h.GetStringAsync("http://www.google.com").ConfigureAwait(false);

    var contextIsNull = HttpContext == null;
    return View();
}

public async Task<ActionResult> Contact()
{
    var h = new HttpClient();
    var sc = SynchronizationContext.Current;
    HttpContext.Session["x"] = "d";

    await Task.Delay(2000).ConfigureAwait(false);

    var contextIsNull = HttpContext == null;

    return View();
}

When executing both of them the SynchronizationContext.Current is null as expected, but HttpContext is not null and in both situations I have access to Session. Why is this? Why isn't HttpContext not null? The context has been switched because I read HttpContext after await, right?

A: HttpContext.Current is null, not Controller.HttpContext.
await doesn't change the values of any of your local or member variables.
Note that just because you can access it doesn't mean you should. HttpContext is not threadsafe.


text:
Q: How can I make windows go fullscreen when snapping to the top of the screen in xfce? You know how in unity when you grab a window and snap it to the top of the screen it will go fullscreen? Im currently using xubuntu but when I snap the window to the top it will just fill the top half of the screen. I wanna know if there is a way in xfce to make windows go full screen when snaping to the top while still keeping that "mosaic" snap just in the sides.
Thanks.

A: In xfce you have to double click on the top to get fullscreen.
Yet I don't know about settings to change the snapping to going fullscreen.
Any setting are at Settings Manager -> Window Manager -> Advanced or Settings Manager -> Window Manager Tweaks


text:
Q: What exactly do these integral functions mean? $$F(x) = \int{f(x)}\,dx$$
$$G(x) = \int_0^x{g(z)}\,dz$$
I am confused about the exact meaning about these functions.  The second function is clear to me, $G(x)$ is just the area under the graph of $g(x)$ from $0$ to some $x$.  But the first function is not so clear.
Also, why is the following considered incorrect?
$$H(x) = \int_0^x{g(x)}\,dx$$

A: These are good questions.
The notation $\displaystyle \int f(x) dx$ is shorthand for "an antiderivative of $f(x)$." That is, a function with the property that $F'(x) = f(x)$. Part of the depth of the fundamental theorem of calculus is that antiderivatives are also ways to calculate the area under a curve. This is remarkable - why should they be related?
The last piece you wrote, $H(x) = \displaystyle \int_0^x g(x) dx$ is terrible notation, and should not be written in front of a non-expert crowd (experts can take in notational abuse much easier than neophytes). It it far more correct to write
$$
H(x) = \int_0^x g(t) dt
$$
to not confuse dummy variables and the actual variable.

A: $$
H(x) = \int_0^x{g(x)}\,dx
$$
is not incorrect (just confusing for unexperienced students).  This function $H$ is an antiderivative of $g$; that is $H'=g$.  But usually we write $G'=g$ and $F'=f$ since it is easier to remember what is what.
Formula
$$
F(x) = \int{f(x)}\,dx
$$
is known as an indefinite integral and means $F'=f$.


text:
Q: How to split div element into multiple rows and columns in css? I have 4 images into a div, how to split them in 2 columns of 2 images in CSS?

Thanks

A: You can use CSS Grid and set the set the columns to repeat twice with a size that matches the dimensions of the images.

#your-cards { display: grid; grid-template-columns: repeat(2, 50px); gap: 0.5em; }

A: You could use css flex properties to do this:

#your-cards {
  display: flex;
  flex-wrap: wrap;
  padding-left: 0;
}

#your-cards div {
  list-style: none;
  flex: 0 0 50%;
}

1

2

3

4

When you give flex 3 properties, it specifies:

*

*flex-grow

*flex-shrink

*flex-basis


text:
Q: Is there a reason people can still tag questions as homework? Since the homework tag is deprecated, why are users still able to tag questions with it? I'm guessing that you haven't blacklisted the tag which means users can still use/recreate it. In that case my follow-up question is: Why not blacklist the homework tag?
It seems as if this just increases the workload for the moderating users of SO. Am I missing something?

A: Not everyone is following MSO closely and thus aware about the new consensus on the tag.
Just remove the tag from the question again and use @nickname comment-reply on the question on the exact name of the person who added the tag to explain on a kind and elaborate way (link to meta, etc) that the homework tag is been deprecated and that it should not be used anymore. That'll refreain them (and all other readers) from adding them again and again. Comment-replies work as good on editors of the post, even though they did not leave a comment.

A:
In that case I guess my question becomes "Why not blacklist the homework tag?"

A tag is not blacklisted, if there are questions using it. It should be burninated (a.k.a. removed from the question's history), but that is not done because there are some questions tagged homework that would need to be closed, or edited. If you remove the tag, you would not be able to easily find those questions using homework.
The plan is to first check every question using that tag, and take any required action (which could also be removing the tag from a perfectly acceptable question that doesn't need to be closed), then avoid the users can use that tag again, if there are many users who keep using it, and you find again too much questions tagged homework.

A: Being "deprecated" isn't a feature on the site.  Rather, it means that we've made the case to remove its existence on the site and we are actively working to remove that tag.
That said, there's currently no way to mark a tag as "don't use this" and have the system enforce it.
The only way to truly deprecate the tag is to remove it from all the questions that it's on, and then the reputation requirements for creating a new tag will kick in, which should stem the creation of the new tag, or at least slow down how often it comes in.
If it proves to be a persistent issue, then it could be blacklisted, meaning it will never be able to get used.  In this case, given how many questions with this tag that exist and the effort it will take to clean them up, I'd assume (and argue for) it would be blacklisted.  It should never come back once it's gone.


text:
Q: Java Glass Pane for WPF (C#.NET) I am building a WPF application in C#.NET and I would like to grey out the window and display a StackPanel in the centre, if a condition is true, like the glass pane in Java. I will be selling my application so I would prefer not that have to ship another licence with it, and it really needs to be free.
Is there any code to let me do this?

A: Just apply a MonochromeEffect from the WPF Shader Effect Library whenever you popup a dialog:
When opening a dialog:
Application.Current.MainWindow.Effect = new MonochromeEffect() { FilterColor = Color.FromArgb(255, 90, 90, 90) };

When closing a dialog:
Application.Current.MainWindow.Effect = null;


text:
Q: Ngrams with non-symmetrical padding in NLTK The quad gram of the word TEXT is
>>generated_ngrams = ngrams('TEXT', 4, pad_left=True, pad_right=True, left_pad_symbol=' ', right_pad_symbol=' ')

>>list(generated_ngrams)
[(' ', ' ', ' ', 'T'), (' ', ' ', 'T', 'E'), (' ', 'T', 'E', 'X'), ('T', 'E', 'X', 'T'), ('E', 'X', 'T', ' '), ('X', 'T', ' ', ' '), ('T', ' ', ' ', ' ')]

According to me the output should have been _TEX, TEXT, EXT__, XT__.
According to this website (http://cloudmark.github.io/Language-Detection/) the output is _TEX, TEXT, EXT_, XT__, T___
It also goes on to say "In general a string of length k, padded with blanks, will have k+1 bi-grams, k+1 tri-grams, k+1 quad-grams and so on."
Based on the output I got from Python I don't think that is valid.
Kindly explain.

A: Padding ensures that each symbol of the actual string occurs at all positions of the ngram. So for 4-grams there will be three padded ngrams of the last symbol, E X T _, X T _ _, and T _ _ _, etc. as your code shows you.
The website you link to adds one space on the left, then pads properly on the right. That's why the counts are different. This gives the same number of ngrams for all lengths. This is the corresponding Python code:
generated_ngrams = ngrams(" " + 'TEXT', 4,
                          pad_left=False, pad_right=True, right_pad_symbol=' ')

Why it was done this way, only the author of the blog really knows. But one consequence of padding out on the right but not the left is that, as the blog points out, a given string of length k will produce a fixed number of n-grams (k+1) for any n-gram size n. The initial space doesn't contribute to this, but serves as a word boundary sign: ngrams that start with a space are word-initial.

A: @alexis answer will provide you with the single-char left pad and multi-char right pad.
If we read the blogpost carefully:

We will also append blanks to the beginning and end of strings in order to help with matching the beginning-of-word and end-of-word situations.
We will represent this using the _ character. Given the word TEXT we would obtain the following N-Grams:

bi-grams _T, TE, EX, XT, T_
tri-grams _TE, TEX, EXT, XT_, T__
quad-grams _TEX, TEXT, EXT_, XT__, T___

The motivation for non-symmetrical padding is unclear.
Continuing with the blogpost:

In general a string of length k , padded with blanks, will have k+1 bi-grams, k+1 tri-grams, k+1 quad-grams and so on.

From the NLTK implementation and symmetrical padding, it should be:

A specifically, a string of length k symmetrical padding with blanks will yield k + (n-1) ngrams. For the case where the word is TEXT:

>>> from functools import partial
>>> from nltk import ngrams
>>> padded_ngrams = partial(ngrams, pad_left=True, pad_right=True, left_pad_symbol='_', right_pad_symbol='_')
>>> x = 'TEXT'

>>> list(ngrams(x, 2))
[('T', 'E'), ('E', 'X'), ('X', 'T')]
>>> len(list(ngrams(x, 2)))
3

>>> list(padded_ngrams(x, 2))
[('_', 'T'), ('T', 'E'), ('E', 'X'), ('X', 'T'), ('T', '_')]
>>> len(list(padded_ngrams(x, 2)))
5
>>> len(list(padded_ngrams(x, 3)))
6
>>> len(list(padded_ngrams(x, 4)))
7
>>> len(list(padded_ngrams(x, 5)))
8

To argue for symmetrical vs non-symmetrical padding, a principled way to test with a dataset and see the effects of the features in a classification task.