text:
Q: MLE and consistency and efficiency of MLE
Here is my understanding of Likelihood function,  maximum likelihood estimator (MLE) and consistency and efficiency of MLE.
(Notes: Comments are not main parts of this post and can be skipped. Only Questions are the most important parts, the rest is the context of the questions and explains why I ask these questions. I'm not expecting anyone to answer all these questions. Any comment is very much welcome.
Hints to question 3, 4 are what I am expecting most.)
I. Likelihood function
Likelihood function, though written as $f(\mathbf{x}|\theta)=f(x_1,\dots, x_n|\theta)$, is defined for both pmf of discrete random variable and continuous random variable. Note that it is not pmf or pdf for a single random variable, but one for joint distribution of random variables. That's why, when $X_i$'s are iid, it is naturally equal to $\prod_i f(x_i|\theta)$.
Comment 1:
(1) To make it look more familiar to one who is used to analysis notation, we can also write likelihood function $f(\mathbf{x}|\theta)$ for discrete variable as $P(X_1=x_1, \dots, X_n=x_n |\theta)=P_{\text{given }\theta}(X_1^{-1}(x_1), \dots, X_n^{-1}(x_n))$ (where $x_i\in \mathbb{R}$), since random variable is indeed function from sample space to $\mathbb{R}$.
(2) we can also write likelihood function $f(\mathbf{x}|\theta)$ for continuous variable as $f_{X_1, \dots, X_n}(x_1, \dots, x_n)=\frac\partial{\partial x_1}\dots\frac\partial{\partial x_n}P(X_1<x_1, \dots, X_n<x_n)\\
=\frac\partial{\partial x_1}\dots\frac\partial{\partial x_n}P(X_1^{-1}(-\infty, x_1), \dots, X_n^{-1}(-\infty, x_n)).$
(I guess $\frac\partial{\partial x_1}\dots\frac\partial{\partial x_n}$ here might be not an accurate way of saying pdf of joint distribution is derivative against multiple values $x_i\in \mathbb{R}$ of random variables.)
Question 1:
In Def 6.3.1 of Casella, Likelihood function doesn't require random variables $X_1,\dots, X_n$ (of the sample) to be i.i.d, while MLE (in Def 7.2.4) requires so?

II. MLE
MLE is maximum of likelihood function, we don't always need to calculate max of log of likelihood function, but sometimes it makes the calculation easier.

III. consistency and efficiency of MLE
Theorem 10.1.6 and 10.1.12 define consistency and efficiency of MLE.
III-1. Consistency
Consistency is that MLE $\hat \theta$ of $\theta$ as well as functions $\tau(\hat \theta)$ of $\hat \theta$ can 'give $\tau( \theta)$' arbitrarily narrow distribution (give tiny interval estimate of $\tau( \theta)$ with extremely high (almost 100%) confidence level) when n is sufficiently large, i.e.
$$P(\tau (\hat \theta)-\epsilon < \tau( \theta) < \tau (\hat \theta)+\epsilon ) \to 1, \text{ as } n\to\infty.$$
Comment 2:
Here the probability is probability about $\hat \theta$ (which is a function of random variables $X_i$ and therefore a random variable itself), not $\theta$ which is regarded as fixed (since the population and its distribution don't change), we can make it more explicit by writing $P(\tau (\hat \theta)-\epsilon < \tau( \theta) < \tau (\hat \theta)+\epsilon )=P(\tau (\hat \theta) < \tau( \theta)+\epsilon, \tau( \theta)-\epsilon < \tau (\hat \theta) )\\=P((\tau (\hat \theta))^{-1}(-\infty,  \tau( \theta)+\epsilon),  (\tau (\hat \theta) )^{-1}(\tau( \theta)-\epsilon, \infty))\\=P(( \hat \theta^{-1}(\tau^{-1}(-\infty,  \tau( \theta)+\epsilon))), ( \hat \theta^{-1}(\tau^{-1}(\tau( \theta)-\epsilon, \infty))).$
so it's, overall, probability about the random variable $\hat \theta$, i.e. probability of events where $\hat \theta$ satisfies certain conditions.
III-2. Asymptotic efficiency
Asymptotic efficiency is that MLE $\hat \theta$ of $\theta$ as well as functions $\tau(\hat \theta)$ of $\hat \theta$, beside being unbiased (converges to $\theta, \tau(\theta)$), has variance that converges to the lower bound of/smallest possible variance (of unbiased estimator)--which is Cramer-Rao Lower Bound $v(\theta)$--divided by n,
i.e. $\sqrt n[\tau(\hat \theta) -\tau( \theta)]\to n[0, v(\theta)].$
Question 2:
It seems $\frac n {v(\theta)}$ is fisher information $I_n(\theta)$ (*), so the larger is fisher information, the smaller the lower bound of variance, is it correct? (This is related to Delta method and Fisher information, if (*) is correct, then it's reasonable to use $\frac 1{I_n(\theta)}$ to describe variance/n in the asymptotic setting, i.e.  when n is large.)
(Updated: this question is partly discussed in the quoted post. My guess is close, but there are still unclear and very confusing details.)

III-3. limiting variance, asymptotic variance, and CR Lower Bound
So overall 'consistent' is an estimator being unbiased (when n, the number of iid sample, is large), 'efficient' is an estimator having the mallest possible variance an (unbiased/consistent) estimator can have, i.e. the limiting variance ($\lim_{n\to\infty} k_n\hat\theta$) or Asymptotic variance ($\sigma^2$ in $k_n[\hat\theta-\theta]\to n[0,\sigma^2]$.) equals CR Lower Bound. ($k_n$ seems to be any sequence of n, e.g. it can be $n^2, \log n, \frac{n^2+3}{-3n-1}\dots$, for MLE $k_n=\sqrt n$ )
Question 3:
The two variances are both variance of (more exactly, linear function of) the estimator, the only difference is that in one we substract from the estimator the parameter it estimates, (such substraction would not change the variance, since $\mathrm{Var}(aX+b)=a^2\mathrm{Var}(X)$), then why we need to define two variance (of estimator for sample of large n)?
Question 4:
Besides, why we need $k_n$ to define the variances, and why for MLE $k_n=\sqrt n$? (My guess is that MLE is similar to mean $\frac{\sum_i X_i}n$ (though I don't know why, this question is mentioned in another post The two estimators of mean of Gamma distribution and the estimators' variances), and so with the square of $\sqrt n$ we can balance the effect (amplifying by factor n) of $\sum_i$ in the nominator and the effect (shrinking by factor $\frac1 {n^2}$ of n in the denominator.


text:
Q: How to prevent GDB from loading debugging symbol for a (large) library? While debugging a Qt 5 application, I am sometimes not interested in the internals of Qt 5 but in the structure of the application itself. Therefore I do not need to load all debugging symbols of the Qt 5 libraries since these take a few seconds to load.
Is it possible to prevent GDB from loading symbols for these Qt 5 libraries while keeping the debugging symbols for my application?

A:
Is it possible to prevent GDB from loading symbols for these Qt 5 libraries while keeping the debugging symbols for my application?

Yes.
As Richard Critten's comment mentions, setting auto-solib-add to 0 will prevent loading of symbols for all shared libraries, and you can then add files manually with the sharedlibrary command (which accepts a regex). If this regex is omitted, then all shared libraries are loaded.
That however would prevent auto-loading of all symbols (not just debug symbols), and would also prevent auto-loading of symbols for system libraries, which are often required to unwind the stack.
A better approach may be to save a copy of Qt5 libraries with full debug info somewhere, e.g. ~/Qt5-debug/, then run strip -g on the original libraries. That way, you will get symbolic info for all libraries, and in the rare case when you actually need full-debug info for Qt5, you can still do that using the GDB file ~/Qt5-debug/libQt5Core.so.5.2 or similar commands.
The chapter GDB Files from the GDB manual has more documentation on using such separate debugging symbols.

redpajama_set_name: RedPajamaStackExchange


text:
Q: asp.net scaffolding complex type using EF Code first I have 2 models looking like this:
public class Person
{

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address PersonsAddress { get; set; }

}

public class Address
{
    public string StreetName { get; set; }
    public string City { get; set; }
}

now, when i scaffold the Person class like this: scaffold controller Person -repository and run the application and go to /persons, EF code first will create the following sql table for me:

*

*ID

*FirstName

*LastName

*Address_StreetName

*Address_City

This is all good, but when i look at the create view, the complex type address is not created by the scaffold template. The create view only has the 2 inputs for firstname and lastname.
So my question is, how can i tell scaffold to also create the fields for streetname and city in the create, edit and list view?
Do i have to edit the templates? And if yes, is it hard to do so? or recommended?

A: You can use T4 Templates to change how the wizard creates the view or you can override the EditorFor and Display for default templates


text:
Q: Sys is undefined I have an ASP.Net/AJAX control kit project that i am working on.  80% of the time there is no problem.  The page runs as it should.  If you refresh the page it will sometimes show a javascript error "Sys is undefined".
It doesn't happen all the time, but it is reproducible.  When it happens, the user has to shut down their browser and reopen the page.
This leads me to believe that it could be an IIS setting.
Another note.  I looked at the page source both when I get the error, and when not.  When the page throws errors the following code is missing:
<script src="/ScriptResource.axd?d=EAvfjPfYejDh0Z2Zq5zTR_TXqL0DgVcj_h1wz8cst6uXazNiprV1LnAGq3uL8N2vRbpXu46VsAMFGSgpfovx9_cO8tpy2so6Qm_0HXVGg_Y1&t=baeb8cc" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>

A: Try setting your ScriptManager to this.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />

A: Dean L's answer, https://stackoverflow.com/a/1718513/292060 worked for me, since my call to Sys was also too early. Since I'm using jQuery, instead of moving it down, I put the script inside a document.ready call:
$(document).ready(function () {
  Sys. calls here
});

This seems to be late enough that Sys is available.

A: I was using telerik and had exactly same problem.
adding this to web.config resolved my issue :)
<location path="Telerik.Web.UI.WebResource.axd">
   <system.web>
     <authorization>
       <allow users="*"/>
     </authorization>
   </system.web>
</location>

maybe it will help you too. it was Authentication problem.
Source

A: Try one of this solutions:
1. The browser fails to load the compressed script
This is usually the case if you get the error on IE6, but not on other browsers.
The Script Resource Handler – ScriptResource.axd compresses the scripts before returning them to the browser. In pre-RTM releases, the handler did it all the time for all browsers, and it wasn't configurable. There is an issue in one of the components of IE6 that prevents it from loading compressed scripts correctly. See KB article here. In RTM builds, we've made two fixes for this. One, we don't compress if IE6 is the browser client. Two, we've now made compression configurable. Here's how you can toggle the web.config.
How do you fix it? First, make sure you are using the AJAX Extensions 1.0 RTM release. That alone should be enough. You can also try turning off compression by editing your web.config to have the following:
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true" />
</scripting>
</system.web.extensions>

2. The required configuration for ScriptResourceHandler doesn't exist for the web.config for your application
Make sure your web.config contains the entries from the default web.config file provided with the extensions install. (default location: C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025)
3. The virtual directory you are using for your web, isn't correctly marked as an application (thus the configuration isn't getting loaded) - This would happen for IIS webs.
Make sure that you are using a Web Application, and not just a Virtual Directory
4. ScriptResource.axd requests return 404
This usually points to a mis-configuration of ASP.NET as a whole. On a default installation of ASP.NET, any web request to a resource ending in .axd is passed from IIS to ASP.NET via an isapi mapping. Additionally the mapping is configured to not check if the file exists. If that mapping does not exist, or the check if file exists isn't disabled, then IIS will attempt to find the physical file ScriptResource.axd, won't find it, and return 404.
You can check to see if this is the problem by coipy/pasting the full url to ScriptResource.axd from here, and seeing what it returns
<script src="/MyWebApp/ScriptResource.axd?[snip - long query string]" type="text/javascript"></script>

How do you fix this? If ASP.NET isn't properly installed at all, you can run the "aspnet_regiis.exe" command line tool to fix it up. It's located in C:\WINDOWS\Microsoft.Net\Framework\v2.0.50727. You can run "aspnet_regiis -i -enable", which does the full registration of ASP.NET with IIS and makes sure the ISAPI is enabled in IIS6. You can also run "aspnet_regiis -s w3svc/1/root/MyWebApp" to only fix up the registration for your web application.
5. Resolving the "Sys is undefined" error in ASP.NET AJAX RTM under IIS 7
Put this entry under <system.webServer/><handlers/>:
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

and remove the one under <system.web/><httpHandlers/>.
References:
http://weblogs.asp.net/chrisri/demystifying-sys-is-undefined
http://geekswithblogs.net/lorint/archive/2007/03/28/110161.aspx

A: I hate adding to such a huge topic and so much later, but I've think I have a solution that works in VS2015 at the very least.
I was on a hunt to find a reason for the sys error, and the only solution that worked for me was to add EnableCdn="true" in a ScriptManager like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true" />

See the MSDN for more information.
Why do we need to do this?
When working on a asp.net web application, you have to enable CDN so that Microsoft can download the Sys. library.
There was probably a script in your page that was using the Sys function. Setting EnableCdn="true" would ensure that the Sys library is downloaded before it is used.
What's CDN?
It stands for "Content Delivery Network" and enabling it allows certain resources to download with simple references.
A quote from https://www.sitepoint.com/7-reasons-to-use-a-cdn/

Most CDNs are used to host static resources such as images, videos,
audio clips, CSS files and JavaScript. You'll find common JavaScript
libraries, HTML5 shims, CSS resets, fonts and other assets available
on a variety of public and private CDN systems.

Both Google and Microsoft have CDNs. All you have to do is add a reference. Usually CDNs are added via a script resource:
<script src="https://ajax.aspnetcdn.com/ajax/4.5.1/1/MicrosoftAjax.js" type="text/javascript"></script>

Once you set EnableCdn="true" and Microsoft will add it's little CDN reference (like the one above) in the page which downloads the Sys library.
I hope that helps anybody that ran into the same issue.

A: I fixed my problem by moving the <script type="text/javascript"></script> block containing the Sys.* calls lower down (to the last item before the close of the body's <asp:Content/> section) in the HTML on the page. I originally had my the script block in the HEAD <asp:Content/> section of my page. I was working inside a page that had a MasterPageFile. Hope this helps someone out.

A: You must add these lines in the web.config

<httpHandlers>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>

Hope this helps.

A: In addition to ensuring you have the ScriptManager on your page you need to ensure that your web.config is appropriately configured.
When ASP.NET AJAX 1.0 was released (for .NET 2.0) there was a lot of custom web.config settings which added handlers, controls, etc.
You'll find the config info here: http://www.asp.net/AJAX/documentation/live/ConfiguringASPNETAJAX.aspx

A: Make sure that any client scripts you have that interact with .NET AJAX have the following line at the end:
if (typeof(Sys) !== 'undefined')  Sys.Application.notifyScriptLoaded();

This tells the script manager that the whole script file has loaded and that it can begin to call client methods

A: I was having this same issue and after much wrangling I decided to try and isolate the problem and simply load the script manager in an empty page which still resulted in this same error.  Having isolated the problem I discovered through a comparison of my site's web.config with a brand new (working) test site that changing <compilation debug="true"> to <compilation debug="false"> in the system.web section of my web.config fixes the problem.
I also had to remove the <xhtmlConformance mode="Legacy"/> entry from system.web to make the update panel work properly.  Click here for a description of this issue.

A: When I experienced the errors

*

*Sys is undefined

*ASP.NET Ajax client-side framework failed to load

in IE when using ASP.NET Ajax controls in .NET 2.0, I needed to add the following to the web.config file within the <system.web> tags:
<httpHandlers>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="GET" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler" validate="false"/>
</httpHandlers>

A: I solved this problem by creating separate asp.net ajax solution and copy and paste all ajax configuration from web.config to working project.
here are  the must configuration you should set in web.config
    <configuration>
<configSections>
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
        <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
            <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>

    </sectionGroup>
</configSections>

        <assemblies>

            <add assembly="System.Web.Extensions,     Version=1.0.61025.0,       Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

        </assemblies>
           </compilation>
        <httpHandlers>
        <remove verb="*" path="*.asmx"/>
        <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
    </httpHandlers>
    <httpModules>
        <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </httpModules>
</system.web>
    <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
        <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </modules>
    <handlers>
        <remove name="WebServiceHandlerFactory-Integrated"/>
        <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </handlers>
</system.webServer>

A: In case none of the above works for you, and you happen to be overriding OnPreRenderComplete, make sure you call base.OnPreRenderComplete. My therapist is going to be happy to see me back

A: I had the same problem after updating my AjaxControlToolkit.dll to the latest version 4.1.7.725 from 4.1.60623.0.
I've searched and came up to this page, but none of the answers help me.
After looking to the sample website of the Ajax Control Toolkit that is in the CodePlex zip file, I have realized that the <asp:ScriptManager> replaced by the new <ajaxtoolkit:ToolkitScriptManager>. I did so and there is no Sys.Extended is undefined any more.

A: In my case the problem was that I had putted the following code to keep the gridview tableheader after partial postback:
    protected override void OnPreRenderComplete(EventArgs e)
    {
        if (grv.Rows.Count > 0)
        {
            grv.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
    }

Removing this code stopped the issue.

A: Was having a similar issue,  except that my page was consistently generating the Sys is undefined error.
For me the problem stems from the fact that I've just installed the AJAX 1.0 extension for .NET 2.0 but had already created my web project  in Visual Studio.
When tried to create AJAX controls I kept encountering this error, I spotted Slace's and MadMax1138s posts here.  And figured it was my web.config, I created a new project using the new "AJAX enabled web site" project type,  and sure enough the web.config has a large number of customizations necessary to use the AJAX controls.
I just updated that web.config with the web.config updates I had already made myself and dropped it into my existing project and everything worked fine.

A: I have been seeing the exact same error today, but it was not a config or direct JavaScript issue.
An external .net project had been updated but the changes not picked up properly in the compilation of the web site. My presumption is that ASP.NET ajax was not able to construct the client representations of the .NET objects properly and so was failing to load correctly.
To resolve, I rebuilt the external project(s), and rebuilt my solution that was experiencing issues. The problem went away.

A: I found the error when using a combination of the Ajax Control Toolkit ToolkitScriptManager and URL Write 2.0.
In my <rewrite> <outboundRules> I had a precondition:
<preConditions>
    <preCondition name="IsHTML">
        <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html"/>
    </preCondition>
</preConditions>

But apparently some of my outbound rules weren't set to use the precondition.
Once I had that preCondition set on all my outbound rules:
<rule preCondition="IsHTML" name="MyOutboundRule">

No more problem.

A: Make sure you don't have any Rewrite rules that change your url.
In my case the application thought it was only level deeper then the url reached.
Example: http://mysite.com/app/page.aspx was the real url.
But i cut off /app/ this worked fine for ASP.net and WCF, but clearly not for Ajax.

A: I had similar problems and to my surprise what I found that one of my developer had saved web.config in the same folder/solution as web123.config and by mistake both of these files were uploaded.
As soon as I deleted the web123.config file, this error disappeared and ajax framework was loading correctly. even though I have
<compilation debug="true">

In my case I also have following segment. My project is using framework 3.5
    <httpHandlers>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>

A: This is going to sound stupid but I had a similar problem with a site being developed in VS2010 and hosted in the VS Dev Server. The page in question had a scriptmanager to create the connection to a wcf service. I added an extra method to the service and this error started appearing.
What fixed it for me was changing from 'Auto-assign Port' to 'Specific port' with a different port number in the oroject Web settings.
I wish I knew why...

A: Development Environment:

*

*Dev-Env: VS 2012

*FX: 4.0/4.5

*Implementations: Master(ScriptManager + UpdatePanel/Timer) + Content (UpdatePanel)

*Patterns: PageRouting.

Disclaimer:
If all the web.config solutions do not work for you and you have implemented PageRouting (IIS 7+), then the code snippet below will solve your problems.
Background:
Dont mean to Highjack this question but had the same problem as everyone else and implemented 100% of the suggestions here, with minor modifications for .Net 4.0/4.5, and none of them worked for me.
In my situation i had implemented Page Routing which was ghosting my problem.  Basically it would work for about 20, or so, debug runs and then BAM would error out with the Sys is undefined error.
After reviewing a couple other posts, that got to talking about the Clean-URL logic, i remembered that i had done PageRouting setup's.
Here is the resource i used to build my patterns: Page Routing
My one-liner code fixed my VS2012 Debugging problem:
rts.Ignore("{resource}.axd/{*pathInfo}")    'Ignores any Resource cache references, used heavily in AJAX interactions.

A: Even after adding the correct entry for web config still getting this error ?  most common reason for this error is JavaScript that references the Sys namespace too early.
Then most obvious fix would be   move the java script block below the ScriptManager control:

A: I don't think this point has been added and since I just spent some time hunting this down I hope it can help.
I am working with IIS 7 and using the ASP.NET v4 Framework.
In my case it was important that an entry be added to both the  and  section of the  entry in the web.config file.
My web.config file has a lot of handlers and in my case it was easiest to add the ScriptResources entry to the top of the handlers section.  Most importantly, it needs to be placed before any entry that will act as a wildcard and capture the request.  Adding it after a wildcard entry will cause it to be ignored and the error will still appear.The module can be added to the top or bottom of the section.
Web.config Sample:
<system.webServer>
    <handlers>
      <clear />
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      <!-- Make sure wildcard rules are below the ScriptResource tag -->
    </handlers>
    <modules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      <!-- Other modules are added here -->
    </modules>
  </system.webServer>

A: I had same probleme but i fixed it by:
When putting a script file into a page, make sure it is
<script></script> and not <script />.

I have followed this:
http://forums.asp.net/t/1742435.aspx?An+element+with+id+form1+could+not+be+found+Script+error+on+page+load
Hope this will help

A: Add
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

Please check  enter link description here

A: In my case, I've found a very hidden reason ... There was this page route with in Global.ascx.cs which doesn't appear in my tests in sub-folders but returns the question error all the time .. another day with strange issues.
routes.MapPageRoute("siteDefault", "{culture}/", "~/default.aspx", false, new RouteValueDictionary(new { culture = "(\\w{2})|(\\w{2}-\\w{2})" }));

A: I know this is an old thread but I found a somewhat unique solution.  In my case I was getting the error because I am using both Webforms and MVC in the same ASP.NET web application.  After mapping routes the issue showed up.  I fixed it by adding the following code to ignore routes for both "{resource}.aspx/{*pathInfo}" and "{resource}.axd/{*pathInfo}"
    private void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
           "Default",
           "{controller}/{action}/{id}",
           new { controller = "Test", action = "Index", id = UrlParameter.Optional }
       );
    }

A: Just create blank .axd files in your solutions root foder problem will be resolved. (2 file: scriptresouce.asx, webresource.asxd)

A: Please please please do check that the Server has the correct time and date set...
After about wasting 6 hours, i read it somewhere...
The date and time for the server must be updated to work correctly...
otherwise you will get 'Sys' is undefined error.

A: Hi thanx a lot it solved my issue ,
By default vs 2008 will add
 <!--<add verb="*" path="*.asmx" validate="false" type="Microsoft.Web.Script.Services.ScriptHandlerFactory, Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      <add verb="GET" path="ScriptResource.axd" type="Microsoft.Web.Handlers.ScriptResourceHandler" validate="false" />-->

Need to correct Default config(Above) to below code
FIX
 <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="GET" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler" validate="false"/>


text:
Q: Delete entity after specified time with JpaRepository I am using Spring Boot and H2 db. I have a Product entity and I want my application to be able to remove the product from the database, but my requirement is this: first set the active flag to false ( then this row will not be taken into account during fetching ) and after a specific period of time completely remove this row from db.
@Entity
@Table(name = "products")
public class Product {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int id;
    private boolean active = true;
    // getters & setters
}

And my method from the service layer responsible for setting the active flag to false and later complete deletion (I have nothing that does the second part of my requirement - complete deletion after specific period of time)
@Transactional
public void deleteProduct(int id) {
    var target = repository.findProductById(id)
            .orElseThrow(() -> new IllegalArgumentException("No product with given id"));
    target.setActive(false);
    // what should I add here to remove the target after a specific time?
}

EDIT
OK, I solved my problem:
@Transactional
public void deleteProduct(int id) {
    var target = repository.findProductByIdAndActiveTrue(id)
            .orElseThrow(() -> new IllegalArgumentException("No product with gicen id"));
    target.setActive(false);
    // complete removal after 150 seconds
    new Thread(() -> {
        try {
            Thread.sleep(150000);
            repository.deleteById(id);
        } catch (Exception e) {
            logger.error("Error removing the product");
        }
    }).start();
}

But now my question is if this is a safe solution as the user may start too many threads now so I think there is a better solution to my problem (safer in terms of multithreading)

A: I am not an expert but i think what you trying to achieve is bad practice.
I believe you should do a scheduling, for example ones per day.
You should update in db the value active. Set a schedule that will check the entries each time and if they have an active value of false then delete. Something like this:
public void deleteProduct(int id) {

    //update value to false
    repository.updateProductValue(id,false);
}

and your scheduling method:
@Scheduled(fixedRate = 150000)
public void deleteNonActiveProducts() {

        List<Product> products = repository.findAllByFalseValue();
        products.forEach(product -> repository.deleteById(product.getId());
}

With this what you are doing is that every 150000 milliseconds you repeat that task and each execution of this task is independent and non parallel.
Hope is useful to you.


text:
Q: Stop TinyMCE 4.1.9 from removing orphaned children tags I am wanting to use ANY tag inside of TinyMCE without it being removed, but it's not working.  My current input is:

[item-thumb]	[item-count]	[item-location]	[item-title]	[item-desc]	[low-estimate]

This is used to iterate through items and replace the short-codes with item data, and put that into a table.  However, it always strips out the tr and td tags because it is not wrapped in a table tag.
I've tried:
valid_elements: "+*[*]",
valid_children: "+*[*]",
extended_valid_elements: "+*[*]",
verify_html: false,
cleanup: false,
cleanup_on_startup : false,

I know some of these are deprecated, but I'm willing to try anything at this point.

A: The issue you are running into is that TinyMCE is designed to create valid, well-formed (X)HTML.  If you attempt to create table related tags but don't wrap them in a table the HTML cleanup/validation routine will always do its best to cleanup the content to make it valid.
There is no way to disable this validation.

A: Why don't you just wrap them in a
, then just remove
 and
 just before saving?
I have done that for something else, but with TinyMCE.
I have the full code in the textarea (where the content of the TinyMCE is), and then used javascript to remove the unwanted code (
 and
 in your case) before saving it to a file.
It will work this way:
IF you load the content of the textarea from a database, then just prefix and suffix the content with what you need to make TinyMCE work.
Then get the content from the textarea when you are going to save it, BUT remove the prefix and suffix before writing it to the database/ file.
Doing this should be easy, and gives you endless possibilities.
(You could either do that by javascript, or by PHP (or whatever server side language you use).)


text:
Q: Powershell not returning correct value As some background, this should take an excel file, and convert it to PDF (and place the PDF into a temporary folder).
E.g. 'C:\Users\gjacobs\Desktop\test\stock.xlsx'
becomes
'C:\Users\gjacobs\Desktop\test\pdf_merge_tmp\stock.pdf'
However, the new file path does not return correctly.
If I echo the string $export_name from within the function, I can see that it has the correct value: "C:\Users\gjacobs\Desktop\test\pdf_merge_tmp\stock.pdf".
But once $export_name is returned, it has a different (incorrect value): "C:\Users\gjacobs\Desktop\test\pdf_merge_tmp C:\Users\gjacobs\Desktop\test\pdf_merge_tmp\stock.pdf".
function excel_topdf{

    param(
        $file
    )

    #Get the parent path
    $parent = Split-Path -Path $file

    #Get the filename (no ext)
    $leaf = (Get-Item $file).Basename

    #Add them together.
    $export_name = $parent + "\pdf_merge_tmp\" + $leaf + ".pdf"

    echo ($export_name) #prints without issue.

    #Create tmp dir
    New-Item -Path $parent -Name "pdf_merge_tmp" -ItemType "Directory" -Force

    $objExcel = New-Object -ComObject excel.application
    $objExcel.visible = $false

    $workbook = $objExcel.workbooks.open($file, 3)
    $workbook.Saved = $true

    $xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type]
    $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $export_name)
    $objExcel.Workbooks.close()

    $objExcel.Quit()

    return $export_name
}

$a = excel_topdf -file 'C:\Users\gjacobs\Desktop\test\stock.xlsx'
echo ($a)

A: The issue you're experiencing is caused by the way how PowerShell returns from functions. It's not something limited to New-Item cmdlet. Every cmdlet which returns anything would cause function output being altered with the value from that cmdlet.
As an example, let's take function with one cmdlet, which returns an object:
function a {
 Get-Item -Path .
}

$outputA = a
$outputA

#### RESULT ####

    Directory:

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d--hs-       12/01/2021     10:47                C:\

If you want to avoid that, these are most popular options (as pointed out by Lasse V. Karlsen in comments):
# Assignment to $null (or any other variable)
$null =  Get-Item -Path .

# Piping to Out-Null
Get-Item -Path . | Out-Null

NOTE: The behavior described above doesn't apply to Write-Host:
function b {
 Write-Host "bbbbbb"
}

$outputB = b
$outputB

# Nothing displayed

Interesting thread to check if you want to learn more.


text:
Q: Which is the best option for make folders from web with AD authentication? I am interested in making a web for a creating a folder structure with acl in a Microsoft AD Domain, the process would be the following:

*

*The user log in to the web (best with credentials of Windows user)

*Authorized users give the name of the folder (in this case the name of the project)

*A structured folder is created with the correct ACL

*Also I need the option to move the folder to another location and remove/rename the folder

I don't know what is the best option, and more compatible to do this, I'm a bit lost for start googling


text:
Q: Как скопировать репозиторий и файлы определенного типа командой cp [BASH] Я хочу скопировать все файлы с расширением .txt из папки testdirectory в папку results (эти две папки лежат в одной директории). Если в папке testdirectory есть папка, а в ней тоже файл расширения .txt, то его тоже нужно скопировать (вместе с папкой)
Я пытался сделать это следующим образом (запускаю в папке testdirectory):
cp -R *.txt ../results
но в таком случае копируются только файлы в ~testdirectory (то есть внутренние папки не трогаются и файлы в них тоже)
Если так:
cp -R ../testdirectory/ *.txt ../results то копируются абсолютно все файлы и папки (то есть копируются файлы с другим расширением, что не нужно)
UPD: ищется решение именно через команду cp


text:
Q: cannot register a node (VM) with selenium grid 2 hub (physical machine) I al trying to register a node which is a VM with windows 7 on a hub that sits on a physical machine windows 7 also.
My server starts succesfully on port 4444.
I run this command to register the node :
This is what i get from my node console :
C:\grid>java -jar selenium-server-standalone-2.35.0.jar -role node -hub http://
hubip:4444/grid/register -browser browserName=firefox,platform=WINDOWS -
rowser browserName=chrome,platform=WINDOWS -browser "browserName=internet explo
er,platform=WINDOWS" -remoteHost nodeip:4444
26 sept. 2013 11:28:40 org.openqa.grid.selenium.GridLauncher main
INFO: Launching a selenium grid node
26 sept. 2013 11:28:40 org.openqa.grid.common.RegistrationRequest addCapability
romString
INFO: Adding browserName=firefox,platform=WINDOWS
26 sept. 2013 11:28:40 org.openqa.grid.common.RegistrationRequest addCapability
romString
INFO: Adding browserName=chrome,platform=WINDOWS
26 sept. 2013 11:28:40 org.openqa.grid.common.RegistrationRequest addCapability
romString
INFO: Adding browserName=internet explorer,platform=WINDOWS
11:28:41.375 INFO - Java: Sun Microsystems Inc. 20.13-b02
11:28:41.375 INFO - OS: Windows 7 6.1 x86
11:28:41.375 INFO - v2.35.0, with Core v2.35.0. Built from revision c916b9d
11:28:41.531 INFO - RemoteWebDriver instances should connect to: ://127.0.0
1:5555/wd/hub
11:28:41.531 INFO - Version Jetty/5.1.x
11:28:41.531 INFO - Started HttpContext[/selenium-server/driver,/selenium-serve
/driver]
11:28:41.531 INFO - Started HttpContext[/selenium-server,/selenium-server]
11:28:41.531 INFO - Started HttpContext[/,/]
11:28:41.546 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@111a3
4
11:28:41.546 INFO - Started HttpContext[/wd,/wd]
11:28:41.546 INFO - Started SocketListener on 0.0.0.0:5555
11:28:41.546 INFO - Started org.openqa.jetty.jetty.Server@a9ae05
11:28:41.546 INFO - using the json request : {"class":"org.openqa.grid.common.R
gistrationRequest","capabilities":[{"seleniumProtocol":"WebDriver","platform":"
INDOWS","browserName":"firefox"},{"seleniumProtocol":"WebDriver","platform":"WI
DOWS","browserName":"chrome"},{"seleniumProtocol":"WebDriver","platform":"WINDO
S","browserName":"internet explorer"}],"configuration":{"port":5555,"host":"10.
128.120","hubHost":"192.168.1.110","registerCycle":5000,
"hub":"://hubip:4444/grid/register","url":"nodeip:4444","remoteHost":"
nodeip:4444","register":true,"proxy":"org.openqa.grid.selenium.proxy.Defau
tRemoteProxy","maxSession":5,"browser":"browserName=firefox,platform=WINDOWS","
ole":"node","hubPort":4444}}
11:28:41.546 INFO - Starting auto register thread. Will try to register every 5
00 ms.
11:28:41.546 INFO - Registering the node to hub :://hubip:4444/grid
register
11:29:56.910 INFO - Registering the node to hub :://hubip:4444/grid
register
11:31:12.274 INFO - Registering the node to hub :://hubip:4444/grid
register
11:32:27.684 INFO - Registering the node to hub :://hubip:4444/grid
register
11:33:43.204 INFO - Registering the node to hub :://hubip:4444/grid
register
11:34:58.599 INFO - Registering the node to hub :://hubip:4444/grid
register

--- the node keeps trying to register but the registration is refused.
Here is what i get from the hub console :
Avertissement: Unregistering the node. It's been down for 60113 milliseconds.
sept. 26, 2013 12:00:04 PM org.openqa.grid.internal.Registry removeIfPresent
Avertissement: Proxy 'nodeip:4444 time out : 300000' was prev
iously registered.  Cleaning up any stale test sessions.
sept. 26, 2013 12:00:07 PM org.openqa.grid.internal.BaseRemoteProxy <init>
Avertissement: Max instance not specified. Using default = 1 instance
sept. 26, 2013 12:00:07 PM org.openqa.grid.internal.BaseRemoteProxy <init>
Avertissement: Max instance not specified. Using default = 1 instance
sept. 26, 2013 12:00:07 PM org.openqa.grid.internal.BaseRemoteProxy <init>
Avertissement: Max instance not specified. Using default = 1 instance
sept. 26, 2013 12:00:13 PM org.openqa.grid.selenium.proxy.DefaultRemoteProxy isA
live
Avertissement: Failed to check status of node: Connection to nodeip
:4444 refused
sept. 26, 2013 12:00:19 PM org.openqa.grid.selenium.proxy.DefaultRemoteProxy isA
live
Avertissement: Failed to check status of node: Connection to nodeip
:4444 refused
sept. 26, 2013 12:00:19 PM org.openqa.grid.selenium.proxy.DefaultRemoteProxy onE
vent
Avertissement: Marking the node as down. Cannot reach the node for 2 tries.
sept. 26, 2013 12:00:25 PM org.openqa.grid.selenium.proxy.DefaultRemoteProxy isA
live
Avertissement: Failed to check status of node: Connection to nodeip
:4444 refusedsept. 26, 2013 12:00:31 PM


text:
Q: What resistor should I use for connecting seven segment to Arduino? I am planning to use Arduino with a 4 digit 7 segment that uses TM1637 driver chip, which has 4 pins, and uses 2 pins for data with i2c protocl.

Here is the code and datasheets:
https://github.com/avishorp/TM1637
Here it says that pull-up resistor is needed. How can I choose appropriate resistors for the 7-segment?

The second problem also arises from the code snippet above. I2C is
  wired-and bus, meaning it should never be driven high.When a logic '1'
  is desirable, the output of the Arduino should be put in
  high-impedance state allowing the pull-up resistor to pull the line to
  its high level. This is unlikely to cause an immediate problem, but in
  the long term it may cause the reliability of the components to
  degrade.

In some part of the datasheet it says:
Electrical character (Ta = -40 - +85℃, VDD = 4.5 - 5.5 V, Vss = 0 V)
Output pull down resistor - Typical ~10KΩ (Test condition K1~K2)

A: I think I usually use 4.7k, but a 10k should be fine.


text:
Q: What's the difference between "end" and "exit sub" in VBA? In VBA, sometimes we want to exit the program after some condition is true. But do I use end or exit sub?

A: This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.
End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears
  all global and static variables.  (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.
Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
  Immediately exits the Sub procedure in which it appears.
  Execution continues with the statement following the statement that
  called the Sub procedure. Exit Sub can be used only inside a Sub
  procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
  Terminates the definition of this procedure.


text:
Q: Why the same user has different PATH value on linux server? I logged on to my Linux server (Redhat AS4) through SSH as the user 'guest', then run the command echo $PATH, and the output is /usr/local/bin:/bin:/usr/bin.
However, when I run the command su - guest to switch to the same user, then run the command echo $PATH, the output becomes /usr/bin:/bin:/usr/local/bin.
Why the same user has different PATH value on Linux server? That makes me get different Python versions and I don't know what causes this problem.

A: Check the fields ENV_SUPATH and ENV_PATH in /etc/login.def
For good scripting practice, do not rely on the PATH variable to execute a command as it is ambiguous.

A: Different scripts (doing different manipulation on the PATH) are sourced in the two cases.
Since you are using the - option, su should source your login script, while ssh should not.
I don't know which behavior you want exactly, but maybe you could check if some su options (e.g. -m, --preserve-environment: do not reset environment variables) could help?

A: It goees like this:-
In /etc/passwd where the user id is defined a home directory and a default shell:
auser:!:97:51::/home/user:/usr/bin/ksh

When auser logs in the 'ksh' or bash or whatever will run this will pick up a default 'PATH' from the '/etc/environment' file (and some shells will run a system wide initialisation file), but, it will also run the commands from an initial script in the home directory in the above case the '.kshrc' file.
So the PATH can be set by the initial command, the system wide settings for that initial command and the 'hidden' .rc files in the users home directory.
The 'su -' does not run the same set of initial commands as login only picks up the default settings from the '/etc/environment' file.

A: Try to debug using the technique described in my answer on superuser, using
debug_msg "running ~/.bashrc ($0), PATH = '$PATH'"

and similar for /etc/bashrc, /etc/profile, etc.

A: from su manpage
su is used to become another user during a login session. Invoked with-
       out a username, su defaults to becoming the super  user.  The  optional
       argument  -  may be used to provide an environment similiar to what the
       user would expect had the user logged in directly.

therefore you will always get different env settings on "su" and "su -"


text:
Q: High contrast theme causes missing icons System Settings will lose icons if the Appearance > Theme is set to High Contrast. The Launcher can also lose some icons. Changing back to the default Ambiance will restore icons after a while but not necessarily immediately.
How can High Contrast be used without the loss of icons?
This pertains to Ubuntu 16.04.

A: This is a bug there where the fix was just released days ago !
Ugrade your packages to these versions and it should fix your issues
xenial:
gnome-themes-standard | 3.18.0-2ubuntu2
gnome-accessibility-themes | 3.18.0-2ubuntu2

However, these are in the repository xenial-proposed currently.
You might want to add the following with your favourite editor
sudo nano /etc/apt/sources.list

replace "us" with the country where you are
deb http://us.archive.ubuntu.com/ubuntu/ xenial-proposed main universe multiverse

then update
sudo apt-get update

and to upgrade only these packages do
sudo apt-get install gnome-themes-standard gnome-accessibility-themes

then i would suggest to comment out the proposed reposoitory, as to not upgrade other packages
sudo nano /etc/apt/sources.list

add a # before the line
#deb http://us.archive.ubuntu.com/ubuntu/ xenial-proposed main universe multiverse

and update again
sudo apt-get update


text:
Q: Scala Option filter method doubts I have been reading through Scala docs and while skimming through Option class I saw filter implementation that looks like this:
final def filter(p: A => Boolean): Option[A] =
  if (isEmpty || p(this.get)) this else None

Why do we have to check whether our Option instance is empty? Wouldn't this result in None either way?

A: The || is short-circuiting, so checking isEmpty first ensures that get won't be called on an empty option (which would throw an exception).


text:
Q: Akka Stream continuously consume websocket Im kinda new to Scala and Akka Stream and im trying to get JSON String messages from a websocket and push them to a Kafka topic.
For now i am only working on the "get messages from a ws" part.
Messages coming from the websocket looks like this :
{
   "bitcoin":"6389.06534240",
   "ethereum":"192.93111286",
   "monero":"108.90302506",
   "litecoin":"52.25484165"
}

I want to split this JSON message to multiple messages :
   {"coin": "bitcoin", "price": "6389.06534240"}
   {"coin": "ethereum", "price": "192.93111286"}
   {"coin": "monero", "price": "108.90302506"}
   {"coin": "litecoin", "price": "52.25484165"}

And then push each of these messages to a kafka topic.
Here's what i achieved so far :
val message_decomposition: Flow[Message, String, NotUsed] = Flow[Message].mapConcat(
    msg => msg.toString.replaceAll("[{})(]", "").split(",")
  ).map( msg => {
    val splitted = msg.split(":")
    s"{'coin': ${splitted(0)}, 'price': ${splitted(1)}}"
  })

val sink: Sink[String, Future[Done]] = Sink.foreach[String](println)

val flow: Flow[Message, Message, Promise[Option[Message]]] =
    Flow.fromSinkAndSourceMat(
      message_decomposition.to(sink),
      Source.maybe[Message])(Keep.right)

val (upgradeResponse, promise) = Http().singleWebSocketRequest(
      WebSocketRequest("wss://ws.coincap.io/prices?assets=ALL"),
      flow)

It's working im getting the expected output Json message but i was wondering if i could write this producer in a more "Akka-ish" style, like using GraphDSL. So i have a few questions :

*

*Is it possible to continuously consume a WebSocket using a GraphDSL ? If yes, can you show me a example please ?

*Is it a good idea to consume the WS using a GraphDSL ?

*Should i decompose the received Json Message like im doing before sending it to kafka ? Or it's better to send it as it is for lower latency ?

*After producing the message to Kafka, i am planning to consume it using Apache Storm, is it a good idea ? Or should i stick with Akka ?

Thanks for reading me, Regards,
Arès

A: That code is plenty Akka-ish: scaladsl is just as Akka as the GraphDSL or implementing a custom GraphStage.  The only reason, IMO/E, to go to the GraphDSL is if the actual shape of the graph isn't readily expressible in the scaladsl.
I would personally go the route of defining a CoinPrice class to make the model explicit
case class CoinPrice(coin: String, price: BigDecimal)

And then have a Flow[Message, CoinPrice, NotUsed] which parses 1 incoming message into zero or more CoinPrices.  Something (using Play JSON here) like:
val toCoinPrices =
  Flow[Message]
    .mapConcat { msg =>
      Json.parse(msg.toString)
        .asOpt[JsObject]
        .toList
        .flatMap { json =>
          json.underlying.flatMap { kv =>
            import scala.util.Try

            kv match {
              case (coin, JsString(priceStr)) =>
                Try(BigDecimal(priceStr)).toOption
                  .map(p => CoinPrice(coin, p))

              case (coin, JsNumber(price)) => Some(CoinPrice(coin, price))
              case _ => None
            }
          }
        }
    }

You might, depending on what the size of the JSONs in the message are, want to break that into different stream stages to allow for an async boundary between the JSON parse and the extraction into CoinPrices.  For example,
Flow[Message]
  .mapConcat { msg =>
    Json.parse(msg.toString).asOpt[JsObject].toList
  }
  .async
  .mapConcat { json =>
    json.underlying.flatMap { kv =>
      import scala.util.Try

      kv match {
        case (coin, JsString(priceStr)) =>
          Try(BigDecimal(priceStr)).toOption
            .map(p => CoinPrice(coin, p))

        case (coin, JsNumber(price)) => Some(CoinPrice(coin, price))
        case _ => None
      }
    }
  }

In the above, the stages on either side of the async boundary will execute in separate actors and thus, possibly concurrently (if there's enough CPU cores available etc.), at the cost of extra overhead for the actors to coordinate and exchange messages.  That extra coordination/communication overhead (cf. Gunther's Universal Scalability Law) is only going to be worth it if the JSON objects are sufficiently large and coming in sufficiently quickly (consistently coming in before the previous one has finished processing).
If your intention is to consume the websocket until the program stops, you might find it clearer to just use Source.never[Message].


text:
Q: How to get an index of specific element ina ListView? I have a ListView of images and checkboxes alternating elements (image, checkbox, image, etc).
When I use Thumbnails.SelectedIndex, it returns the element position, but I want the element position only for images and to have checkboxes ignored.
How to do this?
private void Thumbnails_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    int item = Thumbnails.SelectedIndex + 1; //get original index for each element in ListView
    MessageBox.Show(Convert.ToString(item));
}

A: Can you do something like this. On my side I can see it display the index only for images. Let me know if u face problem.
    private void Thumbnails_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        int item = Thumbnails.SelectedIndex + 1; //get original index for each element in ListView

        object content = Thumbnails.SelectedItem;
        if (content is Image)
        {
            MessageBox.Show(Convert.ToString(item));
        }

    }


text:
Q: How do you lowercase environment variables in Visual C++? Is it possible to lower case environment variables from Visual C++ project settings e.g. $(TargetName), $(ConfigurationName) etc without having to specify these as new environment variables.  I would like to keep everything lower case to match my unix builds.
Thanks

A: Yes, it is possible!
Just use $(MacroName.toLower())
or $(MacroName.toUpper()).
For example:
$(Configuration) == Debug
$(Configuration.toLower()) == debug
$(Configuration.toUpper()) == DEBUG

This works as of Visual Studio 2017, can't tell if it does for older versions, though.

A: Here it says:

These macros are not case sensitive.

According to some, $(Target..) is lower case, whereas $(OutputDir) is not necessarely:

*

*http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/f83e967c-ae19-4073-a9a3-75f2e4482c74

*Visual Studio 2005 creates output directories in lowercase
However, I don't know about any documentation confirming this.


text:
Q: Javascript Video player When I click the Space button (break),  it only plays video. It's not stopping with Space.
I don't know what the problem is.
document.addEventListener("keydown", (e) => {
  const tagName = document.activeElement.tagName.toLowerCase();

  if (tagName === "input") return;

  switch (e.key.toLowerCase()) {
    case " ":
      if (tagName === "button") return;
    case "k":
      playVideo();
      break;
  }
});
// Play video function
function playVideo() {
  play_pause.innerHTML = "pause";
  play_pause.title = "pause";
  video_player.classList.add("paused");
  mainVideo.play();
}
// Pause video function
function pauseVideo() {
  play_pause.innerHTML = "play_arrow";
  play_pause.title = "play";
  video_player.classList.remove("paused");
  mainVideo.pause();
}

play_pause.addEventListener("click", () => {
  const isVideoPaused = video_player.classList.contains("paused");
  isVideoPaused ? pauseVideo() : playVideo();
});

mainVideo.addEventListener("play", () => {
  playVideo();
});

A: let state = true;
switch (e.key.toLowerCase()) {
 case e.keyKode == 32:
 if(state == true){
     playVideo();
     state = false;
 } else {
   pauseVideo();
   state = true;
 }
break;
}
}

Try this out for space.

A: There is correct answer if someones need.

      case e.keyCode == 32:
        if (mainVideo.paused) {
            mainVideo.play();
        } else {
            mainVideo.pause();
        }
        break;


text:
Q: How can each derived class can have its own static value, while sharing the same base method in Java? class Base {
    Base() {
        System.out.println("Base Constructor");
    }
}

class Derived1 extends Base {
    private static String pattern = "a+b+";
    Derived1() {
        super();
        System.out.println("Derived 1 Constructor");
    }

    public static boolean doesMatch(String v) {
        return v.matches(pattern);
    }
}

class Derived2 extends Base {
    private static String pattern = "c+";
    Derived2() {
        super();
        System.out.println("Derived 2 Constructor");
    }

    public static boolean doesMatch(String v) {
        return v.matches(pattern);
    }
}

class Builder {
    public static Base baseFromString(String v) throws Exception {
        if (Derived1.doesMatch(v)) return new Derived1();
        if (Derived2.doesMatch(v)) return new Derived2();
        throw new Exception("Could not match " + v + " to any derived type.");
    }
}

class Test {
    public static void main(String[] args) throws Exception {
        Base b = Builder.baseFromString("aaab");
    }
}

The code above has a primary problem I want to solve:

*

*The doesMatch method is repeated code for the two derived classes. I'd like to move it to the base class, but then it won't be able to access the pattern member. How do I structure my code better so that each derived class can have its own static pattern, while they all share the same base doesMatch method?

I've tried messing around with abstract classes and interfaces, but I couldn't get anything to work. I am fine with those types of solutions as long as there is a hierarchy where the derived classes either extend or implement the base class.
Secondary question (from original post)

*I might want to add several more derived classes. I'd like to not have to update the baseFromString method with another if every time I extend the base class. Is this something that can be solved with polymorphism?

A: A functional technique (Java 9+), but there is some performance overhead:
class Base {
    Base() {
        System.out.println("Base Constructor");
    }
}

class Derived1 extends Base {
    Derived1() {
        super();
        System.out.println("Derived 1 Constructor");
    }
}

class Derived2 extends Base {
    Derived2() {
        super();
        System.out.println("Derived 2 Constructor");
    }
}

interface NewBase {
    Base create();
}

final class Pattern {
    final private String pattern;
    final private NewBase newBase;
    public Pattern(String pattern, NewBase newBase) {
        this.pattern = pattern;
        this.newBase = newBase;
    }
    public String getPattern() {
        return pattern;
    }
    public NewBase getNewBase() {
        return newBase;
    }
}

class Builder {
    final private static List<Pattern> newObjects = new ArrayList<>();
    private static void addPattern(String pattern, NewBase newObject) {
        newObjects.add(new Pattern(pattern, newObject));
    }
    static {
        addPattern("a+b+", Derived1::new);
        addPattern("c+", Derived2::new);
    }
    public static Base baseFromString(String v) throws Exception {
        for (Pattern p : newObjects) {
            if (v.matches(p.getPattern()))
                return p.getNewBase().create();
        }
        throw new Exception("Could not match " + v + " to any derived type.");
    }
}

Just update the static Builder initializer to call the addPattern for new patterns and derived classes.

A: You can't do that, at least not with static members. The problem is that static members cannot be overridden.
public class Driver {
    public static void main(String args[]) {
        Derived aDerived = new Derived();
        aDerived.print(); // prints "Value is 5", not "Value is 10"
    }
}

public class Base {
    protected static final int VALUE = 5;
    public Base() {}

    protected void print() {
        System.out.println("Value is " + VALUE);
    }
}

public class Derived extends Base {
    protected static final int VALUE = 10; // does not override base Value
    public Derived() {}
}

Each subclass can have its own value, and they would all inherit print(). But it doesn't do what you want because print() will always reference Base.VALUE even in the inherited Derived.print().
So, static doesn't work. I assume that you feel the pattern member needs to be static because there only needs to be one copy of the pattern value for the entire class. That one copy part should have tipped you off to a handy little design pattern: the singleton pattern!
public class Driver {
    public static void main(String args[]) {
        Derived aDerived = new Derived();
        aDerived.print(); // prints "Value is 10"
    }
}

public class Base {
    protected Value val = Value.getInstance();
    public Base() {}

    protected void print() {
        System.out.println("Value is " + val.value());
    }
}

public class Derived extends Base {
    public Derived() { val = DerivedValue.getInstance(); }
}

public class Value {
    private int value = 5;
    public int value() { return value; }

    private static Value instance = new Value();
    protected Value() {}
    public static Value getInstance() { return instance; }
}

public class DerivedValue extends Value {
    private int value = 10;
    public int value() { return value; }

    private static DerivedValue instance = new DerivedValue();
    private DerivedValue() {}
    public static DerivedValue getInstance() { return instance; }
}

There's a lot more code in this version, but now there is only one copy of the two different values used.
Note: Below is how you can make the value members final. You'll have to set up your packages appropriately so the protected Base(Value v) constructor is only visible to the Derived class.
public class Base {
    protected final Value val;
    public Base() { val = Value.getInstance(); }
    protected Base(Value v) { val = v; }

    protected void print() {
        System.out.println("Value is " + val.value());
    }
}

public class Derived extends Base {
    public Derived() { super(DerivedValue.getInstance()); }
}


text:
Q: using signals in django application code suggestion Hello everyone I want to do charts based on my models the count of mail_items sent per countries , in my model you will see  Country_origine
the idea is I want to do another model that has 2 columns ' country ' and ' mail_items_count ' then I want to make a signal  when new item saved to ' mail_items ' the signal will update the ' country+mail_items_count ' increase the ' mail_items_count ' by one ,
also I want to make a function to sum all counts in the ' mail_item_count '  column .
in my views.py I want to make a view that query all countries with their ratio : ( I have to make  a dictionary, I have to loop throw each object in the query , and take the country name as the key in the dictionary , and take the counter (integer) divided by the output of the sum function to calculate the ratio of each country , and append in the dictionnary ... to send the response with all coutries and ratio dictionnary)
models.py
class mail_items(models.Model):
        mail_item_fid = models.OneToOneField(Mail_item_Event,on_delete=models.CASCADE)
        Event_code = models.OneToOneField(Mail_item_Event,on_delete=models.CASCADE,related_name="mail_item_event_cd")
        office_Evt_cd = models.ForeignKey(Office,on_delete=models.CASCADE, related_name='office_Ev')
        Date_Evt = models.DateTimeField()
        Country_origine = models.ForeignKey(Pays, on_delete=models.CASCADE ,related_name='paysOrigine')
        Country_destination = models.ForeignKey(Pays,on_delete=models.CASCADE,related_name='paysDestination')
        Expediteur = models.ForeignKey(Client,on_delete=models.CASCADE,related_name='expedi')
        Destinateur = models.ForeignKey(Client,on_delete=models.CASCADE,related_name='destin')

sorry if it was so long ....
I am still quite beginner even searched a lot I couldn't make this possible , can you help me coding this part or send me links that could help me out coding it ?

A: Suppose that the other model is called mail_item_count, you can use post_save signal on mail_items model which will be fired when you save an object of mail_items and update the count there. For instance:
from django.db.models.signals import post_save

@receiver(post_save, sender=mail_items)
def update_count(sender, instance, created, **kwargs):
    # get the object for the required country or create it if it doesn't exist
    count_object, _ = mail_item_count.objects.get_or_create(country=instance.Country_origine)
    count_object.count = count_object.count + 1
    count_object.save()

And as for getting sum for all the countries, you can do something like:
sum(instance.count for instance in mail_item_count.objects.all())

A: Using annotation you could do this without creating an additional model. It would also reduce the overhead of implementing signals
You can do this directly in a view like this to get counts across all countries:
from django.db.models import Count

countries = Pays.objects.annotate(num_emails=Count('paysOrigine'))

#example result
print(countries[0].num_emails)

Alternatively if you don't need counts for all at once you could add a property to the Pays model:
class Pays(models.Model):
    ...

    @property
    def email_count(self):
        return self.paysOrigine_set.all().count()


text:
Q: How to apply media query to only certain width range How to apply a media query between 360px - 640px. This is overlapping my (max-width: 320px) mediaquery.
@media screen and (min-width:360px) and (max-width:640px) and (orientation : landscape)

My webpage where the problem occurs

A: You don't have anything but this one media query in your page. If you want to change something under 320px you need to declare it separately. You should declare media queries that affect everything under the page width.
Here is a simple example of how media queries work: http://jsfiddle.net/ra9ry8t4/1/
It's probably easier to test in JSFiddle but here it is also as a snippet:

@media screen and (min-width: 480px) {
  body {
    background-color: yellow;
  }
}

@media screen and (min-width: 320px) and (max-width:480px) {
  body {
    background-color: blue;
  }
}

@media screen and (min-width: 320px) and (max-width:480px) and (orientation: landscape) {
  body {
    background-color: green;
  }
}

@media screen and (max-width: 320px) {
  body {
    background-color: red;
  }
}

Media Queries Example

Increase or decrease the size of of this window to see the background color change


text:
Q: How to set different paths for view helpers? I'm developing a modular application with Zend Framework and I find that I use a lot of view helpers that are common across all my modules, I would like to have the following structure work, where I have a central location of view helpers to use in any module plus each module having its own view helpers, is this possible?
APPLICATION_PATH
    /modules/module1/views/helpers
    /modules/module2/views/helpers
    /modules/module3/views/helpers
    /views/helpers <-- central location for all modules

A: Thank you joellord for your help, based on the information given by joellord I was able to load view helpers from a central location plus the view helpers located in each of my modules. I added the following to my main application bootstrap file:
public function _initView(){
    $view = new Zend_View($this->getOptions());

    $view->setEncoding('UTF-8');
    $view->addHelperPath(APPLICATION_PATH.'/helpers/', 'Application_Helpers_');
     $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
        'ViewRenderer'
    );
    $viewRenderer->setView($view);
    return $view;
}

A: In my Bootstrap, I have the following function:
protected function _initView() {
  $view->addHelperPath(APPLICATION_PATH."/../library/Myapp/View/Helper/", 'Myapp_View_Helper_');
  }

That helps me achieve what I think you want.  My general helpers are all located in /library/Myapp/View/Helper


text:
Q: How to realize by pandas 'two sql result merge together ' I have two dataframe like this:
A:
         pay  num
store
A001         医保   43
A001         微信   25
A001        支付宝    6
A001         现金   25
A001         通联    1
A002         医保   21
A002         微信   38
A002        支付宝   11
A002         现金   53
A003         医保   22
...
AC24         微信   29
AC24        支付宝   15
AC24         现金   51
AC3H         微信    7
AC3H         现金   15

B:
       pay  num
store
A001    医保   43
A001    微信   25
A001   支付宝    6
A001    通联    1
A002    医保   21
A002    微信   38
A002   支付宝   11
A002    现金   53
A003    医保   22
...
AC24    微信   29
AC24   支付宝   15
AC24    现金   51
AC3H    微信    7
AC3H    现金   15

I  want  merge  A and B together by A.(store+pay)==B.(store+pay), A and B length don't same, use pandas how to realize this?

A: I believe you need create MultiIndex by add pay to original index by DataFrame.set_index and parameter append=True, then use Series.add and last Series.reset_index:
a = A.set_index('pay', append=True)['num']
b = B.set_index('pay', append=True)['num']

df = a.add(b, fill_value=0).reset_index(level=1)


text:
Q: How do I get rid of extra Black Mushrooms? I was told to submit this as a question... I've been trying to get rid of my Four Black mushrooms in my stash but I have no clue how to... any help is welcome...I have tried Salvaging them, but can't. I have also attempted to sell them, but that doesn't work. I've tried asking for help on the general chat, but was only told what they were used for. I tried posting it in a Diablo 3 forum, but have not gotten a response... I don't know where I'm supposed to get the other items to create the staff. I have a Diablo 3 game... please help me.

A: There are 2 ways to get rid of the extra Black Mushrooms:

*

*Toss it(throw in on the ground) and forget it

*Create a new hero, give all the unwanted items to him, then delete this hero

A: If an item is unsellable and unsalvageable then you can throw it away. You can do this as simply as dragging it from your inventory to the main screen to drop it on the floor and then ignoring it until it goes away. I would assume it will be lost when you reload your game but it may be that progressing through quests or other things will also cause dropped items to disappear - I'm not really sure on that but it will be guaranteed gone by the next time you play the game. :)

A: With the Black Mushroom you can create the Staff of Herding.
List of requirements for the staff and its upgrades:
Staff of Herding: Requires

*

*Black Mushroom

*Wirt's Bell

*Liquid Rainbow

*Gibbering Gemstone

*Leoric's Shinbone

*a 50,000 gold crafting cost

Nightmarish Staff of Herding: Requires the Staff of Herding and a 200,000 gold crafting cost
Hellish Staff of Herding: Requires the Nightmarish Staff of Herding and a 500,000 gold crafting cost
Infernal Staff of Herding: Requires the Hellish Staff of Herding and a 1,000,000 gold crafting cost
The total cost to craft the final version, the Infernal Staff of Herding, is 1,750,000 gold.
It has also been confirmed that the staff is used to get to the secret level.
Here is a link with a list where all the items can be found.

A: Black Mushroom is part of the ingredient to create Staff of Herding, you only require 1 so you can just throw the extra away. The staff is use to unlock a secret dungeon in Act 1 called Whimsyshire.
Ingredients to create the staff are as follow:

*

*Black Mushroom - Found rarely in a room on Cathedral level one, in early Act One.

*Leoric's Shinbone - Found rarely in the fireplace in Leoric's Manor, in late Act One.

*Wirt's Bell - An Act II vendor (Squirt) sells it for 100,000 gold on her Potions and Dyes tab.

*Liquid Rainbow - Spawns in the Mysterious Cave in the Mysterious Chest in the Oasis, Act 2.

*Gibbering Gemstone - Random drop from Chiltara in the Caverns of Frost, Level 2, Act 3.

*Plan: Staff of Herding - To teach the recipe to Haedrig. Drops randomly from Izual, Act 4.

More detail on how to acquire ingredients are here.
On previous version you are able to upgrade the staff to use in different difficulty, however with current update is not necessary anymore nor can you upgrade it.


text:
Q: How to Append Multiple Lists in a "For" Loop Vertically? My "for" loop is scraping from multiple pages (in this case, three that I put into a list). But the print output/csv output is not picking up the previous iterations through the loop (it's only giving me the results of the final, third page). I think the term I'm looking for here is "array" as I'd like each of the page's results to append vertically to each other. I seem to be misinterpreting how this function is working:
results.append(details)
This is all thanks to QHarr's excellent answer found here: How Can I Export Scraped Data to Excel Horizontally?
Here is the full, working code I am using:
import requests, re
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
import time

examplelist = [['1'], ['2'], ['3']]

pages = [i for I in examplelist for i in I]

for key in pages:
    driver = webdriver.Chrome(executable_path=r"C:\Users\User\Downloads\chromedriver_win32\chromedriver.exe")
    driver.get('https://www.restaurant.com/listing?&&st=KS&p=KS&p=PA&page=' + str(key) + '&&searchradius=50&loc=10021')
    time.sleep(10)
    WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".restaurants")))
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    restaurants = soup.select('.restaurants')
    results = []
    for restaurant in restaurants:
        details = [re.sub(r'\s{2,}|[,]', '', i) for i in restaurant.select_one('h3 + p').text.strip().split('\n') if i != '']
        details.insert(0, restaurant.select_one('h3 a').text)
        results.append(details)
#print(results)

df = pd.DataFrame(results, columns= ['Name', 'Address', 'City', 'State', 'Zip', 'Phone', 'AdditionalInfo'])
df.to_csv(r'C:\Users\User\Documents\Restaurants.csv', sep=',', encoding='utf-8-sig', index = False)

driver.close()

Thanks

A: I think you keep emptying results with results = [] inside the loop and so you lose what you've already put in there. Initialize outside of the loop like so
results=[]
for key in pages:
    driver = webdriver.Chrome(executable_path=r"C:\Users\User\Downloads\chromedriver_win32\chromedriver.exe")
    driver.get('https://www.restaurant.com/listing?&&st=KS&p=KS&p=PA&page=' + str(key) + '&&searchradius=50&loc=10021')
    time.sleep(10)
    WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".restaurants")))
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    restaurants = soup.select('.restaurants')
    for restaurant in restaurants:
        details = [re.sub(r'\s{2,}|[,]', '', i) for i in restaurant.select_one('h3 + p').text.strip().split('\n') if i != '']
        details.insert(0, restaurant.select_one('h3 a').text)
        results.append(details)
#print(results)

and remove that initialization from inside the loop.


text:
Q: Accessing caller information quickly I'm working on an aspectj aspect which needs to know where it's invoked from.  At the moment I'm using
new Throwable().getStackTrace();

to access this information but each aspect is taking several hundred microseconds to run.
I've looked at the SecurityManager but that only seems to be able to get me the class name.
Are there any other alternatives I've missed?
Update
JMH Benchmark results referred to in my comment on @apangin's answer:
Benchmark                       Mode  Cnt      Score    Error  Units
MyBenchmark.javalangaccess13i   avgt  100   2025.865 ±  8.133  ns/op
MyBenchmark.javalangaccess2i    avgt  100   2648.598 ± 24.369  ns/op
MyBenchmark.throwable1          avgt  100  12706.978 ± 84.651  ns/op

Benchmark code:
@Benchmark
public StackTraceElement[] throwable1() {
    return new Throwable().getStackTrace();
}

@SuppressWarnings("restriction")
@Benchmark
public static StackTraceElement javalangaccess2i() {
    Exception e = new Exception();
    return sun.misc.SharedSecrets.getJavaLangAccess().getStackTraceElement(e, 2);
}

@SuppressWarnings("restriction")
@Benchmark
public static StackTraceElement javalangaccess13i() {
    Exception e = new Exception();
    return sun.misc.SharedSecrets.getJavaLangAccess().getStackTraceElement(e, 13);
}

Tests run under Windows 10, JDK 1.8.0_112 on a Dell XPS13 9343 (i5-5200U @ 2.2GHz)

A: Unfortunately, Throwable.getStackTrace() seems to be the only viable option to get the caller frame in pure Java 8.
However, there is a JDK-specific trick to access just one selected stack frame.
It uses non-standard sun.misc.SharedSecrets API.
public static StackTraceElement getCaller() {
    Exception e = new Exception();
    return sun.misc.SharedSecrets.getJavaLangAccess().getStackTraceElement(e, 2);
}

Here 2 is the index of the required frame.
This works fine until the latest JDK 8, but private API will not be accessible in JDK 9. A good news is that Java 9 will have new standard Stack-Walking API. Here is how to do the same in Java 9.
public static StackWalker.StackFrame getCaller() {
    return StackWalker.getInstance(Collections.emptySet(), 3)
            .walk(s -> s.skip(2).findFirst())
            .orElse(null);
}

The alternative option, that works well for both older and newer versions of Java, is JVMTI GetStackTrace function. It requires linking native code though.

A: You are talking about AspectJ. So you do not need any reflection but can just use on-board AspectJ means such as thisEnclosingJoinPointStaticPart.getSignature() in combination with a call() pointcut:
Driver application:
package de.scrum_master.app;

public class Application {
    private static final long NUM_LOOPS = 1000 * 1000;

    public static void main(String[] args) {
        Application application = new Application();

        long startTime = System.nanoTime();
        for (long i = 0; i < NUM_LOOPS; i++)
            application.doSomething();
        System.out.printf(
            "%-40s  |  %8.3f ms%n",
            "AspectJ thisEnclosingJoinPointStaticPart",
            (System.nanoTime() - startTime) / 1.0e6
        );

        startTime = System.nanoTime();
        for (long i = 0; i < NUM_LOOPS; i++)
            application.doSomething2();
        System.out.printf(
            "%-40s  |  %8.3f ms%n",
            "Throwable.getStackTrace",
            (System.nanoTime() - startTime) / 1.0e6
        );

        startTime = System.nanoTime();
        for (long i = 0; i < NUM_LOOPS; i++)
            application.doSomething3();
        System.out.printf(
            "%-40s  |  %8.3f ms%n",
            "SharedSecrets.getJavaLangAccess",
            (System.nanoTime() - startTime) / 1.0e6
        );
    }

    public void doSomething() {}
    public void doSomething2() {}
    public void doSomething3() {}
}

Aspect:
package de.scrum_master.aspect;

import de.scrum_master.app.Application;
import sun.misc.SharedSecrets;

public aspect MyAspect {
    before() : call(* Application.doSomething()) {
        Object o = thisEnclosingJoinPointStaticPart.getSignature();
        //System.out.println(o);
    }

    before() : call(* Application.doSomething2()) {
        Object o = new Throwable().getStackTrace()[1];
        //System.out.println(o);
    }

    before() : call(* Application.doSomething3()) {
        Object o = SharedSecrets.getJavaLangAccess().getStackTraceElement(new Throwable(), 1);
        //System.out.println(o);
    }
}

Console log:
AspectJ thisEnclosingJoinPointStaticPart  |     7,246 ms
Throwable.getStackTrace                   |  1852,895 ms
SharedSecrets.getJavaLangAccess           |  1043,050 ms

As you can see, AspectJ is about 140x faster than the next best reflection-based method.
BTW, if you uncomment the print statements in the aspect, you see these three types of output:
void de.scrum_master.app.Application.main(String[])
de.scrum_master.app.Application.main(Application.java:16)
de.scrum_master.app.Application.main(Application.java:21)

Enjoy!


text:
Q: Errors running laravel 5 under docker I try to install laravel 5.0/mysql"5.5"/php_version under docker and I can not site in browser and make seeding of app:
I have 3 config files:
docker-compose.yml :
version: '3.1'

services:

    youtube_api_demo_app:
        build:
            context: ./web
            dockerfile: Dockerfile.yml

        container_name: youtube_api_demo_app_container
        environment:
            - APACHE_RUN_USER=#1000
        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        ports:
            - 8085:80
        working_dir: ${APP_PTH_CONTAINER}

    db:
        image: mysql:5.5.62
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: 1
        volumes:
            - ${DB_PATH_HOST}:/var/lib/mysql

    adminer:
        image: adminer
        restart: always
        ports:
            - 8086:8080
        links:
            - db

    youtube_api_demo_composer:
        image: composer:1.6
        container_name: youtube_api_demo_composer_container
        volumes:
            - ${APP_PATH_HOST}:${APP_PTH_CONTAINER}
        working_dir: ${APP_PTH_CONTAINER}
        command: composer install --ignore-platform-reqs

.env:
# PATHS
DB_PATH_HOST=./databases
APP_PATH_HOST=./YoutubeAPI_Demo
APP_PTH_CONTAINER=/var/www/html/

web/Dockerfile.yml:
FROM php:5.6-apache
RUN apt-get update -y && apt-get install -y libpng-dev   nano  libmcrypt-dev
RUN docker-php-ext-install \
    pdo_mysql \
    mcrypt \
    && a2enmod \
    rewrite

and env of my app /YoutubeAPI_Demo/.env :

APP_NAME=Laravel APP_ENV=local
  APP_KEY=base64:4+BRJbKtSQ7Z7yBVkYxe+NxfLkVPBAG2Gm1I93Qwukc=
  APP_DEBUG=true APP_URL=http://127.0.0.1:8085/ APP_SUBDIRECTORY=
LOG_CHANNEL=stack
DB_USERNAME=root DB_PASSWORD=1 DB_CONNECTION=mysql
  DB_HOST=127.0.0.1:8086 DB_PORT=:8086 DB_DATABASE=youtube_api_demo

I am not sure if I set valid DB_HOST and DB_PORT parameters, actually I tried different.
1) I builded the app and entered the console, but I got error migrating:
# php artisan migrate
  [PDOException]
  SQLSTATE[HY000] [2002] Connection refused

But I entered adminer and created the db: https://imgur.com/a/ePBfMiv
2) Entering in browser http://127.0.0.1:8085/ I got error :
You don't have permission to access / on this server.
Apache/2.4.25 (Debian) Server at 127.0.0.1 Port 8085

 docker ps
CONTAINER ID        IMAGE                                  COMMAND                  CREATED             STATUS                          PORTS                    NAMES
a51ccd12ae40        adminer                                "entrypoint.sh docke…"   About an hour ago   Up About an hour                0.0.0.0:8086->8080/tcp   youtubeapi_demo_adminer_1
7f9ee8f14c9d        mysql:5.5.62                           "docker-entrypoint.s…"   About an hour ago   Up About an hour                3306/tcp                 youtubeapi_demo_db_1
b2c47edaf616        youtubeapi_demo_youtube_api_demo_app   "docker-php-entrypoi…"   About an hour ago   Up About an hour                0.0.0.0:8085->80/tcp     youtube_api_demo_app_container
3dcc1a4ce8f0        adminer                                "entrypoint.sh docke…"   5 weeks ago         Up 4 hours                      0.0.0.0:8083->8080/tcp   lprods_adminer_container
933d9fffaf76        postgres:9.6.10-alpine                 "docker-entrypoint.s…"   5 weeks ago         Up 4 hours                      0.0.0.0:5433->5432/tcp   lprods_db_container
2f73a600b999        adminer                                "entrypoint.sh docke…"   6 weeks ago         Up 4 hours                      0.0.0.0:8082->8080/tcp   votes_docker_adminer_1
52ea479b8791        mysql:5.6.41                           "docker-entrypoint.s…"   6 weeks ago         Restarting (1) 34 seconds ago                            votes_docker_db_1

What are wrong in config options ?
Thanks!

A: 1) In .env: you can use :
DB_CONNECTION=mysql
DB_HOST=db // THAT IS MYSQL container name
DB_PORT=3306

2) Try url
http://127.0.0.1:8085/public

with usual laravel 5 dirs settings


text:
Q: Unzip a zipped file that is saved using name and date of download like this (Query Transaction History_20221126.zip) I have a data related problem,
I want to unzip a file in my download folder.
This zip file is for daily use, meaning that is something I will keep downloading on a daily basis and the zip folder name usually contain date and time of download as the folder name.
This is how the zip folder name usually looks like below.
Query Transaction History_20221125035935_42217.zip
and the excel file in the folder comes like this
Query Transaction History_20221126035617_01.xls
If you check closely the name for the both the zip file and xls are combination of name(Query Transaction History_) and date and time of the download (20221126035617_01)
So I was able to come up with the script below.
library(plyr)

my_dir<-"C:/Users/Guest 1/Downloads"

zip_files <-list.files(path ="C:/Users/Guest 1/Downloads",
    pattern ="Query Transaction History_20221126.*zip",full.names = TRUE )

 ldply(.data =zip_files,.fun = unzip,exdir =my_dir )

it works fine and extract the file to the download folder. But it is something that i will be keep doing on a daily basis and the date will keep changing while the name is constatcnt so i tried this code.
library(glue)

sea<-format(Sys.Date(),"%Y%m%d") #formatting date to suit the date attached to zip file

zip_files <-list.files(path ="C:/Users/Guest 1/Downloads",
    pattern =glue("Query Transaction History_{sea}.*zip",full.names = TRUE )) #using glue to glue the date variable and attached it to the zipped file and run.

It works fine
Now to unzip using apply function below
 ldply(.data =zip_files,.fun = unzip,exdir =my_dir )#using apply to unzip

I get the error below
Warning message:
In FUN(X[[i]], ...) : error 1 in extracting from zip file

Thanks

A: With the zip files residing outside your getwd() you'll need to specify the full file path like so:
ldply(.data =zip_files,
      .fun = function(file_name){
                unzip(file.path("C:/Users/Guest 1/Downloads",
                                file_name),
                exdir = my_dir
                )
              }
)

Note: unless you require {plyr} anyway, you could just use base R sapply or Map instead of ldply.


text:
Q: Insert avoid duplicate same table I'm starting with SQL and programming as a whole.
I'm trying to insert some rows into my table, but I get an error if some row with same value already exists.
I need to add a record in the table "GPointBagCalender" a date for each LOGINUID, with SEALTYPE always equal to 4. The problem is that if I record a duplicate of LOGINUID and the date, it gives me an error of primary key.
I've tried IF NOT EXISTS
BEGIN
    IF NOT EXISTS (SELECT LoginUID, RegDate, SealType
                   FROM GPointBagCalender
                   WHERE RegDate = CONVERT(Datetime, '2018-07-25 01:32:00', 120))
    BEGIN
        INSERT INTO GPointBagCalender
            SELECT DISTINCT
                g.LoginUID,
                CONVERT(Datetime, '2018-07-25 01:32:00', 120), 4
            FROM
                GPointBag g
    END
END

and WHERE NOT EXISTS
INSERT INTO GPointBagCalender
    SELECT DISTINCT
        g.LoginUID, CONVERT(Datetime, '2018-07-25 01:32:00', 120), 4
    FROM
        GPointBag g
    WHERE
        NOT EXISTS (SELECT LoginUID, RegDate, SealType
                    FROM GPointBagCalender
                    WHERE RegDate = CONVERT(Datetime, '2018-07-25 01:32:00', 120))

In WHERE NOT EXISTS case, I get "0 rows affected". In the IF NOT EXISTS case, it only executes the command, or if there's no one register matching the date, it records a row for each LOGINUID.
Appreciate any help.

A: I am assuming you're using MySQL, but this should work on most DBs.
Use: INSERT IGNORE INTO which will silently ignore errors when encountering duplicate records.

A: You can do what you intend with:
INSERT INTO GPointBagCalender ( . . . ) -- list the columns here
    SELECT DISTINCT g.LoginUID,
       CONVERT(Datetime, '2018-07-25 01:32:00', 120), 4
    FROM GPointBag g
    WHERE NOT EXISTS (SELECT LoginUID, RegDate, SealType
                      FROM GPointBagCalender gbc
                      WHERE gbc.LongUID = g.LoginUID AND
                            RegDate = CONVERT(Datetime, '2018-07-25 01:32:00', 120)
                     );


text:
Q: Having trouble getting value from server in lightning component component
<aura:component controller="AudioController">
    <aura:attribute name="setMeOnInit" type="String" default="default value" />
    <aura:handler name="init" value="{!this}" action="{!c.getRecURL}"/>

{!v.setMeOnInit}

</aura:component>

Server controller
public class AudioController {

 @AuraEnabled
    public static String getRecURLdata() {
        Contract c = [SELECT Id, recURL__c FROM Contract WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
        return 'hello from cont';
    }

}

Client controller
({
    "getRecURL" : function(cmp) {
        var action = cmp.get("c.getRecURLdata");

            action.setCallback(this, function(response) {
                cmp.set("v.setMeOnInit", response.getReturnValue());
            });

        $A.enqueueAction(action);
    }
})

These are mostly just test values. I'm trying to get "hello from cont" to show up in the component

A: Your code was failing because ApexPages can only be used from Visualforce page context.
If you actually need Id from SObject in your controller, then what I would suggest is to use is to use force:hasRecordId. More on this interface you can read here. Then your code would look like this.
component.cmp:
<aura:component controller="AudioController" implements="force:hasRecordId">
    <aura:attribute name="setMeOnInit" type="String" default="default value" />
    <aura:handler name="init" value="{!this}" action="{!c.getRecURL}"/>

{!v.setMeOnInit}

</aura:component>

AudioController.cls:
public class AudioController {

    @AuraEnabled
    public static String getRecURLdata(final Id recordId) {
        if (recordId.getSObjectType() == null) {
            throw new AuraHandledException('RecordId is null');
        }
        if (recordId.getSObjectType() != Contract.getSObjectType()) {
            throw new AuraHandledException('Wrong SObject Type. Please use this component on Contract record page');
        }
        Contract c = [SELECT Id, Name FROM Contract WHERE Id = :recordId];
        return 'hello from cont';
    }

}

componentController.js:
({
    "getRecURL" : function(component) {
        var action = component.get("c.getRecURLdata");
        action.setParams({
            recordId: component.get('v.recordId')
        })

        console.log('Hello World');
        action.setCallback(this, $A.getCallback(function(response) {
            let state = response.getState();
            if (state === 'SUCCESS') {
                component.set("v.setMeOnInit", response.getReturnValue());
            } else {
                console.error(response.getError()[0].message);
            }
        }));

        $A.enqueueAction(action);
    }
})

And you will need to write tests for AudioController and can pass recordId directly as a parameter.
And won't need to manage Page parameters in your tests, which will lead to easier to read and maintain code.