text:
Q: each() function slows down Sorry, just found I had a bracket in the wrong place! All is well now. Thanks for the help.
I have this each function that fires when I click certain buttons. The function is fast for say the first 10 clicks. However, each time I trigger the function (click a button) the function gets slower and slower. It seems to be taking twice as long on each click. Does anybody know why, and I suppose more importantly, how I can change the code to prevent this?
Thanks!
function CollarStyleFunction(){

$('#Collar-Style-Box').children(".Fabrics").children(".SwatchBox").children('img').each(function () {

    var titleIs = this.title;
    if (titleIs==option) {
        $(this).parent().css("display", "inline");
    }

});

///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

Some other info and code:
The JS loads a XML file and loads 10 fabric swatches into the div (class="Fabrics"):
function parse(document){

    $(document).find("Swatch").each(function(){
        $(".Fabrics").append(
            '
'+
            ''+
            '
'
        );
    });

} //function parse End

HTML:

Collar Style

A: Just some comments…
> function CollarStyleFunction(event){

The event parameter is not used, does it serve a purpose?
>     $('#Collar-Style-Box').children(".Fabrics").children(".SwatchBox").children('img').each(function (i) {

Others have commented on using a selector (which likely will be passed to a native querySelectorAll method) instead of multiple function calls.
The i parameter is not used, does it serve a purpose?
>     titleIs = $(this).attr('title');

The variable titleIs becomes global when the above is executed. It should probably be kept local. Also more efficient to just get the title property:
var titleIs = this.title;

.
>     if (titleIs==(option)) {

Is option initialised elsewhere? There is no need for the parenthesis round option:
  if (titleIs == option) {

.
>         $(this).parent().css("display", "inline");

Do you really want inline? Consider setting display to '' (empty string) so the element can return to its default or inherited value, e.g.:
this.parentNode.style.display = '';

>     }
> });


text:
Q: sorting on aggregate of value in a given field in elasticsearch I have the following field in my index
field1:{key:value}

Is it possible to sort my query on sum of values in field1.
Thanks

A: Here's one way you could do this, assuming you know the fields ahead of time. It should be possible with some minor refinements if you need to wildcard the fields. This assumes the sibling fields on the nested type are numeric.
Example mapping:
  "test": {
    "mappings": {
      "type1": {
        "properties": {
          "field1": {
            "properties": {
              "key1": {
                "type": "integer"
              },
              "key2": {
                "type": "integer"
              }
            }
          }
        }
      }
    }
  }

Default results:
  "hits": {
    "total": 2,
    "max_score": 1,
    "hits": [
      {
        "_index": "test",
        "_type": "type1",
        "_id": "AV8O7956gIcGI2d5A_5g",
        "_score": 1,
        "_source": {
          "field1": {
            "key1": 11,
            "key2": 17
          }
        }
      },
      {
        "_index": "test",
        "_type": "type1",
        "_id": "AV8O78FqgIcGI2d5A_5f",
        "_score": 1,
        "_source": {
          "field1": {
            "key1": 5,
            "key2": 6
          }
        }
      }
    ]
  }

Query with script:
GET /test/_search
{
  "query": {
    "function_score": {
      "query": {
        "match_all": {}
      },
      "functions": [
        {
          "script_score": {
            "script": "return (doc['field1.key1'].value + doc['field1.key2'].value) * -1"
          }
        }
      ]
    }
  }
}

Logic taking the lowest score as the best score (least negative in this case):
{
  "took": 18,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": -11,
    "hits": [
      {
        "_index": "test",
        "_type": "type1",
        "_id": "AV8O78FqgIcGI2d5A_5f",
        "_score": -11,
        "_source": {
          "field1": {
            "key1": 5,
            "key2": 6
          }
        }
      },
      {
        "_index": "test",
        "_type": "type1",
        "_id": "AV8O7956gIcGI2d5A_5g",
        "_score": -28,
        "_source": {
          "field1": {
            "key1": 11,
            "key2": 17
          }
        }
      }
    ]
  }
}

Hopefully this gives you the gist of whatever specific scoring logic you need

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to align two UILabels with dynamic heights to the bottom of a UICollectionViewCell using autolayout I have a UICollectionViewCell that has two labels in it - side by side. They are supposed to take up equal width and the height of the tallest should align to the bottom and push out the container so that it stretches to the tallest of the two. What kind of autolayout constraints can I put on these labels to get that behavior without manual intervention? Is that even possible to define using autolayout constraints?

A: You can certainly use auto layout constraints to size a container view based on the tallest of its contents. That part is easy.
(Here, for example, I'm sizing a container based on which of two things inside it is wider. It's exactly the same problem, in effect.)
The problem here, though, is that UICollectionViewCells are not self-sizing, so it's hard to see what auto layout has to do with anything. You're going to have to size the cell in code no matter what.


text:
Q: Android view.animate() works different and wrong after first execution I've implemented a banner which pops out whenever the user losts connection. When is reconnected, another banner shows up for some seconds and disappears.
The layout is a RelativeLayout with a grey TextView for the warning*, and a green TextView for the reconnection message.

If I just change Visibility.GONE and Visibility.VISIBLE on them, everything works fine.
But I wanted to do it fancier, so I added some animations. And I'm having a weird problem here. In first execution everything works as expected. Following executions don't work right.
I want to animate both textviews at the same time when reconnection happens. So the grey textview fades out, while the green textview fades in (both at the same time). This works like that only on first execution. Next times it executes secuentially: first the grey textview fades out, and after that, green textview fades in. And I don't want it secuentially.
I've uploaded a video to Youtube (30s) so you can see the effect. First working, and then not. It's easier to watch this than to read my description: https://youtu.be/rD1ZNzKen0U
Crossfade method is where all the magic happens. As you see, the view.animate() is called inside two threads. Initially I implemented exactly the same code, but without threads, because the animate() method should be asynchronous. But I'm getting nuts with this problem, so I tried do it like this. I've also tried to execute view.clearAnimations() before setting each animation. But nothing.
private void crossfade() {
    final int animationDuration = 600;

    // Set the view to 0% opacity but visible, so that it is visible (but fully transparent) during the animation.
    bannerNetworkConnected.setAlpha(0f);
    bannerNetworkConnected.setVisibility(View.VISIBLE);

    bannerNetworkDisconnected.animate()
            .alpha(0f)
            .setDuration(animationDuration)
            .setListener(null);

    bannerNetworkConnected.animate()
            .alpha(1f)
            .setDuration(animationDuration)
            //  .setListener(null);
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    dissapearFadding();
                }
            });

    flipper.stopFlipping();
}

Method for dismissing the reconnected banner:
private void dissapearFadding() {
    bannerNetworkConnected.animate()
            .alpha(0f)
            .setDuration(300)
            .setStartDelay(1500)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    bannerNetworkDisconnected.setVisibility(View.GONE);
                    container.setVisibility(View.GONE);
                    bannerNetworkConnected.setVisibility(View.GONE);
                }
            });
}

Network switching receiver:
public void networkStateChange(boolean connected) {
    Log.i(MainActivity.TAG, "MainActivity.networkStateChange() " + connected);
    //bannerNetworkDisconnected.setVisibility(connected ? View.GONE : View.VISIBLE);

    if (bannerNetworkDisconnected != null && bannerNetworkConnected != null) {
        bannerNetworkDisconnected.clearAnimation();
        bannerNetworkConnected.clearAnimation();

        if (!connected) {
            appearFromTop();
        } else if (connected && bannerNetworkDisconnected.getVisibility() == View.VISIBLE) {
            crossfade();
        } else {
            container.setVisibility(View.GONE);
            bannerNetworkConnected.setVisibility(View.GONE);
            bannerNetworkDisconnected.setVisibility(View.GONE);
            flipper.stopFlipping();
        }
    }
}

Banner XML:
    <RelativeLayout
    android:id="@+id/banner_network_container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:visibility="gone">

    <TextView
        android:id="@+id/banner_network_disconnected"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="No connection. Retrying..."
        android:textColor="#F0F0F0"
        android:visibility="gone"/>

    <TextView
        android:id="@+id/banner_network_connected"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#44bb44"
        android:text="Reconnected!"
        android:textColor="#F0F0F0"
        android:visibility="gone"/>
</RelativeLayout>

I've created a new project and copied all the code for this, and the problem still there. If you want to inspect the whole classes here, you have the whole project on github:
https://github.com/rolgalan/NetworkBanner
I really would appreciate any help on this, because I've spent too much hours now to fix this and I'm getting crazy. It's really weird because it actually executes both animations... but one after the other instead of doing them in parallel like in the first execution.
*Actually the warning banner is a bit more complex than a simple TextView (LinearLayout) since I wanted a blink effect for "retrying..." text. But we shouldn't care about this.

A: It's pretty funny (for me) because I literally just answered a few minutes ago another question which is exactly the same problem as yours:
Please read my answer from here:
Why does running a second viewpropertyanimation on a view break the animation listeners?
so from what I explained there, the fix is easy:

*

*add .setStartDelay(0)

*to crossFade() -> bannerNetworkConnected.animate()
so it resets the delay and they can run together.


text:
Q: How to moniter memory allocated by some java method at runtime I am creating a java program in which my class suppose A has it's some predefined behavior. But user can over-ride my class to change its behavior. So my script will check if there is some subclass than I will call it's behavior but what if he has written some blocking code or memory leak in his code.
This may harm my process. Is there is any way in java to monitor memory allocated by some method.
Please suggest.

A:
but what if he has written some blocking code or memory leek in his
  code

First of all i suggest you document your class well. Describe what the user is allowed to do and what not. Give use cases what to do(if possible).
For the blocking code part, if you have some timing issues, you could wrap the execution of the method in say a Future and let a ExecutorService execute the code. That way you will be able to cancel the execution if the execution takes too much time.
For the memory leak issue, well i guess you are not talking about memory leaks but increased memory consumption caused by calling the overridden method. Memory leaks in java are rare after all.
You will not be able to detect the memory consumption of a method, that's not how java works. Memory is global. What will you do if for example an external library is loaded(JNI), or some library in the classpath is called that will use more memory now? You just can not tell.
Other then monitoring the overall memory consumption, there is no other way(someone please tell me if i am wrong).

A: For external monitoring, you can use VisualVM or JConsole (part of JDK), for internal you can use the Runtime class:
Runtime rt = Runtime.getRuntime();
    long totalMem = rt.totalMemory();
    long maxMem = rt.maxMemory();
    long freeMem = rt.freeMemory();

Via the Thread class, you can check the status of all threads. Never used it directly, because application servers or batch processing APIs doing their job... So, I don't need to reinvent the wheel. And I suggest to use tools like VisualVM...
EDIT: Watch also this thread: Why do threads share the heap space?
You cannot analyze the heap usage of a single thread. If you have problems with the execution of foreign code, you should sepearate it as good as you can from other threads and analyze the thread or heap dumps. This could be done as mentioned with VisualVM or JConsole which was also added by Oracle (or SUN).

A: Oracle has quite a good document about solving memory leaks. It suggests that one should use NetBeans Profiler as a tool.
http://www.oracle.com/technetwork/java/javase/memleaks-137499.html
I believe you can use the same debugging API for checking against misbehaving code while it is running, but that will come with a performance penalty and is probably akin to killing a fly with a sledgehammer. I personally would not let anything like that to run in production. Instead I would rely on rigorous testing and peer review.

A: Depending on what sort of behavior that the subclass can do, then we might think of options. For example, if it's a database related operation, we can force them to do connection clean ups, if it's file based, we can force them to read the file through your class and check for how big the file is, if it's any http call or some other streaming functionality, we can look at enforcing constraints accordingly.
If you're just worried about the heap size utilization and memory leaks there, you might want to look at http://java.dzone.com/tips/getting-jvm-heap-size-used which explains how to get runtime memory programatically. But then you'll have to do periodic checks and you can never be sure of whether a memory usage is caused by the subclass behavior.

A: I just found this while i was trying to build up an agent that records memory allocations:
In the post How to track any object creation in Java since freeMemory() only reports long-lived objects? it is specified that there is an open source project Java Allocation Instrumenter that you could use to register your own callback (it has examples too) and using that you are able to obtain what you need.
I started few days ago to work on a similar project and while researching i found your question and the below post.
I personally needed this kind of code in some unit tests to check if one allocates too many objects inside critical methods and found that using Runtime class was not appropiate because Garbage collector may interfere and the test recorded negative numbers for allocated memory.


text:
Q: Optimizing AWS RedShift query I am storing user details in a longitudinal table with each attribute of a user corresponding to a separate row. There can obviously be multiple rows per user since the data is longitudinal.
I am trying to find all user details of a particular user based on the mobile number provided. I am using the following query:
select ws.*
from (select * from user_details) as vs
inner join
  (select distinct ms.user_id
   from (select <given mobile no> as Phone) as ls
   inner join (select * from user_details) as ms on ls.Phone = ms.value
  ) as ws
on ws.user_id = vs.user_id

'key' column corresponds to the user attribute and 'value' corresponds to the value of that user attribute.
The sample table is:

|---------|--------|------------|---------------------|
| user_id |   key  |   value    |       timestamp     |
|---------|--------|------------|---------------------|
|  100    | mobile | 765783xxxx | 2018-09-09 13:40:00 |
|  100    |  email | abc@te.com | 2018-09-09 13:41:00 |
|  100    |  name  | johnny doe | 2018-09-09 13:42:00 |
|  101    | mobile | 456898xxxx | 2018-09-09 13:43:00 |
|  101    | email  | hi@som.org | 2018-09-09 13:44:00 |
|  101    |  name  | janey doe  | 2018-09-09 13:45:00 |
|---------|--------|------------|---------------------|

I am first finding user_id based on given mobile number and joining it with the value column and then I want to find all rows corresponding to that user_id.
I have set up DISTKEY on user_id column and SORTKEY on timestamp column.
This table has close to 2 billion rows.
The cluster details are:
Cluster Properties:

*

*Cluster Type: Single Node

*Node Type: dc1.large

Capacity Details:

*

*Current Node Type: dc1.large

*CPU: 7 EC2 Compute Units (2 virtual cores) per node

*Memory: 15GiB per node

*Platform: 64-bit

The query with this configuration is currently taking 160 seconds to execute.
Appreciate any help in optimizing this query and reducing the run time.

A: It is very difficult to suggest improvements on a query without understanding the contents of the table nor what you are trying to achieve.
It is quite possible that it could be as simple as:
SELECT DISTINCT user_id
FROM user_details
WHERE value = <given mobile no>

The other part of optimizing a query in Amazon Redshift is to wisely use DISTKEY and SORTKEY. Once again, it is difficult to recommend suitable values without knowing the data and how it is used, but this query would benefit from value being the SORTKEY. (But that doesn't necessarily mean it is best choice for all usage of the table.)


text:
Q: MATLAB bins setting in histogram I want to change how data are distributed in the histogram that I built.My histogram looks like

But I want it to look like

I set
bins1=[10,30,50,70];
hist(data,bins1)

How can I arrange the bins as in the second figure?

A: Use histc instead of hist. histc allows you to define the edges while hist uses the second input parameter as centers.


text:
Q: Migrate AutoML translation's custom model to another GCP Project I have some custom models for Google AutoML Translations trained in a QA GCP project.
I want to promote the models to production but I don't find a way to export/migrate the models from  QA to the PROD project.
Is it possible that the only solution is to train again from scratch models? I want to avoid this solution because the training sets are exactly the same between QA and PROD and the training process is not cheap.
Thank you in advance to anyone who will help to figure out a possible solution.


text:
Q: Use Excel VBA to change the value of a cell in a closed workbook? I currently use this function in VBA to get the value of a cell in a closed workbook. I want to use a similar process to SET the value of the cell to whatever I want, without opening the file. Is that possible?
Private Function GetValue(path, file, sheet, ref)

    Dim arg As String
    If Right(path, 1) <> "\" Then path = path & "\"
    If Dir(path & file) = "" Then
        GetValue = "File Not Found"
        Exit Function
    End If
    arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
        Range(ref).Range("A1").Address(, , xlR1C1)
    GetValue = ExecuteExcel4Macro(arg)
End Function

A: Yes you can do this using ADO as Gary commented but only if your Excel Worksheet is arranged in a Database like structure.
Meaning you have valid fields arranged in columns (with or without headers).
For example:

Now, you see that ID number 12345 have a name John John and you want to update it to John Knight.
Using ADO you can try:
Edit1: You can actually do this without using Recordset. See below update.
Sub conscious()
    Dim con As ADODB.Connection
    Dim sqlstr As String, datasource As String

    Set con = New ADODB.Connection
    datasource = "C:\Users\UserName\Desktop\TestDataBase.xlsx" 'change to suit

    Dim sconnect As String
    sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source=" & datasource & ";" & _
                "Extended Properties=""Excel 12.0;HDR=YES"";"

    With con
        .Open sconnect
        sqlstr = "UPDATE [Sheet1$] SET [Name] = ""John Knight"" WHERE [ID Number] = 12345"
        .Execute sqlstr
        .Close
    End With

    Set con = Nothing
End Sub

Result:

I'm not entirely sure if this is what you want but HTH.
Notes:

*

*You need to add reference to Microsoft ActiveX Data Objects X.X Library (early bind).

*But you can also do this using late bind (no reference).

*Connection string used is for Excel 2007 and up.

*Sheet1 is the name of the target sheet you want to update the value to.

Edit1: This is how to do it if your file have no header
First change the connection string HDR argument to NO:.
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
           "Data Source=" & datasource & ";" & _
           "Extended Properties=""Excel 12.0;HDR=NO"";"

Then adjust your SQL string to:
sqlstr = "UPDATE [Sheet1$] SET F2 = ""John Knight"" WHERE F1 = 12345"

So that is F1 for field 1, F2 for field 2 etc.


text:
Q: Put json data from jquery into Thymeleaf I am using google book api for ISBN and I am able to get data. Now I want to attach that data into a form. I am not able to that.
This is my Jquery Code
$(document).ready(function(){
    $('#submitCode').click(function(){
    var x;
     var isbn = $('#isbn').val();
     var xmlhttp = new XMLHttpRequest();
     var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;

        xmlhttp.onreadystatechange = function() {
        /*<![CDATA[*/
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        x = JSON.parse(xmlhttp.responseText);
        callback(x);
       }/*]]>*/
       };
       xmlhttp.open("GET", url, true);
       xmlhttp.send();

function callback(x) {
alert(JSON.stringify(x));
console.log(x);
};
});
});

My HTML code

 <input id="author" name="author" th:field="*{author}" type="text" class="validate" />
  Author

  <input id="title" name="title" th:field="*{title}" type="text" class="validate" />
   Title

How should I attach author data and title into the form in Thymeleaf?

A: If you've been able to retrieve the data already, you should only need to update the DOM using $('#id').val(value). I did a bit of digging, and it looks like your API returns the title and authors like this, hence the use of json.items[0].volumeInfo in the new callback code.
{
  "items": [{
    "volumeInfo": {
      "title": "Example Title",
      "subtitle": "Example Subtitle",
      "authors": [ "Example Author" ]
    }
  }]
}

$(document).ready(function() {
  $('#submitCode').click(function() {
    var x;
    var isbn = $('#isbn').val();
    var xmlhttp = new XMLHttpRequest();
    var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;

    xmlhttp.onreadystatechange = function() {
      /*<![CDATA[*/
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        x = JSON.parse(xmlhttp.responseText);
        callback(x);
      } /*]]>*/
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();

    function callback (json) {
      var book = json.items[0].volumeInfo
      $('#author').val(book.authors.join('; '))
      $('#title').val(book.title)
    };
  });
});

<input id="isbn" type="text" value="1904764827"/>ISBN

  <input id="author" name="author" th:field="*{author}" type="text" class="validate" />
  Author

  <input id="title" name="title" th:field="*{title}" type="text" class="validate" />
  Title

<button id="submitCode">Submit</button>


text:
Q: Rancher docker macos exec permission denied I installed docker via rancher desktop on MacOS and I have been using docker for several months. Now something happened automagical (not possible) and I am not able to start some of containers eg kafka, via docker-compose.
I have docker-compose.yml file:
version: '3.7'
services:

  kafka:
    image: confluentinc/cp-server:5.5.0
    restart: always
    ports:
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 1
  // ... other props
    command: /create.sh
    volumes:
      - ./create.sh:/create.sh
      - ./t.config:/t.config

I want to start this container docker-compose up -d
and got an error:
Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "/create.sh": permission denied: unknown

Environment
% docker --version
Docker version 20.10.17-rd, build c2e4e01

% docker-compose --version
Docker Compose version v2.11.1

Rancher Desktop Version: 1.6.1

I read a lot of posts and the most possible is that my file does not have correct permissions but:
% ls -l create.sh
-rwxr-xr-x  1 myUser  u  1083 Oct 26 16:08 create.sh

I tried to change permission in container:
    command: chmod a+x /create.sh && /create.sh

then docker image began restart again and again without any log files.
I also allowed my Rancher desktop full disk access

I tried to downgrade rancher by install older version https://docs.rancherdesktop.io/getting-started/installation/
I am not able to addGroup as macOs user Docker Rancher - Permission Denied when using docker from WSL
Finally, it works on another computers (macOS, linux).
Is there any other thing I can check / change to verify the issue?
I checked that my container store directory instead of my volume files and  as I read here Single file volume mounted as directory in Docker, there is something wrong with my files.
Should I configure something in mac preferences as I think could do something in mac settings few months ago that's why all containers has been working.

A: I found a solution mention here
https://github.com/rancher-sandbox/rancher-desktop/issues/1209#issuecomment-1370181132
Basically this is because of how rancher engine mount. So you have to direct it to use mountType: 9p


text:
Q: Plotting for next row after the slice I am plotting values of column X and FT according to column CN value in the following code
import matplotlib.pyplot as plt, plt.plot(X[CN==1],FT[CN==1]), plt.plot(X[CN==36],FT[CN==36])
and the data is given as
+-------+-----+----+-------+-------+
| X     |  N  | CN | Vdiff | FT    |
+-------+-----+----+-------+-------+
|   524 |   2 |  1 |   0.0 | 0.12. |
|   534 |   2 |  1 |   0.0 |0.134. |
|   525 |   2 |  1 |   0.0 |0.154. |
|     . |     |    |       |.      |
|     . |     |    |       |.      |
|  5976 |  15 | 14 |   0.0 |3.54.  |
|  5913 |  15 | 14 |   0.1 |3.98.  |
|  5923 |   0 | 15 |   0.0 |3.87.  |
|     . |     |    |       |.      |
|     . |     |    |       |.      |
| 33001 |   7 | 36 |   0.0 |7.36   |
| 33029 |   7 | 36 |   0.0 |8.99   |
| 33023 |   7 | 36 |   0.1 |12.45  |
| 33114 |   0 | 37 |   0.0 |14.33  |
+-------+-----+----+-------+-------+

I am getting incomplete graphs so I need to use 1 next row in my plot. For example for the graph of CN==36 as plt.plot(X[CN==36],FT[CN==36]) I want to use first row of CN==37 in my plot. Note that CN values are repetitive.
I have to plot multiple graphs in this way so a general code above graphs will be appreciated.

Addition on request in comment: Check at the end of the circular shape they are not touching their edges so circle is incomplete. for example for aqua & green color cycles. I want complete cycles so I need 1 or 2 additonal rows in data to plot.


text:
Q: Have to be root to access a CIFS mount within a home directory. Why is that? I have mounted a CIFS share on my ubuntu box by adding the below line to my fstab file. The share mounts without drama however if i try access the share as myself i get a permissions error, however if i access the share are root i can go straight on in and make all the changes i want.
//192.168.0.60/me     /home/me/me cifs    user,dir_mode=777,uid=1000,username=me,file_mode=777,gid=1000,password=PasswordHere       0       0

It is my understanding that by setting the dir mode to 777 and specifying the UID and GID as 1000 (the code for 'me') it would permit the 'me' user access.
No doubt this is a pretty simple error on my behalf.
Any ideas please let me know :)


text:
Q: Select2 - need a event when drop down list is formed after opening the dropdown I am using select2 jquery plugin
I am using open event
var select2 = $('select').select2();
select2.on("select2:open", () => {
   // I want to do some code here with $('.select2-results__option')
   //$('.select2-results__option').size() is not equal to actual elements
});

This event triggers when we click the dropdown. but I am not getting the dropdown elements in this event.
I have 2000 dropdown elements. but in open event I am not getting that. Is there any event to detect the dropdown list is filled or not.

A: I had a similar problem when I tried to remove an item after open.
You could use a async function to check if the list is complete:
select2.on("open", function (e) {
   asyncCheck();
});

async asyncCheck() {
  // Waiting for 0 milliseconds was enough for me, maybe you need to increase the value
  await new Promise(resolve => window.setTimeout(resolve, 0));

  // Here comes your check, if list is completly populated ...
}

But be aware, that this will not work with IE 11 as async and Promise are not supported in IE 11 (see Promises and async function from Can I Use
My workaround for IE 11 looks like this:
$(document).ready(checkContinuously());

function checkContinuously() {
  // Do your check here
  setTimeout(checkContinuouslyForNullOption, 100);
}

But is has the obvious drawback of always executing the check and theoretically could cause a stack overflow as it uses recursion.

A: Try to catch 'results:all' event of select2 itself (not DOM).
Here from Select2.prototype._registerEvents:
this.on('query', function (params) {
  if (!self.isOpen()) {
    self.trigger('open', {});
  }

  this.dataAdapter.query(params, function (data) {
    self.trigger('results:all', {
      data: data,
      query: params
    });
  });
});

as we can see open is triggered before querying dataAdapter, that's because you don't have options in its handler I guest.
select2.on("results:all", function (args) { console.log(args.data);});

A: One way of finding if there are options or not is
$('#select').find("option").length which provides the number of options there are.
Fiddle Here


text:
Q: How to handle the 'Invalid Argument Error' for output labels in tf.keras I am using a data set with classification labels 1 to 8.
While using keras sequential model, when I create an output layer with 8 neurons, it gives an Invalid argument error. My understanding is that it recognizes labels as 0 to 7 and does not include 8.
Thus, when I create an output layer with 9 neurons, it seems to work.
My query is, is it okay to use 9 neurons instead of 8?
Code is as follows:
model = keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape=X.shape[1:] ))
model.add(keras.layers.Dense(70, activation="selu",kernel_initializer="lecun_normal"))
model.add(keras.layers.Dense(70, activation="selu",kernel_initializer="lecun_normal"))
model.add(keras.layers.Dense(8, activation="softmax"))

model.compile(loss='sparse_categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])
history = model.fit(X, y, epochs=100,
                    validation_data=(X_test, y_test))

error message:
InvalidArgumentError:  Received a label value of 8 which is outside the valid range of [0, 8).  Label values: 2 7 7 6 8 1 2 8 6 3 6 8 2 6 1 2 5 8 8 8 1 1 7 8 2 8 6 8 7 5 8 6
[[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (defined at :6) ]] [Op:__inference_train_function_823581]

A: Using 9 neurons wouldn't be a right choice to go with. Since, you have a total of 8 class labels in your dataset, your logit vector should be 8-dimensional which would then be converted to a categorical distribution by applying the softmax function and thus computing the Cross-entropy loss. The computation of the softmax categorical distribution includes a normalization factor which is the sum of the exponential of the logit vector components. Thus, adding 9 neurons would simply make this computation flawed since you would be adding an extra random value every time.
In this case, the best solution would be to adjust your labels in the pre-processing stage. It is a pretty simple job to do and doesn't require much coding either. Let's say your labels are stored in a numpy array, you could do something like this:
labels = np.array([1, 2, 3, 4, 1, 5, 8]

map_dict = {1:0, 2:1, 3:2, 4:3, 5:4, 6:5, 7:6, 8:7}

for k, v in map_dict.items():
    labels[labels == k] = v

A: When you have 8 layers at the top of the model and you are using sparse categorial cross entropy loss it expects the label values to be 0 up to 7. When it gets a label of 8 it creates an error. When you change from 8 neurons to 9 it expects to see labels in the range of 0 to 8 so it will not generate an error. Since none of the samples have a  label of 0 your network will classify properly.


text:
Q: Separate UI and API server I am new to Jhipster application. I have successfully developed application by using Jhipster.
Now i want to deploy application in Tomcat server. So i am trying to generate war by using mvnw -Pdev package command. its successfully generated war.
Now i am trying to deploy this war into tomcat, its successfully deployed. But i am facing issue as its running only backend(API) server only.
I am unable to run frontend application in browser.
could you please any one help me on this. I want to run UI and API server in tomcat.
Thanks in advance.

A: -Pdev is for development it was not made for deploying into Tomcat, in dev you are supposed to run frontend code from webpack dev server not from java backend because you want to benefit from frontend code hot reloading.
If you still want to run in Tomcat for dev without hot reloading (bad for your productivity), run a -Pprod build so that your war includes the javascript bundle of your frontend code
As a general comment, deploying a JHipster app into any app server usually requires more effort than embracing the executable jar recommended approach.


text:
Q: Dynamic programming: max sum through a 2-D matrix(a harder version) It's from my algorithm class and I think I really need some help.
Given a cost matrix Happiness[][] where Happiness[i][j] denotes the happiness of visiting cell with coordinates (i,j), you start from top right corner and ends at bottom left corner. We want to find max happiness.
You can only go down or go left in the matrix.
But we have 2 constraints here:
1.you can choose to skip zero or more rows which mean you can go to the last row at first if you want.
2.When you choose to go left, cost = cost - 1. The second consecutive left causes cost = cost - 2, but when you go down then go left, it refreshes.
Here is an example:

This is the step:

I am not sure I am right or wrong. I use top down.
My solution:
To reach a cell matrix[i][j], you must have come from one cell higher or left to the original cell.
My recurrence:(I stuck here)
I think the base cases are leftmost row and bottommost column.
How can computer check the consecutive steps and know is an opt solution?
I know it's strange to post the whole question, but I can not simplify the question better...

A: In agreement with @גלעד ברקן's comment, the trick to solving this problem is adding an extra dimension representing the number of lefts taken to reach the cell to the recurrence relation.
Note: to make this problem easier, I have reversed the rows of the given matrix so that the allowed movement directions are down and right, and the starting cell becomes (0, 0) and the ending cell becomes (W - 1, H - 1), where W and H are the width and height of the matrix respectively. Also, the matrix and the corresponding max happiness dp table are considered to be in row major order, i.e. matrix[y][x] is the value at the cell (x, y).
Our true base case is the happiness of visiting the starting cell, which is either matrix[0][0] or 0, depending on whether the value of the starting cell has to be included in the total happiness. However, we also have two pseudo base cases are quite simpler to calculate compared to the actual recursion.
These pseudo base cases are the leftmost column (remember, the rows have been reversed, so this is the rightmost column in the original matrix) and the topmost row. The recurrence relation for a cell (0, y) (1 <= y < H) in the leftmost column is:
h[y][0][0] = matrix[y][0] + max(h[i][0][0] for i in 0 to y-1)

Where h is our max happiness dp table and h[y][x][r] is the max happiness gained on going from cell (0, 0) to (x, y) (following the given rules) having taken r consecutive rights (or lefts, for the original non row-reversed matrix) just before arriving at (x, y). Thus, if r is 0, the last traversed cell was one directly above the current cell. The only possible way to reach a cell in the leftmost column is to come from a cell directly above it.
An important thing to note about our max happiness table is that the maximum happiness for any cell (x, y) is given by the maximum of h[y][x][r] for all values of r. If h is a three-dimensional array/list, it can also be represented as max(h[y][x]).
Similarly, the recurrence relation for a cell (x, 0) (1 <= x < W) in the topmost row is:
h[0][x][x] = h[0][x-1][x-1] + matrix[0][x] - x

This stems from the fact that the only way to reach a cell in the topmost row is to keep going right from the starting cell. The number of rights taken to reach a cell in the topmost row is equal to its 0-based X-coordinate, hence the penalty of -x.
Now that we have our base cases, we can move on to the recurrence relation for a cell (x, y), where 1 <= x < W and 1 <= y < H.
While estabilishing this recurrence relation, the first thing to note is that there are only two possibilities: either the last cell was above or to the left of the given cell. We shall consider both these possibilities.
If the last cell was above the given cell, it would have the coordinates (x, j), where 0 <= j < y. For maximum happiness, the happiness at the last cell must also be maximum. Thus, the maximum happiness at (x, y) when the last cell is above the given cell is given by
h[y][x][0] = matrix[y][x] + max(max(h[j][x]) for j in 0 to y-1)

Note that the number of rights made (r) is 0, and max(h[j][x]) is the maximum happiness obtained on reaching the cell (x, j) with any number of rights.
If the last cell was to the left of the given cell (or in other words, the last move was to the right), its coordinates would simply be (x - 1, y). This is because we can move only one cell to the right at a time. Unlike the previous case, the last cell position is constant. However, the number of consecutive rights (r) taken to reach this cell is variable. Therefore, we must consider all possible values for r. Since a minimum of 1 right and a maximum of x rights can be made, 1 <= r <= x. For each value of r, the maximum happiness of this cell is the maximum happiness of the cell to the left (the last cell) for r - 1 rights plus the value at (x, y) minus the penalty (which is just r - 1). In pseudocode,
for r in 1 to x:
    h[y][x][r] = h[y][x-1][r-1] + matrix[y][x] - r

We now have everything we need to run the algorithm in a bottom-up or a top-down approach. Our final answer, the maximum happiness taken to reach the bottom-right (bottom-left, for the original non-row-reversed matrix) cell, is given by max(h[H-1][W-1]).
Putting everything together, we have the following (Python-esque) bottom-up algorithm with a time complexity of O(W^2 * H^2) algorithm:
h[0][0][0] = matrix[0][0]

for x in range(1, W):
    h[0][x][x] = h[0][x-1][x-1] + matrix[0][x] - x

for y in range(1, H):
    h[y][0][0] = matrix[y][0] + max(h[i][0][0] for i in range(y))

for y in range(1, H):
    for x in range(1, W):
        for r in range(1, x + 1):
            h[y][x][r] = h[y][x-1][r-1] + matrix[y][x] - r
        h[y][x][0] = matrix[y][x] + max(max(h[j][x]) for j in range(y))

return max(h[H-1][W-1])

On closer inspection, it appears that the O(W) operation of computing max(h[j][x]) can be removed by precalculating it, making the final time complexity O(W * H^2). Note that this optimization is valid only for the bottom-up approach. This works because the cell (x, j) (where j < y) should have already been visited in the bottom-up approach. In the code below, max(h[y][x]) is stored in h[y][x][W].
The full, optimized version of the bottom-up algorithm in Python 3 (including the given example matrix as input and row-reversal of the input matrix):
matrix = [[5, -2, -1, 5, 3, -99, 4, 0],
[5, -2, -1, -3, 3, -99, 2, -3],
[-98, -98, -98, -98, -98, -98, -98, -98],
[-99, -99, -99, -99, -99, -99, -99, -99],
[5, 0, -3, 5, -1, 7, -2, 2],
[1, 2, 7, 0, 0, 1, -1, -1]]

H = len(matrix)
W = len(matrix[0])

for row in matrix:
    row.reverse()

h = [[[0] * (W + 1) for i in range(W)] for j in range(H)]

h[0][0][0] = matrix[0][0]
h[0][0][W] = h[0][0][0]

for x in range(1, W):
    h[0][x][x] = h[0][x-1][x-1] + matrix[0][x] - x
    h[0][x][W] = h[0][x][x]

for y in range(1, H):
    h[y][0][0] = matrix[y][0] + max(h[i][0][0] for i in range(y))
    h[y][0][W] = h[y][0][0]

for y in range(1, H):
    for x in range(1, W):
        h[y][x][0] = matrix[y][x] + max(h[j][x][W] for j in range(y))
        h[y][x][W] = h[y][x][0]
        for r in range(1, x + 1):
            h[y][x][r] = h[y][x-1][r-1] + matrix[y][x] - r
            h[y][x][W] = max(h[y][x][W], h[y][x][r])

print(h[H-1][W-1][W])


text:
Q: Why does list.remove() not remove all items that meet the condition? I have a bunch of feature classes in a geodatabase, and some of them are empty. I want to generate a list of all feature class names, and then remove the names of any feature classes that are empty. For some reason, the (example) code below removes some, but not all of the empty files.
These lines correctly produce a list of all the feature classes:
myDir = r'C:\Projects\geodatabase.gdb'
arcpy.env.workspace = myDir
myfiles = 'MLresult_*'
file_list = arcpy.ListFeatureClasses(myfiles)

If I print the name and the number of records of all files in the list...
for file in file_list:
    print(file)
    print(arcpy.management.GetCount(file))

The printout is something like:
MLresult_2013
9
MLresult_2018
4
MLresult_2020
0
MLresult_2021
0

Where multiple files are empty (and the counts are all correct). BUT, when I execute these lines...
for file in file_list:
    if arcpy.management.GetCount(file)[0] == "0":
        file_list.remove(file)

then the list removes some of the "empty" files, but not all, so the list now looks like:
['MLresult_2013', 'MLresult_2018', 'MLresult_2021']

Why would it remove MLresult_2020, but not MLresult_2021, when
arcpy.management.GetCount(file)[0] == "0"

Is true for both?

A:
Python behind the scenes creates an iterator for your list, and it is
the iterator which moves through your list one entry at a time. The
iterator is evaluated once, which means that if you then modify your
list, the iterator could potentially get 'lost' - you also can't use
the file variable to modify your list, since it is just a reference to
the thing in your list.
Reference

You should avoid modifying a list in for loop using its element in the loop, especially avoid removing an item from the list.
You can solve the issue using a list comprehension:
file_list = arcpy.ListFeatureClasses(myfiles)

# list comprehension
file_list = [f for f in file_list if arcpy.management.GetCount(f)[0] != 0]

But this doesn't remove empty feature classes from the geodatabase. It just removes the items from file_list list.


text:
Q: Macro which prints an expression and evaluates it (with __STRING) For learning and demonstrating, I need a macro which prints its parameter and evaluates it. I suspect it is a very common case, may be even a FAQ but I cannot find actual references.
My current code is:
#define PRINT(expr) (fprintf(stdout, "%s -> %d\n", __STRING(expr), (expr)))

and then:
PRINT(x & 0x01);

It works fine but I am not sure of the legal status of the __STRING macro, specially since it is in the private __ namespace.
So, my questions:

*

*Is there a better way to write this macro?

*Is __STRING standard/great/evil?

*How to use existing search tools to find about __STRING? SO's search engine just searches anything containing string :-(

A: Something like
#define PRINT(expr) (fprintf(stdout, "%s -> %d\n", #expr, (expr)))

is probably what you want. # is the stringification operator.

A: You can use the # preprocessor token which converts the parameter following it to a string literal:
#include <stdlib.h>
#include <stdio.h>

#define STR(x) #x
#define PRINT(expr) (fprintf(stdout, "%s -> %d\n", STR(expr), (expr)))

int main(void)
{
    int x = 7;

    PRINT(x & 0x01);

    return EXIT_SUCCESS;
}

*It's definitely not standard, and this is the first time I've come across it; not surprising as it doesn't seem to do much more than the STR() macro above, at a first glance.

*Google seems to work fine.

A: It is glibc who has been providing __STRING since (at least) version 1.04 (1992-09-03), maybe earlier.
/usr/include/sys/cdefs.h:
#define __CONCAT(x,y)   x ## y
#define __STRING(x) #x

They were both used in glibc back then. Currently, __STRING is not used in glibc, but is kept there for app use.
On Linux, you may rely upon these. IIUC, __STRING and __CONCAT were adopted in NetBSD 1.3; Solaris provides neither. Other OSes may vary.


text:
Q: How is the slit material not considered an observer? As far as I can tell, the essential process of "observation" is that there is an interaction with something else, providing a means by which any part of the universe noticed something about the thing being observed.
In the double-slit experiment it is absolutely obvious that the slits (and material the slit is in) affect the electron somehow.  Why is this not considered an observation/interaction? Sure, the math works this way, but why can we act like one interaction doesn't matter while another does?

A: If the interaction with the electron changes the state of the system representing the double slit in such a way that you could (in principle) find out through which of the slits the electron had passed, the interference pattern gets indeed lost.  Otherwise you will observe interference. You find a nice elementary discussion in "The Feynman Lectures on Physics", vol.3, sects. 3-2 and 3-3.

A: In this case, the wavefunction collapses to one of two states: either the electron hits the screen and is absorbed, or the electron does not hit the screen and passes through the slits. In the latter case, the state it collapses to has peaks for both slits at once: it is the sum of the two wavefunctions that would arise if either just one or the other slit was open.
A wavefunction doesn't have to collapse to a single-point position state, it can collapse to a 'narrower' but still spread-out wavefunction.
However, it should be noted that measurement being synonymous with interaction is mainly a feature of no-collapse interpretations, like the Everett (Many Worlds) Interpretation. Collapse interpretations usually make a distinction: to trigger collapse and an observation/measurement, the observer has to be 'big enough' in some sense that it acts classically rather than as a quantum system; or, in some interpretations, the observer has to be 'intelligent' or 'conscious'.
The screen with the slits in it is certainly big enough to pass for those interpretations relying on mass or number of states to trigger collapse. It's obviously not conscious/intelligent, so it would not pass the 'Schrodinger's Cat' test in which we suppose that the cat doesn't collapse the wavefunction; we need a human to open the box to do so. If a cat can't do it, an inanimate screen certainly cannot.
For the no-collapse interpretations, we have to understand that the appearance of collapse is observer-relative. From the point of view of the system interacting with the electron (like the cat in the box), the wavefunction appears to have collapsed, but to an external human observer who has not yet opened the box, it has not. This is because when systems interact, they enter a superposition of non-interacting, orthogonal states, each of them consisting of an observer seeing one outcome. The cat in the box is a superposition of a cat seeing the electron spin 'up' and a cat seeing the electron spin 'down'. Each part of the cat wavefunction thinks it is the whole, and the electron has collapsed to one definite state. To the human outside the box, both electron and cat are still jointly in a superposition, yet to collapse.
So as a human observing the double-slit experiment, we can ignore the slits observing/collapsing the wavefunction, because they only do so from the slits' point of view. Each version of the slits sees one outcome: either the electron hit the screen, or it passed through. From our external human point of view, the collapse has not occurred yet; it only (apparently) does so when the human observer sees the result. (And the human becomes a quantum superposition of mutually-invisible observers each seeing the electron in only one place.)
In summary:

*

*In this particular case, the collapse is to a 'through both slits' wavefunction which gives the expected interference pattern, and so isn't a problem. We're not ignoring it; it's actually required.

*Collapse interpretations allow interactions not to trigger measurement/collapse if the system is not conscious, or very small/light. The answer depends on which interpretation you're using.

*No-collapse interpretations (e.g., Everett/Many Worlds) are the ones for which interaction is generally synonymous with measurement/collapse. But in these the appearance of 'collapse' is specific to the observer doing the interacting, and other external observers don't see it until they interact, and can ignore it.

A: Not only in the double-slit experiment, but for every edge, it is the edges that influence the electron. Behind each edge you find a wave-shaped distribution of electrons on a screen. And as you say, it is the perfectly functioning mathematical solution that seems to make deeper explanations superfluous.
If something influences the direction of movement of the electron - like the photon, by the way - then it is the surface electrons of the edges. There is the research field of phononic and other wave-like excitations in materials. It should not be difficult for a specialist in this field to make a theory of feedback on the movement path of the electron (photon) from this. And perhaps this even holds the chance to prove the passage of the electron (photon) through the slit.


text:
Q: How can I create new factorization projects? I found many factorization projects in the internet : Mersenne-primes, Fermat-primes, Cunningham-project , Proth-number-search and many more.
If I want to create a new fatorization project :

1) How can I find out if such a project is already in progress (Of course,
       I can search with google first, but maybe google does not find an
       existing project because I named it wronlgy) ?
2) How can I suggest to open a new project and submit the factorizations, I
       already found ?

I found this site : https://primes.utm.edu/ , where prime curious and prime numbers can be submitted, but I doubt I can create a new project on this site.


text:
Q: hive date dim - customize week number My requirement is to populate week number against calendar date.The catch is week number will start from October 1 and end at December 7.
So week commencing October 1 will be treated as week 1 , 7th October as week 2 and so on last week number will populate against December 7. Rest will have week number column as NULL. How to do it in hive ?

A: with t as (select date '2014-10-23' as dt)

select  case
            when dt between cast(concat(date_format(dt,'yyyy'),'-10-01') as date)
                    and     cast(concat(date_format(dt,'yyyy'),'-12-07') as date)

            then datediff (dt,cast(concat(date_format(dt,'yyyy'),'-10-01') as date)) div 7 + 1
        end     as week_number

from    t

+-------------+
| week_number |
+-------------+
|           4 |
+-------------+


text:
Q: Let $k$ be an integer not divisible by $5$. Show that either $k^2-1$ or $k^2+1$ is divisible by $5$.
Let $k$ be an integer not divisible by $5$. Show that either $k^2-1$ or $k^2+1$ is divisible by $5$.

Looking at this mod $5$ it seems that $k$ can be one of the form $k \equiv 1,2,3,4 \pmod{5}$. This would imply that $k^2 \equiv 1,4,9,16 \equiv 1,4,4,1 \pmod{5} \Longrightarrow k^2-1 \equiv0,3,3,0 \pmod{5}$ so $k^2-1$ is divisible by $5$? Similar reasoning could be used for $k^2+1$, but that wouldn't give any zero remainders so $5$ doesn't divide $k^2+1$ right?
I feel like I'm missing something since it seems that $k^2-1$ could also give a remainder $3$?

A: I wouldn't get so "sophisticated"- just do the calcuations.
(Edited so Dietrich Burde won't be annoyed with me!)
If k is not a multiple or 5 we have one and only one of
a)k= 5n+ 1 so $k^2= 25n^2+ 10n+ 1$.
$k^2- 1= 25n^2- 10n= 5(5n^2- 2n)$.
b)k= 5n+ 2 so $k^2= 25n^2+ 20n+ 4$.  $k^2+ 1= 25n^2+ 20n+ 5= 5(5n^2+ 4n+ 1)$.
c)k= 5n+ 3 so $k^2= 25n^2+ 30n+ 9$.  $k^2+ 1= 25N^2+ 30n+ 10= 5(5n^2+ 6n+ 2)$.
d)K= 5N+ 4 so $k^2= 25n^2+ 40n+ 16$. $k^2- 1= 25n^2+ 40N+ 15= 5(5n^2+ 8n+ 3)$.

A: We must have $k \equiv 1,2,3,4 \pmod 5$. Working$\pmod5$ one finds the following:
$k \equiv 1 \implies k^{2}-1 \equiv 0$
$k \equiv 2 \implies k^{2}+1\equiv5\equiv0$
$k \equiv 3 \implies k^{2} + 1 \equiv 10 \equiv 0$
$k \equiv 4 \implies k^{2} - 1 \equiv 15 \equiv 0$.


text:
Q: Create submenus in modx revolution using wayfinder I have Resources and I want to create submenu .
like i have resources
Home
About us
Services
Blogs
Service1
service 2
service 3
Now i want to create submenu like

Home

SERVICES

service1

service2</ul

service3</ul

Blogs

service1

service2</ul

service3</ul

Means same link under 2 different menus but with different url , How can i do this using wayfinder in Modx revolution.
Currently service1 , 2  3  don't have parent resource.

A: You could move Service 1, 2 and 3 under Services (as child docs). Then you could make three additional child resources under Blogs, and make each one of those a symlink to Service 1, 2, or 3.
MODX Symlinks RTM

A: Wayfinder will do this out of the box. You need to create the structure in the site tree in MODX using a Symlinks. Symlinks in MODX allow you to publish a Resource in another location and that Resource can have its own unique alias/URL.


text:
Q: How to apply simple patch (reverse detected) I'm trying to create and apply a simple patch to fix a bug with gradle.
I copy the file (/usr/bin/gradle) to my working directory, then make the change.  I then create the patch:
diff -u /usr/bin/gradle gradle > gradle.patch

Then I attempt to apply it:
sudo patch < gradle.patch
Reversed (or previously applied) patch detected!  Assume -R? [n]

If I proceed anyway, it fails.  I have tried generating the patch with the files reversed, and in this case it applies "successfully," but does nothing.
The generated patch looks like this:
--- /usr/bin/gradle 2013-09-09 16:47:58.000000000 -0400
+++ gradle  2015-10-13 11:39:36.005269565 -0400
@@ -67,7 +67,8 @@

 CLASSPATH=$APP_HOME/lib/gradle-launcher-1.4.jar

-export JAVA_HOME=/usr/lib/jvm/default-java
+# commenting out as per (https://stackoverflow.com/a/22309017)
+# export JAVA_HOME=/usr/lib/jvm/default-java

 # Determine the Java command to use to start the JVM.
 if [ -n "$JAVA_HOME" ] ; then

I have tried editing the file paths at the top of the patch to both be /usr/bin/gradle, however this doesn't help.
I have also tried passing -p0, in which case it give:
Ignoring potentially dangerous file name /usr/bin/gradle
can't find file to patch at input line 3
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|--- /usr/bin/gradle    2013-09-09 16:47:58.000000000 -0400
|+++ /usr/bin/gradle    2015-10-13 11:39:36.005269565 -0400
--------------------------
File to patch: /usr/bin/gradle
File /usr/bin/gradle is not a regular file -- refusing to patch
1 out of 1 hunk ignored -- saving rejects to file /usr/bin/gradle.rej

When I specify the file in this case, it still fails.
This seems like a simple task, what am I doing wrong?

A: You need to patch the right file.
The way you call it, it will try to patch the new file and thus correctly assumes a reversed patch.
Try to copy an old version of the file to your current directory and the patch will apply.
Regarding your -p0 test: do you have permission to modify /usr/bin/gradle?
Do you have permission to create files in /usr/bin?
Also note that there are deviating rules for getting the filename to patch.
The rules used by gpatch are different from both the original patch and the POSIX patch standard.
Note that the "not a regular file" message is specific to gpatch. Please list the file /usr/bin/gradle. The message is only printed when the file is not a regular file, so something looks strange.
So the solution is:
patch only patches plain files but the file you like to patch is a symbolic link.
If you have a copy of the plain (old version) file in your current directory, patch will do what you expect.
BTW: the usual rule for getting the file name to patch is to look for the shortest name as the usual naming convention is to use:
file.orig
and
file


text:
Q: Hibernate Data Not inserted in database hello i am using hibernate simple example and i am not know more about hibernate
here my example is running successful but data are not inserted in the database i can't understand
this is my code
package com;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Hibernate example to inset data into Contact table
 */
public class FirstExample {
  public static void main(String[] args) {
  Session session = null;

  try{
  // This step will read hibernate.cfg.xml

  SessionFactory sessionFactory = new

Configuration().configure().buildSessionFactory();
 session =sessionFactory.openSession();
  //Create new instance of Contact and set

 System.out.println("Inserting Record");
  ContactDetails contact = new ContactDetails();
  contact.setId(3);
  contact.setFirstName("Deepak");
  contact.setLastName("Kumar");
  contact.setEmail("deepak_38@yahoo.com");
  session.save(contact);
  System.out.println("Done");
  }catch(Exception e){
  System.out.println(e.getMessage());
  }finally{
  // Actual contact insertion will happen at this step
  session.flush();
  session.close();

  }

  }
}

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
    <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/hibernateexample</property>
    <property name="connection.username">root</property>
    <property name="connection.password">admin</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="myeclipse.connection.profile">hibernateexample</property>
    <mapping resource="contact.xml" />

</session-factory>

</hibernate-configuration>

package com;

public class ContactDetails {
  private String firstName;
  private String lastName;
  private String email;
  private long id;

  /**
 * @return Email
 */
  public String getEmail() {
  return email;
  }

  /**
 * @return First Name
 */
  public String getFirstName() {
  return firstName;
  }

  /**
 * @return Last name
 */
  public String getLastName() {
  return lastName;
  }

  /**
 * @param string Sets the Email
 */
  public void setEmail(String string) {
  email = string;
  }

  /**
 * @param string Sets the First Name
 */
  public void setFirstName(String string) {
  firstName = string;
  }

  /**
 * @param string sets the Last Name
 */
  public void setLastName(String string) {
  lastName = string;
  }

  /**
 * @return ID Returns ID
 */
  public long getId() {
  return id;
  }

  /**
 * @param l Sets the ID
 */
  public void setId(long l) {
  id = l;
  }

}

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="com.ContactDetails" table="CONTACT">
   <id name="id" type="long" column="ID" >
   <generator class="assigned"/>
  </id>

  <property name="firstName">
   <column name="FIRSTNAME" />
  </property>
  <property name="lastName">
  <column name="LASTNAME"/>
  </property>
  <property name="email">
  <column name="EMAIL"/>
  </property>
 </class>
</hibernate-mapping>

why data not inserted in database

A: try using transaction.
Add the codes in the FirstExample class.
Transaction tx=session.beginTransaction(); // Add this soon after initializing session object

tx.commit() // just before saving the session

A: The mapping should be
and the XML file accordingly should be of the same name.
Check out this tutorial :
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html


text:
Q: Throw an error when the error comes in the payload of a 200 status code I have one API that returns errors in several ways (I know it's not very good idea but it's a legacy API). I have to concatenate three API calls only if the previous call is successful, I have working this approach except for some cases that returns errors in payload (With a 200 status). For do this I want to use Spring Web Client and I do the following:
Mono
        .when(placeOrderCall)
        .doOnSuccess(response -> {
          if (!isSuccesful(response)) {
              throw new Exception("");
          }
        })
        .then(changeSubscription)
        .doOnSuccess(response -> {
          if (!isSuccesful(response)) {
            throw new Exception("");
          }
        })
        .then(httpCall)
        .doOnSuccess(response -> {
          if (!isSuccesful(response)) {
            throw new Exception("");
          }
        })
        .doOnError(error -> System.out.println("Error"))
        .block();

But I can't throw an exception in doOnSuccess...I want to break the flow and send it to doOnError. Is this posible?
Thanks!!!

A: Since, you haven't mentioned why you are not able to throw exception in doOnSuccess so I am guessing that it is because of checked Exception. So, for this, simple solution is to throw RuntimeException like below -
throw new RuntimeException("");

A: Please, read reactor documentation part about handle() method.
Your code can be rewritten as following then:
   Mono
    .when(placeOrderCall)
    .handle((res, sink) -> {
      if (!isSuccesful(response)) {
        sink.error(new Exception(""));
      } else {
        sink.next(res);
      }
    })
    .then(changeSubscription)
    .handle((res, sink) -> {
      if (!isSuccesful(response)) {
        sink.error(new Exception(""));
      } else {
        sink.next(res);
      }
    })
    .then(httpCall)
    .handle((res, sink) -> {
      if (!isSuccesful(response)) {
        sink.error(new Exception(""));
      } else {
        sink.next(res);
      }
    })
    .doOnError(error -> System.out.println("Error"))
    .block();

In case any handle method executes sink.error() the subsequent then() functions won't be called and only the last .doOnError() will be invoked.


text:
Q: The multi-part identifier could not be bound SQL Server error I searched SO and Google for awhile but couldn't seem to find any that related to this error occurring in the set part of the code and if it did occur in that part, the solution didn't help me.
I am trying to use a user inputted weight and subtract it by the total weight. This equals the shrink
SET @Shrink  = @InputWeight -  [ICPL].[OriginalQuantity_Stk];

I also tried it this way and got the same error.
SET @Shrink  = @InputWeight - Sum([ICPL].[OriginalQuantity_Stk]);

The table is called IC_ProductLots and the alias is ICPL
The error I get is:

The multi-part identifier "ICPL.OriginalQuantity_Stk" could not be
  bound.

Here are my joins if that helps at all:
FROM
    (((( IC_Products [PC]
INNER JOIN
    DC_Transactions [DCT] ON [PC].ProductKey = [DCT].ProductKey)
INNER JOIN
    AR_Customers ON [DCT].CustomerKey = AR_Customers.CustomerKey)
INNER JOIN
    IC_ProductLots [ICPL] ON [DCT].LotKey = [ICPL].LotKey)
LEFT OUTER JOIN
    IC_ProductCosts [ICP] ON ICP.ProductKey = PC.ProductKey
                          AND ICP.ProductCostCode = 5)

Let me know if seeing any more code would help.
SET NOCOUNT ON;
DECLARE @PurchaseCost Decimal(19,8);
DECLARE @InputWeight Decimal(19,8);
DECLARE @Shrink Decimal(19,8);

SET @PurchaseCost = 1;
SET @InputWeight = 20;
SET @Shrink  = @InputWeight;

SELECT DISTINCT
     CAST([AR_Customers].[CustomerCode] AS NVARCHAR(40)) + ' - ' + CAST([AR_Customers].[Name] AS NVARCHAR(40)) AS [Supplier]
   , [PC].ProductCode
   , [PC].Description1
   , Count([ICPL].OriginalQuantity_Alt) AS [Boxes]
   , [ICPL].UnitOfMeasure_Alt
   , Sum([ICPL].OriginalQuantity_Stk) AS [Weight]
   , [ICPL].UnitOfMeasure_Stk
   , [ICP].UnitCost AS [Unit Cost]
   , Sum(ROUND([DCT].[Quantity_Stk] *[ICP].[UnitCost], 2)) AS [Total Sales]
   , Avg(([ICPL].[OriginalQuantity_Stk] / [ICPL].[OriginalQuantity_Alt])) AS [Avg. Box Weight]
   , @Shrink AS [Shrink]
 FROM (((( IC_Products [PC]
    INNER JOIN  DC_Transactions [DCT]
     ON [PC].ProductKey = [DCT].ProductKey)
    INNER JOIN  AR_Customers
     ON [DCT].CustomerKey = AR_Customers.CustomerKey)
    INNER JOIN  IC_ProductLots [ICPL]
     ON [DCT].LotKey = [ICPL].LotKey)
    LEFT OUTER JOIN  IC_ProductCosts [ICP]
     ON ICP.ProductKey=PC.ProductKey and ICP.ProductCostCode=5)
 WHERE
    ([ICPL].ProductionDate >= { ts '2015-06-24 00:00:00' }   AND ([ICPL].ProductionDate <= { ts '2015-06-24 00:00:00' } OR [ICPL].ProductionDate Is Null))
AND ((1=1)  AND AR_Customers.CustomerKey IN (124) )
 GROUP BY
     CAST([AR_Customers].[CustomerCode] AS NVARCHAR(40)) + ' - ' + CAST([AR_Customers].[Name] AS NVARCHAR(40))
   , [PC].ProductCode
   , [PC].Description1
   , [ICPL].UnitOfMeasure_Alt
   , [ICPL].UnitOfMeasure_Stk
   , [ICP].UnitCost
   , [ICPL].ProductionDate
   , AR_Customers.CustomerKey
 ORDER BY
     CAST([AR_Customers].[CustomerCode] AS NVARCHAR(40)) + ' - ' + CAST([AR_Customers].[Name] AS NVARCHAR(40))

Would it be easier if I created another variable that calculated the sum of the original stock and then did @InputWeight - @TotalSum?
Sample Output:
Input weight 1,000
Product Code | Boxes | Weight | Shrink
1234         | 2     | 250    |
2324         | 5     | 225    |
3234         | 4     | 175    |
4234         | 1     | 250    |
______________________________________
Total:       | 12    | 900    | 100
The shrink is the difference of the input weight and the total weight. If it appears in every row that is okay, but the number should appear as 100 in every row if it follows this example.

A: Referencing a field in a SET statement won't work - you need to actually SELECT the data at some point.  Without seeing more of your code, I can't offer any guarantees, but I believe that you are trying to do something like the following:
SET @Shrink  = @InputWeight -
  (
    SELECT Sum([ICPL].[OriginalQuantity_Stk])
    FROM IC_Products [PC]
        INNER JOIN  DC_Transactions [DCT]
         ON [PC].ProductKey = [DCT].ProductKey
        INNER JOIN  AR_Customers
         ON [DCT].CustomerKey = AR_Customers.CustomerKey
        INNER JOIN  IC_ProductLots [ICPL]
         ON [DCT].LotKey = [ICPL].LotKey
        LEFT OUTER JOIN  IC_ProductCosts [ICP]
         ON ICP.ProductKey=PC.ProductKey and ICP.ProductCostCode=5
    WHERE ... -- add in your WHERE clause here
  )


text:
Q: How to clear cached redirects in Chrome How do you clear cached redirects in Chrome?
I changed the DNS for a domain name and when I go to mydomain.com. Even though ping mydomain.com now shows it resolves to the correct IP, if I type in "mydomain.com" into Chrome, it still redirects to mydomain.com/404, which was a redirect automatically setup by the old webhost.
Clearing Chrome's browser cache has no effect, and Chrome seems to ignore /etc/hosts. I tried using a "different" URL, like mydomain.com?123, but Chrome still redirects to mydomain.com/404. Is this a bug or is there someway to clear whatever cache Chrome uses to save 301 redirects?

A: I had a similar issue with a site still re-directing to my.site.com/new-site
and found the 'clear cache'  via internals to work.
Redirects can be caused by a variety of things - caching by your browser, your system, the network, the site configuration itself and any in between steps.
In addition to clearing browsing history and cookies, I also tried the answers from Clear cache for specific domain name in chrome - I suggest trying answers in order of increasing complexity (e.g. start with what you're happiest with and if that doesn't work, try one of the more tricky solutions)
From  https://superuser.com/users/83619/tom-auger

After opening up the developer tools (usually by pressing F12) Click + Hold on the "Reload Page" button. From the popup list, choose "Empty Cache and Hard Reload".

From https://superuser.com/users/87608/euroblaze

Here's how to delete Chrome's cookies selectively by domain or subdomain:
  * go to chrome://settings/content/cookies
  * type the domain name in the search box
  * click delete

A: The only method that worked from me is using Development tools an check on disable cache and the redirection were gone :)
reference

A: On desktop Chrome, deleting the last hour of browsing history works, so long as you've followed the redirect within the last hour.
On Android Chrome, visit chrome://net-internals, click the downward arrow at the top right corner, and choose 'clear cache'. That is the only solution I found for Chrome on Android.

A: If it's an 301 redirect Chrome will cache it. To clear the cache, go to:
Chrome Menu > Settings > Show advanced settings... > Privacy > Click Clear browsing data...

A: Go to chrome://net-internals/#dns and click the Clear Host Cache button

A: On chromium 88
chrome://settings/clearBrowserData
Check "Cached images and files" and click "Clear Data"


text:
Q: GDB doesn't step in function outside one file I try to debug my program with gdb and the step function.
Everything works fine as long as the functions are in the same file.
But if the function is outside, gdb will jump over it.
How can I solve that?
Note:

*

*I compiled with -ggdb options

*I'm using GNU gdb Red Hat Linux (6.7-1rh)
(if that is possible, appeared in startfrequence of gdb)

Example:
#include "foo2.h"  // contains function foo2

void foo(void){ printf("hello"); }

void main (void){

  foo();    // debuggable -> jump into possible
  foo2();   // not debuggable

}

A: When debugging the application with gdb, use si (stepi) instead of ni (nexti). si will step into other functions, ni stays within the current function. Check the documentation at http://sourceware.org/gdb/current/onlinedocs/gdb/Continuing-and-Stepping.html#Continuing-and-Stepping for more (^F for nexti or stepi).


text:
Q: How many concurrent connections were allowed (and was there any caching) on now-legacy Heroku Shared Databases? I'm making the migration from the old Heroku shared database to the equivalent new plan.  Based on my number of total table rows, it appears that the Basic database is the correct fit.
However, Heroku makes the following note when talking about the required migrations:

Please note that dev and basic databases have a limit of 20 connections. If you require more connections, provision a production tier database.

Heroku also now specifies that Dev and Basic have 0MB of cache.
My question is whether the old 5MB/20GB "shared" databases allowed more than 20 connections (or whether there was an limit, and what it was), and where there was any cache.  I'm guessing the answer is no (is there any relation here to number of dynos, btw?), but I can't find the specs in their docs.  Should the answer be yes, then it might change my mind about upgrading to Basic vs. Crane if that would be more equivalent in terms of performance, despite 10M rows being plenty, records-wise.

A: Performance wise, the new dev and basic plans are comparable to the old shared plan.
The connection limit can be though of as the # of dynos connecting to your database. It has nothing to do with performance of the database itself. With a 20 connection limit, that means that you can only have 20 dynos (assuming single threaded code) connecting to your database.
From our experience, if you have >20 dynos, you should be running on a higher capacity database anyway for performance and production capabilities.

A: You should consider a connection pool, either in your application code or as an intermediate layer somewhere.
http://wiki.postgresql.org/wiki/Number_Of_Database_Connections


text:
Q: Outputting an array of react components and having access to parent's "this" using a a prop within child I have an array of components which are all separate views that I am injecting to it's parent via a prop
const steps =
[ <StepOne wizardContext={shippingObj.from} onAction={this.handleFrom}/>,
  <StepTwo wizardContext={shippingObj.to} onAction={this.handleFrom} />,
  <StepThree wizardContext={shippingObj.weight} onAction={this.handleFrom} />,
  <StepFour wizardContext={shippingObj.shippingOption} onAction={this.handleFrom} />,
  <Confirm wizardContext={shippingObj} onAction={this.handleFrom} />
]
<Wizard steps={steps}/>

In the Wizard component I'm rendering each step based on the actual step
{this.props.steps[this.state.compState]}

Also in the wizard component I have a method
  handleFrom(val) {
    let state = val.stage,
    key = Object.keys(val)[0];
    this.setState({
      wizardContext: { ...this.state.wizardContext, [key]: val[key]}
    })
  }

However onAction is undefined meaning it doesn't have access to "this"
If I include each one of them individually within parent wizard component I do have access to this and it works
/*THIS WORKS */
switch (this.state.compState) {
      case 1:
        return <StepOne onAction={this.handleFrom} data={this.state.wizardContext.from} />
      case 2:
        return <StepTwo onAction={this.handleFrom} data={this.state.wizardContext.to} />
      case 3:
        return <StepThree onAction={this.handleFrom} data={this.state.wizardContext} />
      case 4:
        return <StepFour onAction={this.handleFrom} data={this.state.wizardContext.shippingOption} />
      case 5:
        return <Confirm shippingLabel={this.state.wizardContext} labelkeys={this.shippingKeys} />
    }

however I want to decouple the steps from the actual wizard
Is there a way to access this or parent methods from the child if the child is an array of components?  Is there a cleaner way to do this?
the components will render just don't have access to "this" in props
Any constructive feedback is appreciated

A: The problem is that you are creating your array of steps outside of the Wizard component, so the this context does not point back to the Wizard (and therefore does not have the appropriate handleFrom method).
You can fix this problem by dynamically injecting the correct this.handleFrom method as a prop in the Wizard's render method. First, remove the onAction prop from your steps array:
const steps =
[ <StepOne wizardContext={shippingObj.from} />,
  <StepTwo wizardContext={shippingObj.to} />,
  <StepThree wizardContext={shippingObj.weight} />,
  <StepFour wizardContext={shippingObj.shippingOption} />,
  <Confirm wizardContext={shippingObj} />
]
<Wizard steps={steps}/>

Then, replace this line:
{this.props.steps[this.state.compState]}

with this:
{
    React.cloneElement(
      this.props.steps[this.state.compState],
      {onAction: this.handleFrom}
    )
}

Make sure you have this.handleFrom = this.handleFrom.bind(this); in the Wizard's constructor so you bind the appropriate context.
What's happening here is that the context for the steps array has no this.handleFrom. So, you inject the onAction={this.handleFrom} prop inside the Wizard component, where the appropriate context is available. For more information on cloneElement, see this question and answer.


text:
Q: Async loop with mongodb nodejs I have 2 collections in MongoDb : users and images
users is like :
{
"_id": ObjectID("58299fc14705d47ff852f8ae"),
"mail": "Qwerty1@test.test",
"username": "Qwerty1",
"token": "g8m7h0phrvhp774cw0xh9qkt9rhu062r2b3gigm0t1o22zkt9",
 ...,
"images": [
    ObjectID("582c547bb7c5cc391e5a1793"),
    ObjectID("582c54ecb7c5cc391e5a1794")
]
}

images is like :
{
"_id": ObjectID("582c5394b522cb37d701dbe3"),
"user": "g8m7h0phrvhp774cw0xh9qkt9rhu06
"image": base64 encoded
}

I make a find in users to get ids of this user's images and I want to fill an array (
    b64Images
) with a a find request to images collection.
db.collection("users").find({$or : [{ username: req.params.username }, {token : req.params.username}]}).toArray(function (err, result) {
   if(result.length){
      var b64Images = [];
      async.each(result[0].images,
      function(item, callback){
         db.collection("images").find({_id : item}).toArray(function (err, resulta) {
            console.log(resulta[0].user);
            b64Images.push(resulta[0].user);
         });
         callback();
      },
      function(err){
         console.log("finished");
         res.json({images : b64Images});
      }
   }
}

But my problem is that my loop is finished before my find in images's response.
So I have an empty array.
I know this is an asynchronous problem but I can't figure it out.

A: I would use Promise.all() approach.
Way it works is: you collect all your promises into array, than pass that array into Promise.all
You can start with this:
//this would go instead of async.each(result[0].images...
let queryPromises = [];

for (let image in result[0].images){
    // toArray returns Promise if no callback passed
    let queryPromise = db.collection("images").find({_id : item}).toArray();
    //query execution has not started yet, so loop is working fine
    queryPromises.push(queryPromise);
}

queryPromises
    // queries execution starts now
   .then(arrayOfResults => {
      // do stuff with your results here; results arrive all at once
      console.log(arrayOfResults);
   }, err => {
      console.log(err)
   });


text:
Q: Scroll-snap-type is not showing at all in my css code, why? i'm new on this forum, and kinda new also in coding... I'm trying to code a very simple page, and I don't know how to select scroll-snap-type, this option doesn't show at all also in the code suggestions in CSS. I would like to apply scroll- snap to the "blocHorizontal" container I made in HTML...so that the div classes inside of it can be scrolled and centered horizontally. I show you what I'm doing:
<!DOCTYPE html>

        <link rel="stylesheet" href="css/style.css" type="text/css">
        <meta charset="utf8">
        <title>Contre-argument:télécharger n'est pas voler</title>

            <marquee>
Culture libre
</marquee>

And this is the CSS:
body {
background-color: yellow;
display: flex;
margin: 0;
padding: 0;
font-family: serif;
}
.slide {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 100px;
}
.blocHorizontal {
height: 100vh;
display: flex;
flex-direction: row;
overflow: scroll;
}
.one {
height: 100vh;
background-image: url("../images/gnegne3.jpg");
background-size: 200%;
}
.two {
height: 100vh;
background-image: url("../images/gnegne4.jpg");
background-size: 200%;
}
.three {
height: 100vh;
background-image: url("../images/gnegne5.jpg");
background-size: 200%;
}
.four {
height: 100vh;
background-image: url("../images/gnegne6.jpg");
background-size: 200%;
}

Any suggestions???I might have done simple errors, I'm really not an expert in coding fo no Thanks in advance :-)


text:
Q: JAVA Web Service with SOAP Client Objective C---Response problem I have this web service in Java:
@WebService(serviceName = "Catalogo_V1")
public class Catalogo_V1 {

    /** This is a sample web service operation */
    @WebMethod(operationName = "hello")
    public String hello(@WebParam(name = "name") String txt)
    {
        return "Hello " + txt + " !";
    }
}

and this part in Objective C (after generate code with WSDL2ObjC):
- (IBAction)buttonPressed:(id)sender
{

    Catalogo_V1PortBinding *binding = [[Catalogo_V1Svc Catalogo_V1PortBinding] initWithAddress:@"http://localhost:8080/WSServer/Catalogo_V1.wsdl"];
    binding.logXMLInOut = YES;  // to get logging to the console.

    Catalogo_V1Svc_hello *r = [[Catalogo_V1Svc_hello alloc] init];

    //NSLog(@"request: %@",r);

    [r setName:i.text];
    //NSLog(@"string: %@ ",i.text);

    Catalogo_V1PortBindingResponse *resp = [binding helloUsingParameters:(Catalogo_V1Svc_hello *)r];

    NSLog(@"response: %@",resp);

    for (id mine in resp.bodyParts)
    {
        if ([mine isKindOfClass:[Catalogo_V1Svc_helloResponse class]])
        {
            //lab.text = [mine Catalogo_V1Svc_helloResponse];
        }
    }
}

and my console show this messages:
2
011-08-30 17:00:11.572 Catalogo-V1[3876:207] OutputHeaders:
{
    "Content-Length" = 451;
    "Content-Type" = "text/xml; charset=utf-8";
    Host = localhost;
    Soapaction = "";
    "User-Agent" = wsdl2objc;
}
2011-08-30 17:00:11.572 Catalogo-V1[3876:207] OutputBody:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:Catalogo_V1Svc="http://org/" xsl:version="1.0">
  <soap:Body>
    <Catalogo_V1Svc:hello>
      <Catalogo_V1Svc:name>ddddddd</Catalogo_V1Svc:name>
    </Catalogo_V1Svc:hello>
  </soap:Body>
</soap:Envelope>
2011-08-30 17:00:11.593 Catalogo-V1[3876:207] Response HTTP:
<NSHTTPURLResponse: 0x5b1ffd0>
2011-08-30 17:00:11.593 Catalogo-V1[3876:207] ResponseStatus: 404
2011-08-30 17:00:11.593 Catalogo-V1[3876:207] ResponseHeaders:
{
    "Content-Length" = 1067;
    "Content-Type" = "text/html";
    Date = "Tue, 30 Aug 2011 15:00:11 GMT";
    Server = "GlassFish Server Open Source Edition 3.1.1";
    "X-Powered-By" = "Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.1 Java/Apple Inc./1.6)";
}
2011-08-30 17:00:11.617 Catalogo-V1[3876:207] ResponseError:
Error Domain=Catalogo_V1PortBindingResponseHTTP Code=404 "not found" UserInfo=0x5b2a320 {NSLocalizedDescription=not found}
2011-08-30 17:00:11.618 Catalogo-V1[3876:207] response: <Catalogo_V1PortBindingResponse: 0x5b25bd0>

the output its correct but i dont recieve any response....

A: Your server responds with HTTP status 404 (File Not Found), which means that the client is posting its SOAP request to an endpoint (URL) that the server isn't configured to respond to.
For example, your client might be directed at http://localhost:8080/foo
but the server is listening at http://localhost/bar.
Check the endpoint URL on your client and the server configuration to ensure it is listening at the same URL.


text:
Q: MongoDB Aggregation : - how to make a fast mongodb aggregation query I have 2 collections of users and attendances.
I am trying to get user's attendance data from attendance collection and merge them
with lookup and set the condition I want to execute to get attendance data
and then again I set the whole attendance data by using reduce to get less data
and this query takes 1 minute to execute locally with 150mbps internet speed
which is a very very slow execution and guess what i have 1000 user but i am only trying to get 10 users and it taking so long time
I want this to be executed within 300ms
const attendanceData = await User.aggregate([
    {
      $match: {
        lastLocationId: Mongoose.Types.ObjectId(typeId),
        isActive: true,
      },
    },
    {
      $project: {
        _id: 1,
        workerId: 1,
        workerFirstName: 1,
        workerSurname: 1,
      },
    },
    {
      $lookup: {
        from: "attendances",
        localField: "_id",
        foreignField: "employeeId",
        as: "attendances",
      },
    },
    {
      $set: {
        attendances: {
          $filter: {
            input: "$attendances",
            cond: {
              $and: [
                {
                  $gte: ["$$this.Date", new Date(fromDate)],
                },
                {
                  $lte: ["$$this.Date", new Date(toDate)],
                },
                {
                  $eq: ["$$this.createdAs", dataType],
                },
                {
                  $eq: ["$$this.status", true],
                },
                {
                  $eq: ["$$this.workerType", workerType],
                },
              ],
            },
          },
        },
      },
    },
    {
      $set: {
        attendances: {
          $reduce: {
            input: "$attendances",
            initialValue: [],
            in: {
              $concatArrays: [
                "$$value",
                [
                  {
                    _id: "$$this._id",
                    createdAs: "$$this.createdAs",
                    Date: "$$this.Date",
                  },
                ],
              ],
            },
          },
        },
      },
    },
    { $skip: 0 },
    { $limit: 10 },
  ]);


text:
Q: Density of states and boundary conditions: how the density of states is physical if it depends on box size This question is closely related to this one: Why is the density of states required conceptually? Should it be seen as a mathematical trick related to Fourier series?
But it was suggested that I ask this question separately.
My question is about the motivation of defining density of states, and its relationship with the boundary conditions when starting from a discrete situation.
I take a simple example: free propagating waves in 1D, thus a solution of the equation:
$$\partial_x^2 f - \frac{1}{c^2} \partial_t^2 f=0$$
I want to find the density of states and then compute the average energy at temperature $T$ that those waves are containing.
If I want to start from a discretized scenario before going to the continuum, I first have to choose boundary conditions on a "box size" $L$.
Periodic boundary choice:
I allow my waves to verify $f(x+L,t)=f(x,t)$. The wavevectors describing those waves are:
$$k_n=\frac{2 n \pi}{L}, n \in \mathbb{Z}$$
$$\langle E \rangle = 2\sum_{n \geq 0} \hbar \omega_n n_B(\omega_n)$$
Where $\omega_n = c |k_n|$, and $n_B(\omega_n)$ the boson population at frequency $\omega_n$ (and at temperature $T$). The factor "2" is here because of the forward and backward propagating waves. Also, the "gap" between two consecutives frequencies is $\delta \omega_n=2c \frac{\pi}{L}$. Using this remark I will be able to find the continuum limit of this summation. I have:
The factor $2$ is here because of the two directions of propagation. Now, if I want to "go to the continuum", I use the fact that: $E_n = \hbar \omega_n$, and:
$$\sum_{n \geq 0} f_n =\sum_{n \geq 0} f_n \frac{\delta E_n}{\delta E_n}=\frac{L}{2 \pi \hbar c}\sum_{n \geq 0} f_n \delta E_n$$
Thus, I have, for $L \gg 1$
$$ \langle E \rangle \approx \int_0^{+\infty} d E (2*\frac{L}{2 \hbar \pi c}) E \ n_B(E) =  \frac{L}{\hbar \pi c}  \int_0^{+\infty} d E \ E \ n_B(E)$$
It gives me the density of states: $\rho_L(E)=\frac{L}{ \hbar \pi c}$
My questions

*

*How can the density of state be physical as it depends on a fictive length $L$
If you agree with what I wrote, and if the density of states is something physical, I don't understand how it can be here. Indeed it explicitely depends on the fictive length $L$, it cannot be physical because of that. Now, as suggested in some of the answers, in the end of the calculation one has to take $L \to + \infty$. In this case the density of states would diverge. How to make sense of this quantity then ? Is it that we reason with the density of state "per" unit length (which does not diverge). Also, in this example it works, but are we sure that "in general", for more complicated scenarios, the density of state per unit volume would become independent of the box size that has been choosen ?

*

*How to avoid this "trick" of using periodic boundary condition in order to find $\langle E \rangle$
As suggested by some of the answers of the linked post, I could directly work in the continuum by considering delta distribution to define the density of states. It should in the end give the same result. I have no idea of how to proceed to find the same result directly working with the continuum and I am interested to see how the two approaches match. I guess that some "dirac distribution" in the limit $L \to +\infty$ in my calculation but I really don't see how.

*

*Does the choice of boundary conditions matter for the density of states ?

I tried to impose strict boundary conditions, i.e: $f(0,t)=f(L,t)=0$ which gives stationnary modes. The meaning of the modes differ but in the end of the calculation, I found the same density of states and average energy. Is it exactly what is meant by those topics Why are periodic boundary conditions used for the derivation of phonons? Why are periodic boundary conditions used for the derivation of phonons?
The predictions I will make are independent of the boundary condition I will choose ? Is there a nice reference in which this thing is precisely discussed ? In all book that I found they just apply periodic boundary condition without any real justification for that.

A: First, it's important to clarify that very often $L$ is not fictional.  In condensed matter systems, $L$ is genuinely the size of the system.  However, if you're working with a crystal on the scale of millimeters or centimeters in size, this is immense compared to the atomic scale, justifying the use of the $L\rightarrow \infty$ limit.

How can the density of state be physical as it depends on a fictive length $L$?

$\rho(E) \mathrm dE$ is the number of states per unit volume of the system which exist in the range $[E, E+\mathrm dE]$.  More generally, if you have some energy range $R$, then the total number of states in that energy range is given by
$$N(R) = V\int_R \rho(E) \mathrm dE$$
If you have a set of non-degenerate, discrete energy levels (as you do for a particle in a 1D box, for instance), the density of states is formally a sum of delta functions:
$$\rho_L(E) = \frac{1}{L}\sum_{n=1}^\infty \delta\left(E- \frac{n^2 \pi^2 \hbar^2}{2mL^2}\right)$$
which, as you say, explicitly depends on $L$. However, consider what happens when we integrate some function $f(E)$ against $\rho_L$:
$$\int f(E) \rho_L(E) \mathrm dE = \sum_{n=1}^\infty f(E_n) \cdot \frac{1}{L}$$
Note that $\Delta E_n \equiv E_{n+1}-E_n = \frac{(2n+1)\pi^2 \hbar^2}{2mL^2}= \frac{2n+1}{n^2} E_n$, so $\frac{\Delta E_n}{E_n}=\frac{2}{n} + \frac{1}{n^2}$.  Furthermore, $n = \sqrt{\frac{2mL^2 E}{\pi^2\hbar^2}}$, so we have
$$\frac{\Delta E_n}{E_n} = \frac{2\pi \hbar}{L\sqrt{2mE_n}} + \frac{2\pi^2 \hbar^2}{mL^2 E_n} \rightarrow \frac{\pi \hbar}{L}\sqrt{\frac{2}{mE_n}}$$
in the limit of large $N$.  This can be rearranged to yield
$$\frac{1}{L} =\sqrt{\frac{m}{2\pi^2\hbar^2 E_n}} \Delta E_n$$
which means that our original integral becomes
$$\int f(E) \rho_L(E) \mathrm dE = \sum_{n=1}^\infty f(E_n) \left( \sqrt{\frac{m}{2\pi^2\hbar^2}}E_n^{-1/2}\right) \Delta E_n \rightarrow \int f(E) \rho(E) \mathrm dE$$
where $\rho(E) \equiv \sqrt{\frac{m}{2\pi^2\hbar^2 E}}$ is the density of states.
The lesson here is that, in the limit of large $L$, the intuitively-defined but ill-behaved sum of delta functions $\rho_L(E)$ can be "smoothed out" into $\rho(E)$ to first order in $L^{-1}$.  $\rho(E)$ has no explicit $L$-dependence, but its interpretation as the number of states per unit energy per unit volume is an approximation which holds only in the limit of large $L$.

How to avoid this "trick" of using periodic boundary condition in order to find $\langle E\rangle$

In principle, you can work with infinite volume from the outset.  However, it's not difficult to see that the interpretation of the density of states is more subtle here due to the various infinities which are floating around. This is roughly analogous to the situation in classical statistical physics, in which it is useful to discretize phase space into cells of volume $\hbar^3$.
Ultimately, the density of states is important because it quantifies the fact that the energy levels of a system are not uniformly distributed over all possible values.  Different energy ranges have different densities.  The reason this topic is much easier to talk about for a large but finite system is that the energy levels are discrete, so the number in any energy range is finite; for an infinite volume, we can't generically say that the number of states in range $A$ is larger or smaller than the number of states in range $B$ because one or both of those numbers could be infinite.
If the energy eigenstates can be labeled with the continuous variable $k$, then we can define
$$\rho(E) = \int \frac{\mathrm dk}{2\pi} \delta\left( E-\epsilon(k)\right)$$
Being an integral over a delta function, this can be evaluated directly.  Assuming that $\epsilon(k)$ is an even function of $k$, this becomes
$$\rho(E) = \int_0^\infty \frac{\mathrm dk}{\pi}\left|\frac{dk}{d\epsilon}\right|\delta\left(k-\epsilon^{-1}(E)\right) = \frac{1}{\pi}\left|\frac{dk}{d\epsilon}\right|$$
If $\epsilon(k) = \frac{\hbar^2 k^2}{2m}$, we have $\rho(\epsilon)=\sqrt{\frac{m}{2\pi^2\hbar^2 \epsilon}}$.  This reproduces the expression obtained in the $L\rightarrow \infty$ limit of the box-normalized system.
In summary, the expression $\rho(E) = \int \frac{\mathrm dk}{2\pi} \delta\left( E-\epsilon(k)\right)$ is suggestive of an interpretation - roughly, something which quantifies the number of states in an energy interval. Though an integral over delta functions appears somewhat dicey, we find after some manipulation that it is related to the derivative of the dispersion relation (though this relationship may vary somewhat depending on what the dispersion relation actually is).

Does the choice of boundary conditions matter for the density of states ?

No, as you've directly computed yourself.  The spectra of the two Hamiltonians (with fixed and periodic boundary conditions, respectively) are shown here:

The orange circles are for fixed boundary conditions, while the blue circles are for periodic ones.  The spacing between the blue energy levels is twice the spacing between the orange ones, but the blue states are doubly degenerate while the orange ones are nondegenerate.
In the limit as $L\rightarrow 0$, the spacing between these energy levels goes to zero, which means that the spectra (and the density of states) become identical.  For finite $L$, the density of states for periodic and fixed boundaries are not exactly the same.
Physically, this can be understood by noting that the physics of the bulk should be somewhat insensitive to the boundary conditions if the boundaries are very, very far away.  This isn't a hard rule - topological materials feature a very interesting correspondence between their bulk and their boundaries - but it suggests that a physicist who lives in the bulk of a crystal would have a very difficult time obtaining information about the crystal boundaries with any localized experiment.


text:
Q: semantic-ui-calendar-react flicker in .tsx The calendar is flickering Using DateInput in .tsx files
Tried fixing the issue by Why datepicker flicker in React when focus in input field?
App1.tsx
import React, { useState } from "react";
import { DateInput } from "semantic-ui-calendar-react";
import "./styles.css";
import "semantic-ui-css/semantic.min.css";

export default function App1() {
  const [date, setDate] = useState("");
  const handleChange = (event, { name, value }) => {
    setDate(value);
  };
  return (

        App1.tsx - Flicker Fixed after using animation=false but getting build
        error

        <DateInput
          name="date"
          placeholder="Date"
          value={date}
          popupPosition="top right"
          onChange={handleChange}
          animation={false}
        />

  );
}

This throws error Type 'false' is not assignable to type 'SemanticTRANSITIONS'
CodeSandbox
Also, I tried to set the duration property to 0. This works intermittently when there is one DateInput, but I have multiple controls on the page if one of them is open and I open another one, the second one flickers.
If there is any other fix for the flickering, please let me know.

A: Fixed this issue by wrapping the DateInput inside a js component and consuming that component from the tsx file.
Set animation={''} for fixing the issue as animation={false} gives console errors.


text:
Q: python:mysql_config not found when connecting to Mysql DB Im trying to connect mysql through python and have the following packages installed.

apt-get install python-pip
pip install flask
apt-get install python-mysqldb
pip install flask-restful

After searching few of the posts, tried installing the below too: (which doesnt seem to work or is not installing)

apt install libmysqlclient-devel
easy_install mysql-python
pip install MySQL-python

My python version :  Python 2.7.12
In my script im using:
import MySQLdb

And in my command if i try:

python nameserver.py

I get the error as:
import MySQLdb
ImportError: No module named MySQLdb

A: You can solve to use this:
first, install build-essential with this:
apt install build-essential
and then, install libmysqlclient-dev with this:
apt install libmysqlclient-dev
then try install mysqlclient with pip like this:
pip install mysqlclient

A: I recommend you to use PyMysql . I found it quite easy to use .
Here is an example :
    import pymysql

    conn = pymysql.connect(host='localhost', port=3306, user='<username>', passwd='<password>', db='mysql')

    cur = conn.cursor()

    cur.execute("SELECT <Column> FROM <Table>")

Here you can find out more about pyMysql :
https://github.com/PyMySQL/PyMySQL