text:
Q: php curl cannot find key I am trying to write a php curl script call an api, but the documentation (http://rest.ensembl.org/documentation/info/vep_region_post) only lists other languages and I am having trouble getting it to work in php curl.
In the documentation, an example call (which I confirmed works) in command line curl is:
curl 'http://rest.ensembl.org/vep/homo_sapiens/region' -H 'Content-type:application/json' \
-H 'Accept:application/json' -X POST -d '{ "variants" : ["21  26960070  rs116645811 G A . . .", "21  26965148  rs1135638 G A . . ." ] }'

My attempt at replicating this in php curl is:
$session = curl_init();
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($session, CURLOPT_POST, 1);
curl_setopt($session, CURLOPT_URL,'http://rest.ensembl.org/vep/homo_sapiens/region');
curl_setopt($session, CURLOPT_HTTPHEADER, array("Content-Type" => "application/json", "Accept" => "application/json"));
curl_setopt($session, CURLOPT_POSTFIELDS, '{ "variants" : ["21  26960070  rs116645811 G A . . .", "21  26965148  rs1135638 G A . . ." ] }');
echo(curl_exec($session));
curl_close($session);

The result I get is:
{"error":" Cannot find \"variants\" key in your POST. Please check the format of your message against the documentation"}
The problem seems to be with the CURLOPT_POSTFIELDS, but since the required argument appears to simply be a string and I am using the same string, I cannot tell how it is going wrong.

A: You cannot pass string with white spaces as POST string. You need to urlencode it:
curl_setopt($session, CURLOPT_POSTFIELDS, urlencode('{ "variants" : ["21  26960070  rs116645811 G A . . .", "21  26965148  rs1135638 G A . . ." ] }'));

A: The remote server cannot understand your request because it is delivered as:
Content-Type: application/x-www-form-urlencoded

which is the default Content-Type for POST requests.
This happens because your code fails to set the desired headers correctly. The PHP documentation explains:

CURLOPT_HTTPHEADER:   An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')

Set the headers in the correct way and it will work:
curl_setopt($session, CURLOPT_HTTPHEADER,
            array("Content-Type: application/json", "Accept: application/json"));

Remark: do not urlencode() the POST fields (as suggested by another answer); the data you send is not a query string.
Your Content-Type header says application/json, make sure the data you send is a correct JSON.


text:
Q: NoUniqueBeanDefinitionException while wiring up InternalResourceViewResolver I'm currently trying to get integration tests running in our Spring MVC project.
One of our components depends on the ViewResolver which gets autowired by Spring. It's configured in the test-context.xml:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

However, this gives me an NoUniqueBeanDefinitionException:
Caused by:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.web.servlet.ViewResolver' available: expected single matching bean but found 2: org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.web.servlet.view.InternalResourceViewResolver#1

When I remove the InternalResourceViewResolver property from the test-context.xml, I get a
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.servlet.ViewResolver' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

How can that happen?

redpajama_set_name: RedPajamaStackExchange


text:
Q: IR reciever's transmission distance I am trying to understand what it means by an IR receiver that has transmission range up to, say, for TSOP1738, 35m. For example, if the receiver's working at 38 kHz, how much sensitive would it be to IR LED transmitters that are way further away but working at the same modulated frequency with a much lower emitting range of a few centimeters? Does it ever detect them? I guess since it has a broad range, it should be able to detect any (even weak) 38 kHz wave circling around? In case it's gonna detect them at a long distance, how actually it does? Please clarify these for me.

A: This chip  uses AGC with a BPF with a Q of ~10 to improve the Signal/Noise Ratio and thus has a wide dynamic range for distance and rejection of noise.  A simple output comparator detects the pulsed Off duration of light relative to the peak which is regulated by AGC.  i.e. steady carrier =0. Pulsed off =1
The necessary conditions for a "0" active output are the IR wavelength ought to be 950nm  +/-100nm (50% loss), modulated at 38kHz ( 5% error reduces signal 50%) and sustained initially for 0.8ms then may be further modulated on/off with 600us bits or 1.67kbaud roughly, although 1200baud is ideal for range or >10 carrier cycles per bit.

The wide range of reception for distance is owing to the wide automatic gain control range (AGC) of burst pulses in a narrow bandwidth (Q=10) of pulses,  wavelength of light and built-in electromagnetic shielding of the Photo Detector (PD) and amplifier. A clean power supply is essential.

The lens gives some gain in the horizontal axis on center but still a total reception angle of ~130 deg at half power.
Path loss (like Friis loss for RF) follows an inverse squared dynamic loss measured with signal power sensitivity of 0.35 (typ)  mW/m².
The threshold for detection is fixed such that ambient noise is unlikely to trigger the duration of a start pattern needed to decode a command if there was any noisy output.  This requires a sustained modulation of 38kHz pulsed IR for at least 0.8ms to allow AGC to capture the signal before the data bit follow by varying the duty cycle.
It has high rejection of 100/120Hz flicker in addition to the black tinted "Daylight Blocking filter" which is transparent at IR wavelengths.

A: This device
http://www.batronix.com/pdf/tsop17xx.pdf
has an IR photodiode behind an IR filter. If some IR radiation is present, the diode starts to conduct and generates a voltage to "input circuit." That voltage is analyzed - has it remarkable enough percentage of 38 kHz fluctuation. If it has, then a positive detection is outputted as the LOW logic state.
35 meters is not the range of the receiver, it is the distance, how far away
TSOP1738 and IR diode TSIP5201 are promised to work together. 38 kHz version of TSOP1738 detects a proper 38 kHz pulsed IR radiation if its intensity at the receiver's aperture ( = the observed sector) is 0,35 mW /square meter or more and no other IR source rolls over the proper signal. TSOP1738 does not care (or more exactly: it doesn't know) how far or near the transmitter is. Detection can happen as well at 1m or 100 m, if there only is a transmitter powerful enough. TSOP1738 is promised to be so sensitive that IR diode TSIP5201 with 400 mA drive is promised to be powerful enough to be detectable at all distances from 0 to 35 m. If distance is longer than 35 m, some lucky individual (receiver or transmitter) can be in such way out of the tolerances that the detection still is possible without any additional optics, but not guaranteed. Adding some reflectors or lenses or changing a more powerful transmitter can easily increase the operating range.
What is strong enough to roll the right signal down. It can be read from the datasheet at least to some degree. For ex, figure 3 shows how the minimum detectable intensity of the proper signal rises when the ambient same wavelength IR radiation intensity grows.
This device gives no other information than "Is there a detectable amount of at the right frequency pulsed IR and at the same time low enough total intensity of disturbing IR signals" - Yes or no?
This device cannot make any difference between two sources of rightly pulsed signal. If you have two different 38 kHz pulsed IR sources and they send simultaneously, their interference can be unpredictable. It is possible that you see a rapid series of positive and negative detections which changes to continuous positive when one of the sources is stopped.
How a pulsed IR that has wrong frequency affects? And is it also detectable?. This demands complex calculations or testing. The latter is surely more reliable method due to the sparse available data about the filtering and detection process. For exact calculations this datasheet is not detailed enough, one need to make much assumptions. But a genuine communication theory engineer can well guess the details close enough.
You should note that the required intensity 0,35 mW/square meter can be produced from far away or from near. Transmitter's output power and how the radiation is directed by using reflectors or lenses affect. IR does not go thru walls, but an ordinary glass is still transparent enough for this device and mirrors work, too.
The radiation diverges to a larger area when it propagates. To double the detection distance without inserting any lenses or concave mirrors for bigger receiver's catching area or more narrow transmitting beam, you should quadruple the transmitting power. It can be surprising, how weak signal is detectable from near and how high transmitting power is needed from far away.

A: Assume 10 milliWatts of IR, emitted over +-19 degree cone; at 10meters, this +-19degree (1/3 of a radian) give +- 1/3*10m coverage in X and in Y, or 6.6meters in X and 6.6meters in Y, or area of 43 square meters.
Assume the receiving photodiode (sensitivity 1amp/watt, 1ua/uW) has lense of 5mm by 5mm. The photodiode energy is 10mW*(0.005m * 0.005m)/43meter^2 or 6 nanoWatts. Thus current is 6 nanoAmps.
Into a 100Kohm resistor, Vout is 600 microVoltsPP or 200uVrms. Assume 10pF capacitance at that node, with Vc=sqrt(K*T/C) telling us the noise floor is 20 microVolts due to 100Kohm. Photodiode shot noise is extra.
How good a signal is this? Bandwidth 1/2*piRC = 159KHz, certainly adequate for 38KHz "square wave" and some casual OOK on-off-keying data. The Signal Noise Ratio (SNR) is 200uVrms / 20uVrms = 10:1 or 20dB. For on-off modulation, your BitErrorRate BER gonna be very low, maybe 1 in a Trillion bits at 20dB SNR.
But you wanted 35 meters, not 10 meters. That reduces the power by 1/(3.5 * 3.5) or another factor of 10; the photodiode current reduces a factor of 10, and the voltage into the receiver also drops 10:1, and the SNR becomes 0 dB.
What is to be done? Narrow the bandwidth.
Consider using the Signetics/Philips/??? NE567 tone-decoder with internal Phase Locked Loop.
And have as your photodetector a photo-transistor, biased so the sunlight and 60Hz get nulled out, while the 38KHz comes thru strongly.


text:
Q: Computer Organization and Architecture A digital computer has a memory unit with 32 bits per word. The instruction set consists of 128 different operations. All instructions have an operation code part (opcode) and an address part (allowing for only one address). Each instruction is stored in one word of memory.
a. How many bits are needed for the opcode?
b. How many bits are left for the address part of the instruction?
c. What is the maximum allowable size for memory?

A: a. 7 bits, because 2^7 = 128 possible opcodes.
b. 25 bits, because 32 - 7 = 25.
c. 2^25 * 32 bits = 128 MB, because with 25 bits you can address at most 2^25 words and each word is 32 bits long.

A: I would not give you the ANSWERS but the HINT is that

*

*if there are 128 instructions to be handled by the processor, you should make room for each one instruction, meaning 128 unique instruction codes for them.

*Secondly, 32 - the above answer will give you the remaining bits

*Lastly, the total size would be rows * cols


text:
Q: .Net Core Identity External Login not working I have a website that has external logins set up for google. I have been successful in getting this to work in development, but when I moved to production it failed to work. When I click the button, instead of sending me to Google's account.google.com page, it just sends me to /Identity/Account/ExternalLogins with an error code of HTTP ERROR 400. The button is the same between production and environment. Other than the email sending portion, everything is the same as it was generated during scaffolding. My production environment uses Ubuntu and Nginx. What could be causing this? I have been unable to recreate the issue outside of production.
btw, this is the default button:
<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
    <button type="submit" class="btn btn-primary" name="provider" value="@provider.Name"
          title="Log in using your @provider.DisplayName account">@provider.DisplayName
    </button>
</form>

My button is the default google log-in button altered, but it works in development, so I don't think that it matters:
<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">

            <button class="abcRioButtonContentWrapper" style="border:inherit; background-color:white !important"
                    type="submit" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">

                    Sign in

            </button>

</form>

Here are the relevant parts of my Startup.cs with some stuff removed from ConfigureServices() for brevity:
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseMySql(Configuration.GetConnectionString("UserDB"), MySqlOptions => MySqlOptions
                .ServerVersion(new Version(8, 0, 22), ServerType.MySql)));

            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultUI()
                .AddDefaultTokenProviders();
            services.Configure<IdentityOptions>(options =>
            {
                options.SignIn.RequireConfirmedAccount = true;
                options.User.RequireUniqueEmail = true;
                options.User.AllowedUserNameCharacters =
                        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._";
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = true;
                options.Password.RequireUppercase = true;
                options.Password.RequiredLength = 8;
            });

            services.AddAuthentication()
                .AddGoogle(options =>
            {
                IConfigurationSection googleAuthNSection =
                    Configuration.GetSection("Authentication:Google");

                options.ClientId = googleAuthNSection["ClientId"];
                options.ClientSecret = googleAuthNSection["ClientSecret"];
            });

            services.AddServerSideBlazor();
            services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            ConnectionString = Configuration["ConnectionStrings:DataDB"];

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHeadElementServerPrerendering();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }

After some more investigation and setting logging to trace, I found the error of:

Connection id "0HM5SB235ONN8" bad request data: "Requests with 'Connection: Upgrade' cannot have content in the request body."

I think is is because of my sites-enabled/default file that I had to configure this way according to the official Blazor deployment docs:
        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                proxy_pass http://localhost:5000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header Connection $http_connection;
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

A: The issue was in my nginx file, I had incorrectly set it up for hosting. I changed it to the following and it worked:
map $http_connection $connection_upgrade {
     "~*Upgrade" $http_connection;
    default keep-alive;
}

server {
    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html;
        server_name domain.us;

    location / {
        proxy_pass         http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection $connection_upgrade;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

And then I changed my Startup.cs to include:
if (string.Equals(
            Environment.GetEnvironmentVariable("ASPNETCORE_FORWARDEDHEADERS_ENABLED"),
            "true", StringComparison.OrdinalIgnoreCase))
            {
                services.Configure<ForwardedHeadersOptions>(options =>
                {
                    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                        ForwardedHeaders.XForwardedProto;
                    // Only loopback proxies are allowed by default.
                    // Clear that restriction because forwarders are enabled by explicit
                    // configuration.
                    options.KnownNetworks.Clear();
                    options.KnownProxies.Clear();
                });
            }
//#################
 app.UseForwardedHeaders();
 app.UseCookiePolicy(new CookiePolicyOptions(){
    MinimumSameSitePolicy = SameSiteMode.Lax
 });
 app.UseCertificateForwarding();


text:
Q: ui.bootstrap popover close on click I have this popover with template
 Add new external reference

So when I click on that link icon, a popover opens witht this tamplate

When I press that 'floppy' icon, I'd like to close the popover. Are there any ways of doing this?
All I can find on documentation is the popover-is-open value, but I don't know if I can use this somehow, any thoughts?

A: What had worked for me (in an angularJs app) is using

popover-trigger="'outsideClick'"

be aware to use it as it is, means, hard copy of string

"'outsideClick'".

If u don't use angularJs, u can just write:

popover-trigger="outsideClick"

Example:

    Approve

A: Step 1 : Add popover-is-open="isOpen" to the trigger link.
 Add new external reference

Step 2 : When you click the floppy icon inside the popover, set isOpen to false:
This is the save icon of the popover:
 Save

This is in the controller:
$scope.save = function () {
  $scope.isOpen = false;
};

See plunker


text:
Q: mimic The "to" option in messaging WP7 I want to mimic the system's "to" textbox that when you start writing in it , it displays the names and accounts that's associated with the user
I don't know if there's already built in in the development tools or I have to implement it, any ideas ?

A: I'd recommend building your own control that is special-purpose built, as opposed to using something like the AutoCompleteBox control from the Toolkit (that is a big challenge to template or customize like your would like to do).
The ACB only offers single selection, while the To: line in Mail/Messaging effectively allows for many items.
Sorry that there isn't anything built into the platform for this.
Disclaimer: Yes, I wrote the original AutoCompleteBox control for Silverlight, and yes it didn't port well to WP7 (though I did not do that work).


text:
Q: regex for float with 6 decimals and 3 numbers I need a regex for a float number positive or negative with a maximum of 3 numbers before the decimal separator and 6 (only 6) numbers after.
Can anyone help me?

A: In JavaScript - this will match what you want. But without further clarification there's nothing more to be done:
/[+|-][0-9]{0,3}\.[0-9]{6}/g

Cheers.

A: It's Perl regex flavour.
For java script : /[+|-]\d{1,3}\.\d{6}/
For java : "[+|-]\\d{1,3}\.\\d{6}" /* Use pattern and matcher in java.util.regex.*/


text:
Q: Solvability of the Pell-like equation $x^{2}-dy^{2} = k$ I found some resources that talk about algorithms for finding fundamental solutions to the Pell-like equation
$$ x^{2} - dy^{2} = k $$
for $d \in \mathbb{N}$ and $k \in \mathbb{Z}$. However, I'm struggling to find results (if there are any) that will tell me if the above equation is solvable given certain $d,k$. A quick search on Math.SE yields a bunch of questions about specific Pell-like equations.... Does anyone have any good resources/papers related to this question? Any help is greatly appreciated.

A: You have not said anything about the size of $k.$     So: if you can find a (even) number $\beta$   such that $$ \beta^2 \equiv 4d \pmod {4k}, $$ so that
$$ \beta^2 = 4d + 4kt $$
for integer $t.$ So, the discriminant of binary form
$$ f(x,y) = k y^2 + \beta xy -t y^2 $$
is $4d.$ There is a process for reducing an indefinite binary form and seeing what class it is in. If $f$ is equivalent to $x^2 - d y^2,$ then $k$ is (primitively) represented by $x^2 - d y^2.$  This does require knowing how to find the complete cycle of a reduced indefinite form. I got the whole business from BUELL
added: let us take notation
$$   \langle a, b, c \rangle  $$
to refer to the quadratic form
$$ f(x,y) = a x^2 + b xy + c y^2 $$
The discriminant is $\Delta = b^2 - 4ac.$ When this is positive but not a square, the form is indefinite. Buell gives the original definition of Gauss and Lagrange for when such a form is reduced.
Proposition: the indefinite (integer coefficient) form $   \langle a, b, c \rangle  $  is reduced if and only if both
$$  ac < 0 \; \; \; \; \; \mbox{AND}  \; \; \; \; \; \; b > |a+c| $$
I know of just one book where this is printed, by Franz Lemmermeyer, who is active on this site and MO. I should give an example, most people haven't seen the cycles of reduced forms:
=========================================
jagy@phobeusjunior:~/old drive/home/jagy/Cplusplus$ ./indefCycle 5 164 15

  0  form              5         164          15  delta     10
  1  form             15         136        -135

           0          -1
           1          10

To Return
          10           1
          -1           0

0  form   15 136 -135   delta  -1
1  form   -135 134 16   delta  9
2  form   16 154 -45   delta  -3
3  form   -45 116 73   delta  1
4  form   73 30 -88   delta  -1
5  form   -88 146 15   delta  10
6  form   15 154 -48   delta  -3
7  form   -48 134 45   delta  3
8  form   45 136 -45   delta  -3
9  form   -45 134 48   delta  3
10  form   48 154 -15   delta  -10
11  form   -15 146 88   delta  1
12  form   88 30 -73   delta  -1
13  form   -73 116 45   delta  3
14  form   45 154 -16   delta  -9
15  form   -16 134 135   delta  1
16  form   135 136 -15   delta  -9
17  form   -15 134 144   delta  1
18  form   144 154 -5   delta  -31
19  form   -5 156 113   delta  1
20  form   113 70 -48   delta  -2
21  form   -48 122 61   delta  2
22  form   61 122 -48   delta  -2     ambiguous
23  form   -48 70 113   delta  1
24  form   113 156 -5   delta  -31
25  form   -5 154 144   delta  1
26  form   144 134 -15   delta  -9
27  form   -15 136 135   delta  1          -1 composed with form zero
28  form   135 134 -16   delta  -9
29  form   -16 154 45   delta  3
30  form   45 116 -73   delta  -1
31  form   -73 30 88   delta  1
32  form   88 146 -15   delta  -10
33  form   -15 154 48   delta  3
34  form   48 134 -45   delta  -3
35  form   -45 136 45   delta  3
36  form   45 134 -48   delta  -3
37  form   -48 154 15   delta  10
38  form   15 146 -88   delta  -1
39  form   -88 30 73   delta  1
40  form   73 116 -45   delta  -3
41  form   -45 154 16   delta  9
42  form   16 134 -135   delta  -1
43  form   -135 136 15   delta  9
44  form   15 134 -144   delta  -1
45  form   -144 154 5   delta  31
46  form   5 156 -113   delta  -1
47  form   -113 70 48   delta  2
48  form   48 122 -61   delta  -2
49  form   -61 122 48   delta  2     ambiguous
50  form   48 70 -113   delta  -1
51  form   -113 156 5   delta  31
52  form   5 154 -144   delta  -1
53  form   -144 134 15   delta  9
54  form   15 136 -135

  form   15 x^2  + 136 x y  -135 y^2

minimum was   5rep   x = -657408301   y = -728220430 disc 26596 dSqrt 163  M_Ratio  118.0844
Automorph, written on right of Gram matrix:
-3412169357059562966992118401  -34017372299466365140228887000
-3779708033274040571136543000  -37681522192077530811963441601
=========================================

A: You have to pick the values of your variables but it's not hard to see what they need to be to yield integers once $solutions$ are seen.
$$x=\pm\sqrt{k+dy^2}\quad \land \quad y=\frac{\sqrt{x^2-k}}{\sqrt{d}}$$
For example
$$x=\sqrt{2+2(7)^2}=10\quad\land\quad y=\frac{\sqrt{5^2-9}}{\sqrt{4}}=2$$


text:
Q: ASP.NET MVC3 Binding to a collection does not generate client side validation I have the following model:
public class FacturaIntrareModel
    {
        private List<DetaliiFacturaIntrareModel> _produse = new List<DetaliiFacturaIntrareModel>();
        public List<DetaliiFacturaIntrareModel> Produse
        {
            get { return _produse; }
            set { _produse = value; }
        }
    }

public class DetaliiFacturaIntrareModel
    {

        [Range(0, double.MaxValue, ErrorMessage = "The Discount must have positive values!")]
        public decimal Discount { get; set;}

    }

The code for the binding is this:
@model  FacturaIntrareModel
@using DevExpress.Data
@Html.DevExpress().GridView(settings =>
{

    settings.Columns.Add(col =>
    {
        col.FieldName = produsId;

        col.Caption = "Discount";
        col.ColumnType = MVCxGridViewColumnType.Default;
        col.SetDataItemTemplateContent
            (c =>
            {
                string idProdus = DataBinder.Eval(c.DataItem, produsId).ToString();
                var index = Model.Produse.FindIndex(y => y.IdProdus.ToString() == idProdus);
                ViewContext.Writer.Write
                    (
                        @Html.TextBoxWithCustomHtmlAttributesFor(x => x.Produse[index].Discount, new { @onchange = "setDiscountProdus(" + idProdus + ", $(this).val())", @style = textBoxWitxh }).ToHtmlString()
                        +
                        @Html.ValidationImageWithTooltipFor(x => x.Produse[index].Discount).ToHtmlString()

                    );
            }
            );
        col.Width = texBoxColWidth;
        col.CellStyle.HorizontalAlign = textBoxColAlign;

    });

}
            ).Bind(Model.Produse).GetHtml()

The html generated for DISCOUNT is:
<input data-type="decimal" id="Produse_1__Discount" name="Produse[1].Discount" onchange="setDiscountProdus(2, $(this).val())" style="width:40px;" type="text" value="2">

No html annotations for the RANGE annotation have been generated.


text:
Q: pouchdb not working on ios safari I am trying to write a cordova application that uses pouchdb as offline DB (without sqlite). my app works from all browsers and from android but not ios. am not sure why is that and what to do to fi it! here is my code to initialise the db:
app.onDeviceReady = function() {
try {
    console.log("starting db");
    window.offline_db = new PouchDB('offline_db');
    if (window.offline_db.adapter) {
        console.log("db started!");
    }
    offline_db.get("op_settings", function(err, doc) {
        if (err) {
            return console.log(err);
        }
        console.log(doc);
    });
} catch (e) {
    console.log(e);
}};

this does not return the doc, even though when I save the doc it says it was saved successfully, it only gives a promise but no result.
Also on safari Mac I can see the db content in debugger, but on safari ios I dont have this tab under resources

A: It seems, that you have put your callback function on the place of options to be passed(optional):
PouchDB get
Please try
offline_db.get("op_settings", null, function(err, doc)

it should work.


text:
Q: How to add a List with widgets to Shared Preferences in Flutter? How do i save List of widgets data into the users phone offline without using online.Can I use shared preferences to save data List of widgets or is there any other method.What actually I was doing is I want to save the list and show again when user returns back to my app but now the app forgets data with empty list.
class AlarmData extends ChangeNotifier {
    List<Alarm> _alarms = [
        Alarm(time:'04:05:06'),
        Alarm(time:'04:05:06'),
        Alarm(time:'04:05:06'),
    ];

    UnmodifiableListView<Alarm> get alarms{
        return UnmodifiableListView(_alarms);
    }

    void addAlarm(String newTaskTitle) {
        final task = Alarm(time: newTaskTitle);
        _alarms.add(task);
        notifyListeners();
    }

    void updateAlarm(Alarm task) {
        task.toggleDone();
        notifyListeners();
    }

    void deleteAlarm(Alarm task) {
        _alarms.remove(task);
        notifyListeners();
    }

    int get alarmCount {
        return alarms.length;
    }
}

Thanks in advance I am new to flutter development.

A: One way I could think of is encoding them as Json and saving them as String in either sharedPreferences or as a file in the app directory (using path_provider)
class Alarm{
  final String time;
  Alarm({this.time});

  @override
  toString(){
    return 'time: $time';
  }

  Map<String, dynamic> toJson() => {
    'time': this.time
  };

  factory Alarm.fromJson(Map<String, dynamic> alarm) => Alarm(
    time: alarm["time"],
  );

}

your class Alarm need fromJson and toJson to made the encoding/decoding correctly. I don't know if it has other parameters but you could add them easy in the constructor and the from/to Json
//You could put this method inside AlarmData if you want to save it everytime you update your changeNotifier
Future<void> saveAlarms(List<Alarm> alarms) async{
  //Option 1 using SharedPreferences
  final SharedPreferences preferences = await SharedPreferences.getInstance();
  final String jsonEncoded = json.encode(alarms);
  await preferences.setString('MyAlarms', jsonEncoded);

  //Option 2 saving a json file in the documentsDirectory of the App
  final Directory appDocDir = await getApplicationDocumentsDirectory();
  final file = File('${appDocDir.path}/MyAlarms.json');
  await file.writeAsString(jsonEncoded);
}

Future<List<Alarm>> get retrieveAlarms async{
  //Option 1 using SharedPreferences
  final SharedPreferences preferences = await SharedPreferences.getInstance();
  final String myAlarms = await preferences.getString('MyAlarms');
  if(myAlarms?.isEmpty ?? true) return <Alarm>[]; //check for null or empty values

  final alarms = json.decode(myAlarms) as List;
  return List<Alarm>.from(alarms.map((x) => Alarm.fromJson(x)));

  //Option 2 saving a json file in the documentsDirectory of the App
  final Directory appDocDir = await getApplicationDocumentsDirectory();
  final readFile = File('${appDocDir.path}/MyAlarms.json');
  if(!(await readFile.exists())) return <Alarm>[]; //check if the file exists
  String jsonAlarms = await readFile.readAsString();
  final jResult = jsonDecode(jsonAlarms) as List;

  return List<Alarm>.from(jResult.map((x) => Alarm.fromJson(x)));

}

now your AlarmData needs a constructor where you give it the list of alarms saved
class AlarmData extends ChangeNotifier{
  List<Alarm> _alarms;

  AlarmData(this._alarms);
  ...
}

You either complete the future retrieveAlarms in the main if you need it at the beggining of the app or just before the AlarmData
 Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final myAlarms = await retrieveAlarms;
  runApp(const HomePage(myAlarms)); //if you want to use it as soon as possible
}

If you don't mind using another package I would recommend using Hive, it allows you to store objects and primitive values (just like sharedPreferences)
@HiveType(typeId: 0)
class Alarms extends HiveObject {

  @HiveField(0)
  String time;
}

Future<void> _initHive() async {
  final appDocumentDir  = await getApplicationDocumentsDirectory();
  Hive.init(appDocumentDir.path);
  Hive.registerAdapter<Alarms>(AlarmsAdapter()); //check the documentation of hive about how to generate this file
  await Hive.openBox<Alarms>('Alarm'); //a box where all your alarms are
}

Future<void> main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await _initHive(); //if you want to use it as soon as possible
    runApp(const HomePage());
}

I see your class extends ChangeNotifier, with Hive it has a Listenable option out of the box so anytime you change (add or delete an alarm) it will update
ValueListenableProvider<Box<Alarm>>.value( //in case you're using provider package
     value: Hive.box<Alarm>('Alarm').listenable(),
),

OR
ValueListenableBuilder(
    valueListenable: Hive.box<Alarm>('Alarm').listenable(),
    builder: (context) => ...
),


text:
Q: Configure session in WEB API 2 with OWIN configuration I have been trying to configure my Web API 2, that uses the Startup class to configure the API (OWIN Self-Hosting), for it to support the use of the Session object.
I am aware that a REST application should be statless, but I need to use the session anyway.
I have tried this solution, but it won't work.
I have also looked at multiple blog posts and articles that suggest using a custom RouteHandler that overrides the GetHttpHandler method to use a controller that implements IRequiresSessionState (as explained here). But my startup class uses HttpRouteCollection, and my method MapHttpRoute does not support the property RouteHandler.
I have tried moving the route configuration from my Startup class to the Application_Start in a Global.asax I have added, but it is not working either (the requests are not reaching the controllers).
Any suggestion would be much appreciated!
Thank you


text:
Q: Dynamically Populate Chef Cookbook Attributes I'm trying to create a recipe which pulls in variables which are defined in a YAML configuration file and then uses their values as recipe attributes.
A couple points:

*

*My config.yml file resides in the root of my chef directory (that is, outside of my cookbooks directory, and on the same level as my Vagrantfile which drives the provisioning process.

*I use a similar approach to populate values into my Vagrantfile, which is what gave me the idea for this solution.  I want to maintain a list of user-configurable values which need to be used in both my Vagrantfile as well as various recipes inside various cookbooks.
As an example, here are two values from config.yml:
---
basics:
  vm_ip: 192.168.56.11
  vm_hostname: luma.com

I use the following in my Vagrantfile to read these values:
require 'yaml'
config_file = "config.yml"
settings = YAML.load_file(File.dirname(File.expand_path(__FILE__)) + "/#{config_file}")

And I reference them as such elsewhere in the Vagrantfile (Syntax abbreviated):
machine.vm.network 'private_network', ip: settings['basics']['vm_ip']
machine.vm.hostname = settings['basics']['vm_hostname']

This approach works great for the Vagrantfile, but of course, that's outside of Chef's purview.
From a Chef perspective, I thought I could perhaps follow a similar approach, since Chef is Ruby-based.  I have a cookbook base with an attributes folder, and a default.rb attributes file.  My initial attempt was to simply duplicate the approach in default.rb:
require 'yaml'
config_file = "config.yml"
settings = YAML.load_file(File.dirname(File.expand_path("../../../", __FILE__)) + "/#{config_file}")

And then reference the config.yml values as attributes like so:
default['vm']['ip'] = settings['basics']['vm_ip']
default['vm']['hostname'] = settings['basics']['vm_hostname']

This fails because, as I've (naively) learned, the __FILE__ value refers to a path on the node rather than to a file in the local directory, as this attributes file is used during convergence, etc.  Stupid me.
So, my thought now is to dynamically populate the attributes file as part of the Vagrantfile, since that's outside of Chef's process.  Before I go through the effort of writing that, I'm wondering if there's a more appropriate chef-based approach I should consider.

A: i might be wrong, but it seems you are trying to invent the wheel. let me elaborate...
vagrant
from vagrant perspective, you should leverage test-kitchen in conjunection with vagrant driver.
once you set it up, take advantage of custom kitchen configuration -- use general configuration and (user) custom configuration (each user might have a different custom conifugration, corresponding to the config.yml you mentioned`)
note also, that kitchen.yml supports erb. you can use it to do things dynamically.
chef
from chef perspective, is a configuration management and you should use it correctly. that is, rather than using an external file (config.yml) to feed chef with values, take advantage of recipe attributes, json attributes or even data bags to store values which will be used during your recipe.
note that attributes can be generated dynamically, you will just have to put some logic for that (same as you did for config.yml)


text:
Q: Web Service and Javascript request on the same localhost port I've got a very simple Axis web service on an Apache Tomcat server (e.g. localhost:9999). I created and run everything with Eclipse Java EE.
I want to invoke that web service on a HTML page with JavaScript (was made in Aptana Studio 3)
- When I open the HTML, there's an error because of the cross-domain-policy.
How can I solve this? Or is it the wrong way?
I tried to run it on the same port as the web service using base-url in the Run Configurations, but it is not working (port is used). Can I get it both running on the same port?
Would be nice if you can help me out.

A: When you download Apache Tomcat (doesn't matter the version) you choose the port your server will run on.
If you have Tomcat tied in with Eclipse Java EE, make sure tomcat isn't already running. You can usually check this by right clicking the Tomcat tool icon on your task bar. If it's already running, stop it and then try running tomcat again through eclipse.
If you don't have tomcat tied in with eclipse, here's a tutorial video on how to do that: https://www.youtube.com/watch?v=LdThrERsSsI
Hope this helps


text:
Q: Is there an Azure devops rest API to manage the process level security My Application, needs to grant permission for users to add new work item type or to edit existing work item type of an existing process.
Is there an Azure devops rest API to manage the process level security ?
I could not find any such API in the documentation.
Any help would be appreciated.
Thanks in advance.

A:
needs to grant permission for users to add new work item type or to
edit existing work item type of an existing process

To customize a process, you need to grant Edit process permissions to a user account for the specific process.
I grabbed the following api from the network of the browser to set the Edit process permission to Allow.
POST  https://dev.azure.com/{org}/_apis/AccessControlEntries/2dab47f9-bd70-49ed-9bd5-8eb051e59c02?api-version=5.1-preview

Sample request body:
{
    "token": "$PROCESS:adcc42ab-9882-485e-a3ed-7678f01f66bc:93xxxxe3-1510-4ae5-9019-f770318a3444:",
    "merge": true,
    "accessControlEntries": [{
        "descriptor": "Microsoft.IdentityModel.Claims.ClaimsIdentity;00037FFE1EBE3CEA@Live.com",
        "allow": 1,
        "deny": 0,
        "extendedInfo": {
            "effectiveAllow": 1,
            "effectiveDeny": 0,
            "inheritedAllow": 1,
            "inheritedDeny": 0
        }
    }]
}

Test in Postman:

Update:
The decoded form of GroupDescriptor can serve as IdentityDescriptor here.


text:
Q: geometric buckling for a torus Consider for a moment a torus. The torus will have two radii. The large one from above (looking down on the donut) of R and the smaller one r (the cross section of the circular tube)
Imagine a object is generated by at a random point inside the plutonium solution, the object will travel in a random direction for a fixed distance d. Each time it changes direction it has probability Pcap of being captured.
What is the probability that the object will be able to bounce around inside the torus and then escape from the torus without being captured.
Secondly what is the probability that the object will fly out of the torus and then re-enter it by flying through the hole in the "donut".
This question relates to the geometric buckling of a nuclear reactor, if we assume that the capture of the neutron in the plutonium nitrate solution has a chance "Q" per capture to generate n new neutrons. Then what will the neutron flux distribution be inside the torus ?
If you will a object with a fissile solution such as plutonium nitrate this it is possible to create a homogenous nuclear reactor, for spheres, cylinders, cubes and other boxes the equations have been worked out and published years ago.


text:
Q: How do I break apart a URL to its component parts in Batch? I have URLs of files of unknown length input into my batch script.
http://Repository.com/Stuff/Things/Repo/file1.csv
http://www.place.com/Folder/file2.xml
There is little to no consistency with them at all. I need a way using batch only (though calling powershell from within batch is an option) to break these into the full path and file name.
http://Repository.com/Stuff/Things/Repo/
http://www.place.com/Folder/
file1.csv
file2.xml
I've seen ways of doing it in many other languages, but I'm limited to batch, and it's not one of my strong languages. I tried using a far /f loop with "delims=/", but it quits when it gets to //.

A: In PowerShell you can cast URL strings to System.Uri class which provides extensive information about the URL and its structure. You may need to work out with Uri.Segments property as follows:
PS C:\> # get System.Uri object:
PS C:\> $uri = [uri]"http://Repository.com/Stuff/Things/Repo/file1.csv"
PS C:\> $uri

AbsolutePath   : /Stuff/Things/Repo/file1.csv
AbsoluteUri    : http://repository.com/Stuff/Things/Repo/file1.csv
LocalPath      : /Stuff/Things/Repo/file1.csv
Authority      : repository.com
HostNameType   : Dns
IsDefaultPort  : True
IsFile         : False
IsLoopback     : False
PathAndQuery   : /Stuff/Things/Repo/file1.csv
Segments       : {/, Stuff/, Things/, Repo/...}
IsUnc          : False
Host           : repository.com
Port           : 80
Query          :
Fragment       :
Scheme         : http
OriginalString : http://Repository.com/Stuff/Things/Repo/file1.csv
DnsSafeHost    : repository.com
IsAbsoluteUri  : True
UserEscaped    : False
UserInfo       :

PS C:\> # get base URL without page name and query parameters:
PS C:\> $uri.Scheme + ":/" + $uri.Authority + (-join $uri.Segments[0..($uri.Segments.Length - 2)])
http:/repository.com/Stuff/Things/Repo/
PS C:\> # get page/file name:
PS C:\> $uri.Segments[-1]
file1.csv

A: @echo off
setlocal EnableDelayedExpansion

set "url=http://Repository.com/Stuff/Things/Repo/file1.csv"

for %%a in ("%url%") do (
   set "urlPath=!url:%%~NXa=!"
   set "urlName=%%~NXa"
)
echo URL path: "%urlPath%"
echo URL name: "%urlName%"

Output:
URL path: "http://Repository.com/Stuff/Things/Repo/"
URL name: "file1.csv"

A: Use the split and SubString methods of the string class.
e.g.
$filename = $url.split('/')[-1]
# $url.split('/') splits the url on the '/' character. [-1] takes the last part
$rest = $url.SubString(0, $url.Length - $filename.Length)
# The first parameter is the starting index of the substring, the second is the length.

A: @echo off
Set input=http://Repository.com/Stuff/Things/Repo/file1.csv
SETLOCAL ENABLEDELAYEDEXPANSION
For %%A in ("%input%") do (
    Set url= %%~pA
    set url=!url:~2!
    Set fileName=%%~nxA
)
echo.URL is: %url%
echo.File Name is: %fileName%
ENDLOCAL

Output


text:
Q: PHP: Using special characters in bad word obfuscator I'm using this bad word detector/obfuscator in php (to be Adsense compliant). It shows the first letter of the bad word, and replaces the remaining letters with this character: ▪
It works fine, except when I'm using words that contain special characters in Spanish, for example: ñ, á, ó, etc.
This is my current code:
<?
function badwords_full($string, &$bad_references) {
    static $bad_counter;
    static $bad_list;
    static $bad_list_q;
    if(!isset($bad_counter)) {
        $bad_counter = 0;
        $bad_list = badwords_list();
        $bad_list_q = array_map('preg_quote', $bad_list);
    }
    return preg_replace_callback('~('.implode('|', $bad_list_q).')~',
        function($matches) use (&$bad_counter, &$bad_references) {
            $bad_counter++;
            $bad_references[$bad_counter] = $matches[0];
            return substr($matches[0], 0, 1).str_repeat('▪', strlen($matches[0]) - 1);
    }, $string);
}

function badwords_list() {
    # spanish
    $es = array(
        "gallina",
        "ñoño"
    );

    # english
    $en = array(
        "chicken",
        "horse"
    );

    # join all languages
    $list = array_merge($es, $en);
    usort($list, function($a,$b) {
        return strlen($b) < strlen($b);
    });
    return $list;
}

$bad = []; //holder for bad words

Test 1:
echo badwords_full('Hello, you are a chicken!', $bad);

Result 1:

Hello, you are a c▪▪▪▪▪▪! (works fine)

Test 2:
echo badwords_full('Hola en español eres un ñoño!', $bad);

Result 2:

Hola en español eres un �▪▪▪▪▪!

Any ideas on how to solve this issue? Thanks!

A: You are splitting a multibyte character in half. Use mb_substr in place of substr.
return mb_substr($matches[0], 0, 1).str_repeat('▪', strlen($matches[0]) - 1);

https://3v4l.org/AnPJl
You also probably want to use mb_strlen in place of strlen.


text:
Q: Questions on Answer to "The cardinality of the set of all finite subsets of an infinite set" Would someone please enlarge on Arturo Magidin's original answer ?
$1.$ Say the question didn't divulge $|S| = |X|$. Then how can $|S|$ be determined? Any intuition?
I recast it below with more details to try to apprehend it. Please feel free to edit errors/problems.
As defined therein, $X$ is an infinite set, and $ S := \{$ all finite subsets of $X \}$.
Since ●  $X$ is given as infinite which means $|X| \ge |\mathbb{N}|$
and ●  $S \quad \supseteq \quad \{\emptyset, \{1\}, \{2\},...,\{n\},...\} = \require{cancel} \cancel{\{\text{singletons}\}} = |\mathbb{N}|$
$\implies \emptyset, \{1\}, \{2\},...,\{n\},... \in S$
$\implies 1, 2, ..., n, ... \in X \iff \mathbb{N} \subseteq X$ thus $\color{limegreen}{|\mathbb{N}| \le |X| \le |S|}$.
For all $n \in \mathbb{N}$, define $S_n$ as did Prof Magidin: $S_n:= \color{violet}{\{}{\text{ all subsets of cardinality $n$ }}  \color{violet}{\}}\subseteq S.$
This definition involves a subset of cardinality $n$ (ie with $n$ elements) so we now scrutinise it.

$2.$ How would you divine/previse to define $S$ wrt $S_n$ ?

$S_n$ has the form $\color{violet}{\{} \quad \{ \, (a_1, ..., a_n) \, \}, \{ \, (b_1, ..., b_n) \, \}, ...\quad \color{violet}{\}}$.
The $n$ elements in each $n$-tuple in each subset of cardinality $n$ can be chosen $n!$   ways,
ie: the $a_1, ..., a_n$ in $(a_1, ..., a_n)$ in $\{ \; (a_1, ..., a_n) \; \}$ can be chosen $n!$ ways.
Thus every such subset of cardinality $n$ determines $n!$ $n$-tuples of elements of $X$.
In general, an $n$-tuple included in any set will produce a subset (of that set) of cardinality $\le n$.
This paragraph implies: $ |S_n| \color{red}{\le}  \, n!|X|^n \,  = |X|$.

$3.$ How and why is $ |S_n| \color{red}{\le}  \, n!|X|^n $?

In toto, $ \begin{align} |X|  \color{lime}{\le} |S| &  = \left|\biguplus_{n=0}^{\infty} S_n\right| = \sum_{n=0}^{\infty}|S_n| = |\underbrace{S_0}_{= \emptyset}| + \sum_{n=1}^{\infty}|S_n|  \\ & = \sum_{n=1}^{\infty}|S_n| \\ &  \color{red}{\le} \sum_{n=1}^{\infty}|X| = |\mathbb{N}||X| \; {\Large{\color{darkturquoise}{[}}}  =  {\Large{{\color{darkturquoise}{]}}}} \; |X| \end{align} $

$4.$ In the last line, how and why is $|\mathbb{N}||X| \; =  \; |X|$ ?


text:
Q: TLBIMP.EXE - Error TI0000 - *.dll is not a valid type library While building our project on the Build Server, the compilation fails with the error message:
TlbImp: error TI0000 : The input file 'C:\*.dll' is not a valid type library.

We tried to manually invoke the TlbImp command thru the VS2005 Command Prompt and the same error message appeared.
To investigate, we tried to create a clean build environment in a Virtual Machine (Vbox), then we run the build there. It went fine.
We also tried to invoke the same TlbImp command thru the VS2005 Command Prompt and it succeeded.
With that, we are assuming that there is nothing wrong with the DLL. Do you have any idea what scenario(s) can cause this problem?
EDIT:
Found the problem, see my answer. ;)

A: If it is working on one machine and not on the other, then most probably some dependency of this DLL is missing in your machine. Inspect the dll through DependencyWalker and you will get to know that which dependency hasn't been built properly.

A: After closer inspection, we found out that the environment variables on the official build server is FUBAR.
The official build server was installed with both VS2003 and VS2005. Our project is VS2005. The build script is using components from VS2003 instead of VS2005 because the VS2003 paths (Path, LIB, LIBPATH and INCLUDE) were first declared before the VS2005 paths.
A simple SET command to override the environment variables with the "correct ones" fixed the build!
Thanks!


text:
Q: Initialize constant from another constant with some changes Let's say a have
struct table { int foo, bar, baz; };

static struct table const A = { .foo = 1, .bar = 2, .baz = 3 };

how could I declare B to be the exact same definition of A but with one change?
For instance what I would like to write is something like
static struct table const B = A, { .bar = 42 };

I am looking for a solution, if any, simpler than the following workaround:
#define A_DEFS .foo = 1, .bar = 2, .baz = 3
static struct table const A = { A_DEFS };

#define B_DEFS A_DEFS, .bar = 42
static struct table const B = { B_DEFS };

A: Try :
static struct table const B = {  A.foo, .bar = 42, A.baz };

A: SparKot's answer let me come to this slightly more convenient solution:
struct table { int foo, bar, baz; };
#define BASE(X) X.foo, X.bar, X.baz

static struct table const A = { .foo = 1, .bar = 2, .baz = 3 };
static struct table const B = { BASE(A), .bar = 42 };
static struct table const C = { BASE(B), .baz = 24 };


text:
Q: JPA Modelgen generates model classes but does not compile them We are using JPA 2, Hibernate and the Criteria API in our project for which we need the Model Generator of Hibernate to create meta model classes.
In our Ant build process we included the annotation processor of hibernate-jpamodelgen.jar to generate the meta model classes for us.
The problem is that the classes that depend on the generated classes do not compile due to a "symbol not found" compile error.
[javac] ...\DocumentSpecifications.java:29: cannot find symbol
[javac] symbol  : class Document_
[javac] location: package ...entity
[javac] import ...entity.Document_;

The ant script looks like this:
<javac srcdir="@{from}"
  destdir="@{to}"
  source="${compile.option.source-version}"
  target="${compile.option.target-version}"
  debug="${compile.option.debug}"
  debuglevel="${compile.option.debuglevel}"
  includeAntRuntime="false"
  fork="${compile.option.fork}"
  classpathref="path.ivy.libs.compile"
  encoding="${sourcefiles.encoding}">
    <compilerarg line="${compile.option.compilerarg} -s @{metamodel}" />
 </javac>

A look in Ant's target directories shows that the meta model Java classes (.java) have been successfully created in the folder src/metamodel but no classes (.class) have been compiled to the folder build/classes.
Does Anyone know how to teach Ant or the Java compiler to include the generated class files?

A: OK, found the problem.
I was using JDK 1.6.0_11 when the error occured.
With a 1.7 JDK it works. Obviously, you have to do the compiling in multiple steps when Using a 1.6 JDK.


text:
Q: How to easily investigate 'This application is modifying the autolayout engine from a background thread' I have this message in the debugger window:

This application is modifying the autolayout engine from a background
  thread after the engine was accessed from the main thread. This can
  lead to engine corruption and weird crashes.

I know what it means and I know how to fix it, but the problem is that I have a lot of threads fired in different parts of the application and is difficult to get a full stack trace.
The app is not crashing, as it is treated as a warning.
How can I pause/halt the application when this occurs, so I can see exactly what is going on there?


text:
Q: WIX: How can I uninstall a previous MSI built using a VS *.vdproj I'm using WIX to create a new installer for an existing product. The installer is very simple - just drops a few dll's into a specified folder on disk.
In the field, my users already have that folder with old dll's in them (since they installed the old MSI - created using a *.vdproj project in VS).
My problem is that after I install the WIX, I have both the old MSI and the new Wix MSI appear in Add/Remove. Expected (? since these 2 are two different kind of MSI's?). I need some kind of an upgrade mechanism - so I was wondering if I can call the old MSI uninstaller from within the WIX one. Or alternately somehow take care of the old Add/Remove entry (a registry hack perhaps?)

A: Assuming the old install and the new install are installed using the same context ( per-user -> per-user or per-machine -> per-machine )  you can use a MajorUpgrade rule to find the old version and get rid of it.  You can do this by syncing up the UpgradeCode property and using a higher ProductVersion or you can do it by authoring a second Upgrade rule using the legacy UpgradeCode GUID.
If the old install was per-user and you want the new install to be per-machine you are out of luck.  This isn't supported by MSI.   Typically I only support per-machine installs and hardcode the ALLUSERS property and remove the CustomerInformation dialog from the installer UI experience.   This is not the default experience for VDPROJ based installers.


text:
Q: QtConcurrent::run emit signal I would like to emit a signal in Qt, from a function that I called with QtConcurrent::run
Is this possible? It seems like my slot never gets called. All of the signals, slots, and functions are part of the same class object. I have tried making the connection in the Master thread, and in the slave thread. I dont really care if the signal and slot are in the same thread or not, I just want to get it to happen.
Thanks

A: The below works just fine in Qt 4.8.7. The signal is emitted from the worker thread, and consumed in the main thread. We assert that the slot runs in the main thread, and the functor runs in the worker thread.
// https://github.com/KubaO/stackoverflown/tree/master/questions/concurrent-emit-qt4-7114421
#include <QtCore>

class Helper : public QObject {
   Q_OBJECT
public:
   int n = 0;
   Q_SLOT void increment() {
      Q_ASSERT(QThread::currentThread() == qApp->thread());
      n++;
   }
};

int main(int argc, char **argv)
{
   QCoreApplication app(argc, argv);
   Helper helper;
   Q_ASSERT(helper.n == 0);
   QtConcurrent::run([&]{
      Q_ASSERT(QThread::currentThread() != qApp->thread());
      QObject src;
      QObject::connect(&src, SIGNAL(destroyed(QObject*)), &helper, SLOT(increment()));
      QObject::connect(&src, SIGNAL(destroyed(QObject*)), &app, SLOT(quit()));
   });
   app.exec();
   Q_ASSERT(helper.n == 1);
}

#include "main.moc"

In Qt 5, you don't need the helper class to demonstrate that it works:
#include <QtConcurrent>

int main(int argc, char **argv)
{
   QCoreApplication app(argc, argv);
   int n = 0;
   Q_ASSERT(n == 0);
   QtConcurrent::run([&]{
      Q_ASSERT(QThread::currentThread() != qApp->thread());
      QObject src;
      QObject::connect(&src, &QObject::destroyed, &app, [&]{
         Q_ASSERT(QThread::currentThread() == qApp->thread());
         n ++;
         qApp->quit();
      });
   });
   app.exec();
   Q_ASSERT(n == 1);
}

A: You can use a Qt::QueuedConnection for that connection (pass it to the connect call which establishes the connection), since the signal will always be emitted from a different thread than the receiver objects thread.
An Qt::AutoConnection will also do the same thing and add the signal to the event queue of the thread of the receiving object.
If the receiving thread is blocked, and thus never reenters the event queue, the signal cannot be received by the slot of the receiving object.

A: You really should use QFuture and QFutureWatcher with QtConcurrent::run().

A: yes it is possible.
just look little example:
in this example we want implement multithread. longProcess function go to thread pool and process in thread pool and after that answer of long process function back to main thread.
Test.h
Class Test: public QObject
{
    Q_OBJECT
public:
    explicit Test(QObject *parent = nullptr);

    void resultAvailable();

    static void doLongProcess(Test *test);

signals:
    void finishedProcess(const QString &massage);

public slots:
    void captureSignal(const QString &message);
};

Test.cpp
void Test::resultAvailable()
{
        QtConcurrent::run(&ContactsModelManager::doLongProcess, this);

        connect(this , &Test::finishedProcess,
                this , &Test::captureSignal);
}

//attention!! doLongProcess is static fnuction
void Test::doLongProcess(Test *test)
{
    //this process is very long
    test->longProcess();
}
 void Test::longProcess()
{
    //do your process

    //at the end emit your signal
    emit finishedProcess("finished process in another thread");
}

void Test::captureSignal(const QString &message)
{
   Qdebug() << "message is: " << message;
}


text:
Q: Java Spark RDD operations not getting processed This is in continuation of my previous question here, but as this is a different issue, I thought it best to create a new question for it. I am having the following code:
JavaMongoRDD<Document> rdd = MongoSpark.load(sc);
System.out.println("Count: " + rdd.count());

Gson gson = new Gson();
        rdd.foreach(item -> {
            String json = item.toJson();
//              JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
//              System.out.println(jsonObject.get("resourceId").getAsJsonObject().get("$binary").getAsString());
            Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {
            }.getType());

            System.out.println(map.get("resourceId"));
            item.forEach((key, value) -> {
                if (key.equalsIgnoreCase("resourceId")) {
                    System.out.println(value);
                    resourceIds.add(value.toString());
                }
            });
        });

I have been trying to extract the information out of the JSON structure using Gson library, and strange thing is that yesterday, this code was giving me output. However, today, when I run a Spark submit job, the count is getting printed, but after that, the MongoConnection is getting closed and the job is falling silent. To first dissuade such assumptions, I'm declaring the Spark job to run with its master as local[3], so all logs would be printed in the driver console itself, not in any worker console.
2019-12-03 01:32:32 INFO  DAGScheduler:54 - ResultStage 1 (count at UUIDTransformerEngine.java:209) finished in 2.707 s
2019-12-03 01:32:32 INFO  DAGScheduler:54 - Job 1 finished: count at UUIDTransformerEngine.java:209, took 2.711357 s
Count: 13716
2019-12-03 01:32:37 INFO  MongoClientCache:48 - Closing MongoClient:

The count also is giving me different results every time I run it, though the Mongo collection is not being edited. I have no idea how to bring the output back on, or what internal process of Spark is hindering the operation. Do I have to cache or something? Please shed some light on it.


text:
Q: Convert Firebase RecycleView data to PDF using iText in android I'm developing an android app with cloud Firestore. In a particular activity, I'm using RecyclerView to display firestore data.
With the help of below code I'm able to generate PDF file with a single text, but unable to complete the code to get the firestore RecyclerView data in PDF. To do this what type of code I need to enter.
    private void createPdf() throws FileNotFoundException, DocumentException {

        File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
        if (!docsFolder.exists()) {
            docsFolder.mkdir();
            Log.i(TAG, "Created a new directory for PDF");
        }

        pdfFile = new File(docsFolder.getAbsolutePath(),"HelloWorld.pdf");
        OutputStream output = new FileOutputStream(pdfFile);
        Document document = new Document();
        PdfWriter.getInstance(document, output);
        document.open();
        document.add(new Paragraph(mContentEditText.getText().toString()));
        document.close();
        previewPdf();
    }


text:
Q: Frenet frame as basis in a product Let $\gamma (t)$ be an embedded curved in $\mathbb{R}^3$ and let $T(t),\ N(t)$ and $B(t)$ be its Frenet frame. Let C be a unit circle (or another closed embedded curve in $\mathbb{R}^3$) and fix a point on $C$, say $C(0)$. We glue at every point of $\gamma(t)$ the curve $C$ at point $C(0)$ such that $N(t)$ is tangent to $C$ and $B(t)$ is normal. This will produce a (not necessarily embedded) surface in $\mathbb{R}^3$. Given $\gamma$ and $C$ how do we plot in Mathematica this construction?
More generally, how can we plot this without fixing the point C(0).I.e. given two Jordan curves $\gamma$ and $C$ we declare that the tangent, normal and binormal of $\gamma$ are, respectively, the normal, binormal and tangent of $C$. How do we plot this, given $\gamma$ and $C$?
Thank you.

A: In the first paragraph of the OP, it says the normal $N(t)$ of $\gamma$ should be tangent to $C$ and in the second, it says the normal should be the binormal.  I went with the first one.  The OP also asks how to do this without fixing the base point $C(0)$.  I don't know what that means.  You could have the base point depend on $t$ or $\gamma(t)$ by using $C(u(t))$ instead of $C(0)$ (or cc[c0] in the code below).
The idea is simple enough: A Frenet frame can be viewed as a rotation matrix, so all you need to do is rotate and translate $C$ into place on $\gamma$, using the frames of the two curves.
(* the curve gamma *)
gg[t_] := {5 Cos[t], 5 Sin[t], 3 ArcTan[t]};
gFSF[t_] = Simplify@Last@FrenetSerretSystem[gg[t], t];

(* the curve C *)
Clear[cFSF];
pts = {{0, 0, 1}, {1, -1, 0}, {2, 0, 1}, {3, 2, 0}, {1, 3, -1}, {0, 2,
     0}, {-1, 1, 1}(*,{0,0,1}*)};
cc = BSplineFunction[pts, SplineClosed -> True];
cFSF[t0_?NumericQ] := Append[#, Cross @@ #] &[  (* FrenetSerretSystem sometimes failed *)
    Table[Indexed[Derivative[n][cc][t], k], {n, 2}, {k, 3}] /.
     t -> t0] // Orthogonalize;
c0 = 0.95;             (* cc[c0] = C(0), base point *)
cFSF0 = cFSF[c0];      (* Frenet frame at base point *)
Show[
 ParametricPlot3D[(cc[t] - cc[c0]), {t, 0, 1},
  MeshFunctions -> {#4 &}, Mesh -> {{c0}}, AxesLabel -> {x, y, z}],
 Graphics3D[{Thick,
   MapThread[{#2, Arrow[{0 cc[c0], 0 cc[c0] + #}]} &, {cFSF0, {Blue,
      Orange, Darker@Green}}]}],
 PlotRange -> All
 ]

Show[
 ParametricPlot3D[gg[t], {t, -2 Pi, 2 Pi},
  PlotStyle -> {Thick, Red}],
 ParametricPlot3D[
  gg[t] + Transpose@gFSF[t].RotateRight@cFSF0.(cc[s] - cc[c0]),
  {t, -2 Pi, 2 Pi}, {s, 0, 1}, Mesh -> {40, 0}],
 PlotRange -> 8, ImageSize -> 300, SphericalRegion -> True
 ]

A: I am not sure I have completely understood but perhaps this is a start:
f[t_] := {Cos[t], Sin[t], t}
{tg, n, b} = FullSimplify[FrenetSerretSystem[f[t], t][[2]]];
su[u_] := {n, b} /. t -> u
pp = ParametricPlot3D[f[t], {t, 0, 2 Pi}];
Manipulate[
 Show[Graphics3D[
   Polygon@Table[
     f[par] + d {Cos[j] + 1, Sin[j]}.su[par], {j, 0, 2 Pi, 0.1}]], pp,
   AspectRatio -> Automatic,
  PlotRange -> {{-2, 2}, {-2, 2}, {0, 7}}], {par, 0, 2 Pi}, {d, 0.1,
  1}]


text:
Q: Virtualbox installation using sudo apt install giving error for ubuntu 20.04 On using command
sudo apt install virtualbox
it's giving Output as
  virtualbox-6.1 6.1.32-149290~Ubuntu~eoan
  virtualbox-6.0 6.0.24-139119~Ubuntu~eoan
You should explicitly select one to install.

E: Package 'virtualbox' has no installation candidate

I have tried using
sudo apt install virtualbox-6.1 6.1.32-149290~Ubuntu~eoan
but getting this
E: Unable to locate package 6.1.32-149290~Ubuntu~eoan
/etc/apt/sources.list
contains
deb http://in.archive.ubuntu.com/ubuntu/ trusty main
deb-src http://in.archive.ubuntu.com/ubuntu/ trusty main

###### Ubuntu Update Repos
deb http://in.archive.ubuntu.com/ubuntu/ trusty-updates main
deb-src http://in.archive.ubuntu.com/ubuntu/ trusty-updates main

even tried sudo apt update and used sudo apt install virtualbox-6.1 but getting this
W: Target CNF (contrib/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list.d/virtualbox.list:1 and /etc/apt/sources.list.d/virtualbox.list:3
for apt install virtualbox-6.1
 virtualbox-6.1 : Depends: libqt5opengl5 (>= 5.0.2) but it is not going to be installed
                  Depends: libqt5printsupport5 (>= 5.0.2) but it is not going to be installed
                  Recommends: libsdl-ttf2.0-0 but it is not installable
E: Unable to correct problems, you have held broken packages.

Please suggest how can i install virtualbox through sudo apt install?
Thanks.

A: Hi there was error in /etc/apt/sources.list and there were duplicate entries also which i removed from software & updates as a result sudo apt update started working followed by that sudo apt install virtualbox also started wokring.


text:
Q: how many replication should I make while using wingen program to generate data? Iam writting my thesis and using software called Wingen3 and I am facing problem in determing How many replication should I put when using the program to generate Data?
Some says 5, some says 10,000 but is there a rule or a formula to determine how many replication?

A: Nobody can give you more than a hand-waving guess without knowing more about your specific case.  Note: I know absolutely nothing about "Wingen3", but sample size questions are (or at least ought to be) a function of the statistical properties of your estimators, not of the software.
In general you replicate simulations when they are stochastic to estimate the distributional behavior of the output measures.  How many replications depends entirely on what type of measure you're trying to determine and what margin of error you're willing to tolerate in the estimates.  One fairly common technique is to make a small initial run and estimate the sample variability of your performance measure.  Then project how large a sample will get you down to the desired margin of error.  This works fairly well if you're estimating means, medians, or quartiles, but not at all well for estimating quantiles in the tail of your distribution. For instance, if you want to determine the 99.9%-ile, you're seeking extremes that happen one time in a thousand on average and you may need tens or even hundreds of thousands of replications to accurately assess such rare events.


text:
Q: C# HttpClient null on second run I have a problem. I created the following ViewModel:
public class TemplateListViewModel
{
    public double WidthHeight { get; set; }

    public ICommand LoadTemplates => new Command(MyHandler);
    public int CurrentTemplateCountReceived;
    public bool HitBottomOfList = false;
    public ObservableCollection<TemplateSource> sourceList { get; set; }

    public TemplateListViewModel()
    {
        CurrentTemplateCountReceived = 0;
        sourceList = new ObservableCollection<TemplateSource>();

        var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
        var width = mainDisplayInfo.Width;
        var density = mainDisplayInfo.Density;
        var ScaledWidth = width / density;

        WidthHeight = (ScaledWidth / 2);

        loadingTemplates += onLoadingTemplates;
        LoadTemplateList();
    }

    private event EventHandler loadingTemplates = delegate { };

    private Task LoadTemplateList()
    {
        loadingTemplates(this, EventArgs.Empty);
        return null;
    }

    private async void onLoadingTemplates(object sender, EventArgs args)
    {
        if (HitBottomOfList == false)
        {
            List<Template> templateList = await App.RestService.GetTemplates(App.User, CurrentTemplateCountReceived);

            if (templateList != null)
            {
                foreach (var template in templateList)
                {
                    ImageSource source = ImageSource.FromUri(new Uri("http://alexander.vreeswijk.eu/memento/" + App.TemplateSource + template.FileName));
                    TemplateSource templateSource = new TemplateSource { Id = template.Id, Source = source, WidthHeight = WidthHeight, FileName = template.FileName };
                    sourceList.Add(templateSource);
                }

                CurrentTemplateCountReceived = sourceList.Count;
            }
            else
            {
                HitBottomOfList = true;
            }
        }
    }

    bool handling = false;

    public async void MyHandler()
    {
        // already handling an event, ignore the new one
        if (handling) return;

        handling = true;

        await LoadTemplateList();

        handling = false;
    }
}

And here is the RestService.cs:
HttpClient client;
public string ErrorMessage { get; set; }

public RestService()
{
    client = new HttpClient();
    client.MaxResponseContentBufferSize = 256000;
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
}

public async Task<List<Template>> GetTemplates(User user, int offset)
{
    var postData = new List<KeyValuePair<string, string>>();
    postData.Add(new KeyValuePair<string, string>("un", user.Username));
    postData.Add(new KeyValuePair<string, string>("pw", user.Password));
    postData.Add(new KeyValuePair<string, string>("offset", offset.ToString()));
    var content = new FormUrlEncodedContent(postData);
    var weburl = "mysite.org/myapp/get_templates.php";
    List<Template> response = await PostResponseTemplates(weburl, content);

    return response;
}

public async Task<List<Template>> PostResponseTemplates(string weburl, FormUrlEncodedContent content)
{
    var response = await client.PostAsync(weburl, content);
    var json = await response.Content.ReadAsStringAsync();

    if (json != "Nothing")
    {
        var jObject = JObject.Parse(json);
        var templatePropery = jObject["Templates"] as JArray;
        List<Template> templateList = new List<Template>();

        foreach (var property in templatePropery)
        {
            List<Template> propertyList = new List<Template>();
            propertyList = JsonConvert.DeserializeObject<List<Template>>(property.ToString());
            templateList.AddRange(propertyList);
        }

        var sourcePropery = (JObject)jObject["Source"];
        foreach (var property in sourcePropery)
        {
            string tempplateSource = property.Value.Value<string>();
            App.TemplateSource = tempplateSource;
        }

        return templateList;
    }
    else
    {
        ErrorMessage = json;
        return default(List<Template>);
    }
}

The ICommand LoadTemplates => new Command(MyHandler); gets called when the CollectionView almost hit the bottom of the list, so it would get more data.
Then I created the MyHandler to check if there is already an event busy with the webcall to get more data, because it fires the event multiple times.
Finally it executes the onLoadingTemplates which gets the data from my webpage.
Now on first run with the LoadTemplateList(); in the constructor everything works great, but when it executes it like: await LoadTemplateList();, when the event is triggered it crashes on the following line in the RestService.cs: var response = await client.PostAsync(weburl, content); with the error:

'Object reference not set to an instance of an object.'

Can someone tell my why this is happening when it gets data when the event is triggered?

A: I would risk to bet on the current CollectionView bug.
It's not the "called second time" case but the renderer just crashes when you change the already loaded bound ObservableCollection (and the window with CollectionView is hidden).
My first thought was that somewhere in the renderer it was executing on the the calling non-UI thread.
But even when you try to modify the bound ObservableCollection from UI-thread the renderer still crashes.
You can be so kind to report this bug i had no time to do it, actually just using other customized listviews.

A: Doing some detective work here.
Since you said that you are getting a NullReferenceException

Object reference not set to an instance of an object.

in the line
var response = await client.PostAsync(weburl, content);

where neither weburl or content can be null since were created previously in the GetTemplates method, it only remains the possibility that client is null in the former line: if that is the case, you should make sure you are setting the following properties in your client after it is created:
httpClient.DefaultRequestHeaders.ConnectionClose = false;
HttpWebRequest.KeepAlive = true;

There is a nice post on HttpClient BestPractices in the MSFT docs.
Hope this helps!


text:
Q: How to load an Array (of numbers) into a google app script Byte[] I have an Array (of numbers) in Google Apps Script, and I want to convert it to base64. I could of course use a simple open-source library such as this one.
However GAS already provides functions for this using Utilities.base64Encode(Byte[])
but to call this function I need a Byte[] not Number[].
Therefore the following script gives an error: (Cannot convert Array to (class)[].)
function testBase64Encode()
{
  var bytes = [];
  for (var i = 0; i < 255; i++) bytes.push(i);

  var x = Utilities.base64Encode(bytes)
}

Normally Byte[]'s come directly out of a Blob's GetBytes() function, however in my case the Array (of numbers) comes out of zlib encryption lib.
So I am trying to find a way to convert that Number Array to a Byte[], acceptable for use with Utilities.base64Encode(Byte[]).
I did try to create a Byte myself and put them into an Array, however the following code also gives an error: (ReferenceError: "Byte" is not defined.)
var b1 = new Byte();

I did some more testing, and it seems to work as long as the value in the bytes' numeric values are 128 or lower. I find this weird because a byte should go up to 255.
The following code runs fine for 'bytes' but fails for 'bytes2' because there is a value greater than 128:
function testByteArrays()
{
  var bytes = [];
  for (var i = 0; i < 128; i++) bytes.push(i);
  var x = Utilities.newBlob(bytes)

  var bytes2 = [];
  for (var i = 0; i < 129; i++) bytes2.push(i);
  var x = Utilities.newBlob(bytes2)
}

A:
...a byte should go up to 255.

But not in Two's complement notation... in that case, the bytes should be in the range [-128..127], where the high-order bit is reserved as a sign bit. Given a positive integer i, we need to calculate the two's complement if it is greater than 127. That can be done by subtracting 28 (256). Applying that to your first example:
function testBase64Encode()
{
  var bytes = [];
  for (var i = 0; i < 255; i++) bytes.push(i<128?i:i-256);

  var x = Utilities.base64Encode(bytes)
}

This will avoid the error message you were receiving (Cannot convert Array to (class)[].). Ideally, you should also ensure that the number values start in the range 0..255.


text:
Q: Add a binary to my path I have an executable. I want to execute the executable in terminal with name only like other commands.
I can put my executable in /usr/local/bin or I could add its PATH to ~/.bashrc. Both will work.
What is better?  Is there  any difference?

A: If you put the executable file in /usr/bin or /usr/local/bin, then you will be able to run that program by only specifying the name (your-program instead of /usr/local/bin/your-program).
If you instead add the directory containing the program to the ~/.bashrc file to the PATH, then any executable file present in that directory can be launched by only typing its name.

A: Adding the location of the file to your $PATH variable in your ~/.bashrc file will only allow you to execute from any location, whereas putting it in /usr/bin/ will allow all users on your system to execute that file from any location.
Why is that? Because, your ~/.bashrc file is only visible to you as a user. So all variable changes done are limited to you. Whereas, adding that file to /usr/bin will allow the file to remain there for all users and since /usr/bin is present in the $PATH variable unless someone removes it, will allow all users to execute it from any location.

A: For example let me assume, you have an executable myscript. You need to run it from a terminal as,
/path/to/myscript

User level Change
If you  add the PATH of that executable to ~/.bashrc, you can run the executable with name only from anywhere (Avinash Raj already mentioned), as
myscript

But the change will be affected in user level. That means if you have any other user(s) they could not access the executable with name only. If they have proper permission they need to run the executable as,
/path/to/myscript

Also, you will not be able to run the script as sudo as it is not in PATH of root, To run as sudo you need to use,
sudo /path/to/myscript

system level change
If you put your script in /usr/local/bin it can be accessed system wide and for all users. In that case any user can run your executable as (subject to having proper permissions)
myscript

In that case you can run the executable as sudo also as,
sudo myscript

Now choose one way depending upon your need.

A: Just as a complement to @souravc answer...
For the "User level Change", instead of editing the ~/.bashrc file you can simply create the directory $HOME/bin/ and place your scripts in there.
The directory will be automatically added to the PATH (at least since Ubuntu 12.04) which means that you'll be able to run all the scripts/executables inside that directory with a simple:
myscript

Just my 2 cents. :)
PS- I tried to post this as a comment to @souravc answer, but I didn't have enough reputation. :-(


text:
Q: angularJS popover, how to use a template? I'm trying to add a popover (bootstrap v3.3.7) in my angularJs app,
I can successfully add a popover like this:

this works perfectly, now how can I do something like I did with bootstrap modals, having an external htm file as template where I can put all the data I wanna show in the popover?
I tried creating a htm page with some DIVs, and link it in the popover like this:
 popover-template="'Views/Popovers/myPopoverTemplate.htm'"

but it doesn't work.
What am I doing wrong? thank you

external template:

test header

        test body

            <button class="btn btn-default" type="button" ng-click=""> Footer - Buttons go here</button>

css for the template:
.testbox {
background: #fff;
color: #000;
padding: 10px;
min-height: 200px;
min-width: 500px;
position: absolute;

}


text:
Q: How to recover files "emptied" from trash I recently updated to macOS Mojave. I was experimenting with the new desktop stack feature. Long story short, I ended up creating a folder on the dock and putting all the files from my desktop into it. When I did this all the files stayed on the desktop, so I deleted them (moved them to trash). When I saw that the files were no longer on my desktop, but were still in the folder in the dock, I emptied my trash. That's when I found out that the files in the folder on the dock must have just been symlinks because once the trash was emptied, so was the folder on my dock.
Uh oh, I just mistakenly deleted all the files that I had on my desktop.
I searched google and see that there are programs (not produced by Apple) I can install to recover these files. I'm wondering if there is a simple (command line) way I can recover these files or if there is an official application produced by Apple that I can install to recover them.
How can I recover files that were emptied from the trash?

A: There is not an official Apple product or command-line tool to undelete / recover in place these files short of Time Machine having made a copy to another volume or to a snapshot.
I have used Data Rescue in the past and would recommend it. There are many questions here covering how that works and their free support is amazing.
The most important thing is to stop using that computer as soon as possible once you verify if Time Machine has you covered, because all disk activity risks over-writing deleted files, reducing your chance to recover intact data from the free space.

This doesn't help your situation now because the data is already lost, but in the future you can use Time Machine.
Time Machine will backup files, even when the drive is not connected, so be sure to check in case you have a local snapshot you can recover.


text:
Q: Get x-axis label into the first colomn of the table - highcharts I am trying to create a table from highcharts.
I am getting all the data properly to table.but as first column I need the x axis labels. how to get it. As column head I need the date and as column values I need date values.
See jsfiidle demo.
Screenshot:

I am using the following code:
Highcharts.drawTable = function() {

// user options
var tableTop = 310,
    colWidth = 100,
    tableLeft = 20,
    rowHeight = 20,
    cellPadding = 2.5,
    valueDecimals = 1,
    valueSuffix = '';

// internal variables
var chart = this,
    series = chart.series,
    renderer = chart.renderer,
    cellLeft = tableLeft;

// draw category labels
$.each(chart.xAxis[0].categories, function(i, name) {

    renderer.text(
        name,
        cellLeft + cellPadding,
        tableTop + (i + 2) * rowHeight - cellPadding
    )
    .css({
        fontWeight: 'bold',

    })
    .add();
});

$.each(series, function(i, serie) {
    cellLeft += colWidth;

    // Apply the cell text
    renderer.text(
            serie.name,
            cellLeft - cellPadding + colWidth,
            tableTop + rowHeight - cellPadding
        )
        .attr({
            align: 'right'
        })
        .css({
            fontWeight: 'bold',
            color:'red'
        })
        .add();

    $.each(serie.data, function(row, point) {

        // Apply the cell text
        renderer.text(
                Highcharts.numberFormat(point.y, valueDecimals) + valueSuffix,
                cellLeft + colWidth - cellPadding,
                tableTop + (row + 2) * rowHeight - cellPadding
            )
            .attr({
                align: 'right'
            })
            .css({
            fontWeight: 'bold',
            color:'blue'
        })
            .add();

        // horizontal lines
        if (row == 0) {
            Highcharts.tableLine( // top
                renderer,
                tableLeft,
                tableTop + cellPadding,
                cellLeft + colWidth,
                tableTop + cellPadding
            );
            Highcharts.tableLine( // bottom
                renderer,
                tableLeft,
                tableTop + (serie.data.length + 1) * rowHeight + cellPadding,
                cellLeft + colWidth,
                tableTop + (serie.data.length + 1) * rowHeight + cellPadding
            );
        }
        // horizontal line
        Highcharts.tableLine(
            renderer,
            tableLeft,
            tableTop + row * rowHeight + rowHeight + cellPadding,
            cellLeft + colWidth,
            tableTop + row * rowHeight + rowHeight + cellPadding
        );

    });

    // vertical lines
    if (i == 0) { // left table border
        Highcharts.tableLine(
            renderer,
            tableLeft,
            tableTop + cellPadding,
            tableLeft,
            tableTop + (serie.data.length + 1) * rowHeight + cellPadding
        );
    }

    Highcharts.tableLine(
        renderer,
        cellLeft,
        tableTop + cellPadding,
        cellLeft,
        tableTop + (serie.data.length + 1) * rowHeight + cellPadding
    );

    if (i == series.length - 1) { // right table border

        Highcharts.tableLine(
            renderer,
            cellLeft + colWidth,
            tableTop + cellPadding,
            cellLeft + colWidth,
            tableTop + (serie.data.length + 1) * rowHeight + cellPadding
        );
    }

});

A: You are using datetime xAxis, so you can't use categories in drawTable code. Instead use series[0].xData which contains all timestamps from points. See demo.
Changed part:
// draw category labels
$.each(chart.series[0].xData, function(i, name) {

    renderer.text(
        Highcharts.dateFormat('%a %d %b', name),
        cellLeft + cellPadding,
        tableTop + (i + 2) * rowHeight - cellPadding
    )
    .css({
        fontWeight: 'bold',

    })
    .add();
});

A: You can get the x axis labels using:
Highcharts.dateFormat('%a %d %b',point.x)

Something like this http://jsfiddle.net/jxSgM/.


text:
Q: Access a static variable from a class stored in a variable Given a class:
class SomeClass{
     static $information = 'useful information';
}

I a trying to access a static variable in a set of php classes. Each class has the $information static variable. If I access the static variable directly
echo SomeClass::$information;

The program outputs the information, however if I try to access it storing it in a variable I get a error that the '::' is unexpected.
$class = SomeClass;
echo $class::$information;

The reason for storing the class in a variable is so that I can have a function that can create an array of Users or an array of Projects for example.

A: You can do this:
$class = SomeClass::class;
echo $class::$information;

::class gets the fully qualified name of a class as a string.

A: class SomeClass {
  public static $information = 'useful information';

  public static function getInformation() {
    return self::$information;
  }
}

Then you can do the following:
# Static Access
echo SomeClass::$information;
echo SomeClass::getInformation();

# Static Access via Class Name in Variable
$someClass = 'SomeClass';
echo $someClass::$information;

## Instantiated access
$someClass = new SomeClass();
echo $someClass->$information;
echo $someClass->getInformation();

A: You can't store a reference to class in a variable, it is useless.
Instead you can store the class name in a variable and call the static method or variable:
$class = 'SomeClass';
echo $class::$information;


text:
Q: Cannot open database "Life" requested by the login. The login failed. Login failed for user I am getting the following in visual studio:

Cannot open database "Life" requested by the login. The login failed. Login failed for user...

My sqlconnection string is as follows:
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Life;Integrated Security=True");

What can I do to get this error to be solved.
In SQL Server Management Studio under Security-Studio-Properties under user- User mapping I tick db_owner
SQL Server agent is running
The database is on a local PC and not on a network

A: There are a number of things that you can check.  https://learn.microsoft.com/en-us/troubleshoot/sql/connect/resolve-connectivity-errors-overview
The most likely problems can be solved by making sure you have the correct database name and user name.  Your user name will be MYPCNAME\MyLoginName in order to use integrated security


text:
Q: after apt-get full-upgrade error on calling firefox I receive error messages like this one:
(/usr/lib/firefox/firefox:32569): dconf-WARNING **: 14:32:38.771: Unable to open /var/lib/snapd/desktop/dconf/profile/user: Keine Bere
chtigung
[Parent 32515, Gecko_IOThread] WARNING: pipe error (69): Die Verbindung wurde vom Kommunikationspartner zurückgesetzt: file /build/fir
efox-y_KX3Y/firefox-69.0.1+build1/ipc/chromium/src/chrome/common/ipc_channel_posix.cc, line 358

This is after running the following command:
$ sudo apt-get full-upgrade


text:
Q: What are the chances for getting bed head after a week? Does anyone happen to know an exact or approximate percentage as far as the chances for getting bed head goes? I'm trying to get one of my characters to get bed head, but I'm not having much luck. I know it takes at least a week, but after a few weeks of checking on my character weekly, it's not happened yet.
So is there a certain number of days I can wait where bed head will absolutely have happened? Or, similarly, can I just exit the game without saving and try again? Or will the game recognize that I played on that character recently?

A: I've heard that if you don't play the game for fifteen days, you will get bed head. I haven't proven this statement, so I don't know if it will actually work.  According to the wiki though, it should.
Source: http://animalcrossing.wikia.com/wiki/Bedhead

A: I do believe that you have to completely not check in for a minimum of two weeks or alternatively you can just skip ahead when Isabelle asks you to confirm the date at the title screen. Keep in mind though, that if you do do that then there will be consequences such as many weeds, cockroaches, some villagers moving out and your popularity decreasing.


text:
Q: nested for loops, all iterations are identical I'm new to Python and the following toy problem baffles me:
import numpy as np
V = np.ones([3,3])
Vini = V
Niter = 10
Vlist = list() # collect all iterations
Vlist.append(V)

for it in range(1, Niter-1):
    for ix in range(0,3):
        for iy in range(0,3):
            V[iy,ix] = Vlist[it-1][iy,ix] + 1
    Vlist.append(V) # save current iteration

(note that I am not after efficiency improvements – this is purely for didactic purposes)
My issue is that all elements of Vlist are identical, where I expected them to differ (by 1) at each iteration. Even Vini has changed its value! Is this a shallow/deep copy kind of thing, or something else? How do I fix this, and how do I reason about this kind of thing? (coming from other languages where a=b means deep copy).

A: Note that a variable holding an object in Python is something like
a "pointer" to the actual object (in other languages).
Your intention is to save in Vlist the curent content of V,
so each time you append something to Vlist, you should append
a copy of the object in question.
So change your code to:
Vlist.append(V.copy())
for it in range(1, Niter-1):
    for ix in range(0,3):
        for iy in range(0,3):
            V[iy,ix] = Vlist[it-1][iy,ix] + 1
    Vlist.append(V.copy())

By the way: You can generate just the same result running:
Vlist.append(V.copy())
for it in range(1, Niter-1):
    V += 1
    Vlist.append(V.copy())


text:
Q: What's the intuition behind the conjugate gradient method? I have been searching for an intuitive explanation of the conjugate gradient method (as it relates to gradient descent) for at least two years without luck.
I even find articles like "An Introduction to the Conjugate Gradient Method Without the Agonizing Pain" hard to understand.
Intuitively, what does this method do (e.g. geometrically) and why does it outperform gradient descent?

A: Just giving an intuitive overview. Michael Zubilevsky's lectures go through it in more technical detail.
Consider the quadratic objective $f(x) = x^T Q x + b^T x$. Geometrically, CG tries to "unwarp" some of the geometry induced by the quadratic form $Q$.
To build intuition, consider $Q \in \mathbb{R}^{2\times 2}$. If $Q = I$, then the contours of $f$ are circles. If $Q$ is diagonal, then the contours of $f$ are $x$-axis and $y$-axis aligned ellipses. If $Q$ has off-diagonal components as well, then there is "correlation" between the $x$ and $y$ directions, so the contours are ellipses whose principal axes are a combination of the $x$- and $y$-axis.
Now consider performing coordinate descent in the $Q=I$ or $Q$ diagonal case. We can reach the optimum in at most $2$ steps by viewing the problem as two $1$-dimensional minimization problems over each coordinate. We have this property because the $x$- and $y$-axis are orthogonal, and they "align" with the geometry of $Q$.
In the case where $Q$ contains off-diagonal components, CG finds orthogonal directions in $Q$'s geometry so that we can perform coordinate descent. We can use Gram-Schmidt to do the orthogonalization to find orthogonal directions, but if we start by orthogonalizing against the gradient, then we observe a lot of simplification in the update rule.
It outperforms gradient descent because by orthogonality of search directions, we ensure that we're never repeating a step along a direction we've searched in before. Thus we get rid of the "zig-zagging" of GD.
[EDIT: some additional notes here]

A: Check the full version of
Shewchuk (1994) An Introdution to the Conjugate Gradient Method without Pain
This pdf is a 64 page document with 40+ figures (full of geometric insights). The version you got is just a 17 page version of the full document, without figures.


text:
Q: xPath - number() and strings How does the function number() convert a string into a number? I've found out that it converts it to the closest mathematical expression, but this is not a clear answer. What exactly does it do?

A: Per W3c:

a string that consists of optional whitespace followed by an optional minus sign followed by a Number followed by whitespace is converted to the IEEE 754 number that is nearest (according to the IEEE 754 round-to-nearest rule) to the mathematical value represented by the string; any other string is converted to NaN

A: Phil Vallone has given the XPath 1.0 definition.
XPath 2.0 defines string-to-double conversion by reference to XML Schema 1.0, which defines it thus:
A literal in the ·lexical space· representing a decimal number d maps to the normalized value in the ·value space· of double that is closest to d; if d is exactly halfway between two such values then the even value is chosen. This is the best approximation of d ([Clinger, WD (1990)], [Gay, DM (1990)]), which is more accurate than the mapping required by [IEEE 754-1985].
XSD 1.1 however relaxes the rules:
Any ·lexical mapping· that maps the ·lexical space· just described onto the ·value space·, is a function, satisfies the requirements of [IEEE 754-2008], and correctly handles the mapping of the literals 'INF', 'NaN', etc., to the ·special values·, satisfies the conformance requirements of this specification... Since IEEE allows some variation in rounding of values, processors conforming to this specification may exhibit some variation in their ·lexical mappings·.


text:
Q: How to get the eigenvalues and eigenvectors with particular normalization condition in Matlab I have a question when I want to calculate the eigenvalues and eigenvectors of a complex 4*4 matrix M.
Let's take an example:
M=
[7.71  0.88 -0.47i 0.11i;
0.88 19.09 0.11i -0.02i;
-0.47i 0.11i -7.71 -0.88;
0.11i -0.02i -0.88 -3.44.]
It's something like, M*V=D*V, here V = [a1, a2, i *b1, i *b2], D is the eigenvalues.
a1,a2,b1,b2 are real values and i is the imaginary index.
If we use command eig(M) directly from MATLAB, it will give eigenvalues with norm(V)=sqrt(a1^2+a2^2+b1^2+b2^2)=1
But now I need the eigenvalues with condition a1^2+a2^2+(i *b1)^2+(i *b2)^2=1 instead of norm(V)=1
Please comment if anyone gets a hint.
Thanks a lot.
Best regards,
mike

A: For the first part of the solution the symbolic toolbox needed. since I do not have the symbolic toolbox at hand so I provide solution by Maxima:
you have 4 complex numbers forming an eigen vector say:
A: a1 + %i * a2;
B: b1 + %i * b2;
C: c1 + %i * c2;
D: d1 + %i * d2;

The %i symbol represents the imaginary unit.
The norm 2 of the vector is:
sqrt(cabs(A) ^ 2 + cabs(B) ^ 2 + cabs(C) ^ 2 + cabs(D) ^ 2).

Here cabs means complex abs.
So we seek a number v such that if we divide elements of the vector by it the resulting vector has this property:
(cabs(A / v) ^ 2 + cabs(B / v) ^ 2 + (%i * cabs(C / v)) ^ 2 + (%i * cabs(D / v)) ^ 2) = 1;

We can solve the equation for v :
A: a1 + %i * a2;
B: b1 + %i * b2;
C: c1 + %i * c2;
D: d1 + %i * d2;
eq: (cabs(A / v) ^ 2 + cabs(B / v) ^ 2 + (%i * cabs(C / v)) ^ 2 + (%i * cabs(D / v)) ^ 2) - 1;
solve(eq , v);

result:
v = sqrt([a1 ^ 2 + a2 ^ 2 + b1 ^ 2 + b2 ^ 2 - c1 ^ 2 - c2 ^ 2 - d1 ^ 2 - d2 ^ 2 ] )
  =sqrt (cabs(A) ^ 2 + cabs(B) ^ 2 - cabs(C) ^ 2 - cabs(D) ^ 2)

Matlab code for normalizing eigenvectors:
M=[...

7.71 0.88 -0.47i 0.11i;

0.88 19.09 0.11i -0.02i;

-0.47i 0.11i -7.71 -0.88;

0.11i -0.02i -0.88 -3.44];

% with nobalance eigenvector do not necessarily normalized
[VEC, D] = eig(M, 'nobalance');
ABS2 = abs(VEC).^2;
ABS2(3:4,:) = -ABS2(3:4,:);
v = sqrt(sum(ABS2,1));
VEC = bsxfun(@rdivide,VEC, v)


text:
Q: How to open a web page from QlikView? I am starting to use QlikView.
I need to open a web site from QlikView script, for instance something like

call ("wwww.mywebsite.com").

Is possible to call a website from QlikView Script?

A: Are you looking to launch a web page from a dashboard page component?  If so you can use a text object with an "Open URL" action. and specify the url (or an expression that returns a url)
If you need to use a web site as a datasource (ie a web service) then you can use the Web file wizard to construct the proper connection to the web service.

A: Yes, you have two options. You can either use the 'Web Files' wizard, or for more complicated web service calls you can use a macro and call it in your script.
Check out the following site:
http://blog.qvapps.com/2010/09/20/using-qlikview-with-web-services/