text:
Q: Unable to connect to remote HTTPS API's without DNS - Istio I have a Service which is running in Istio 1.16 with envoy sidecar injection enabled.
The service connect with a remote API every now and then to send the health information.
The remote end point is https but without having a domain name, yeah the endpoint have to be invoked like https://168.x.x.x/http/health. I could see the connection is working fine with another API but with a proper hostname.
So the issue is clearly with the DNS resolution, I am not great with networking. So, you folks should help me out.
This is the error i get from the server (of service).

x509: cannot validate certificate for  because it doesn't contain any IP SANs

*

*Istio version - 1.16

*Kubernetes - 1.24

*golang (service) - 1.19

Can we bypass this x509 SAN check using destination Rules?

A: The error "x509: certificate has expired or is not yet valid" usually occurs when the SSL certificate being used has expired or has not yet been activated. This error can also occur when the certificate being used is not valid for the domain or IP address that the request is being sent to.
To resolve this issue, you will need to either obtain a new valid SSL certificate or renew the existing certificate.
You can check your certificate expiration date by using the below command:
kubeadm certs check-expiration

Refer to this SO for more detailed steps.


text:
Q: VBA fill a range with a specific cell In a worksheets i have "Dates" in Cells(1,1), Cells(1,10), Cells(1,19), Cells(1,28) .....
I have a variable named nr_rows witch in my case is 860, and i need to put under every "Dates" the results from Row 1 in Row 2 until Row 860.
The results must be like:
       |       A         |       J          |      S           |.....
-----------------------------------------------------------
  1    |  21.02.16 16:20 |  21.02.16 16:21  |  21.02.16 16:22  |.....
  2    |  21.02.16 16:20 |  21.02.16 16:21  |  21.02.16 16:22  |.....
  3    |  21.02.16 16:20 |  21.02.16 16:21  |  21.02.16 16:22  |.....
.....................................................................
860    |  21.02.16 16:20 |  21.02.16 16:21  |  21.02.16 16:22  |.....

This i what i have done but i have error 1004
nr_rows is 860
col = 1
For col = 1 To 256
    For n = 1 to nr_rows

ActiveSheet.Cells(1, col).Select
    Selection.AutoFill Destination:=Range(Cells(1, col), Cells(n,col))
    col = col + 9

    Next n
Next col

A: edited after OP's clarifications about quitting AutoFill() method
use this:
Option Explicit

Sub main()
    Dim nr_rows As Long, col As Long

    nr_rows = 860
    With ActiveSheet
        For col = 1 To 256 Step 9
            .Cells(1, col).Resize(nr_rows).Value = .Cells(1, col).Value
        Next col
    End With
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Emacs Lisp - Should you unset keys before setting them? If I'm going to redefine a key, should I call (global-unset-key (kbd "key-combo")), or does using the function global-set-key automatically call that for me?

A: There is absolutely no need to unset the key before setting it.
This is similar to variable setting in any programming language: you do not need to do foo = NULL before foo = x. This comparison is closer than one might think because (global-unset-key k) is the same as (global-set-key k nil).

A: Like sds saied, global-unset-key actually calls global-set-key:
(defun global-unset-key (key)
  "Remove global binding of KEY.
KEY is a string or vector representing a sequence of keystrokes."
  (interactive "kUnset key globally: ")
  (global-set-key key nil))

so there is no real difference between set and unset key actually.


text:
Q: How to perform this integration in terms of elementary functions? I need to perform this in tegration in terms of elementary functions... I'm not used to perform integrations like this, so a detailed answer would be very welcome. My integral is the following,
%
$$
\int \frac{dx}{\sqrt{P(x)}} \,\, ,
$$
with
$$
P(x) = \frac{1}{27}-x^{2}(1+2x) \,\, , \qquad x \in \mathbb{R}\,\, .
$$
Once the roots of $P(x)$ are $r_{1}=-1/6$ and the following 2-algebric multiplicity $r_{2}=r_{3} = 1/3$, we can Put the polynomial in the form,
$$
P(x) = 2\left(x +\frac{1}{6}\right)\left(x-\frac{1}{3}\right)^{2} \,\, .
$$
I'm stuck here.

A: Use the substitution $$x+\frac {1}{6}=t^2$$
For integrals of the form, $$\int \frac{1}{(ax+b) \sqrt{px+q}} \rm dx$$
A standard substitution is $px+q=t^2$

A: The hint:
Let $$\sqrt{x+\frac{1}{6}}=t.$$


text:
Q: String comparisons in selenium using xpath fails even though both strings are exactly same I am using key word driven and data driven framework.
Expected string is coming from excel sheet and Actual from webpage
even though both variable print exactly same strings  still the Test script fails.
It does "PASS" for strings with no space like "Resign" but "FAIL" for string with space like "Property Search"
below is the result which prints PASS till "Resign" after that it fails
ignore the numbers its for debugging.
I also included xpath used in result.
Result generated
By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[1]
Tool tip text present :- Revals
Revals
1
By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[2]/a[contains(text(),'Managed Client Accounts')]
Tool tip text present :- Managed Client Accounts
Managed Client Accounts
1
By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[3]
Tool tip text present :- Resigns
Resigns
1
By.xpath: .//[@id='dashboard-dropdown']/li[4]/a
Tool tip text present :- Outstanding AR
Outstanding AR
4
By.xpath: .//[@id='menuCreateDashboard']
Tool tip text present :- Manage Dashboard
Manage Dashboard
4
By.xpath: html/body/div[2]/div/div[2]/ul/li[2]/a
Tool tip text present :- Property Search
Property Search
4
By.xpath: html/body/div[2]/div/div[2]/ul/li[3]/a
Tool tip text present :- Tax Resource Database
Tax Resource Database
4
By.xpath: html/body/div[2]/div/div[2]/ul/li[4]/a[contains(text(),'Quick Links')]
Tool tip text present :- Quick Links
Quick Links
4
Here is the code:
public String verify_Text(String locatorType, String value, String data){
       try
  {
     By locator;
     locator = locatorValue(locatorType, value);
     System.out.println(locator);
     WebElement element = driver.findElement(locator);

     //WebElement element = driver.findElement(By.cssSelector("#header>h1 a"));
    // Get tooltip text
    String toolTipText = element.getText();
    System.out.println("Tool tip text present :- " + toolTipText);
    System.out.println(data);

    // Compare toll tip text

         if(toolTipText.contentEquals(data))
           {
               System.out.println("1");
              return PASS;

           }

  }
  catch(Exception e)
  {
     LOG.error(Executor.currentSheet + ":" + e);
     getScreenshot("verify_Link", data);
     System.out.println("3");
     return FAIL;
  }
  getScreenshot("verify_Link", data);
  System.out.println("4");
  return FAIL;

}

A: line of code which worked   for me
if(toolTipText.replaceAll("\\s+","").equalsIgnoreCase(data.trim().replaceAll("\\s+","")))

I realized after using this code and debugging is data passed from excel sheet had space in between two letter whereas there was no space on webelement tool tip .But this I was not able to figure it out using inspect element as its not visible.
before using replaceall("\s+","")
By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[5]/a
Tool tip text present :- ManageDashboard
Manage Dashboard
after  using replaceAll("\s+","") and removing space from data coming from excel sheet
By.xpath: html/body/div[2]/div/div[2]/ul/li[1]/ul/li[5]/a
Tool tip text present :- ManageDashboard
ManageDashboard

A: I don't have enough rep to comment but I am suggesting some things to try:
You could trim the string, perhaps there is a char that is not visible in one of the Strings.
if(toolTipText.trim().contentEquals(data.trim()))

Or you could try to use normalize-space to remove tab, carriage return and line feed characters.
/*/a[normalize-space() = 'Hello World']

A: Sometimes when you fetch the text from WebElements, they tend to have a leading or trailing space(s) in them. A better comparison would be
toolTipText.trim().equals(data.trim())
If this still doesn't work, maybe remove all the spaces from the strings and then compare. Like this:
toolTipText = toolTipText.trim().replaceAll("\\p{Z}", "");
data = data.trim().replaceAll("\\p{Z}", "");
toolTipText.equals(data)

Here, the string Outstanding AR will become OutstandingAR after replaceAll. This is certainly an overkill, but if it works, then it's evident that the spaces in the string is what caused the problem.

A: In my opinion, your function is trying to do way too much and is overly complicated for the simple task you are trying to accomplish. I think at least part of the issue is that you are using contentEquals() instead of equals().
You are using Java. There is a great library that will take care of all the different comparisons you would want to do with it called JUnit. Use that to do your comparisons and clean up the code and you can use code like the below.
String expectedTooltip = "some value from Excel";
By locator = By.cssSelector("#header > h1 a");
getScreenshot("verify_Link", expectedTooltip);
Assert.assertEquals("verify tooltip", expectedTooltip, getTooltip(locator));

and a support function that just gets the tooltip from the element specified by the locator. You don't want to pass around strings and convert them to locators. Use the By class instead. It makes things simpler. I added a .trim() here to get rid of any unintended spaces at either end of the string.
public String getTooltip(By locator)
{
    return driver.findElement(locator).getText().trim();
}

If you still have issues with string not matching, there may be non-printable characters in some of those strings that you will have to remove/replace before performing the comparisons. One way to figure this out is to loop through each string and print the ASCII values for each character and see where the difference is.


text:
Q: Removing trailing white spaces after text in python Let's say that I have a file with several SQL queries, all separated by ";". If put the contents of the file in a string and do:
with open(query_file) as f:
    query = f.read()
    f.close()

queries = query.split(';')

I'll get a list where each item is one of the queries. Which is my final objective. However, how do I include here that if the last item is only spaces, next lines, tabs or an empty string to remove it? Can it be done via the .split()? I want to avoid things like this:
>>> a = 'a;b;'
>>> a.split(';')
['a', 'b', '']

Or this (this is a bad example, but you get the idea):
>>> a = '''a;b;\n'''
>>> a.split(';')
['a', 'b', '\n']

Thanks!
EDIT: I'm open to other approaches as well, basically separating the string into all the individual queries.


text:
Q: How do I get how many days straight user login in MySQL? How do I get how many days user straight login in one month or years?
Here is an example:
user_id   | login
1         | 2017-05-01
2         | 2017-05-01
1         | 2017-05-03
1         | 2017-05-04
1         | 2017-05-05

I want get many days for user_id 1 is 3 days straight login with a MySQL query.

A: You need to SELECT all the rows in descending order of login, store previous date and user id into temp variables and compare the date difference for each row, e.g.:
SELECT user_id, login,
IF(@previousid = user_id AND DATEDIFF(@previouslogin, login) = 1, @count:= @Count + 1, @count:=1) as `count`,
@previousid := user_id, @previouslogin := login
FROM logins, (SELECT @previousid := null, @count := 1, @previouslogin := null) a
ORDER BY login desc;

Once done, you can wrap this query into another SELECT use GROUP BY with MAX aggregate function to get the max number of days for each user, e.g.:
SELECT user_id, MAX(count) as `count`
FROM (
 SELECT user_id, login,
 IF(@previousid = user_id AND DATEDIFF(@previouslogin, login) = 1, @count:= @Count + 1, @count:=1) as `count`,
 @previousid := user_id, @previouslogin := login
 FROM logins, (SELECT @previousid := null, @count := 1, @previouslogin := null) a
 ORDER BY login desc) a
 GROUP BY user_id;

Here's the SQL Fiddle.


text:
Q: How to submit my first program to SPOJ platform? Why I am getting time limit exceeded or runtime error NZEC? My problem is given as CODESPTB ON SPOJ.
My program is working correctly on my IDE NetBeans but when I am submitting this program on SPOJ it is not submitting correctly.
It is saying time limit exceeded or sometimes it is saying Runtime Error NZEC.
         public class Main {
         public static void main(String[] args) throws java.lang.Exception {
         java.util.Scanner s=new java.util.Scanner(System.in);
        //System.out.println(s.hasNext());
        //if(s.hasNext()){
        int firstLine=s.nextInt();
        int[][] finalArray=new int[firstLine][];
        for(int i=0;i<firstLine;i++){
        /* if(s.hasNextInt()){*/  int secondLine= s.nextInt();
           int[] thirdLineArray=new int[secondLine];

           for(int j=0;j<secondLine;j++){
               thirdLineArray[j]=s.nextInt();
           }
           finalArray[i]=thirdLineArray;

        }
        //}
        PassingMultiDimArray(finalArray);
//       for(int[] x:finalArray){
//           System.out.println();
//           for(int y:x){
//               System.out.print(y+" ");
//           }
//       }
        //}

    }

    private static void PassingMultiDimArray(int[][] finalArray) {
    for(int i=0;i<finalArray.length;i++){
        countSwapInsertSort(finalArray[i]);
    }
    }

    private static void countSwapInsertSort(int[] a) {
    //    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
   // int a[]={14,44,37,20,43,20,33,55};
    int swap=0;
    for(int i=1;i<a.length;i++){
    for(int j=i;j>0;j--){
        if(a[j]<a[j-1]){
            int temp=a[j];
            a[j]=a[j-1];
            a[j-1]=temp;
            swap++;
        }
        else break;
    }
}

     //System.out.println(Arrays.toString(a));
     System.out.println(swap);

    }

}

Please tell my mistake, how to submit this problem on SPOJ corectly?

A: for(int i=1;i<a.length;i++){
for(int j=i;j>0;j--){
    if(a[j]<a[j-1]){
        int temp=a[j];
        a[j]=a[j-1];
        a[j-1]=temp;
        swap++;
    }
    else break;
}

High time complexity O(n2)


text:
Q: Best pattern to solve problem where objects only differ in one attribute As I am maintaining and extend a software system in Java, I saw a colleague (who left due to retirement) implementing a table with a generic approach. This approach is unluckily bound to tables (ui-elements) with a key-value appearance.
For example:
Description   | Value |
--------------|-------|
1             |     1 |
2             |     2 |
3             |     3 |

Means, the description (key of an enum) is bound to a value (stored in the enum).
There are multiple (ui-elements) tables, where this approach fits the requirement in an optimal way. Values and description are (as said) stored in enums and read for creating the table (ui-element).
Now, I have to face the situation, that there should be more than one column (of an ui-element table) with values. For example:
Description   | Value1 | Value2  |
--------------|--------|---------|------
1             |      1 |       1 |...
2             |      2 |       1 |...
3             |      3 |       1 |...

For the columns (of an ui-element table) applies that they are all similar. The only difference they have is there is an underlying SQL (or an sql string inside the enum) , where for each value for the specific column in the specific row is requested.
So let's say our table (ui-element) defines due to the row a specific animal and due to the column a specific location.  In the specific cell, there is the amount of animals in the zoo for the given animal and location.
For example (database sight)
--Value1 1
SELECT * FROM ZOO WHERE [...] AND **LOCATION = 'CA'**

--Value2 1
SELECT * FROM ZOO WHERE [...] AND **LOCATION = 'UA'**

Data:
Description| CA | UA  |...
-----------|----|-----|-----
Turtle     |.3..|  9  |...
Lions      |.6..|  1  |...
Horse      |4.. |  0  |...

This value (for location or the row) is/was constant in the enum and seems to be the breakpoint, breaking this hard-wired construct.
One approach would be to create the same objects in the enum again with passing the location as additional parameter. This way would result in having:
Enum Values(
 - Value1 1_CA
 - Value2 1_UA
)

Which seems to create a big overhead, since the objects only differ in location, but all other parameters are the same.
Another way I thought of was refactoring the enum to an abstract class and derive from it, so that I have the base values and only objects/class like following

*

*CA extends BaseClass

*UA extends BaseClass

However this seems not like a clean approach, more like an "make it any case works" approach. Inheritance would be used in the way it shouldn't be, so I thought of delegation. But for delegation, the BaseClass must be instantiable (which is incorrect too).
How could this problem be solved without breaking the concept of clean OOP?
PS: Has i have slept now one night above this problem, I think i'll use the enum as parameterclass, passing to a separate class (and thus it's constructor) to create the elements in a generic way (by giving the additonal parameter for each row (location)). Because the order is constant, i think this approach will help by solving it this way. If this is the way I can solve it, I will write it as separate problem solution in the comments.

A:
How could this problem be solved without breaking the concept of clean OOP?

This is not an OOP problem. This is a data structure problem.
I know this because there is no behavior associated with this data. If there was we could design objects that would locate that behavior, as methods, with the data. Instead what I see is a desire to have a data structure that can be used to look up these values.
That's what collections are for.
I see two dimensions. If you need to be able to look up individual values by keys into those dimensions then hash tables work fine.
_____|CA|UA|_____
Turtle |.3..| 9 |...
Lions |.6..| 1 |...
Horse |4..| 0 |...
Hash<String, Hash<String, Integer>> zoo = new HashMap<>();

Hash<String, Integer> turtle = new HashMap<>();
turtle.put("CA", 3);
turtle.put("UA", 9);
zoo.put("Turtle", turtle)

Hash<String, Integer> lions = new HashMap<>();
lions.put("CA", 6);
lions.put("UA", 1);
zoo.put("Lions", lions)

Hash<String, Integer> horse = new HashMap<>();
horse.put("CA", 4);
horse.put("UA", 0);
zoo.put("Horse", horse)

log(zoo.get("Horse").get("UA"));

Done this way new zoo locations can be added with ease as well as new animals. If you want type safety you can use enums as the keys rather than strings. But now the enums have to be edited and recompiled every time something new is added. Done with strings your code could actually discover the locations and the animals dynamically.
You might be wondering what value this data structure has over whatever some database framework might have handed you. It's that this is yours. Defined your way. You can write code against it and completely ignore how the framework decided to do it. Only an adapter has to know how to talk to both. Everything else can just assume things are done your way.


text:
Q: bootstrap 4 responsive form containing a two-column section with image I am using Bootstrap 4.6 in a project. I need to display an image in form where:
The image is in one column, and properties of the image (title, etc.) are in a second column.
I want the displayed form to look something like this:
-----------------------------------------------------
|                          Title   ..............    |
|                          Caption ..............    |
|                                                    |
|   Image                                            |
|                                                    |
|                                                    |
|                                                    |
------------------------------------------------------

This is my HTML markup for my form:

Modal Form

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

        <form class="tagForm" id="tag-form" action="#" method="post" enctype="multipart/form-data">

                      <input type="text" name="photoTitle">Title

                <input type="hidden" id="frm-val" name="frm-val" value="">

                  <input type="radio" name="status">Option1
                  <input type="radio" name="status">Option2

                  Notes:
                  <input id="notes" class="form-control" type="textarea"/>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <input id="form-submit" type="submit" class="btn btn-primary" value="Submit">

        </form>

How do I cleanly (and in a responsive way) display the image in one column, and it's properties alongside the image, in another column alongside the image?

A: Looks like you're just missing a BS "row" class.  Anytime you create a div with a "col" class, you'll want to contain those in a "row" class.  Just change

to

If you want the radio buttons and notes in that right col div too, those will need to be contained in the 2nd "col" div.  But I'm not sure that's your end goal based on the mockup.
More grid examples are available on the BS site for v4.6:
BS v4.6 Grid Layout


text:
Q: How can I pass integer into string for sql query I have written a program that extracts data from an SQL table:
String url = "jdbc:mysql://localhost/petcare";
        String password = "ParkSideRoad161997";
        String username = "root";
        // Step 2: Making connection using
        // Connection type and inbuilt function on
//        Connection con = null;
        PreparedStatement p = null;
        ResultSet rs = null;

        // Try block to catch exception/s
        try {
            Connection con = DriverManager.getConnection(url, username, password);
            // SQL command data stored in String datatype
            String sql = "select * from inbox";
            p = con.prepareStatement(sql);
            rs = p.executeQuery();

            // Printing ID, name, email of customers
            // of the SQL command above
            System.out.println("inboxId");
            int inboxId;

            // Condition check
            while (rs.next()) {

                  inboxId = rs.getInt("InboxId");
//                System.out.println(inboxId);
            }

            String sql2 = "select * from message where inboxId = int";//this is where i need help
            p = con.prepareStatement(sql2);
            rs = p.executeQuery();

            // Printing ID, name, email of customers
            // of the SQL command above
            System.out.println("Inbox:");

        }

        // Catch block to handle exception
        catch (SQLException e) {

            // Print exception pop-up on screen
            System.out.println(e);
        }

Once I get the inboxId, I want to run sql2 and pass inboxId as int. How can I do this. Each user will have a different inboxId so thats why to get the user inbox I want to extract and messages in the message table that are meant for inboxId of the user.
I tried the query string sql and it works now I just need to fix String sql2.

A: String sql2 = "select * from message where inboxId = " + 1234;
1234 could be a variable. You could also use String.format() to do it as well.
String sql2 = String.format("select * from message where inboxId = %d", 1234);

A: Try this:
  String sql2 = "select * from message where inboxId = ?"; //The ? indicates a variable in the prepared statement.
  p = con.prepareStatement(sql2);
  p.setInt(1, inboxId);
  rs = p.executeQuery();


text:
Q: What's the biggest difference between dir() and __dict__ in Python class C(object):
    def f(self):
        print self.__dict__
        print dir(self)
c = C()
c.f()

output:
{}

['__class__', '__delattr__','f',....]

why there is not a 'f' in self.__dict__

A: The function f belongs to the dictionary of class C.  c.__dict__ yields attributes specific to the instance c.
>>> class C(object):
    def f(self):
        print self.__dict__

>>> c = C()
>>> c.__dict__
{}
>>> c.a = 1
>>> c.__dict__
{'a': 1}

C.__dict__ would yield attributes of class C, including function f.
>>> C.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'C' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None, 'f': <function f at 0x0313C1F0>})

While an object can refer to an attribute of its class (and indeed all the ancestor classes), the class attribute so referred does not become part of the associated dict itself.  Thus while it is legitimate access to function f defined in class C as c.f(), it does not appear as an attribute of c in c.__dict__.
>>> c.a = 1
>>> c.__dict__
{'a': 1}

A: Class dir() and dict only show defined functions (methods).
Instance dir() shows data+methods while its dict only shows
data attributes, not methods.
class C2:
...     def __init__(self, id):
...         self.id = id
...     def set(self, len):
...         self.len = len
...
c2 = C2("stick")
dir(C2)
['__class__',.., '__init__', 'set']
dir(c2)
['__class__',.., '__init__', 'id', 'set']
C2.__dict__
mappingproxy({'__init__': <function C2.__init__ at 0x000001899C61E9D0>, 'set': <function C2.set at 0x000001899C61ED30>,...})
c2.__dict__
{'id': 'stick'}

A: dir() does much more than look up __dict__
First of all, dir() is a API method that knows how to use attributes like __dict__ to look up attributes of an object.
Not all objects have a __dict__ attribute though. For example, if you were to add a __slots__ attribute to your custom class, instances of that class won't have a __dict__ attribute, yet dir() can still list the available attributes on those instances:
>>> class Foo(object):
...     __slots__ = ('bar',)
...     bar = 'spam'
...
>>> Foo().__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__dict__'
>>> dir(Foo())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'bar']

The same applies to many built-in types; lists do not have a __dict__ attribute, but you can still list all the attributes using dir():
>>> [].__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__dict__'
>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

What dir() does with instances
Python instances have their own __dict__, but so does their class:
>>> class Foo(object):
...     bar = 'spam'
...
>>> Foo().__dict__
{}
>>> Foo.__dict__.items()
[('__dict__', <attribute '__dict__' of 'Foo' objects>), ('__weakref__', <attribute '__weakref__' of 'Foo' objects>), ('__module__', '__main__'), ('bar', 'spam'), ('__doc__', None)]

The dir() method uses both these __dict__ attributes, and the one on object to create a complete list of available attributes on the instance, the class, and on all ancestors of the class.
When you set attributes on a class, instances see these too:
>>> f = Foo()
>>> f.ham
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'ham'
>>> Foo.ham = 'eggs'
>>> f.ham
'eggs'

because the attribute is added to the class __dict__:
>>> Foo.__dict__['ham']
'eggs'
>>> f.__dict__
{}

Note how the instance __dict__ is left empty. Attribute lookup on Python objects follows the hierarchy of objects from instance to type to parent classes to search for attributes.
Only when you set attributes directly on the instance, will you see the attribute reflected in the __dict__ of the instance, while the class __dict__ is left unchanged:
>>> f.stack = 'overflow'
>>> f.__dict__
{'stack': 'overflow'}
>>> 'stack' in Foo.__dict__
False

TLDR; or the summary
dir() doesn't just look up an object's __dict__ (which sometimes doesn't even exist), it will use the object's heritage (its class or type, and any superclasses, or parents, of that class or type) to give you a complete picture of all available attributes.
An instance __dict__ is just the 'local' set of attributes on that instance, and does not contain every attribute available on the instance. Instead, you need to look at the class and the class's inheritance tree too.


text:
Q: Is there any way to get base type stored in a variable or member pointer? Consider the following code
#include <type_traits>
#include <iostream>

class A {};

class B : public A {};

class C : public A {};

void parseType(A* base)
{
   std::cout << typeid(std::remove_pointer<decltype(base)>::type).name() << "\n";
}

int main(int argc, char** argv)
{
    A* a = new B;

    A* b = new C;

    parseType(a); // outputs A

    parseType(b); // outputs A

    return 0;
}

there's any way to get the type stored in base parameter from function parseType()? literally always the type it's the base type.

A: Yes.  Just dereference the pointer and apply the typeid:
void parseType(A* base)
{
    std::cout << typeid(*base).name() << "\n";
}

The reason is that typeid will evaluate the operand at runtime if its operand is a glvalue expression of polymorphic type.  In your original example, decltype is a compile time operation and extracts the static type of base, so it's always A.
Note that this requires A to have at least one virtual member function so that it qualifies as a polymorphic type.  Also, you forgot to #include <typeinfo>.


text:
Q: Как изменить цвет autocomplete в sublime text 3?
Какое свойство отвечает за цвет вот этой менюшки и где оно находится?

A: За цвет бэкграунда всплывающих подсказок в Sublime Text 3 отвечает класс table_row.
Preferences → Browse Paskages → User, создаём файл Default.sublime-theme, если он ещё не создан, и между [] вставляем в него следующий код:
// Бэкграунд всплывающих подсказок
    {
        "class": "table_row",
        "layer1.tint": [255, 228, 225, 255],
        "layer1.opacity": 1,
    },
Где layer1.tint — цвет бэкграунда всплывающих подсказок в RGBA, layer1.opacity — прозрачность бэкграунда, свойство принимает значения от 0 до 1.

За текст всплывающих подсказок отвечает класс auto_complete_label:
// Текст в автокомплите
    {
        "class": "auto_complete_label",
        "fg": [72, 72, 72, 255],
        "match_fg": [0, 0, 0, 255],
        "selected_fg": [250, 128, 114, 255],
        "selected_match_fg": [220, 20, 60, 255]
    },

*

*fg — цвет текста невыделенных вариантов автокомплита,

*match_fg — цвет уже набранного текста в невыделенных вариантах,

*selected_fg — цвет текста выделенных вариантов автокомплита (когда появляются варианты автозаполнения, их можно выбирать стрелками вверх/вниз),

*selected_match_fg — цвет уже набранного текста в выделенных вариантах.


text:
Q: Resolve URL injection I have a site where Google Security Issues say "URL Injection"
It added gibberish code at the end like:
index.php/tmo7kx9vo-5399_n0m43kqjv-4143-umoyzxfgs_cwbl_0exy6kre

I'm not sure how to resolve it as the index.php page doesn't contain a form of any type and checking and rechecking the code, I didn't find any malicious code.
Any type of help is appreciated.


text:
Q: Paint a single cell (or a single row) in a JTable without the renderer I have a JTable and i want a cell (or its row) painted in red when the value entered is higher than a certain value. I'm checking that into a TableModelListener to detect TableChange, so I see no way of colouring the table at the renderer (yet I'm sure it is possible, only it is unknown for me).
I also saw this question but i don't know how to use it.

A: that job for prepareRendered as you can see here

A: Following is for single table cell you can extend it for row:
First take table column you want to pint and then add a TableCellRenderer to it as follows:
    TableColumnModel columnModel = myTable.getColumnModel();
    TableColumn column = columnModel.getColumn(5); // Give column index here
    column.setCellRenderer(new MyTableCellRenderer());

Make MyTableCellRendere class which implements TableCellRenderer and extends JLabel(so that we can give a background color to it). It will look something like following:
public class MyTableCellRenderer extends JLabel implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
            int col) {
        JLabel jLabel = (JLabel) value;
        setBackground(jLabel.getBackground());
        setForeground(UIConstants.black);
        setText(jLabel.getText());
        return this;
    }
}

Now in method where you are listening table cell value change do something like follow:
JLabel label = new JLabel(changedValue);
// check for some condition
label.setBackground(Color.red); // set color based on some condition
myTable.setValueAt(label, 0, 5); // here 0 is rowNumber and 5 is colIndex that should be same used to get tableColumn before.


text:
Q: MS Project 2010 Filter and Highlights I'd like to know if there is a way to highlight dates that differs from one another.
I have two columns "Baseline Finish Date" and "Re-forecast Finish Date" and I would like to highlight the dates that for each task, is different in those columns.
Meaning the tasks that suffered a re-forecast due to other circumstances, and does not equal to the original dates.
I also would like a filter that does the same thing as above, showing only this different date tasks.

A: I just use a number field with a formula inside that shows the difference between Baseline and the Finish date. If it shows anything other than zero, you're off. Seems to work great.


text:
Q: Xcode Organizer - The service is invalid I'm using XCode 4.3 (on Lion) and my iPod touch 2nd generation does show up, but displays "The service is invalid" (0xE8000022). I've tried every possible combination of restarting/reconnecting the device and have even restored the OS on the device... any ideas on how to further figure this out?

A: EDIT - initially I suggested restarting the device but I realized you had already done this.
I think this answer might be valid:
Error : The service is invalid


text:
Q: Sharing button works perfectly on iPhone but crash on iPad I'm trying to add a button in order to share some sentences in Twitter, Facebook... etc. It all works on all iPhone models but simulator crash with an iPad.
This is my code:
@IBAction func shareButton(sender: AnyObject) {
    frase = labelFrases.text!
    autor = labelAutores.text!

    var myShare = "\(frase) - \(autor)"

    let activityVC: UIActivityViewController = UIActivityViewController(activityItems: [myShare], applicationActivities: nil)

    self.presentViewController(activityVC, animated: true, completion: nil)

And this is the error:

Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController (<_UIAlertControllerActionSheetRegularPresentationController: 0x7c0f9190>) should have a non-nil sourceView or barButtonItem set before the presentation occurs

How should I solve it?

A: For ipad (iOS > 8.0) you need to set popoverPresentationController:
//check ipad
if (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
{
    //ios > 8.0
    if ( activityVC.respondsToSelector(Selector("popoverPresentationController"))){
        activityVC.popoverPresentationController?.sourceView = super.view
    }
}

self.presentViewController(activityVC, animated: true, completion: nil)

More information here:
UIActivityViewController crashing on iOS 8 iPads

A: Do this instead for Swift 5 to get share button working on both iPad and iPhone:
@IBAction func shareButton(sender: UIButton) { {
    let itemToShare = ["Some Text goes here"]
    let avc = UIActivityViewController(activityItems: itemToShare, applicationActivities: nil)

    //Apps to be excluded sharing to
    avc.excludedActivityTypes = [
        UIActivityType.print,
        UIActivityType.addToReadingList
    ]
    // Check if user is on iPad and present popover
    if UIDevice.current.userInterfaceIdiom == .pad {
        if avc.responds(to: #selector(getter: UIViewController.popoverPresentationController)) {
            avc.popoverPresentationController?.barButtonItem = sender
        }
    }
    // Present share activityView on regular iPhone
    self.present(avc, animated: true, completion: nil)
}

Hope this helps!

A: Slightly adapted version to make it work on any button, iPad and iPhone.
Xcode 13.4.1 (Swift 5.6)
    let itemToShare = ["Some Text goes here"]
    let avc = UIActivityViewController(activityItems: itemToShare, applicationActivities: nil)

    //Apps to be excluded sharing to
    avc.excludedActivityTypes = [
        UIActivity.ActivityType.print,
        UIActivity.ActivityType.addToReadingList
    ]
    // Check if user is on iPad and present popover
    if UIDevice.current.userInterfaceIdiom == .pad {
        if avc.responds(to: #selector(getter: UIViewController.popoverPresentationController)) {
            avc.popoverPresentationController?.sourceView = sender as? UIView
        }
    }
    // Present share activityView on regular iPhone
    self.present(avc, animated: true, completion: nil)


text:
Q: Renderer YUV frames in openGLES without CADisplayLink On my iOS app, I'm using AVAssetReader to decode a local MP4 file and openGLES to renderer each YUV420 frames. I'm using the presentation timestamp to drive the playback at the proper frame rate. What it's not clear to me is if I should use CADisplayLink callback to know when a frame should be displayed (always observing the PTS) or if it's okay to don't use it and have instead a secondary thread that simply pulls the decoded images and renders them via openGLES. I have experimented both solutions and both seem to work (at least to my eyes). Also the time it takes to display a YUV frame in both case seems to be about the same ~2-3ms. So what is the deal with CADisplayLink? it seems not to be necessary but it's recommended...I don't understand. Can some one explain to me?

A: CADisplayLink synchronizes OpenGL drawing with display refresh to help avoid screen tearing.  It's not required, but is recommended since it's possible with NSTimer you may experience screen tearing.  Ultimately the PTS is never really going to be the precise time the user's eyeball sees the image, but certainly it would be better to have a little bit of incongruity with the display time than potentially having two different frames on the screen at once.


text:
Q: change captcha design in Fast Secure Contact Form plugin I am using  Fast Secure Contact Form plugin to create contact form widget.It working fine . Now i like to change captcha appearance.
Original captcha generated by plugin

But, I need to change it design like below

Any option available or any other ways to do this !
Thanks in advance

A: First, you should know that a image like that is very easy to read by almost any OCR. The first one is much more hard to crack.
Anyway, if you don't want to hack the existing plugin, you can use Really Simple Captcha, it looks exactly like that.
In your form:
<?php
 $captcha_instance = new ReallySimpleCaptcha();
 $prefix = mt_rand();
 $word = $captcha_instance->generate_random_word();
 $image = $captcha_instance->generate_image($prefix, $word);
?>

<input type="text" name="captcha" id="captcha" value="" />
<input type="hidden" name="captcha-id" value="<?php echo $prefix; ?>" />
<img src="<?php echo $image; ?>" width="72" height="24" />

after your form is submitted:
$captcha_instance = new ReallySimpleCaptcha();
if(!$captcha_instance->check($_POST['captcha_id'], $_POST['captcha'])) die('wrong captcha!');

// captcha ok, remove the image
$captcha_instance->remove($captcha_id);

A: I recently added reCAPTCHA feature to the forms:
By default, the original Secure Image CAPTCHA is enabled, but you can enable Google reCAPTCHA if you want. Just go to the form edit page Security tab - CAPTCHA Settings. Check the setting "Enable reCAPTCHA", enter your Google reCAPTCHA keys for the site. Included is a link to get new free keys.


text:
Q: Django Admin Choicefield Error I'm trying to set the Gender for my Users in Admin but get the Error

Value u"[u'm']" is not a valid choice.

admin.py
class PlayerForm(forms.ModelForm):
    GENDER_CHOICES = (
        ('m', 'Male'),
        ('f', 'Female'),
    )
...
gender = forms.MultipleChoiceField(label="Gender", choices=GENDER_CHOICES)
...

class Meta:
    model = Player

class PlayerAdmin(admin.ModelAdmin):
    form = PlayerForm

admin.site.register(Player, PlayerAdmin)

models.py (Player Model)
class Player(AbstractBaseUser):
    GENDER_CHOICES = (
        ('m', 'Male'),
        ('f', 'Female'),
    )
    ...
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    ...

Fun fact: The form does display the correct default value from dadabase in admin.
POST Payload when trying to submit the Form:
------WebKitFormBoundary009tVyo4cRJvIAnC
Content-Disposition: form-data; name="gender"

m

Edit: Forgot to mention that the DB is Postgres 8.4 and the column in question is a
VARCHAR(1)

A: Since you are using MultipleChoiceField:
gender = forms.MultipleChoiceField(label="Gender", choices=GENDER_CHOICES)

It's going to save gender to a "list".  Resulting in:
>>> gender = ['m']

You need to use ChoiceField which is used to select a single thing:
gender = forms.ChoiceField(label="Gender", choices=GENDER_CHOICES)

Resulting in:
>>> gender = 'm'


text:
Q: Why were these common operations on collections renamed in Julia? Many common operations on collections in Julia such as deleting an item from a Set were renamed recently, with the old functions deprecated.
For example,
del(IntSet(1,2,3), 1)

now pops up a warning
WARNING: del is deprecated, use delete! instead.

Some of the renamed functions:
@deprecate  push        push!
@deprecate  pop         pop!
@deprecate  grow        grow!
@deprecate  enqueue     unshift!
@deprecate  unshift     unshift!
@deprecate  shift       shift!
@deprecate  insert      insert!
@deprecate  del         delete!
@deprecate  del_all     empty!

Why were these renamed? Is appending a ! to functions that change the state of a collection now a convention?

A: You can read the julia-dev thread here.  Basically, it's simply changing to respect the rule described in the  arrays documentation:

The last function, fill!, is different in that it modifies an existing
  array instead of constructing a new one. As a convention, functions
  with this property have names ending with an exclamation point. These
  functions are sometimes called "mutating" functions, or "in-place"
  functions.

FWIW I think this is a good idea, at least for Base.

A: The use of ! was always an explicit convention to indicate mutation, it was just not properly enforced until recently. For push, one could easily argue that it's not essential. But using push! instead of push makes it clear that mutation is happening in this case in precisely the same way that mutation would happen when using sort!, which is very different from sort.
This exclamation-mark convention exists in Scheme and Ruby and probably several other languages. It doesn't exist in a language like R which wouldn't allow one to perform the mutation without recourse to the underlying guts of the language.


text:
Q: MUI pagation 'rows per page' text becomes broken when I import bootstrap css So like the title says, when I import bootstrap CSS in my react project for some reason MUI table pagation text becomes broken, see image below:
https://imgur.com/a/pLxu8EO
does anyone have a solution for this issue? I am sure it's bootstrap since I tried commenting the import statment and the issue was fixed.


text:
Q: caused by com.mysql.jdbc.exceptions.jdbc4.mysqlsyntaxerrorexception unknown column I use springboot + mybatis and run with the SpringJUnit4ClassRunner, use the default database h2, and the scripts:
create table sql:
create TABLE IF NOT EXISTS `test_company` (
  `id`          bigint   unsigned  not null auto_increment,
  `pid`         bigint   DEFAULT null COMMENT '',
  `outer_id`    bigint DEFAULT null COMMENT '',
  `name`        VARCHAR(256) DEFAULT NULL COMMENT '',
  `parent_company_name` VARCHAR(256) DEFAULT NULL COMMENT '',
  `user_id` bigint DEFAULT NULL COMMENT '用户ID',
  `user_name` VARCHAR(64) DEFAULT NULL COMMENT '',
  `type`        INTEGER DEFAULT null COMMENT '',
  `level`       INTEGER DEFAULT null COMMENT '',
  `status`      INTEGER DEFAULT null COMMENT ''
);

the model Company:
@Data
@NoArgsConstructor
public class Company implements Serializable {

    private static final long serialVersionUID = -5822686079080905768L;
    private Long id;    private Long pid;
    private Long outerId;
    private String name;
    private String parentCompanyName;
    private Long userId;
    private String userName;
    private Integer type;
    private Integer level;
    private Integer status;
}

the resultMap of mapper:
<resultMap id="CompanyMap" type="Company">
    <id column="id" property="id"/>
    <result column="pid" property="pid"/>
    <result column="outer_id" property="outerId"/>
    <result column="name" property="name"/>
    <result column="parent_company_name" property="parentCompanyName"/>
    <result column="user_id" property="userId"/>
    <result column="user_name" property="userName"/>
    <result column="type" property="type"/>
    <result column="level" property="level"/>
    <result column="status" property="status"/>
</result>

some sqls:
<sql id="tb">
    test_company
</sql>

<sql id="cols_all">
    id, <include refid="cols_exclude_id" />
</sql>

<sql id="cols_exclude_id">
    pid, outer_id, `name`, `parent_company_name`, user_id, user_name, `type`, `level`, status
</sql>

<sql id="vals">
    #{pid}, #{outerId}, #{name}, #{parentCompanyName}, #{userId}, #{userName}, #{type}, #{level}, #{status}
</sql>

create sql:
<insert id="create" parameterType="Company" keyProperty="id" useGeneratedKeys="true">
    INSERT INTO
    <include refid="tb" />
    (<include refid="cols_exclude_id" />)
    VALUES
    (<include refid="vals" />)
</insert>

it runs well before there is not the column parent_company_name,
but when I added the column parent_company_name and rerun the DAO method with create it had this error
    org.springframework.jdbc.BadSqlGrammarException:
### Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'parent_company_name' in 'field list'
### The error may involve Company.create-Inline
### The error occurred while setting parameters

my IDE was IntelliJ IDEA, I don't know if it caused by the cache or something else, I just added a new column and checked all sql scripts was correct.

A: From what I understand you are using spring boot and writing migration scripts and I am assuming this is flyway or some other migration tool. One thing to note is that once a migration script runs it won't re-run if you did not configure it to do validation on migrate or any other configuration the migration might be using.
So you should check your database to see if the column was actually created. If it wasn't then you will have to write a second migration script to alter the existing table instead of inserting the parent_company_name column to the initial script. thus your version 2 migration will have:
ALTER TABLE `test_company` ADD COLUMN `parent_company_name` VARCHAR(256) DEFAULT NULL COMMENT '';

Alternatively if you are using flyway and you are still in development mode, you can do a validate on migrate and set clean on validation error to true so that it cleans the database and re runs your migration script.


text:
Q: UIViewController subclass not receiving touchesBegan iphone ipad So I subclassed UIViewController and in the nib I have a UIView, and in it a tableview. It is my understanding that both UIViewController and UIView are subclasses of UIResponder, so they should receive the - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
method.
However, this is not the case, and my view controller subclass is not receiving that method. I'd really like to not subclass the UIView, if that's allright.
I am trying to implement this, but my
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [textfield resignFirstResponder];
}

Is not getting called.

A: It depends on where you touch.  If you touch in the table view the touches are sent to the tableview, not the view controller.  If you touch in a textfield that is in your view, the touches are sent to the UITextField itself.  If you touch outside the tableview, outside the textfield but in the viewcontrollers' view then the view controller should get those touches.

A: If you change your VC's view to a UIControl (UIControl is the superclass of a UIView) in IB, you can assign it an IBAction.  You can have your textfield resignFirstResponder in that action.

A: Unfortunately, touchesBegan only takes place in the view, despite UIViewController being a subclass of UIReponder.  The docs for touchesBegan say this.

Tells the receiver when one or more fingers touch down in a view or window.

A: Is the UIView you are talking about is one you have created, or are you using the one furnished with the UIViewController ?
Further more, if the click happen on the UITableView, you will have to subclass this to let your UIViewController know that a click occurred on the tableview...


text:
Q: How to clear width when outputting from a stream, after using std::setw? I'm using a std::stringstream to parse a fixed format string into values.  However the last value to be parsed is not fixed length.
To parse such a string I might do:
std::stringstream ss("123ABCDEF1And then the rest of the string");
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag
   >> sLeftovers;

But how do I set the width such that the remainder of the string is output?
Through trial and error I found that doing this works:
   >> std::setw(-1) >> sLeftovers;

But what's the correct approach?

A: Remember that the input operator >> stops reading at whitespace.
Use e.g. std::getline to get the remainder of the string:
std::stringstream ss("123ABCDEF1And then the rest of the string");
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag;
std::getline(ss, sLeftovers);

A: std::setw only affects exactly one operation, i.e. >> bFlag will reset it to default, so you don't need to do anything to reset it.
i.e. your code should just work
std::stringstream ss("123ABCDEF1And then the rest of the string");
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag
   >> sLeftovers;

A: Try this:
std::stringstream ss("123ABCDEF1And then the rest of the string");
std::stringstream::streamsize initial = ss.width(); // backup
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag
   >> sLeftovers;

ss.width(initial); // restore

A: I'm surprised that setw(-1) actually works for you because I haven't seen this documented, and when I tried your code on VC10, I only got "And" for sLeftovers. I'd probably use std::getline( ss, sLeftovers ) for the remainder of the string, which worked for me in VC10.


text:
Q: PHP tools for realtime execution analysis? For those of you who have ever used Microsoft Excel in a manner that required some very complicated formulas, you have probably noticed that there is a function where you can 'step in' to the formula to see in real time what data is being calculated by each function, the true value of a cell, etc. and so on.
I'm a SAP consultant by day, coder by night, and running the debug mode in SAP is very powerful. It let's you set breakpoints, see variables being populated in realtime as you step through loops, function calls, etc. in the code, and it is extremely useful for development analysis.
Are there any tools in the PHP world that would allow someone to do this kind of realtime analysis of the code execution?

A: I suggest you try Eclipse (download):

A: Take a look at XDebug, a PHP extension.


text:
Q: First mass ceremony by a new priest What is the name for the first mass ceremony conducted by a new priest?
For example, in the catholic church, a priest for the first time transforms bread and wine into Eucharistia. After this mass, there is a celebration, feasting, people in the church welcoming the new priest.

A: Informally, this strikes me as an "inaugural mass".
However, you may infer from my last name that I may be less than qualified to opine in this area.


text:
Q: Read value in Excel in Java, problems Windows vs Linux I have app with Java in Springboot, I read the value numeric from cell 3123456,89, We are using in Excel the format the money European -> . Thousand and ,  decimals.
String stringValue = new DataFormatter().formatCellValue(cell);

I read the cell as a String.
Then I parse this String to Double ->
Double.parseDouble(stringValue .replaceAll("\\.", "").replaceAll(",", "."));

I need this parse because We are insert numerics in format European but Java is format American ( , Thousand and . decimals)
This process IS CORRECT WITH WINDOWS.
Now I upload my app a Linux, I have any problems...
Now I get this value -> 3,123,456,89 , If I use replace -> "Error multiple points" If i wish replace , I lose part decimal...
I use apache.poi for read the Excels.
  <!-- EXCELS -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.15</version>
    </dependency>

Finally In linux I have problems with this code, that, in windows is correct. thanks.

A: Seems your problem results from the fact, that in your Linux system Java uses a different default Locale than in your Windows system.
You can construct the DataFormatter having a special Locale. If that is Locale.US, then the whole replacement will not be necessary as the stringValue will be formatted for that Locale.US. Then you can use java.text.NumberFormat of the same locale to get the Number out of the string.
...
DataFormatter dataFormatter = new DataFormatter(java.util.Locale.US);
java.text.NumberFormat numberFormat = java.text.NumberFormat.getInstance(java.util.Locale.US);
String stringValue = dataFormatter.formatCellValue(cell);
Double doubleValue = null;
try {
 doubleValue = numberFormat.parse(stringValue).doubleValue();
} catch (Exception ex) {
 //do nothing
}
...

Another approach is getting the cell value as numeric value instead of as formatted string.
For apache poi 3.15 this would be like:
...
if (cell.getCellTypeEnum() == CellType.NUMERIC) {
 Double doubleValue = cell.getNumericCellValue();
}
...

See also https://poi.apache.org/components/spreadsheet/quick-guide.html#CellContents.


text:
Q: Backbone.js validation broken (0.9.9 vs. 0.9.10) Backbone changed a few things about validation between these versions, first off, you now have to explicitly pass {validation: true} with a set call for validation to trigger. There must have been another change too, because this doesn't work no longer.
model.set(obj, {
    error : function(model, error){
        //Do stuff with error
    }
})

I found this ticket on backbone's github, but it only answers the issue if using save, not set.
https://github.com/jashkenas/backbone/issues/2153

A: Here's the solution I've discovered.
1) Assign the set to a variable called success (or whatever you like)
var success = model.set(obj, {validate : true});

2) Check the status of success, and then use model.validationError
if(!success){
    var error = model.validationError;
    // Do stuff with error
}


text:
Q: Text align in table [bootstrap] Is there a set of classes in Twitters Bootstrap Framework that aligns text?
E.g. I have some tables with $ totals that I want aligned to the right...
Total

and
$1,000,000.00

A: You can use class="text-right"
More reference https://getbootstrap.com/docs/4.0/utilities/text/


text:
Q: take space after comma in math mode I have searched hard for the answer to this question but have not been able to find it. I'm typing an article and I have to write a lot of formulas, and for me it's more beautiful write
f(x, y) than f(x,y). I'm tired of always writing a thin space \, after a comma in mathmode, and it's also confusing. Is there a way to automate this?

A: , is \mathpunct so has  a thin space by default unless you have changed the settings. Compare with {,}

\documentclass{article}

\begin{document}

$f(x, y)$

$f(x{,} y)$

\end{document}

A: You may also define your own command with the space you want:
\documentclass{article}

\newcommand{\fxy}{$f(x,\,y)$}

\begin{document}
    \fxy, compared to

    $f(x,y)$

\end{document}

A: If you're willing to have more space after every comma in math mode.
\documentclass{article}

\AtBeginDocument{%
  \mathchardef\stdcomma=\mathcode`,
  \mathcode`,="8000
}
\begingroup\lccode`~=`, \lowercase{\endgroup\def~}{\stdcomma\,}

\begin{document}

$f(x,y)$

$a,b,c$

\end{document}

If you only want the space when specifying variables, you can use the same method as the package icomma, but this requires discipline in input: if a comma is followed by a space (in math mode), a thin space is added.
\documentclass{article}

\makeatletter
\AtBeginDocument{%
  \mathchardef\stdcomma=\mathcode`,
  \mathcode`,="8000
}
\begingroup\lccode`~=`, \lowercase{\endgroup\def~}{%
  \futurelet\@let@token\spaced@comma
}
\newcommand{\spaced@comma}{%
  \stdcomma
  \ifx\@let@token\@sptoken\,\fi
}
\makeatother

\begin{document}

$f(x, y)$ % added space

$f(x,y)$ % compare with the standard

$a,b,c$ % no space is added

\end{document}

I'd avoid setting \thinmuskip to a larger value. Here's why.
\documentclass{article}

\thinmuskip=6mu

\begin{document}

$f(x,y)=\sin x-\sin y$ % with the new setting

\thinmuskip=3mu

$f(x,y)=\sin x-\sin y$ % with the standard setting

\end{document}

As you see, \thinmuskip is not only used after commas, but in several other places, which would be affected by the same enlarged space.


text:
Q: Try and Catch on TSQL - catch not catching I have a stored procedure that seems not to be logging its errors correctly.
The code is erroring, but the catch block doesn't seem to be coming into effect.
The try block is fairly long - but the erroring section is simple and comes rightat the end, so I've precis'd that.
BEGIN TRY
insert into tbl_X
select * from #temp_tbl_Y

RETURN 1
END TRY

BEGIN CATCH
    Insert Into ExtractsErrorLog
    SELECT
    getdate() as ErrorDate
    ,object_name(@@procid) as ProcedureName
    ,ERROR_NUMBER() as ErrorNumber
    ,ERROR_LINE() as ErrorLine
    ,ERROR_MESSAGE() as ErrorMessage
    ;
DECLARE @errormessage as varchar(max);
DECLARE @errorseverity as int;
DECLARE @errorstate as int;

set @errormessage = ERROR_MESSAGE();
set @errorseverity = ERROR_SEVERITY();
set @errorstate = ERROR_STATE();

 RAISERROR (@errormessage,
            @errorseverity,
            @errorstate
               );

END CATCH;

The error the proc is failing on is our old friend
"Column name or number of supplied values does not match table definition."
I've fixed that error - It was a dumb lazy mistake - but  I'm baffled why my error logging process didn't seem to be working - no row is being  inserted into my ExtractsErrorLog table.

A: TSQL's TRY...CATCH does not catch that error.  This error falls into the "compilation/recompilation" type errors that are not handled by the CATCH block "within the same level of execution".
From MSDN:

The following types of errors are not handled by a CATCH block when
  they occur at the same level of execution as the TRY…CATCH construct:

*

*Compile errors, such as syntax errors, that prevent a batch from
  running.

*Errors that occur during statement-level recompilation, such
  as object name resolution errors that occur after compilation because
  of deferred name resolution

...

You can use TRY…CATCH to handle errors that occur during compilation
  or statement-level recompilation by executing the error-generating
  code in a separate batch within the TRY block. For example, you do
  this by placing the code in a stored procedure or by executing a
  dynamic Transact-SQL statement using sp_executesql. This allows
  TRY…CATCH to catch the error at a higher level of execution than the
  error occurrence. For example, the following code shows a stored
  procedure that generates an object name resolution error. The batch
  that contains the TRY…CATCH construct is executing at a higher level
  than the stored procedure; and the error, which occurs at a lower
  level, is caught.

I ran into similar issues with a script creating a transaction inside a TRY...CATCH that would  ROLLBACK the transaction if it failed.  A statement inside the transaction was throwing that same error and caused the transaction to never be closed, as the CATCH was never entered.
As mentioned in the MSDN article, one alternative is to create a stored procedure out of your INSERT statement and then call that inside your try/catch.  If the sproc is wrong, you'll catch the compilation error while trying to create it.  If the table definition later changes to invalidate the sproc, then the TRY...CATCH will catch the exception for you.
If you want it to all live in one script, you can make it a temporary stored procedure, but you will then need to handle the compilation errors while you are creating the sprocs.  It's not pretty, but it will work:
-- Creating error sproc to re-use code
CREATE PROCEDURE #HandleError AS
    Insert Into ExtractsErrorLog
    SELECT  GETDATE() as ErrorDate
            ,object_name(@@procid) as ProcedureName
            ,ERROR_NUMBER() as ErrorNumber
            ,ERROR_LINE() as ErrorLine
            ,ERROR_MESSAGE() as ErrorMessage;

    DECLARE @errormessage as varchar(max);
    DECLARE @errorseverity as int;
    DECLARE @errorstate as int;

    set @errormessage = ERROR_MESSAGE();
    set @errorseverity = ERROR_SEVERITY();
    set @errorstate = ERROR_STATE();

    RAISERROR ( @errormessage,
                @errorseverity,
                @errorstate);
GO

-- Create a stored procedure of our INSERT and catch any compilation errors
CREATE PROCEDURE #TEST AS
    insert into tbl_X
    select * from #temp_tbl_Y
GO
IF (@@ERROR <> 0) BEGIN
    exec #HandleError
    -- If there was an error creating the sprocs, don't continue to the next batch
    RETURN
END

-- If compilation succeeded, then run the sproc
BEGIN TRY
    exec #TEST
    RETURN
END TRY
BEGIN CATCH
    exec #HandleError
END CATCH;

A: I used THROW in my CATCH block before the INSERT statement for my logging - and got the same issue as you. Once I moved THROW after the logging INSERT statement it worked. Looks like THROW might terminate the session.
You don't use THROW in your code example, but thought this might help someone else.

A: It's your RETURN: "Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block."


text:
Q: Disable Copy/Paste into a specific folder - C# I have this C# program:
TestProgram:
        static void Main(string[] args)
                {
                    var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    var directory = Directory.CreateDirectory(Path.Combine(path, "folder"));
                    using (StreamWriter sw = new StreamWriter(Path.Combine(directory.FullName, "example.txt")))
                    {
                        sw.WriteLine("hi");
                    }
                    var directorySecurity = directory.GetAccessControl();
                    var administratorRule = new FileSystemAccessRule("Administrators", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
                    var usersRole = new FileSystemAccessRule("Users", FileSystemRights.Read, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
                    directorySecurity.AddAccessRule(administratorRule);
                    directorySecurity.AddAccessRule(usersRole);
                    directory.SetAccessControl(directorySecurity);
                }

So, I want to create a directory which only Administrators can edit the name and the content.
In order to test this code snippet, I've copied this directory into C: and I've created a usertest which is member of Users group and stop.
This works fine because usertest cannot edit example.txt. But if I (as usertest) create a test.txt file on C:\Users\usertest\Desktop and copy/paste into C:\folder created by the execution of TestProgram.exe, the operation is successful. How can I edit the C# program in order to avoid the copy/paste into folder?
Before you ask, I've already search in StackOverflow but nothing seems to be right for my context.
Thanks
EDIT:
on C: folder, the Users group (usertest is a member of it) has the:

*

*Read and execute

*Read

*List folder content

rights.
So, how can I inhibit the inheritance from C: to folder?

A: If you want to do it using c#, you can call DirectorySecurity.SetAccessRuleProtection() and make the bool preserveInheritance to false.
To stop inheritance in Windows 11:

Windows explorer -> Right click on the folder -> Select the menu option named "Properties" -> Change to the tab named "Security" -> Click the button named "Advanced Settings" -> Hit the button at the bottom named "Disable inheritance".

The Advanced Settings option has a really useful tab named "Effective access" where you can see what can actually do users or groups to that object.


text:
Q: Get signature(YPDrawSignatureView) to display using an unwind segue I'm trying to display a user's signature on another ViewController using an unwind segue. However when I press save (which I set to my Unwind segue) the UIImageView does not display the signature I took. I'm using YPDrawSignatureView to capture the signature and the .getSignature method in it
here's the get signature func (found in my SignatureViewController) :
var signatureimage = UIImage()
func getSignature() {
    signatureimage = self.Signature.getSignature()
}

and here's my unwind segue (found in another ViewController) :
@IBOutlet var signature: UIImageView!
@IBAction func unwindFromSignature(sender: UIStoryboardSegue) {
    if let sourceViewController = sender.sourceViewController as? SignatureView {
        sourceViewController.getSignature()
        signature = UIImageView(image: sourceViewController.signatureimage)
        signature.sizeToFit()
    }
}

as you can probably see, my final outlet is called "signature" and is an UIImageView.

A: You're creating a new image view when you do
signature = UIImageView(image: sourceViewController.signatureImage)

You want to set the image on your already existing image view
signature.image = sourceViewController.signatureImage


text:
Q: Good practice to write to a file In the main function of my program, I call timesRule which is returning a Boolean value. In this function I want to write to a file. However, if I understood correctly the function times rule needs to return IO() if it writes to file.
How should I structure my code to write to a file in a function returning a Boolean value ?
timesRule :: (MultiSet LocalType) -> Bool
timesRule sequent = do
    let result = MultiSet.concatMap (\x -> if isPrl x then [checkTimes x, checkTimes2 x] else [x] ) sequent
    let file = "tmp/log.txt"
    let content = "TIMES rule: " ++  (show(MultiSet.toList result))
    let log = writeToFile file content
    prefixRule result

Used function:
import qualified System.IO.Strict as SIO

writeToFile :: FilePath -> String -> IO()
writeToFile file content = do
    x <- SIO.readFile file
    writeFile file ("\n"++content)
    appendFile file x

A: The somewhat obvious solution would be changing the type your function to IO Bool as @Robin Zigmond pointed out.
There is some problem with your syntax apart from calling writeToFile, though. For your function timesRule to have the given type it would need to look like this:
timesRule :: (MultiSet LocalType) -> Bool
timesRule sequent = -- there is no do here
    let
        result = MultiSet.concatMap (\x -> if isPrl x then [checkTimes x, checkTimes2 x] else [x] ) sequent

        -- the following two lines are superfluous ...
        file = "tmp/log.txt"
        content = "TIMES rule: " ++  (show(MultiSet.toList result))

        -- ... because this still doesn't work
        log = writeToFile file content

        -- ... and what were you going to use `log` for, anyway?
    in
        prefixRule result

Changing your type to IO Bool allows you to use monadic do-syntax. Bool by itself neither has an applicative nor a monad instance and thus there is no meaningful do-syntax. (In order to have either an applicative or a monad instance, you need a type function like Maybe or IO, fyi):
timesRule :: (MultiSet LocalType) -> IO Bool
timesRule sequent = do
    let
        result = MultiSet.concatMap (\x -> if isPrl x then [checkTimes x, checkTimes2 x] else [x] ) sequent

        file = "tmp/log.txt"
        content = "TIMES rule: " ++  (show(MultiSet.toList result))

    -- the syntax to get the value of type `a` out of `IO a` is this:
    log <- writeToFile file content

    -- the function to turn a value of type `a` into `IO a` is `pure`:
    pure (prefixRule result)

You stil don't use log and might as well replace
log <- writeToFile file content
with
writeToFile file content
Given that writeToFile has type ... -> IO (), the () is pronounced "unit", the value of log is () and thus log does not contain any useful information (probably).

The less obvious solution is to refactor your code a bit and seperate the concerns. Sometimes it does make sense to have a function write to a file and return some boolean value. In your case, you probably want a funcion that returns result, i.e. turn this line into a function:
MultiSet.concatMap (\x -> if isPrl x then [checkTimes x, checkTimes2 x] else [x] ) sequent

Then you already have prefixRule that gives you the Bool and you have writeFile. This way you separate pure code (anything that does not have the type IO something) form code with IO-side effects.


text:
Q: How to remove all characters standing before a specific character- Notepad ++ I searched all around but couldn't find any solutions.
Having lot of lines contains special character of "\"
Ex:
Test\Example\Sample\example.aspx
Test1\Example1\Sample\example2.aspx
I want delete all of text before the "\ so the unnecessary text like "Test\Example\Sample\" will be gone, only the name such as filename being kept. How can I do it?

A: try to find this: .*\\ and replace it with nothing


text:
Q: Failed to open raster - ArcGIS 10 SP2, Python 2.6.5, Windows 7 I have an arcpy / python script that is working fine with ArcMap 10 no Service pack (Build 2414) on windows XP, but consistently failing on using ArcMap 10 SP2 (Build 3200). Getting the ESRI 99999 error. In a nutshell, this script is supposed to reclassify and convert four raster files to polygon (shp).
Here is the code. Any help or ideas would be appreciated.
import arcpy, os, string
arcpy.CheckOutExtension("Spatial")
from arcpy.sa import *

#set output location
outLoc = "O:/gis/!KEYHOLE/DAILY_SHP"

#get file date, set data directory
fileDate = arcpy.GetParameterAsText(0)
dataFolder = "O:/gis/PRED_SVC/MET_PROJ/FOR_OBS_LTG_DATA"

#add file date message
arcpy.AddMessage("...using file date " + fileDate + "...")

#set precip amount file based on date input
prefixList = ["erc", "thz", "prpdur_", "prpamt_"]
for prefix in prefixList:
metName = prefix + fileDate
metFile = os.path.join(dataFolder, metName)
print metName
print metFile

#output workspace, turn overwrite output on
arcpy.env.workspace = "c:/tmp"
arcpy.env.overwriteOutput = 1

#reclassify
if prefix == "erc":
    remap = RemapRange([[-99, -1.282, 1], [-1.282, -0.842, 2], [-0.842, -0.524, 3], [-0.524, -0.253, 4], \
             [-0.253, 0, 5], [0, 0.253, 6], [0.253, 0.524, 7], [0.524, 0.842, 8], [0.842, 1.282, 9], \
             [1.282, 1.645, 10], [1.645, 1.881, 11], [1.881, 99, 12]])
    arcpy.AddMessage("...reclassifying ERC...")

elif prefix == "thz":
    remap = RemapRange([[-99, -1.645, 1], [-1.645, -1.282, 2], [-1.282, -0.842, 3], [-0.842, -0.524, 4], \
             [-0.524, -0.253, 5], [-0.253, 0.253, 6], [0.253, 0.524, 7], [0.524, 0.842, 8], \
             [0.842, 1.282, 9], [1.282, 99, 10]])
    arcpy.AddMessage("...reclassifying 1000HR fuels...")

elif prefix == "prpdur_":
    remap = RemapRange([[0, 0.009, 1], [0.009, 1.9999, 2], [1.9999, 4.9999, 3], \
                        [4.9999, 9.9999, 4], [9.9999, 25, 5]])
    arcpy.AddMessage("...reclassifying precipitation duration...")

else:
    remap = RemapRange([[0, 0.0009, 1], [0.0009, 0.09999, 2], [0.09999, 0.249999, 3], \
                        [0.249999, 0.499999, 4], [0.499999, 0.999999, 5], \
                        [0.999999, 1.999999, 6], [1.999999, 1000000, 7]])
    arcpy.AddMessage("...reclassifying precipitation amount...")

rcls = Reclassify(metFile, "Value", remap)

#make raster layer, convert to poly
metLyr = arcpy.MakeRasterLayer_management(rcls, "metLyr")
arcpy.env.workspace = outLoc
arcpy.env.overwriteOutput = 1
outPolyName = string.replace(prefix, "_", "") + "_poly.shp"
outPolyFile = outLoc + os.sep + outPolyName
arcpy.AddMessage("...converting " + metFile + " to poly...")
print outLoc
print outPolyName
print outPolyFile
arcpy.RasterToPolygon_conversion(metLyr, outPolyFile)
del rcls

arcpy.CheckInExtension("Spatial")

A: I don't have an immediate solution to this problem, as it may be a bug, but I would suggest that the first thing you do is upgrade ArcGIS 10 from Service Pack 2, to the latest Service Pack, which is 5.
ArcGIS 10 (Desktop, Engine, Server) Service Pack 5 - English
I am making this suggestion from the outset, as there have been a number of questions posted in the last couple of months that were solved by upgrading to the current version.
Here are the Issues Addressed in Service Pack 3
This fix seems like it may be related to your problem:
NIM067104:  Lookup and Reclassify tools produce incorrect results when using a string field as the lookup/reclass field.
I would still recommend upgrading to SP 5 as it will include this bug fix, along with others.
If you are not able to upgrade to the current Service Pack, that would be useful information to include in your question.


text:
Q: ATG - Build error caused by packages not found I'm trying to build an ATG's project on Eclipse, and it occurs the following errors:
error: package org.apache.axis2 does not exist
error: package org.apache.axiom.om does not exist

Despite of the presence of the above packages inside the project, the build is not recognizing them. What should be the problem?
I also can see their JARs referenced on Project properties' Libraries section. Among other dozens of packages only the above ones can't be found.

A: *

*Any Jar reference used in the workspace should be put in the
Eclipse project build path.

*Path of the jars used should be put
under the ClassPath dependencies property in the MANIFEST.MF files.

*If the above two are not working, then clean the workspace, close
the workspace and try to launch eclipse again. Though this solution
is weird, it works best !!


text:
Q: How to find all irreducible elements in $\mathbb{Z}[\sqrt{2}]$ I am trying to find all irreducible elements in $\mathbb{Z}[\sqrt{2}]$. So, all the elements of the form $(2bd+ac)+(bc+ad)\sqrt{2}$ such that either $(a+b\sqrt{2})$ or $(c+d\sqrt{2})$ is a unit.
I know all the units in this ring
( $U(\mathbb{Z}[\sqrt{2}]) = \{(1+\sqrt{2})^n | n \in \mathbb{N}\}$). So I suppose one thing I can do is just plug in a unit I know (e.g. $(1+\sqrt{2})$ or $(3+2\sqrt{2})$ and just know that any element of the form $(4d+3c+(2c+3d)\sqrt{2})$ where $c,d$ are integers is an irreducible (as long as it is not a unit itself, and of course we would get rid of all the ones that were associates of each other). Seems quite long-winded and inefficient, though.
I'm still not seeing a pattern though for how I can find all the irreducible elements. Can someone help?

A: The intersection of the ideal generated by an irreducible element with $\mathbf Z$ is the ideal generated by a prime $p$. Hence you have to find what happens to primes in the ring of algebraic integers $\mathbf Z[\sqrt2]$.
You have two cases for an odd $p\mkern1mu$:

*

*$p$ is inert if $2$ is a non-quadratic residue mod. $p$. By the second supplementary law of quadratic reciprocity, if $p\equiv \pm 3\mod 8$.

*$p$ is decomposed into the product of two conjugate irreducible elements. This happens if $p\equiv \pm 1\mod 8$.

As to $2$, $\sqrt 2$ is obviously irreducible and we have $2=(\sqrt 2)^2$ (one says $2$ is ramified).
These irreducible elements are unique within a unit factor, so there remains to find the units in this ring. For this,  one know $m+n\sqrt2$ is a unit if and only if $N(m+n\sqrt2)=m^2-2n^2=\pm 1$. So you have solve this Pell-Fermat equation. The general result is that the group of units is infinite, isomorphic to the (additive) group $\;\mathbf Z/2\mathbf Z\times \mathbf Z$.

A: The definition of irreducibility is that if $a=bc$ then either $b$ or $c$ is a unit.
Now going by that, in $\mathbb{Z}[\sqrt{2}]$, an element is irreducible if $a+b\sqrt{2} = (a'+b'\sqrt2)(a''+b''\sqrt2)$ implies either $a'+b'\sqrt2 = 1$ or $a''+b''\sqrt2 =1$


text:
Q: Netbeans error Annotation processor 'org.checkerframework.checker.nullness.NullnessChecker' not found I'm trying to get NonNull annotations working in NetBeans, and it's been one headache after another.
I followed the instructions at https://checkerframework.org/manual/#netbeans and can confirm that checker-qual.jar is added as both a compile and processor library. I've enabled annotation processing and added org.checkerframework.checker.nullness.NullnessChecker as an Annotation Processor.
In the source code I can import import org.checkerframework.checker.nullness.qual.NonNull and have @NonNull annotations compile. However while building I get this:
error: Annotation processor 'org.checkerframework.checker.nullness.NullnessChecker' not found
What do I need to do to resolve this error?

A: The instructions for the NetBeans processor path are incorrect: they first talk about adding checker.jar, but then mention checker-qual.jar https://github.com/typetools/checker-framework/blob/master/docs/manual/external-tools.tex#L904
checker.jar contains the actual annotation processor and should be put on the processor path.
I'll update the instructions.
However, we did not yet find a way to add the annotated JDK jdk8.jar to the bootclasspath that the processor uses. Therefore, none of the JDK annotations that are provided will be visible within NetBeans. We will therefore need to remove support for the Nullness Checker from NetBeans, until we find a proper solution.


text:
Q: Extent report not generated when script abruptly ends I have POM based selenium framework,i am using extent reports and the reports are generated fine if all of the scripts run. If one of the script fails abruptly due to browser disappear then my script is failing and then report is not generated.
Ex: I have 3 scripts to run as part of my driver script, when 3rd script is running if something goes wrong(like browser disappear) then report is not generated. I want extent report generated whenever it fails/stops. My driver script has extent.flush which is the last execution as part of scripts. How can we generate report on failure. If the failure is due to object not found then i am able to get the report.
How to generate report whenever i stop the execution?
Any help is greatly appreciated.
thanks
Raju

A: I'm assuming that you are using TestNG if that is true add the parameter alwaysRun = true  in the TestNG methods e.g.
@BeforeMethod(alwaysRun = true)
public void beforeMethod()
//your_code
}

@AfterMethod(alwaysRun = true)
public void afterMethod() {
 //your_code
}


text:
Q: How do I map through an unnamed array in React? I have an array that looks like this.
[{"id":19,"name":"asd","salary":123},{"id":20,"name":"wer","salary":1}]
But when I try to map through it in React I get an Error
Uncaught TypeError: data.map is not a function
import React, { Component, useState, useEffect } from 'react';

function EmployeeList() {
const [data, setData] = useState({ items : [] });

const getEmployees = () => {
    fetch("http://127.0.0.1:8000/api/employee-list")
    .then((response) => response.json())
    .then((data) => {
        setData(data);
        console.log(data);
    })
};

useEffect(() => {
    getEmployees();
}, [])

return (

            {data.map((employee) =>

{employee.name}

            )}

)
export default EmployeeList;

A: That's because you are not setting data to an array, but an object at first. Use this instead:
const [data, setData] = useState([]);

This assumes that your data comes back from the API as you specified, i.e., as an array. If instead it comes back in the format suggested by your original initial value then you'd need to use:
   {data && data.items && data.items.map((employee) =>


text:
Q: Trying to build a static database class that I can access from any function outside of the class UPDATED: Changed code to the now working class code using PDO instead of deprecated methods
The original question was answered and the problem is solved. Phil brought up using PDO instead of traditional SQL so seeing as this class is in its infancy, I have decided to start the migration process.
class db
{
    private static $connection;
    const __DB__HOST__      = __DB__HOST__;
    const __DB_USERNAME__   = __DB_USERNAME__;
    const __DB_PASSWORD__   = __DB_PASSWORD__;
    const __DB_NAME__       = __DB_NAME__;

    private static function getConnection() {
        if (self::$connection === null) {

            $dsn = sprintf("mysql:dbname=".__DB_NAME__.";host=".__DB_HOST__, __DB_USERNAME__, __DB_PASSWORD__,"charset=utf8" );

            self::$connection = new PDO($dsn, self::__DB_USERNAME__, self::__DB_PASSWORD__, array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ));
        }
        return self::$connection;
     }

    //Make the query
    private static function dbQuery($sql_string) {

        $conn = self::getConnection();

        $sth = $conn->prepare($sql_string);
        $sth->execute();

        return $sth;
    }

    //Return all results from sqlquery in array
    public static function dbDataArray($sql_string){

        $data = self::dbQuery($sql_string)->fetchAll();

        return $data;
    }

    public static function Value($sql_string){

        $data = self::dbQuery($sql_string)->fetchColumn();

        return $data;
    }
}

This is the progress of the class so far and it seems to be working great. Special Thanks to Phil for all the support.
Any other recommendations are welcome and will be greatly appreciated.
Thanks again.

Original question
Basically I am trying to build a db access class that I can use with the following syntax
$test = db::dbDataArray("SELECT * FROM fw_settings");

The class will create the connection if one is not present so I can just call the methods from the class anytime without needing to create a new instance.
Here is what I have so far for the structure with a single function. Once I can get the status class to work on a single query item I will add all the other functions.
class db
{
    public $connection;
    const __DB__HOST__      = __DB__HOST__;
    const __DB_USERNAME__   = __DB_USERNAME__;
    const __DB_PASSWORD__   = __DB_PASSWORD__;
    const __DB_NAME__       = __DB_NAME__;

    function __construct() {

        if (self::$connection == null){

             self::$connection = mysql_connect(__DB_HOST__,__DB_USERNAME__,__DB_PASSWORD__)
                or die('Unable to Connect to SQL Host'.__DB_HOST__);
             @mysql_select_db(__DB_NAME__)
                or die('Unable to Select DB: '.__DB_NAME__);
        }
    }

    //Regular SQL query such as delete, update, etc.
    public static function dbQuery($sql_string) {

        //Handle the rest of the SQL query here
        if (!$sqlResult = mysql_query($sql_string, self::$connection) ){
            //Let's output the MySQL error if we have one
            die('

'.$sql_string.'

                    SQL Error:'. mysql_error(self::$connection).'

'
            );

        }
        else {
            //Return the sql result
            if (strpos($sql_string, "DELETE")){
                if (mysql_affected_rows($sqlResult) > 0){
                    return $sqlResult;
                }
                else{
                    return false;
                }
            }
            else{
                return $sqlResult;
            }
        }
    }

    //Return all results from sqlquery in array
    public static function dbDataArray($sql_string){

        $data = array();
        $dataQuery = self::dbQuery($sql_string);
        $i = 1;

        while(($row = mysql_fetch_assoc($dataQuery)) !== false){
            foreach($row AS $key=>$val){
                $data[$i][$key] = $val;
            }
            $i++;
        }
        return $data;
    }
}

The constants are defined in another file that is loaded before the class, so they will be present.
The error that I am getting right now is as follows.

Fatal error: Access to undeclared static property: db::$connection

It looks like it is making the connection fine. I just can't access the connection using the dbQuery function. The dbQuery function is used in all the other functions.
This is just the start of the class, and it is based on a group of functions I was already using.
The ultimate goal once it is working is to be able to pass a database name to the class and access that database in that specific instance, so I can use multiple databases in the projects I am planning to use this in.

A: In order for your class to operate statically, you need to do a few things.
First, make the connection static, eg
private static $connection;

Secondly, why all the underscores?
define('DB_HOST', 'localhost');
define('DB_NAME', 'your_db_name');
define('DB_USER', 'username');
define('DB_PASS', 'password');

Also, why use class constants at all? Just use the constants you've already defined.
Third, lose the constructor. You cannot expect to create an instance of this class and use it statically. I would go for a lazy-load approach for the connection
private static function getConnection() {
    if (self::$connection === null) {
        $dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8',
            DB_HOST, DB_NAME);

        self::$connection = new PDO($dsn, DB_USER, DB_PASS, array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ));
    }
    return self::$connection;
}

Then, your public methods would call this method internally. I'll also flesh out your dbDataArray method to show you how to return an associative array
public static function dbDataArray($query, $params = array()) {
    $stmt = self::getConnection()->prepare($query);
    $stmt->execute($params);
    return $stmt->fetchAll();
}


text:
Q: Метаданные MP3 Сколько бит/байт занимают метаданные в MP3 или как это можно узнать с помощью библиотеки JLayer на Java?
A: Последние 128 байт файла mp3 содержат метаданные. Можете написать программу которая считывает их. Структура:

Song title30 characters
Artist30 characters
Album30 characters
Year4 characters
Comment30 characters
Genre1 byte

Но это для ID3v1,у ID3v2 структура сложнее.Описание можно посмотреть здесь.
Библиотека для чтения информации здесь.


text:
Q: Persist Product setData I'm using the following code to try and update a product's description:
$product = $this->productRepository->getById(5);
$product->setData('description', 'foo');
$this->productRepository->save($product, $saveOptions = false);

While the data does get saved
(I can fetch it correctly via $product->getData('description');),
it is not changed in the db and thus no changes in the actual description.
Are additional steps necessary or am I using a false approach entirely?

A: As it turns I was editing the wrong shop-language. Persisting the data actually worked the whole time.
It's a good idea to always use the storeId when getting the model-object form the repository.


text:
Q: Why does base class pointer to a derived class object with overridden method call a base class method? #include<iostream>
using namespace std;

class Base
{
public:
    void show() { cout<<" In Base \n"; }
};

class Derived: public Base
{
public:
    void show() { cout<<"In Derived \n"; }
};

int main(void)
{
    Base *bp = new Derived;
    bp->show(); // RUN-TIME POLYMORPHISM
    return 0;
}

In the above code, show() is  declared in the base class and is overriden in the derived class. The base class pointer bp points to a derived class object. Now, when bp to call the non virtual show() function.
Output:
In Base

But, bp points to derived class, so why the base's function is called rather than the derived class function?

A:
// RUN-TIME POLYMORPHISM

In C++ it's opt-in. For a function call to be resolved polymorphically at run-time, the programmer must explicitly say that's desired by marking it virtual.
The reason is that dynamic dispatch is never without a cost, and a staple of C++'s design is that "you don't pay for what you don't need". You must say you really need it for it to be enabled.

A: You need to make show() virtual to allow kicking in of runtime polymorphism.
virtual void show() { cout<<" In Base \n"; }

A: The core issue here is that show method is not overridden in the derived class. Starting with C++11 you can use override specifier to ensure that method really does override something so compiler will detect this problem for your:
class Derived: public Base
{
public:
    void show() override { cout<<"In Derived \n"; }
};

prog.cc:13:10: error: 'void Derived::show()' marked 'override', but does not override

In order to override a method it should be declared as virtual in base class:
class Base
{
    public: virtual
    void show() { cout<<" In Base \n"; }
};

A: To complement the other answers posted here, with reference to this comment:

I know, but base pointer point to derived then why call base function?

Please see this post: https://stackoverflow.com/a/50830338/5743288
It follows, therefore, that if you were to do this:
Derived *dp = new Derived;
dp->show();

You would get the following output:
In Derived

even without declaring show() as virtual (because the compiler would then know which method you have said that you want to call).
So, as others point out, if you want the service you have to pay the price (although, even with your original code, the compiler would probably be smart enough to optimise out the virtual function call anyway, see here).

A: Most folks have already answered that you need to declare a function to be virtual for it to bind at runtime when your code executes.
I want to add that without virtual, the method to be called is decided at compile time and it will pick the method of the class whose variable/pointer type you declared. In your case, Base class type.
Additionally, would like to provide a good to read link which can help clear your concept of runtime polymorphism in C++ : https://www.geeksforgeeks.org/virtual-function-cpp/

A: This is actually what is call RUN TIME POLYMORPHISM. And in C++ its programmers discretion to call desired function of base or derived class, based on the object given to base class pointer.
Irrespective of the base class pointer pointing to any derived class object. If the function being called is non-virtual then always base class function will be called to a base class pointer.
To call derived class function from a base class pointer the function must be marked as virtual.

A: int main(void)
{
    Base *bp = new Derived;
    bp->show(); // RUN-TIME POLYMORPHISM
    return 0;
}

compiler bind it with base class object while compiling
    "new Derived" passing object to base but it been binded with base object it refer to same class
    once if you add virtual binding will happen run time and once object passed by derived it bind with drived class

A: In c++,even-though you make the base class pointer point to derived class object, it still calls the function from the base class, this is because of Early binding, so in order to achieve Late binding make the function inside the base class as virtual.
i.e., virtual void show()
{
.......
}
Now, the o/p will be "In Derived".


text:
Q: Fermat's primality test and Carmichael number I am playing with prime numbers and Fermat's Little Theorem. I read about Carmichael numbers and that they should pass the tests. The problem is, when I test it and use two different conditions it should end with the same result, but it isn't.
Code :
import java.math.BigInteger;

public class FermatTest {
    public static boolean passesAllFermatTests(BigInteger n) {
        BigInteger testValue = BigInteger.ONE;

        while (testValue.compareTo(n) == -1) {
            if (!passesFermatTest(n, testValue)) {
                return false;
            }
            testValue = testValue.add(BigInteger.ONE);
        }
        return true;
    }

    public static boolean passesFermatTest(BigInteger n, BigInteger a) {
        //if( !a.modPow(n.subtract(BigInteger.ONE), n).equals(BigInteger.ONE)) {
        if(! a.modPow(n, n).equals(a)) {
            return false;
        }

        return true;
    }

    public static void main(String[] args) {
        System.out.println(passesAllFermatTests(BigInteger.valueOf((long) 561)));
    }
}

When I run it with this condition, it returns true ( pass it ). If I run it with the commented condition, it returns false. It should be the same, isn't it? Is there an error in my code or I misunderstood something?

A: The problem is when a = 3, your commented condition return false, it is because 3 and 561 is not relatively prime! Carmichael number require gcd(a,n) = 1 (please refer to the wikipedia: https://en.wikipedia.org/wiki/Carmichael_number).
So in your program, you should first check "a" and "n" is relatively prime first before applying the commented condition.


text:
Q: Secure link url for landing page I want to send a user to a landing page first before they come to the real url when clicking on a link.
<a href="contents/landing_location.php?locationed='.$obj->id.'">

When the user click the link, it will go to this page.
<?php
session_start();
  if(!empty($_GET['locationed'])){
      $_SESSION['locationed'] = $_GET['locationed'];
      header('Location: realLocation.php');
      exit;
  }
?>

And then the user will be redirected to the realLocation.php
However, this link is showing up in the bottom of the browser, so the user can find the locationed string in the url.
My question is how to make this link is securable, so that it can not be shown to the user.

A: locationed is using the $_GET method. Try using the $_POST method for secure redirection.