问:
NoClassDefFoundError when using retrofit 2.4.0 in a module (android library)
Been working on using retrofit in an android library for a project. While, if configured in the app's gradle or if the source of the library is part of the app project, everything seems to be work well.

But, if the library project is proguarded and included in the app as an @aar. There seems to be a obsfucation issue.

Here's my proguard for retrofit in android module project:

```<code>-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Exceptions
-keepattributes RuntimeVisibleAnnotations
-keepattributes RuntimeInvisibleAnnotations
-keepattributes RuntimeVisibleParameterAnnotations
-keepattributes RuntimeInvisibleParameterAnnotations

-keepattributes EnclosingMethod
-keepclasseswithmembers class * {
    @retrofit2.http.* <methods>;
}
-keepclasseswithmembers interface * {
    @retrofit2.* <methods>;
}

# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on RoboVM on iOS. Will not be used at runtime.
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions

# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain service method parameters.
-keepclassmembernames,allowobfuscation interface * {
    @retrofit2.http.* <methods>;
}
# Ignore annotation used for build tooling.
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keep public interface com.mylibrary.interfaces.**
-keep public class com.mylibrary.rest.RetrofitClientInstance
-keep public class com.mylibrary.models.** {*;}

-dontwarn org.xmlpull.v1.**
-dontwarn javax.annotation.**

### OkHttp3
-dontwarn okhttp3.**
-dontwarn okio.**
-dontwarn javax.annotation.**
# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
</code>```

And, this is how my RetrofitClientInstance class look like:

```<code>public class RetrofitClientInstance {

    private static Retrofit retrofit;

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder()
                    .baseUrl(Constants.BASE_API_URL)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
</code>```

And the error that I'm getting:

```<code>java.lang.NoClassDefFoundError: Failed resolution of: Lretrofit2/Retrofit$Builder;
        at com.mylibrary.rest.RetrofitClientInstance.getRetrofitInstance(RetrofitClientInstance.java:15)
        at com.mylibrary.rest.LoginAPIHelper.<init>(LoginAPIHelper.java:29)
        at com.mylibrary.rest.LoginAPIHelper.getInstance(LoginAPIHelper.java:36)
        at com.view.LoginActivity.onCreate(LoginActivity.java:124)
        at android.app.Activity.performCreate(Activity.java:6772)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2715)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2823)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6349)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "retrofit2.Retrofit$Builder" on path: DexPathList[[zip file "/data/app/com.inventaapp-2/base.apk"],nativeLibraryDirectories=[/data/app/com.inventaapp-2/lib/arm, /data/app/com.inventaapp-2/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.mylibrary.rest.RetrofitClientInstance.getRetrofitInstance(RetrofitClientInstance.java:15)
        at com.mylibrary.rest.LoginAPIHelper.<init>(LoginAPIHelper.java:29)
        at com.mylibrary.rest.LoginAPIHelper.getInstance(LoginAPIHelper.java:36)
        at com.inventaapp.view.LoginActivity.onCreate(LoginActivity.java:124)
        at android.app.Activity.performCreate(Activity.java:6772)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2715)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2823)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6349)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
</code>```

I've tried multi-dexing the main app that imports the library. Doesn't affect behavior. Infact if the source is imported as a module in the app project, it works without multi-dexing.

Also, if the aar is imported as library. But if I add the retrofit gradle imports in the main project's gradle. It works in that case too.

What am I missing here? Seems similar issue to this: https://github.com/square/retrofit/issues/1811

FYI, my gradle looks like:

```<code> implementation 'com.google.code.gson:gson:2.8.2'
 implementation 'com.squareup.retrofit2:retrofit:2.4.0'
 implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'
</code>```

Any assistance is much appreciated.

Thanks in advance,
Arnab

答: Issue is fixed in retrofit 2.9.0, just update to the last version.</p>

Body:
Been working on using retrofit in an android library for a project. While, if configured in the app's gradle or if the source of the library is part of the app project, everything seems to be work well.

But, if the library project is proguarded and included in the app as an @aar. There seems to be a obsfucation issue.

Here's my proguard for retrofit in android module project:

-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Exceptions
-keepattributes RuntimeVisibleAnnotations
-keepattributes RuntimeInvisibleAnnotations
-keepattributes RuntimeVisibleParameterAnnotations
-keepattributes RuntimeInvisibleParameterAnnotations

-keepattributes EnclosingMethod
-keepclasseswithmembers class * {
    @retrofit2.http.* <methods>;
}
-keepclasseswithmembers interface * {
    @retrofit2.* <methods>;
}

# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on RoboVM on iOS. Will not be used at runtime.
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions

# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain service method parameters.
-keepclassmembernames,allowobfuscation interface * {
    @retrofit2.http.* <methods>;
}
# Ignore annotation used for build tooling.
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keep public interface com.mylibrary.interfaces.**
-keep public class com.mylibrary.rest.RetrofitClientInstance
-keep public class com.mylibrary.models.** {*;}

-dontwarn org.xmlpull.v1.**
-dontwarn javax.annotation.**

### OkHttp3
-dontwarn okhttp3.**
-dontwarn okio.**
-dontwarn javax.annotation.**
# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase

And, this is how my RetrofitClientInstance class look like:

public class RetrofitClientInstance {

    private static Retrofit retrofit;

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder()
                    .baseUrl(Constants.BASE_API_URL)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

And the error that I'm getting:

java.lang.NoClassDefFoundError: Failed resolution of: Lretrofit2/Retrofit$Builder;
        at com.mylibrary.rest.RetrofitClientInstance.getRetrofitInstance(RetrofitClientInstance.java:15)
        at com.mylibrary.rest.LoginAPIHelper.<init>(LoginAPIHelper.java:29)
        at com.mylibrary.rest.LoginAPIHelper.getInstance(LoginAPIHelper.java:36)
        at com.view.LoginActivity.onCreate(LoginActivity.java:124)
        at android.app.Activity.performCreate(Activity.java:6772)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2715)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2823)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6349)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "retrofit2.Retrofit$Builder" on path: DexPathList[[zip file "/data/app/com.inventaapp-2/base.apk"],nativeLibraryDirectories=[/data/app/com.inventaapp-2/lib/arm, /data/app/com.inventaapp-2/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.mylibrary.rest.RetrofitClientInstance.getRetrofitInstance(RetrofitClientInstance.java:15)
        at com.mylibrary.rest.LoginAPIHelper.<init>(LoginAPIHelper.java:29)
        at com.mylibrary.rest.LoginAPIHelper.getInstance(LoginAPIHelper.java:36)
        at com.inventaapp.view.LoginActivity.onCreate(LoginActivity.java:124)
        at android.app.Activity.performCreate(Activity.java:6772)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2715)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2823)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6349)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)

I've tried multi-dexing the main app that imports the library. Doesn't affect behavior. Infact if the source is imported as a module in the app project, it works without multi-dexing.

Also, if the aar is imported as library. But if I add the retrofit gradle imports in the main project's gradle. It works in that case too.

What am I missing here? Seems similar issue to this: https://github.com/square/retrofit/issues/1811

FYI, my gradle looks like:

 implementation 'com.google.code.gson:gson:2.8.2'
 implementation 'com.squareup.retrofit2:retrofit:2.4.0'
 implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'

Any assistance is much appreciated.

Thanks in advance,
Arnab


来源: stackexchange

问:
Issues making import in python
I'm new with python and I'm trying to import one module for using some functions but I'm having issues with it.
This is my directory:

This is my source path:

```<code>/home/adrian/eclipse-workspace/Desarrollos/desarollos_backend_HLC_filters/website_base_filter_2/controllers/generic_functions.py
</code>```

This is my class inside the file.

```<code>class CustomerPortalFilters(CustomerPortal):

    def hola(self):
        print('que pasa')
</code>```

From the module website_invoice_filter_2 I need to import the file generic_functions.py from website_base_filter_2.

This is my try, but Eclipse IDE cannot resolve it.

```<code>from Desarrollos.desarollos_backend_HLC_filters.website_base_filter_2.controllers.generic_functions import CustomerPortalFilters
</code>```

Thanks for reading.

答:
You need to add __init__.py at the root level in order to use it in the import.

Just create a new empty file named __init__.py and try again. Basically it will tell the interpreter that it is a python directory so that you can use it in other python files.

ContentLicense: CC BY-SA 4.0

Title: Issues making import in python

Body:
I'm new with python and I'm trying to import one module for using some functions but I'm having issues with it.
This is my directory:

This is my source path:

/home/adrian/eclipse-workspace/Desarrollos/desarollos_backend_HLC_filters/website_base_filter_2/controllers/generic_functions.py

This is my class inside the file.

class CustomerPortalFilters(CustomerPortal):

    def hola(self):
        print('que pasa')

From the module website_invoice_filter_2 I need to import the file generic_functions.py from website_base_filter_2.

This is my try, but Eclipse IDE cannot resolve it.

from Desarrollos.desarollos_backend_HLC_filters.website_base_filter_2.controllers.generic_functions import CustomerPortalFilters

Thanks for reading.


问:
Google Firestore - How to get several documents by multiple ids in one round-trip?
I am wondering if it's possible to get multiple documents by a list of ids in one round trip (network call) to the Firestore database.</p>

答:
If you are using flutter, you can do the following:

Firestore.instance.collection('your_collection_name')
  .where(FieldPath.documentId, whereIn:["list", "of", "document", "ids"])
  .getDocuments();
```

This will return a Future containing List<DocumentSnapshot> which you can iterate as you feel fit.

Body:
If you are using flutter, you can do the following:

Firestore.instance.collection('your_collection_name')
  .where(FieldPath.documentId, whereIn:["list", "of", "document", "ids"])
  .getDocuments();

This will return a Future containing List<DocumentSnapshot> which you can iterate as you feel fit.


问:
Why is it necessary to have default constructor in this when i already have one constructor
Why is it necessary to have a default constructor in this case I mean if in class car if I add car(){}function then no error is being shown!! but I already have one constructor car(int p,string s)</p>

```<code>#include<iostream>
using namespace std;
class car{
    int price;
    int model_no;
    string name;
    public:
    void print(){
        cout<<name<<endl;cout<<price<<endl;
    }
    car(int p,string s){
        price=p;
        name=s;
    }
    car(car&x){
        price=x.price;
    }

};
int main(){
    car a;
    a(5,"BMW");
    a.print();
    //cout<<a.name;
    //cout<<sizeof(car);
    return 0;
}
</code>```

答:
```<code>car a;
</code>```

tries to  call the standard constructor, because you give no parameters. But there is no standard constructor, so it's requesting one.

```<code>a(5, "BMW");
</code>```

tries to call an operator () but there is no operator like this.

Simply write car a(5, "BMW"); instead of car a; a(5, "BMW")

Body:
Why is it necessary to have a default constructor in this case I mean if in class car if I add car(){}function then no error is being shown!! but I already have one constructor car(int p,string s)

#include<iostream>
using namespace std;
class car{
    int price;
    int model_no;
    string name;
    public:
    void print(){
        cout<<name<<endl;cout<<price<<endl;
    }
    car(int p,string s){
        price=p;
        name=s;
    }
    car(car&x){
        price=x.price;
    }

};
int main(){
    car a;
    a(5,"BMW");
    a.print();
    //cout<<a.name;
    //cout<<sizeof(car);
    return 0;
}

Body:
car a;

tries to  call the standard constructor, because you give no parameters. But there is no standard constructor, so it's requesting one.

a(5, "BMW");

tries to call an operator () but there is no operator like this.

Simply write car a(5, "BMW"); instead of car a; a(5, "BMW")


问:
IF statement being ignored. Function not supposed to execute when IF is not fulfilled, but still does
I'm not sure why my IF statement is being ignored. The function is not supposed to execute if the IF statement is not being met. Here's the code:</p>

```<code>function myFormSubmit(e) {
  var timestamp = e.values[0];
  var type = e.values[2];
  var taxNumber = e.values[3];
  var title = e.values[15];
  var surname = e.values[16];
  var fullNames = e.values[17];
  var ID = e.values[18];

  var file = DriveApp.getFileById("1pWe4TBF3_mlqglfoIrTO8d6O2fSra27lPt0Iy9Tjwjw");

  var folder = DriveApp.getFolderById("17F678vzKcE7AaVqef0k-f96uHCOJeotv");

  var copy = file.makeCopy(surname + ',' + fullNames, folder);

  var doc = DocumentApp.openById(copy.getId());

  var body = doc.getBody();

  if (type = "Personal Financial Services") {

  body.replaceText("{{FullNames}}", fullNames);
  body.replaceText("{{Surname}}", surname);
  body.replaceText("{{ID}}", ID);
  body.replaceText("{{IncomeTaxNumber}}", taxNumber);
  body.replaceText("{{Title}}", title)

  doc.saveAndClose();
  }
}
</code>```

答:
one equal sign is assignment

eg var type = "somevalue"

for equalty use == or === sign

in your case value is assigned to type variable so that ie true.

Body:
I'm not sure why my IF statement is being ignored. The function is not supposed to execute if the IF statement is not being met. Here's the code:

function myFormSubmit(e) {
  var timestamp = e.values[0];
  var type = e.values[2];
  var taxNumber = e.values[3];
  var title = e.values[15];
  var surname = e.values[16];
  var fullNames = e.values[17];
  var ID = e.values[18];

  var file = DriveApp.getFileById("1pWe4TBF3_mlqglfoIrTO8d6O2fSra27lPt0Iy9Tjwjw");

  var folder = DriveApp.getFolderById("17F678vzKcE7AaVqef0k-f96uHCOJeotv");

  var copy = file.makeCopy(surname + ',' + fullNames, folder);

  var doc = DocumentApp.openById(copy.getId());

  var body = doc.getBody();

  if (type = "Personal Financial Services") {

  body.replaceText("{{FullNames}}", fullNames);
  body.replaceText("{{Surname}}", surname);
  body.replaceText("{{ID}}", ID);
  body.replaceText("{{IncomeTaxNumber}}", taxNumber);
  body.replaceText("{{Title}}", title)

  doc.saveAndClose();
  }
}


问:
Is there a way to concatenate strings in html attributes?
I'm using MVC3 and I wanted to use a partial view to create dynamic DOM elements. This is my current partial view:

```<code>@model MVCApp.ViewModels.TitlesViewModel

<div class="display-label">Name</div>
<div id="label"+"@Model.Id" class="display-field">@Model.InitValue</div>
</code>```

Model.Id is 1 but in the HTML in the browser, I currently get:

```<code>id="label"+"1"
</code>```

So if I try and do something like:

```<code>alert($("#label1").text())
</code>```

There's an alert box with nothing in it.

So how can I add the two strings together to form one coherent string that is recognized by jQuery (or document.getElementByID(str) for that matter).

答:
Here is what you need to do.

```<code>id="label_@Model.Id"
</code>```

Underscore(_) is required.For me passing id without Underscore made an issue. Happy conding.

ContentLicense: CC BY-SA 3.0

Body:
I'm using MVC3 and I wanted to use a partial view to create dynamic DOM elements. This is my current partial view:

@model MVCApp.ViewModels.TitlesViewModel

Name

@Model.InitValue

Model.Id is 1 but in the HTML in the browser, I currently get:

id="label"+"1"

So if I try and do something like:

alert($("#label1").text())

There's an alert box with nothing in it.

So how can I add the two strings together to form one coherent string that is recognized by jQuery (or document.getElementByID(str) for that matter).

Body:
Here is what you need to do.

id="label_@Model.Id"

Underscore(_) is required.For me passing id without Underscore made an issue. Happy conding.


问:
SSH check to remote gerrit with server name not working
Environment:-

```<code>ProductName:    Mac OS X
ProductVersion: 10.15.4
BuildVersion:   19E287
</code>```

Problem:-

SSH connection check to remote gerrit server with server name not working. where as it works with IP address

```<code> With IP Address:-

  ssh -T -p 29418 ramesh@40.41.42.43

  ****    Welcome to Gerrit Code Review    ****
  Hi Ramesh, you have successfully connected over SSH.

  Unfortunately, interactive shells are disabled.
  To clone a hosted Git repository, use:

  git clone ssh://ramesh@gerrit.server.com:29418/REPOSITORY_NAME.git
</code>```

With server name:-

```<code>ssh -Tvvv -p 29418 ramesh@gerrit.server.com
    OpenSSH_8.1p1, LibreSSL 2.7.3
    debug1: Reading configuration data /etc/ssh/ssh_config
    debug1: /etc/ssh/ssh_config line 47: Applying options for *
    debug1: Connecting to gerrit.server.com port 29418.
</code>```

i have added the server name in MAC OS's host file but still it is hanging. Is it something issue with OpenSSH?

答: Mac OS upgraded to ProductVersion: 10.15.5 and in this it is working fine.</p>

Body:
Environment:-

ProductName:    Mac OS X
ProductVersion: 10.15.4
BuildVersion:   19E287

Problem:-

SSH connection check to remote gerrit server with server name not working. where as it works with IP address

 With IP Address:-

  ssh -T -p 29418 ramesh@40.41.42.43

  ****    Welcome to Gerrit Code Review    ****
  Hi Ramesh, you have successfully connected over SSH.

  Unfortunately, interactive shells are disabled.
  To clone a hosted Git repository, use:

  git clone ssh://ramesh@gerrit.server.com:29418/REPOSITORY_NAME.git

With server name:-

ssh -Tvvv -p 29418 ramesh@gerrit.server.com
    OpenSSH_8.1p1, LibreSSL 2.7.3
    debug1: Reading configuration data /etc/ssh/ssh_config
    debug1: /etc/ssh/ssh_config line 47: Applying options for *
    debug1: Connecting to gerrit.server.com port 29418.

i have added the server name in MAC OS's host file but still it is hanging. Is it something issue with OpenSSH?


问:
Can we add additional Jmeter Load generators during the test execution?
We are running test from distributed master slave machines. We need to add additional load generators during the execution of test whenever the memory consumption of the slaves increase from a certain threshold.
Main Question: Can we add more ips(slave machines/load generators) in the jmeter cmd during execution.    </p>

答: I think you can not add additional slaves machine once test started. Alternatively, you can start separate new test.</p>


问:
Spring Data and native query with like statement
I have the following repository definition:

```<code>public interface InstructionRepository extends JpaRepositoryWithSpecification<Instruction> {

    String FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY =
            "SELECT * FROM instruction i WHERE i.invoice_documents_trackings like '%:trackingId%'";

    @Query(value = FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY, nativeQuery = true)
    List<Instruction> findByFileTrackingsContaining(@Param("trackingId") String trackingId);
}
</code>```

The reason why I use native query here is because invoice_documents_trackings column represents a map serialized to json string. So basically I want to find all instructions that have particular trackingId stored in the invoice_documents_trackings map.

When I execute the method I always get 0 results despite the fact that If I execute the same query manually I get expected results.

I also tried to change the query so that it looks like:

```<code>String FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY =
        "SELECT * FROM instruction i WHERE i.invoice_documents_trackings like %:trackingId%"
</code>```

And this does not work either.

Would really appreciate any help, than

答:
I think the issue is the way you're using %

```<code>String FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY =
        "SELECT * FROM instruction i WHERE i.invoice_documents_trackings like CONCAT('%', :trackingId, '%')"
</code>```

Body:
I have the following repository definition:

public interface InstructionRepository extends JpaRepositoryWithSpecification<Instruction> {

    String FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY =
            "SELECT * FROM instruction i WHERE i.invoice_documents_trackings like '%:trackingId%'";

    @Query(value = FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY, nativeQuery = true)
    List<Instruction> findByFileTrackingsContaining(@Param("trackingId") String trackingId);
}

The reason why I use native query here is because invoice_documents_trackings column represents a map serialized to json string. So basically I want to find all instructions that have particular trackingId stored in the invoice_documents_trackings map.

When I execute the method I always get 0 results despite the fact that If I execute the same query manually I get expected results.

I also tried to change the query so that it looks like:

String FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY =
        "SELECT * FROM instruction i WHERE i.invoice_documents_trackings like %:trackingId%"

And this does not work either.

Would really appreciate any help, than

Body:
I think the issue is the way you're using %

String FIND_INSTRUCTIONS_BY_TRACKING_ID_QUERY =
        "SELECT * FROM instruction i WHERE i.invoice_documents_trackings like CONCAT('%', :trackingId, '%')"


问:
NRWL NX importing lib error TS2307: Cannot find module '@eduboard/interfaces'
I've just created a new NX project for work and I've created a lib for out interfaces to have them on the backend and the front end.

I'm getting this error when I compile

```<code>apps/askeddi/src/app/pages/global-admin/global-admin.component.ts(5,38): error TS2307: Cannot find module '@eduboard/interfaces'.
</code>```

From everything i have read is that i have done nothing wrong but its asking for a module and its just an index.ts file.

```<code>export * from './lib/user';
export * from './lib/global-admin-dashboard';
</code>```

And this the global-admin-dashboard

```<code>interface Schools {
  total: number;
  active: number;
  usingAssessor: number;
}

interface TotalNActive {
  total: number;
  active: number;
}

export interface GlobalAdminDashboard {
  schools: Schools;
  schoolGroups: TotalNActive;
  users: TotalNActive;
}

</code>```

答:
You need to specify the location of your library for TypeScript to locate.

Add your library to the tsconfig.json at the root of your project under "paths":

```<code>{
  "compilerOptions": {
    ...
    "paths": {
      "@package/my-lib": ["libs/my-lib/src/index.ts"]
    }
  }
}
</code>```

You may need to reload VSCode to have TypeScript reload the tsconfig.json.

Body:
I've just created a new NX project for work and I've created a lib for out interfaces to have them on the backend and the front end.

I'm getting this error when I compile

apps/askeddi/src/app/pages/global-admin/global-admin.component.ts(5,38): error TS2307: Cannot find module '@eduboard/interfaces'.

From everything i have read is that i have done nothing wrong but its asking for a module and its just an index.ts file.

export * from './lib/user';
export * from './lib/global-admin-dashboard';

And this the global-admin-dashboard

interface Schools {
  total: number;
  active: number;
  usingAssessor: number;
}

interface TotalNActive {
  total: number;
  active: number;
}

export interface GlobalAdminDashboard {
  schools: Schools;
  schoolGroups: TotalNActive;
  users: TotalNActive;
}

Body:
You need to specify the location of your library for TypeScript to locate.

Add your library to the tsconfig.json at the root of your project under "paths":

{
  "compilerOptions": {
    ...
    "paths": {
      "@package/my-lib": ["libs/my-lib/src/index.ts"]
    }
  }
}

You may need to reload VSCode to have TypeScript reload the tsconfig.json.


问:
ST_BUFFER in google bigquery?
To create a polygon around a pair of lat+lon coordinates I'd expect to be able to buffer the geogpoint:

e.g. ST_BUFFER(ST_GEOGPOINT(lat, lon), 1000)

This creates a circular polygon with a radius of 1000m.

Bigquery doesn't seem to have the buffer function, which seems like a really basic one - am I missing something? Thanks!

答:
As for now, ST_BUFFER function is not supported in query engine yet. All available geography functions in Standard SQL you can see here. Additionally, you can think about using buffer function from the open source library Turf.JS to make buffers and use it in BigQuery:

```<code>jslibs.turf.ST_BUFFER(geometry_to_buffer GEOGRAPHY, radius NUMERIC, units STRING, steps NUMERIC)
</code>```

Please follow carto tutorial to learn more about using this function.

Title: ST_BUFFER in google bigquery?

Body:
As for now, ST_BUFFER function is not supported in query engine yet. All available geography functions in Standard SQL you can see here. Additionally, you can think about using buffer function from the open source library Turf.JS to make buffers and use it in BigQuery:

jslibs.turf.ST_BUFFER(geometry_to_buffer GEOGRAPHY, radius NUMERIC, units STRING, steps NUMERIC)

Please follow carto tutorial to learn more about using this function.


问:
Change JavaScript code to only expand next row, not all next rows in table
I'm very new to this and trying to work out how something works that someone previous to me has implemented and I need to alter.

We have a table with say 3 or 4 headers and at present one row below it.
JavaScript is used so that upon clicking on a row, it expand to display the next row.

What I'm trying to do is have another table within one of the rows that only shows after expanding.

            $(document).ready(function(){
            $("#report66 tr:odd").addClass("odd");
            $("#report66 tr:not(.odd)").hide();
            $("#report66 tr:first-child").show();
            $("#report66 tr.odd").click(function(){
                $(this).next("tr").toggle();
                $(this).find(".arrow").toggleClass("up");
            });
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table.tableSection {
        display: table;
        width: 500%;
    }
    .table.tableSection thead, table.tableSection tbody {
        float: left;
        width: 100%;
    }
    .table.tableSection tbody {
        overflow: auto;
        height: 250px;
    }
    .table.tableSection tr {
        width: 100%;
        display: table;
        text-align: left;
    }
    .table.tableSection th, table.tableSection td {
        width: 33%;
    }
    .td, th {
     border: 1px solid #dddddd;
     text-align: left;
     padding: 5px;
     background-color: #00565c;
     color: white;
 }</code>```

        Header1
        Header2
        Header3
        Header4

        Data1
        Data2
        Data3
        Data4

    Information
    Information

        Test

        Test

```
</div>
</div>
</p>

<p>So with this you can see that upon selecting the first row of data it expands and shows the next row. The table within that row, is collapsed and you have to expand this.</p>

<p>Main question is, how can I change this so that the 2nd table is not collapsed? (I'm not bothered about collapsing it)</p>

<p>There are a lot of different methods of achieving this but every single one I find, doesn't seem to fit what I need.</p>

<p><strong>EDIT WITH ORIGINAL CODE SNIPPET</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#report66 tr.information-row').hide();
    $("#report66 tr:not(.information-row)").click(function(){
 $('#report66 tr.information-row').toggle();
  });
});
    </script>
    <style>
    .new table {
  table-layout: fixed;
  width: 100% ;
}
</style>

<?php

 if($replacementpending >= 1)
   {

echo "<h4><center><b>Network | Pending Acceptance</b></center></h4>";

   $sql = "SELECT * FROM  `stock`.`replacements.joblog` WHERE `status` = 'Pending' AND `ownership` = 'Stock' ORDER BY `id` ASC";
   $retval = mysqli_query( $conn, $sql );

   if(! $retval ) {
      die('Could not get data: ' . mysqli_error());
   }
 echo
     "<table border='1'>
        <table id='report66'>
            <tr>
            <th style='background-color:#003033'>DB Ref</th>
            <th style='background-color:#003033'>Ticket Ref</th>
            <th style='background-color:#003033'>Item Requested</th>
            <th style='background-color:#003033'>Customer</th>
            <th style='background-color:#003033'><center><span class='glyphicon glyphicon-circle-arrow-down'></span></center></th>
        </tr>";
   while($row = mysqli_fetch_array($retval)) {
        echo "<tr>";
        echo
        "<td>{$row['id']}</td>".
         "<td>{$row['req_ticketref']}</td>".
        "<td>{$row['req_model']}</td>".
        "<td>{$row['req_customer']}</td>".
        "<td style='table-layout: fixed; width: 3%'><center><span class='glyphicon glyphicon-circle-arrow-down'></span></center></td>";
    }
echo
       "
       <tr class='information-row' style='background-color:#00181a'>
       <td colspan='8' style='background-color:#00181a'>
       ";
    echo "
    <center><h4><b>Additional information</b></h4>
       <table style='table-layout: fixed; width: 70%'>
       <th style='background-color:#003033;text-align:right'>CI Name</th><td>{$row['ciref']}</td><tr>
       <th style='background-color:#003033;text-align:right'>Requested By</th><td>{$row['req_name']}</td><tr>
       <th style='background-color:#003033;text-align:right'>Ticket Reference</th><td>{$row['req_ticketref']}</td><tr>
       <th style='background-color:#003033;text-align:right'>Customer</th><td>{$row['req_customer']}</td><tr>
       <th style='background-color:#003033;text-align:right'>Date/Time Logged</th><td>{$row['datetimelogged']}</td><tr>
        </table>
        <br>
        <legend></legend>
    <h4><b>Delivery Details</b></h4>
        <table style='table-layout: fixed; width: 70%'>
        <th style='background-color:#003033;text-align:right'>End User Company Name</th><td>{$row['endusername']}</td><tr>
        <th style='background-color:#003033;text-align:right'>Address Line 1</th><td>{$row['address1']}</td><tr>
        <th style='background-color:#003033;text-align:right'>Address Line 2</th><td>{$row['address2']}</td><tr>
        <th style='background-color:#003033;text-align:right'>City</th><td>{$row['city']}</td><tr>
        <th style='background-color:#003033;text-align:right'>Post Code</th><td>{$row['postcode']}</td><tr>
        <th style='background-color:#003033;text-align:right'>Country</th><td>{$row['country']}</td><tr>
        </table>
        <br>
        </center>
       </td>
       </tr>
       ";

   }
   echo "</table>";
  }
  ?></code>```

答:
When you do $("#report66 tr:not(.odd)").hide(); you actually hide all tr elements inside the main table, which do not have the .odd class name. Since you have another table inside the main one, this rule applies to the tr elements in it.

You can explicitly show all rows in the inner table:

            $(document).ready(function(){
            $("#report66 tr:odd").addClass("odd");
            $("#report66 tr:not(.odd)").hide();
            $("#report66 tr:first-child").show();
            $("#report66 tr table tr").show(); // Show all inner table rows
            $("#report66 tr.odd").click(function(){
                $(this).next("tr").toggle();
                $(this).find(".arrow").toggleClass("up");
            });
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table.tableSection {
        display: table;
        width: 500%;
    }
    .table.tableSection thead, table.tableSection tbody {
        float: left;
        width: 100%;
    }
    .table.tableSection tbody {
        overflow: auto;
        height: 250px;
    }
    .table.tableSection tr {
        width: 100%;
        display: table;
        text-align: left;
    }
    .table.tableSection th, table.tableSection td {
        width: 33%;
    }
    .td, th {
     border: 1px solid #dddddd;
     text-align: left;
     padding: 5px;
     background-color: #00565c;
     color: white;
 }</code>```

        Header1
        Header2
        Header3
        Header4

        Data1
        Data2
        Data3
        Data4

    Information
    Information

        Test

        Test

```
</div>
</div>
</p>

<p><strong>EDIT</strong>  </p>

<p>If you want to have multiple visible cells, which toggle the visibility of the information row right after the row they are in, the script can be simplified and you can add a specific class to that row:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {
  $('#report66 tr.information-row').hide();
  $("#report66 tr:not(.information-row)").click(function () {
    $(this).next().toggle();
  });
});</code>```

    .table.tableSection {
        display: table;
        width: 500%;
    }
    .table.tableSection thead, table.tableSection tbody {
        float: left;
        width: 100%;
    }
    .table.tableSection tbody {
        overflow: auto;
        height: 250px;
    }
    .table.tableSection tr {
        width: 100%;
        display: table;
        text-align: left;
    }
    .table.tableSection th, table.tableSection td {
        width: 33%;
    }
    .td, th {
     border: 1px solid #dddddd;
     text-align: left;
     padding: 5px;
     background-color: #00565c;
     color: white;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <table id='report66'>
    <tr>
      <th>Header1</th>
      <th>Header2</th>
      <th>Header3</th>
      <th>Header4</th>
    </tr>
    <tr>
      <td>Data1</td>
      <td>Data2</td>
      <td>Data3</td>
      <td>Data4</td>
    </tr>
    <tr class="information-row">
      <td colspan="8">
        Information
        Information
        <table>
          <th>Test</th>
          <tr>
            <td>Test</td>
          </tr>
        </table>
      </td>
    </tr>
    <tr>
      <td>Data5</td>
      <td>Data6</td>
      <td>Data7</td>
      <td>Data8</td>
    </tr>
    <tr class="information-row">
      <td colspan="8">
        Information 2
        Information 2
        <table>
          <th>Test</th>
          <tr>
            <td>Test</td>
          </tr>
        </table>
      </td>
    </tr>
  </table></code>```

Body:
I'm very new to this and trying to work out how something works that someone previous to me has implemented and I need to alter.

We have a table with say 3 or 4 headers and at present one row below it.
JavaScript is used so that upon clicking on a row, it expand to display the next row.

What I'm trying to do is have another table within one of the rows that only shows after expanding.

            $(document).ready(function(){
            $("#report66 tr:odd").addClass("odd");
            $("#report66 tr:not(.odd)").hide();
            $("#report66 tr:first-child").show();
            $("#report66 tr.odd").click(function(){
                $(this).next("tr").toggle();
                $(this).find(".arrow").toggleClass("up");
            });
        });

.table.tableSection {
        display: table;
        width: 500%;
    }
    .table.tableSection thead, table.tableSection tbody {
        float: left;
        width: 100%;
    }
    .table.tableSection tbody {
        overflow: auto;
        height: 250px;
    }
    .table.tableSection tr {
        width: 100%;
        display: table;
        text-align: left;
    }
    .table.tableSection th, table.tableSection td {
        width: 33%;
    }
    .td, th {
     border: 1px solid #dddddd;
     text-align: left;
     padding: 5px;
     background-color: #00565c;
     color: white;
 }

        Header1
        Header2
        Header3
        Header4

        Data1
        Data2
        Data3
        Data4

    Information
    Information

        Test

        Test

So with this you can see that upon selecting the first row of data it expands and shows the next row. The table within that row, is collapsed and you have to expand this.

Main question is, how can I change this so that the 2nd table is not collapsed? (I'm not bothered about collapsing it)

There are a lot of different methods of achieving this but every single one I find, doesn't seem to fit what I need.

EDIT WITH ORIGINAL CODE SNIPPET

<?php

 if($replacementpending >= 1)
   {

echo "
Network | Pending Acceptance
";

   $sql = "SELECT * FROM  `stock`.`replacements.joblog` WHERE `status` = 'Pending' AND `ownership` = 'Stock' ORDER BY `id` ASC";
   $retval = mysqli_query( $conn, $sql );

   if(! $retval ) {
      die('Could not get data: ' . mysqli_error());
   }
 echo
     "

            DB Ref
            Ticket Ref
            Item Requested
            Customer

";
   while($row = mysqli_fetch_array($retval)) {
        echo "
";
        echo
        "{$row['id']}	".
         "{$row['req_ticketref']}	".
        "{$row['req_model']}	".
        "{$row['req_customer']}	".
        "	";
    }
echo
       "

       ";
    echo "

Additional information

       CI Name	{$row['ciref']}

       Requested By	{$row['req_name']}

       Ticket Reference	{$row['req_ticketref']}

       Customer	{$row['req_customer']}

       Date/Time Logged	{$row['datetimelogged']}

        <legend></legend>

Delivery Details

        End User Company Name	{$row['endusername']}

        Address Line 1	{$row['address1']}

        Address Line 2	{$row['address2']}

        City	{$row['city']}

        Post Code	{$row['postcode']}

        Country	{$row['country']}

       ";

   }
   echo "
";
  }
  ?>

Body:
When you do $("#report66 tr:not(.odd)").hide(); you actually hide all tr elements inside the main table, which do not have the .odd class name. Since you have another table inside the main one, this rule applies to the tr elements in it.

You can explicitly show all rows in the inner table:

            $(document).ready(function(){
            $("#report66 tr:odd").addClass("odd");
            $("#report66 tr:not(.odd)").hide();
            $("#report66 tr:first-child").show();
            $("#report66 tr table tr").show(); // Show all inner table rows
            $("#report66 tr.odd").click(function(){
                $(this).next("tr").toggle();
                $(this).find(".arrow").toggleClass("up");
            });
        });

.table.tableSection {
        display: table;
        width: 500%;
    }
    .table.tableSection thead, table.tableSection tbody {
        float: left;
        width: 100%;
    }
    .table.tableSection tbody {
        overflow: auto;
        height: 250px;
    }
    .table.tableSection tr {
        width: 100%;
        display: table;
        text-align: left;
    }
    .table.tableSection th, table.tableSection td {
        width: 33%;
    }
    .td, th {
     border: 1px solid #dddddd;
     text-align: left;
     padding: 5px;
     background-color: #00565c;
     color: white;
 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<table id='report66'>
    <tr>
        <th>Header1</th>
        <th>Header2</th>
        <th>Header3</th>
        <th>Header4</th>
    </tr>
    <tr>
        <td>Data1</td>
        <td>Data2</td>
        <td>Data3</td>
        <td>Data4</td>
    <tr>
    <td colspan='8'>
    Information
    Information
    <table>
        <th>Test</th>
        <tr>
        <td>Test</td>
    </table>
</table>

EDIT

If you want to have multiple visible cells, which toggle the visibility of the information row right after the row they are in, the script can be simplified and you can add a specific class to that row:

$(document).ready(function () {
  $('#report66 tr.information-row').hide();
  $("#report66 tr:not(.information-row)").click(function () {
    $(this).next().toggle();
  });
});

    .table.tableSection {
        display: table;
        width: 500%;
    }
    .table.tableSection thead, table.tableSection tbody {
        float: left;
        width: 100%;
    }
    .table.tableSection tbody {
        overflow: auto;
        height: 250px;
    }
    .table.tableSection tr {
        width: 100%;
        display: table;
        text-align: left;
    }
    .table.tableSection th, table.tableSection td {
        width: 33%;
    }
    .td, th {
     border: 1px solid #dddddd;
     text-align: left;
     padding: 5px;
     background-color: #00565c;
     color: white;
 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <table id='report66'>
    <tr>
      <th>Header1</th>
      <th>Header2</th>
      <th>Header3</th>
      <th>Header4</th>
    </tr>
    <tr>
      <td>Data1</td>
      <td>Data2</td>
      <td>Data3</td>
      <td>Data4</td>
    </tr>
    <tr class="information-row">
      <td colspan="8">
        Information
        Information
        <table>
          <th>Test</th>
          <tr>
            <td>Test</td>
          </tr>
        </table>
      </td>
    </tr>
    <tr>
      <td>Data5</td>
      <td>Data6</td>
      <td>Data7</td>
      <td>Data8</td>
    </tr>
    <tr class="information-row">
      <td colspan="8">
        Information 2
        Information 2
        <table>
          <th>Test</th>
          <tr>
            <td>Test</td>
          </tr>
        </table>
      </td>
    </tr>
  </table>


问:
Preserve original dates, Xarray Groupby
I'm reducing an xarray dataset by day

```<code>new_dataset = dataset.groupby('time.day').first()
</code>```

I'm expecting time dimension values similar to

```<code>array([ '2016-09-03T23:21:19.500000000', '2016-09-10T23:12:58.500000000', '2016-10-03T23:20:13.500000000'], dtype='datetime64[ns]')
</code>```

but am receiving integer values under a dimension called days

```<code>array([ 1,  2 ])
</code>```

Preserving the dimension types of this grouped xarray is important in using it as a drop-in operation to pre-existing workflows. Furthermore plotting time series of a point sampled from this xarray along the days axis will not preserve the spacing that days originally had between one another in the time domain.

Is there a simple or xarrays way of mapping days to datetime64 objects? Or should I independently group time coordinates of the original dataset and re-map them separately?

答:
dataset.groupby('time.day').first() groups data by day of the month, i.e. (1 Jan 2016, 1 Feb 2016, 1 Mar 2016,...,1 Dec 2019) are all grouped together. The output will be an array of up to 31 elements. The first operation reduces these groups by taking the first member of the group.

I suspect this isn't what you want to do, and that you are trying get the first data point for each calendar day. In which case, use dataset.resample(time='D').first().

Title: Preserve original dates, Xarray Groupby

Body:
I'm reducing an xarray dataset by day

new_dataset = dataset.groupby('time.day').first()

I'm expecting time dimension values similar to

array([ '2016-09-03T23:21:19.500000000', '2016-09-10T23:12:58.500000000', '2016-10-03T23:20:13.500000000'], dtype='datetime64[ns]')

but am receiving integer values under a dimension called days

array([ 1,  2 ])

Preserving the dimension types of this grouped xarray is important in using it as a drop-in operation to pre-existing workflows. Furthermore plotting time series of a point sampled from this xarray along the days axis will not preserve the spacing that days originally had between one another in the time domain.

Is there a simple or xarrays way of mapping days to datetime64 objects? Or should I independently group time coordinates of the original dataset and re-map them separately?


问:
JpaRepository nativeQuery - table does not exists
when trying to perform an update on table using JpaRepository and @Query annotation I receive an error "Table not exists" and:

```<code>has thrown exception:org.hibernate.exception.SQLGrammarException: could n
ot execute statement
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute s
tatement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException
: could not execute statement
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
        at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
        at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

Caused by: oracle.jdbc.OracleDatabaseException: ORA-00942: table or view does not exist

        at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:498)
        ... 154 common frames omitted
</code>```

My Query:

```<code>@Modifying
@Transactional
@Query(nativeQuery = true, value = "UPDATE T_MY_TABLE SET VISIBLE_FLAG = 0 "
        + "WHERE ID = :myId ")
int updateMyTab(@Param("myId") Long myId);
</code>```

When using JpaRepository.save method to update the table, it executes normally without any problems.

Also, I have SELECT nativeQueries, which works. Only the updates does not.

On table there is:
- created synonym for the schema
- grants for select, insert, update, delete for the schema

Table DOES exists, the update, if executed directly on DB and on any schema/user it works without any problems and updates rows

答:
I managed to solve the issue - problem was in database object naming. I used upper-case in object naming while tables names were case sensitive. I had to change:

```<code>@Modifying
@Transactional
@Query(nativeQuery = true, value = "UPDATE T_MY_TABLE SET VISIBLE_FLAG = 0 "
        + "WHERE ID = :myId ")
int updateMyTab(@Param("myId") Long myId);
</code>```

to:

```<code>@Modifying
@Transactional
@Query(nativeQuery = true, value = "UPDATE "\t_my_table"\ SET VISIBLE_FLAG = 0 "
        + "WHERE ID = :myId ")
int updateMyTab(@Param("myId") Long myId);
</code>```

Body:
when trying to perform an update on table using JpaRepository and @Query annotation I receive an error "Table not exists" and:

has thrown exception:org.hibernate.exception.SQLGrammarException: could n
ot execute statement
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute s
tatement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException
: could not execute statement
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
        at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
        at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
        at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

Caused by: oracle.jdbc.OracleDatabaseException: ORA-00942: table or view does not exist

        at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:498)
        ... 154 common frames omitted

My Query:

@Modifying
@Transactional
@Query(nativeQuery = true, value = "UPDATE T_MY_TABLE SET VISIBLE_FLAG = 0 "
        + "WHERE ID = :myId ")
int updateMyTab(@Param("myId") Long myId);

When using JpaRepository.save method to update the table, it executes normally without any problems.

Also, I have SELECT nativeQueries, which works. Only the updates does not.

On table there is:
- created synonym for the schema
- grants for select, insert, update, delete for the schema

Table DOES exists, the update, if executed directly on DB and on any schema/user it works without any problems and updates rows

Body:
I managed to solve the issue - problem was in database object naming. I used upper-case in object naming while tables names were case sensitive. I had to change:

@Modifying
@Transactional
@Query(nativeQuery = true, value = "UPDATE T_MY_TABLE SET VISIBLE_FLAG = 0 "
        + "WHERE ID = :myId ")
int updateMyTab(@Param("myId") Long myId);

to:

@Modifying
@Transactional
@Query(nativeQuery = true, value = "UPDATE "\t_my_table"\ SET VISIBLE_FLAG = 0 "
        + "WHERE ID = :myId ")
int updateMyTab(@Param("myId") Long myId);


问:
Join these 2 tables to get this specific output?
I am using SQL Server 2014. I am working on a query where I want to extract information from 2 specific tables to create my final output.

An extract of the 2 tables (Rebookings and ResaList) are given below.

Rebookings Table (each CancelledID has its corresponding RebookingID):

```<code>CancelledID            RebookingID
  102                     541
  250                     351
  129                     800
  ...
</code>```

ResaList Table:

```<code>ID      Property         ArrivalDate       RN
100       X              2020-05-22         9
102       X              2020-03-05         7
250       D              2020-04-12        10
129       E              2020-03-15         8
351       D              2020-09-23         5
541       X              2020-06-01         7
800       E              2020-07-11         8
...
</code>```

Here is my desired output:

```<code>ID       Property        ArrivalDate         RN    RebookingID        Rebooking_ArrivalDate    Rebooking_RN     Tag
102         X            2020-03-05           7       541              2020-06-01                   7           Cancelled
250         D            2020-04-12          10       351              2020-09-23                   5           Re-booked
129         E            2020-03-15           8       800              2020-07-11                   8           Re-booked
</code>```

This is what I have done so far:

```<code>USE [MyDatabase]

select
  a.[ID],
  a.[Property],
  a.[Arrival Date],
  a.[RN],
  b.[RebookingID],
  (CASE WHEN a.[ID] in (SELECT [CancelledID] FROM [Rebookings]) THEN 'Re-booked'
      ELSE 'Cancelled'
      END) as [Tag]
from [ResaList] a
LEFT JOIN [Rebookings] b on b.[CancelledID] = a.[ID]
where a.[ID] in (SELECT [CancelledID] FROM [Rebookings])
GROUP BY a.[ID], a.[Property], a.[ArrivalDate], b.[RebookingID]
</code>```

I am stuck at how to bring Rebooking_ArrivalDate and Rebooking_RN into the above output. Any help would be appreciated.

答:
Using select in an inner query to find out existing records is very bad way to do this. On larger tables you will suffer a lot.
Here is a compact and efficient way-</p>

```<code>    select
    a.ID,
    a.Property,
    a.Arrival Date,
    a.RN,
    b.RebookingID,
    b.Rebooking_ArrivalDate,
    b.Rebooking_RN,
    coalesce(b.tag,'Cancelled')as tag
from ResaList a left join
    (
    select *, 'Re-booked' as tag from Rebookings
    ) b
    on a.ID=b.CancelledID
</code>```

Body:
I am using SQL Server 2014. I am working on a query where I want to extract information from 2 specific tables to create my final output.

An extract of the 2 tables (Rebookings and ResaList) are given below.

Rebookings Table (each CancelledID has its corresponding RebookingID):

CancelledID            RebookingID
  102                     541
  250                     351
  129                     800
  ...

ResaList Table:

ID      Property         ArrivalDate       RN
100       X              2020-05-22         9
102       X              2020-03-05         7
250       D              2020-04-12        10
129       E              2020-03-15         8
351       D              2020-09-23         5
541       X              2020-06-01         7
800       E              2020-07-11         8
...

Here is my desired output:

ID       Property        ArrivalDate         RN    RebookingID        Rebooking_ArrivalDate    Rebooking_RN     Tag
102         X            2020-03-05           7       541              2020-06-01                   7           Cancelled
250         D            2020-04-12          10       351              2020-09-23                   5           Re-booked
129         E            2020-03-15           8       800              2020-07-11                   8           Re-booked

This is what I have done so far:

USE [MyDatabase]

select
  a.[ID],
  a.[Property],
  a.[Arrival Date],
  a.[RN],
  b.[RebookingID],
  (CASE WHEN a.[ID] in (SELECT [CancelledID] FROM [Rebookings]) THEN 'Re-booked'
      ELSE 'Cancelled'
      END) as [Tag]
from [ResaList] a
LEFT JOIN [Rebookings] b on b.[CancelledID] = a.[ID]
where a.[ID] in (SELECT [CancelledID] FROM [Rebookings])
GROUP BY a.[ID], a.[Property], a.[ArrivalDate], b.[RebookingID]

I am stuck at how to bring Rebooking_ArrivalDate and Rebooking_RN into the above output. Any help would be appreciated.

Body:
Using select in an inner query to find out existing records is very bad way to do this. On larger tables you will suffer a lot.
Here is a compact and efficient way-

    select
    a.ID,
    a.Property,
    a.Arrival Date,
    a.RN,
    b.RebookingID,
    b.Rebooking_ArrivalDate,
    b.Rebooking_RN,
    coalesce(b.tag,'Cancelled')as tag
from ResaList a left join
    (
    select *, 'Re-booked' as tag from Rebookings
    ) b
    on a.ID=b.CancelledID


问:
How to measure the execution time for a classification algorithm in Python's scikit-learn?
How do I measure the time taken to train and test a classifier like SVM, KNN and Decision Treen in scikit-learn?</p>

答:
You can use the time module like so

```<code>import time
start = time.time()

# enter your code here

end = time.time()
print(end - start, "seconds")
</code>```

Body:
You can use the time module like so

import time
start = time.time()

# enter your code here

end = time.time()
print(end - start, "seconds")


问:
Vim: insert mode is very slow with 400+ lines
I have a file with 400+ lines (it's a thesis). When I edit it somewhere near
the top (say, on line 20), Vim is snappy as always. However, editing it near
the bottom (around line 400) causes a noticeable delay between me typing the character
and Vim showing it on the screen. As a consequence, it is almost impossible to
edit a file this big.

What is the reason for this and what can I do?

I've tried toggling the swapfile, syntax, scrolloff etc, but it doesn't
seem to help. The maximum number of lines for Vim should be 2147483647, so I
should actually have a long way to go here :)

In case this is related to setting maxmem, then what would be a reasonable
value, considering that I edit files up to 2500 lines?

Thanks very much for any help! Cheers.

答:
I recently came across this exact problem - lag while typing at the bottom of a relatively short (markdown) file. After uninstalling plugins and commenting out most of the settings in my .vimrc, I discovered that the issue was markdown folding coming from the vim-markdown plugin that is pre-installed with vim. Commenting out let g:markdown_folding = 1 did the trick.

I still wanted to have automatic folding on markdown files, so I installed vim-markdown-folding and there are no issues with performance.


问:
Use NProgress with "React.lazy"
I have the following component tree:

<BrowserRouter>
  <Suspense fallback={
MyFallback
}>
    <Switch>
      <Route component={HomePage} path="/" exact />
      <Route
        component={lazy(() => import('./pages/Auth/Login'))}
        path="/auth/login"
        exact
      />
    </Switch>
  </Suspense>
</BrowserRouter>
```

I was using React.Suspense to show a loading fallback. However, now I want to show a progress bar at the top of the current page instead of using a normal Suspense loading fallback, which removes the entire current route to display the fallback.

How do I add NProgress, for example, to indicate the loading progress of the page that is being loaded?

Maybe the new React's Concurrent Mode can help with that? :)

答:
Here is the solution</p>

```<code>const LazyLoad = () => {
    useEffect(() => {
        NProgress.start();

        return () => {
            NProgress.stop();
        };
    });

    return '';
};

<Suspense fallback={<LazyLoad />}>
</code>```

Title: Use NProgress with "React.lazy"

Body:
I have the following component tree:

<BrowserRouter>
  <Suspense fallback={
MyFallback
}>
    <Switch>
      <Route component={HomePage} path="/" exact />
      <Route
        component={lazy(() => import('./pages/Auth/Login'))}
        path="/auth/login"
        exact
      />
    </Switch>
  </Suspense>
</BrowserRouter>

I was using React.Suspense to show a loading fallback. However, now I want to show a progress bar at the top of the current page instead of using a normal Suspense loading fallback, which removes the entire current route to display the fallback.

How do I add NProgress, for example, to indicate the loading progress of the page that is being loaded?

Maybe the new React's Concurrent Mode can help with that? :)

Body:
Here is the solution

const LazyLoad = () => {
    useEffect(() => {
        NProgress.start();

        return () => {
            NProgress.stop();
        };
    });

    return '';
};

<Suspense fallback={<LazyLoad />}>


问:
How to declare SCSS <length> type attribute selector by REACT property
Basically I want to create a reusable component which can be slightly modified from the outside in react:

SomewhereElse.tsx

```<code>...
<FooComponent width={200}>
...
</code>```

FooComponent.tsx

```<code>interface IFooProps {
  //default width of 150px
  width?: 150;
  //default margin of 5px
  margin?: 5;
}

interface IFooState{
  checked: boolean;
}

class FooComponent extends Component<IFooProps, IFooState> {
    constructor(props: IFooProps) {
        super(props);
        ...
    }

...

    render(): ReactElement {
        return (
          <div className="foo-component"
              data-width={this.props.width + 'px'}
          >
          ...
</code>```

FooComponent.scss

```<code>.foo-component {
    ...
    width: attr(data-width length);
    ...
</code>```

But it always gives me the following error when running the application (chrome):

... Please consider that I need a "number" as property because I am doing some calculations based on that number for some of the inner components so everything fits together.

EDIT:

Using "style" is not working for me because I have some ::before ::after features in my scss which are broken when using style because they occasionally modify "right:" based on the width.

For better understanding, this is my base:
https://www.sitepoint.com/react-toggle-switch-reusable-component/

答:
As suggested from G-Cyrillus I have found a possible solution using CSS custom properties. Unfortunetly I did not find a solution using attribute selector so I could stick to one solution type.

Add your custom properties in the scss file "parent" class like:

```<code>.foo-component {
    --customwidth: 150px;
    --custommargin: 5px;

    width: var(--customwidth, 150px);
    ...
    &-inner {
        margin-left: var(--custommargin, 5px);
    }
    ...
}
</code>```

After you declared the customproperty it's possible to use it with var(<propertyname>, <initialvalue>).

In React you slightly can modify the render() like:

```<code> render(): ReactElement {
    //set the custom properties for width, margin and slider position
    let cssProperties = {};
    cssProperties['--customwidth'] = this.props.width == null ? '150px' : this.props.width + 'px';
    cssProperties['--custommargin'] = this.props.margin == null ? '150px' : this.props.margin + 'px';
    cssProperties['--switchposition'] = (this.props.width == null ? 115 : this.props.width - 35) + 'px';

    return (
      <div className="foo-component" style={cssProperties}>
      ...
}
</code>```

Which will work for every component seperatly.

Body:
Basically I want to create a reusable component which can be slightly modified from the outside in react:

SomewhereElse.tsx

...
<FooComponent width={200}>
...

FooComponent.tsx

interface IFooProps {
  //default width of 150px
  width?: 150;
  //default margin of 5px
  margin?: 5;
}

interface IFooState{
  checked: boolean;
}

class FooComponent extends Component<IFooProps, IFooState> {
    constructor(props: IFooProps) {
        super(props);
        ...
    }

...

    render(): ReactElement {
        return (

          ...

FooComponent.scss

.foo-component {
    ...
    width: attr(data-width length);
    ...

But it always gives me the following error when running the application (chrome):

... Please consider that I need a "number" as property because I am doing some calculations based on that number for some of the inner components so everything fits together.

EDIT:

Using "style" is not working for me because I have some ::before ::after features in my scss which are broken when using style because they occasionally modify "right:" based on the width.

For better understanding, this is my base:
https://www.sitepoint.com/react-toggle-switch-reusable-component/

Body:
As suggested from G-Cyrillus I have found a possible solution using CSS custom properties. Unfortunetly I did not find a solution using attribute selector so I could stick to one solution type.

Add your custom properties in the scss file "parent" class like:

.foo-component {
    --customwidth: 150px;
    --custommargin: 5px;

    width: var(--customwidth, 150px);
    ...
    &-inner {
        margin-left: var(--custommargin, 5px);
    }
    ...
}

After you declared the customproperty it's possible to use it with var(<propertyname>, <initialvalue>).

In React you slightly can modify the render() like:

 render(): ReactElement {
    //set the custom properties for width, margin and slider position
    let cssProperties = {};
    cssProperties['--customwidth'] = this.props.width == null ? '150px' : this.props.width + 'px';
    cssProperties['--custommargin'] = this.props.margin == null ? '150px' : this.props.margin + 'px';
    cssProperties['--switchposition'] = (this.props.width == null ? 115 : this.props.width - 35) + 'px';

    return (
      <div className="foo-component" style={cssProperties}>
      ...
}

Which will work for every component seperatly.


问:
Using MDC or Threadlocal
I'd like to propagate X-Request-Id received from my Nginx to other services in my k8s when calling them using http.

Right now, I'm using request filters to catch that X-Request-Id header and putting it to the MDC.

        final String nginxRequestId = requestContext.getHeaderString("X-Request-Id");
        if (nginxRequestId != null) {
            MDC.put("infra_request", nginxRequestId);
        }
```

Now, I'm calling the endpoint of service B inside the k8s (so no Nginx in the way) and I'd like to obtain that X-Request-Id to put it into the request's header. I can see two options here:

simply get that value from MDC

store that header in the thread local variable (as the service is using Dropwizard) in addition to storing it in MDC

I'd probably do it using the MDC, but I'm not sure whether this is the best practice or whether there could be some catch/problems with that.

答: I have used both the MDC and ThreadLocal for the similar purpose of passing a transaction-id to the headers. Internally, MDC uses ThreadLocal and it has some predefined functionalities like adding a prefix to every log. I would suggest having ThreadLocal if the data which you are putting is of some business use, otherwise, you can go with MDC.</p>

Title: Using MDC or Threadlocal

Body:
I'd like to propagate X-Request-Id received from my Nginx to other services in my k8s when calling them using http.

Right now, I'm using request filters to catch that X-Request-Id header and putting it to the MDC.

        final String nginxRequestId = requestContext.getHeaderString("X-Request-Id");
        if (nginxRequestId != null) {
            MDC.put("infra_request", nginxRequestId);
        }

Now, I'm calling the endpoint of service B inside the k8s (so no Nginx in the way) and I'd like to obtain that X-Request-Id to put it into the request's header. I can see two options here:

simply get that value from MDC

store that header in the thread local variable (as the service is using Dropwizard) in addition to storing it in MDC

I'd probably do it using the MDC, but I'm not sure whether this is the best practice or whether there could be some catch/problems with that.


问:
Xcode crashes on opening xib files
I have problems with xcode and can't open xib files. Everytime I click on the xib file, xcode crashes. This happens on the xcode3.2 as well as the xcode4.

Is there anything I can do to it? I have un-installed and re-installed but still not working.

Any help would really be appreciable.

If it helps, I am using xcode4 and bought it from the app store.

答: Just Install one xcode at a time. Means use Xcode 4 or Xcode 3.2 alone. This may solve your problem. Try that.</p>

Title: Xcode crashes on opening xib files


问:
What is the purpose of this 'a' in this array slicing in Python ( W[: , : , : , a] )?
Here is the code example:

```<code>weights = W[:,:,:,a]
</code>```

Here, a is an integer number

In array slicing, I need a good explanation (references are a plus) on Python's slice notation. I don't understand what is the purpose of this 'a'. We know that a 3D array is like a stack of matrices where:

The first index, i, selects the matrix

The second index, j, selects the row

The third index, k, selects the column

答:
Shapes:

Let M to be the your n-dimensional array:

Reference image: https://fgnt.github.io/python_crashkurs_doc/_images/numpy_array_t.png

A shape of M (x,) means your array have x lines

A shape of M (x, y) means your array have x lines and y columns

A shape of M (x, y, z) means your array have x lines, y columns and z "layers"

If you want you can think of shapes as (lines, columns, layers,...), but things become complicated when you talk about four-dimensional arrays or greater (maybe you could name them as stacks of blocks for the fourth dimension).

Anyway, a way better naming convention is the following:

M (axis 0, axis 1, axis 2, ..., axis n) as shown in the reference image.

To find the shape of array in Python, simply write: M.shape

Slicing:

In array indexing, the comma separates the dimensions of an array:
M [axis 0, axis 1, axis 2, ..., axis n]
For each axis you can have the following slice structure:

[ start : stop : step ] where:

start: the first index for the selected axis (included in the result)

start = 0 is the default start index (does not need to be specified)

stop: the last index for the selected axis (not included in the result)

stop = len(axis) is the default end index (does not need to be specified)

step: the step of traversing the selected axis:

step = 0 is not allowed

step = 1 is the default step (does not need to be specified)

step = -1 means reverse traversing

step = n means from n to n step

The following slicings are equivalent:
M [0:n+1:1], M [:] and M[::] according to default values.

Mixed together, now we can write in a generic slicing notation:

M [start-index-for-axis 0 : stop-index-for-axis 0 : step-for-axis 0,

     start-index-for-axis 1 : stop-index-for-axis 1 : step-for-axis 1,

     start-index-for-axis 2 : stop-index-for-axis 2 : step-for-axis 2,

     ...

     start-index-for-axis n : stop-index-for-axis n : step-for-axis n],

Enough theory, let's see some examples:

We have M, a two-dimensional array, with a (5, 5) shape:

```<code>M = np.arange(1, 26).reshape(5, 5)
print(M)
</code>```

result:

```<code>[[ 1  2  3  4  5]
[ 6  7  8  9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]]
</code>```

```<code>print('Traverse the matrix from the last line to the first one (axis=0)', matrix[::-1],  sep='\n')
</code>```

Result:

```<code>[[21 22 23 24 25]
[16 17 18 19 20]
[11 12 13 14 15]
[ 6  7  8  9 10]
[ 1  2  3  4  5]]
</code>```

```<code>print('The 3 columns in the middle of the matrix (take all data from axis=0, and take a slice from axis=1):' , matrix[:, 1:4],sep='\n')
</code>```

Result:

```<code>[[ 2  3  4]
[ 7  8  9]
[12 13 14]
[17 18 19]
[22 23 24]]
</code>```

Now, your slice: W [:, :, :, a], where  a is an integer variable, can be interpreted as:

M is a four-dimensional array

you take all from axis 0, axis 1 and axis 2

you take just the index a from axis 3

A four-dimensional array can be imagined as a stack/array of three-dimensional blocks, and your slice means: take the a column from each matrix from each block, and ends up with a three-dimensional array.

Body:
Here is the code example:

weights = W[:,:,:,a]

Here, a is an integer number

In array slicing, I need a good explanation (references are a plus) on Python's slice notation. I don't understand what is the purpose of this 'a'. We know that a 3D array is like a stack of matrices where:

The first index, i, selects the matrix

The second index, j, selects the row

The third index, k, selects the column

Body:
Shapes:

Let M to be the your n-dimensional array:

Reference image: https://fgnt.github.io/python_crashkurs_doc/_images/numpy_array_t.png

A shape of M (x,) means your array have x lines

A shape of M (x, y) means your array have x lines and y columns

A shape of M (x, y, z) means your array have x lines, y columns and z "layers"

If you want you can think of shapes as (lines, columns, layers,...), but things become complicated when you talk about four-dimensional arrays or greater (maybe you could name them as stacks of blocks for the fourth dimension).

Anyway, a way better naming convention is the following:

M (axis 0, axis 1, axis 2, ..., axis n) as shown in the reference image.

To find the shape of array in Python, simply write: M.shape

Slicing:

In array indexing, the comma separates the dimensions of an array:
M [axis 0, axis 1, axis 2, ..., axis n]
For each axis you can have the following slice structure:

[ start : stop : step ] where:

start: the first index for the selected axis (included in the result)

start = 0 is the default start index (does not need to be specified)

stop: the last index for the selected axis (not included in the result)

stop = len(axis) is the default end index (does not need to be specified)

step: the step of traversing the selected axis:

step = 0 is not allowed

step = 1 is the default step (does not need to be specified)

step = -1 means reverse traversing

step = n means from n to n step

The following slicings are equivalent:
M [0:n+1:1], M [:] and M[::] according to default values.

Mixed together, now we can write in a generic slicing notation:

M [start-index-for-axis 0 : stop-index-for-axis 0 : step-for-axis 0,

     start-index-for-axis 1 : stop-index-for-axis 1 : step-for-axis 1,

     start-index-for-axis 2 : stop-index-for-axis 2 : step-for-axis 2,

     ...

     start-index-for-axis n : stop-index-for-axis n : step-for-axis n],

Enough theory, let's see some examples:

We have M, a two-dimensional array, with a (5, 5) shape:

M = np.arange(1, 26).reshape(5, 5)
print(M)

result:

[[ 1  2  3  4  5]
[ 6  7  8  9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]]

print('Traverse the matrix from the last line to the first one (axis=0)', matrix[::-1],  sep='\n')

Result:

[[21 22 23 24 25]
[16 17 18 19 20]
[11 12 13 14 15]
[ 6  7  8  9 10]
[ 1  2  3  4  5]]

print('The 3 columns in the middle of the matrix (take all data from axis=0, and take a slice from axis=1):' , matrix[:, 1:4],sep='\n')

Result:

[[ 2  3  4]
[ 7  8  9]
[12 13 14]
[17 18 19]
[22 23 24]]

Now, your slice: W [:, :, :, a], where  a is an integer variable, can be interpreted as:

M is a four-dimensional array

you take all from axis 0, axis 1 and axis 2

you take just the index a from axis 3

A four-dimensional array can be imagined as a stack/array of three-dimensional blocks, and your slice means: take the a column from each matrix from each block, and ends up with a three-dimensional array.


问:
How to define QML gradient object in javascript
This is my qtquick qml code

```<code>function show_me(element) {
    console.log(element.gradient)
}

Rectangle {
    gradient: Gradient {
        GradientStop {
            position: 0
            color: "#30cfd0"
        }

        GradientStop {
            position: 1
            color: "#330867"
        }
    }

    MouseArea {
        anchors.fill: parent
        hoverEnabled: true

        onEntered: {
            show_me(parent)
        }
    }
}
</code>```

The output is

```<code>qml: QQuickGradient(0x559f18a4dd40)
</code>```

the output gives me a QtQuickGradient object

I wonder how do I define a QtQuickGradient object in javascript?

I want to something like:

```<code>var gradient = //QtQuickGradient (i don't know)
element.gradient = gradient
</code>```

Please help me to define it

答:
You can create the Gradient object using common Component item, for example:

Component {
    id: myGradient
    Gradient {
        GradientStop { position: 0.0; color: "red" }
        GradientStop { position: 0.5; color: "yellow" }
        GradientStop { position: 1.0; color: "green" }
    }
}

Rectangle {
    id: rect
    width: 100
    height: 100
    anchors.centerIn: parent
    color: "orange"
    Text {
        anchors.centerIn: parent
        text: "click me"
    }
    TapHandler {
        onTapped: {
            var gradient = myGradient.createObject(rect);
            rect.gradient = gradient;
        }
    }
}
```

Body:
This is my qtquick qml code

function show_me(element) {
    console.log(element.gradient)
}

Rectangle {
    gradient: Gradient {
        GradientStop {
            position: 0
            color: "#30cfd0"
        }

        GradientStop {
            position: 1
            color: "#330867"
        }
    }

    MouseArea {
        anchors.fill: parent
        hoverEnabled: true

        onEntered: {
            show_me(parent)
        }
    }
}

The output is

qml: QQuickGradient(0x559f18a4dd40)

the output gives me a QtQuickGradient object

I wonder how do I define a QtQuickGradient object in javascript?

I want to something like:

var gradient = //QtQuickGradient (i don't know)
element.gradient = gradient

Please help me to define it


问:
react-spring and framer-motion laggy on firefox
I have problem with two animation libraries(react-spring, framer-motion). I was trying to make simple animation in moment when component is first time visible. (it's simplify version)

<motion.div initial={{x: -25, opacity: 0}} animate={{x: 0, opacity: 1}} transition={{duration: 2.5}} className="App-logo">NAME</motion.div>

Github project

It looks very smooth on Chrome, Brave, Edge, but on Firefox it looks laggy in the end of animation.
This example is based on framer-motion but in react-spring it looks the same. When transition-duration is shorter and translateX longer it looks better but still it's not smooth animation(and it's not solution for this problem to change properties which works on other browsers).
Firefox(76.0.1)(OS Win10).

I tried to do the same animation using clear css and it looks smooth on each browser. I was searching for solutions to my problem but i didn't find any particural answears.

答:
I think it is the difference int the rendering engine of Firefox and Chrome. Firefox just position the div pixel by pixel without subpixel rendering. If you add a slight rotation to the div it makes FF engine to skip optimization.

```<code><motion.div initial={{x: -25, opacity: 0, rotation: 0.02}} animate={{x: 0, opacity: 1, rotation: 0.02}} transition={{duration: 2.5}} className="App-logo">NAME</motion.div>
</code>```

Update: Based on your your git repo I add an example. If I add rotation for the first two line, the animation is noticeably smoother in Firefox than with the last line.

https://codesandbox.io/s/happy-cannon-tew1f

Body:
I think it is the difference int the rendering engine of Firefox and Chrome. Firefox just position the div pixel by pixel without subpixel rendering. If you add a slight rotation to the div it makes FF engine to skip optimization.

<motion.div initial={{x: -25, opacity: 0, rotation: 0.02}} animate={{x: 0, opacity: 1, rotation: 0.02}} transition={{duration: 2.5}} className="App-logo">NAME</motion.div>

Update: Based on your your git repo I add an example. If I add rotation for the first two line, the animation is noticeably smoother in Firefox than with the last line.

https://codesandbox.io/s/happy-cannon-tew1f


问:
nodejs - unable to write files in linux server
I have hosted a node server in AWS. Server runs fine. In server, a file (for eg, abc.pdf) is generated programmatically. The file gets saved in /tmp location.

I wanted this file in another location /home/ubuntu/nodeserver/file/ But to this location, file is not getting saved. It only works in tmp folder.

I gave full permission to the folder but still, it's not working.

This is how I specified path for tmp folder

```<code>file:///tmp/
</code>```

But the path I gave for the other folder is not working

```<code>file:///home/ubuntu/nodeserver/file
</code>```

Thanks!

答:
Found the issue

The path should have been like this

```<code>file://home/ubuntu/nodeserver/file
</code>```

Body:
I have hosted a node server in AWS. Server runs fine. In server, a file (for eg, abc.pdf) is generated programmatically. The file gets saved in /tmp location.

I wanted this file in another location /home/ubuntu/nodeserver/file/ But to this location, file is not getting saved. It only works in tmp folder.

I gave full permission to the folder but still, it's not working.

This is how I specified path for tmp folder

file:///tmp/

But the path I gave for the other folder is not working

file:///home/ubuntu/nodeserver/file

Thanks!

Body:
Found the issue

The path should have been like this

file://home/ubuntu/nodeserver/file


问:
What is side effect in C?
Wikipedia says that:

In computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, that is to say has an observable effect besides returning a value (the main effect) to the invoker of the operation.

But how can we access a variable outside its local environment, can anyone explain this situation, side effect, main effect and sequence point comprehensibly?

答:
There is nothing called "main effect" in the C language.

The formal definition of side effect in the C language (C17 5.1.2.3/2) is rather:

Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any
  of those operations are all side effects, which are changes in the state of the execution environment.

Plainly, a side effect is:

accessing a volatile variable, or

writing to any variable,

or writing to a file

(Where stdout is likely to regard as a file for the given system.)

This is relevant when determining if/how a compiler is allowed to optimize code (C17 5.1.2.3/4):

In the abstract machine, all expressions are evaluated as specified by the semantics. An actual
  implementation need not evaluate part of an expression if it can deduce that its value is not used and
  that no needed side effects are produced (including any caused by calling a function or accessing a
  volatile object).

But also when it comes to determine if an expression has well-defined behavior or not, which is where sequence points come in. Sequence points is however a big topic of its own, explained for example in several answers here: Why are these constructs using pre and post-increment undefined behavior?

Title: What is side effect in C?


问:
Can an  contain a  in HTML5?
I have a structure which is as follows:

```<code><a href="#">
  <footer>
    <p>Some text</p>
    <h2>A Heading</h2>
  </footer>
</a>
</code>```

This works and displays as expected in all browsers (even IE6 with the HTML5shiv.js) except Firefox 3.6. In Firefox 3.6 the display is completely screwed and if you use Firebug to inspect the DOM, the  element is empty and the elements which should be inside it are outside of it.

All the tags are closed correctly. The  is set to display:block in the CSS.

The W3C validator validates the document and does not mark this structure as incorrect.

The spec states that an  element may be classed as flow content when it contains other flow content. The  is flow content.

Is it just that Firefox 3.6 doesn't render HTML entirely correctly?

Any ideas for a fix?

Ta!

答:
According the W3C HTML5 Reference the Footer Elements content model is:

Flow content, but with no heading
  content descendants, no sectioning
  content descendants, and no footer
  element descendants.

Which an a element is interactive content.(Which also can be a Flow Content)

So using the a element will validate, if you validate it against HTML5 Standards. Using something like the W3C validator.

So to answer your question, FireFox 3.6 Doesn't conform to HTML5 standards completely. FireFox 4.0 conforms better than 3.6. You can find a list of what elements of HTML5 (and CSS3) are supported by legacy browsers here.

As for the fix I would suggest that you hide the footer from Firefox, and show a div with your content in that is hidden for everything but firefox. I would accomplish this using jQuery CSS Browser Detection using jQuery instead of Hacks is a good place to start.

Title: Can an <a> contain a <footer> in HTML5?

Body:
I have a structure which is as follows:

Some text

A Heading

This works and displays as expected in all browsers (even IE6 with the HTML5shiv.js) except Firefox 3.6. In Firefox 3.6 the display is completely screwed and if you use Firebug to inspect the DOM, the  element is empty and the elements which should be inside it are outside of it.

All the tags are closed correctly. The  is set to display:block in the CSS.

The W3C validator validates the document and does not mark this structure as incorrect.

The spec states that an  element may be classed as flow content when it contains other flow content. The  is flow content.

Is it just that Firefox 3.6 doesn't render HTML entirely correctly?

Any ideas for a fix?

Ta!


问:
Xaml Rendering in IIS not working (but in IISExpress)
For my application, I am rendering some charts (WPF based) on the server and sending them back to the client.
I recently migrated the app to NET Core, which seemed to work fine until the very end when I deployed things on IIS. There, the charts are empty. However, when hosting the app in IISExpress, everything works smoothly.

I am now wondering what the differences between IIS and IISexpress are when it comes to graphics.

The code I am executing:

```<code>RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)control.Width, (int)control.Height, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Clear();

renderTargetBitmap.Render((Visual)control);

var encoder = new PngBitmapEncoder();

var bitmapFrame = BitmapFrame.Create(renderTargetBitmap);
encoder.Frames.Add(bitmapFrame);
encoder.Save(memoryStream);
</code>```

The code is run in an STA thread, for the sake of this problem the chart library doesn't matter, it is also supposed to work for a simple grid with a background color..

As I said, the code runs a) in a (non-wpf) console application b) in IIS Express c) in IIS before migrating to NET Core.

Any ideas how I can make this work?

答:
I finally found the solution, there is a well hidden compatibility switch available

https://github.com/microsoft/WPF-Samples/tree/master/Compatibility

Service/Non-interactive Window Stations
Rendering will continue by default, irrespective of the presence of display devices. Unless the WPF API's being used are short-lived (like rendering to a bitmap), it can lead to a CPU spike. If an application running inside a service would like to receive the 'default' WPF behavior, i.e., no rendering in the absence of display devices, then it should set to true

In short, add a new file "runtimeconfig.template.json" to your project with the content

```<code>{ "configProperties": { "Switch.System.Windows.Media.ShouldRenderEvenWhenNoDisplayDevicesAreAvailable": true } }
</code>```

Body:
For my application, I am rendering some charts (WPF based) on the server and sending them back to the client.
I recently migrated the app to NET Core, which seemed to work fine until the very end when I deployed things on IIS. There, the charts are empty. However, when hosting the app in IISExpress, everything works smoothly.

I am now wondering what the differences between IIS and IISexpress are when it comes to graphics.

The code I am executing:

RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)control.Width, (int)control.Height, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Clear();

renderTargetBitmap.Render((Visual)control);

var encoder = new PngBitmapEncoder();

var bitmapFrame = BitmapFrame.Create(renderTargetBitmap);
encoder.Frames.Add(bitmapFrame);
encoder.Save(memoryStream);

The code is run in an STA thread, for the sake of this problem the chart library doesn't matter, it is also supposed to work for a simple grid with a background color..

As I said, the code runs a) in a (non-wpf) console application b) in IIS Express c) in IIS before migrating to NET Core.

Any ideas how I can make this work?

Body:
I finally found the solution, there is a well hidden compatibility switch available

https://github.com/microsoft/WPF-Samples/tree/master/Compatibility

Service/Non-interactive Window Stations
Rendering will continue by default, irrespective of the presence of display devices. Unless the WPF API's being used are short-lived (like rendering to a bitmap), it can lead to a CPU spike. If an application running inside a service would like to receive the 'default' WPF behavior, i.e., no rendering in the absence of display devices, then it should set to true

In short, add a new file "runtimeconfig.template.json" to your project with the content

{ "configProperties": { "Switch.System.Windows.Media.ShouldRenderEvenWhenNoDisplayDevicesAreAvailable": true } }