text:
Q: Design: How to obtain precise logs when logging from "High-level" classes Question
The following list of statements will quickly introduce my question:

*

*An Interface called IValidator represents a contract for a validation process,

*Some classes implement this interface with their own logic,

*The Main method owns a List of IValidator and uses them all to perform validation,

*The Main method needs to log an error if a validation goes wrong,

*I don't want classes implementing IValidator to know about log at all (to be able to concentrate all log actions in Main),

*I want the Main method to be able to log the reason of the validation failure.

The design question comes here: according to you what's the best way to have precise log about validation (i.e. why did the validation fail) when classes implementing validation don't know about log ?
Here is some code illustrating my question:
public interface IValidator
{
    bool Validate(String toValidate);
}

public class VowelValidator : IValidator
{
    public bool Validate(string toValidate)
    {
        // .. Insert validation process here...
        return true;
    }
}

public class LenghtValidator : IValidator
{
    public bool Validate(string toValidate)
    {
        // .. Insert validation process here...
        return false;
    }
}

public class Manager
{
    public static void Main()
    {
        List<IValidator> validators = new List<IValidator>()
        {
            new VowelValidator(),
            new LenghtValidator()
        };

        foreach (var validator in validators)
        {
            if (!validator.Validate("FooBar"))
            {
                /*
                 * Handle log here.
                 * I'd like to log something like "failed because string is too long"
                 * or "failed because string does not contain vowels".
                 */
            }
        }
    }
}

Some possibilities

*

*I could add a String GetValidationDescription() method to the IValidator and use it in Main to get a description of the validation that failed

*

*But this means that every time I face that problem I'll have to add extra-methods only for log's sake. I'm not very happy with that.

*I could log the actual type of the IValidator that failed (i.e. "Validation failed on LengthValidator") using GetType(). Then when I read the log I have to remember what that particular validator does and I can understand what went wrong.

*

*This implies remembering / finding out what the validator does: no all information appears in the log.

Do you have other suggestions ?
Are you aware of a common pattern for this kind of problem ?
Christophe.

A: Your current design for the validators is that they return true/false and do other information, but your requirement is to get some details about the failure, so you must change the interface or accept that the only thing you can log is that ValidtorXyz said "no".
Maintain a separation of concerns:

*

*The validator validates and reasonably report why validation fails

*The Logger logs information, so if it knew the the why it could log it, in some other scenario a UI might display the why
So logging is very clearly not the responsibility of the validator.
Adding a getValidationDescription() to the interface does not seem bad to me. It's quite legitimate for any object to describe itself - we do have toString() methods everywhere. There's nothing to say this is used specifically for logging.
However, a complex validator, for example a date validator, might fail for several reasons (eg. badly formatted input, month out of range ...) so I think you would do better to have as part of the result reasonForFailure.
One approach: create a return type object.
  class ValidationResult{
       boolean isValid;
       String validationDescription;
       String failureReason;
  }

another approach provide a failure callback
   validate(String input, IOnError callThisOnError);

where main provides:
   class OnError implements IOnError {
         void reportError(String input, String failureReason);
   }


text:
Q: How To Get Text From "A" Tag - Python Selenium (Categories, Subcategories, Sub-subcategories) I need to get parent categories, subcategories and sub-subcategories. I'm getting the items in the main category without any problems. While retrieving the elements in the subcategory, I can capture the Selenium element, but the text is coming empty. What should I do?
My Python codes:
mainCategories = driver.find_element(By.ID, "mainMenu").find_elements(By.TAG_NAME, "li[class='categories']")

for i in mainCategories:

    subCategories = i.find_elements(By.TAG_NAME, "li[class='subs']")

    for j in subCategories:
        print("j = ", j)              # it returns Selenium elements and its length matches the subcategories.
        print("j.text = ", j.text)    # it returns ""

My Html like this:

        Main Category 1

                    ...

                        Subcategory 1

Sub-subcategory 1

Sub-subcategory 2

                            ... Other Sub-subcategories' li's ...

                    ... Other Subcategories' li's ...

    ... Other Main Categories' li's ...

Thanks in advance for your help.

A: The texts of sub categories is presented in a elements below the li elements you are locating.
Please try this, it should give you sub categories texts:
mainCategories = driver.find_element(By.ID, "mainMenu").find_elements(By.TAG_NAME, "li[class='categories']")

for i in mainCategories:

    subCategories = i.find_elements(By.XPATH, ".//li[@class='subs']/a")

    for j in subCategories:
        print("j = ", j)
        print("j.text = ", j.text)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relative velocity from space-time diagram Consider two frames of reference, with velocities V1 and V2 relative to an initial ground frame.  I have made the space-time diagrams for the three frames (Time represented on Y-axis).

As far as I know, the relative velocity between frame-1 and frame-2 (relative velocity is represented in green) is the projection of net velocity of frame-2 (i.e., t2 axis) on space-1 (x1) axis or Vise-Versa.
So,
  Considering $c = 1$,
$=> V21 = \sin(\beta-\alpha)$
$=> V21 = (\sin\beta \cos\alpha  - \cos\alpha \sin\beta)$
We can simply calculate values of sines and cosines.
$\sin\alpha = V1/1 = V1$
$\sin\beta = V2/1 = V2$
$=> V21 = ( V2\sqrt{(1-V1^2)} - V1\sqrt{(1-V2^2)})$
While we know the correct formula,
$V21 = (V2-V1)/(1-V1V2)$
What is wrong with this approach to find relative velocities?
It worked correctly for calculating the space-time transformation relations between two frames.
Sorry for the bad diagram.

A: The problem is that your spacetime diagram is wrong: you're using Euclidean geometry, when you should be using Minkowski. The actual diagram, if you'll forgive the low quality picture, looks something like this:

where I've drawn the $t^2 - x^2 = \pm 1$ hyperbolae, and the angles obey $\tan \alpha = v_1$ and $\tan \beta = v_2$. Note that that unit vectors have unit length with respect to the Minkowski metric but not with respect to the Euclidean metric: they lie on a hyperbola, not on a circle.
If you want to see how things look from frame 1, you have to move everything out along the hyperbolae:

where now $\delta$ is the unknown angle we want to find. To find it geometrically, however, we need to do some algebra first, because the geometry is hyperbolic, and it doesn't correspond to what happens when we draw on paper. And the key fact we need is that if given a velocity $v$ we define the rapidity $\eta$ by $v = \tanh \eta$, such that $\eta$ goes from zero to infinity as $v$ goes from zero to one, then when doing Lorentz transformations, rapidities simply add. This is still geometric, in a sense, because rapidity is a parameter along the hyperbolae, though it's not the usual arclength.
From this, the velocity addition formula is straightforward if we know our hyperbolic identities: since rapidities simply add and subtract, we have that $\eta_{21} = \eta_2-\eta_1$, and
$$v_{21} = \tanh(\eta_2 - \eta_1) = \frac{\tanh{\eta_2} - \tanh{\eta_1}}{1 - \tanh{\eta_2}\tanh{\eta_1}} = \frac{v_2 - v_1}{1 - v_1 v_2}.$$


text:
Q: How to select one Tkinter Radiobutton per variable I am trying to make a loop that populates 9 radio buttons, each with 4 options, and placed in a grid. The following code words, however, I can select more than one option for each question. My understanding is that for each variable I should only be able to select one. Is the loop constructed incorrectly?

MODES = [
    ('dep_name1', 'dep_but1', 2, "Not at all", 'op1'),
    ('dep_name2', 'dep_but2', 3, "Several days", 'op2'),
    ('dep_name3', 'dep_but3', 4, "More than half the days", 'op3'),
    ('dep_name4', 'dep_but4', 5, "Nearly everyday", 'op4'),
    ]

for r in range (2, 11):
    for dep_name, button, c, text, b_val in MODES:
        button = tk.StringVar()
        # button.set("L")
        dep_name = tk.Radiobutton(window, text=text, variable=button, indicatoron=0, value=b_val).grid(row=r, column=c, sticky='e')

window.columnconfigure("all", weight=1)
window.rowconfigure("all", weight=1)

window.mainloop()

A: You are creating one variable for each radiobutton. You should have one variable for each group of radiobuttons.
Since the variable can have only one value at a time, tkinter uses the variable to know which radiobuttons belong to a logical group. That is to say, all radiobuttons with the same variable are one logical group of buttons.
Here's one way to do it:
vars = []
for r in range (2, 11):
    var = tk.StringVar(value="op1")
    vars.append(var)
    for dep_name, button, c, text, b_val in MODES:
        tk.Radiobutton(window, text=text, variable=var, indicatoron=0, value=b_val).grid(row=r, column=c, sticky='e')

This example saves the variables to a list so that you can reference them by index elsewhere in your code.
I don't quite understand what dep_name and dep_button are supposed to represent. In both cases you initialize them from MODES, but then you change them inside the loops. Regardless, the point is that you need to create the variable just inside the outer loop so that you create one variable for each group of radiobuttons.


text:
Q: How To write a server side script using jsp and java and How to run it? I am new to this technology, I dont no how to write a server side program and how to run before jsp page start to load. Any one can you please guide me how to do it?
Thanks in Advance,
Ver

A: First install a server like Tomcat and start it.
Run the examples that are available out of the box at http://localhost:8080/examples
Click on the JSP or servlet examples in the browser, and click on Execute for any one of those.
Then navigate to the examples directory on the file system under /webapps/examples/
The simple thing is to try changing the JSP code there, and start modifying the code in there to get a better hang of things.


text:
Q: Invalid escape sequence \\ is used but it still doesnt work in java for my file path I have read the other posts and answers and applied them but it still doesnt work.
I am brand new to Java in my class but it's online and accelerated so it's a bit difficult for me to understand at a quick pace so please bear with me if i don't understand.
String fileName = "C:\\Users\\Jonathan Lee\\eclipse-workspace\myfile.text";

I have that and I've tried different amount of backslashes but that seems to create even more errors.

A: You will have to escape each backslash like that: String fileName = "C:\\Users\\Jonathan Lee\\eclipse-workspace\\myfile.text"


text:
Q: Fill whole div with an image regardless of image size not working I'm trying to fill a whole div with an image, regardless of the size of the image, but for some reason the image is only as big as it's default size. It does not automatically stretch to fit the size of the div. I tried setting the width and height of the image to 100%, thinking that it'll fit the div that way, but the image still stayed in its default size. Is there a way to automatically stretch an image to fill a div, without testing and changing each image by hand?

A: From your question, it is unclear whether you are trying to use a background image or an img element to fill the div.
If you want to fill the div using an img element, the code you've posted will already do that for you. You just need to place an img element within the div, such as:

If you want to stretch the image to fill the div using it as a background image, you simply need to add the value cover to the background-size property:
background-size:cover;

JSFiddle for img element
JSFiddle for background image

A: The  tag is an html element that has nothing to do with the background image of that
.
As APAD1 correctly points out, the proper way to force a background image to fill an html element is to use background-size.

*

*background-size: contain fills the element until the background image touches the first edge of its container (maintaining the aspect ratio).

*background-size: cover fills the element entirely while maintaining the aspect ratio of the image.

*background-size: 100% 100% fills the element entirely so that the background image touches the edge of the element on all sides (thus potentially distorting the image).


text:
Q: How can I load a data file into external SRAM via Quartus I am working with a Cyclone V GX starting board. It has 4mb of external SRAM. I have written a very simple memory interface for accessing it. That works.
Now I would like to load a raw (hex?) file into the external SRAM on my board for my FPGA to work with. Is there an easy way to accomplish this via Quartus II?
edit:
I am not looking for a way to program my FPGA (by loading a design), this is clear to me. My FPGA has already has my micro-controller design loaded. Now I want to load a program (in the form of raw data) for it into the external SRAM on my board.

A: No, it is not possible to access the SRAM of the Cyclone V GX Starter Kit directly from Quartus II. From page 37 of the User Manual, the SRAM is only connected to the FPGA. Thus, the user application in the FPGA will need to be responsible for writing the desired data into the external memory.
As mentioned by Zuofu, the Terasic "C5G Control Panel" can access the SRAM for you, allowing single-word R/W access or doing R/W to/from a file. This uses the Terasic custom user application to send data using JTAG into a Nios II program implementing a SRAM interface. As mentioned in their later comment, since SRAM is fully static, you could load your HEX file using the Control Panel, then reprogram the FPGA using Quartus II with your own application. With the board powered on continuously, the SRAM contents will still be available for your application to access.
The trick won't work for the larger LPDDR2 because, as a dynamic memory, reprogramming the FPGA would leave the device without a controller to complete refresh cycles in the memory. Thus, you would expect memory corruption to occur.
To include this sort of feature in your own application, you would have to implement both ends of a JTAG communication system to move data to/from your computer and onto the FPGA for sending to the SRAM.

A: The "Control Panel" application provided by the actual manufacturer (Terasic) should let you do this: Cyclone V GX board


text:
Q: Not sure how to handle exceptions using try catch if element was not found I am trying to handle the error message on login page by clearing the Username field from the entered input.
Here is my code:
using OpenQA.Selenium;
using System;
using System.Linq.Expressions;
using TestProject.Common.Extensions;
using TestProject.SDK;
using TestProject.SDK.Tests;
using TestProject.SDK.Tests.Helpers;

namespace SecondTest
{
    public class LoginTest : IWebTest
    {
        public object Assert { get; private set; }
        public object TimeUnit { get; private set; }
        public object InvalidInputErrorTxt { get; private set; }
        public bool IWebelement { get; private set; }
        public bool ErrorMsg { get; private set; }

        public ExecutionResult Execute(WebTestHelper helper)
        {
            var driver = helper.Driver;
            var URL = "https://www.office1.bg/login";
            driver.Navigate().GoToUrl(URL);
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            driver.FindElementById("CybotCookiebotDialogBodyLevelButtonAccept").Click();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            //Login
            Pages.LoginPage LoginPage = new Pages.LoginPage(driver);
            LoginPage.PerformLogin("atanas.grudev1@gmail.com", "123456789");
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            try
            {
                IWebElement Level = driver.FindElementByClassName("corporal-page-list-item");
                if (Level.Displayed)
                {
                    Level.Click();
                    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
                    driver.FindElementByClassName("corporate-login-button-wrapper").Click();
                    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
                    return ExecutionResult.Passed;
                }
                else
                {
                    IWebElement ErrorMsg = driver.FindElementByXPath("//*[@id='loginForm']/div/div[1]");
                    if (ErrorMsg.Displayed)
                    {
                        LoginPage.TxtUserName.Clear();
                        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
                        return ExecutionResult.Failed;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return ExecutionResult.Passed;
        }
            }
        }

Seems ExecutionResult at the beginning requires return ExecutionResult.Passed/Failed; at the end of the code, but since I have try - catch I am not sure how to get the correct result. End goal is:
If valid credentials are entered code from the first if statement should be executed and to get Passed result.
If the entered credentials are not valid the website will throw an error and if the error is present on the the screen the input from the username field should be cleared and get the Failed Result.
Thank you in advance!

A: A few suggestions:

*

*In general, you want to avoid use of try-catch to control code flow whenever possible. In this case, you can use driver.FindElements() (note the plural ElementS) and check for an empty list to avoid exceptions being thrown when no element is found. This is a best practice according to the docs.

findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.

*Setting the timeout for ImplicitWait only needs to be done once. Once set, that timeout is applied automatically every time an element is searched for. It doesn't actually wait when called... I think maybe you are confusing it with WebDriverWait?

*Using ImplicitWait is not recommended by the Selenium contributors. You should instead use WebDriverWait each time you need to wait.

*I would suggest you investigate and use the Page Object Model. If done right, it will save you a lot of time with code reuse, make your project much more organized, and make your test code a lot cleaner. It looks like you are trying to use something like Page Objects with your LoginPage.PerformLogin() call but all your driver.FindElement() calls should be in the appropriate page object and you should have one page object per "page".
Here's the code after implementing the first two suggestions. I'll let you do #3 and #4, if you choose to. I removed the try-catch, added new ifs, and removed all but the first ImplicitWait set.
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using TestProject.Common.Extensions;
using TestProject.SDK;
using TestProject.SDK.Tests;
using TestProject.SDK.Tests.Helpers;

namespace SecondTest
{
    public class LoginTest : IWebTest
    {
        public object Assert { get; private set; }
        public object TimeUnit { get; private set; }
        public object InvalidInputErrorTxt { get; private set; }
        public bool IWebelement { get; private set; }
        public bool ErrorMsg { get; private set; }

        public ExecutionResult Execute(WebTestHelper helper)
        {
            var driver = helper.Driver;
            var URL = "https://www.office1.bg/login";
            driver.Navigate().GoToUrl(URL);
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            driver.FindElementById("CybotCookiebotDialogBodyLevelButtonAccept").Click();

            //Login
            Pages.LoginPage LoginPage = new Pages.LoginPage(driver);
            LoginPage.PerformLogin("atanas.grudev1@gmail.com", "123456789");

            IReadOnlyCollection<IWebElement> level = driver.FindElementsByClassName("corporal-page-list-item");
            if (level.Any() && level.ElementAt(0).Displayed)
            {
                level.ElementAt(0).Click();
                driver.FindElementByClassName("corporate-login-button-wrapper").Click();

                return ExecutionResult.Passed;
            }

            IReadOnlyCollection<IWebElement> errorMsg = driver.FindElementsByXPath("//*[@id='loginForm']/div/div[1]");
            if (errorMsg.Any() && errorMsg.ElementAt(0).Displayed)
            {
                LoginPage.TxtUserName.Clear();
                return ExecutionResult.Failed;
            }

            return ExecutionResult.Passed;
        }
    }
}

A few notes on the new code that you may not have seen before.

*

*.Any() is an equivalent in LINQ to .Count > 0. It returns true if the list is not empty, and false otherwise.

*.ElementAt() is a LINQ method that allows you to access a member of the collection by index. NOTE: Even though it has "Element" in the name, it has nothing to do with WebElement or Selenium.

Let me know if you have any questions.


text:
Q: PDE / Calculus of Variations problem from Evans I'm trying to learn Calculus of Variations and I can't solve the following problem from Chapter 8 of Larry Evans' PDE book. Could someone please help with a solution?
Let $\Sigma \subset \mathbb{R}^3$ denote the graph of the smooth function $u: U \to \mathbb{R},$ $U \subset \mathbb{R}^2.$ Then $$\int_U (1+|Du|^2)^{-2} \; \text{det}(D^2u) \; dx$$ represents the integral of the Gauss curvature over $\Sigma.$ Prove this expression depends only on $Du$ restricted to $\partial U.$

A: That can be done, though it is a bit messy. In the following we let $f_{ij}$ denotes the partial derivative $\frac{\partial^2 f}{\partial x^i \partial x^j}$. Basically you want to show that for any $u$,
$$ \frac{d}{dt}\bigg|_{t=0} \mathcal F (u_t) = 0, $$
where $u_t = u+ t\varphi$ for any $\varphi \in C^\infty_0(\Omega)$ and $\mathcal F (f) = \int_{\Omega} (1+ |Df|^2)^{-a} \det (D^2 f) \ \mathrm dx$.
Direct calculations give
\begin{align}
&\frac{d}{dt}\bigg|_{t=0} \mathcal F (u_t) \\
&=\int_\Omega \left(\frac{-2a \det (D^2 u)}{(1+ |du|^2)^{a+1}} \langle D u , D \varphi\rangle+ \frac{1}{(1+ |Du|^2)^a } ( \varphi_{11} u_{22} + \varphi_{22} u_{11} - 2\varphi_{12}u_{12})\right) \mathrm dx.\end{align}
For the second term, one use integration by part twice to get
$$\int_\Omega \left( \frac{\varphi_{11} u_{22} - \varphi_{12} u_{12} }{(1+|Du|^2)^a}\right) \mathrm  dx = \int_\Omega \frac{2a\det D^2 u}{(1+ |Du|^2)^{a+1}} \varphi_1 u_1\mathrm d x.$$
and similarly
$$\int_\Omega \left( \frac{\varphi_{22} u_{11} - \varphi_{12} u_{12} }{(1+|Du|^2)^a}\right) \mathrm  dx = \int_\Omega \frac{2a\det D^2 u}{(1+ |Du|^2)^{a+1}} \varphi_2 u_2\mathrm d x.$$
thus these two terms cancel the first term and thus the derivative is zero. This implies $\mathcal F(u)$ is invariant under any interior perturbation and thus depends only on its value on the boundary. Clearly it does not depend on $u$. But it is not clear to me why it depends only on $Du$ (even when $a=2$ or $3/2$).

A: The question includes a hint, which alludes to the Gauss-Bonnet theorem,
$$ \int_M K \,\mathrm{d}A + \int_{\partial M} k_g \,\mathrm{d}s = 2\pi \chi(M). $$
Since the integral corresponds to the first term with $M = \text{graph of } u$ which is homotopy equivalent to $U$ (so $\chi(M)=\chi(U)$), the result follows.
So it remains to show that,
$$ \int_M K \,\mathrm{d}A = \int_U (1+|Du|^2)^{-3/2} \mathrm{det}(D^2u) \,\mathrm{d}x.$$
This follows from the fact that
\begin{align}
  K &= \frac{\mathrm{det}(D^2u)}{1+|Du|^2},\\
  \mathrm{d}A &= \sqrt{1+|Du|^2}\,\mathrm{d}x,
\end{align}
 with respect to the local paramerization $\varphi(x) = (x,u(x)).$ In theory this is not difficult to show, as you have an explicit formula for the Gaussian curvature in terms of $\varphi$ and its derivatives. The computation however is quite painful and I don't know if there are ways to simplify it.

Comment: One may wonder if there's an easier way of showing this. Since the quantity only depends on the values of $u$ on $\partial U,$ we may try to write it as the divergence of something and apply the divergence theorem.
Unfortunately, the Gauss-Bonnet theorem suggests this isn't possible. The RHS includes $\chi(M) = \chi(U),$ which is a topological invariant which doesn't straightforwardly depend on only it's boundary. So you can probably apply the divergence theorem to write the desired quantity as $\mathrm{div}\,F(u) + G(u)$ where $\int_U G(u)$ is independent of $u$ and corresponds to some topological quantity. However such an approach would also require some form of differential topology along the way.


text:
Q: "Non-selective query against large object type" only occurs in trigger context despite filtering on lookups I have a very simple after delete trigger that searches for orphan records and deletes them:
List<my_ns__Orphanable_Object__c> orphans = Database.query(
    ' SELECT ' +
        ' Id ' +
    ' FROM ' +
        ' my_ns__Orphanable_Object__c ' +
    ' WHERE ' +
        ' my_ns__Lookup1__c = null ' +
        ' AND my_ns__Lookup2__c = null ' +
        ' AND my_ns__Lookup3__c = null ');

One of our customers has a large amount of data in the "Orphanable Object" and recieves this error when deleting a record:

System.QueryException: Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when:1. The filter value includes null (for instance binding with a list that contains null)2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)

What I can not understand is; why does this only happen in the trigger context?
To debug the issue I ran the same code in the devloper console and it ran without issue and the orphans list contained ~250 records. This also removed the possibitlity that the query was returning too many results.

A: That error appears here and a few similar threads I found that triggers are more sensitive to this restriction, although I can't find official documentation on it.
Your my_ns__Orphanable_Object__c table does contain more than 100k rows, right? If so, the returned row count is irrelevant; SFDC is complaining that your query requires a tablescan, and doesn't allow that in this scenario.
To stop the exception, you need to adjust your criteria to be "selective". Specifically, you need to filter on an indexed column. Based on the column names, it looks like you are filtering on lookups, which is good because they are indexed. (The common fix for normal string or number columns is to mark them as External ID, which indexes them.)
But you are filtering on the NULL value, which Salesforce does not consider selective. That's why I think you are seeing the error.
I'm sure there are more elegant workarounds, but the immediate one that comes to mind is:

*

*create a new hidden numeric field, something like Deletable__c. Mark it External ID.

*create a field update workflow that populates that field with a 1 when any of the lookups are null, otherwise a 0.

*use that field in your trigger query.

Totally untested and as I said, there is probably a more elegant workaround, but something like that should work. You could also consider filtering on LastModifiedDate if feasible since date fields are indexed as well.

A: Two things. First, you should check out the Query Plan tool, which might help you here. Second, I would recommend using a formula checkbox to determine records where all three lookups are null.
Is_Orphan__c
    AND(
        ISNULL(my_ns__Lookup1__c),
        ISNULL(my_ns__Lookup2__c),
        ISNULL(my_ns__Lookup3__c)
    )

Then your query becomes:
SELECT Id FROM my_ns__Orphanable_Object__c WHERE Is_Orphan__c = true

No checks against null so no table scan.


text:
Q: How to prevent unwanted hook requests? I developed an application that works with Github and Github Hooks, when a new hook request received, I just update/clone the repository (and then I do a little process on repository)
Because I accept all hook requests blindly, everyone can generate a hook request and send it t me.
I want to know how can I protect my application from unwanted hook requests?

A: Github does not include any secret information with the payload (based on https://help.github.com/articles/post-receive-hooks).
So your best defense is to make the url of your webhook hard to guess by using a random string in the url of your web hook.
You may also consider, although this may break over time, checking that request.connection.remoteAddress is within a range of addresses that are know to belong to Github host (Rackspace at the moment?).  This answer includes know ip addresses: How to verify a post-receive hook request actually came from github?


text:
Q: How to add background linear-gradient to iOS Safari, Mac Safari, Edge, and IE11? We are attempting to use background: linear-gradient() to get the following output. However, we are running into a problem where the css is not being applied to the following browsers.
Question:
How can we get it to work on all browsers?
Browsers with issues

*

*Mac High Sierra Safari 11.1

*IE11

*Microsoft Edge 44.17763.771.0

*Safari on iOS (v12)

What we tried

.box {
  padding:20px;
  display:inline-block;
  border-right:2px solid #000;
  border-left:2px solid #000;
  background:
    linear-gradient(to left ,#000 10px,transparent 10px 30px,#000 0) top,
    linear-gradient(to right,#000 10px,transparent 10px 30px,#000 0) bottom;
  background-size:100% 2px;
  background-repeat:no-repeat;
}
<div class="box">
Some text inside
</div>

A: Double position color stops are not supported in IE/Edge and Safari < v13.
https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
Simply change your code as such:
background:
    linear-gradient(to left ,#000 10px,transparent 10px, transparent 30px, #000 0) top,
    linear-gradient(to right,#000 10px,transparent 10px, transparent 30px, #000 0) bottom;


text:
Q: Find the image of line that go through zero under the exponential function I am trying to find the image of $f(z)=e^z$ while $ z \in \mathbb{C}$. z is a line that go through the origin.
I know that $z=x+iy$ while $x,y$ real numbers. Writing $$e^{z} = e^x(\cos y + i\sin y),$$
now the meaning of the set is that $y=nx \quad n \in \mathbb{R}$
so I substitute this condition and get
$$e^x(\cos nx + i\sin nx)= e^x(\cos x + i\sin x)^n.$$

*

*Is my method correct?

*What is this set? can I say that $e^x(\cos nx + i\sin nx)$ is a circle with radius $e^x$? how does it look on the plane?

A: I don't think your parameterization is quite right. You have $y = nx$, $n\in\mathbb{R}$, so your set is $\{(x,nx): n\in \mathbb{R}\}\subset\mathbb{R}^2$. But you're paramterizing $z$ a line through the origin in the complex plane. Your line through the origin in the real plane is a different set.
You want to find the image of a line through the origin in the complex plane. We can parametrize this as $z(r) = re^{i\theta}$, where $r\in \mathbb{R}$ and $\theta$ is constant. So $$f(z(r)) = e^{re^{i\theta}} = (e^{e^{i\theta}})^r.$$ Since $\theta$ is fixed $e^{e^{i\theta}}$ is a constant complex number, denote it with say $c$. Then $f(z(r)) = \{c^r: r\in \mathbb{R}\}$.


text:
Q: Set of java Protobuf objects vs Class objects behave differently Creating a set of objects from a generated protobuf class with the same values identifies and removes the duplicate items from the set (Is this because of matching hashCode()?). However creating the Set with a class having the same members and objects with the same data doesn't remove the duplicate item from the set since it allocates new address to the created object. How does protobuf maintain the addresses to the objects it creates and provide the same object when a new object with the same values is created? Can someone please explain why there is this difference in the Set<> construction?
Consider the following class called NodeJava which is an class defining a node in a network with members host,port.
public class NodeJava {
    private String host;
    private Integer port;

    public NodeJava(String host, Integer port) {
        this.host = host;
        this.port = port;
    }
}

Now Let's create  HashSet of NodeJava objects as follows:
Set<NodeJava> nodes = new HashSet<>();
nodes.add(new NodeJava("localhost", 12345)); // New address to each of the objects
nodes.add(new NodeJava("localhost", 12346));
nodes.add(new NodeJava("localhost", 12346));
System.out.println(nodes.size());  // 3 is the result

Similarly, defining the NodeJava as a protocol buffer message and using the resulting java generated class.
message NodeProto {
    string host = 1;
    uint32 port = 2;
}

We can build an object using the builder pattern as follows:
private NodeProto create(String host, Integer port) {
    NodeProto.Builder node = NodeProto.newBuilder();
    node.setHost(host);
    node.setPort(port);
    return node.build();
}

Similarly creating a set of these objects results in a different result:
Set<NodeProto> nodes = new HashSet<>();
nodes.add(create("localhost", 12345));
nodes.add(create("localhost", 12346));
nodes.add(create("localhost", 12346)); // Same address as older
System.out.println(nodes.size());  // 2 is the result

A: Sets use equals (and by extension hashCode) to determine whether two objects are the "same". In your NodeJava class, you don't implement equals, so two objects are equal only if they are the same object (i.e. if a==b).
If you look at the code for NodeProto that gets generated, it's likely you'll find an implementation of equals (and a corresponding implementation of hashCode) that takes the values of the fields into account, so even though the second and third instances that you create are separate objects, they are considered equal.


text:
Q: django how to secure my project I work on a project where I'll have to configure remotely some products.
These products have a sim card and can connect on internet through gsm so I won't be able to connect to them directly.
Customers will connect on my website to make configuration requests on their products by filling forms, when they are done, I save in DB all products new config and I will send a sms to each products, the sms make the products know that they have to connect with http to an url specified in the sms, when they connect to the url I identify the product with their serial number and send their new configurations.
Now I don't really know how to secure all the data sended in the sms or the manage the authentification from the product to my server.
I thought to make an authentification based on a MD5/SHA HASH formula, but the problem is that the secret used to hash will be stored in the product and if the secret and the formula gets to be known, it will become critical.
Maybe using dynamic hash with date of the day with product infos would be better. HTTPS could resolve everything maybe but I just can't only use the serial number of the product as authorisation.
I thought also to add a private key infra but I think its too complex.
I would encrypt data with product public key for example and the product would encrypt data with my server public key, but I don't know if its too hard to implement this architecture.
I use django framework, ngnix.

A: I think your confusing what a 'hash' is, with encrypting/decrypting data.  A hash is typically one way, with no means to (easily) 'unhash' the information that has been transferred.
The weakest link in your design is the very limited SMS (text messaging) system for transferring the data.  It lacks the ability to use a large/full character set (such as binary) - which means encrypted messages would have to be quite long to be secure.  But it also limits the length of messages, so these long encrypted messages could not be sent.
As mentioned in the comments, this question is too general to provide a specific answer to.  But if these were 'smart' devices, a dedicated configuration 'app' - using SSL - would likely be your best solution.


text:
Q: Why is a transparent JButton showing images of the frame when transparency is added? I'm developing a GUI for a Java application and I want to have a background image. The problem is that I have a type of "drawer" filled with buttons, that has buttons highlighted in red when are selected.
Im using the method buttonName.setBackground(new Color(255, 102, 102, 200)); to set the highlited button and the transparency at the same time. The problem is that despite that the method works and transparents the button, the transparency shows random parts of the frame behind the button, beign these the header, another button, the scrollbar of the JScrollPane where the buttons are located, etc. The text of the button still shows up, and the button works, but the background shows the text from other buttons or parts of the frame.
Besides, I realized that if I click a button and pass the mouse over the selected button multiple times, the transparency starts to accumulate to the point that it gets to a solid color.
package buttonsbug;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

/**
 *
 * @author F&H
 */
public class ButtonsBug extends JFrame implements ActionListener {

    private ArrayList<JButton> botones;
    private JLabel panelPrin, panelNav, panelUser, panelImgUser, nombre, puesto;
    private JButton logout, planDis, consuEmpleados, funConsultarPiezas, btnCalidad, compraMat, soySuper, histProy, crearProyecto, clientes, adminConsProye;
    private JPanel buttonScroll;
    private JScrollPane navScroll;
    private BufferedImage img;
    private Dimension screenSize;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new ButtonsBug().setVisible(true);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    System.exit(0);
                }
            }
        });
    }

    public ButtonsBug() {
        botones = new ArrayList<>();

        screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setSize(ajustarDimensiones(1400), ajustarDimensiones(800));

        setContentPane(panelPrin = new JLabel());
        panelPrin.setSize(ajustarDimensiones(1400), ajustarDimensiones(800));
        try {
            img = ImageIO.read(new File("src/tw3.png"));
            Image dimg1 = img.getScaledInstance(panelPrin.getWidth(), panelPrin.getHeight(), Image.SCALE_SMOOTH);
            ImageIcon imageIcon = new ImageIcon(dimg1);
            panelPrin.setIcon(imageIcon);
        } catch (IOException z) {
            System.out.println(z.getMessage());
            JOptionPane.showMessageDialog(this, "¡Error en la lectura de imagen!", "Error", JOptionPane.ERROR_MESSAGE);
        }

        panelPrin.setBackground(java.awt.Color.white);
        panelPrin.add(panelNav = new JLabel());
//        panelPrin.setOpaque(true);

//        panelNav.setOpaque(true);
        panelNav.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
//        panelNav.setBackground(new Color(0, 0, 0, 150));
        panelNav.setBounds(0, 0, ajustarDimensiones(305), ajustarDimensiones(771));
        panelNav.add(panelUser = new JLabel());
        panelNav.add(logout = new JButton());
        logout.setContentAreaFilled(false);
//        logout.setOpaque(true);

//        panelUser.setOpaque(true);
        panelUser.setBounds(ajustarDimensiones(1), ajustarDimensiones(1), ajustarDimensiones(303), ajustarDimensiones(88));
        panelUser.add(panelImgUser = new JLabel());
        panelUser.add(nombre = new JLabel());
        panelUser.add(puesto = new JLabel());
        nombre.setText("Wil Fonseca");
        puesto.setText("Production manager");

        nombre.setBounds(ajustarDimensiones(55), ajustarDimensiones(25), ajustarDimensiones(245), ajustarDimensiones(20));
        puesto.setBounds(ajustarDimensiones(55), ajustarDimensiones(45), ajustarDimensiones(245), ajustarDimensiones(20));
        nombre.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(14)));
        puesto.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(12)));
        nombre.setForeground(Color.white);
        puesto.setForeground(Color.white);

        logout.setText("Logout");
        logout.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(34)));
        logout.setBounds(ajustarDimensiones(1), ajustarDimensiones(691), ajustarDimensiones(303), ajustarDimensiones(88));
        logout.setBackground(Color.white);
        logout.setForeground(Color.red);
        logout.addActionListener(this);
        logout.setBorder(null);
        logout.setBorderPainted(false);
        logout.setFocusPainted(false);

        panelImgUser.setBounds(ajustarDimensiones(3), ajustarDimensiones(24), ajustarDimensiones(40), ajustarDimensiones(40));

        try {
            img = ImageIO.read(new File("src/Usuario.png"));
            Image dimg1 = img.getScaledInstance(panelImgUser.getWidth(), panelImgUser.getHeight(), Image.SCALE_SMOOTH);
            ImageIcon imageIcon = new ImageIcon(dimg1);
            panelImgUser.setIcon(imageIcon);
        } catch (IOException z) {
            System.out.println(z.getMessage());
        }

        setTitle("ButtonsBug");
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);

        buttonGenerator();

    }

    public int ajustarDimensiones(int coo) {
        int newC = 0;
        double res = (screenSize.getHeight());
        float newRes;
        if (res < 1080) {
            if (coo == 1400) {
                return 1208;
            } else if (coo == 800) {
                return 680;
            }
        }
        if (coo == 0) {
            return newC;
        } else {
            if (res < 1080) {
                newRes = (918f / 1080f);
                if (coo == 305) {
                    newC = (int) (newRes * coo) - 1;
                } else if (coo == 90) {
                    newC = (int) (newRes * coo) - 1;
                } else if (coo == 224) {
                    newC = (int) (newRes * coo) - 1;
                } else if (coo == 601) {
                    newC = (int) (newRes * coo) + 3;
                } else if (coo == 1066) {
                    newC = (int) (newRes * coo) - 1;
                } else if (coo == 1474 || coo == 1576) {
                    newC = (int) (newRes * coo) + 1;
                } else if (coo == 1059) {
                    newC = (int) (newRes * coo) - 10;
                } else if (coo == 1095) {
                    newC = (int) (newRes * coo) + 14;
                } else {
                    newC = (int) (newRes * coo);
                }
            } else {
                newRes = (float) (res / 1080f);
                newC = (int) (newRes * coo);
            }
            if (newC < 0) {
                newC = 1;
            }

        }

        return newC;
    }

    public void buttonGenerator() {

        int y = 0;
        panelNav.add(navScroll = new JScrollPane(buttonScroll = new JPanel(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
        navScroll.setBorder(BorderFactory.createEmptyBorder());
        navScroll.setBounds(ajustarDimensiones(1), ajustarDimensiones(90), ajustarDimensiones(303), ajustarDimensiones(600));
//        navScroll.setBackground(Color.white);
        navScroll.setOpaque(false);

        navScroll.getVerticalScrollBar().setUnitIncrement(30);
        navScroll.setPreferredSize(new Dimension(ajustarDimensiones(305), ajustarDimensiones(601)));
//        buttonScroll.setBackground(Color.white);
        buttonScroll.setPreferredSize(new Dimension(ajustarDimensiones(305), ajustarDimensiones(601)));
        buttonScroll.setLayout(null);
        navScroll.setViewportView(buttonScroll);
        buttonScroll.setOpaque(false);
        navScroll.getViewport().setOpaque(false);

        buttonScroll.add(funConsultarPiezas = new JButton());
        funConsultarPiezas.setContentAreaFilled(false);
        //           funConsultarPiezas.setOpaque(true);
        funConsultarPiezas.setText("Consultar pieza");
        funConsultarPiezas.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(30)));
        funConsultarPiezas.setBounds(ajustarDimensiones(1), ajustarDimensiones(0), ajustarDimensiones(301), ajustarDimensiones(80));
        //        funConsultarPiezas.setBackground(java.awt.Color.white);
        funConsultarPiezas.setForeground(Color.white);
        funConsultarPiezas.addActionListener(this);
        funConsultarPiezas.setBorder(null);
        funConsultarPiezas.setBorderPainted(false);
        funConsultarPiezas.setFocusPainted(false);
        botones.add(funConsultarPiezas);

        y += 81;

        buttonScroll.add(btnCalidad = new JButton());
        btnCalidad.setContentAreaFilled(false);
        //     btnCalidad.setOpaque(true);
        btnCalidad.setText("Quality Check");
        btnCalidad.setBounds(ajustarDimensiones(1), ajustarDimensiones(y), ajustarDimensiones(301), ajustarDimensiones(80));
        btnCalidad.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(30)));
        //        btnCalidad.setBackground(Color.white);
        btnCalidad.setForeground(Color.white);
        btnCalidad.addActionListener(this);
        btnCalidad.setBorder(null);
        btnCalidad.setBorderPainted(false);
        btnCalidad.setFocusPainted(false);
        botones.add(btnCalidad);

        y += 81;
        buttonScroll.add(planDis = new JButton());
        planDis.setContentAreaFilled(false);
        //       planDis.setOpaque(true);
        planDis.setText("Diseño y planear");
        planDis.setBounds(ajustarDimensiones(1), ajustarDimensiones(y), ajustarDimensiones(301), ajustarDimensiones(80));
        planDis.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(30)));
        //         planDis.setBackground(Color.white);
        planDis.setForeground(Color.white);
        planDis.addActionListener(this);
        planDis.setBorder(null);
        planDis.setBorderPainted(false);
        planDis.setFocusPainted(false);
        botones.add(planDis);

        y += 81;

        buttonScroll.add(compraMat = new JButton());
        compraMat.setContentAreaFilled(false);
//            compraMat.setOpaque(true);
        compraMat.setText("Compra Material");
        compraMat.setBounds(ajustarDimensiones(1), ajustarDimensiones(y), ajustarDimensiones(301), ajustarDimensiones(80));
        compraMat.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(30)));
        //compraMat.setBackground(Color.white);
        compraMat.setForeground(Color.white);
        compraMat.addActionListener(this);
        compraMat.setBorder(null);
        compraMat.setBorderPainted(false);
        compraMat.setFocusPainted(false);
        botones.add(compraMat);

        y += 81;

        buttonScroll.add(soySuper = new JButton());
        soySuper.setContentAreaFilled(false);
//            soySuper.setOpaque(true);
        soySuper.setText("Liberar piezas");
        soySuper.setBounds(ajustarDimensiones(1), ajustarDimensiones(y), ajustarDimensiones(301), ajustarDimensiones(80));
        soySuper.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(30)));
        //soySuper.setBackground(Color.white);
        soySuper.setForeground(Color.white);
        soySuper.addActionListener(this);
        soySuper.setBorder(null);
        soySuper.setBorderPainted(false);
        soySuper.setFocusPainted(false);
        botones.add(soySuper);

        y += 81;

        buttonScroll.add(crearProyecto = new JButton());
        crearProyecto.setContentAreaFilled(false);
//            crearProyecto.setOpaque(true);
        crearProyecto.setText("Crear proyecto");
        crearProyecto.setBounds(ajustarDimensiones(1), ajustarDimensiones(y), ajustarDimensiones(301), ajustarDimensiones(80));
        crearProyecto.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(30)));
        //crearProyecto.setBackground(Color.white);
        crearProyecto.setForeground(Color.white);
        crearProyecto.addActionListener(this);
        crearProyecto.setBorder(null);
        crearProyecto.setBorderPainted(false);
        crearProyecto.setFocusPainted(false);
        botones.add(crearProyecto);

        y += 81;

        buttonScroll.add(clientes = new JButton());
        clientes.setContentAreaFilled(false);
//            clientes.setOpaque(true);
        clientes.setText("Clientes");
        clientes.setBounds(ajustarDimensiones(1), ajustarDimensiones(y), ajustarDimensiones(301), ajustarDimensiones(80));
        clientes.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(30)));
        //clientes.setBackground(Color.white);
        clientes.setForeground(Color.white);
        clientes.addActionListener(this);
        clientes.setBorder(null);
        clientes.setBorderPainted(false);
        clientes.setFocusPainted(false);
        botones.add(clientes);

        y += 81;

        buttonScroll.add(adminConsProye = new JButton());
        adminConsProye.setContentAreaFilled(false);
//            adminConsProye.setOpaque(true);
        adminConsProye.setText("Consultar proyectos");
        adminConsProye.setBounds(ajustarDimensiones(1), ajustarDimensiones(y), ajustarDimensiones(301), ajustarDimensiones(80));
        adminConsProye.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(26)));
        //adminConsProye.setBackground(Color.white);
        adminConsProye.setForeground(Color.white);
        adminConsProye.addActionListener(this);
        adminConsProye.setBorder(null);
        adminConsProye.setBorderPainted(false);
        adminConsProye.setFocusPainted(false);
        botones.add(adminConsProye);

        y += 81;

        buttonScroll.add(histProy = new JButton());
        histProy.setText("Historial");
        histProy.setContentAreaFilled(false);
//            histProy.setOpaque(true);
        histProy.setBounds(ajustarDimensiones(1), ajustarDimensiones(y), ajustarDimensiones(301), ajustarDimensiones(80));
        histProy.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(30)));
        //histProy.setBackground(Color.white);
        histProy.setForeground(Color.white);
        histProy.addActionListener(this);
        histProy.setBorder(null);
        histProy.setBorderPainted(false);
        histProy.setFocusPainted(false);
        botones.add(histProy);

        y += 81;

        buttonScroll.add(consuEmpleados = new JButton());
        consuEmpleados.setText("Trabajadores");
        consuEmpleados.setContentAreaFilled(false);
//            consuEmpleados.setOpaque(true);
        consuEmpleados.setBounds(ajustarDimensiones(1), ajustarDimensiones(y), ajustarDimensiones(301), ajustarDimensiones(80));
        consuEmpleados.setFont(new java.awt.Font("Arial", 1, ajustarDimensiones(30)));
        //consuEmpleados.setBackground(Color.white);
        consuEmpleados.setForeground(Color.white);
        consuEmpleados.addActionListener(this);
        consuEmpleados.setBorder(null);
        consuEmpleados.setBorderPainted(false);
        consuEmpleados.setFocusPainted(false);
        botones.add(consuEmpleados);

        y += 81;

        buttonScroll.setPreferredSize(new Dimension(ajustarDimensiones(305), ajustarDimensiones(y)));
    }

    public void botonSeleccionado(JButton but) {
        for (JButton b : botones) {
            if (b.getText().equalsIgnoreCase(but.getText())) {
                b.setOpaque(true);
                b.setBackground(new Color(255, 102, 102, 200));
                b.setForeground(Color.white);
            } else {
                b.setOpaque(false);
                //b.setBackground(Color.white);
                b.setForeground(Color.white);
            }
            b.revalidate();
            b.repaint();
        }
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        JButton obj = (JButton) ae.getSource();
        if (obj != logout) {
            botonSeleccionado(obj);
        }
    }

}

If someone knows how to make a clean transparent button, I would really appreciate the help.
I leave here the source code with the test images that I'm using.
https://drive.google.com/file/d/1l8R52WTDyP93L0UhTNd3oorD7Qhv-TcP/view?usp=sharing
In this image, you can see the 3 kind of bugs that I have, in the first one you can see how there's another button in the background and the scroll bar is shown in the left of the button. In the second one, it's the header of the navigation panel. In the third one, I passed the mouse multiple times over the selected button and it turned into a solid color instead of a transparent one.
EDIT:
I decided to check if the bug persisted if I applied it to the navigation panel, because it will have to be transparent as well when the application is finished. So I added the following lines of code in the lines 82 and 83 of the code above:
        panelNav.setBackground(new Color(0, 0, 0, 200));
        panelNav.setOpaque(true);

In this other image I applied the transparency to the whole navigation panel, which is a JLabel. In the first image is shown what appears when the frame is displayed, there's even parts of the frame that are displayed beneath the navigation panel. In the second one is shown what happens when I use the scroll bar once.
EDIT 2:
I replaced all the JLabel that were used as JPanel for actual JPanel. Sadly, the bug persisted. I add an extra button in the main JPanel, I did this because I thought the bug origin from adding buttons to a JScrollPane. But it seems that the problem is directly in how I implement the method buttonName.setBackground().
Here's the new version of the code:
https://drive.google.com/file/d/1PuHMkEYNbBoafqs5XiyUaeCkIyXfnHFJ/view?usp=sharing

A: Any issues like the one you are seeing in the example app you have posted in 99% of cases happen due to incorrect mixing of opaque and/or non-opaque components.
As I can see from the code - you are using setOpaque(...) to change opacity of various components, but it's quite chaotic. Shortly what opaque property does - it affects the way Swing repaints the specific UI element (panel/label/button/etc) whenever a visual update for that element is required.
For example when you hover a button with the mouse - it might need to repaint if it has a different hover state, whether it's just an icon or a slightly/completely different style. This is where opacity comes into play - opaque=true components will never pass repaint calls "under" themselves (in other/proper terms - to their parent components). That means that if you have an opaque button on a panel and it have to be repainted when it changes to "hover" state - that button will be the only component to get repainted as there is no reason to repaint anything below it because it is opaque, you literally should not be able to see through it, so the graphics are expected to fill all pixels within bounds of that button with opaque colors.
Theoretically. On practice if you set a button to an opaque state, but keep it's graphics content transparent or semi-transparent (which is obviously a mistake, but Swing will never tell you about it) - you will end up seeing various visual artifacts like the ones you see in your application. That happens due to Graphics2D implementation often performing different paint operations at (0,0) coordinate to optimize their speed - this is not really important to know, but that is partially why you might see other component "parts" mixed in your component bounds when it is transparent. It's a bit more complicated than that, but it shouldn't ever really matter as it is simply an internal Swing optimization.
Similar visual problems might also be caused by mixing opaque=true and opaque=false components on the same layout. Most probably that is the case for your issue as well. I did quickly try to set everything in your demo to opaque=false and it did fix the issue, but it's not really the correct way to fix it, especially if you want to keep some components opaque. That just means the problem lies somewhere in the way of mixing components with different opacity types on top of each other within a single container.
My personal recommendation - never mix opaque and non-opaque components in one layout if there is even a slight chance they will overlap (meaning their bounds will intersect within the layout). Or even better - never overlap components on top of each other within a single container. Use multiple nested containers with appropriate non-null layouts, this will also help you a lot in the future to easily modify your UI.
I can give you a simple example that can demonstrate why it is bad:
/**
 * @author Mikle Garin
 */
public class OpacityGlitch
{
    public static void main ( String[] args )
    {
        SwingUtilities.invokeLater ( () -> {
            final JFrame frame = new JFrame ( "Opacity glitch sample" );

            // Opaque by default
            final JPanel panel = new JPanel ( null );

            // Opaque by default, but might vary with L&F
            final JButton button1 = new JButton ( "1111111" );
            panel.add ( button1 );

            // Non-opaque to demonstrate the problem
            final JButton button2 = new JButton ( "2222222" );
            panel.add ( button2 );

            // Intersecting buttons
            button1.setBounds ( 100, 100, 150, 30 );
            button2.setBounds ( 130, 115, 150, 30 );

            frame.getContentPane ().add ( panel );

            frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
            frame.setSize ( 500, 500 );
            frame.setLocationRelativeTo ( null );
            frame.setVisible ( true );
        } );
    }
}

Theoretically what you should get is button1 always being on top (due to it being added earlier and being painted last on the container), but on practice - which button is fully visible and on top of the other one will change if you try hovering either of the buttons. This happens due to both buttons being opaque and repaint calls not going past the button components to their container and whatever intersects with them further on. To fix this particular case it is enough to make button2 non-opaque because it should always stay below the button1 and if it is non-opaque it will safely pass the repaint calls at least to it's container:
button2.setOpaque ( false );

Although I personally would recommend making all involved components opaque in such cases to avoid other possible issues if component order may be changed in the future or due to any user interactions - for instance the scroll bar in your application is the prime example. Container does not have to be non-opaque though as it will correctly pass repaint calls between components placed in it and will correctly repaint itself as well.
Once you change buttons from my example above to non-opaque the issue will disappear due to repaint being correctly handled for them.
This might be a complicated topic for a beginner in Swing, but I highly recommend to fully understand why and how things like that happen, otherwise it will become a huge problem for you in the future, once your application grows bigger.


text:
Q: Remove NaN values from dataframe without fillna or Interpolate I have a dataset:
           367235   419895  992194
1999-01-11  8   5   1
1999-03-23  NaN 4   NaN
1999-04-30  NaN NaN 1
1999-06-02  NaN 9   NaN
1999-08-08  2   NaN NaN
1999-08-12  NaN 3   NaN
1999-08-17  NaN NaN 10
1999-10-22  NaN 3   NaN
1999-12-04  NaN NaN 4
2000-03-04  2   NaN NaN
2000-09-29  9   NaN NaN
2000-09-30  9   NaN NaN

When I plot it, using plt.plot(df, '-o') I get this:

But what I would like is for the datapoints from each column to be connected in a line, like so:

I understand that matplotlib does not connect datapoints that are separate by NaN values. I looked at all the options here for dealing with missing data, but all of them would essentially misrepresent the data in the dataframe.  This is because each value within the dataframe represents an incident; if I try to replace the NaNs with scalar values or use the interpolate option, I get a bunch of points that are not actually in my dataset. Here's what interpolate looks like:
df_wanted2 = df.apply(pd.Series.interpolate)

If I try to use dropna I'll lose entire rows\columns from the dataframe, and these rows hold valuable data.
Does anyone know a way to connect up my dots?  I suspect I need to extract individual arrays from the datasframe and plot them, as is the advice given here, but this seems like a lot of work (and my actual dataframe is much bigger.)  Does anyone have a solution?

A: Try iterating through with apply and then inside the apply function drop the missing values
def make_plot(s):
    s.dropna().plot()

df.apply(make_plot)

A: An alternative would be to outsource the NaN handling to the graph libary Plotly using its connectgaps function.
import plotly
import pandas as pd

txt = """367235 419895 992194
1999-01-11 8 5 1
1999-03-23 NaN 4 NaN
1999-04-30 NaN NaN 1
1999-06-02 NaN 9 NaN
1999-08-08 2 NaN NaN
1999-08-12 NaN 3 NaN
1999-08-17 NaN NaN 10
1999-10-22 NaN 3 NaN
1999-12-04 NaN NaN 4
2000-03-04 2 NaN NaN
2000-09-29 9 NaN NaN
2000-09-30 9 NaN NaN"""

data_points = [line.split(' ') for line in txt.splitlines()[1:]]
df = pd.DataFrame(data_points)

data = list()
for i in range(1, len(df.columns)):
    data.append(plotly.graph_objs.Scatter(
        x = df.iloc[:,0].tolist(),
        y = df.iloc[:,i].tolist(),
        mode = 'line',
        connectgaps = True
    ))

fig = dict(data=data)
plotly.plotly.sign_in('user', 'token')
plot_url = plotly.plotly.plot(fig)

A: use interpolate method with parameter 'index'
df.interpolate('index').plot(marker='o')

alternative answer
plot after iteritems
for _, c in df.iteritems():
    c.dropna().plot(marker='o')

extra credit
only interpolate from first valid index to last valid index for each column
for _, c in df.iteritems():
    fi, li = c.first_valid_index(), c.last_valid_index()
    c.loc[fi:li].interpolate('index').plot(marker='o')


text:
Q: Proof that Muckenhoupt's $A_q$ Condition Implies $A_p$ for $pIt is said $f\in A_p$ if it satisfies the following (Muckenhoupt's $A_p$) condition:
$$\underset{I\subset\mathbb{R}}\sup\left(\dfrac{1}{|I|}\int_If(t)dt\right)\left(\dfrac{1}{|I|}\int_If(t)^{-\frac{p'}{p}}\right)^\frac{p}{p'}<\infty$$
where the $\sup$ is taken over bounded intervals $I$ in $\mathbb{R}$, and $p'$ is the Holder conjugate of $p$.
I find the following fact that $A_1\subset A_p\subset A_\infty$ for $1\leq p\leq\infty$ on Wikipedia's page, but have not found this proven in any papers so far (nor have found a proof myself).
Any reference to this would be appreciated.

A: For any nonnegative measurable function $h$ on a probability space $\Omega$ the quasi-norm $\|h\|_q=\left(\int_{\Omega} h^q\right)^{1/q}$ is increasing with $q$, $0<q<\infty$. Indeed, Jensen's inequality gives
$$ \left(\int_{\Omega} h\right)^q \le \int_{\Omega} h^q \tag1 $$
which says $\|h\|_1\le \|h\|_q$ for $q\ge 1$. Given $0< q_1<q_2<\infty$, apply (1) to $h^{q_1}$ with $q=q_2/q_1$.
Specialize the above to $\Omega$ being an interval $I$ with normalized Lebesgue measure, and $h=1/f$. Then
$$ \left(\dfrac{1}{|I|}\int_If(t)^{-\frac{p'}{p}}\right)^\frac{p}{p'} = \|h\|_q \tag2$$
where $q=p'/p$ is a decreasing function of $p$. Therefore, (2) is a decreasing  function of $p$, which implies that the inequality
$$\underset{I\subset\mathbb{R}}\sup\left(\dfrac{1}{|I|}\int_If(t)dt\right)\left(\dfrac{1}{|I|}\int_If(t)^{-\frac{p'}{p}}\right)^\frac{p}{p'}<\infty$$
becomes weaker (more permissive) as $p$ increases.
To handle $A_\infty$, one can introduce $\|h\|_0=\exp\int_\Omega \log h$ and argue that $\|h\|_0\le \|h\|_q$ for all $q>0$; the rest goes as above.
A reference is Harmonic Analysis by Stein, section V.1.3, page 195:


text:
Q: Ionic Capacitor Admob simple example fails with type? I am trying to integrate the Capacitor Admob by the example
https://ionicframework.com/docs/native/admob

but
import { Admob } from '@ionic-native/admob';

...

constructor(private admob: Admob)

fails with
[ng]     ERROR in src/app/map/map.page.ts:81:30 - error TS2749: 'Admob' refers to a value, but is being used as a type here.
[ng]
[ng]     81               private admob: Admob,

?
Why should the example break?

A: I have run into this "gotcha" as well. You need to import import { Admob } from '@ionic-native/admob/ngx'; as this is the portion that indicates to import the angular specific version.

A: According to the docs, "Capacitor Not compatible."
This may be of use?
Capacitor AdMob


text:
Q: Spamhaus is blocking several customers since a couple of days? I received a couple of complaints from customers that got their emails rejected.
I haven't changed my config, so this must be an issue with spamhaus.
I'm running Postfix with these settings for spamhaus:
   smtpd_sender_restrictions = [...]
   reject_rhsbl_helo dbl.spamhaus.org,
   reject_rhsbl_reverse_client dbl.spamhaus.org,
   reject_rhsbl_sender dbl.spamhaus.org,

Here are a couple of my logs where customers get blocked:
NOQUEUE: reject: RCPT from mx08-0020e701.pphosted.com[91.207.212.174]: 554 5.7.1 Service unavailable; Unverified Client host [mx08-0020e701.pphosted.com] blocked using dbl.spamhaus.org; from=<prvs=122944b5d5=XXX.XXX@XXX.com> to=<XXX@XXX.de> proto=ESMTP helo=<mx07-0020e701.pphosted.com>
NOQUEUE: reject: RCPT from mailout09.t-online.de[194.25.134.84]: 554 5.7.1 Service unavailable; Sender address [XXX@t-online.de] blocked using dbl.spamhaus.org; from=<XXX@t-online.de> to=<info@XXX.de> proto=ESMTP helo=<mailout09.t-online.de>
NOQUEUE: reject: RCPT from mail-fr2deu01on2094.outbound.protection.outlook.com[40.107.135.94]: 554 5.7.1 Service unavailable; Helo command [DEU01-FR2-obe.outbound.protection.outlook.com] blocked using dbl.spamhaus.org; from=<#XXX@XXX.com> to=<XXX@XXX.de> proto=ESMTP helo=<DEU01-FR2-obe.outbound.protection.outlook.com>

Anybody knows how I can fix this (without exposing my mailserver)?

A: Your configuration is dangerously wrong. You must filter the DNS return codes, as instructed.
Not every response from spamhaus indicates a listing, some indicate lookup errors (usually: querying via a shared open DNS server, thus exceeding lookup rates). Your configuration blocks clients on all results, including 127.255.255.0/24 responses.
This configuration fixes the immediate problem by only rejecting on actual results. Depending on the nature of the error, this may mean you are then not blocking anyone:
smtpd_sender_restrictions = [...]
 reject_rhsbl_sender dbl.spamhaus.org=127.0.1.[2..99],
 reject_rhsbl_helo dbl.spamhaus.org=127.0.1.[2..99],
 reject_rhsbl_reverse_client dbl.spamhaus.org=127.0.1.[2..99],

This suggested fix only makes you not mistreat the error responses. You additionally have to configure your DNS lookups according to the usage guidelines - to yet again retrieve the intended responses.
To begin with this, on the machine in question, call this command:
dig +short 2.0.0.127.zen.spamhaus.org

And then see what the returned code corresponds to in their public list explaining the codes.


text:
Q: How to prevent auto parsing of an URL tag and render it as the full tag instead? Does anyone know if KnockoutJS parses < and > in its observables? I am returning a string such as...

google.com

...but it renders as...

<a href="www.google.com" target="_blank" style="color: #0065CB">www.google.com</a>

...and so the url is not rendered properly. Here is the template, the tag with the problem is ${ text }:

A: You will want to use {{html text}} instead of ${ text } to make sure that your value is not escaped.  If you are using data-bind attributes in KO, then there is a "html" binding that can be used as an alternative to the "text" binding.


text:
Q: Updating Controller for New Custom Object Field--Testing Problem I updated a custom object that existed in production with a new field (Approval_Status__c, picklist). That object was queried by a controller (apex class) in production, as well. All I want to do is update the controller so that it queries the new field. I was able to edit the apex class in sandbox with the additional new field and went through the steps to deploy the edited controller as outlined here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_deploy.htm
Unfortunately, I cannot seem to get the deploy to succeed past the testing stage. I'm not sure why this is because I don't think that the addition of the field would be enough to break the code. (For reference, the only line that has changed is from
return [SELECT Category__c, Credits_Earned__c, Date_Approved__c, Date_Earned__c, Title__c FROM Recertification_Activities__c WHERE Program_ID__c =: rid];

to
return [SELECT Approval_Status__c, Category__c, Credits_Earned__c, Date_Approved__c, Date_Earned__c, Title__c FROM Recertification_Activities__c WHERE Program_ID__c =: rid];

Any suggestions on how to get through the testing would be greatly appreciated.

A: I am going to say with 99% certainty that the issue is not related in any way to your current deployment attempt.
I believe your tests are currently in a state where they will not pass in production without any deployment being attempted. This can happen over time if tests are not properly written.
To verify follow this path:
Login to production
Setup -> Develop -> Apex Test Execution -> Select Tests -> Check box for all -> Click run
if any of the tests fail then any deployment you make will fail and you should review the reasons why the tests fail and determine if it is an improper test or if it is actually pointing you to a potential problem.
Some ways to get your deployment completed:

*

*Fix the test methods or the process that is broken

*When deploying select "Specified tests" and enter the name of the test class that tests the controller you are deploying.


text:
Q: Worklow 2013 does not stop I'm working on SharePoint Server 2016. Some monts ago I developed a 2013 Workflow using SharePoint Designer 2013. Today I noticed many Workflow instances are on status Started even they completed their job, so I decided to stop them manually from the UI (http://mySharePoint/_layouts/15/wrkstat.aspx?List={ListGuid}&WorkflowInstanceName=WFGuid). They don't stop.
Maybe buggy UI? ...I decided to wrote a powershell script:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$sourceWebURL = "http://mySharePoint"
$sourceListName = [Guid]"ListGuid"
$web = get-spweb $sourceWebURL
$list = $web.Lists[$sourceListName]

$wfm = New-object Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager($web)
$sub = $wfm.GetWorkflowSubscriptionService()
$wfs = $sub.EnumerateSubscriptionsByList($list.ID)
$wfis = $wfm.GetWorkflowInstanceService()

$item = $list.GetItemById($itemId)

$workflowInstances=$wfis.EnumerateInstancesForListItem($list.ID,$item.ID)

foreach($wf in $workflowInstances)
{
    $wfis.CancelWorkflow($wf)
}

They don't stop either...
This is the scenario:

Each running WF is on Started, has done what it had to, but is not stoppable.
Somebody has an idea what's going on?

A: You can use the following PowerShell commands to cancel all workflow instances on the list.
$sourceWebURL = 'your site'
$sourceListName = 'your list'
$spSourceWeb = Get-SPWeb $sourceWebURL
$spSourceList = $spSourceWeb.Lists[$sourceListName]
$items = $spSourceList.getItems()

#-- Getting a Workflow manager object to work with.
$wfm = New-object Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager($spSourceweb)

$wfis=$wfm.GetWorkflowInstanceService()

Foreach($item in $items){
    $wfinstances =  $wfis.EnumerateInstancesForListItem($spSourcelist.ID, $item.ID);
    foreach($instance in $wfInstances)
    {
             $wfis.CancelWorkflow($instance);

    }
}


text:
Q: Creation of a test image with 2d circular shaped objects having Gaussian brightness distribution profile I want to create a test image which consists of 2d circular shaped objects each having a Gaussian brightness distribution profile.
To make it simple objects should be the same.
I then put the objects at random positions.
In the resulting composed image I would like to prevent overlapping objects.
An alternative would also be that the brighter pixels dominate.
How could that be done?
Result:

The single object:

My code:
(*a single object*)
objectData = GaussianMatrix[20, 0];
object = Image[objectData/Max[objectData]];

(*the test image,here 400 pixels square*)
imageData = Array[0 &, {400, 400}];
image = Image[imageData];

(*some random mean positions*)
randomCoords = Array[{RandomReal[], RandomReal[]} &, 20];

(*image composition*)
ImageCompose[image, object, randomCoords*400]

A: Update:
Belisarius suggested in comments a method using image processing (i.e. GaussianFilter) to generate the image. I'd modify his approach to use RandomChoice to generate the initial spots, which seems more direct to me:
img = Image@RandomChoice[{10000, 1} -> {0, 1}, {400, 400}];
ImageAdjust@GaussianFilter[img, 15]

I am going to create your object as the PDF of a binormal distribution with means equal to the $(x,y)$ position of the object, and equal standard deviations (to give a circular particle image) whose values (8) have been chosen to be pleasing with an image size of 400 units (of course, adjust to taste).
Clear[object, positions, imagefunction]
SeedRandom[7]

object[px_, py_] = PDF[BinormalDistribution[{px, py}, {8, 8}, 0], {x, y}];

Now generate some random positions, apply the object function to generate those objects, then sum all those distribution PDF to obtain a parametric description of a 3D surface:
positions = RandomInteger[{1, 400}, {20, 2}];
imagefunction = Plus @@ object @@@ positions;

Finally use DensityPlot to slice that surface and obtain your image:
DensityPlot[imagefunction, {x, 1, 400}, {y, 1, 400},
  PlotPoints -> 150, ColorFunction -> GrayLevel,
  Frame -> None, PlotRange -> All
]

To get an actual image, rather than a Graphics object, use e.g. Rasterize, Export ...:
Rasterize[%]

A: ImageAdjustwon't work well when there are superpositions,
SeedRandom[42];
n = 400;
gf[i_Image] := GaussianFilter[i, {n/20, n/80}]
ImageAdjust [ ri= gf@RandomImage[BernoulliDistribution[50/n^2], {n, n}]]

Use Clip/Rescale instead:
resc = Max@ImageData@gf@Image@SparseArray[{n/2, n/2} -> 1, {n, n}];

Image@Clip@Rescale[ImageData@ri, {0, resc}]
(* or, mostly the same but slower*)
ImageApply[Clip@Rescale[#, {0, resc}] &, ri]

A: One way to proceed is to make an image that contains a single white pixel at each desired center point and then to convolve the small particle with the image:
particle = Import["http://i.stack.imgur.com/gi6U1.png"];
randomCoords = Array[{RandomReal[], RandomReal[]} &, 20];
img = Image[Array[0 &, {400, 400}]];
points = ReplacePixelValue[img, randomCoords*400 -> 1];
ImageConvolve[points, particle]

A: Here is a pedestrian way to avoid overlaps. I'll show it "by hand" although it could be automated. I believe this or something similar came up once before on this forum but I cannot seem to locate it.
The original setup is as follows.
rad = 20;
scale = 400;
objectData = GaussianMatrix[rad, 0];
object = Image[objectData/Max[objectData]];
imageData = Array[0 &, {scale, scale}];
image = Image[imageData];
SeedRandom[1111];
randomCoords = RandomReal[1, {20, 2}];
image1 = ImageCompose[image, object, randomCoords*scale]

To get something similar but without overlaps we can iteratively use Nearest. I'll show one approach although there are others. The idea is to select only points that have no neighbor too close. This is inefficient insofar as we could take one from any pair that overlap, but implementing that means in effect changing the NearestFunction in a loop.
SeedRandom[1111];
randomCoords = Array[{RandomReal[], RandomReal[]} &, 40];
nf = Nearest[randomCoords];
randomCoords2 =
  Select[randomCoords,
   With[{nbr = nf[#, {2, 2/Sqrt[scale]}]}, Length[nbr] == 1] &];
Length[randomCoords2]
randomCoords3 = Array[{RandomReal[], RandomReal[]} &, 30];
nf2 = Nearest[Join[randomCoords2, randomCoords3]];
randomCoords4 =
  Select[randomCoords3,
   With[{nbr = nf2[#, {2, 2/Sqrt[scale]}]}, Length[nbr] == 1] &];
Length[randomCoords4]

(* Out[246]= 11

Out[250]= 9 *)

We again have 20 points as luck would have it. So let's look at the placement this time.
image2 = ImageCompose[image, object,
  Join[randomCoords2, randomCoords4]*400]


text:
Q: Javascript/html align text in middle and add sub-heading I have this HTML/javascript code where I have a heading on the page. What I am trying to do is align this heading in the middle(left and right alignment) and then add a sub-heading below it which is also aligned in middle:
#BotChatGoesHere {
        text-align: center;
        border: 1px solid #333;
        height: 600px;
        position: relative;
        width: 460px;
      }
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>Title1</title>

    <link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />

            Welcome!

        How Can I help you

In the above what I am trying to do is have Welcome! be aligned in the middle(left and right alignment) and then just below it has How Can I help you? also show up in another band as a sub-heading and aligned in middle. Bot the heading and sub-heading are in separate colored bands.
How can I do this as I don't know HTML or Javascript and looks my try above is not working?
UPDATE:
Below is how it looks like currently.As you can see from the pic neither does it aligns to middle(left and right equal) but How can I help you gets superimposed. What I want is Welcome! to be in one blue band but aligned to middle and then another similar band for how can I help you?

A: I don't know what you were exaclty trying to achieve. I added class ".help-container" to position "How can I help you". You can add different styling- colors, font sizes etc. there, if you want.

#BotChatGoesHere {
        text-align: center;
        border: 1px solid #333;
        position: relative;
}

.help-container{
        position: absolute;
        left: 0;
        right: 0;
        top: 39px;
        margin: 0 !important;
        background-color: #9dfb9d;
}
   <!DOCTYPE html>

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Title1</title>

<link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />

        Welcome!

        How Can I help you


text:
Q: How to handle rest exceptions in CQRS? In my aspnet core 3.1 project I am using CQRS approach, I have issue with getting correct Rest exception. Instead of actual error I am getting back server error.
My RestException class looks like:
    public class RestException : Exception
    {
        public HttpStatusCode Code { get; }
        public object Errors { get; }

        public RestException(HttpStatusCode code, object errors = null)
        {
            Code = code;
            Errors = errors;
        }
    }

My middleware for rest exception:
    public class ErrorHandlingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ErrorHandlingMiddleware> _logger;

        public ErrorHandlingMiddleware(RequestDelegate next,
         ILogger<ErrorHandlingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex, _logger);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception exception,
        ILogger<ErrorHandlingMiddleware> logger)
        {
            object errors = null;
            switch (exception)
            {
                case RestException re:
                    logger.LogError(exception, "REST ERROR");
                    errors = re.Errors;
                    context.Response.StatusCode = (int) re.Code;
                    break;
                case { } e:
                    logger.LogError(exception, "SERVER ERROR");
                    errors = string.IsNullOrWhiteSpace(e.Message) ? "Error" : e.Message;
                    context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
                    break;
            }

            context.Response.ContentType = "application/json";
            if (errors != null)
            {
                var result = JsonConvert.SerializeObject(new
                {
                    errors
                });
                await context.Response.WriteAsync(result);
            }
        }
    }

Startup class:
 app.UseMiddleware<ErrorHandlingMiddleware>();

Create handler which I am using rest exception:
             public async Task<Project> Handle(Command request, CancellationToken
             cancellationToken)
            {
                var project = new Project
                {
                    Name = request.Name,
                    KubesprayCurrentVersion = request.KubesprayCurrentVersion,
                    KubesprayTargetVersion = request.KubesprayCurrentVersion,
                    OrganizationId = request.OrganizationId,
                    CloudCredentialId = request.CloudCredentialId,
                    CreatedAt = DateTime.Now
                };

                await _context.Projects.AddAsync(project, cancellationToken);

                if(await _context.Projects.Where(x => x.Name ==
                 request.Name).AnyAsync(cancellationToken: cancellationToken))
                    throw new RestException(HttpStatusCode.BadRequest, new {Name = "Project
                Name already exists"});

                var success = await _context.SaveChangesAsync(cancellationToken) > 0;
                if(success) return project;

                throw new Exception("Problem saving changes");
            }

My projects controller:
    [HttpPost]
    public async Task<ActionResult<Project>> Create(Create.Command command) => await
    Mediator.Send(command);

A: Your middleware looks ok, but at first glance I would say that probably you are throwing your RestException from a async code and it might get wrapped as a AggregateException.
Then in your HandleExceptionAsync it will not go to the RestException case, therefore you are getting the "SERVER ERROR" message.
Could you adding a case for AggregateException and see if your exception goes to that case?

A: Your custom middleware might conflict with the DeveloperExceptionPage middleware. Can you check that you don't call the app.UseDeveloperExceptionPage() method?


text:
Q: CSS height - 100% between 2 divs I am working on a CSS3/HTML5 Asp.NET 4.5 web application. I have the HTML and CSS the way I want it for my layout except for one issue.
The theory behind my css is the header and nav are obviously set at the top of the page, with a container with an aside and article, followed by an independent footer that I want always to be at the bottom of the page regardless of how little content there is. Everything works except that when I have the aside set to 100% height, it is 100% of the viewport height, meaning that on pages with little content, you have to scroll 260px (the combined height of the header, nav, and footer) to see it. So, to address that, I set the margins of the aside to 280px top, and 80px bottom thinking that would do the trick. It did not. So I started playing with position and clear as suggested by similar questions on SO and around the web without success.
HTML:

    <form id="form1" runat="server">

Nathan A. Chesebro

United States Merchant Marine

                Vessel data

                <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
                </asp:ContentPlaceHolder>

    </form>

CSS
*
{
    margin: 0;
}
body
{
    margin: 0px auto;
    height: 100%;
}

form, html
{
    height: 100%;
}

header
{
    margin: 0px auto;
    background-color: #1041a2;
    background-image: url(../Images/headerHCJ.png);
    background-repeat: no-repeat;
    background-position-x: right;
    height: 150px;
    position: relative;
}

nav
{
    background-image: url(../Images/nav.png);
    font-family: Arial;
    color: white;
    background-repeat: repeat-x;
    height: 30px;
    width: 100%;
    line-height: 30px;
    margin: 0px auto;

}

#content
{
    margin: 0px auto;
    height: 100%;
}

aside
{
    margin: 180px 0px 80px 0px auto;
    float: left;
    width: 250px;
    background-color: gray;
    height: 100%;
    overflow: hidden;
    position: relative;
    clear: both;
}

article
{
    margin: 0px auto;
    padding-left: 250px;
    min-height: 100%;
}

footer {
    height:80px;
    background: black;
    clear: both;
}

A: Is this what you're looking for? It's just a concept so I didn't copy your exact code.
Also, I am using a calc() method in the CSS (which is getting more and more browser support but may still be restrictive on some eg. opera-mini etc.).
Here's the fiddle: http://jsfiddle.net/thePav/A3NCW/1/
CSS
html,
body {height: 100%; margin: 0; padding: 0}

header {height: 150px; background-color: #800}
  header #logo {}
  header #title {}

nav {height: 30px; background-color: #080}

#content {overflow: hidden; height: calc(100% - 280px)}
  #content aside {background-color: #555; height: 100%; float: left; width: 25%}
  #content article {float: left; width: 75%}

#footer {width: 100%; height: 100px; position: absolute; bottom: 0; left: 0; background-color: #000}

HTML

Some content here

A: You can use display's 'table' and 'table-cell' values.
Check out this fiddle: http://jsfiddle.net/scottmey/j9jrz/
#content {
    display: table;
    width: 100%;
}
aside {
    display: table-cell;
}
article {
    display: table-cell;
}

A: CSS cannot be used to make two items the same height.
You either need to use javascript to set the height, or else use a table tag.


text:
Q: Is there a system call in linux to reserve virtual address space (not memory, just address space) I have a user space "platform" forking different processes. All these processes start executing a platform plat_init() function, and then run some other application code (which is not mine. i.e. I cannot change this code).
At some point in time some of these processes may do a plat_shared_mem_alloc() to allocate shared memory. This function returns a handle H (one handle per shared memory block allocated at each call). Another function, plat_get_shared_memory_address(H) can be called to retrieve the address (in the process virtual space) of H.
H can be sent to other linux processes (using usual IPC).
I would like any call to plat_get_shared_memory_address(H) made by any processes to return the same address (for the same handle H).
In other words, I want to map the shared physical memory to the same virtual address in all processes using it, regardless on when the mapping is done.
I thought the plat_shared_mem_alloc() could call shm_open() to create a "file" in the file system, and I am aware mmap() has the MAP_FIXED flag to force the virtual address of the mapping.
But nothing guarantee that if a process P1 maps a shared memory handle at address A, then the same address A is/will be available in another process P2 address space. Maybe P2's application's code has already mapped something at address A before calling plat_get_shared_memory_address(H), and mmap() will fail.
So I am thinking of blocking some address space in each process during plat_init() call (which I know comes first). and using some of that address space when needed for mmap().
In other words, is there a system call to block (reserve) some virtual address space of a process (without allocation any memory at this time), so I could, later on, if needed, map things at the same address in my different processes?


text:
Q: Cast datatype with variable Is it possible in T-SQL to cast a data type with a variable type?
I.e. Though this won't work since it expects a string literal but gets the gist across:
select @DataType = Data_Type
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'emp'
and COLUMN_NAME = 'emp_id'

SELECT
cast(emp_id as @DataType)
FROM emp

A: No, you will need to use dynamic SQL for this, e.g.
DECLARE @sql NVARCHAR(MAX);

SELECT @sql = N'SELECT CAST(emp_id AS ' + Data_Type
 + ') FROM dbo.emp;'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'emp'
AND TABLE_SCHEMA = 'dbo' -- this might be important!
AND COLUMN_NAME = 'emp_id';

PRINT @sql;
-- EXEC sp_executesql @sql;

However, this seems wrong to me. Why don't you know the data types of your columns?
And in addition, you will need a much more complex query as you will want to take precision / scale / max length into account. If emp_id is a varchar, for example, all of the results will be truncated to one character.
And finally, I strongly recommend sys.columns over INFORMATION_SCHEMA.

A: I needed to do something similar so I created a function so that I can return the literal data type as would be needed for my dynamic SQL. I was surprised that I could not find a function like this already created: (Or maybe I shouldn't be surprised as CASTING through Dynamic SQL wouldn't by my recommendation... but at this point I can not think of an alternative as the source table is variable)
Anyway here is the function should anyone ever need it. Please note that so far I have only included data types from the table that I am trying to CAST into... so I imagine anyone who uses this will need to follow suit and include the data types they need or possibly all the rest of them.
CREATE FUNCTION dbo.GetLiteralDataType( @TableName as VARCHAR(100), @ColumnName as VARCHAR(100) )
    RETURNS VARCHAR(100)
    AS
    BEGIN

        DECLARE @DataType as VARCHAR(100)
        DECLARE @FullDataType as VARCHAR(100)
        DECLARE @MaxLength AS INT
        DECLARE @Precision AS INT
        DECLARE @Scale AS INT

        SET @DataType =(SELECT TOP 1 y.name FROM SYS.TABLES t
        INNER JOIN SYS.COLUMNS c ON t.object_id = c.object_id
        INNER JOIN SYS.TYPES y ON y.system_type_id = c.system_type_id
        WHERE t.name = @TableName AND c.name = @ColumnName)

        SET @MaxLength =(SELECT TOP 1 c.max_length FROM SYS.TABLES t
        INNER JOIN SYS.COLUMNS c ON t.object_id = c.object_id
        INNER JOIN SYS.TYPES y ON y.system_type_id = c.system_type_id
        WHERE t.name = @TableName AND c.name = @ColumnName)

        SET @Precision =(SELECT TOP 1 c.precision FROM SYS.TABLES t
        INNER JOIN SYS.COLUMNS c ON t.object_id = c.object_id
        INNER JOIN SYS.TYPES y ON y.system_type_id = c.system_type_id
        WHERE t.name = @TableName AND c.name = @ColumnName)

        SET @Scale =(SELECT TOP 1 c.scale FROM SYS.TABLES t
        INNER JOIN SYS.COLUMNS c ON t.object_id = c.object_id
        INNER JOIN SYS.TYPES y ON y.system_type_id = c.system_type_id
        WHERE t.name = @TableName AND c.name = @ColumnName)

        IF @DataType ='decimal'
        BEGIN
            SET @FullDataType = 'DECIMAL('+ @Precision + ',' + @Scale + ')'
        END

        IF @DataType ='varchar'
        BEGIN
            SET @FullDataType = 'VARCHAR('+ @MaxLength + ')'
        END

        IF @DataType ='bit'
        BEGIN
            SET @FullDataType = 'BIT'
        END

        IF @DataType ='money'
        BEGIN
            SET @FullDataType = 'MONEY'
        END

        IF @DataType ='date'
        BEGIN
            SET @FullDataType = 'DATE'
        END

        RETURN @FullDataType
    END


text:
Q: c# prevent unnecessary api calls I have an api that fetches data in pages and send it back to the client. If a client iterates over the returned collection more than once i want to prevent additional calls to the api
var actualItems = _pagedApiCollection.GetItems<Foo>().ToArray();

Call to api
public IEnumerable<Foo> GetItems<Foo>() {
  Page currentPage;
  do
  {
    currentPage =  _pagedApi.GetNextPage(reqid);

    foreach (var item in currentPage)
        yield return (Foo)item;

  } while (currentpage.HasNextPage);
}

IE how can additional calls to
_pagedApiCollection.GetItems<Foo>().ToArray()

Be prevented from new page fetches? Is it possible to Cache results in a property until Dispose() or similar?


text:
Q: Kendo UI Hierarchical grid shows no header for child elements I have an ASP.NET MVC application.
Here is my view code.
The problem that I am facing is that the kendo UI hierarchical grid does no show headers for child elements. Can you provide me any hint?
Here is the grid in the index file:
@section Scripts {

}

        @(Html.Kendo().Grid<Portal.Web.Areas.Orders.Models.Registroheader>()
            .Name("grid")
            .Columns(columns =>
            {
                columns.Bound(r => r.CodiceMateriale).Title("Codice Materiale");
                columns.Bound(r => r.TestoBreve).Title("Testo Breve");
                columns.Bound(r => r.UM).Title("UM");
                columns.Bound(r => r.Quantità).Title("Quantità");

            })
            .Scrollable()
            .ClientDetailTemplateId("expandTemplate")
            .HtmlAttributes(new { style = "", id = "grid" })
            .DataSource(dataSource => dataSource
            .Ajax()
            .Read(read => read.Action("RegistroHeader_Read", "RegistroRicondizionamento", Model))
             )
            .Deferred()
        )


text:
Q: Shell Script - Maximized Desktop Application in Linux I am a beginner in Unix environment or with desktop application.
I have application running and I am able to get its pid using this pgrep <<pid name>>. Can we maximize this this application or makes its window active using shell script?
Thanks in advance!

A: wmctrl does just that:
#!/bin/bash

pid=1234

# Note that one PID may have several windows opened, possibly
# with the same title, so you may have to implement
# some additional logic in order to choose the correct one.

window_refs=$(wmctrl -p -l | grep " $pid " | egrep -o 0x[0-9a-z]+)
for ref in $window_refs; do
    wmctrl -i -r "$ref" -b "add,maximized_vert,maximized_horz"
done


text:
Q: how to get only date from the TableCalendar I want to get only selected date from tablecalender, but it gives me this output
2021-08-18 12:00:00.000Z

here is tablecalender code

  final dateFormat = DateFormat('yyyy-MMMM-dd');
  DateTime _chosenDate = DateTime.now();
child: TableCalendar(
              calendarController: _controller,
              initialSelectedDay: _chosenDate,
              initialCalendarFormat: CalendarFormat.month,
              calendarStyle: CalendarStyle(
              canEventMarkersOverflow: true,
              markersColor: Colors.white,
              weekdayStyle: TextStyle(color: Colors.blue[900]),

              todayColor: Colors.white54,
              todayStyle: TextStyle(color: Colors.blue[900], fontSize: 15, fontWeight: FontWeight.bold),
              selectedColor: Colors.blue[900],
              outsideWeekendStyle: TextStyle(color: Colors.blue[900]),
              outsideStyle: TextStyle(color: Colors.blue[900]),
              weekendStyle: TextStyle(color: Colors.blue[900]),
              renderDaysOfWeek: false,),
              onCalendarCreated: (date,event,_){
              },
              onDaySelected: (date, event,_) {
                setState(() {
                 _chosenDate = date;
                  print("_chosenDate");
                  print(_chosenDate);
                });
              },
            ));

  }

i tried to use split method, but it is not accessible
please help how to get only date (2021-08-18) using tablecalender

A: in print replace _chosenDate with "${_chosenDate.toString().split(" ").first}"