问:
What is the struct (binary format) of float datatype in C?
How can I find information about float datatype in C? I mean the bit struct for this type (decimal, signal indicator, etc...)?
Let me explain what I'm trying to do:

I am implementing an network protocol and I need to send 6 octects with Latitude and Longitude (according to protocol documentation). First 3 octects must have LAT information and last 3 must have LON information.
I can't use bitwise operators in float datatype, so for debug, I'm copying memory of float variable to a new uint32_t variable (both 4-bytes wide) and then, trying to shift bit's to get the correct value, but it's not working.

This is the code that I'm using to test/debug conversion:

```<code>    int32_t b = 0;
    memcpy(&b,&a,4);
    int32_t c = (b >> 23);
    printf("Valor de C: 0x%X, Decimal: %d\n",c,c);
// Should print only '23', but it's printing
// Valor de C: 0x41B, Decimal: 1051
</code>```

After 'knowing' the correct bit-position of float, I'll copy those bit's to my protocol data, which is an array of unsigned char[6] (this I can't change the type, only values).

Any tip's about how to accomplish this?

答:
Here is a sample code showing how to encode the float latitude. (same thing for longitude).
See: https://en.wikipedia.org/wiki/Q_(number_format)#Float_to_Q for an introduction to fixed point encoding with 2 complements sign management.

It uses fixed point encoding with weight provided by the specification.

```<code>#include <stdio.h>
#include <stdlib.h>
int main()
{

    /* weight of one bit */
    const float weight = 180./(1 << 23);
    printf ("w=%f\n",weight);

    /* a few sample conversions */
    /* 2.53 degres */
    float lat = 2.53;
    printf ("lat=%f\n",lat);

    int fp_lat = (int) (0.5f + lat / weight);
    printf ("fplat=0x%x\n",fp_lat);

    lat = 180.f; /* +180 degres */
    printf ("lat=%f\n",lat);

    fp_lat = (int) (0.5f+ lat / weight);
    printf ("fplat=0x%6x\n",fp_lat); /*exactly 23 bits */

    /* negative numbers)*/
    lat = -180.f; /* -180 degres */

    printf ("lat=%f\n",lat);

    fp_lat = (int) (0.5f + abs(lat) / weight);
    if (lat <0)
    {
        /*2 complement representation */
        fp_lat = (~fp_lat + 1) & 0xffffff;
    }
    printf ("fplat=0x%6x\n",fp_lat); /* same value as 180 */

    /*sample packing for latitude */
    unsigned char msg[6];
    msg[0] = (unsigned char)((fp_lat >> 16) & 0xff); /* most significant byte of 24 bits*/
    msg[1] = (unsigned char)((fp_lat >> 8 ) & 0xff);
    msg[2] = (unsigned char)((fp_lat      ) & 0xff);

    /* to be continued */
    return 0;

}
</code>```

Body:
How can I find information about float datatype in C? I mean the bit struct for this type (decimal, signal indicator, etc...)?
Let me explain what I'm trying to do:

I am implementing an network protocol and I need to send 6 octects with Latitude and Longitude (according to protocol documentation). First 3 octects must have LAT information and last 3 must have LON information.
I can't use bitwise operators in float datatype, so for debug, I'm copying memory of float variable to a new uint32_t variable (both 4-bytes wide) and then, trying to shift bit's to get the correct value, but it's not working.

This is the code that I'm using to test/debug conversion:

    int32_t b = 0;
    memcpy(&b,&a,4);
    int32_t c = (b >> 23);
    printf("Valor de C: 0x%X, Decimal: %d\n",c,c);
// Should print only '23', but it's printing
// Valor de C: 0x41B, Decimal: 1051

After 'knowing' the correct bit-position of float, I'll copy those bit's to my protocol data, which is an array of unsigned char[6] (this I can't change the type, only values).

Any tip's about how to accomplish this?

Body:
Here is a sample code showing how to encode the float latitude. (same thing for longitude).
See: https://en.wikipedia.org/wiki/Q_(number_format)#Float_to_Q for an introduction to fixed point encoding with 2 complements sign management.

It uses fixed point encoding with weight provided by the specification.

#include <stdio.h>
#include <stdlib.h>
int main()
{

    /* weight of one bit */
    const float weight = 180./(1 << 23);
    printf ("w=%f\n",weight);

    /* a few sample conversions */
    /* 2.53 degres */
    float lat = 2.53;
    printf ("lat=%f\n",lat);

    int fp_lat = (int) (0.5f + lat / weight);
    printf ("fplat=0x%x\n",fp_lat);

    lat = 180.f; /* +180 degres */
    printf ("lat=%f\n",lat);

    fp_lat = (int) (0.5f+ lat / weight);
    printf ("fplat=0x%6x\n",fp_lat); /*exactly 23 bits */

    /* negative numbers)*/
    lat = -180.f; /* -180 degres */

    printf ("lat=%f\n",lat);

    fp_lat = (int) (0.5f + abs(lat) / weight);
    if (lat <0)
    {
        /*2 complement representation */
        fp_lat = (~fp_lat + 1) & 0xffffff;
    }
    printf ("fplat=0x%6x\n",fp_lat); /* same value as 180 */

    /*sample packing for latitude */
    unsigned char msg[6];
    msg[0] = (unsigned char)((fp_lat >> 16) & 0xff); /* most significant byte of 24 bits*/
    msg[1] = (unsigned char)((fp_lat >> 8 ) & 0xff);
    msg[2] = (unsigned char)((fp_lat      ) & 0xff);

    /* to be continued */
    return 0;

}


来源: stackexchange

问:
DataTables js How to reduce the width of the entire table
I am using DataTables with AJAX datasource, by default there is alot of columns, so the page will automatically need to scroll right.

Below is the picture:

I wonder if there is a way to reduce the width of the entire table manually perhaps using CSS?

I tried doing the below:

```<code><section id="ticket-table-container">
    <table id="tickets-table" class="display" style="width:100%">
        <thead>
            <tr>
                <th>CustomerCompanyName</th>
                <th>CustomerContactName</th>
                <th>CustomerId</th>
                <th>CustomerRegion</th>
                <th>ID</th>
                <th>LastUpdatedBy</th>
                <th>LastUpdatedTime</th>
                <th>Product</th>
                <th>Subject</th>
                <th>TicketChannel</th>
                <th>TicketCreated</th>
                <th>TicketSLAExpiry</th>
                <th>TicketSeverity</th>
                <th>TicketStatus</th>
                <th>TicketType</th>
            </tr>
        </thead>
    </table>
</section>
</code>```

Putting the table inside the section and manually changing the width of the section. However, that does not help.

I know I can specify responsive with this code below:

```<code>  $(document).ready(function () {
            $("#tickets-table").DataTable({
                "responsive": true,
                "processing": true,
                "serverSide": true,
</code>```

However I wonder if it is possible to not use responsive and somehow just manually change the width so that the the table width is shortened so that the page does not need to scroll right?

答:
You are saying that your table should stretch to the available space in the parent container when you do style="width:100%" on your
 tag. Remove it to make the table use the required space.

Also, please avoid inline CSS styling, HTML should be used for structure and semantic, while CSS is used for presentation.

ContentLicense: CC BY-SA 4.0

Body:
I am using DataTables with AJAX datasource, by default there is alot of columns, so the page will automatically need to scroll right.

Below is the picture:

I wonder if there is a way to reduce the width of the entire table manually perhaps using CSS?

I tried doing the below:

                CustomerCompanyName
                CustomerContactName
                CustomerId
                CustomerRegion
                ID
                LastUpdatedBy
                LastUpdatedTime
                Product
                Subject
                TicketChannel
                TicketCreated
                TicketSLAExpiry
                TicketSeverity
                TicketStatus
                TicketType

Putting the table inside the section and manually changing the width of the section. However, that does not help.

I know I can specify responsive with this code below:

  $(document).ready(function () {
            $("#tickets-table").DataTable({
                "responsive": true,
                "processing": true,
                "serverSide": true,

However I wonder if it is possible to not use responsive and somehow just manually change the width so that the the table width is shortened so that the page does not need to scroll right?

Body:
You are saying that your table should stretch to the available space in the parent container when you do style="width:100%" on your <table> tag. Remove it to make the table use the required space.

Also, please avoid inline CSS styling, HTML should be used for structure and semantic, while CSS is used for presentation.


问:
How to store ArrayList into sharedPreferences in Android
In my application I want store ArrayList into sharedPreferences and get this list in another page!

For store this List i used this library : https://github.com/MrNouri/GoodPrefs

I write below codes, but when get this data I don't know how can get data!

My codes for store list :

```<code>for (int i : intList) {
    stringBuilder.append("ID : ").append(testPlans.get(i).getId())
            .append("Type : ").append(testPlans.get(i).getItemType())
            .append("Content").append(steps.get(i).getStepData().toString()).append("-");
    App.stepsBodyList.add(new DataItem(testPlans.get(i).getId(),
            testPlans.get(i).getItemType(),
            steps.get(i).getStepData().toString()));
}

GoodPrefs.getInstance().saveObjectsList(TEST_STEPS_STORED_LIST, App.stepsBodyList);
</code>```

My codes for get data :

```<code>private List<DataItem> storedStepsBodyList = new ArrayList<>();

    Toast.makeText(context, ""+
            GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,).size()
            , Toast.LENGTH_SHORT).show();
</code>```

This library for get list give me 2 constructor, one is tag name and second value is default! (TEST_STEPS_STORED_LIST,)

But I don't know can i set default value for second item of constructor!

I write this GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,storedStepsBodyList) but show me error for this storedStepsBodyList .

How can i fix it?

答:
Simple way, you can use Gson library, add it to build.gradle, it will serialize your list to JSON and save it to SharePreference

```<code>  implementation 'com.google.code.gson:gson:2.8.6'
</code>```

```<code>    public void saveItems(List<Item> items) {
        if (items != null && !items.isEmpty()) {
            String json = new Gson().toJson(items);
            mSharedPreferences.edit().putString("items", json).apply();
        }
    }

    public List<Item> getItems() {
        String json = mSharedPreferences.getString("items", "");
        if (TextUtils.isEmpty(json)) return Collections.emptyList();
        Type type = new TypeToken<List<Item>>() {
        }.getType();
        List<Item> result = new Gson().fromJson(json, type);
        return result;
    }
</code>```

Body:
In my application I want store ArrayList into sharedPreferences and get this list in another page!

For store this List i used this library : https://github.com/MrNouri/GoodPrefs

I write below codes, but when get this data I don't know how can get data!

My codes for store list :

for (int i : intList) {
    stringBuilder.append("ID : ").append(testPlans.get(i).getId())
            .append("Type : ").append(testPlans.get(i).getItemType())
            .append("Content").append(steps.get(i).getStepData().toString()).append("-");
    App.stepsBodyList.add(new DataItem(testPlans.get(i).getId(),
            testPlans.get(i).getItemType(),
            steps.get(i).getStepData().toString()));
}

GoodPrefs.getInstance().saveObjectsList(TEST_STEPS_STORED_LIST, App.stepsBodyList);

My codes for get data :

private List<DataItem> storedStepsBodyList = new ArrayList<>();

    Toast.makeText(context, ""+
            GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,).size()
            , Toast.LENGTH_SHORT).show();

This library for get list give me 2 constructor, one is tag name and second value is default! (TEST_STEPS_STORED_LIST,)

But I don't know can i set default value for second item of constructor!

I write this GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,storedStepsBodyList) but show me error for this storedStepsBodyList .

How can i fix it?

Body:
Simple way, you can use Gson library, add it to build.gradle, it will serialize your list to JSON and save it to SharePreference

  implementation 'com.google.code.gson:gson:2.8.6'

    public void saveItems(List<Item> items) {
        if (items != null && !items.isEmpty()) {
            String json = new Gson().toJson(items);
            mSharedPreferences.edit().putString("items", json).apply();
        }
    }

    public List<Item> getItems() {
        String json = mSharedPreferences.getString("items", "");
        if (TextUtils.isEmpty(json)) return Collections.emptyList();
        Type type = new TypeToken<List<Item>>() {
        }.getType();
        List<Item> result = new Gson().fromJson(json, type);
        return result;
    }


问:
How is the colon used when running a program in the command line?
I'm taking a Java assessment test. I do not understand the use of the colon in the command line. Could someone please elaborate? Thanks.

Here is the question...

Given:

```<code>class One {
    int x = 0;
    {assert x == 1;}
}
public class Two {
    public static void main(String[] args) {
        int y = 0;
        assert y == 0;
        if(args.length > 0)
            new One();
    }
}
</code>```

Which of the following will run without error? (Choose all that apply.)

```A. java Two
B. java Two x
C. java -ea Two
D. java -ea Two x
E. java -ea:One Two
F. java -ea:One Two x
G. java -ea:Two Two x
```

答: The -ea is a command line argument to enables assertions. If you give a class after the -ea, it is enabled just for the classes listed. e.g. -ea:One turns on assertions for class One

ContentLicense: CC BY-SA 3.0

Body:
I'm taking a Java assessment test. I do not understand the use of the colon in the command line. Could someone please elaborate? Thanks.

Here is the question...

Given:

class One {
    int x = 0;
    {assert x == 1;}
}
public class Two {
    public static void main(String[] args) {
        int y = 0;
        assert y == 0;
        if(args.length > 0)
            new One();
    }
}

Which of the following will run without error? (Choose all that apply.)

A. java Two
B. java Two x
C. java -ea Two
D. java -ea Two x
E. java -ea:One Two
F. java -ea:One Two x
G. java -ea:Two Two x


问:
Outputting huge number when using an array to print out even and odd numbers on C
I was asked to code a program that asks for an integer 'n', then scan for 'n' integers, and then sort and print those integers in even numbers, ascending, then the odd numbers, descending.

So I began by having the even numbers in the first column of an array, and then the odd numbers in the second column, and then print them, but at the end I'm getting nothing but huge, similar numbers instead of the values I initially entered.

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
  int array1_size, unfill;
  printf("How many integers do you wish to enter?\n");
  scanf("%d",&array1_size);
  int array1[array1_size][2];

  for (int i = 0; i < array1_size; ++i)
  {
    printf("Enter integer number %d\n", i+1);
    scanf("%d",&array1[i][0]);
  }

  for (int i = 0; i < array1_size; ++i)
  {
   if ( (array1[i][0] % 2) != 0 )
    {
      array1[i][1] = array1[i][0];
      array1[i][0] = unfill;
    }
  }

  printf("Your even numbers are:\n");
  for (int i = 0; i < array1_size; ++i)
  {
    printf("%d\n", array1[array1_size][0]);
  }

  printf("...and your odd numbers are:\n");
  for (int i = 0; i < array1_size; ++i)
  {
    printf("%d\n", array1[array1_size][1]);
  }

  return(0);
}
</code>```

答:
You declare

```<code>int array1[array1_size][2];
</code>```

The highest-index legally accessable element inside that is

```<code>array1[array1_size-1][2-1]
</code>```

This line is hence highly suspicious

```<code>printf("%d\n", array1[array1_size][1]);
</code>```

Also you do not initialise unfill  but copy its content elsewhere here

```<code>array1[i][0] = unfill
</code>```

You possible leave the content of any array1[i][0] non initialised, because your code is vulnerable by a failing scanf(), because here you ignore the usually very helpful return value, which could warn you in case anything went wrong with scanning.

```<code>scanf("%d",&array1[i][0])
</code>```

Any of these issues could be the explanation of your observed huge numbers, which sometimes are a symptom of using non-initialized variables or content of illegally accessed memory.

Body:
I was asked to code a program that asks for an integer 'n', then scan for 'n' integers, and then sort and print those integers in even numbers, ascending, then the odd numbers, descending.

So I began by having the even numbers in the first column of an array, and then the odd numbers in the second column, and then print them, but at the end I'm getting nothing but huge, similar numbers instead of the values I initially entered.

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int array1_size, unfill;
  printf("How many integers do you wish to enter?\n");
  scanf("%d",&array1_size);
  int array1[array1_size][2];

  for (int i = 0; i < array1_size; ++i)
  {
    printf("Enter integer number %d\n", i+1);
    scanf("%d",&array1[i][0]);
  }

  for (int i = 0; i < array1_size; ++i)
  {
   if ( (array1[i][0] % 2) != 0 )
    {
      array1[i][1] = array1[i][0];
      array1[i][0] = unfill;
    }
  }

  printf("Your even numbers are:\n");
  for (int i = 0; i < array1_size; ++i)
  {
    printf("%d\n", array1[array1_size][0]);
  }

  printf("...and your odd numbers are:\n");
  for (int i = 0; i < array1_size; ++i)
  {
    printf("%d\n", array1[array1_size][1]);
  }

  return(0);
}

Body:
You declare

int array1[array1_size][2];

The highest-index legally accessable element inside that is

array1[array1_size-1][2-1]

This line is hence highly suspicious

printf("%d\n", array1[array1_size][1]);

Also you do not initialise unfill  but copy its content elsewhere here

array1[i][0] = unfill

You possible leave the content of any array1[i][0] non initialised, because your code is vulnerable by a failing scanf(), because here you ignore the usually very helpful return value, which could warn you in case anything went wrong with scanning.

scanf("%d",&array1[i][0])

Any of these issues could be the explanation of your observed huge numbers, which sometimes are a symptom of using non-initialized variables or content of illegally accessed memory.


问:
Connecting Google Cloud Spanner with Liquibase
I am trying to create containers with Liquibase implementation which can connect with the Google Cloud Spanner.

I am getting the following error:

Caused by: com.google.cloud.spanner.SpannerException: INVALID_ARGUMENT: io.grpc.StatusRuntimeException: INVALID_ARGUMENT: Unsupported concurrency mode in query using INFORMATION_SCHEMA.

I have searched everywhere but have not got anything substantial to understand what could be the problem.

答:
I assume that you are using the official Google Open Source JDBC driver.

The error you are getting indicates that you are trying to query the INFORMATION_SCHEMA tables while a read/write transaction is active. You should switch to either autocommit mode or to a read-only transaction. You can do so using one of the following SQL statements, or by setting the appropriate mode through code:

Switch to autocommit: SET AUTOCOMMIT=TRUE

Switch to read-only: SET READ ONLY=TRUE

It should be sufficient to turn on only one of these two modes, but switching on both should also work.

If that does not work, or if my initial assumption is not correct: Could you share some more information about which JDBC driver you are using and how you are connecting to the database?

Additional information: There is now a community based Liquibase integration for Cloud Spanner here: https://github.com/cloudspannerecosystem/liquibase-spanner


问:
Access-Control-Allow-Origin header completely ignored by FireFox
I set up my website (running IIS8.5) to send the response header for CORS to a subdomain off my main domain and the header response is getting to Firefox just fine. All plug-ins, ad-blockers, etc, are disabled and I can see the header in the DOM inspector.
I've tried:

```<code>Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: https://services.mywebsite.com
Access-Control-Allow-Origin: http://services.mywebsite.com
Access-Control-Allow-Origin: null
Access-Control-Allow-Origin: "null"
</code>```

I've verified the SSL Certificate is working just fine (it's a wildcard cert for *.mywebsite.com from Sectigo and I've verified that the entire certification path is working properly)

There are no other response headers except for: X-Frame-Options: SAMEORIGIN  ,however, I removed it with the same result.
The site predates CORS by years (ASP.NET Webforms) and there are no other settings I can find that would prevent Firefox from acknowledging this response header.

I've read dozens of posts here (usually someone had a self-signed cert or forgot something) but am at a loss on what is wrong?

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://services.mywebsite.com/api/geodata/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

It's absolutely NOT MISSING!  WTF Firefox?

Pulling hair out here. Anyone?

```<code>HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
Expires: -1
Server: Microsoft-IIS/8.5
X-Content-Type-Options: nosniff
Access-Control-Allow-Origin: https://services.mywebsite.com
X-Frame-Options: SAMEORIGIN
Date: Wed, 27 May 2020 08:28:05 GMT
</code>```

Someone else suggested adding a CORS module to IIS.  I did, then added to my web.config file the following (in system.webserver section):

```<code><cors enabled="true">
    <add origin="*" allowed="true" >
        <allowHeaders allowAllRequestedHeaders="true" />
    </add>
</cors>
</code>```

No Joy! Same message from Firefox (and Chrome) - both browsers completely ignore this directive.  Could this be a bug in Mozilla?

-------------------- more info ---------------------------------

I think the problem is with the following jquery script with my CHAT (which is doing the calling to the api).  It's worked for 12 years (and still works on old versions), so I'm looking to see what's been deprecated. I suspect that SignalR may be the issue and confusing the browser(s) - since SignalR is making the request (not sure, though -just guessing now). Sorry for not mentioning this sooner.

```<code>        $.connection.hub.start()
        .done(function () {
            var existingChatId = getExistingChatId(chatKey);
            $.get("https://services.mywebsite.com/api/geodata/", function (response) {
                myHub.server.logVisit(document.location.href, document.referrer, response.city_name, response.region_name, response.country_name, existingChatId);
            }, "json");
        })
        .fail(function () { chatRefreshState(false); });
</code>```

------------------- after using wildcards for CORS headers --------------

```<code>HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
Expires: -1
Server: Microsoft-IIS/10.0
X-Content-Type-Options: nosniff
X-SourceFiles: =?UTF-8?B?RDpcU2l0ZXNcaWNhcnBldGlsZXMyXFdlYlxzaWduYWxyXHN0YXJ0?=
X-Powered-By: ASP.NET
X-Frame-Options: SAMEORIGIN
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: *
Date: Sun, 07 Jun 2020 10:31:35 GMT
</code>```

Still no joy - Headers are there. Must be a bug in ASP.NET webforms, IIS, SignalR  (please note this is NOT MVC).  Time to upgrade this site for this client. No one supports webforms anymore, anyway - it's dead.

答:
Do you have app.UseCors() in your middleware pipeline, before app.MapSignalR()?

You can start with app.UseCors(CorsOptions.AllowAll) to check if it'll work and then add your own domain.

```<code>app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
</code>```

Body:
I set up my website (running IIS8.5) to send the response header for CORS to a subdomain off my main domain and the header response is getting to Firefox just fine. All plug-ins, ad-blockers, etc, are disabled and I can see the header in the DOM inspector.
I've tried:

Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: https://services.mywebsite.com
Access-Control-Allow-Origin: http://services.mywebsite.com
Access-Control-Allow-Origin: null
Access-Control-Allow-Origin: "null"

I've verified the SSL Certificate is working just fine (it's a wildcard cert for *.mywebsite.com from Sectigo and I've verified that the entire certification path is working properly)

There are no other response headers except for: X-Frame-Options: SAMEORIGIN  ,however, I removed it with the same result.
The site predates CORS by years (ASP.NET Webforms) and there are no other settings I can find that would prevent Firefox from acknowledging this response header.

I've read dozens of posts here (usually someone had a self-signed cert or forgot something) but am at a loss on what is wrong?

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://services.mywebsite.com/api/geodata/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

It's absolutely NOT MISSING!  WTF Firefox?

Pulling hair out here. Anyone?

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
Expires: -1
Server: Microsoft-IIS/8.5
X-Content-Type-Options: nosniff
Access-Control-Allow-Origin: https://services.mywebsite.com
X-Frame-Options: SAMEORIGIN
Date: Wed, 27 May 2020 08:28:05 GMT

Someone else suggested adding a CORS module to IIS.  I did, then added to my web.config file the following (in system.webserver section):

<cors enabled="true">
    <add origin="*" allowed="true" >
        <allowHeaders allowAllRequestedHeaders="true" />
    </add>
</cors>

No Joy! Same message from Firefox (and Chrome) - both browsers completely ignore this directive.  Could this be a bug in Mozilla?

-------------------- more info ---------------------------------

I think the problem is with the following jquery script with my CHAT (which is doing the calling to the api).  It's worked for 12 years (and still works on old versions), so I'm looking to see what's been deprecated. I suspect that SignalR may be the issue and confusing the browser(s) - since SignalR is making the request (not sure, though -just guessing now). Sorry for not mentioning this sooner.

        $.connection.hub.start()
        .done(function () {
            var existingChatId = getExistingChatId(chatKey);
            $.get("https://services.mywebsite.com/api/geodata/", function (response) {
                myHub.server.logVisit(document.location.href, document.referrer, response.city_name, response.region_name, response.country_name, existingChatId);
            }, "json");
        })
        .fail(function () { chatRefreshState(false); });

------------------- after using wildcards for CORS headers --------------

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
Expires: -1
Server: Microsoft-IIS/10.0
X-Content-Type-Options: nosniff
X-SourceFiles: =?UTF-8?B?RDpcU2l0ZXNcaWNhcnBldGlsZXMyXFdlYlxzaWduYWxyXHN0YXJ0?=
X-Powered-By: ASP.NET
X-Frame-Options: SAMEORIGIN
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: *
Date: Sun, 07 Jun 2020 10:31:35 GMT

Still no joy - Headers are there. Must be a bug in ASP.NET webforms, IIS, SignalR  (please note this is NOT MVC).  Time to upgrade this site for this client. No one supports webforms anymore, anyway - it's dead.

Body:
Do you have app.UseCors() in your middleware pipeline, before app.MapSignalR()?

You can start with app.UseCors(CorsOptions.AllowAll) to check if it'll work and then add your own domain.

app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();


问:
Call cmdlet directly without loading it via $profile
I created a cmdlet *.ps1 file with a single function Backup-Data that I load into my $profile with Import-Module Backup-Data.ps1.

Everytime I test it, I save the file and reopen the powershell console but this process is very tedious. So, I was wondering whether there is a way to call that directly from the console?

答:
Unless you're defining new types in the Backup-Data.ps1 script, the following should suffice for restarting your testing in an interactive session:

```<code>Remove-Module Backup-Data -Force
Import-Module Backup-Data.ps1
</code>```

Body:
Unless you're defining new types in the Backup-Data.ps1 script, the following should suffice for restarting your testing in an interactive session:

Remove-Module Backup-Data -Force
Import-Module Backup-Data.ps1


问:
disqus comment count update
I am trying to get the comment count from disqus. Now To count comments, I just use javascript provided by Disqus like this

```<code> function () {
            var s = document.createElement('script');
            s.async = true;
            s.type = 'text/javascript';
            s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
            (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
        }()
</code>```

Btw, I look into them which are not updated right now.
So I want to solve this problem how to update the number of comments in real-time.
Do you have any idea for this?
Please let me know.

Thanks

答:
To load disqus comments count dynamically add the following code to your template:

```<code>DISQUSWIDGETS.getCount({reset: true});
</code>```

One common use case of this function is to update elements on the page that were not available via the initial load of count.js.

Title: disqus comment count update

Body:
I am trying to get the comment count from disqus. Now To count comments, I just use javascript provided by Disqus like this

 function () {
            var s = document.createElement('script');
            s.async = true;
            s.type = 'text/javascript';
            s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
            (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
        }()

Btw, I look into them which are not updated right now.
So I want to solve this problem how to update the number of comments in real-time.
Do you have any idea for this?
Please let me know.

Thanks

Body:
To load disqus comments count dynamically add the following code to your template:

DISQUSWIDGETS.getCount({reset: true});

One common use case of this function is to update elements on the page that were not available via the initial load of count.js.


问:
How to solve "cURL error 60: SSL certificate problem"?
I use WAMP on a local development environment and am trying to send mail but get the error message:

exception: "SendinBlue\Client\ApiException"

file: "\vendor\sendinblue\api-v3-sdk\lib\Api\SMTPApi.php"

line: 3986

message: "[0] cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)"

Laravel: 6.18.15

webup/laravel-sendinblue: 2.0.3

sendinblue/api-v3-sdk: 6.3.0

PHP: 7.2.25

答:
Sendinblue had an issue with their SMTP API on 30 May. According to their status page https://status.sendinblue.com/
Their statement on June 1, 2020 11:27AM CEST:

[Resolved] On Saturday May 30th, 2020, at 10:48 UTC, an SSL root
  certificate belonging to a certificate authority and used to sign one
  of our certificate expired. Due to this some customers may have faced
  some issues with the following application: • Automation export
  contact was impacted on May 31th, 2020, 6:00 UTC. •
  smtp-relay.sendinblue.com on SSL port, was impacted for some customers
  using old browser and/or old openssl version lower than 1.1.0. We
  fixed the issue on May 31th, 2020, 18:23 UTC, by updating the expired
  Root certificat. We are deeply sorry for the inconvenience, and we are
  working to improve our response to this kind of incident.

It should work now.


问:
flutter program work okay on chrome, but cannot work correctly on web server
I'm pretty new to flutter, and wrote the following flutter program to get the client IP address and location. I'm calling "http://ip-api.com/json" for IP address and location information. The program works okay by using device "chrome" and "web server", I can print client's location on the page.

.
When I deployed to github webpage or firebase hosting , and the program  shows "loading circle" for ever. It seems that the program cannot get the ip address after it was deployed to the github web server (or other web server).

I found the program throw "XMLHTTPRequest Error" once i deployed it to Github html page or firebase hosting.  It works fine on the local web server or chrome.  any suggestion on that?  Thanks a lot.

```<code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class IP_info{
  final String IP;
  final String city;
  final String ZIP;
  final String st_code;
  final String state_name;
  final String country_code;
  final String country_name;

  IP_info({this.IP, this.city, this.st_code,this.ZIP,
     this.state_name,this.country_code,this.country_name});

  factory IP_info.fromJson(Map<String, dynamic> json){
    return IP_info(
      IP:json['query'],
      ZIP:json['zip'],
      city:json['city'],
      country_code:json['countryCode'],
      st_code:json['region'],
      country_name:json['country_name'],
      state_name:json['regionName'],
    );
  }

}
void main() {
  runApp(MaterialApp(
      title: 'Covid 19 cases near you',
      home: MyApp()
  ),
  );
}

class MyApp extends StatefulWidget{
  @override
  State<StatefulWidget> createState()  => MyAppState();
}

class MyAppState extends State<MyApp> {

  bool _isLoading = false;
  IP_info ip_info;

  @override
  void initState() {
     _isLoading=true;
    _getPublicIP();
  }

_getPublicIP() async {
    try {

      const url = 'http://ip-api.com/json';

      final response = await http.get(url);
      if (response.statusCode == 200) {
        ip_info = IP_info.fromJson(json.decode(response.body));
        print(ip_info.toString());

        setState(() {
          _isLoading = false;
        });
        }
      else {
        // The request failed with a non-200 code
        print(response.statusCode);
        print(response.body);
      }

    } catch (e) {
      print(e);
    }
  }

 @override
  Widget build(BuildContext context) {
    return  Scaffold(
        appBar: AppBar(title: Text('Testing IP address'),    ),
        body: Container(
          padding: const EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            color: Colors.white,
          ),
          child: _isLoading? Center(
              child: Column(children: [
                CircularProgressIndicator(),
                SizedBox(height: 10,),
                Text("Loading your location infomation ...", style: TextStyle(color: Colors.blueAccent),),
              ]
              )
          )
              : new Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center ,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget> [
              Text('You are in ${ip_info.city} ${ip_info.state_name} ',
                style: TextStyle(
                  fontWeight: FontWeight.bold,),
              ),

            ],
          ),
        )
    );
  }
</code>```

答: I switched to geolocation-db.com/json (instead of using 'ip-api.com/json) to get the location information of the client's node, and it works! I think it is related to the server side. I think it may be related to the web request has to be https instead of http. </p>

Body:
I'm pretty new to flutter, and wrote the following flutter program to get the client IP address and location. I'm calling "http://ip-api.com/json" for IP address and location information. The program works okay by using device "chrome" and "web server", I can print client's location on the page.

.
When I deployed to github webpage or firebase hosting , and the program  shows "loading circle" for ever. It seems that the program cannot get the ip address after it was deployed to the github web server (or other web server).

I found the program throw "XMLHTTPRequest Error" once i deployed it to Github html page or firebase hosting.  It works fine on the local web server or chrome.  any suggestion on that?  Thanks a lot.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class IP_info{
  final String IP;
  final String city;
  final String ZIP;
  final String st_code;
  final String state_name;
  final String country_code;
  final String country_name;

  IP_info({this.IP, this.city, this.st_code,this.ZIP,
     this.state_name,this.country_code,this.country_name});

  factory IP_info.fromJson(Map<String, dynamic> json){
    return IP_info(
      IP:json['query'],
      ZIP:json['zip'],
      city:json['city'],
      country_code:json['countryCode'],
      st_code:json['region'],
      country_name:json['country_name'],
      state_name:json['regionName'],
    );
  }

}
void main() {
  runApp(MaterialApp(
      title: 'Covid 19 cases near you',
      home: MyApp()
  ),
  );
}

class MyApp extends StatefulWidget{
  @override
  State<StatefulWidget> createState()  => MyAppState();
}

class MyAppState extends State<MyApp> {

  bool _isLoading = false;
  IP_info ip_info;

  @override
  void initState() {
     _isLoading=true;
    _getPublicIP();
  }

_getPublicIP() async {
    try {

      const url = 'http://ip-api.com/json';

      final response = await http.get(url);
      if (response.statusCode == 200) {
        ip_info = IP_info.fromJson(json.decode(response.body));
        print(ip_info.toString());

        setState(() {
          _isLoading = false;
        });
        }
      else {
        // The request failed with a non-200 code
        print(response.statusCode);
        print(response.body);
      }

    } catch (e) {
      print(e);
    }
  }

 @override
  Widget build(BuildContext context) {
    return  Scaffold(
        appBar: AppBar(title: Text('Testing IP address'),    ),
        body: Container(
          padding: const EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            color: Colors.white,
          ),
          child: _isLoading? Center(
              child: Column(children: [
                CircularProgressIndicator(),
                SizedBox(height: 10,),
                Text("Loading your location infomation ...", style: TextStyle(color: Colors.blueAccent),),
              ]
              )
          )
              : new Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center ,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget> [
              Text('You are in ${ip_info.city} ${ip_info.state_name} ',
                style: TextStyle(
                  fontWeight: FontWeight.bold,),
              ),

            ],
          ),
        )
    );
  }


问:
access header of current page in js
I'm redirecting to another url from my Spring Application. To do so I'm using this :

```<code>    @GetMapping
    public void method(HttpServletResponse httpServletResponse) {
        httpServletResponse.setHeader("Location", "http://localhost:3000/");
        httpServletResponse.setHeader("TOKEN","123");
        httpServletResponse.setStatus(302);
    }
</code>```

Now I can redirect to any domain/path. But the biggest question is how can I retrieve that token from client part ?

I mean in my website(using plain JS only).

I had plan to use socket/rsocket, but now I think I would be better if I establish a connection only after user is verified or token is received in client.

I tried : window.pageHeaders["TOKEN"], but it says : Cannot read property 'TOKEN' of undefined

答:
Instead of redirecting to :3000, redirect to :3000/token, call token from there, retrieve the token, then redirect to :3000 or wherever you want.

Maybe PHP support the requested kind of way, just react doesn't or I can't. So let's just skip that, as the mentioned solution works, stick to this.

Title: access header of current page in js

Body:
I'm redirecting to another url from my Spring Application. To do so I'm using this :

    @GetMapping
    public void method(HttpServletResponse httpServletResponse) {
        httpServletResponse.setHeader("Location", "http://localhost:3000/");
        httpServletResponse.setHeader("TOKEN","123");
        httpServletResponse.setStatus(302);
    }

Now I can redirect to any domain/path. But the biggest question is how can I retrieve that token from client part ?

I mean in my website(using plain JS only).

I had plan to use socket/rsocket, but now I think I would be better if I establish a connection only after user is verified or token is received in client.

I tried : window.pageHeaders["TOKEN"], but it says : Cannot read property 'TOKEN' of undefined


问:
String manipulation, removing a single comma
UPDATE 1:

This is how I am attempting to build the string:

```<code>header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}
</code>```

ORIGINAL QUESTION:

I have a string similar to this:

```<code>$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";
</code>```

How do I remove the last comma?

答:
Instead of fixing the error you should fix the cause and don’t insert that last comma in the first place.

The best would be to build the data structure using PHP’s native data types and then use json_encode to convert it to a JSON data string:

```<code>function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());
    $channel = array(
        'title'       => $title,
        'link'        => 'http://www.example.com/external.php',
        'description' => 'company description goes here',
        'items'       => array()
    );
    while ($row = mysql_fetch_array($results)) {
        $channel['items'][] = array(
            'title'       => $row['title'],
            'link'        => $row['link'],
            'guid'        => $row['link'],
            'pubDate'     => $row['date'],
            'description' => $row['description']
        );
    }
    mysql_close($connection);
    $data = array('rss' => array('channels' => array($channel)));
    return json_encode($data);
}
</code>```

Body:
UPDATE 1:

This is how I am attempting to build the string:

header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}

ORIGINAL QUESTION:

I have a string similar to this:

$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";

How do I remove the last comma?

Body:
Instead of fixing the error you should fix the cause and don’t insert that last comma in the first place.

The best would be to build the data structure using PHP’s native data types and then use json_encode to convert it to a JSON data string:

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());
    $channel = array(
        'title'       => $title,
        'link'        => 'http://www.example.com/external.php',
        'description' => 'company description goes here',
        'items'       => array()
    );
    while ($row = mysql_fetch_array($results)) {
        $channel['items'][] = array(
            'title'       => $row['title'],
            'link'        => $row['link'],
            'guid'        => $row['link'],
            'pubDate'     => $row['date'],
            'description' => $row['description']
        );
    }
    mysql_close($connection);
    $data = array('rss' => array('channels' => array($channel)));
    return json_encode($data);
}


问:
Janusgraph JanusGraphException Could not commit transaction due to exception during persistence
I got janusgraph 0.4.0

apache.tinkerpop.gremlin 3.4.2

com.github.jespersm.spring-data-gremlin 1.0.0-SNAPSHOT

and Widnows 10

And i try to run such a test

```<code>    Graph graph = JanusGraphFactory.open("inmemory");
    graph.traversal()
         .addV("Org").iterate();

    graph.traversal().tx().commit();
</code>```

And thats all

when i run this test (or any tests where is JanusGraphFactory.open and tx().commit() after that),
 i get this exception

```<code>    [2019-11-18 16:50:56,774]  INFO builder.ReadConfigurationBuilder: Set default timestamp provider MICRO
    [2019-11-18 16:50:56,790]  INFO idmanagement.UniqueInstanceIdRetriever: Generated unique-instance-id=c0a8014f15872-DESKTOP-DQPEHPP1
    [2019-11-18 16:50:56,801]  INFO diskstorage.Backend: Initiated backend operations thread pool of size 24
    [2019-11-18 16:50:56,875]  INFO kcvs.KCVSLog: Loaded unidentified ReadMarker start time 2019-11-18T13:50:56.873113Z into org.janusgraph.diskstorage.log.kcvs.KCVSLog$MessagePuller@6a0659ac
    [2019-11-18 16:50:57,197]  WARN consistentkey.ConsistentKeyLocker: Skipping outdated lock on KeyColumn [k=0x 16-165-160-118-108- 30- 80-101-114-115-111-238, c=0x  0] with our rid ( 99- 48- 97- 56- 48- 49- 52-102- 49- 53- 56- 55- 50- 45- 68- 69- 83- 75- 84- 79- 80- 45- 68- 81- 80- 69- 72- 80- 80- 49) but mismatched timestamp (actual ts 2019-11-18T13:50:57.094518Z, expected ts 2019-11-18T13:50:57.094518800Z)
    [2019-11-18 16:50:57,198] ERROR database.StandardJanusGraph: Could not commit transaction [1] due to storage exception in system-commit
    org.janusgraph.core.JanusGraphException: Could not execute operation due to backend exception

    org.janusgraph.core.JanusGraphException: Could not commit transaction due to exception during persistence

        at org.janusgraph.graphdb.transaction.StandardJanusGraphTx.commit(StandardJanusGraphTx.java:1475)
        at org.janusgraph.graphdb.tinkerpop.JanusGraphBlueprintsGraph$GraphTransaction.doCommit(JanusGraphBlueprintsGraph.java:297)
        at org.apache.tinkerpop.gremlin.structure.util.AbstractTransaction.commit(AbstractTransaction.java:104)
        at factograph.core.project.cypher.CypherTransformerTest.someError(CypherTransformerTest.java:159)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:567)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
        at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
        at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
        at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    Caused by: org.janusgraph.core.JanusGraphException: Could not execute operation due to backend exception
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:56)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction.persist(CacheTransaction.java:91)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction.flushInternal(CacheTransaction.java:139)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction.commit(CacheTransaction.java:196)
        at org.janusgraph.diskstorage.BackendTransaction.commit(BackendTransaction.java:150)
        at org.janusgraph.graphdb.database.StandardJanusGraph.commit(StandardJanusGraph.java:717)
        at org.janusgraph.graphdb.transaction.StandardJanusGraphTx.commit(StandardJanusGraphTx.java:1464)
        ... 25 more
    Caused by: org.janusgraph.diskstorage.locking.PermanentLockingException: Permanent locking failure
        at org.janusgraph.diskstorage.locking.AbstractLocker.checkLocks(AbstractLocker.java:359)
        at org.janusgraph.diskstorage.locking.consistentkey.ExpectedValueCheckingTransaction.checkAllLocks(ExpectedValueCheckingTransaction.java:175)
        at org.janusgraph.diskstorage.locking.consistentkey.ExpectedValueCheckingTransaction.prepareForMutations(ExpectedValueCheckingTransaction.java:154)
        at org.janusgraph.diskstorage.locking.consistentkey.ExpectedValueCheckingStoreManager.mutateMany(ExpectedValueCheckingStoreManager.java:72)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction$1.call(CacheTransaction.java:94)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction$1.call(CacheTransaction.java:91)
        at org.janusgraph.diskstorage.util.BackendOperation.executeDirect(BackendOperation.java:68)
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:54)
        ... 31 more
    Caused by: org.janusgraph.diskstorage.PermanentBackendException: Read 1 locks with our rid  99- 48- 97- 56- 48- 49- 52-102- 49- 53- 56- 55- 50- 45- 68- 69- 83- 75- 84- 79- 80- 45- 68- 81- 80- 69- 72- 80- 80- 49 but mismatched timestamps; no lock column contained our timestamp (2019-11-18T13:50:57.094518800Z)
        at org.janusgraph.diskstorage.locking.consistentkey.ConsistentKeyLocker.checkSeniority(ConsistentKeyLocker.java:528)
        at org.janusgraph.diskstorage.locking.consistentkey.ConsistentKeyLocker.checkSingleLock(ConsistentKeyLocker.java:454)
        at org.janusgraph.diskstorage.locking.consistentkey.ConsistentKeyLocker.checkSingleLock(ConsistentKeyLocker.java:118)
        at org.janusgraph.diskstorage.locking.AbstractLocker.checkLocks(AbstractLocker.java:351)
        ... 38 more
</code>```

I was triyng everything!

Remove all m2 folder and mvn clean + reimport, but that do not help

Reload idea by admin and clean idea chache

I tried to run 'bin/JanusGraph.sh clean', but that doest help

Remove every local gremlin and janusgraph dirs, and reload them again

Found one little mention on stackoverflow JanusGraphException: Could not execute operation due to backend exception, but cant undestand whats happend in this solution, what the "zip" does the author mention and how does it help him

Please, somebody, do you know the answer???

Its a VERY strange problem...

答: More info here https://github.com/JanusGraph/janusgraph/issues/1979. It will be fixed in next release</p>

Body:
I got janusgraph 0.4.0

apache.tinkerpop.gremlin 3.4.2

com.github.jespersm.spring-data-gremlin 1.0.0-SNAPSHOT

and Widnows 10

And i try to run such a test

    Graph graph = JanusGraphFactory.open("inmemory");
    graph.traversal()
         .addV("Org").iterate();

    graph.traversal().tx().commit();

And thats all

when i run this test (or any tests where is JanusGraphFactory.open and tx().commit() after that),
 i get this exception

    [2019-11-18 16:50:56,774]  INFO builder.ReadConfigurationBuilder: Set default timestamp provider MICRO
    [2019-11-18 16:50:56,790]  INFO idmanagement.UniqueInstanceIdRetriever: Generated unique-instance-id=c0a8014f15872-DESKTOP-DQPEHPP1
    [2019-11-18 16:50:56,801]  INFO diskstorage.Backend: Initiated backend operations thread pool of size 24
    [2019-11-18 16:50:56,875]  INFO kcvs.KCVSLog: Loaded unidentified ReadMarker start time 2019-11-18T13:50:56.873113Z into org.janusgraph.diskstorage.log.kcvs.KCVSLog$MessagePuller@6a0659ac
    [2019-11-18 16:50:57,197]  WARN consistentkey.ConsistentKeyLocker: Skipping outdated lock on KeyColumn [k=0x 16-165-160-118-108- 30- 80-101-114-115-111-238, c=0x  0] with our rid ( 99- 48- 97- 56- 48- 49- 52-102- 49- 53- 56- 55- 50- 45- 68- 69- 83- 75- 84- 79- 80- 45- 68- 81- 80- 69- 72- 80- 80- 49) but mismatched timestamp (actual ts 2019-11-18T13:50:57.094518Z, expected ts 2019-11-18T13:50:57.094518800Z)
    [2019-11-18 16:50:57,198] ERROR database.StandardJanusGraph: Could not commit transaction [1] due to storage exception in system-commit
    org.janusgraph.core.JanusGraphException: Could not execute operation due to backend exception

    org.janusgraph.core.JanusGraphException: Could not commit transaction due to exception during persistence

        at org.janusgraph.graphdb.transaction.StandardJanusGraphTx.commit(StandardJanusGraphTx.java:1475)
        at org.janusgraph.graphdb.tinkerpop.JanusGraphBlueprintsGraph$GraphTransaction.doCommit(JanusGraphBlueprintsGraph.java:297)
        at org.apache.tinkerpop.gremlin.structure.util.AbstractTransaction.commit(AbstractTransaction.java:104)
        at factograph.core.project.cypher.CypherTransformerTest.someError(CypherTransformerTest.java:159)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:567)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
        at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
        at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
        at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    Caused by: org.janusgraph.core.JanusGraphException: Could not execute operation due to backend exception
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:56)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction.persist(CacheTransaction.java:91)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction.flushInternal(CacheTransaction.java:139)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction.commit(CacheTransaction.java:196)
        at org.janusgraph.diskstorage.BackendTransaction.commit(BackendTransaction.java:150)
        at org.janusgraph.graphdb.database.StandardJanusGraph.commit(StandardJanusGraph.java:717)
        at org.janusgraph.graphdb.transaction.StandardJanusGraphTx.commit(StandardJanusGraphTx.java:1464)
        ... 25 more
    Caused by: org.janusgraph.diskstorage.locking.PermanentLockingException: Permanent locking failure
        at org.janusgraph.diskstorage.locking.AbstractLocker.checkLocks(AbstractLocker.java:359)
        at org.janusgraph.diskstorage.locking.consistentkey.ExpectedValueCheckingTransaction.checkAllLocks(ExpectedValueCheckingTransaction.java:175)
        at org.janusgraph.diskstorage.locking.consistentkey.ExpectedValueCheckingTransaction.prepareForMutations(ExpectedValueCheckingTransaction.java:154)
        at org.janusgraph.diskstorage.locking.consistentkey.ExpectedValueCheckingStoreManager.mutateMany(ExpectedValueCheckingStoreManager.java:72)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction$1.call(CacheTransaction.java:94)
        at org.janusgraph.diskstorage.keycolumnvalue.cache.CacheTransaction$1.call(CacheTransaction.java:91)
        at org.janusgraph.diskstorage.util.BackendOperation.executeDirect(BackendOperation.java:68)
        at org.janusgraph.diskstorage.util.BackendOperation.execute(BackendOperation.java:54)
        ... 31 more
    Caused by: org.janusgraph.diskstorage.PermanentBackendException: Read 1 locks with our rid  99- 48- 97- 56- 48- 49- 52-102- 49- 53- 56- 55- 50- 45- 68- 69- 83- 75- 84- 79- 80- 45- 68- 81- 80- 69- 72- 80- 80- 49 but mismatched timestamps; no lock column contained our timestamp (2019-11-18T13:50:57.094518800Z)
        at org.janusgraph.diskstorage.locking.consistentkey.ConsistentKeyLocker.checkSeniority(ConsistentKeyLocker.java:528)
        at org.janusgraph.diskstorage.locking.consistentkey.ConsistentKeyLocker.checkSingleLock(ConsistentKeyLocker.java:454)
        at org.janusgraph.diskstorage.locking.consistentkey.ConsistentKeyLocker.checkSingleLock(ConsistentKeyLocker.java:118)
        at org.janusgraph.diskstorage.locking.AbstractLocker.checkLocks(AbstractLocker.java:351)
        ... 38 more

I was triyng everything!

Remove all m2 folder and mvn clean + reimport, but that do not help

Reload idea by admin and clean idea chache

I tried to run 'bin/JanusGraph.sh clean', but that doest help

Remove every local gremlin and janusgraph dirs, and reload them again

Found one little mention on stackoverflow JanusGraphException: Could not execute operation due to backend exception, but cant undestand whats happend in this solution, what the "zip" does the author mention and how does it help him

Please, somebody, do you know the answer???

Its a VERY strange problem...


问:
Run async function in the body of a scaffold
I want to decide what content is displayed in the screen on the basis of a boolean variable called isAdmin. The value for this field is fetched from firestore.

Here's what I got so far:

```<code>Future<bool> isUserAnAdmin() async {
    var snap = await Firestore.instance
        .collection("Users")
        .document(UserSingleton().fireUser.uid)
        .get();
    UserSingleton().user = User.fromJson(snap.data);
    return UserSingleton().user.isAdmin;
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text("hemlp"),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 15),
              child: GestureDetector(
                child: Icon(Icons.exit_to_app),
                onTap: () async => await Auth.logoutUser().then(
                    (value) => Navigator.pushNamed(context, '/SignInPage')),
              ),
            )
          ],
        ),
        body: isUserAnAdmin() == true ? AdminPage() : PatientPage());
  }
</code>```

The problem is that I'm always routed to PatientPage(), irrespective of the value of isAdmin. I suspect that this is happening because it isn't waiting for the value returned by isUserAnAdmin(). I thought I could just await isUserAnAdmin(), but I can't use await in the body of the Scaffold.

I thought I could resolve the issue by doing this:

```<code>body: isUserAnAdmin().then((value) {
          value == true ? AdminPage() : PatientPage();
        })
</code>```

But I get an error that states:

```<code>The argument type 'Future<Null>' can't be assigned to the parameter type 'Widget'.
</code>```

Any idea on how I can resolve this?

答:
You body should using a FutureBuilder:</p>

```<code>body: FutureBuilder<bool>(
  future: isUserAnAdmin(),
  builder: (context, data) {
    if (data.hasData && data.data) {
      return AdminPage();
    } else {
      return PatientPage();
    }
  },
)
</code>```

Body:
I want to decide what content is displayed in the screen on the basis of a boolean variable called isAdmin. The value for this field is fetched from firestore.

Here's what I got so far:

Future<bool> isUserAnAdmin() async {
    var snap = await Firestore.instance
        .collection("Users")
        .document(UserSingleton().fireUser.uid)
        .get();
    UserSingleton().user = User.fromJson(snap.data);
    return UserSingleton().user.isAdmin;
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          title: Text("hemlp"),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 15),
              child: GestureDetector(
                child: Icon(Icons.exit_to_app),
                onTap: () async => await Auth.logoutUser().then(
                    (value) => Navigator.pushNamed(context, '/SignInPage')),
              ),
            )
          ],
        ),
        body: isUserAnAdmin() == true ? AdminPage() : PatientPage());
  }

The problem is that I'm always routed to PatientPage(), irrespective of the value of isAdmin. I suspect that this is happening because it isn't waiting for the value returned by isUserAnAdmin(). I thought I could just await isUserAnAdmin(), but I can't use await in the body of the Scaffold.

I thought I could resolve the issue by doing this:

body: isUserAnAdmin().then((value) {
          value == true ? AdminPage() : PatientPage();
        })

But I get an error that states:

The argument type 'Future<Null>' can't be assigned to the parameter type 'Widget'.

Any idea on how I can resolve this?

Body:
You body should using a FutureBuilder:

body: FutureBuilder<bool>(
  future: isUserAnAdmin(),
  builder: (context, data) {
    if (data.hasData && data.data) {
      return AdminPage();
    } else {
      return PatientPage();
    }
  },
)


问:
Oracle SQL - Count only one of specified value
I do hope someone can help me with this.

I am doing two count functions on on of my columns, both specified by where the column has a specific text (see below code). On my count for meeting (WHERE EVENT_TYPE = 'meeting_start'), I have found that this can pop up more than once within the same meeting. I need to only count this once per meeting event id and cannot find a way to do this.

```<code>select I.CRM_INSTANCE_NAME,
       C.CUSTOMER_NAME,
       U.USER_NAME,
       ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0') AS USER_ACTIVATION_DATE,
       ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0') AS LAST_ACTIVITY_DATE,
       COUNT(E.EVENT_TYPE) AS MEETING,
       COUNT(F.EVENT_TYPE) AS FINALISED

       FROM SBX_USERS U
        LEFT JOIN SBX_CUSTOMERS C on U.CUSTOMER_ID = C.CUSTOMER_ID
        LEFT JOIN SBX_CRM_INSTANCES I on C.CRM_INSTANCE_ID = I.CRM_INSTANCE_ID
        LEFT JOIN SBX_MEETING M on U.USER_ID = M.USER_ID
        LEFT JOIN SBX_EVENTS E ON SOURCE_ID  = M.MEETING_ID
        LEFT JOIN (SELECT * FROM SBX_EVENTS WHERE EVENT_TYPE = 'meeting_start' AND EVENT_CREATION_DATE >=add_months(sysdate, -12)) E on E.SOURCE_ID = M.MEETING_ID
        LEFT JOIN (SELECT * FROM SBX_EVENTS WHERE EVENT_TYPE = 'finalize'AND EVENT_CREATION_DATE >=add_months(sysdate, -12)) F on F.SOURCE_ID = M.MEETING_ID

where U.ENABLED_FLAG IN ('Y','E')

group by  I.CRM_INSTANCE_NAME, C.CUSTOMER_NAME, U.USER_NAME, ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0'), ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0')
order by  I.CRM_INSTANCE_NAME;
</code>```

Above is the code I am using at that moment, thanks in advance for your help.

Regards

Dr

答:
You don't need the two extra outer joins from sbx_events, you can use conditional aggregation instead, e.g. something like:

```<code>select I.CRM_INSTANCE_NAME,
       C.CUSTOMER_NAME,
       U.USER_NAME,
       ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0') AS USER_ACTIVATION_DATE,
       ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0') AS LAST_ACTIVITY_DATE,
       COUNT(DISTINCT CASE WHEN E.EVENT_TYPE = 'meeting_start' AND eVENT_CREATION_DATE >=add_months(sysdate, -12) THEN 1 END) AS MEETING,
       COUNT(CASE WHEN E.EVENT_TYPE = 'finalize' AND eVENT_CREATION_DATE >=add_months(sysdate, -12) THEN 1 END) AS FINALISED
       FROM SBX_USERS U
        LEFT JOIN SBX_CUSTOMERS C on U.CUSTOMER_ID = C.CUSTOMER_ID
        LEFT JOIN SBX_CRM_INSTANCES I on C.CRM_INSTANCE_ID = I.CRM_INSTANCE_ID
        LEFT JOIN SBX_MEETING M on U.USER_ID = M.USER_ID
        LEFT JOIN SBX_EVENTS E ON SOURCE_ID  = M.MEETING_ID
where U.ENABLED_FLAG IN ('Y','E')
group by  I.CRM_INSTANCE_NAME, C.CUSTOMER_NAME, U.USER_NAME, ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0'), ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0')
order by  I.CRM_INSTANCE_NAME;
</code>```

N.B. you had two tables aliased as e, so I've taken a guess as to which one you meant in the counts.

Also, if you only care about the meeting_start and finalize event_types, you could add that as a join condition from the sbx_events table, along with the date restriction.

Body:
I do hope someone can help me with this.

I am doing two count functions on on of my columns, both specified by where the column has a specific text (see below code). On my count for meeting (WHERE EVENT_TYPE = 'meeting_start'), I have found that this can pop up more than once within the same meeting. I need to only count this once per meeting event id and cannot find a way to do this.

select I.CRM_INSTANCE_NAME,
       C.CUSTOMER_NAME,
       U.USER_NAME,
       ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0') AS USER_ACTIVATION_DATE,
       ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0') AS LAST_ACTIVITY_DATE,
       COUNT(E.EVENT_TYPE) AS MEETING,
       COUNT(F.EVENT_TYPE) AS FINALISED

       FROM SBX_USERS U
        LEFT JOIN SBX_CUSTOMERS C on U.CUSTOMER_ID = C.CUSTOMER_ID
        LEFT JOIN SBX_CRM_INSTANCES I on C.CRM_INSTANCE_ID = I.CRM_INSTANCE_ID
        LEFT JOIN SBX_MEETING M on U.USER_ID = M.USER_ID
        LEFT JOIN SBX_EVENTS E ON SOURCE_ID  = M.MEETING_ID
        LEFT JOIN (SELECT * FROM SBX_EVENTS WHERE EVENT_TYPE = 'meeting_start' AND EVENT_CREATION_DATE >=add_months(sysdate, -12)) E on E.SOURCE_ID = M.MEETING_ID
        LEFT JOIN (SELECT * FROM SBX_EVENTS WHERE EVENT_TYPE = 'finalize'AND EVENT_CREATION_DATE >=add_months(sysdate, -12)) F on F.SOURCE_ID = M.MEETING_ID

where U.ENABLED_FLAG IN ('Y','E')

group by  I.CRM_INSTANCE_NAME, C.CUSTOMER_NAME, U.USER_NAME, ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0'), ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0')
order by  I.CRM_INSTANCE_NAME;

Above is the code I am using at that moment, thanks in advance for your help.

Regards

Dr

Body:
You don't need the two extra outer joins from sbx_events, you can use conditional aggregation instead, e.g. something like:

select I.CRM_INSTANCE_NAME,
       C.CUSTOMER_NAME,
       U.USER_NAME,
       ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0') AS USER_ACTIVATION_DATE,
       ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0') AS LAST_ACTIVITY_DATE,
       COUNT(DISTINCT CASE WHEN E.EVENT_TYPE = 'meeting_start' AND eVENT_CREATION_DATE >=add_months(sysdate, -12) THEN 1 END) AS MEETING,
       COUNT(CASE WHEN E.EVENT_TYPE = 'finalize' AND eVENT_CREATION_DATE >=add_months(sysdate, -12) THEN 1 END) AS FINALISED
       FROM SBX_USERS U
        LEFT JOIN SBX_CUSTOMERS C on U.CUSTOMER_ID = C.CUSTOMER_ID
        LEFT JOIN SBX_CRM_INSTANCES I on C.CRM_INSTANCE_ID = I.CRM_INSTANCE_ID
        LEFT JOIN SBX_MEETING M on U.USER_ID = M.USER_ID
        LEFT JOIN SBX_EVENTS E ON SOURCE_ID  = M.MEETING_ID
where U.ENABLED_FLAG IN ('Y','E')
group by  I.CRM_INSTANCE_NAME, C.CUSTOMER_NAME, U.USER_NAME, ltrim(TO_CHAR(U.CREATED_DATE ,'mm-yyyy'),'0'), ltrim(TO_CHAR(U.LAST_UPDATED_DATE ,'dd-mm-yyyy'),'0')
order by  I.CRM_INSTANCE_NAME;

N.B. you had two tables aliased as e, so I've taken a guess as to which one you meant in the counts.

Also, if you only care about the meeting_start and finalize event_types, you could add that as a join condition from the sbx_events table, along with the date restriction.


答:
You should use a FutureBuilder in body.
This will call your async function and update when result is ready.</p>

Title: Run async function in the body of a scaffold


问:
Reading file string into an array (In a pythonic way)
I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.

I have pretty much everything sorted up to convert the lines into arrays.

I basically do (pseudopython code)

```<code> line=file.readlines()
 line=line.split(' ') # Or whatever separator
 array=np.array(line)
 #And then iterate over every value casting them as floats
      newarray[i]=array.float(array[i])
</code>```

This works, buts seems a bit counterintuitive and antipythonic, I wanted to know if there is a better way to handle the inputs from a file to have at the end an array full of floats.

答:
How about the following:</p>

```<code>import numpy as np

arrays = []
for line in open('data.txt'):
  arrays.append(np.array([float(val) for val in line.rstrip('\n').split(' ') if val != '']))
</code>```

Body:
I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.

I have pretty much everything sorted up to convert the lines into arrays.

I basically do (pseudopython code)

 line=file.readlines()
 line=line.split(' ') # Or whatever separator
 array=np.array(line)
 #And then iterate over every value casting them as floats
      newarray[i]=array.float(array[i])

This works, buts seems a bit counterintuitive and antipythonic, I wanted to know if there is a better way to handle the inputs from a file to have at the end an array full of floats.

Body:
How about the following:

import numpy as np

arrays = []
for line in open('data.txt'):
  arrays.append(np.array([float(val) for val in line.rstrip('\n').split(' ') if val != '']))


问:
Laravel Multiple Pagination in one page
I'm having some trouble with my pagination.
I'm having two tables with data from a database and I paginated it with laravel Paginator.

Now my problem is when you go to, for example, page 2 it adds ?page=2 but that makes the first table go to page 2 too.

Is there anyway to get something like this ?

page_table1={number}&page_table2={number}

so you don't apply the page change on other tables.

答:
This is late, but it works with laravel 7.x

```<code>$messages = Message::where('status', 0)
    ->paginate(10, ['*'], 'p')
    ->appends(Arr::except(Request::query(), 'p'));
</code>```

In your view, example(inbox.blade.php)

```<code>{{$messages->links()}}
</code>```

Title: Laravel Multiple Pagination in one page

Body:
This is late, but it works with laravel 7.x

$messages = Message::where('status', 0)
    ->paginate(10, ['*'], 'p')
    ->appends(Arr::except(Request::query(), 'p'));

In your view, example(inbox.blade.php)

{{$messages->links()}}


问:
Cypress - Find an element that contains another element with a certain attribute
Title says it all, I can't figure out how can I do something like

Get .card that has button with attribute id=random (the code should return the card and retry the whole process until found, ex: if it finds a card but not a button with that id it should look redo the .carda search)

How I tought it would work but actually doesnt because doesnt retry the .get and if the .find succedes it returns the button

cy.get(".card").find("button[id=random]")

答:
I prefer this approach:

cy.get(".card:has('button[id=random]')")


问:
How do I link to a Blogger post with a post ID?
If I have the ID of a post on a Blogger blog, how do I translate that ID into a URL which links to the post?

My ultimate goal is to pull posts from my Blogger site to my own site, and then be able to permalink to the actual posts. I'm doing this by parsing the RSS feed for my blog with Javascript. Unfortunately the "link" field in the RSS feed isn't a URL to the blog post... it's a URL to a feed of the comments. I can, however, grab the post ID, which I assumed would be a good way to find the post URL. Any other suggestions appreciated.

Edit: Upon further inspection, I found that the actual post link IS included in the RSS feed. The library I'm using to parse the RSS feed was giving me the wrong link. However, the main question still stands.

Edit: Still can't get a direct link. Here's an example of the links I get for a single entry:

```<code><link rel="replies" type="application/atom+xml" href="http://chadsharpe.blogspot.com/feeds/2276618748913180797/comments/default" title="Post Comments">
<link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=4528045192864780582&postID=2276618748913180797" title="2 Comments">
<link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4528045192864780582/posts/default/2276618748913180797?v=2">
<link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4528045192864780582/posts/default/2276618748913180797?v=2">
<link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Funwhenwet/~3/PuX-Fqz_xKE/sharpe-watson-bomb-chris-o-jimmy.html" title="Sharpe, Watson, Bomb, Chris O, Jimmy">
</code>```

The URL I want is:

```<code>http://chadsharpe.blogspot.com/2010/08/sharpe-watson-bomb-chris-o-jimmy.html
</code>```

答:
Reading the spec for post object in blogger rest api v3:
https://developers.google.com/resources/api-libraries/documentation/blogger/v3/python/latest/blogger_v3.posts.html

If you are using Python rest API v3 import googleapiclient and google_auth_oauthlib
and use get(blogId=*, postId=*) to get the post object the attribute you are looking for is "url" for a published post. But if the post is a draft "url" will hold the base url for the blog.

ContentLicense: CC BY-SA 2.5

Body:
If I have the ID of a post on a Blogger blog, how do I translate that ID into a URL which links to the post?

My ultimate goal is to pull posts from my Blogger site to my own site, and then be able to permalink to the actual posts. I'm doing this by parsing the RSS feed for my blog with Javascript. Unfortunately the "link" field in the RSS feed isn't a URL to the blog post... it's a URL to a feed of the comments. I can, however, grab the post ID, which I assumed would be a good way to find the post URL. Any other suggestions appreciated.

Edit: Upon further inspection, I found that the actual post link IS included in the RSS feed. The library I'm using to parse the RSS feed was giving me the wrong link. However, the main question still stands.

Edit: Still can't get a direct link. Here's an example of the links I get for a single entry:

<link rel="replies" type="application/atom+xml" href="http://chadsharpe.blogspot.com/feeds/2276618748913180797/comments/default" title="Post Comments">
<link rel="replies" type="text/html" href="https://www.blogger.com/comment.g?blogID=4528045192864780582&postID=2276618748913180797" title="2 Comments">
<link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4528045192864780582/posts/default/2276618748913180797?v=2">
<link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4528045192864780582/posts/default/2276618748913180797?v=2">
<link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/Funwhenwet/~3/PuX-Fqz_xKE/sharpe-watson-bomb-chris-o-jimmy.html" title="Sharpe, Watson, Bomb, Chris O, Jimmy">

The URL I want is:

http://chadsharpe.blogspot.com/2010/08/sharpe-watson-bomb-chris-o-jimmy.html


问:
Assertion failed: url != null is not true

════════ Exception caught by widgets library ═══════════════════════════════════
  The following assertion was thrown building HomePage(dirty, state: _HomePageState#493d9):
  Assertion failed:
  F:\…\painting_network_image_web.dart:23
  url != null
  is not true

This is the error I get when I add this codes in home.dart

```<code>WallpaperModel wallpaperModel = WallpaperModel();
wallpaperModel = WallpaperModel.fromMap(element);
wallpapers.add(wallpaperModel);
</code>```

also /widget/widget.dart

```<code>Widget wallpapersList({List<WallpaperModel> wallpapers, context}) { return Container( padding: EdgeInsets.symmetric(horizontal: 15.0), child: GridView.count( shrinkWrap: true, physics: ClampingScrollPhysics(), crossAxisCount: 2, childAspectRatio: 1.0, mainAxisSpacing: 5.0, crossAxisSpacing: 5.0, children: wallpapers.map((wallpaper) { return GridTile( child: Container( child: Image.network(wallpaper.src.portrait), ), ); }).toList(), ), ); }
</code>```

this is the error I get when I execute my code I tried to use flutter clean also then run flutter run -v

答:
After saw your code, please change

```<code>return SrcModel(
  orignal: jsonData["orignal"],
  small: jsonData["small"],
  portrait: jsonData["protrait"],
);
</code>```

to

```<code>return SrcModel(
  orignal: jsonData["original"],
  small: jsonData["small"],
  portrait: jsonData["portrait"],
);
</code>```

now I see your pics and I like your design

Body:
════════ Exception caught by widgets library ═══════════════════════════════════
  The following assertion was thrown building HomePage(dirty, state: _HomePageState#493d9):
  Assertion failed:
  F:\…\painting_network_image_web.dart:23
  url != null
  is not true

This is the error I get when I add this codes in home.dart

WallpaperModel wallpaperModel = WallpaperModel();
wallpaperModel = WallpaperModel.fromMap(element);
wallpapers.add(wallpaperModel);

also /widget/widget.dart

Widget wallpapersList({List<WallpaperModel> wallpapers, context}) { return Container( padding: EdgeInsets.symmetric(horizontal: 15.0), child: GridView.count( shrinkWrap: true, physics: ClampingScrollPhysics(), crossAxisCount: 2, childAspectRatio: 1.0, mainAxisSpacing: 5.0, crossAxisSpacing: 5.0, children: wallpapers.map((wallpaper) { return GridTile( child: Container( child: Image.network(wallpaper.src.portrait), ), ); }).toList(), ), ); }

this is the error I get when I execute my code I tried to use flutter clean also then run flutter run -v

Body:
After saw your code, please change

return SrcModel(
  orignal: jsonData["orignal"],
  small: jsonData["small"],
  portrait: jsonData["protrait"],
);

to

return SrcModel(
  orignal: jsonData["original"],
  small: jsonData["small"],
  portrait: jsonData["portrait"],
);

now I see your pics and I like your design


问:
Making Boolean mask on date column in Pandas
Letsay I have a DataFrame with badly formatted dates:

```<code>df = pd.DataFrame(['01-01-1980','2001-03-01','05/22/2020'],columns=['DATE'])
</code>```

I want to compare them to some date '06/07/2003'. Doing Boolean mask on Timestamp-converted values is obvious way to go:

```<code>mask=pd.Timestamp(df['DATE']) < pd.Timestamp('06/07/2003')
</code>```

but that does not fly because Timestamp does not understand Series object. You can go pedestrian way but that is ugly:

```<code>mask=pd.Series([pd.Timestamp(df.loc[x,'DATE']) for x in df['DATE'].index]) < pd.Timestamp('06/07/2003')
</code>```

How to do it concisely?

答:
Actually I found one answer while posting - there is 'apply' function on Pandas Series class:</p>

```<code>mask=df['DATE'].apply(pd.Timestamp) < pd.Timestamp('06/07/2003')
</code>```

Body:
Letsay I have a DataFrame with badly formatted dates:

df = pd.DataFrame(['01-01-1980','2001-03-01','05/22/2020'],columns=['DATE'])

I want to compare them to some date '06/07/2003'. Doing Boolean mask on Timestamp-converted values is obvious way to go:

mask=pd.Timestamp(df['DATE']) < pd.Timestamp('06/07/2003')

but that does not fly because Timestamp does not understand Series object. You can go pedestrian way but that is ugly:

mask=pd.Series([pd.Timestamp(df.loc[x,'DATE']) for x in df['DATE'].index]) < pd.Timestamp('06/07/2003')

How to do it concisely?

Body:
Actually I found one answer while posting - there is 'apply' function on Pandas Series class:

mask=df['DATE'].apply(pd.Timestamp) < pd.Timestamp('06/07/2003')


问:
Filling in values in python dictionary
I have the following example code </p>

```<code>test_dict = dict.fromkeys(['x','y','z'], np.zeros(5))

for j in range(5):
    test_dict['x'][j]= j*10

print(test_dict)
</code>```

<p>I expect that this should fill in the value in 'x' as {0., 10., 20., 30., 40.} and it does. But it also fills in the same values for 'y' and 'z' which I don't want. Why is this happening and how can I prevent it? </p>

答:
Your dictionary keys all point to the same value.  Try initializing it with a comprehension instead:</p>

```<code>test_dict = {key: np.zeros(5) for key in ['x', 'y', 'z']}
</code>```

Title: Filling in values in python dictionary

Body:
I have the following example code

test_dict = dict.fromkeys(['x','y','z'], np.zeros(5))

for j in range(5):
    test_dict['x'][j]= j*10

print(test_dict)

I expect that this should fill in the value in 'x' as {0., 10., 20., 30., 40.} and it does. But it also fills in the same values for 'y' and 'z' which I don't want. Why is this happening and how can I prevent it?

Body:
Your dictionary keys all point to the same value.  Try initializing it with a comprehension instead:

test_dict = {key: np.zeros(5) for key in ['x', 'y', 'z']}


问:
Android Material Toolbar surface color looks different on two different toolbars
I'm trying to change the background color of the material toolbar to the surface color with:

```<code>android:background="?attr/colorSurface"
</code>```

which works as expected (to simplify it I set the background color directly at the view and did not create a custom style for that). In order to define multiple colors for light and dark mode I created two colors.xml files. When in light mode the applied surface color looks as expected:

But when I'm changing to dark mode the two toolbars look like this (still both referencing the same color resource):

The right toolbar has the correct background color, the left one not.

Then I checked if the same thing happens with every color I define in dark mode so I changed the surface color to my primary color. In dark mode it looks like this:

So in this case the colors look the same, but when I'm using my surface color, it does not.

I also tried to change the Widget.MaterialComponents.Toolbar.Surface toolbar to Widget.MaterialComponents.Toolbar, but still the same result.

答:
So in this case the colors look the same, but when I'm using my surface color, it does not.

It happens because of Elevation Overlays.

You can avoid the elevation overlays setting elevationOverlayEnabled to false in your app theme.

Just a final note. In your MaterialToolbar you should use:

```<code>    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.PrimarySurface"
        ..>
</code>```

This style will automatically switch between the component's primary colored style in light theme and surface colored style in dark theme.

Body:
I'm trying to change the background color of the material toolbar to the surface color with:

android:background="?attr/colorSurface"

which works as expected (to simplify it I set the background color directly at the view and did not create a custom style for that). In order to define multiple colors for light and dark mode I created two colors.xml files. When in light mode the applied surface color looks as expected:

But when I'm changing to dark mode the two toolbars look like this (still both referencing the same color resource):

The right toolbar has the correct background color, the left one not.

Then I checked if the same thing happens with every color I define in dark mode so I changed the surface color to my primary color. In dark mode it looks like this:

So in this case the colors look the same, but when I'm using my surface color, it does not.

I also tried to change the Widget.MaterialComponents.Toolbar.Surface toolbar to Widget.MaterialComponents.Toolbar, but still the same result.

Body:
So in this case the colors look the same, but when I'm using my surface color, it does not.

It happens because of Elevation Overlays.

You can avoid the elevation overlays setting elevationOverlayEnabled to false in your app theme.

Just a final note. In your MaterialToolbar you should use:

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.PrimarySurface"
        ..>

This style will automatically switch between the component's primary colored style in light theme and surface colored style in dark theme.


问:
The solution is executed with error 'out of bounds' on the line 25
Receiving an out of bounds error during compilation, tried alternate approaches still the same. it says error occurred on line 25 which is just a cin statement within bounds. where exactly am I going wrong. Clang, Debugger is generating this error.</p>

```<code>int main ()
{

  int n;

  cin >> n;

  int work[n];

  for (int j = 1; j <= n; j++)
    {
      cin >> work[j];
    }

    int i = -2, j = -1, k = 0, l = 0;

    int ch = 0, bi = 0, ba = 0;

    while (l < n)
    {
      ch = ch + work[i+3];
      l++;

      bi  = bi + work[j+3];
      l++;

      ba = ba + work[k+3];
      l++;

      i+=3;
      j+=3;
      k+=3;
    }

    if (ch > bi && ch > ba)
    cout << "chest" << endl;

    else if (bi > ch && bi > ba)
    cout << "biceps" << endl;

    else
    cout << "back" << endl;

  return 0;
}
</code>```

答:
UPDATE: Had to add nested if and else to make it work, now it works within bounds</p>

```<code> while (l < n)
{
  ch = ch + work[i+3];
  l++;

  if(l<n)
  {
    bi  = bi + work[j+3];
    l++;
  }

  else
  break;

  if(l<n)
  {
    ba = ba + work[k+3];
    l++;
  }

  else
  break;

  i+=3;
  j+=3;
  k+=3;
}
</code>```

Body:
Receiving an out of bounds error during compilation, tried alternate approaches still the same. it says error occurred on line 25 which is just a cin statement within bounds. where exactly am I going wrong. Clang, Debugger is generating this error.

int main ()
{

  int n;

  cin >> n;

  int work[n];

  for (int j = 1; j <= n; j++)
    {
      cin >> work[j];
    }

    int i = -2, j = -1, k = 0, l = 0;

    int ch = 0, bi = 0, ba = 0;

    while (l < n)
    {
      ch = ch + work[i+3];
      l++;

      bi  = bi + work[j+3];
      l++;

      ba = ba + work[k+3];
      l++;

      i+=3;
      j+=3;
      k+=3;
    }

    if (ch > bi && ch > ba)
    cout << "chest" << endl;

    else if (bi > ch && bi > ba)
    cout << "biceps" << endl;

    else
    cout << "back" << endl;

  return 0;
}

Body:
UPDATE: Had to add nested if and else to make it work, now it works within bounds

 while (l < n)
{
  ch = ch + work[i+3];
  l++;

  if(l<n)
  {
    bi  = bi + work[j+3];
    l++;
  }

  else
  break;

  if(l<n)
  {
    ba = ba + work[k+3];
    l++;
  }

  else
  break;

  i+=3;
  j+=3;
  k+=3;
}


问:
Bar chart with bars from two different dataframes
I have the following dataframes:

```<code>      import pandas as pd
      import numpy as np
      import matplotlib.pyplot as plt

      df_One = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
                             'Qtd_Instrumentation': [18, 5, 25, 10]})

     df_Two = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
                   'Qtd_Instrumentation': [14, 1, 22, 10]})
</code>```

I would like to build a bar graph that contains the information from the two data frames, that is, the blue bars indicate the datadrame_One and the vertical red bars indicate the information of the dataframe_Two.

I tried to implement it as follows:

```<code>       fig, ax = plt.subplots()
       n_group = len(df_One['Category'])
       index = np.arange(n_group)
       bar_width = 0.35
       opacity = 0.8

       rects1 = df_One.plot.bar(x='Category', y='Qtd_Instrumentation', color='r', label = 'Station
                                One')
       rects2 = df_Two.plot.bar(x='Category', y='Qtd_Instrumentation', color='b', label = 'Station
                                Two')

       plt.xlabel('Category Instrumentation')
       plt.ylabel('Qtd Instrumentation')

       plt.show()
</code>```

However, this code is wrong, as it designs two bar graphs instead of building just one graph with the two representations.

Does anyone know how I can build this described chart? Tks

答:
I'd suggest merging the two dataframes first:

```<code>df_c = pd.merge(df_One, df_Two, on='Category')
df_c.plot.bar(x='Category')
</code>```

gives:

note that you might want to pass how='outer' to merge if you have missing categories.

Body:
I have the following dataframes:

      import pandas as pd
      import numpy as np
      import matplotlib.pyplot as plt

      df_One = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
                             'Qtd_Instrumentation': [18, 5, 25, 10]})

     df_Two = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
                   'Qtd_Instrumentation': [14, 1, 22, 10]})

I would like to build a bar graph that contains the information from the two data frames, that is, the blue bars indicate the datadrame_One and the vertical red bars indicate the information of the dataframe_Two.

I tried to implement it as follows:

       fig, ax = plt.subplots()
       n_group = len(df_One['Category'])
       index = np.arange(n_group)
       bar_width = 0.35
       opacity = 0.8

       rects1 = df_One.plot.bar(x='Category', y='Qtd_Instrumentation', color='r', label = 'Station
                                One')
       rects2 = df_Two.plot.bar(x='Category', y='Qtd_Instrumentation', color='b', label = 'Station
                                Two')

       plt.xlabel('Category Instrumentation')
       plt.ylabel('Qtd Instrumentation')

       plt.show()

However, this code is wrong, as it designs two bar graphs instead of building just one graph with the two representations.

Does anyone know how I can build this described chart? Tks

Body:
I'd suggest merging the two dataframes first:

df_c = pd.merge(df_One, df_Two, on='Category')
df_c.plot.bar(x='Category')

gives:

note that you might want to pass how='outer' to merge if you have missing categories.