text:
Q: Best ASP.NET dynamic user control load approach I have a food menu ASP.NET Web app. I use a datagrid to display the menu items. When the user clicks an item in the grid, a user control opens up below the item to allow the user to enter item details and add the item to an order. The item detail user control in turn contains several user controls with RadioButtonLists, DataLists  and TextBoxes. The RadioButtonLists and DataLists are populated from a database. The user should be able to open and close several items at a time, like Windows Browser with sub-folders.
I've tried doing this with strait ASP.NET AJAX using ScriptManger, etc.. I set the item detail user control Visible property to True, and populate the list controls during the OnPreRender event. This is slow and sort of complicated because of the ASP.NET page/control life cycle.
I've been looking into using JQuery requests to ASHX files or Page Methods on the server to generate the item detail controls with maybe RenderControl and sending the generated HTML back to JQuery.
Questions:
Am I on the right track?
Would this sort of approach work for rendering and sending back HTML that may be complex and long?
Would JQuery requests be more efficient than my current approach?
Can anybody point me in the right direction for references and/or examples?
Thanks for the bandwidth.

A: I found a lot of help that led to my solution at:
http://weblogs.asp.net/sanjeevagarwal/archive/2008/07/22/Dynamically-create-ASP.NET-user-control-using-ASP.NET-Ajax-and-Web-Service.aspx


text:
Q: LWS - Apparent difference in behavior using data returned from Apex call Prior to enabling LWS in Spring '22 we were able to successfully 'modify' objects returned
from an Apex Call.
After enabling LWS we cannot modify the data.
Allow me to give an example.
Below is some 'pseudo code' which :

*

*Calls an Apex method

*The result of the call is a list of custom objects, each of which has two attributes : quantity and price

*After the result is returned, we loop through all the items and perform a simple calculation using the above mentioned attributes, and store the result on the item in an attribute called  TotalPriceAmount.

*The updated line items are stored in a variable that is bound to the UI, so we can see all three values :)
     return getLineItems({id : recordId})
     .then(result => {

         result.forEach(oneLineItemVm => {

             /* Embellish the line item with a TotalPriceAmount so we can show it on the UI :) */

             let quantity = oneLineItemVm.Quantity;
             let unitprice = oneLineItemVm.UnitPrice;

             oneLineItemVm.TotalPriceAmount = unitprice * quantity;

         });

 /* Store the embellished on a @tracked attribute somewhere
 lineItems = result;
 ....

That 'pattern' works fine before enabling LWS.
The line that sets the TotalPriceAmount has NO effect after enabling LWS.
It appears that data returned from Apex is now not able to be modified?
Can anyone confirm that they have seen similar behavior?
Of course, this has made me question the original pattern, and perhaps I agree that we should NOT be attempting to modify the data. It's not hard to imagine unintended side effects of this way of coding.
But the question remains still. Does anyone else see this changed behavior?
as an aside ....
If a clone (using whatever method you like (in our case _.deepClone) is made of the returned data, then behavior is as expected (we can see the TotalPriceAmount) on the item.
We'll most likely be adopting this (cloning any returned data if it needs to be embellished) as standard practice from now on.
Any thoughts would be appreciated. Just looking for some confirmation here on what I'm seeing.
Thanks
edit : in case it is not clear, the apex method (in my pseudo code example : getLineItems) is NOT a cacheable method. It would look like this in the real world
 @AuraEnabled
    public static List < LineItemVm > getLineItems(Id id) {

If this method was decorated with (cacheable=true) then I of course would not be even asking the question. Attempting to modify the result of such a method has NEVER worked, nor should it.
the api version of the Apex Class : 48
the api version of the LWC : 52
My question stands as is : Would someone be able to confirm for me (like a yes or no answer) whether the behavior I am describing can be reproduced.

A: Edit: This will be fixed in Spring 22, as confirmed by engineering. The original answer will remain below.

In Locker Service (LS), they use an ObservableMembrane with a readOnlyMembrane within it that protects cached values. This membrane immediately rejects any writes to the protected object. If you attempt to write to an existing property, you get an error that reads Cannot assign to read only property 'x' on object, while if you attempt to write a non-existent property, you get Cannot add property x, object is not extensible. However, if the object comes from a non-cacheable Apex method, it is not protected by this readOnlyMembrane, and you're freely allowed to set any value for any property.
In LWS, they use a WeakMap that pairs together "red values" and "blue values." I did a deep dive for this answer because of a bug in this mechanic once before. All you really need to know for this answer is that red values are "safe" and blue values are "unsafe." When you get a response from Apex, your copy of that data is a blue value, and the protected version stored in sanitized storage is a "red value."
The blue value is wrapped in a Proxy that protects the data in various ways. If the Apex method that returns the data is marked as cacheable, then any attempt to write an existing property gets the error set' on proxy: trap returned falsish for property 'x'. Attempting to write a non-existent property is allowed on the blue object. When the Apex method is not cacheable, this extra protection isn't applied, and you can write whatever you want to the blue value.
This part of the answer is mostly an educated guess from my previous experience, but I have not yet identified the exact mechanism that is causing this behavior as of yet. It appears that, for whatever reason, any writes to the response object, which is a blue value, do not end up getting copied to the red value. When this blue value is subsequently traded for a red value at some point in the future, you end up losing whatever modifications were made to the previous blue value Proxy.
You can see this appear in the code I wrote to try and diagnose this problem.
  getUncached() {
    return new Promise((resolve, reject) => {
      uncachedMethod()
        .then((result) => {
          this.uncached = result;
          result.checked = true;
          result.message = 'Other message'
          console.log("uncached result json", JSON.stringify(result));
          console.log("uncached result object", result);
          console.log("uncached property json", JSON.stringify(this.uncached));
          console.log("uncached property object", this.uncached);
          resolve();
        })
        .catch((err) => {
          this.uncachedError = err.message;
          reject(err);
        });
    });
  }

Output:
uncached result json {"message":"Other message","checked":true}
uncached result object {message: 'Hello, world'}
uncached property json {"message":"Other message","checked":true}
uncached property object {message: 'Hello, world'}

Here, JSON.stringify is easily able to read the blue value properties we set, but the variable itself triggers a red value response, and all we get back is the original response. I get similar outputs on an Apex method that is cached, assuming I do not try to modify message, which is what my methods are returning:
@AuraEnabled(cacheable=true)
public static Map<String, Object> cachedMethod() {
    return new Map<String, Object> {
        'message' => 'Hello, world'
    };
}
@AuraEnabled(cacheable=false)
public static Map<String, Object> uncachedMethod() {
    return new Map<String, Object> {
        'message' => 'Hello, world'
    };
}

I am going to try and diagnose the problem to try and understand the problem better, but I feel like this is almost certainly a bug. At the very least, when they start enabling this for all customers, it will cause problems for anyone that's taken advantage of modifying uncached Apex responses in Locker Service. I will be reporting this as a potential bug this weekend.
The workaround is to copy the values before attempting to modify them, as you've discovered. Hopefully we'll be able to get this resolved before this becomes a major issue. Uncached values should behave the same in both LS and LWS.

A: The team is actively investigating this suite of issues with Lightning Web Security and looking at possible ways to allow the data modification behavior as experienced Lightning Locker in the past in a secure manner.
Would you mind sharing the code to getLineItems, for us to see how the APEX requests are made and how you are interacting with the response once it is received? It would greatly help verify our potential solutions.
Please feel free to scrub any potential information you don't want to share or if you want to share privately please let me know.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check duplicate from Strings given by user I am writing a code for checking duplicate which is typed by user. When the user type the second duplicate, the program will stop and warn the user of the duplication. My logic is I will put given words to the ArrayList and then check the next given word in the current ArrayList if it is already there or not.
public class RecurringWord {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        ArrayList<String> words = new ArrayList<String>();
        while (true) {
            System.out.println("Type a word: ");
            String word = reader.nextLine();
            words.add(word);
            int i = 0;
            if (words.contains(words.get(i+1))) {
                System.out.println("You gave the word " + words.get(i+1) + " twice");
            }
            i++;
            break;
        }
    }
}

A: You need a little reorganizing and logic check. If you want to stop when user tries to add the same word twice, then stop and don't add it at all to the list, you then won't have to keep any index at all.
while (true) {
    System.out.println("Type a word: ");
    String word = reader.nextLine();
    if (words.contains(word)) {
       System.out.println("You gave the word " + word + " twice");
       break;
      }
    words.add(word);
 }

A: Try something as listed below
  ArrayList<String> words = new ArrayList<String>();
   while (true) {
    System.out.println("Type a word: ");
    String word = reader.nextLine();

    if (words.contains(word)) {
        System.out.println("You gave the word " + words.get(i+1) + " twice");
    }else{
       words.add(word);

    break;
}

A: First of all. For your requirement there is no need to use an iterator i.
Additional see the comments:
Scanner reader = new Scanner(System.in);

Set<String> words = new HashSet<>();
while (true) {
    System.out.println("Type a word: ");
    String word = reader.nextLine();
    if (words.contains(word)) {
        System.out.println("You gave the word " + words + " twice");
        break; // end the programm if the word exists twice
    }
    words.add(word); // add the new word after the check.
}

in your example the user can only type in one word, after that the programm ends.
words.get(i+1)

will result in an Exception because the element will never exists.
you start at element 0 not 1.
Furthermore I suggest you to use a Set if it is an invalid case to have the same word twice:
Set<String> words = new HashSet<>();

The Set will never contains two Strings that are equal.

A: while (true) {
        System.out.println("Type a word: ");
        String word = reader.nextLine();
        if (words.contains(word)) {
            System.out.println("You gave the word " + word + " twice");
            break;
        }
        //This is only reached when `word` is new.
        //Add it to the list to keep track of it for later possible duplicates
        words.add(word);
}

A: Try to use Set, its special for unique values. add() method return boolean: true if added, false if not.
example:
Set<String> example = new HashSet<String>();
String[] arr = {"a", "b", "c", "d", "a"};
for (int i = 0; i<5; i++)
{
    boolean res = example.add(arr[i]);
    System.out.println(res);
}

output will be:
true
true
true
true
false

UPD
Your example:
public class RecurringWord {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        Set<String> words = new HashSet<String>();
        while (true) {
            System.out.println("Type a word: ");
            String word = reader.nextLine();
            if(!words.add(word));{
                System.out.println("You gave the word " + word+" twice");
                break;
            }
        }
    }
}

A: You need something like this:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class RecurringWord {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        Map<String, Integer> countMap = new HashMap<String, Integer>();
        System.out.println("Type a word: ");
        String word = reader.nextLine();
        String[] words = word.split(" ");
        for (int i = 0; i < words.length; i++) {
            if (countMap.containsKey(words[i])) {
                countMap.put(words[i], countMap.get(words[i]) + 1);
            } else {
                countMap.put(words[i], 1);
            }
        }
        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println("You gave the word " + entry.getKey()
                        + " : " + entry.getValue() + " many times");
            }
        }
        reader.close();
    }
}

If you just want to have twice check then try with below snippet:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class RecurringWord {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.println("Type a word: ");
        String word = reader.nextLine();
        String[] words = word.split(" ");
        List<String> wordsList = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
            if (wordsList.contains(words[i])) {
                System.out
                        .println("You gave the word " + words[i] + " : twice");
            } else {
                wordsList.add(words[i]);
            }
        }
        reader.close();
    }
}


text:
Q: what's the differences between using <> and not using it in java? I have a piece of code like this:
@RequestMapping(value = "/find/{id}")
@GetMapping
public ResponseEntity<QuestionModel> find(@PathVariable("id") Long id) {
    Question question = questionService.find(id);
    QuestionModel questionModel = new QuestionModel(question);
    **return new ResponseEntity<>(questionModel, HttpStatus.OK);**
}

I wanna know that what's differences between that & this:
@RequestMapping(value = "/find/{id}")
@GetMapping
public ResponseEntity<QuestionModel> find(@PathVariable("id") Long id) {
    Question question = questionService.find(id);
    QuestionModel questionModel = new QuestionModel(question);
    **return new ResponseEntity(questionModel, HttpStatus.OK);**
}

A: If you don't use any <...> you will use raw-types. You should never use raw-types, generics are way safer to use and prevent way more bugs due to increased compiler knowledge. Java only still supports it for backwards compatibility reasons < Java 5. See What is a raw type and why shouldn't we use it?
Using <> (diamond operator) instead of <Foo> (writing it out) is just syntactic sugar for convenience. The compiler replaces the diamond operator with the fully-written out type (same for var in Java 10). See What is the point of the diamond operator in Java 7?
// Are the same
List<Integer> values = new ArrayList<Integer>();
List<Integer> values = new ArrayList<>();

// Raw types, don't use if > Java 5
List values = new ArrayList();
// Assigning a raw-type to a generic variable, mixing both, don't use
List<Integer> values = new ArrayList();


text:
Q: Why is Griffiths ignoring the bounded surface current caused by the magnetization of the cylinder? My problem arises in Griffiths's book chapter 6, when he discusses the auxiliary field $\mathbf{H}$.
At first he claims that Ampere's law inside a magnetized material is as follows:
$$\nabla \times \left( \dfrac{1}{\mu_0} \mathbf{B} - \mathbf{M} \right) = \mathbf{J}_f$$
And that is of course understandable since the bound surface current is not inside the Amperian loop. Now, when we read on we reach an example (in that same section):

And then his solution for both the field inside the material and outside of it:

Applying Eq. 6.20 to an Amperian loop of radius $s < R$,
$$H(2 \pi s) = I_{f_{\text{enc}}} = I \dfrac{\pi s^2}{\pi R^2},$$
so, inside the wire,
$$\mathbf{H} = \dfrac{I}{2 \pi R^2} s \hat{\phi} \ \ \ (S \le R). \tag{6.21}$$
Outside the wire
$$\mathbf{H} = \dfrac{I}{2 \pi s} \hat{\phi} \ \ \ (S \ge R). \tag{6.22}$$
In the latter region (as always, in empty space) $\mathbf{M} = \mathbf{0}$, so
$$\mathbf{B} = \mu_0 \mathbf{H} = \dfrac{\mu_0 I}{2 \pi s} \hat{\phi} \ \ \ (s \ge R),$$

Now, as can be seen, for the outside case, he uses the equation he earlier defined for the inside case only - which doesn't contain the term expressing the contribution of the bounded surface current to the magnetic field, I was under the impressiong that the definition
$$\mathbf{H} \equiv \dfrac{1}{\mu_0} \mathbf{B} - \mathbf{M}$$
is only valid for Ampere's law inside a material. For the outside case I would except to see the term
$$\mathbf{K}_b = \mathbf{M} \times \mathbf{\hat{n}}$$
as well but that is not the case.
Can someone please clarify this for me?

A: The relation
$$
\mathbf B = \mu_0(\mathbf H + \mathbf M)
$$
is general, it is valid both inside body, outside the body (in vacuum), and also at the boundary of the two.
Outside the body magnetization vanishes, $\mathbf M = 0$ so there the relation simplifies into
$$
\mathbf B =\mu_0 \mathbf H.
$$

A: In addition to the bound surface current you've identified, there are also bound volume currents inside the wire.  But we can show that the net effects of all these bound currents cancel out for points outside the wire.
Specifically, imagine any loop $L$ encircling the wire.  The net amount of bound current passing through this loop is
$$
I_b = \iint_S \vec{J}_b \cdot d \vec{a},
$$
where $S$ is a surface spanning our loop $L$.  Since $\vec{J}_b = \vec{\nabla} \times \vec{M}$, we can apply Stokes's theorem to find that
$$
I_b = \iint_S \vec{J}_b \cdot d \vec{a} = \iint_S \left( \vec{\nabla} \times \vec{M} \right) \cdot d \vec{a} = \oint_L \vec{M} \cdot d\vec{l}.
$$
But $\vec{M} = 0$ everywhere on the loop (since it sits outside the wire), and so $I_b = 0$ as well.
This means that when we apply Ampere's Law, we have
$$
\oint \vec{B} \cdot d\vec{l} = \mu_0 I = \mu_0 (I_b + I_f) = \mu_0 I_f,
$$
i.e., only the free current contributes to the integral.  If we further assume that the problem has axial symmetry (which is reasonable in this problem, assuming that the copper rod is homogenous), then Griffiths's derivation of the magnetic field follows.
Note that the above method applies to bound surface currents as well.  We just have to view a surface current $\vec{K}$ as a volume current "with a delta function in it", similarly to how we can treat point charges or surface charges as density functions over all of space by inserting delta-functions judiciously.  For example, if we assume that the copper rod is a linear medium, then we have $\vec{M} = \chi_m \vec{H}$, and so
$$
\vec{J}_b = \chi_m \vec{\nabla} \times \vec{H} = \frac{\chi_m I}{\pi R^2} \hat{z}, \qquad \vec{K}_b = \chi_m \vec{H} \times \hat{n} = - \frac{\chi_m I}{2 \pi R} \hat{z}.
$$
These two terms can be combined, if we wish, into a single distributional bound current density:
$$
\vec{J}_b = \left[ \frac{\chi_m I}{\pi R^2} - \frac{\chi_m I}{2 \pi R} \delta(s - R) \right] \hat{z}.
$$
Defined in this way, we can simply talk about a bound current density which satisfies $\vec{J}_b = \vec{\nabla} \times \vec{M}$ in a distributional sense, without worrying about the split between volume and surface currents.  Note also that neither term (bound volume current or bound surface current) has zero net current on its own;  it's only their net bound current, combined, that vanishes.


text:
Q: wordpress files could not downloaded on Mozilla I run wordpress+woocommerce, but when user try to download file from the site,
Mozilla show that:
secure connection failed
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified. Please contact the website owners to inform them of this problem.
Only work in Chrome.
And when I upgrade wordpress to v5.4 woocommerce v4, it has this issue!
Any help will be grateful.


text:
Q: How to show hide nvd3 pie chart labels programmatically I am stuck at a very small issue. I need to show and hide pie labels on click of radio button. I am using nvd3 pie chart with Dojo.
Following is the code snippet:
if(this._elemPool.data_type.widget[0].checked) {
          this.connectedWidgets.graph.chart.labelType("value");
          this.connectedWidgets.graph.chart.showLabels(false);
        } else {
          this.connectedWidgets.graph.chart.labelType("percent");
          this.connectedWidgets.graph.chart.showLabels(true);
        }

When I select percent labels option first it works correctly then when i select value option it does not hide the label nor does it show values.
Can anyone please help me resolve this. I need to show label only when it is percent otherwise not.

A: It seems like NVD3 forgets to remove labels. You could manually remove all elements in your chart as a workaround. Execute the following lines after you have made changes to your chart's settings:
d3.select("#chart svg").selectAll("*").remove();
chart.update();

Demo

var chart;

nv.addGraph(function() {
  chart = nv.models.pieChart()
    .x(function(d) {
      return d.label
    })
    .y(function(d) {
      return d.value
    });

  d3.select("#chart svg")
    .datum(exampleData())
    .transition().duration(350)
    .call(chart);

  return chart;
}, function() {
  switchToPercentageMode();
});

function switchToPercentageMode() {
  chart.labelType("percent")
    .showLabels(true);
  d3.select("#chart svg").selectAll("*").remove();
  chart.update();
}

function switchToValueMode() {
  chart.labelType("value")
    .showLabels(false);
  d3.select("#chart svg").selectAll("*").remove();
  chart.update();
}

$("#percentage").change(function() {
  switchToPercentageMode();
});

$("#value").change(function() {
  switchToValueMode();
});

function exampleData() {
  return [{
    "label": "One",
    "value": 29.765957771107
  }, {
    "label": "Two",
    "value": 0
  }, {
    "label": "Three",
    "value": 32.807804682612
  }, {
    "label": "Four",
    "value": 196.45946739256
  }, {
    "label": "Five",
    "value": 0.19434030906893
  }, {
    "label": "Six",
    "value": 98.079782601442
  }, {
    "label": "Seven",
    "value": 13.925743130903
  }, {
    "label": "Eight",
    "value": 5.1387322875705
  }];
}
#chart {
  height: 500px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.2/nv.d3.min.css" rel="stylesheet" />

<input type="radio" name="chartMode" value="percentage" id="percentage" checked>
Percentage
<input type="radio" name="chartMode" value="value" id="value">
Value

  <svg></svg>


text:
Q: Selenium href click after inputting field I am new to selenium and python and am hoping to get some guidance here.
I am trying to enter a zip code and then parse the resulting data that gets displayed.  The problem I have is that after entering a zip code I cannot seem to click on the correct href id.
site I am testing on is: https://www.citizensbank.com/custom/RegionializationGateway.aspx?targetpage=/loans/mortgage-refinance.aspx#
I am using selenium ver 3.141.0 and python 3.9.1
what I have tried is the following:
...
inputElement = driver.find_element_by_id('zip_input_region')
inputElement.send_keys(zip)

#Attempt 1 not working
searcher = driver.find_element_by_class_name("cta_btn")
searcher.click()

#Attempt 2 not working
element_to_click = driver.find_element_by_id("zip_submit_region")
driver.execute_script("arguments[0].click();", element_to_click)

#Attempt 3 not working
driver.find_element_by_link_text("Submit").click()

WebDriverWait(driver, 15).until(EC.url_changes(url))

...
What am I missing?  Appreciate any help or guidance you can provide.
Thanks in advance!

A: Try the following wait for the element to be clickable. Also added Options
options = Options()
options.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Chrome(options=options)
wait = WebDriverWait(driver, 10)
driver.get('https://www.citizensbank.com/custom/RegionializationGateway.aspx?targetpage=/loans/mortgage-refinance.aspx#')
wait.until(EC.element_to_be_clickable((By.ID, "zip_input_region"))).send_keys(zip)
wait.until(EC.element_to_be_clickable((By.ID, "zip_submit_region"))).click()

Import
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options


text:
Q: Multilevel StdClass Object, print result First post here, but couldnt find any good results when searching..
Data is from a third party API via SOAP.
Im trying to print the value of an object, but only gets:

Notice: Trying to get property of non-object in xx.

Tried $results->Info->First->One2;
1object(stdClass)#3 (1) {
  ["Info"]=>
  object(stdClass)#4 (27) {
["First"]=>
object(stdClass)#5 (7) {
  ["One1"]=>
  NULL
  ["One2"]=>
  NULL
  ["One3"]=>
  NULL
}
["Second"]=>
object(stdClass)#6 (7) {
  ["Two1"]=>
  string(0) ""
  ["Two2"]=>
  string(0) ""
  ["Two3"]=>
  string(3) "1WL"
  }
 }
}

´
stdClass Object
(
[Info] => stdClass Object
    (
        [First] => stdClass Object
            (
                [One1] => value1
                [One2] => value2
                [One3] => value3
            )
    [Second] => stdClass Object
            (
                [Two1] => value4
                [Two2] => value5
                [Two3] => value6
                )
    )
}


text:
Q: How to fix cross-origin error when request to Kylo API I have a running instance of a Kylo Sandbox in a server called: kyloserver. I am trying to access Kylo API from my website, running in localhost:8080.
I try to use Search API calling url:
http://kyloserver:8400/proxy/v1/feedmgr/search?q=mary&rows=20&start=0

and using Basic Authentication in header like this (javascript):
Authorization: 'Basic ' + btoa(this.username + ":" + this.password)

The response is:

Failed to load
  http://kyloserver:8400/proxy/v1/feedmgr/search?q=mary&rows=20&start=0:
  Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:8080' is therefore not allowed
  access. The response had HTTP status code 403.

If I use swagger by logging into the UI I can get the results properly.
How can I access the API successfully?
(Kylo Version: 0.8.3)
Thanks.

A: Kylo has disabled CORS support by default. You'll need to write a plugin to override the default configuration with one that enables CORS:
https://github.com/Teradata/kylo/blob/v0.8.4/services/service-app/src/main/java/com/thinkbiganalytics/server/DefaultWebSecurityConfigurer.java

A: Finally I decided to create a Proxy web service which is hosted in the same server as Kylo, which just redirects the requests from the web to the Kylo Service.


text:
Q: Обязать наследников воспользоваться событием Допустим, в абстрактном классе описано событие.
Можно ли обязать наследников обязательно воспользоваться им?

A: Насколько я понял, Вам просто нужно использовать интерфейс, содержащий это событие, для всех наследников.


text:
Q: "Attribute Error" using pytrends library on python I'm trying to run a script using pytrends library to scrape Google Trends.
import pytrends
kw_list = ["covid"]
pytrends.build_payload(kw_list, cat=0, timeframe='2021-02-01 2021-07-09', geo='BR', gprop='')
gt_o3_ytd1 = pytrends.interest_over_time()

I'm getting the following error message:
AttributeError                            Traceback (most recent call last)
<ipython-input-4-e6a3a9855c66> in <module>
      2
      3 kw_list = ["covid"]
----> 4 pytrends.build_payload(kw_list, cat=0, timeframe='2021-02-01 2021-07-09', geo='BR', gprop='')
      5 gt_o3_ytd1 = pytrends.interest_over_time()

AttributeError: module 'pytrends' has no attribute 'build_payload'

A: # import the TrendReq method from the pytrends request module
from pytrends.request import TrendReq

# execute the TrendReq method by passing the host language (hl) and timezone (tz) parameters
pytrends = TrendReq(hl='en-US', tz=360)

kw_list = ["covid"]
pytrends.build_payload(kw_list, cat=0, timeframe='2021-02-01 2021-07-09', geo='BR', gprop='')
gt_o3_ytd1 = pytrends.interest_over_time()
gt_o3_ytd1

A: Try
mytrend = pytrends.TrendReq()
mytrend.build_payload(kw_list, cat=0, timeframe='2021-02-01 2021-07-09', geo='BR', gprop='')
gt_o3_ytd1 = pytrends.interest_over_time()


text:
Q: Using jQuery on dynamically added content I am newbie to jQuery and javascript. In my application I have a list of users. When a particular user is clicked from the list, a div element is replaced with details about the user dynamically. When another user is clicked, again I replace the same div element with this user details. So at a time only one user details can be seen.
I use jquery, so my code to the above description looks like.

$('table#moderate_users tr').click(function() {
$.get('/moderate/user/'+uid, function(data){         $('div.user_info').html(data);
});
});
This works perfect and the content is inserted dynamically.
I have a dropdown(html select tag) in the dynamically added content. So I get the dropdown only when i click on a user from the list and it changes repectively when I click on another user. I wanted to find the value of the select tag using jquery whenever it is changed. So I wrote

$('select#assign_role').change(function(){
alert(this.val());
});
Since this dropdown is added after document.ready, adding this script inside document.ready function never worked. I also tried to insert the above script along the with the user details which is dynamically added.For my surprise this script is not inserted into the document at all, while the rest of the HTML content are inserted perfect. I am not aware if i can add insert javascript after the document has loaded. I am not aware how i could use jQuery to find out the value of the select tag which is added dynamically.
Thanks.

A: you want jQuery's "live" functionality:
$('select#assign_role').live('change',function(){
alert($(this).val());
});

also notice I changed alert(this.val()); to alert($(this).val()); considering that this inside a jQuery event handler references the actual dom element, not a jQuery object.

A: From the looks of your code, it seems that you are inserting a chunk of HTML into that div. So even if you wire your event to the dropdown after the page load, it will not work, since all of your event binding will be ignored when you insert new HTML code into div.
Try moving your code inside the function that inserts HTML. Something like this:
    $('table#moderate_users tr').click(function() {
    $.get('/moderate/user/'+uid, function(data){
    $('div.user_info').html(data);
     $('select#assign_role').change(function(){
      alert(this.val());
     });
    });
    });

A: On IE the live function doesn't work for onchange on <select> elements.
http://www.neeraj.name/blog/articles/882-how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery
You will need to either add the select then do a setTimeout and then bind with the jquery.bind type of functionality, or, what I have done, is when you create the element then just set the onchange event handler there directly.
If you don't need to support IE then the live function works great.


text:
Q: How to create compile time condition checks in C The problem is that due to some unavoidable reasons I need to maintain 2 copy of same structure in a C code.
Is there a way I can add some compiler check to make sure if someone changes (adds/deletes/modifies) one of the structure that person should also update the copy ?
The two solutions I can think of are :

*

*I can add a comment as a request to whoever makes changes (Very unreliable)

*I can use offsetof() for fields as a runtime check

But I am looking for something which can assure this during compilation.

A: There is no perfect way.
You can use a static assert macro like found in C compiler asserts - how to implement?
and then assert the sizeof each struct is the same.  But that doesn't mean they are identical.
Possibly the better way is to add some code generation in so that part of the build you generate the copy from the original.
But ultimately something is wrong when you have to duplicate something rather than re-use.

A: Only allow struct doublestruct * and global supporting functions like ds_foo(struct doublestruct *, ...) to be visible to the rest of code.  Then file ds.c can control all access to and from struct doublestruct and maintain a redundant copy.
// ds.h
struct doublestruct *ds_Init();
void ds_setA(struct doublestruct *ds, int A);
int ds_getA(const struct doublestruct *ds);

// ds.c
struct doublestruct {
  int A;
  double B;
  char C;
};

#include <stdlib.h>

struct doublestruct * ds_Init() {
  struct doublestruct *p = malloc(sizeof *p *2);
  if (p) memset(p, 0, sizeof *p * 2);
  return p;
}

void ds_setA(struct doublestruct *ds, int A) {
  ds[0].A = A;
  ds[1].A = A;
}

int ds_getA(const struct doublestruct *ds) {
  if (ds[0].A != ds[1].A) exit(-1);  // Memory failure
  return ds[0].A;
}

A: I think the right way to cope with this situation is to make some kind of signature to the structure definition and check it at make time so you can check for modifications.

*

*first, mark the structures of this type, so you can access to them
easily:  something like '_some_tag_' #define'd as nothing in
some header allows you to search for it automatically.

*then, use some kind of development tool to parse the fields, canonicalyze them
and make some kind of hash function as a result.

*register this signature for future compilations and warn the compiling team of a
structure change.

Think, you had better to be overcomplaint than under, so in case of structure modification you'll get at least one indication.
Suppose you have:
struct A { bla bla bla };

and then you modify it to be:
#include <somefile where you have defined macro ___hash_protected___>
/* #define ___hash_protected___ */
...
struct ___hash_protected___ A { bla bla bla };

now, write a program that searches for that tag, computes the signature of structure A and checks it with the value stored in a database file.  It must do two things: first compute the hash value of the structure, then compare it with the saved one and warn if they differ.  If structure is new, just add the hash value to the database.
I you want to protect it from unauthorized use, just use a cryptographic secure hash function (e.g. SHA256) and protect it with some secret string prepended.
Of course, you'll have to parse at least the structure definition to be able to calculate a valid hash.
but, REMEMBER, you had better to define it in a common include file, than to define it twice.  I know there are cases in which a define file has to be distributed to be used at several places, leading to possible different versions of it.


text:
Q: Which is faster to analyze between .str.contains and "string" in "string" I have to create a column in a dataframe with hundreds of conditions. This includes looking into text. :
print(df["Short description"].str.contains("e"))

This code works on a single line but when I include it in my function with all the others, I get the error :
attributeerror 'str' object has no attribute 'str'

Now, if I execute a basic elseif but not for a Dataframe in my function with everything else, it works :
"e" in df2["Short description"]: return "things"

So I would need to know which one is faster for Python, knowing that my function is :
df2["Deversement Service"] = df2.swifter.apply(conditions, axis=1)

Where is condition is hundreds of else if similar to the one above.
Thanks for your help

A: The return value of df["Short Description"] is already a str. You don't need to use .str you can directly use .contains("e")
Example:
print(df["Short description"].contains("e"))


text:
Q: Excel files are not being read when executing Selenium C# Scripts on Azure Releases I have some Selenium C# tests hosted on Azure which they need to look for the pre-built excel file in project tree, stored inside bin folder, to execute some file upload validation scenarios.
When they are executed locally these scenarios pass without any problem, but when it comes to be executed on the Azure they receive the following error.
invalid argument: File not found : D:\a\r1\a_Selenium_Tests\TestApplication\bin\Debug\netcoreapp3.1\Files\SC003_CT014_ActiveEmployees.xlsx

The files do exists in the following path: ...\bin\Debug\netcoreapp3.1\Files...
And the code I use to them is:
string root = Directory.GetCurrentDirectory() + "\\Files\\" + file;
Do you know if there's a missing file configuration or building the filePath in another way?
Thanks for your help :D

A: Directory.GetCurrentDirection() returns the current working directory, not the folder in which the DLL file resides. The current working directory is a different thing. In your case, the current working directory is probably something like D:\a\r1\. Instead, you need to get the folder in which the test assembly resides:
var binDirectory = Path.GetDirectoryName(GetType().Assembly.Location);
//                                       ^^^^^^^^^
var excelFilePath = Path.Combine(binDirectory, "Files", "SC003_CT014_ActiveEmployees.xlsx");

Note: Replace GetType() with typeof(ClassName) if you are executing your code from a static method, or you would like to specify a path to a different assembly than the one that is currently executing.


text:
Q: Difficulty understanding why acceleration of free fall is lower at the equator than the poles I have been told that the acceleration of free fall is lower at the equator than at the poles, and that this has to do with the fact that at the equator, you are moving with circular motion so centripetal and centrifugal forces are at play, whereas at the pole this is not the case.
I've considered two frames of reference: one at the pole (O) and one at the equator (O'). If a ball is dropped at the equator, then in the reference frame O', there is centripetal force $F$ acting on the ball so the force on the ball is $mg{_{1}}+F = mg{_{2}}$ where $mg{_{1}}$ is the ball's "true" weight while mg${_{2}}$ is the apparent weight, so it makes sense that acceleration of free fall, $g{_{2}}$ is smaller. However, from the reference frame O, the falling ball appears to undergo centrifugal force, $-F$, so $mg{_{1}}-F = mg{_{2}}$ meaning acceleration of free fall would appear greater ($g{_{2}}>g{_{1}}$). This is obviously a contradiction. Where is the flaw in my understanding?

A: Consider the descent of the ball from a reference frame in which the Earth is rotating once every 24 hours. Whether that frame has its origin of coordinates at the equator or at a pole is irrelevant.
At the equator the pull of gravity on the body has to supply the falling body's acceleration towards the Earth merely to keep the body rotating with the Earth, in other words it has to supply the centripetal force needed. So less force is left over to give the observable free fall acceleration. As an equation
$$ma_\text{free fall}=mg_e-mr\omega^2\ \ \ \ \text{so}\ \ \ \ a_\text{free fall}=g_e-r\omega^2$$
in which $g_e$ is the gravitational field strength at the equator.
At the pole, $r=0$ and the gravitational field strength, $g_p$ is slightly greater than $g_e$, owing to the Earth's shape, so
$$a_\text{free fall}=g_p$$
So the free fall acceleration is greater at the pole than at the equator for two reasons!
If you wish to consider the situation from a frame of reference rotating with the Earth, you attribute the ball's reduced freefall acceleration at the equator to a centrifugal force acting away from the Earth (as well as to the field strength being less at the equator). In this rotating frame there is no centripetal force requirement; you are not rotating with respect to that frame!

A: The shape  of the Earth is not really a perfect sphere as usually thought
It's like an elliphoid with the two flat regions on the North and and South poles and bulging surface on the equator.  So the radius from the Earth's centre to the equator is greater than its radius from its centre to either of the two poles which means that it is closer to the Earth's centre of mass on the two poles than on the equator, and the gravitational pulling force of the Earth on a particke is
F= G (Mm)/r^2 . Where r is the distance between the Earth's centre of mass and the particle , M is the Earth's mass, m is the particle's mass . G is gravitational constant. When the particle is realeased, it will fall toward the Earth's surface with an acceleration called gravitational acceleration, as a result of the gravitational force of the Earth pulling on the particle , F = m*a(g)
F=G(Mm)/r^2 and F =ma(g) ---->  ma(g)= GM*m/r^2 or a(g)= GM/r^2
When you substitute the Earth's radius from its centre to the equator in the formula  to compute the gravitational acceleration of the particle
a(g) = GM/r^2
where G and M are constant and the Earth's radius from its centre to either the two poles and tge Earth's radius from its centre to the equator,
You can see that the gravitational acceleration at two poles are greater due to the fact that  radius from the Earth's centre to the two  pole is smaller  than the radius from the Earth's centre to the equator
Now consider the Earth's rotational motion around its axis
When it rotates any object on its surface also rotates about its axis , and there are two forces acting on objects. One is the reaction or normal force from the Earth's surface along the radial axis from its centre of mass outward to objects on its surface, and the other force is gravitaional force directed inward toward its centre of mass
So the net force is :
Fnet = Fn - ma (g) = ma(r)
Where Fn is normal force,  ma(g) is the gravitational force,
a(r) is centripetal acceleration which also points toward the Earth's centre of mass along the radial axis "r"
Fn = mg -----> Fnet = mg -ma(g)= ma(r)
Radial acceleration a(r) can also be expressed as:
a(r) = w^2R . Where w is angular velocity of the circular motion,
R is the radius of he circle or circular path of objects on the Earth's surface
So mg -ma(g) = ma(r) can be simplified as :
g - a(g) = a(r) ----> g - a(g) = -w^2R
g = a(g) -w^2R
Where g is free fall acceleration, angular velocity w and the radius R are constant for the same object
Since earlier, a(g) has been prove to be greater at the two poles
Free fall acceleration "g" is also greater at the two poles


text:
Q: Match any comma and dot in currency format, but not the last one I want to convert money format to decimal, which is will be stored in the database as decimal data type
example:
12,345.45 to 12345.45
10.000.00 to 10000.00

I've tried with this regex pattern /(,|\.)/ but the last dot(indicate cents value) still involved, I was confused about how to exclude the last dot
expected result, exclude the last dot in given string

A: Using php, you may use preg_replace like this:
$repl = preg_replace('/\.(?=\d+\.)|,/', '', $str);

RegEx Demo
RegEx Details:

*

*\.: Match .

*(?=\d+\.): Positive lookahead to assert that we have a dot ahead after 1+ digits

*|: OR

*,: Match a comma


text:
Q: gradle dependency not being executed My situation is this:

*

*before I can package this app I need to pull a common dependency

*I pull it once to the root directory and then copy it to the subproject for speed

*I need to then build

*drop a build artifact into this copied directory

So, when I run this sample task, it pulls the dependency to the root folder but never copies it and I am just not seeing why. Below is my trimmed down kotlin build
import com.ullink.Msbuild
import java.io.File

plugins {
    id("com.ullink.msbuild") version "3.8" apply false

}
subprojects {
    apply(plugin = "com.ullink.msbuild")
    val solution = projectDir.walkTopDown().find { it.extension == "sln" }!!
    tasks {

        val restore by register("restore", Exec::class) {
            executable = "nuget"
            args = listOf(
                    "restore", solution.canonicalPath,
                    "-Source",
                    (getenv("NUGET_SOURCE") ?: project.properties["package.sources"]) as String
            )
        }

        val msbuild by named<Msbuild>("msbuild") {
            dependsOn(restore)
            solutionFile = solution
            projectName = project.name
            verbosity = "quiet"
            targets = listOf("Clean", "Rebuild")
            configuration = "Release"
        }

        val cpfms by register<Copy>("cpFms"){
            dependsOn(rootProject.tasks.named("pullfms"))
            doLast{
                println("cpFms do last")

                val from = projectDir
                        .listFiles()
                        .find{ it.isDirectory() && it.name.toLowerCase().startsWith("prism.core.fulfillmentmicroservice") }!!
                println("making copy ${from} -> ${projectDir}")
                from(from)

                into(projectDir)
            }
        }

        val build by named("build") {
            dependsOn(msbuild)
        }
        val cpdll by register<Copy>("cpFmsdll") {
            dependsOn(cpfms,build)

            doLast{
                println("cpFmsdll do last")
                val from = projectDir.walkTopDown().find{ it.name == "PRISMDataAdaptor.dll" }!!
                val to = projectDir.listFiles().find{ it.isDirectory() && it.name.toLowerCase().startsWith("prism.core.fulfillmentmicroservice") }!!
                println("cp dll ${from} -> ${to}")
                from(from)
                into(to)
            }
        }

    }
}

tasks{
    val pullFms by register("pullfms", Exec::class) {
        args = listOf(
                "install", "PRISM.Core.FulfillmentMicroService",
                "-Source", (getenv("NUGET_PUBLISH") ?: project.properties["publish.repo"]) as String
        )
        executable = "nuget"
    }
}

so when I run
gradle :adaptor-cwi_ky_statewide_smd:cpFmsdll
I expect that it will

*

*pull my dependency as defined in the root project

*copy it to the local project

*build

*copy the build dll into the folder in step 2

The dry run shows what I would expect:
PS C:\Users\cbongiorno\dev\sterling\prism\prism-adaptors> gradle --dry-run :adaptor-cwi_ky_statewide_smd:cpFmsdll
:adaptor-cwi_ky_statewide_smd:assemble SKIPPED
:adaptor-cwi_ky_statewide_smd:check SKIPPED
:adaptor-cwi_ky_statewide_smd:restore SKIPPED
:adaptor-cwi_ky_statewide_smd:msbuild SKIPPED
:adaptor-cwi_ky_statewide_smd:build SKIPPED
:pullfms SKIPPED
:adaptor-cwi_ky_statewide_smd:cpFms SKIPPED
:adaptor-cwi_ky_statewide_smd:cpFmsdll SKIPPED

but the execution doesn't actually do it?! The directly isn't copied in the the local project but it is in the root project
PS C:\Users\cbongiorno\dev\sterling\prism\prism-adaptors> gradle :adaptor-cwi_ky_statewide_smd:cpFmsdll

> Task :adaptor-cwi_ky_statewide_smd:restore
MSBuild auto-detection: using msbuild version '15.5.180.51428' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\bin'.
All packages listed in packages.config are already installed.

> Task :pullfms
Feeds used:
  https://repo.dev.backgroundcheck.com/nexus/repository/nuget-group/

Installing package 'PRISM.Core.FulfillmentMicroService' to 'C:\Users\cbongiorno\dev\sterling\prism\prism-adaptors'.
  CACHE https://repo.dev.backgroundcheck.com/nexus/repository/nuget-group/FindPackagesById()?id='PRISM.Core.FulfillmentMicroService'&semVerLevel=2.0.0
Package "PRISM.Core.FulfillmentMicroService.0.0.77" is already installed.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.3/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 1m 6s
3 actionable tasks: 3 executed
PS C:\Users\cbongiorno\dev\sterling\prism\prism-adaptors> ls | select -Last 20

    Directory: C:\Users\cbongiorno\dev\sterling\prism\prism-adaptors

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        7/14/2020  10:08 PM                gradle
d-----        7/21/2020   3:36 PM                infra
d-----        5/13/2020   4:17 AM                PRISM-Adaptor-QC_LA_SaintBernard
d-----        8/25/2020   4:25 PM                PRISM.Core.FulfillmentMicroService.0.0.77
d-----        7/14/2020   8:07 AM                routeadaptor-apinationwide_msmj1_dre
d-----        5/13/2020   4:18 AM                serviceadaptor-cwi_ky_statewide_smd
d-----        5/13/2020   4:18 AM                serviceadaptor-cwi_ny_statewide
d-----        5/13/2020   4:18 AM                serviceadaptor-qc_ny_statewide
-a----        7/14/2020   8:07 AM           2581 .gitattributes
-a----        8/25/2020   4:22 PM          13996 .gitignore
-a----        8/25/2020   4:51 PM           6653 build.gradle.kts
-a----        7/21/2020   3:36 PM            987 Dockerfile
-a----        8/14/2020   4:28 PM            206 gradle.properties
-a----        7/14/2020  10:08 PM           5764 gradlew
-a----        7/14/2020  10:08 PM           2942 gradlew.bat
-a----        7/21/2020   3:36 PM           2222 Jenkinsfile
-a----        5/13/2020   4:17 AM          11565 PRISM-Adaptors.txt
-a----        7/14/2020   8:07 AM            722 README.md
-a----        8/25/2020   3:24 PM            416 settings.gradle.kts
-a----        7/14/2020   8:07 AM            978 sh.exe.stackdump

PS C:\Users\cbongiorno\dev\sterling\prism\prism-adaptors> ls .\adaptor-cwi_ky_statewide_smd\

    Directory: C:\Users\cbongiorno\dev\sterling\prism\prism-adaptors\adaptor-cwi_ky_statewide_smd

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        7/21/2020   1:24 PM                build
d-----        7/21/2020   1:14 PM                CWI_KY_STATEWIDE_SMDSol
-a----        5/13/2020   4:17 AM           2581 .gitattributes

PS C:\Users\cbongiorno\dev\sterling\prism\prism-adaptors>

at the end I see to basically need to replicate this code (example):
nuget.exe restore CWI_TN_DAVIDSON_SMDSol\CWI_TN_DAVIDSON_SMDSol.sln -source "https://www.nuget.org/api/v2;http://prism-prod-oct/NuGetLocalServer/nuget"
MSBuild.exe C:\PRISMGit\adaptor-cwi_tn_davidson_smd\CWI_TN_DAVIDSON_SMDSol\CWI_TN_DAVIDSON_SMDSol.sln /t:Clean /p:Configuration=Release
MSBuild.exe C:\PRISMGit\adaptor-cwi_tn_davidson_smd\CWI_TN_DAVIDSON_SMDSol\CWI_TN_DAVIDSON_SMDSol.sln /t:Rebuild /p:Configuration=Release

Set-Location C:\PRISMGit\adaptor-cwi_tn_davidson_smd\CWI_TN_DAVIDSON_SMDSol\PRISM.Adaptor.CWI.TN.DAVIDSON.SMD\

$Package = Find-Package -Name PRISM.Core.FulfillmentMicroService -Source http://prism-prod-oct/NuGetLocalServer/nuget

NuGet.exe install $Package.Name  -Version $Package.Version -source http://prism-prod-oct/NuGetLocalServer/nuget

Copy-Item -Path .\bin\Release\PRISMDataAdaptor.dll -Destination (".\"+$Package.Name+ "." + $Package.Version+"\")   -Recurse -Force

A: Regarding the configuration of your copy task:
val cpfms by register<Copy>("cpFms") {
    dependsOn(rootProject.tasks.named("pullfms"))
    doLast {
        // ...
        from(from)
        into(projectDir)
    }
}

val cpdll by register<Copy>("cpFmsdll") {
    dependsOn(cpfms,build)
    doLast {
        // …
        from(from)
        into(to)
    }
}

The issue is that you configuration your copy task during the its execution. So I think your tasks is not configured and then not executed.
You can see an example of configuration in the Gradle Copy documentation. There is no doLast part.
Your copy task are relying on file/directory that are created by an earlier task.
I think you should considered that the file will be here and use include from regarding a pattern and not regarding that files are really here (which may explain why you used doLast)
Example:
val cpfms by register<Copy>("cpFms") {
    dependsOn(rootProject.tasks.named("pullfms"))
    from("**/PRISMDataAdaptor.dll")
    into("prism.core.fulfillmentmicroservice")
}

A: Ok, thanks to @dwursteisen for putting me on the right track. Solving this specific problem required use of delegation:
      val cpfms by register<Copy>("cpFms") {
            dependsOn(rootProject.tasks.named("pullfms"))

            val from by lazy {
                rootProject.projectDir.listFiles()
                        .find { it.isDirectory() && it.name.toLowerCase().startsWith("prism.core.fulfillmentmicroservice") }
            }
            from(from)
            into(projectDir)
        }

This now, actually works. However, the above sample may actually be better as it's just simply less complicated.


text:
Q: Aligning labels in a chordDiagram from circlize package I have quite a complex circos plot and am having some trouble aligning the labels.
To demonstrate the issue I have included a short reproducible example below.
I can not figure out how to nicely align every label so that they all sit exactly the same distance from the corresponding segment e.g. as per the label tyranosauras rex. Many of the labels are hidden and overlapping and different distances from the edge of the plot. Any help would be greatly appreciated.
library("circlize")
circos.clear()

# create data
somelongnames <- c("homo sapiens", "arabidopsis thaliania", "Tyrannosaurus rex",
                  "some other long name", letters[seq(4)])

df <- data.frame(x = somelongnames,
                 y = c("this label is very far away from the plot", "Golgi",
                       letters[13:18]),
                 count = c(2, 10, 4, 5, 5, 1, 9, 3))

# set colours
ll <- unique(c(df$x, df$y))
grid.col <- rainbow(length(ll))
grid.col <- setNames(grid.col, ll)

# create plot
par(mar = c(1,1,1,1)*12, cex = 0.6, xpd=NA)

chordDiagram(df, annotationTrack = "grid",
             preAllocateTracks = 1,
             grid.col = grid.col,
             directional = 1,
             direction.type = c("diffHeight", "arrows"),
             link.arr.type = "big.arrow")

circos.trackPlotRegion(track.index = 1, panel.fun = function(x, y) {
  xlim = get.cell.meta.data("xlim")
  ylim = get.cell.meta.data("ylim")
  sector.name = get.cell.meta.data("sector.index")
  circos.text(mean(xlim),
              ylim[1] + .1,
              sector.name,
              facing = "clockwise",
              niceFacing = TRUE,
              adj = c(-0.5, 0.1),
              cex = 1,
              col=grid.col[sector.name],
              font = 2)
  circos.axis(h = "top",
              labels.cex = .6,
              major.tick.length = 1,
              sector.index = sector.name,
              track.index = 2)
}, bg.border = NA)

A: This question has been answered here by the package author of circlize
Re-posting here to answer the above -
The main problem is the setting of track.index = 2 in circos.axis() which changes the current track.
Change the position on y-axis to ylim[1] + cm_h(2). This means 2cm's offset to the y = ylim[1]. (It seems it is not really 2cm on the plot, but you can manually change this value).
adj is changed to adj = c(0, 0.5). Note the value of adj is multiplied to the length of the text length, so the physical length are not the same for all sector names.
Remove major.tick.length = 1 because I think the default length of ticks should look fine.
The following code fixes the above question
chordDiagram(df, annotationTrack = "grid",
             preAllocateTracks = 1,
             grid.col = grid.col,
             directional = 1,
             direction.type = c("diffHeight", "arrows"),
             link.arr.type = "big.arrow")

circos.trackPlotRegion(track.index = 1, panel.fun = function(x, y) {
  xlim = get.cell.meta.data("xlim")
  ylim = get.cell.meta.data("ylim")
  sector.name = get.cell.meta.data("sector.index")
  circos.text(CELL_META$xcenter,
              ylim[1] + cm_h(2),
              sector.name,
              facing = "clockwise",
              niceFacing = TRUE,
              adj = c(0, 0.5),
              cex = 1,
              col=grid.col[sector.name],
              font = 2)
  circos.axis(h = "bottom",
              labels.cex = .6,
              sector.index = sector.name
              )
}, bg.border = NA)


text:
Q: bootstrap unselectable radio button i have this btn-group:

                Sex

                    <input id="filtro_sexo" type="hidden" />

                        <button value="Male" type="button" class="btn">Male</button>
                        <button value="Female" type="button" class="btn">Female</button>

the problem is that I need the user to be able to select or deselect the option. the user should be able to select one option, or none.
but data-toggle = "buttons-radio" will not let me deselect the option selected.

A: I achieve this by using [data-toggle=buttons-checkbox], add a custom attribute [data-single-select], and write few lines of jQuery:
HTML:

    <button class="btn">...</button>
    <button class="btn">...</button>
    <button class="btn">...</button>

jQuery:
$("[data-toggle='buttons-checkbox'][data-single-select] .btn").live('click', function(evt){
    $(this).siblings().removeClass('active');
});

@Rafael
using [input type="radio"] looks way too ugly. That's why we use Bootstrap.


text:
Q: How to get first record of each group created using groupBy() with Laravel eloquent model? I have a table structured as following named renewals.
------------------------------------------------
| id  | membership_id| valid_from | valid_upto |
------------------------------------------------
|  1  | 1            | 2015-02-15 | 2016-02-15 |
|  2  | 2            | 2015-05-16 | 2016-05-16 |
|  3  | 2            | 2016-05-16 | 2017-05-16 |
|  4  | 3            | 2014-06-16 | 2015-06-16 |
|  5  | 3            | 2015-06-16 | 2016-06-16 |
|  6  | 3            | 2016-06-16 | 2017-06-16 |
|  7  | 1            | 2016-02-15 | 2017-02-15 |
------------------------------------------------

I need to get record of each members with latest valid_upto date. How to do that using Laravel Eloquent. Any other easy method will be appreciated.

A: In User Model
public function latest_renewal()
{
    return $this->hasOne('App\Renewals', 'membership_id')->latest('valid_upto');
}

In controller
$users = User::with('latest_renewal')->get();
/*
 [
   {
     'id' => 1,
     'name' => 'user1',
     'latest_renewal' => {
         'id' => 7,
         'membership_id' => 1,
         'valid_from' => '2016-02-15',
         'valid_upto' => '2017-02-15',

     }
   },
   {
     'id' => 2,
     'name' => 'user2',
     'latest_renewal' => {
         'id' => 3,
         'membership_id' => 2,
         'valid_from' => '2016-05-16',
         'valid_upto' => '2017-05-16',

      }
    }
 ]

A: Renewals::groupBy('membership_id')->havingRaw('MAX(valid_upto)')->get();

or
Renewals::groupBy('membership_id')->having( function( $query )
{
    $query->latest('valid_upto');
})->get();

A: In plain MySQL, you could get your latest records per member by following:
select a.*
from renewals a
left join renewals b on a.membership_id = b.membership_id
and a.valid_upto < b.valid_upto
where b.membership_id is null

DEMO
Using Laravel, you could write it using query builder as:
DB::table('renewals as a')
  ->select('a.*')
  ->leftJoin('renewals as b', function ($join) {
        $join->on('a.membership_id','=','b.membership_id')
             ->whereRaw(DB::raw('a.valid_upto < b.valid_upto'));
   })
  ->whereNull('b.membership_id')
  ->get()

A: May be something simlilar to this
DB::statement("SET SQL_MODE=''");

Renewal::groupBy('membership_id')
         ->latest('valid_upto')
         ->get();

Read more about the first SET SQL_MODE: Laravel : Syntax error or access violation: 1055 Error

A: $data = Renewal::get();
$groups = $data->groupBy('membership_id');
$results = [];
foreach($groups as $group) {
   /*collection*/
   $results[] = $group[0];
}
return $results;

source : https://stackoverflow.com/a/29731825/13381751

A: You can use below query for your purpose.
$renewals = Renewals::groupBy('membership_id')->orderBy('valid_upto','desc')->get();


text:
Q: Spring Boot: Hibernate and Flyway boot order I have created Spring application. Pom xml is attached.
It has a config like this (below) and some db/migration/V1__init.sql for Flyway db migration tool.
It has hsqldb in-memory database and it is created after application is started. It is clean after creation.
I want Hibernate to create a schema based on entity classes and then Flyway fills the tables. Now Flyway starts V1__init.sql before tables is created and throw an exception. How can I change this order or what solution can I do?
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect

pom.xml:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>1.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.hsqldb</groupId>
        <artifactId>hsqldb</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>

    <!-- For using 'LEGACYHTML5' mode in Thymeleaf -->
    <dependency>
        <groupId>net.sourceforge.nekohtml</groupId>
        <artifactId>nekohtml</artifactId>
        <version>1.9.21</version>
    </dependency>
    <dependency>
        <groupId>xml-apis</groupId>
        <artifactId>xml-apis</artifactId>
        <version>1.4.01</version>
    </dependency>

    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>1.3.3.RELEASE</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

A: For more recent users that use Spring Boot +2.1 and as @mota commented into @user3707816's answer, you can use spring.flyway.enabled=false in application.properties and then create a new instance manually:
Flyway.configure().dataSource(dataSource)
                .baselineOnMigrate(true)
                .schemas(PG_DATABASE_SCHEMA)//optional, by default is public
                .load().migrate();

A: I had the same issue.
I wanted my schema to be created by hibernate because of it's database independence.  I already went through the trouble of figuring out a nice schema for my application in my jpa classes,  I don't like repeating myself.
But I want some data initialization to be done in a versioned manner which flyway is good at.
Spring boot runs flyway migrations before hibernate. To change it I overrode the spring boot initializer to do nothing.  Then I created a second initializer that runs after hibernate is done.  All you need to do is add this configuration class:
import org.flywaydb.core.Flyway;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

@Configuration
public class MigrationConfiguration {

    /**
     * Override default flyway initializer to do nothing
     */
    @Bean
    FlywayMigrationInitializer flywayInitializer(Flyway flyway) {
        return new FlywayMigrationInitializer(flyway, (f) ->{} );
    }

    /**
     * Create a second flyway initializer to run after jpa has created the schema
     */
    @Bean
    @DependsOn("entityManagerFactory")
    FlywayMigrationInitializer delayedFlywayInitializer(Flyway flyway) {
        return new FlywayMigrationInitializer(flyway, null);
    }

}

That code needs java 8,  If you have java 7 or earlier,  replace (f)->{} with an inner class that implements FlywayMigrationStrategy
Of course you can do this in xml just as easily.
Make sure to add this to your application.properties:
flyway.baselineOnMigrate = true

A: This works for me with Spring Boot 2.3.1
1- you need to disable boot for Flyway, by insert into resources/application.properties:
spring.flyway.enabled = false

2- Start your migration scripts from version 2 as V1 is used as a baseline, V1 file will be ignored.
3- Make the @SpringBootApplication class implements CommandLineRunner interface (It is used to execute the code after the Spring Boot application started
). and it will be like this:
@SpringBootApplication
public class SpringBootApplication implements CommandLineRunner {

    @Autowired
    DataSource dataSource;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        Flyway.configure().baselineOnMigrate(true).dataSource(dataSource).load().migrate();
    }

}

This answer helped me

A: All SQL migrations will start after Hibernate creates all the tables.
Spring Boot 2.2.2, Flyway 6.0.8
To disable boot for Flyway, insert into resources/application.properties:
spring.flyway.enabled=false

Create separate configuration for Flyway to make it load when Hibernate is ready:
@Configuration
public class FlywayConfiguration {

    @Autowired
    public FlywayConfiguration(DataSource dataSource) {
        Flyway.configure().baselineOnMigrate(true).dataSource(dataSource).load().migrate();
    }
}

Start your migration scripts from version 2:
resources/db.migration/V2__fill-tables.sql

V1 is used as a baseline, V1 file will be ignored.

A: Spring Boot auto-configuration of Flyway ensures that database migrations have run before Hibernate is initialised. In other words, you can't rely on Flyway auto-configuration and use Flyway to populate tables created by Hinernate.
One solution is to fully embrace Flyway and use it to both create the tables and populate them. You can then switch off Hibernate's table creation (spring.jpa.hibernate.ddl-auto=none). This approach is more robust as it will allow your database to evolve more easily. This is what I would recommend that you do.
Another solution is to disable auto-configuration of Flyway (flyway.enabled=false) and to configure it your self. You can then configure Flyway to depend on Hibernate so that Hibernate has created the tables before Flyway tries to populate them.

A: For anyone who still wants to configure Flyway as a bean as of Spring Boot 2.1.8 and later, but is falling onto the circular dependency error, there is a way to exclude the @DependsOn("flyway") that the auto-configured EntityManagerFactory uses by default.
First, set spring.flyway.enabled to false and then create a class extending BeanFactoryPostProcessor so we can exclude the Flyway dependency before the beans are created. Example:
@Component
public class FlywayDeferrerPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        excludeDependsOnFlywayFromBean(beanFactory, DataSourceScriptDatabaseInitializer.class);
        excludeDependsOnFlywayFromBean(beanFactory, EntityManagerFactory.class);
    }

    private void excludeDependsOnFlywayFromBean(ConfigurableListableBeanFactory beanFactory, Class<?> beanClass) {
        Stream.of(beanFactory.getBeanNamesForType(beanClass))
            .map(beanFactory::getBeanDefinition)
            .filter(it -> it.getDependsOn() != null && it.getDependsOn().length > 0)
            .forEach(it -> it.setDependsOn(Stream.of(it.getDependsOn()).filter(name -> !name.equals("flyway")).toArray(String[]::new)));
    }
}

This example is very minimal and could probably break on new versions. For instance, in my project, I did the same thing somewhat differently using a custom method recursivelyExcludeDependencyOnFromBeanDefinition(EntityManagerFactory.class, Flyway.class), that finds all dependencies form EntityManagerFactory which also depends on Flyway, so we don't have to know, for example, that DataSourceScriptDatabaseInitializer also depends on Flyway.
To make it all work, just add the bean definition normally:
@Bean(initMethod = "migrate")
@DependsOn("entityManagerFactory")
public Flyway flyway() { /* ... */ }

Of course, if you don't care about Flyway being available as a bean, then I would recommend using a custom @Configuration file like the one from @pavelety's answer.

A: may be because of the order
add
on application.properties
flyway.out-of-order = true

or
application.yml on spring
flyway:
  out-of-order: true


text:
Q: If the restriction of two continuous linear functions are equal, then are these two functions equal? Let $X$ be a normed space and let $M$ be a linear subspace of $X$. Let $f,g\in X^*$ be such that $f|_M=g|_M$. Then can we get $f=g$?
Or do we need $M$ being dense to get $f=g$? If so, how to prove it?
Thank you in advance!

A: Take $f,g\colon \Bbb R^2\to \Bbb R$ where $f(x,y)=xy$ and $g(x,y)=0$. Then $f|_{\Bbb R\times\{0\}}=g|_{\Bbb R\times\{0\}}$ since both are identically $0$, but $f\neq g$ since $f(1,1)\neq g(1,1)$.

A: The first statement is not true, as we can take any $f\in X^*$ nonzero, let $g=\lambda f$ for some nonunit scalar $\lambda$, and let $M=\ker(f)$.
The second statement is true, and follows by continuity.  Suppose $M$ is dense, and $f=g$ on $M$.  Then $f-g=0$ on $M$, and by continuity $f-g=0$ on $X$.  To be more precise, fix $x\in X$ and $\varepsilon>0$.  Since $f-g$ is continuous, there is some $\delta>0$ such that $|(f-g)(x-y)|<\varepsilon$ whenever $\|x-y\|<\delta$.  Since $M$ is dense, there is some $y\in M$ with $\|x-y\|<\delta$, and thus $|(f-g)(x)|=|(f-g)(x-y)|<\varepsilon$.  Since $\varepsilon>0$ was arbitrary, $(f-g)(x)=0$, and since $x\in X$ was arbitrary, $f-g=0$.

A: Consider the normed space $(C[-1,1], \|\cdot\|_\infty)$ and two functionals $F,G \in C[-1,1]^*$ given by
$$F(f) = \int_{-1}^1 f(x)\,dx, \qquad \quad G(f) = 2\int_{0}^1 f(x)\,dx$$
for all $f \in C[-1,1]$.
Then $F \ne G$ but $F$ and $G$ coincide on the subspace of even continuous functions on $[-1,1]$.


text:
Q: go from an extended polynomial to a Bezier polynomial What is the analytical expression to do a change of basis from the extended polynomial form i.e.
$$ \mathbf {B} (t)=\sum _{j=0}^{n}{t^{j}\mathbf {C} _{j}} $$
to a Bezier form
$$ \mathbf{B} (t) =\sum _{i=0}^{n}{n \choose i}(1-t)^{n-i}t^{i} \mathbf{P} _{i}$$
where $\mathbf{P} _{i}$ are the control points and we know the relation
$$\mathbf{C} _{j}={\frac {n!}{(n-j)!}}\sum _{l=0}^{j}{\frac {(-1)^{l+j}\mathbf {P} _{l}}{l!(j-l)!}}$$
so what has to be done is to solve the following system for $\mathbf{P}$
\begin{gather}
\begin{bmatrix} \mathbf{C}_0 \\
\vdots \\
\mathbf{C}_j \\
\vdots \\
\mathbf{C}_n \end{bmatrix} = AB \begin{bmatrix} \mathbf{P}_0 \\
\vdots \\
\mathbf{P}_j \\
\vdots \\
\mathbf{P}_n \end{bmatrix}
\end{gather}
where $A\in \mathcal{M}_{n\times n}(\mathbb{R})$ is defined by
\begin{align} A_{ij} =& \frac{n!}{(n-i)!} &\mbox{ if }i=j \\
& 0 &\mbox{ sinon}
\end{align}
and $B \in \mathcal{M}_{n\times n}(\mathbb{R})$ is defined by
\begin{align} B_{ij} =& \frac{(-1)^{i+j}}{i!(j-i)!} &\mbox{ if }i\geq j \\
&  0 &\mbox{ sinon}
\end{align}
an then $(AB)^{-1}$ will be the matrix to change the basis, anyone knows the analytical value for $(AB)^{-1}$?

A: See section 7 of these notes:
https://www.uio.no/studier/emner/matnat/math/MAT-INF4160/h15/undervisningsmateriale/bezier1.pdf
Or section 3.3 of these notes:
http://hdl.lib.byu.edu/1877/2822


text:
Q: What is the relative performance difference of if/else versus switch statement in Java? Worrying about my web application's performances, I am wondering which of "if/else" or switch statement is better regarding performance?

A: According to Cliff Click in his 2009 Java One talk A Crash Course in Modern Hardware:

Today, performance is dominated by patterns of memory access.  Cache misses dominate – memory is the new disk. [Slide 65]

You can get his full slides here.
Cliff gives an example (finishing on Slide 30) showing that even with the CPU doing register-renaming, branch prediction, and speculative execution, it's only able to start 7 operations in 4 clock cycles before having to block due to two cache misses which take 300 clock cycles to return.
So he says to speed up your program you shouldn't be looking at this sort of minor issue, but on larger ones such as whether you're making unnecessary data format conversions, such as converting "SOAP → XML → DOM → SQL → …" which "passes all the data through the cache".

A: I remember reading that there are 2 kinds of Switch statements in Java bytecode. (I think it was in 'Java Performance Tuning' One is a very fast implementation which uses the switch statement's integer values to know the offset of the code to be executed. This would require all integers to be consecutive and in a well-defined range. I'm guessing that using all the values of an Enum would fall in that category too.
I agree with many other posters though... it may be premature to worry about this, unless this is very very hot code.

A: In my test the better performance is ENUM > MAP > SWITCH > IF/ELSE IF in Windows7.
import java.util.HashMap;
import java.util.Map;

public class StringsInSwitch {
public static void main(String[] args) {
    String doSomething = null;

    //METHOD_1 : SWITCH
    long start = System.currentTimeMillis();
    for (int i = 0; i < 99999999; i++) {
        String input = "Hello World" + (i & 0xF);

        switch (input) {
        case "Hello World0":
            doSomething = "Hello World0";
            break;
        case "Hello World1":
            doSomething = "Hello World0";
            break;
        case "Hello World2":
            doSomething = "Hello World0";
            break;
        case "Hello World3":
            doSomething = "Hello World0";
            break;
        case "Hello World4":
            doSomething = "Hello World0";
            break;
        case "Hello World5":
            doSomething = "Hello World0";
            break;
        case "Hello World6":
            doSomething = "Hello World0";
            break;
        case "Hello World7":
            doSomething = "Hello World0";
            break;
        case "Hello World8":
            doSomething = "Hello World0";
            break;
        case "Hello World9":
            doSomething = "Hello World0";
            break;
        case "Hello World10":
            doSomething = "Hello World0";
            break;
        case "Hello World11":
            doSomething = "Hello World0";
            break;
        case "Hello World12":
            doSomething = "Hello World0";
            break;
        case "Hello World13":
            doSomething = "Hello World0";
            break;
        case "Hello World14":
            doSomething = "Hello World0";
            break;
        case "Hello World15":
            doSomething = "Hello World0";
            break;
        }
    }

    System.out.println("Time taken for String in Switch :"+ (System.currentTimeMillis() - start));

    //METHOD_2 : IF/ELSE IF
    start = System.currentTimeMillis();

    for (int i = 0; i < 99999999; i++) {
        String input = "Hello World" + (i & 0xF);

        if(input.equals("Hello World0")){
            doSomething = "Hello World0";
        } else if(input.equals("Hello World1")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World2")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World3")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World4")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World5")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World6")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World7")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World8")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World9")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World10")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World11")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World12")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World13")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World14")){
            doSomething = "Hello World0";

        } else if(input.equals("Hello World15")){
            doSomething = "Hello World0";

        }
    }
    System.out.println("Time taken for String in if/else if :"+ (System.currentTimeMillis() - start));

    //METHOD_3 : MAP
    //Create and build Map
    Map<String, ExecutableClass> map = new HashMap<String, ExecutableClass>();
    for (int i = 0; i <= 15; i++) {
        String input = "Hello World" + (i & 0xF);
        map.put(input, new ExecutableClass(){
                            public void execute(String doSomething){
                                doSomething = "Hello World0";
                            }
                        });
    }

    //Start test map
    start = System.currentTimeMillis();
    for (int i = 0; i < 99999999; i++) {
        String input = "Hello World" + (i & 0xF);
        map.get(input).execute(doSomething);
    }
    System.out.println("Time taken for String in Map :"+ (System.currentTimeMillis() - start));

    //METHOD_4 : ENUM (This doesn't use muliple string with space.)
    start = System.currentTimeMillis();
    for (int i = 0; i < 99999999; i++) {
        String input = "HW" + (i & 0xF);
        HelloWorld.valueOf(input).execute(doSomething);
    }
    System.out.println("Time taken for String in ENUM :"+ (System.currentTimeMillis() - start));

    }

}

interface ExecutableClass
{
    public void execute(String doSomething);
}

// Enum version
enum HelloWorld {
    HW0("Hello World0"), HW1("Hello World1"), HW2("Hello World2"), HW3(
            "Hello World3"), HW4("Hello World4"), HW5("Hello World5"), HW6(
            "Hello World6"), HW7("Hello World7"), HW8("Hello World8"), HW9(
            "Hello World9"), HW10("Hello World10"), HW11("Hello World11"), HW12(
            "Hello World12"), HW13("Hello World13"), HW14("Hello World4"), HW15(
            "Hello World15");

    private String name = null;

    private HelloWorld(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void execute(String doSomething){
        doSomething = "Hello World0";
    }

    public static HelloWorld fromString(String input) {
        for (HelloWorld hw : HelloWorld.values()) {
            if (input.equals(hw.getName())) {
                return hw;
            }
        }
        return null;
    }

}

//Enum version for betterment on coding format compare to interface ExecutableClass
enum HelloWorld1 {
    HW0("Hello World0") {
        public void execute(String doSomething){
            doSomething = "Hello World0";
        }
    },
    HW1("Hello World1"){
        public void execute(String doSomething){
            doSomething = "Hello World0";
        }
    };
    private String name = null;

    private HelloWorld1(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void execute(String doSomething){
    //  super call, nothing here
    }
}

/*
 * http://stackoverflow.com/questions/338206/why-cant-i-switch-on-a-string
 * https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10
 * http://forums.xkcd.com/viewtopic.php?f=11&t=33524
 */

A: It's extremely unlikely that an if/else or a switch is going to be the source of your performance woes. If you're having performance problems, you should do a performance profiling analysis first to determine where the slow spots are. Premature optimization is the root of all evil!
Nevertheless, it's possible to talk about the relative performance of switch vs. if/else with the Java compiler optimizations. First note that in Java, switch statements operate on a very limited domain -- integers. In general, you can view a switch statement as follows:
switch (<condition>) {
   case c_0: ...
   case c_1: ...
   ...
   case c_n: ...
   default: ...
}

where c_0, c_1, ..., and c_N are integral numbers that are targets of the switch statement, and <condition> must resolve to an integer expression.

*

*If this set is "dense" -- that is, (max(ci) + 1 - min(ci)) / n > α, where 0 < k < α < 1, where k is larger than some empirical value, a jump table can be generated, which is highly efficient.

*If this set is not very dense, but n >= β, a binary search tree can find the target in O(2 * log(n)) which is still efficient too.
For all other cases, a switch statement is exactly as efficient as the equivalent series of if/else statements. The precise values of α and β depend on a number of factors and are determined by the compiler's code-optimization module.
Finally, of course, if the domain of <condition> is not the integers, a switch
statement is completely useless.

A: For most switch and most if-then-else blocks, I can't imagine that there are any appreciable or significant performance related concerns.
But here's the thing:  if you're using a switch block, its very use suggests that you're switching on a value taken from a set of constants known at compile time.  In this case, you really shouldn't be using switch statements at all if you can use an enum with constant-specific methods.
Compared to a switch statement, an enum provides better type safety and code that is easier to maintain.  Enums can be designed so that if a constant is added to the set of constants, your code won't compile without providing a constant-specific method for the new value. On the other hand, forgetting to add a new case to a switch block can sometimes only be caught at run time if you're lucky enough to have set your block up to throw an exception.
Performance between switch and an enum constant-specific method should not be significantly different, but the latter is more readable, safer, and easier to maintain.

A: I totally agree with the opinion that premature optimization is something to avoid.
But it's true that the Java VM has special bytecodes which could be used for switch()'s.
See WM Spec (lookupswitch and tableswitch)
So there could be some performance gains, if the code is part of the performance CPU graph.

A: That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two if/else blocks glued together or its size is unpredictable, then you may highly consider a switch statement.
Alternatively, you can also grab Polymorphism. First create some interface:
public interface Action {
    void execute(String input);
}

And get hold of all implementations in some Map. You can do this either statically or dynamically:
Map<String, Action> actions = new HashMap<String, Action>();

Finally replace the if/else or switch by something like this (leaving trivial checks like nullpointers aside):
actions.get(name).execute(input);

It might be microslower than if/else or switch, but the code is at least far better maintainable.
As you're talking about webapplications, you can make use of HttpServletRequest#getPathInfo() as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers:

*

*Using a custom Servlet oriented framework, too many servlets, is this an issue

*Java Front Controller
If you're worrying about Java EE webapplication performance in general, then you may find this article useful as well. There are other areas which gives a much more performance gain than only (micro)optimizing the raw Java code.

A: Use switch!
I hate to maintain if-else-blocks! Have a test:
public class SpeedTestSwitch
{
    private static void do1(int loop)
    {
        int temp = 0;
        for (; loop > 0; --loop)
        {
            int r = (int) (Math.random() * 10);
            switch (r)
            {
                case 0:
                    temp = 9;
                    break;
                case 1:
                    temp = 8;
                    break;
                case 2:
                    temp = 7;
                    break;
                case 3:
                    temp = 6;
                    break;
                case 4:
                    temp = 5;
                    break;
                case 5:
                    temp = 4;
                    break;
                case 6:
                    temp = 3;
                    break;
                case 7:
                    temp = 2;
                    break;
                case 8:
                    temp = 1;
                    break;
                case 9:
                    temp = 0;
                    break;
            }
        }
        System.out.println("ignore: " + temp);
    }

    private static void do2(int loop)
    {
        int temp = 0;
        for (; loop > 0; --loop)
        {
            int r = (int) (Math.random() * 10);
            if (r == 0)
                temp = 9;
            else
                if (r == 1)
                    temp = 8;
                else
                    if (r == 2)
                        temp = 7;
                    else
                        if (r == 3)
                            temp = 6;
                        else
                            if (r == 4)
                                temp = 5;
                            else
                                if (r == 5)
                                    temp = 4;
                                else
                                    if (r == 6)
                                        temp = 3;
                                    else
                                        if (r == 7)
                                            temp = 2;
                                        else
                                            if (r == 8)
                                                temp = 1;
                                            else
                                                if (r == 9)
                                                    temp = 0;
        }
        System.out.println("ignore: " + temp);
    }

    public static void main(String[] args)
    {
        long time;
        int loop = 1 * 100 * 1000 * 1000;
        System.out.println("warming up...");
        do1(loop / 100);
        do2(loop / 100);

        System.out.println("start");

        // run 1
        System.out.println("switch:");
        time = System.currentTimeMillis();
        do1(loop);
        System.out.println(" -> time needed: " + (System.currentTimeMillis() - time));

        // run 2
        System.out.println("if/else:");
        time = System.currentTimeMillis();
        do2(loop);
        System.out.println(" -> time needed: " + (System.currentTimeMillis() - time));
    }
}

My C# standard code for benchmarking

A: A good explanation at the link below:
https://www.geeksforgeeks.org/switch-vs-else/
Test(c++17)
1 - If grouped
2 - If sequential
3 - Goto Array
4 - Switch Case - Jump Table
https://onlinegdb.com/Su7HNEBeG

A: Speed: A switch statement might prove to be faster than ifs provided number of cases are good. If there are only few cases, it might not effect the speed in any case. Prefer switch if the number of cases are more than 5 otherwise, you may use if-else too. If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.
Clarity in readability: A switch looks much cleaner when you have to combine cases. Ifs are quite vulnerable to errors too. Missing an else statement can land you up in havoc. Adding/removing labels is also easier with a switch and makes your code significantly easier to change and maintain.
Example:->
String environment="QA";
    switch(environment.toLowerCase().trim()) {
    case "qa":
        System.out.println(environment+" :"+"Environment running the TestCases");
        break;
    case "Stage":
        System.out.println(environment+" :"+"Environment running the TestCases");
        break;
    case "Dev":
        System.out.println(environment+" :"+"Environment running the TestCases");
        break;
    case "UAT":
        System.out.println(environment+" :"+"Environment running the TestCases");
        break;
    case "Prod":
        System.out.println(environment+" :"+"Environment running the TestCases");
        break;
    default:
        System.out.println(environment+" :"+"Please pass the right Environment");
        break;
    }

    String browser="Chrome";

    if (browser.equals("chrome")) {
        System.out.println(browser + ": " + " Launch the Browser");
    } else if (browser.equals("safari")) {
        System.out.println(browser + ": " + " Launch the Browser");
    } else if (browser.equals("IE")) {
        System.out.println(browser + ": " + " Launch the Browser");
    } else if (browser.equals("opera")) {
        System.out.println(browser + ": " + " Launch the Browser");

    } else if (browser.equals("Edge")) {
        System.out.println(browser + ": " + " Launch the Browser");

    } else {
        System.out.println("Please pass the right browser");
    }


text:
Q: Multiplying two series together How would I multiply two series together? Or also split them into two separate series? For example:
$$\sum_{y=1}^{b}\sum_{x=1}^{a}2^{(2x+3y)}$$
I tried multiplying the summation of $4^x$ with $8^y$...

A: Use that $2^{2x+3y}=2^{2x}\cdot 2^{3y}$ and so
$$
\sum_{x=1}^a\sum_{y=1}^b 2^{2x+3y}=\left\{\sum_{x=1}^a2^{2x}\right\}\cdot\left\{\sum_{y=1}^b2^{3y}\right\}
$$
which you correctly state yield
$$
\left\{\sum_{x=1}^a 4^x\right\}\cdot\left\{\sum_{y=1}^b8^y\right\}.
$$
These are finite geometric series.

Let's calculate the first sum:
$$
\sum_{x=1}^a 4^x=\left\{\sum_{x=0}^a4^x\right\} -1=\frac{1-4^{a+1}}{1-4}-1.
$$
Now you can simplify this a bit.


text:
Q: PHP json string variable I want to decode a JSON string. However, the value that I got is something like this string(100) "{"data":{"type":"campaign-folders","id":"d208f3171a","attributes":{"name":"My Folder"}}}".
Could anyone tell me what should I do so that I can treat this variable as a usual string ?

A: Use json_decode http://php.net/manual/en/function.json-decode.php
$obj = json_decode($json);
var_dump($obj);

A: Use json_decode ,you can solve it.
var_dump(json_decode($json, true));//check this.

A: here to convert JSON string to Array
 $someArray = json_decode($someJSON, true);
  print_r($someArray);
 echo $someArray[0]["name"];

and here to convert JSON to Object
$someObject = json_decode($someJSON);
 print_r($someObject);
 echo $someObject[0]->name;


text:
Q: How to normalise gaussian mask I try to make algorithm, which make gaussian 1d array on ints.
I try to make algorithm, which make gaussian 1d array and off caurce at the and I have float array with normal distribution
Something like this [0.00411637, 0.0501476, 0.224746, 0.370544, 0.224746, 0.0501476, 0.00411637]
And how to normalise this to the view something like this [1,3,4,9,4,3,1] ,
I have tried different normalisatians but at the end values start to go beyond the limit of the maximum value of ints
My code:
float get_super_hard_exp_1d(int x,int sigma){
    float power_of_exp = (float)std::pow(x,2) / (float)(2 * std::pow(sigma,2));
    return exp(-power_of_exp);
}

float return_point_gauss_1d(int x, int sigma){
    return (1.0f / (std::pow((2.0f * M_PI + sigma),0.5f))) * get_super_hard_exp_1d(x,sigma);
}

std::vector<float> get1DMaskBlurGaus(int r){
    std::vector<float> out;

    int sigma = 1;

    for(int x = -r; x <= r; x++){
        out.push_back(return_point_gauss_1d(x,sigma));
    }

    for(int j = 0; j < out.size(); j++){
        std::cout << out[j] << " ";
    }
    std::cout << std::endl << out.size() << std::endl;
    return out;

}


text:
Q: How to handle backstack for replacing the same fragment with different data In order to navigate between fragments within 1 activity, I implemented a method called fragmentSwicher, that gets a fragment and replaces it with activated fragment in container.
So far so good, but now the problem is I want to re-use a fragment with different data, but my fragmentSwitcher method refuses to change fragment because of existing the fragment in backstack.
public void fragmentSwitcher(Fragment frg) {

    String backStateName = frg.getClass().getName();
    String fragmentTag = backStateName;

    FragmentManager manager = getFragmentManager();

    boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);

    FragmentTransaction ft = manager.beginTransaction();

    // check if fragment, is poped from backstack and there isnt any fragment in backstack like what we want to replace
    if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
        ft.replace(R.id.main_container, frg, fragmentTag);
    }

    // with this method, we make sure that, no loading fragment come into frament backstack list, so, we are back safe.
    if (!backStateName.equals("com.thetba.websitebuilder.fragments.ProgressFragments")) {
        ft.addToBackStack(backStateName);
    }

    ft.commit();

}

And this the method that handles backstack in MainActivity:
@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() == 1) {
        finish();
    // check if there is more than one fragment in backstack, show it
    } else {
        getFragmentManager().popBackStack();
    }
}

I tried to partially solve this issue this way: I put
ft.replace(R.id.main_container, frg, fragmentTag);

outside of
    if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) {
        ft.replace(R.id.main_container, frg, fragmentTag);
    }

And fragmentSwitcher() replaces the same fragment with different data, BUT when user presses the back button, s/he will face with this fragment:
com.thetba.websitebuilder.fragments.ProgressFragments

that is not in backstack.
That said, what should I do to handle backstack when replacing same fragment?

A: This problem is because of replacing same Fragment class, although you can just repopulate Fragment with another data, but, handling BackStack in this solution is complicated.
so, for this purpose only you can introduce new Fragment with new name for replacement. to do this, you can add some random things at the end of backstackName string.
example:
if (backStateName.contains("com.thetba.websitebuilder.fragments.PagesFragment")) {
       backStateName += String.valueOf(getRandomInt(10, 500));
}