问:
Rails scaffold_controller generator doesn't apply model attributes to views
I'm using the scaffold_controller generator on an existing model with existing attributes, but the view forms that get generated don't have any input controls for the corresponding model attributes - they're just empty forms. Why is that?

e.g:

```<code>rails generate scaffold_controller User --skip --no-test-framework
</code>```

Where the User already has name and email attributes should generate forms with name and email fields...

答:
In rails 5, you can get the list of columns with type using following code.

```<code>Model.columns.reject{|n| n.name == "id" or n.name == "created_at" or n.name == "updated_at" }.map{|i| "#{i.name}:#{i.type}"}.join(" ")
</code>```

Later you can paste the output post rails g scaffold_controller Model

Body:
I'm using the scaffold_controller generator on an existing model with existing attributes, but the view forms that get generated don't have any input controls for the corresponding model attributes - they're just empty forms. Why is that?

e.g:

rails generate scaffold_controller User --skip --no-test-framework

Where the User already has name and email attributes should generate forms with name and email fields...

Body:
In rails 5, you can get the list of columns with type using following code.

Model.columns.reject{|n| n.name == "id" or n.name == "created_at" or n.name == "updated_at" }.map{|i| "#{i.name}:#{i.type}"}.join(" ")

Later you can paste the output post rails g scaffold_controller Model


来源: stackexchange

问:
How to access global variable
From the following code, I wish for the output of names to contain an array of names taken from a column in a csv file. When the function is run, the array remains empty. Why?

```<code>def cp_identifier():
    global names
    names = []
    array_dec()
    print(names)

def array_dec():
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')
        for row in card_list_table:
            names.append(row["Card Name"])
</code>```

Current Output:

```<code>[]
</code>```

Expected output:

```<code>['Card Name', 'Card Name', ... , 'Card Name']
</code>```

答:
Because names is global to cp_identifier but not to array_dec. In the latter names is a local variable that is thrown away after the call.

However, avoid globals whenever possible. You can just return the names array from array_dec.

ContentLicense: CC BY-SA 4.0

Title: How to access global variable

Body:
From the following code, I wish for the output of names to contain an array of names taken from a column in a csv file. When the function is run, the array remains empty. Why?

def cp_identifier():
    global names
    names = []
    array_dec()
    print(names)

def array_dec():
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')
        for row in card_list_table:
            names.append(row["Card Name"])

Current Output:

[]

Expected output:

['Card Name', 'Card Name', ... , 'Card Name']


问:
How do I include the same partial multiple times with different content using Nunjucks?
I have a few page templates which need to include the same partial numerous times but with different content. I've had a look at looping this, however, they're not necessarily going to be in the concurrent  order.

For example my page template will look like this

```<code>{% extends "layout.html" %}

{% set page = inner %}

{% block content %}

    {% include "partials/image-text-block.html" %}

    {% include "partials/example-block.html" %}

    {% include "partials/image-text-block.html" %}

{% endblock %}
</code>```

With my include file looking like

```<code><div class="col-12 col-sm-6 col-sm-offset-1 image-text__copy">
    <h2 class="navy">{{ page.imageText.title }}</h2>

    <p class="light-body">{{ page.imageText.text }}</p>

    <div class="button-wrap">
        <a href="#" class="button">{{ page.imageText.buttonText }}</a>
    </div>
</div>
</code>```

I'm currently using a json file to inject the content.

```<code>    "inner": {
        "imageText": {
            "imageSide": "left",
            "text": "dsauhf oaiuoags f"
        }
    }
</code>```

What would be the best way to provide different content to each include please?

Thanks in advance!

答:
try using setting different variable values

Input:

```<code>{% set sectionHeader = { title: 'Title 1', subtitle: 'Subtitle 1' } %}
{% include "_partials/section-header.html" %}

{% set sectionHeader = { title: 'Title 2', subtitle: 'Subtitle 2' } %}
{% include "_partials/section-header.html" %}
</code>```

_partials/section-header.html

```<code><header class="section-header">
    <h3 class="section-title">{{sectionHeader.title}}</h3>
    <p class="section-subtitle">{{sectionHeader.subtitle}}</p>
</header>
</code>```

Output:

```<code><header class="section-header">
    <h3 class="section-title">Title 1</h3>
    <p class="section-subtitle">Subtitle 1</p>
</header>

<header class="section-header">
    <h3 class="section-title">Title 2</h3>
    <p class="section-subtitle">Subtitle 2</p>
</header>
</code>```

or you could use macros

article.njk

```<code>{% macro articleMacro(title) %}
  <article>
      <header>{{title}}</header>
      <p>article body</p>
      <footer></footer>
  </article>
{% endmacro %}
</code>```

page.njk

```<code>{% import "article.njk" as article %}

{{ article('header one') }}

{{ article('header two') }}
</code>```

Body:
I have a few page templates which need to include the same partial numerous times but with different content. I've had a look at looping this, however, they're not necessarily going to be in the concurrent  order.

For example my page template will look like this

{% extends "layout.html" %}

{% set page = inner %}

{% block content %}

    {% include "partials/image-text-block.html" %}

    {% include "partials/example-block.html" %}

    {% include "partials/image-text-block.html" %}

{% endblock %}

With my include file looking like

{{ page.imageText.title }}

{{ page.imageText.text }}

        {{ page.imageText.buttonText }}

I'm currently using a json file to inject the content.

    "inner": {
        "imageText": {
            "imageSide": "left",
            "text": "dsauhf oaiuoags f"
        }
    }

What would be the best way to provide different content to each include please?

Thanks in advance!

Body:
try using setting different variable values

Input:

{% set sectionHeader = { title: 'Title 1', subtitle: 'Subtitle 1' } %}
{% include "_partials/section-header.html" %}

{% set sectionHeader = { title: 'Title 2', subtitle: 'Subtitle 2' } %}
{% include "_partials/section-header.html" %}

_partials/section-header.html

<header class="section-header">
    <h3 class="section-title">{{sectionHeader.title}}</h3>
    <p class="section-subtitle">{{sectionHeader.subtitle}}</p>
</header>

Output:

<header class="section-header">
    <h3 class="section-title">Title 1</h3>
    <p class="section-subtitle">Subtitle 1</p>
</header>

<header class="section-header">
    <h3 class="section-title">Title 2</h3>
    <p class="section-subtitle">Subtitle 2</p>
</header>

or you could use macros

article.njk

{% macro articleMacro(title) %}
  <article>
      <header>{{title}}</header>
      <p>article body</p>
      <footer></footer>
  </article>
{% endmacro %}

page.njk

{% import "article.njk" as article %}

{{ article('header one') }}

{{ article('header two') }}


问:
How to get the value of a column in the row with the first occurrence of another value in a particular column in MySQL?
I have a SQL table with the following columns:

```<code>|    Date    |    Pass/Fail    |
--------------------------------
| yyyy-mm-dd |      PASS       |

| yyyy-mm-dd |      FAIL       |
</code>```

How do I obtain the value in the "Date" column of the row with the first occurrence (ordered by date) of "PASS" in the "Pass/Fail" column?

答:
You can use order by with limit 1

```<code>select * from tablename
where PassFailCol='Pass'
order by date
limit 1
</code>```

Body:
I have a SQL table with the following columns:

|    Date    |    Pass/Fail    |
--------------------------------
| yyyy-mm-dd |      PASS       |

| yyyy-mm-dd |      FAIL       |

How do I obtain the value in the "Date" column of the row with the first occurrence (ordered by date) of "PASS" in the "Pass/Fail" column?

Body:
You can use order by with limit 1

select * from tablename
where PassFailCol='Pass'
order by date
limit 1


问:
Creating a trigger from SQL view
I have two tables that are updated by one function (GLPOST and GLPOSTO).

I have created a view (GLREP) based on these two tables that transposes the rows of GLPOSTO into columns as this is how I want my data.

Now I want to create a trigger (OPTIONAL) on this view to insert to a new table (GLREPORTEXCEL) once the view collects the data from the various tables in the view format.

View GLREP:

```<code>CREATE VIEW [dbo].[GLREP]
AS
    (SELECT *
     FROM
         (SELECT
              GLPOST.ACCTID,
              JRNLDATE,
              GLPOST.FISCALYR,
              GLPOST.FISCALPERD,
              GLPOST.SRCECURN,
              GLPOST.BATCHNBR,
              GLPOST.ENTRYNBR,
              GLPOST.JNLDTLDESC,
              GLPOST.JNLDTLREF,
              GLPOST.TRANSAMT,
              GLPOST.CONVRATE,
              GLPOST.SCURNAMT,
              GLPOSTO.OPTFIELD,
              GLPOST.CNTDETAIL,
              CSOPTFD.VDESC
          FROM
              GLPOST
          LEFT JOIN
              GLPOSTO ON GLPOST.ACCTID = GLPOSTO.ACCTID
                      AND GLPOST.POSTINGSEQ = GLPOSTO.POSTINGSEQ
                      AND glpost.CNTDETAIL = glposto.CNTDETAIL
          LEFT JOIN
              CSOPTFD ON GLPOSTO.OPTFIELD = CSOPTFD.OPTFIELD
                      AND GLPOSTO.VALUE = CSOPTFD.VALUE) AS source
     PIVOT
          (MAX([VDESC])
              FOR [OPTFIELD] IN (ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION, STAFF)) AS PVT
           )
</code>```

My trigger that is not working:

```<code>CREATE TRIGGER OPTIONAL
ON GLREP
FOR INSERT
AS
    INSERT INTO GLREPORTEXCEL (ACCTID, TRANDATE, FISCALYR, FISCALPERD, SRCECURN, BATCHNBR,
                               ENTRYNBR, JNLDTLDESC, JNLDTLREF, TRANSAMT, CONVRATE, SCURNAMT,
                               CNTDETAIL, STAFF, ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION)
        SELECT
            ACCTID, JRNLDATE, FISCALYR, FISCALPERD, SRCECURN, BATCHNBR,
            ENTRYNBR, JNLDTLDESC, JNLDTLREF, TRANSAMT, CONVRATE, SCURNAMT,
            CNTDETAIL, STAFF, ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION
        FROM
            inserted
</code>```

New table that I want to insert into is called GLREPORTEXCEL.

答:
As I hinted and marc specifically wrote in the comments, SQL Server does not support for triggers on views - only instead of triggers.

This is documented on the CREATE TRIGGER (Transact-SQL) page, in the Arguments paragraph:

table | view

  The table or view on which the DML trigger runs. This table or view is sometimes referred to as the trigger table or trigger view. Specifying the fully qualified name of the table or view is optional. You can only reference a view by an INSTEAD OF trigger. You can't define DML triggers on local or global temporary tables.

(emphasis mine).

This means that you need to change the trigger from a for trigger to an instead of trigger:

```<code>CREATE TRIGGER OPTIONAL
ON GLREP
INSTEAD OF INSERT
AS
    INSERT INTO GLREPORTEXCEL (ACCTID, TRANDATE, FISCALYR, FISCALPERD, SRCECURN, BATCHNBR,
                               ENTRYNBR, JNLDTLDESC, JNLDTLREF, TRANSAMT, CONVRATE, SCURNAMT,
                               CNTDETAIL, STAFF, ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION)
        SELECT
            ACCTID, JRNLDATE, FISCALYR, FISCALPERD, SRCECURN, BATCHNBR,
            ENTRYNBR, JNLDTLDESC, JNLDTLREF, TRANSAMT, CONVRATE, SCURNAMT,
            CNTDETAIL, STAFF, ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION
        FROM
            inserted
</code>```

Title: Creating a trigger from SQL view

Body:
I have two tables that are updated by one function (GLPOST and GLPOSTO).

I have created a view (GLREP) based on these two tables that transposes the rows of GLPOSTO into columns as this is how I want my data.

Now I want to create a trigger (OPTIONAL) on this view to insert to a new table (GLREPORTEXCEL) once the view collects the data from the various tables in the view format.

View GLREP:

CREATE VIEW [dbo].[GLREP]
AS
    (SELECT *
     FROM
         (SELECT
              GLPOST.ACCTID,
              JRNLDATE,
              GLPOST.FISCALYR,
              GLPOST.FISCALPERD,
              GLPOST.SRCECURN,
              GLPOST.BATCHNBR,
              GLPOST.ENTRYNBR,
              GLPOST.JNLDTLDESC,
              GLPOST.JNLDTLREF,
              GLPOST.TRANSAMT,
              GLPOST.CONVRATE,
              GLPOST.SCURNAMT,
              GLPOSTO.OPTFIELD,
              GLPOST.CNTDETAIL,
              CSOPTFD.VDESC
          FROM
              GLPOST
          LEFT JOIN
              GLPOSTO ON GLPOST.ACCTID = GLPOSTO.ACCTID
                      AND GLPOST.POSTINGSEQ = GLPOSTO.POSTINGSEQ
                      AND glpost.CNTDETAIL = glposto.CNTDETAIL
          LEFT JOIN
              CSOPTFD ON GLPOSTO.OPTFIELD = CSOPTFD.OPTFIELD
                      AND GLPOSTO.VALUE = CSOPTFD.VALUE) AS source
     PIVOT
          (MAX([VDESC])
              FOR [OPTFIELD] IN (ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION, STAFF)) AS PVT
           )

My trigger that is not working:

CREATE TRIGGER OPTIONAL
ON GLREP
FOR INSERT
AS
    INSERT INTO GLREPORTEXCEL (ACCTID, TRANDATE, FISCALYR, FISCALPERD, SRCECURN, BATCHNBR,
                               ENTRYNBR, JNLDTLDESC, JNLDTLREF, TRANSAMT, CONVRATE, SCURNAMT,
                               CNTDETAIL, STAFF, ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION)
        SELECT
            ACCTID, JRNLDATE, FISCALYR, FISCALPERD, SRCECURN, BATCHNBR,
            ENTRYNBR, JNLDTLDESC, JNLDTLREF, TRANSAMT, CONVRATE, SCURNAMT,
            CNTDETAIL, STAFF, ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION
        FROM
            inserted

New table that I want to insert into is called GLREPORTEXCEL.

Body:
As I hinted and marc specifically wrote in the comments, SQL Server does not support for triggers on views - only instead of triggers.

This is documented on the CREATE TRIGGER (Transact-SQL) page, in the Arguments paragraph:

table | view

  The table or view on which the DML trigger runs. This table or view is sometimes referred to as the trigger table or trigger view. Specifying the fully qualified name of the table or view is optional. You can only reference a view by an INSTEAD OF trigger. You can't define DML triggers on local or global temporary tables.

(emphasis mine).

This means that you need to change the trigger from a for trigger to an instead of trigger:

CREATE TRIGGER OPTIONAL
ON GLREP
INSTEAD OF INSERT
AS
    INSERT INTO GLREPORTEXCEL (ACCTID, TRANDATE, FISCALYR, FISCALPERD, SRCECURN, BATCHNBR,
                               ENTRYNBR, JNLDTLDESC, JNLDTLREF, TRANSAMT, CONVRATE, SCURNAMT,
                               CNTDETAIL, STAFF, ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION)
        SELECT
            ACCTID, JRNLDATE, FISCALYR, FISCALPERD, SRCECURN, BATCHNBR,
            ENTRYNBR, JNLDTLDESC, JNLDTLREF, TRANSAMT, CONVRATE, SCURNAMT,
            CNTDETAIL, STAFF, ADVANCE, MEDICAL, MILEAGE, MOTORVEHICLE, PROMOTION
        FROM
            inserted


问:
Convert manualy created DOK to CSR
For a machine learning task I need a sparse matrix in CSR format.
As a first step I manualy build a DOK, looking like this (based on this guid):

```<code>dok = { (0,0): 1, (0,9): 1, (5,12): 1}
#the value is always 1
#the keys representing the position in the matrix
#my DOK has around 6 million entries like these
</code>```

I know want to format this into CSR. If I understand the docs correct, this is only possible if my input is also a sparse matrix. But my DOK is not recognised as a sparse matrix, just as a dictionary. I was also not able to cast my DOK to a "real" DOK (Following error occured):

```<code>TypeError: Expected rank <=2 dense array or matrix.
</code>```

So how can I convert my DOK to a CSR?

答:
```<code>In [472]: dok = { (0,0): 1, (0,9): 1, (5,12): 1}
</code>```

Make a blank dok matrix:

```<code>In [473]: M = sparse.dok_matrix((20,20), dtype=int)
In [474]: M
Out[474]:
<20x20 sparse matrix of type '<class 'numpy.int64'>'
    with 0 stored elements in Dictionary Of Keys format>
</code>```

M is a subclass of Python dictionary.  It used to be that we could use dictionary .update method to efficiently add new values from a Python dictionary, but that method has been disabled (try it to see the error message).  However a backdoor has been provided:

```<code>In [475]: M._update(dok)
In [476]: M
Out[476]:
<20x20 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in Dictionary Of Keys format>
</code>```

_update has a cautionary comment, that values are not checked, so use with caution.

Once you have dok format, you can convert it to csr format:

```<code>In [477]: M1=M.tocsr()
In [478]: M1
Out[478]:
<20x20 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in Compressed Sparse Row format>
In [479]: M1.A
Out[479]:
array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       ...
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
      dtype=int64)
</code>```

If you made an error in defining your dok, it probably will show up in the csr conversion.

Another option is to iterate through your dok and construct the corresponding coo style inputs (data, rows, cols).  Those were the original style, and well worth understanding and using.

Title: Convert manualy created DOK to CSR

Body:
For a machine learning task I need a sparse matrix in CSR format.
As a first step I manualy build a DOK, looking like this (based on this guid):

dok = { (0,0): 1, (0,9): 1, (5,12): 1}
#the value is always 1
#the keys representing the position in the matrix
#my DOK has around 6 million entries like these

I know want to format this into CSR. If I understand the docs correct, this is only possible if my input is also a sparse matrix. But my DOK is not recognised as a sparse matrix, just as a dictionary. I was also not able to cast my DOK to a "real" DOK (Following error occured):

TypeError: Expected rank <=2 dense array or matrix.

So how can I convert my DOK to a CSR?

Body:
In [472]: dok = { (0,0): 1, (0,9): 1, (5,12): 1}

Make a blank dok matrix:

In [473]: M = sparse.dok_matrix((20,20), dtype=int)
In [474]: M
Out[474]:
<20x20 sparse matrix of type '<class 'numpy.int64'>'
    with 0 stored elements in Dictionary Of Keys format>

M is a subclass of Python dictionary.  It used to be that we could use dictionary .update method to efficiently add new values from a Python dictionary, but that method has been disabled (try it to see the error message).  However a backdoor has been provided:

In [475]: M._update(dok)
In [476]: M
Out[476]:
<20x20 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in Dictionary Of Keys format>

_update has a cautionary comment, that values are not checked, so use with caution.

Once you have dok format, you can convert it to csr format:

In [477]: M1=M.tocsr()
In [478]: M1
Out[478]:
<20x20 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in Compressed Sparse Row format>
In [479]: M1.A
Out[479]:
array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       ...
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
      dtype=int64)

If you made an error in defining your dok, it probably will show up in the csr conversion.

Another option is to iterate through your dok and construct the corresponding coo style inputs (data, rows, cols).  Those were the original style, and well worth understanding and using.


问:
How convert epoch time integerfield to datetime field in django admin
I use django and for saving time I am using epoch time in an IntegerField so my model is like this:

```<code>class MyModel(models.Model):
    start_time = models.IntegerField()
</code>```

and start_time in admin is like this:

It's not a problem but it's hard to check and update field for a person so my question is how can I convert this IntegerField to DateTimeField in django admin without changing my model? I know I can represent this field as readonly field and convert epoch time to DateTime but how can i use django admin DateTime picker?

答:
I found my answer hope it help someone else, it's work but maybe it's not the best answer.

I used an intermediate field because I couldn't change the real field so I create a form to have a DateTimeField:

```<code>from django import forms
from django.contrib.admin.widgets import AdminSplitDateTime

class MyModelAdminForm(forms.ModelForm):
    start_date_time = forms.SplitDateTimeField(widget=AdminSplitDateTime())

    class Meta:
        model = MyModel
        fields = '__all__'
</code>```

then I add form to my admin:

```<code>@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    form = MyModelAdminForm
    fields = ('start_date_time',)
</code>```

for setting initial value of previous saved object in form:

```<code>def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)
    if obj:
        form.base_fields['start_date_time'].initial = datetime.datetime.fromtimestamp(obj.start_time)
    return form
</code>```

the result is:

and last step is saving DateTimeField to IntegerField as epoch time:

```<code>def save_model(self, request, obj, form, change):
    obj.start_time = round(form.cleaned_data['start_date_time'].timestamp())
    obj.save()
</code>```

Body:
I use django and for saving time I am using epoch time in an IntegerField so my model is like this:

class MyModel(models.Model):
    start_time = models.IntegerField()

and start_time in admin is like this:

It's not a problem but it's hard to check and update field for a person so my question is how can I convert this IntegerField to DateTimeField in django admin without changing my model? I know I can represent this field as readonly field and convert epoch time to DateTime but how can i use django admin DateTime picker?

Body:
I found my answer hope it help someone else, it's work but maybe it's not the best answer.

I used an intermediate field because I couldn't change the real field so I create a form to have a DateTimeField:

from django import forms
from django.contrib.admin.widgets import AdminSplitDateTime

class MyModelAdminForm(forms.ModelForm):
    start_date_time = forms.SplitDateTimeField(widget=AdminSplitDateTime())

    class Meta:
        model = MyModel
        fields = '__all__'

then I add form to my admin:

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    form = MyModelAdminForm
    fields = ('start_date_time',)

for setting initial value of previous saved object in form:

def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)
    if obj:
        form.base_fields['start_date_time'].initial = datetime.datetime.fromtimestamp(obj.start_time)
    return form

the result is:

and last step is saving DateTimeField to IntegerField as epoch time:

def save_model(self, request, obj, form, change):
    obj.start_time = round(form.cleaned_data['start_date_time'].timestamp())
    obj.save()


问:
How to implement virtual scroll for 4 images in a row using React js
I am currently displaying the image in

```<code> {images.map((image, index) =>    <img key={index} src={image} alt="info"></img>      )}
</code>```

and here 5 images per row have to be displayed. Say I have a list of files in an array:

```<code> MyArray = [1.png,2.png,3.png,4.png,5.png,................]
</code>```

So currently I am displaying it as

```<code>1,2,3,4,5
 6,7,8,9,10
</code>```

but I am unable to implement the virtual scroll in React after trying react virtualized.

I have 2 queries:

Do I have to choose list or grid based scrolling?

I have stored an array in MyArray, so how can I send the array to the below list?

```<code><List
  width={rowWidth}
  height={listHeight}
  rowHeight={rowHeight}
  rowRenderer={this.renderRow}
  rowCount={this.list.length}
  overscanRowCount={3}
/>
</code>```

 i am displaying svg's

updated implementions:

答:
You will need to use the Grid srolling.
Please see basic implementation for 4 images in a row below. You will need to adjust styling and other visual elements as per your needs.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Grid } from 'react-virtualized';

// Grid data as an array of arrays
const myArray = [
  [1.png,2.png,3.png,4.png],
  [5.png,6.png,7.png,8.png],
  // And so on...
];

function cellRenderer ({ columnIndex, key, rowIndex, style }) {
  return (
    <img
      key={key}
      style={style}
      src={myArray[rowIndex][columnIndex]}
      alt="info"
    />
  )
}

// Render your grid
ReactDOM.render(
  <Grid
    cellRenderer={cellRenderer}
    columnCount={4}
    columnWidth={100}
    height={300}
    rowCount={myArray.length}
    rowHeight={30}
    width={300}
  />,
  document.getElementById('example')
);
</code>```

Also, here is the code that I ran on my machine to test the implementation. I made it with create-react-app. Screenshot of running app included.

```<code>import React from 'react';
import { Grid } from 'react-virtualized';

// Grid data as an array of arrays
const myArray = [
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  // And so on...
];

function cellRenderer ({ columnIndex, key, rowIndex, style }) {
  return (
      <div
        key={key}
      >
      <img
        style={style}
        src={myArray[rowIndex][columnIndex]}
        alt="info"
      />
      </div>
  )
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>TESTING WITH CATS</h1>
          <Grid
            cellRenderer={cellRenderer}
            columnCount={4}
            columnWidth={100}
            height={200}
            rowCount={myArray.length}
            rowHeight={100}
            width={1200}
          />
      </header>
    </div>
  );
}

export default App;
</code>```

Implementation with SVGs.

Dexter, please make sure all your images are inside of the public folder (screenshot below).

You will need to manually add them to myArray. Alternatively - you can write a function that automatically imports them for you and pushes them into smaller arrays of 4.

```<code>import React from 'react';
import { Grid } from 'react-virtualized';

// Grid data as an array of arrays
const myArray = [
  ['/images/11.svg','/images/11.svg','/images/11.svg','/images/11.svg'],
  ['/images/11.svg','/images/11.svg','/images/11.svg','/images/11.svg'],
  ['/images/11.svg','/images/11.svg','/images/11.svg','/images/11.svg'],
  ['/images/11.svg','/images/11.svg','/images/11.svg','/images/11.svg'],
  // And so on...
];

function cellRenderer ({ columnIndex, key, rowIndex, style }) {
  return (
      <div
        key={key}
      >
          <img
            style={style}
            src={myArray[rowIndex][columnIndex]}
            alt="info"
          />
      </div>
  )
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>TESTING WITH SVGS</h1>
          <Grid
            cellRenderer={cellRenderer}
            columnCount={4}
            columnWidth={100}
            height={200}
            rowCount={myArray.length}
            rowHeight={100}
            width={1200}
          />
      </header>
    </div>
  );
}

export default App;

</code>```

Body:
I am currently displaying the image in

 {images.map((image, index) =>          )}

and here 5 images per row have to be displayed. Say I have a list of files in an array:

 MyArray = [1.png,2.png,3.png,4.png,5.png,................]

So currently I am displaying it as

1,2,3,4,5
 6,7,8,9,10

but I am unable to implement the virtual scroll in React after trying react virtualized.

I have 2 queries:

Do I have to choose list or grid based scrolling?

I have stored an array in MyArray, so how can I send the array to the below list?

<List
  width={rowWidth}
  height={listHeight}
  rowHeight={rowHeight}
  rowRenderer={this.renderRow}
  rowCount={this.list.length}
  overscanRowCount={3}
/>

 i am displaying svg's

updated implementions:

Body:
You will need to use the Grid srolling.
Please see basic implementation for 4 images in a row below. You will need to adjust styling and other visual elements as per your needs.

import React from 'react';
import ReactDOM from 'react-dom';
import { Grid } from 'react-virtualized';

// Grid data as an array of arrays
const myArray = [
  [1.png,2.png,3.png,4.png],
  [5.png,6.png,7.png,8.png],
  // And so on...
];

function cellRenderer ({ columnIndex, key, rowIndex, style }) {
  return (
    <img
      key={key}
      style={style}
      src={myArray[rowIndex][columnIndex]}
      alt="info"
    />
  )
}

// Render your grid
ReactDOM.render(
  <Grid
    cellRenderer={cellRenderer}
    columnCount={4}
    columnWidth={100}
    height={300}
    rowCount={myArray.length}
    rowHeight={30}
    width={300}
  />,
  document.getElementById('example')
);

Also, here is the code that I ran on my machine to test the implementation. I made it with create-react-app. Screenshot of running app included.

import React from 'react';
import { Grid } from 'react-virtualized';

// Grid data as an array of arrays
const myArray = [
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  ['https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg','https://i.imgur.com/NVHKPPq.jpg'],
  // And so on...
];

function cellRenderer ({ columnIndex, key, rowIndex, style }) {
  return (
      <div
        key={key}
      >
      <img
        style={style}
        src={myArray[rowIndex][columnIndex]}
        alt="info"
      />
      </div>
  )
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>TESTING WITH CATS</h1>
          <Grid
            cellRenderer={cellRenderer}
            columnCount={4}
            columnWidth={100}
            height={200}
            rowCount={myArray.length}
            rowHeight={100}
            width={1200}
          />
      </header>
    </div>
  );
}

export default App;

Implementation with SVGs.

Dexter, please make sure all your images are inside of the public folder (screenshot below).

You will need to manually add them to myArray. Alternatively - you can write a function that automatically imports them for you and pushes them into smaller arrays of 4.

import React from 'react';
import { Grid } from 'react-virtualized';

// Grid data as an array of arrays
const myArray = [
  ['/images/11.svg','/images/11.svg','/images/11.svg','/images/11.svg'],
  ['/images/11.svg','/images/11.svg','/images/11.svg','/images/11.svg'],
  ['/images/11.svg','/images/11.svg','/images/11.svg','/images/11.svg'],
  ['/images/11.svg','/images/11.svg','/images/11.svg','/images/11.svg'],
  // And so on...
];

function cellRenderer ({ columnIndex, key, rowIndex, style }) {
  return (
      <div
        key={key}
      >
          <img
            style={style}
            src={myArray[rowIndex][columnIndex]}
            alt="info"
          />
      </div>
  )
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>TESTING WITH SVGS</h1>
          <Grid
            cellRenderer={cellRenderer}
            columnCount={4}
            columnWidth={100}
            height={200}
            rowCount={myArray.length}
            rowHeight={100}
            width={1200}
          />
      </header>
    </div>
  );
}

export default App;


问:
Get website's contents from a list of URLs in a text-file
I have a list of URLs in a text file as below:

File URL.txt

```<code>https://url2.html
https://url3.html
...
https://urln.html
</code>```

I want to get content of those URLs into a text file line by line as shown below

Expected file Content.txt:

```<code>Content of web from url2.html
Content of web from url3.html
...
Content of web from urln.html
</code>```

Please help me to find a solution for my problem, can I use Python or Java code for this.

Thank you for consideration!

答:
Your question is a bit unclear but I will assume for now that you want to read a single line from a text file somewhere online with a given URL. If this is not what you wanted to know please let me know and I will do my best to further help you. Anyhow here is a simple way of doing this in pure Java using java.io.InputStreamReader and java.net.URL#openStream():

```<code>/**
     * Reads a text file from url and returns the first line as string.
     * @param url web location of the text file to read
     * @return {@code null} if an error occurred
     */
    static String downloadStringLine(URL url) {

        try {
            java.io.InputStreamReader stream = new java.io.InputStreamReader(url.openStream());
            java.io.BufferedReader reader = new java.io.BufferedReader(stream);
            return reader.readLine();
        }
        catch (java.io.IOException e) {
            System.out.printf("Unable to download string from %s", url.toString());
            return null;
        }
    }
</code>```

EDIT: Since you wanted a way to read all text content from an URL here is how to do that by iterating over lines from BufferedReader and storing them to a local text file using PrintWriter:

```<code>public class Main {

/**
 * Reads and writes text based content from the given url to a file
 * @param url web location of the content to store
 */
private static void storeURLContent(java.net.URL url, java.io.File file) {

    try {
        java.io.InputStreamReader stream = new java.io.InputStreamReader(url.openStream());
        java.io.BufferedReader reader = new java.io.BufferedReader(stream);

        java.io.PrintWriter writer = new java.io.PrintWriter(file);

        System.out.println("Reading contents of " + url.toString());
        java.util.Iterator<String> iter = reader.lines().iterator();
        while (iter.hasNext()) {
            writer.println(iter.next());
            writer.flush();
        }
        System.out.println("Done, contents have been saved to " + file.getPath());
        // Do not forget to close all streams
        stream.close(); reader.close(); writer.close();
    }
    catch (java.io.IOException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {

    try {
        java.net.URL url = new java.net.URL("https://www.w3.org/TR/PNG/iso_8859-1.txt");
        java.io.File file = new java.io.File("contents.txt");

        storeURLContent(url, file);
    }
    catch (java.net.MalformedURLException e) {
        e.printStackTrace();
    }
}
</code>```

}

Body:
I have a list of URLs in a text file as below:

File URL.txt

https://url2.html
https://url3.html
...
https://urln.html

I want to get content of those URLs into a text file line by line as shown below

Expected file Content.txt:

Content of web from url2.html
Content of web from url3.html
...
Content of web from urln.html

Please help me to find a solution for my problem, can I use Python or Java code for this.

Thank you for consideration!

Body:
Your question is a bit unclear but I will assume for now that you want to read a single line from a text file somewhere online with a given URL. If this is not what you wanted to know please let me know and I will do my best to further help you. Anyhow here is a simple way of doing this in pure Java using java.io.InputStreamReader and java.net.URL#openStream():

/**
     * Reads a text file from url and returns the first line as string.
     * @param url web location of the text file to read
     * @return {@code null} if an error occurred
     */
    static String downloadStringLine(URL url) {

        try {
            java.io.InputStreamReader stream = new java.io.InputStreamReader(url.openStream());
            java.io.BufferedReader reader = new java.io.BufferedReader(stream);
            return reader.readLine();
        }
        catch (java.io.IOException e) {
            System.out.printf("Unable to download string from %s", url.toString());
            return null;
        }
    }

EDIT: Since you wanted a way to read all text content from an URL here is how to do that by iterating over lines from BufferedReader and storing them to a local text file using PrintWriter:

public class Main {

/**
 * Reads and writes text based content from the given url to a file
 * @param url web location of the content to store
 */
private static void storeURLContent(java.net.URL url, java.io.File file) {

    try {
        java.io.InputStreamReader stream = new java.io.InputStreamReader(url.openStream());
        java.io.BufferedReader reader = new java.io.BufferedReader(stream);

        java.io.PrintWriter writer = new java.io.PrintWriter(file);

        System.out.println("Reading contents of " + url.toString());
        java.util.Iterator<String> iter = reader.lines().iterator();
        while (iter.hasNext()) {
            writer.println(iter.next());
            writer.flush();
        }
        System.out.println("Done, contents have been saved to " + file.getPath());
        // Do not forget to close all streams
        stream.close(); reader.close(); writer.close();
    }
    catch (java.io.IOException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {

    try {
        java.net.URL url = new java.net.URL("https://www.w3.org/TR/PNG/iso_8859-1.txt");
        java.io.File file = new java.io.File("contents.txt");

        storeURLContent(url, file);
    }
    catch (java.net.MalformedURLException e) {
        e.printStackTrace();
    }
}

}


问:
Graph API for iPhone
Can any one suggest how I could remove the cancel button next to login button in the Facebook graph API for iPhone. Where does the code lie?</p>

答:
The default answer is you can't, its a web page in a WebView by Facebook.

But since Facebook iOS SDK is open sourced. You can actually inject javascript into the WebView to remove the button using this function.

```<code>- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
</code>```

But this method is probably against the policy of Facebook so do it at your own risk.

ContentLicense: CC BY-SA 3.0

Title: Graph API for iPhone

Body:
The default answer is you can't, its a web page in a WebView by Facebook.

But since Facebook iOS SDK is open sourced. You can actually inject javascript into the WebView to remove the button using this function.

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script

But this method is probably against the policy of Facebook so do it at your own risk.


问:
Having trouble to setting position of iframe scrollbar?
I've been attempting to set the position of an iframe scrollbar. The scrollbar appears to move to the correct position but is then reset back to the default position.
The final goal is to be able to put content in the text area and have the content in the iframe match the position in text area as it is being updated via oninput.

function scrollMe() {
document.getElementById('iframeScroll').srcdoc = document.getElementById('wordMe').value;
document.getElementById('iframeScroll').contentWindow.document.documentElement.scrollTop = 1000;
document.getElementById('iframeScroll').contentWindow.document.documentElement.scrollLeft = 1000;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea oninput="scrollMe()" id="wordMe"></textarea>
<iframe id="iframeScroll" srcdoc=""></iframe></code>```

Uncaught TypeError:
Cannot set property 'scrollTop' of null at scrollMe at HTMLTextAreaElement.oninput

答:
function scrollMe() {
document.getElementById('iframeScroll').srcdoc = document.getElementById('wordMe').value;
document.getElementById('iframeScroll').scrollTop = 1000;
document.getElementById('iframeScroll').scrollLeft = 1000;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea oninput="scrollMe()" id="wordMe"></textarea>
<iframe id="iframeScroll" srcdoc=""></iframe></code>```

Body:
I've been attempting to set the position of an iframe scrollbar. The scrollbar appears to move to the correct position but is then reset back to the default position.
The final goal is to be able to put content in the text area and have the content in the iframe match the position in text area as it is being updated via oninput.

function scrollMe() {
document.getElementById('iframeScroll').srcdoc = document.getElementById('wordMe').value;
document.getElementById('iframeScroll').contentWindow.document.documentElement.scrollTop = 1000;
document.getElementById('iframeScroll').contentWindow.document.documentElement.scrollLeft = 1000;

}

<textarea oninput="scrollMe()" id="wordMe"></textarea>

Uncaught TypeError:
Cannot set property 'scrollTop' of null at scrollMe at HTMLTextAreaElement.oninput

Body:
function scrollMe() {
document.getElementById('iframeScroll').srcdoc = document.getElementById('wordMe').value;
document.getElementById('iframeScroll').scrollTop = 1000;
document.getElementById('iframeScroll').scrollLeft = 1000;

}

<textarea oninput="scrollMe()" id="wordMe"></textarea>
<iframe id="iframeScroll" srcdoc=""></iframe>


问:
Razor pages and webapi in the same project
I created a web app (razor pages) in .net core 3.0. Then I added an api controller to it (both from templates, just few clicks). When I run app, razor page works, but api call returns 404. Where is the problem and how can I make it work?</p>

答:
You need to configure your startup to support web api and attribute routing.

services.AddControllers() adds support for controllers and API-related features, but not views or pages. Refer to MVC service registration.

Add endpoints.MapControllers if the app uses attribute routing. Refer to Migrate MVC controllers.

Combine razor pages and api like:

```<code>public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
        });

        services.AddRazorPages()
            .AddNewtonsoftJson();
        services.AddControllers()
            .AddNewtonsoftJson();
    }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
     //other middlewares
      app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
        });
    }
</code>```

Body:
You need to configure your startup to support web api and attribute routing.

services.AddControllers() adds support for controllers and API-related features, but not views or pages. Refer to MVC service registration.

Add endpoints.MapControllers if the app uses attribute routing. Refer to Migrate MVC controllers.

Combine razor pages and api like:

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
        });

        services.AddRazorPages()
            .AddNewtonsoftJson();
        services.AddControllers()
            .AddNewtonsoftJson();
    }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
     //other middlewares
      app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
        });
    }


问:
Unable to run protractor using jenkins
I am able to run the protractor using command prompt.

However, when I try to run protractor using jenkins, it started the selenium server but does not execute the browser and will fail due to timeout.

Is there any configuration that I need to do at jenkins side aside from the project path?

I also have tried to install the package manually to makesure its updated.

Below is the error when I try to build/run protractor using jenkins:

```<code>> webhis_jasmine@ protractor C:\Users\user1\.jenkins\HISWEBJASMINE
> protractor conf.js

[12:06:44] I/launcher - Running 1 instances of WebDriver
[12:06:44] I/local - Starting selenium standalone server...
[12:06:46] I/local - Selenium standalone server started at http://10.190.40.39:56419/wd/hub
Started
[31mF[0mA Jasmine spec timed out. Resetting the WebDriver Control Flow.
A Jasmine spec timed out. Resetting the WebDriver Control Flow.
[31mF[0mA Jasmine spec timed out. Resetting the WebDriver Control Flow.
[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m
</code>```

i tried to run webdriver-manager update only using jenkins just to check and it is giving below error:

```<code>C:\Users\user1\.jenkins\HISWEBJASMINE>webdriver-manager update
'webdriver-manager' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\user1\.jenkins\HISWEBJASMINE>exit 9009
</code>```

Here is config file:

```<code>// conf.js
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
exports.config = {

  capabilities: {
      'browserName': 'chrome'
  },
  specs: ['Patient_positive.js','Visit_positive.js'],
  suites:{
        Smoke: ['ChainLocators.js', 'Dropdown.js'],
            Regression: 'ElementBasics.js',
            Testbed: 'testbed.js',
            PatientPositive: 'Patient_positive.js',
            PatientNegative: 'Patient_negative.js',
            VisitPositive: 'Visit_positive.js',
            VisitNegative: 'Visit_negative.js',
            EpisodeCPOEPositive: 'EpisodeCPOE_positive.js'
    },
  onPrepare:function(){
      browser.driver.manage().window().maximize();
      jasmine.getEnv().addReporter(
                new Jasmine2HtmlReporter({
                  savePath: './test/reports/',
                  screenshotsFolder: 'images',
                  takeScreenshots: true,
                  fixedScreenshotName: true,
                  takeScreenshotsOnlyOnFailures: false,
                  cleanDestination: false,
                  showPassed: true,
                  fileName: 'Test_Report',
                  fileNameSuffix: '',
                  fileNameDateSuffix: true
                })
              );
             },

        jasmineNodeOpts:{
            showColors: true
        }
};
</code>```

Is it related?

Update: I strip the spec to have to only 1 'it' and run. Manage to get a success result and report is generated, but i see the browser not launched as when running using cmd prompt.

```<code>C:\Users\hafizan.abdmulok\.jenkins\HISWEBJASMINE>npm run protractor

> webhis_jasmine@ protractor C:\Users\hafizan.abdmulok\.jenkins\HISWEBJASMINE
> protractor conf.js

[15:14:40] I/launcher - Running 1 instances of WebDriver
[15:14:40] I/local - Starting selenium standalone server...
[15:14:43] I/local - Selenium standalone server started at http://10.190.40.39:52793/wd/hub
Started
Successfully open patient page
Successfully enter name
Successfully select title
Successfully select gender
Successfully enter date of birth
Successfully select ID type
Successfully enter idno= 850921141112
Successfully select Nationality= Malaysia
Successfully enter mobile no
Successfully enter patient address line 1
Successfully enter patient address line 2
Successfully enter patient address line 3
Successfully enter patient postcode= 57000
Successfully enter patient city= Bukit Jalil
Successfully select patient State= Kuala Lumpur
Successfully select patient State= Malaysia
[32m.[0m

1 spec, 0 failures
Finished in 63.169 seconds

CGM
[15:15:52] I/local - Shutting down selenium standalone server.
[15:15:52] I/launcher - 0 instance(s) of WebDriver still running
[15:15:52] I/launcher - chrome #01 passed
Finished: SUCCESS
</code>```

答:
Try using directConnect:true in your config file instead of seleniumAddress: 'http://localhost:4444/wd/hub',

before runing the test do the below activities

```<code>webdriver-manager clean

node node_modules/protractor/bin/webdriver-manager update --standalone --versions.standalone=3.8.0
</code>```

Hope it helps you

Title: Unable to run protractor using jenkins

Body:
I am able to run the protractor using command prompt.

However, when I try to run protractor using jenkins, it started the selenium server but does not execute the browser and will fail due to timeout.

Is there any configuration that I need to do at jenkins side aside from the project path?

I also have tried to install the package manually to makesure its updated.

Below is the error when I try to build/run protractor using jenkins:

> webhis_jasmine@ protractor C:\Users\user1\.jenkins\HISWEBJASMINE
> protractor conf.js

[12:06:44] I/launcher - Running 1 instances of WebDriver
[12:06:44] I/local - Starting selenium standalone server...
[12:06:46] I/local - Selenium standalone server started at http://10.190.40.39:56419/wd/hub
Started
[31mF[0mA Jasmine spec timed out. Resetting the WebDriver Control Flow.
A Jasmine spec timed out. Resetting the WebDriver Control Flow.
[31mF[0mA Jasmine spec timed out. Resetting the WebDriver Control Flow.
[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m[31mF[0m

i tried to run webdriver-manager update only using jenkins just to check and it is giving below error:

C:\Users\user1\.jenkins\HISWEBJASMINE>webdriver-manager update
'webdriver-manager' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\user1\.jenkins\HISWEBJASMINE>exit 9009

Here is config file:

// conf.js
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
exports.config = {

  capabilities: {
      'browserName': 'chrome'
  },
  specs: ['Patient_positive.js','Visit_positive.js'],
  suites:{
        Smoke: ['ChainLocators.js', 'Dropdown.js'],
            Regression: 'ElementBasics.js',
            Testbed: 'testbed.js',
            PatientPositive: 'Patient_positive.js',
            PatientNegative: 'Patient_negative.js',
            VisitPositive: 'Visit_positive.js',
            VisitNegative: 'Visit_negative.js',
            EpisodeCPOEPositive: 'EpisodeCPOE_positive.js'
    },
  onPrepare:function(){
      browser.driver.manage().window().maximize();
      jasmine.getEnv().addReporter(
                new Jasmine2HtmlReporter({
                  savePath: './test/reports/',
                  screenshotsFolder: 'images',
                  takeScreenshots: true,
                  fixedScreenshotName: true,
                  takeScreenshotsOnlyOnFailures: false,
                  cleanDestination: false,
                  showPassed: true,
                  fileName: 'Test_Report',
                  fileNameSuffix: '',
                  fileNameDateSuffix: true
                })
              );
             },

        jasmineNodeOpts:{
            showColors: true
        }
};

Is it related?

Update: I strip the spec to have to only 1 'it' and run. Manage to get a success result and report is generated, but i see the browser not launched as when running using cmd prompt.

C:\Users\hafizan.abdmulok\.jenkins\HISWEBJASMINE>npm run protractor

> webhis_jasmine@ protractor C:\Users\hafizan.abdmulok\.jenkins\HISWEBJASMINE
> protractor conf.js

[15:14:40] I/launcher - Running 1 instances of WebDriver
[15:14:40] I/local - Starting selenium standalone server...
[15:14:43] I/local - Selenium standalone server started at http://10.190.40.39:52793/wd/hub
Started
Successfully open patient page
Successfully enter name
Successfully select title
Successfully select gender
Successfully enter date of birth
Successfully select ID type
Successfully enter idno= 850921141112
Successfully select Nationality= Malaysia
Successfully enter mobile no
Successfully enter patient address line 1
Successfully enter patient address line 2
Successfully enter patient address line 3
Successfully enter patient postcode= 57000
Successfully enter patient city= Bukit Jalil
Successfully select patient State= Kuala Lumpur
Successfully select patient State= Malaysia
[32m.[0m

1 spec, 0 failures
Finished in 63.169 seconds

CGM
[15:15:52] I/local - Shutting down selenium standalone server.
[15:15:52] I/launcher - 0 instance(s) of WebDriver still running
[15:15:52] I/launcher - chrome #01 passed
Finished: SUCCESS

Body:
Try using directConnect:true in your config file instead of seleniumAddress: 'http://localhost:4444/wd/hub',

before runing the test do the below activities

webdriver-manager clean

node node_modules/protractor/bin/webdriver-manager update --standalone --versions.standalone=3.8.0

Hope it helps you


问:
Room returns long but not inserting data in to table - one to many relationship
i have two entity class

```<code>@Entity(tableName = "TrackingItemTable")
data class TrackingItem(
                        @ColumnInfo val ProductName:String,
                        @ColumnInfo val ProductPrice:Float,
                        @ColumnInfo val ProductImage:String,
                        @ColumnInfo val ProductCurrencySymbol:String,
                        @ColumnInfo val ProductAddedDate: Date,
                        @ColumnInfo val ProductSiteName:String,
                        @PrimaryKey @ColumnInfo val ProductUrl:String,
                        @ColumnInfo val ProductAffiliateUrl:String,
                        @ColumnInfo var ProductNotificationPrice:Float? = null,
                        @ColumnInfo var ProductLastUpdatedPrice:Float
)
</code>```

and it has an foregin key relationship with the other entity

```<code>@Entity(foreignKeys = arrayOf(ForeignKey(entity = TrackingItem::class,
    parentColumns = arrayOf("ProductUrl"),
    childColumns = arrayOf("ProductAnalyticsUrl"),
    onDelete = ForeignKey.CASCADE)), tableName = "TrackingItemDataTable")

data class TrackingItemData(@ColumnInfo val ProductAnalyticsUrl:String,
                            @ColumnInfo val Price:Float,
                            @ColumnInfo val Date: Long,
                            @PrimaryKey(autoGenerate = true) @ColumnInfo var id:Int = 0
)
</code>```

whenever i try to insert a row in to the TrackingItemData table, the row didnt get inserted, however the room returns a Long value,here is my dao

```<code>@Dao
interface TrackingItemDataDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertTrackingItemData(trackingItemData:TrackingItemData): Single<Long>

    @Query("SELECT * FROM TrackingItemDataTable")
    fun getAllTrackingItems():LiveData<List<TrackingItemData>>

}
</code>```

and i insert the data like this

```<code>Db.analyticsDao().insertTrackingItemData(
    TrackingItemData(ProductAnalyticsUrl = url,
        Price = currentPrice,
        Date = currentTime))
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({
        Log.d("shopzy", it.toString())
    },{
        Log.d("shopzy", it.toString())
    })
</code>```

the throwable of rx java didnt catch any exceptions, the code print the long value, but when i download the db from emulator and see the table i dont find a row in it, and getAllTrackingItems() from the dao returns 0 rows, what have i done wrong?

答: For some weird reason removing  tableName = "TrackingItemDataTable" from the second entity class solved the problem, not sure why it did</p>

Body:
i have two entity class

@Entity(tableName = "TrackingItemTable")
data class TrackingItem(
                        @ColumnInfo val ProductName:String,
                        @ColumnInfo val ProductPrice:Float,
                        @ColumnInfo val ProductImage:String,
                        @ColumnInfo val ProductCurrencySymbol:String,
                        @ColumnInfo val ProductAddedDate: Date,
                        @ColumnInfo val ProductSiteName:String,
                        @PrimaryKey @ColumnInfo val ProductUrl:String,
                        @ColumnInfo val ProductAffiliateUrl:String,
                        @ColumnInfo var ProductNotificationPrice:Float? = null,
                        @ColumnInfo var ProductLastUpdatedPrice:Float
)

and it has an foregin key relationship with the other entity

@Entity(foreignKeys = arrayOf(ForeignKey(entity = TrackingItem::class,
    parentColumns = arrayOf("ProductUrl"),
    childColumns = arrayOf("ProductAnalyticsUrl"),
    onDelete = ForeignKey.CASCADE)), tableName = "TrackingItemDataTable")

data class TrackingItemData(@ColumnInfo val ProductAnalyticsUrl:String,
                            @ColumnInfo val Price:Float,
                            @ColumnInfo val Date: Long,
                            @PrimaryKey(autoGenerate = true) @ColumnInfo var id:Int = 0
)

whenever i try to insert a row in to the TrackingItemData table, the row didnt get inserted, however the room returns a Long value,here is my dao

@Dao
interface TrackingItemDataDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertTrackingItemData(trackingItemData:TrackingItemData): Single<Long>

    @Query("SELECT * FROM TrackingItemDataTable")
    fun getAllTrackingItems():LiveData<List<TrackingItemData>>

}

and i insert the data like this

Db.analyticsDao().insertTrackingItemData(
    TrackingItemData(ProductAnalyticsUrl = url,
        Price = currentPrice,
        Date = currentTime))
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({
        Log.d("shopzy", it.toString())
    },{
        Log.d("shopzy", it.toString())
    })

the throwable of rx java didnt catch any exceptions, the code print the long value, but when i download the db from emulator and see the table i dont find a row in it, and getAllTrackingItems() from the dao returns 0 rows, what have i done wrong?


答:
If you really need to use a global variable then following is a better way to declare global names

```<code>global names

def cp_identifier():
    #global names
    names = []
    array_dec()
    print(names)

def array_dec():
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')
        for row in card_list_table:
            names.append(row["Card Name"])
</code>```

Title: How to access global variable

Body:
From the following code, I wish for the output of names to contain an array of names taken from a column in a csv file. When the function is run, the array remains empty. Why?

def cp_identifier():
    global names
    names = []
    array_dec()
    print(names)

def array_dec():
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')
        for row in card_list_table:
            names.append(row["Card Name"])

Current Output:

[]

Expected output:

['Card Name', 'Card Name', ... , 'Card Name']

Body:
If you really need to use a global variable then following is a better way to declare global names

global names

def cp_identifier():
    #global names
    names = []
    array_dec()
    print(names)

def array_dec():
    with open("card_list_currents.csv", "r") as file:
        card_list_table = csv.DictReader(file, delimiter=',')
        for row in card_list_table:
            names.append(row["Card Name"])


问:
String split with Dot character not working
I have a simple string with the value "45.7961887"

I want split this variable using the "." as separator.

But when split, the string array result is empty.

Image with the value:
Image with the string value

Now, with the split:
Image with the split

答: Did you escape the dot? string.split("\\.") or string.split("[.]")


问:
php variable scope
i'm confused about the php variable scope.
such as:

```<code>while(true){
    $var = "yes , it is a test!";
  }
  printf($var)
</code>```

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .

答: while is not a function. scope of variable refers to variable inside functions and classes

Title: php variable scope

Body:
i'm confused about the php variable scope.
such as:

while(true){
    $var = "yes , it is a test!";
  }
  printf($var)

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .


问:
Issue with some strings in Localizable.strings
I am facing a problem with some strings in Localizable.strings.

I created the files for the base language and the translations, I added the first keys and it worked like a charm. Later though, I made some additions in the code and I added some new keys with their respective translations. However when running the app on the simulator, instead of the text, only the keys appeared, no translation there (only for the new keys that I added, the old ones worked just fine).

I cleaned the project, I uninstalled the app, I reset the simulator: nothing worked.

At some point I moved the added keys at the top of the Localizable.strings file and it worked.

Has anybody else faced the same issue? Is there something I could do besides moving the new keys at the top in order to work?

答:
I had exactly the same issue with an Arabic .strings file, was driving me crazy because checking the structure using plutil -lint Localizable.strings was succeeding.

Then I discovered after trial and error there was a line with a weird invisible character that apparently was causing the following lines to be ignored.

After I removed that hidden character, worked fine.


问:
Create criteria from sub query
I am trying to convert my query to Criteria where I am facing issues. Below is the query which I am trying to convert

```<code>SELECT
    machine_type_id,
    machine_type,
    user_name
FROM
    nc_machine_types
WHERE
    CASE
        WHEN
            TRIM(':q') = ''
                OR ':q' IS NULL
        THEN
            machine_type IS NOT NULL
        ELSE (machine_type = ':q'
            OR machine_type_id = (SELECT
                machine_type_id
            FROM
                nc_machine_screen
            WHERE
                machine_no = ':q'))
    END
</code>```

The predicate I can convert now is

```<code>return new Specification<MachineType>() {
        @Override
        public Predicate toPredicate(Root<MachineType> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<>();

            if(!StringUtils.isBlank(q)) {

                Subquery<Long> ordersSubquery = query.subquery(Long.class);
                    Root rootB = ordersSubquery.from(Mahine.class);

         ordersSubquery.select(rootB.get("machineType").get("machineTypeId"));
                        ordersSubquery.where(cb.equal(rootB.get("machineNo"), q));

                        predicates.add(cb.equal(root.get("machineType"), q));
                cb.or(cb.equal(root.get("machineId"), ordersSubquery));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        }
};
</code>```

The query which is getting constructed is like

```<code>select machine_type_id, user_name, machine_type from machine_types where machine_type=?
</code>```

The OR clause is not coming in the query. How can I add it in the query?

答:
I got the answer. I can simply remove

```<code>predicates.add(cb.equal(root.get("machineType"), q));
cb.or(cb.equal(root.get("machineId"), ordersSubquery));
</code>```

and add

```<code>cb.or(cb.equal(root.get("machineType"), q), cb.equal(root.get("machineId"), ordersSubquery));
</code>```

Title: Create criteria from sub query

Body:
I am trying to convert my query to Criteria where I am facing issues. Below is the query which I am trying to convert

SELECT
    machine_type_id,
    machine_type,
    user_name
FROM
    nc_machine_types
WHERE
    CASE
        WHEN
            TRIM(':q') = ''
                OR ':q' IS NULL
        THEN
            machine_type IS NOT NULL
        ELSE (machine_type = ':q'
            OR machine_type_id = (SELECT
                machine_type_id
            FROM
                nc_machine_screen
            WHERE
                machine_no = ':q'))
    END

The predicate I can convert now is

return new Specification<MachineType>() {
        @Override
        public Predicate toPredicate(Root<MachineType> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<>();

            if(!StringUtils.isBlank(q)) {

                Subquery<Long> ordersSubquery = query.subquery(Long.class);
                    Root rootB = ordersSubquery.from(Mahine.class);

         ordersSubquery.select(rootB.get("machineType").get("machineTypeId"));
                        ordersSubquery.where(cb.equal(rootB.get("machineNo"), q));

                        predicates.add(cb.equal(root.get("machineType"), q));
                cb.or(cb.equal(root.get("machineId"), ordersSubquery));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        }
};

The query which is getting constructed is like

select machine_type_id, user_name, machine_type from machine_types where machine_type=?

The OR clause is not coming in the query. How can I add it in the query?

Body:
I got the answer. I can simply remove

predicates.add(cb.equal(root.get("machineType"), q));
cb.or(cb.equal(root.get("machineId"), ordersSubquery));

and add

cb.or(cb.equal(root.get("machineType"), q), cb.equal(root.get("machineId"), ordersSubquery));


问:
Is it possible to return a NULL value over Response.Write?
```<code>context.Response.ContentType = "text/plain";
context.Response.Write(returnString);
</code>```

If returnString is NULL what will it pass, or will it fail?

EDIT: The question was if it is possible, the above was just an example which I realize I could have tested. However I am looking for any other possible ways to do this beyond just my code example, I just couldn't think of anything else to write in the body text without repeating information that is already in the question title.

答:
While I agree with the sentiment of others in that it probably would have been pretty easy to test this rather than to ask the question...  But, since you asked, here is a code sample for you.  The result of the code was no text being displayed on the screen.</p>

```<code>    protected void Page_Load(object sender, EventArgs e)
    {
        string myString = null;
        Response.ContentType = "text/plain";
        Response.Write(myString);
        Response.End();
    }
</code>```

OwnerDisplayName: Ryan

ContentLicense: CC BY-SA 2.5

Body:
context.Response.ContentType = "text/plain";
context.Response.Write(returnString);

If returnString is NULL what will it pass, or will it fail?

EDIT: The question was if it is possible, the above was just an example which I realize I could have tested. However I am looking for any other possible ways to do this beyond just my code example, I just couldn't think of anything else to write in the body text without repeating information that is already in the question title.

LastEditorDisplayName: Ryan

Body:
While I agree with the sentiment of others in that it probably would have been pretty easy to test this rather than to ask the question...  But, since you asked, here is a code sample for you.  The result of the code was no text being displayed on the screen.

    protected void Page_Load(object sender, EventArgs e)
    {
        string myString = null;
        Response.ContentType = "text/plain";
        Response.Write(myString);
        Response.End();
    }

OwnerDisplayName: Russell Solberg


问:
Calling Card Integration in iPhone
I need to develop an application to integrate calling card functionality. The application will have an access number, a country code and a pin number setting.

When a user wants to make a call the system should dial the access number and then after a time interval it should dial the country code and finally pin number followed by the actual telephone number.

How would one implement this?

答:
Might work, haven't tried it. Won't work in simulator. Real answer s/b close

```<code>UIApplication *app = [UIApplication sharedApplication];
NSString *urlString = [NSString stringWithFormat:@"te1://12125551212,,,%@,,,%@", numLang, numPin];
NSURL *url = [NSURL URLWithString:urlString];
[app openURL:url];
</code>```

Comma are pauses.

Title: Calling Card Integration in iPhone

Body:
Might work, haven't tried it. Won't work in simulator. Real answer s/b close

UIApplication *app = [UIApplication sharedApplication];
NSString *urlString = [NSString stringWithFormat:@"te1://12125551212,,,%@,,,%@", numLang, numPin];
NSURL *url = [NSURL URLWithString:urlString];
[app openURL:url];

Comma are pauses.


问:
How could I use regular expression to split Chinese characters at right position?
I want to split specific Chinese characters in some lines. Actually, it worked, but the position of the split character was wrong. How could I split it at right position?

I split Chinese characters by regular expression in python 3.6

```<code>str = '我到家'
pattern = '([\u4e00-\u9fa5]?(?:到))'
compiled_pattern = re.compile(pattern)
new_str = re.split(compiled_pattern, str)
print(new_str)
</code>```

The output by my code is

```<code>['', '我到', '家']
</code>```

But what I want is

```<code>['我', '到', '家']
</code>```

How could I fix it and spit the character at right position?

答:
Just do like this

```<code>list(str)
</code>```

I tried it, and output is the same as you want

```<code>['我', '到', '家']
</code>```

Body:
I want to split specific Chinese characters in some lines. Actually, it worked, but the position of the split character was wrong. How could I split it at right position?

I split Chinese characters by regular expression in python 3.6

str = '我到家'
pattern = '([\u4e00-\u9fa5]?(?:到))'
compiled_pattern = re.compile(pattern)
new_str = re.split(compiled_pattern, str)
print(new_str)

The output by my code is

['', '我到', '家']

But what I want is

['我', '到', '家']

How could I fix it and spit the character at right position?

Body:
Just do like this

list(str)

I tried it, and output is the same as you want

['我', '到', '家']


问:
PayPal Payouts via W3C Web Payments API
PayPal provide payout payment functionality to their merchants/customers via a native bespoke API. Is there anyway other than this feature request to surface the functionality via the Web Payments API?</p>

答:
Great news!

@adrianhopebailie has detailed a solution right here right now for Web Payment Disbursement functionality that requires no (absolutely ZERO) changes to the Payment Request OR Payment Handler APIs and W3C standards! (Always a bonus :-)

As he correctly points out, the methodData argument is opaque and pretty much down to the autonomous Payment Handler to specify. So Stripe, Square, and PayPal are free to specify to their customers the format/naming-convention for communicating Application Fees between Web App supplier and Stripe.

To quote Adrian's example: -

```<code>const methodData = [
  {
    supportedMethods: "https://square.com/",
    data: {
      parties: [{
        merchantId: "super-mini-cabs",
        portion: 0.1
      },{
        merchantId: "driver-fred",
        portion: 0.9
      }],
    },
  },
  {
    supportedMethods: "https://stripe.com",
    data: {
      application_fee_amount: 1.00,
    },
  },
  {
    supportedMethods: "https://paypal.com",
    data: {
      payouts: [{
        paypalId: 12478764,
        amount: 1.00
      },{
        paypalId: 23448764,
        amount: 9.00
      }],
    },
  },
];
</code>```

Just tell us PayPal what you need us to tell you and it's done!

Title: PayPal Payouts via W3C Web Payments API

Body:
Great news!

@adrianhopebailie has detailed a solution right here right now for Web Payment Disbursement functionality that requires no (absolutely ZERO) changes to the Payment Request OR Payment Handler APIs and W3C standards! (Always a bonus :-)

As he correctly points out, the methodData argument is opaque and pretty much down to the autonomous Payment Handler to specify. So Stripe, Square, and PayPal are free to specify to their customers the format/naming-convention for communicating Application Fees between Web App supplier and Stripe.

To quote Adrian's example: -

const methodData = [
  {
    supportedMethods: "https://square.com/",
    data: {
      parties: [{
        merchantId: "super-mini-cabs",
        portion: 0.1
      },{
        merchantId: "driver-fred",
        portion: 0.9
      }],
    },
  },
  {
    supportedMethods: "https://stripe.com",
    data: {
      application_fee_amount: 1.00,
    },
  },
  {
    supportedMethods: "https://paypal.com",
    data: {
      payouts: [{
        paypalId: 12478764,
        amount: 1.00
      },{
        paypalId: 23448764,
        amount: 9.00
      }],
    },
  },
];

Just tell us PayPal what you need us to tell you and it's done!


问:
C# Async Await and general async question
I am trying to understand something about async programming in general.
In C# it seems that everyone is now using async await syntatic sugar for async operations that are IO bound.

My question is: Does any operation that is IO bound like a file reading, http request etc that was sync until now can become asnync by writting a wrapper function that is async?

Or since the underlying "old" implementation if it is sync will not help at all?
will the thread that used to wait until now will be released or not?

Anyone?

答:
Yes, your sync function can become async, for example in HTTP Request you can change your Sync function

```<code>public static Task<HttpResponseMessage> GetRequest(string requestUri, Dictionary<string, string> requestHeaders)
    {
        return HttpRequestFactory.Get(requestUri, requestHeaders);
    }
</code>```

Calling function

```<code>var result =  HttpClient.GetRequest(requestUri, _request, _requestHeaders)
</code>```

you will change this into async like this

```<code>public static async Task<HttpResponseMessage> GetRequest(string requestUri, Dictionary<string, string> requestHeaders)
   {
            return await HttpRequestFactory.Get(requestUri, requestHeaders);
   }
</code>```

calling function to

```<code>var result = HttpClient.GetRequest(requestUri, _request, _requestHeaders).Result;
</code>```

Hope so this will help to you..

Body:
Yes, your sync function can become async, for example in HTTP Request you can change your Sync function

public static Task<HttpResponseMessage> GetRequest(string requestUri, Dictionary<string, string> requestHeaders)
    {
        return HttpRequestFactory.Get(requestUri, requestHeaders);
    }

Calling function

var result =  HttpClient.GetRequest(requestUri, _request, _requestHeaders)

you will change this into async like this

public static async Task<HttpResponseMessage> GetRequest(string requestUri, Dictionary<string, string> requestHeaders)
   {
            return await HttpRequestFactory.Get(requestUri, requestHeaders);
   }

calling function to

var result = HttpClient.GetRequest(requestUri, _request, _requestHeaders).Result;

Hope so this will help to you..


问:
absolute positioned child div width, getting out of relative positioned container
I know it's very common question but could find the solution!
A div which has position: relative and a div inside it has position: absolute and width: 100% just overflowing it's parent. I don't know what's I'm missing.

what I have:

```<code>.parent-div {
  position: relative;
  overflow: hidden;
}

.child-div {
  position: absolute;
  width: 100%
  max-width: 100%;
  box-sizing: border-box;
}
</code>```

Note: here parent div is bootstrap list-group-item element

Any help would be appreciable. Thanks!

UPDATE:

Issue has been resolved! It's because of that bootstrap group. So, I've took another wrapper and let it's position relative and it's now working perfectly!

答:
Have you tried box-sizing: border-box; it Include padding and border in the element's total width and height:

https://www.w3schools.com/cssref/css3_pr_box-sizing.asp

Body:
I know it's very common question but could find the solution!
A div which has position: relative and a div inside it has position: absolute and width: 100% just overflowing it's parent. I don't know what's I'm missing.

what I have:

.parent-div {
  position: relative;
  overflow: hidden;
}

.child-div {
  position: absolute;
  width: 100%
  max-width: 100%;
  box-sizing: border-box;
}

Note: here parent div is bootstrap list-group-item element

Any help would be appreciable. Thanks!

UPDATE:

Issue has been resolved! It's because of that bootstrap group. So, I've took another wrapper and let it's position relative and it's now working perfectly!


问:
How to obtain sheet names from XLS files without loading the whole file?
I'm currently using pandas to read an Excel file and present its sheet names to the user, so he can select which sheet he would like to use. The problem is that the files are really big (70 columns x 65k rows), taking up to 14s to load on a notebook (the same data in a CSV file is taking 3s).

My code in panda goes like this:

```<code>xls = pandas.ExcelFile(path)
sheets = xls.sheet_names
</code>```

I tried xlrd before, but obtained similar results. This was my code with xlrd:

```<code>xls = xlrd.open_workbook(path)
sheets = xls.sheet_names
</code>```

So, can anybody suggest a faster way to retrieve the sheet names from an Excel file than reading the whole file?

答:
I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. The following function works for xlsx files.

```<code>def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['sheetId'], # can be @sheetId for some versions
                'name': sheet['name'] # can be @name
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets
</code>```

Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.

Benchmarking: (On a 6mb xlsx file with 4 sheets)

Pandas, xlrd: 12 seconds

openpyxl: 24 seconds

Proposed method: 0.4 seconds

Body:
I'm currently using pandas to read an Excel file and present its sheet names to the user, so he can select which sheet he would like to use. The problem is that the files are really big (70 columns x 65k rows), taking up to 14s to load on a notebook (the same data in a CSV file is taking 3s).

My code in panda goes like this:

xls = pandas.ExcelFile(path)
sheets = xls.sheet_names

I tried xlrd before, but obtained similar results. This was my code with xlrd:

xls = xlrd.open_workbook(path)
sheets = xls.sheet_names

So, can anybody suggest a faster way to retrieve the sheet names from an Excel file than reading the whole file?

Body:
I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. The following function works for xlsx files.

def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['sheetId'], # can be @sheetId for some versions
                'name': sheet['name'] # can be @name
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets

Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.

Benchmarking: (On a 6mb xlsx file with 4 sheets)

Pandas, xlrd: 12 seconds

openpyxl: 24 seconds

Proposed method: 0.4 seconds


问:
Google Sheets - Trouble importing XML on particular page
Attempting to use ImportXML in Google Sheets to retrieve a specific piece of text but am having trouble after searching my ass off for answers.

Hoping someone here can help correct the problem.

The page is: https://www.afi.com.au
And the text I'm wanting to import is in the pink box:

Here's where I'm at with the code, I've attempted to retrieve the XPath but it doesn't like what I have, I'm sure someone here will spot the prob in a heartbeat...

```<code>=IMPORTXML("http://www.afi.com.au","//body[@class='entry-homepage type-homepage']/div[@class='page page-home']/div[@class='page__item']/div[@class='js-evo7-component']/div[@class='hero']/div[@class='hero__inner-root rellax']/div[@class='hero__inner']/div[@class='container']/div[@class='grid']/div[@class='grid__item one-third palm-one-whole']/div[@class='hero__share-price']/div[@class='price-number']//text()")
</code>```

答:
How about this workaround? In this workaround, the data is retrieved using a xpath, and the value is retrieved using a regular expression. It seems that the retrieved data is updated when the page is retrieved. So I used this method. The modified formula is as follows. Please think of this as just one of several answers.

Sample formula:

In this sample formula, http://www.afi.com.au is put in the cell "A1".

```<code>=REGEXEXTRACT(IMPORTXML(A1,"//div[@class='js-evo7-component']/@data-config"),"netAssetBacking"":{""price"":""([\d.]+)")
</code>```

Retrieve data using the xpath of //div[@class='js-evo7-component']/@data-config with IMPORTXML().

Retrieve the value using the regular expression of netAssetBacking"":{""price"":""([\d.]+) with REGEXEXTRACT().

Result:

References:

IMPORTXML

REGEXEXTRACT

Body:
Attempting to use ImportXML in Google Sheets to retrieve a specific piece of text but am having trouble after searching my ass off for answers.

Hoping someone here can help correct the problem.

The page is: https://www.afi.com.au
And the text I'm wanting to import is in the pink box:

Here's where I'm at with the code, I've attempted to retrieve the XPath but it doesn't like what I have, I'm sure someone here will spot the prob in a heartbeat...

=IMPORTXML("http://www.afi.com.au","//body[@class='entry-homepage type-homepage']/div[@class='page page-home']/div[@class='page__item']/div[@class='js-evo7-component']/div[@class='hero']/div[@class='hero__inner-root rellax']/div[@class='hero__inner']/div[@class='container']/div[@class='grid']/div[@class='grid__item one-third palm-one-whole']/div[@class='hero__share-price']/div[@class='price-number']//text()")

Body:
How about this workaround? In this workaround, the data is retrieved using a xpath, and the value is retrieved using a regular expression. It seems that the retrieved data is updated when the page is retrieved. So I used this method. The modified formula is as follows. Please think of this as just one of several answers.

Sample formula:

In this sample formula, http://www.afi.com.au is put in the cell "A1".

=REGEXEXTRACT(IMPORTXML(A1,"//div[@class='js-evo7-component']/@data-config"),"netAssetBacking"":{""price"":""([\d.]+)")

Retrieve data using the xpath of //div[@class='js-evo7-component']/@data-config with IMPORTXML().

Retrieve the value using the regular expression of netAssetBacking"":{""price"":""([\d.]+) with REGEXEXTRACT().

Result:

References:

IMPORTXML

REGEXEXTRACT


问:
I use name data to result code,Sql update question

Update x1 a set a.dept_cd=(select distinct dept_cd from x2 b a.nm=b.nm)
```

It's my sql
Distinct make data unique, but  it result in an error message,

row subquery returns more than one row

My data is string
So i use name to return code(dept_cd)
Can you help me?

答:
If this query return that error, it means that you have more than one dept_cd where nm is equal to the one you are looking for.

The goal of distinct is to avoid having twice the same value of dept_cd.

If you need one the first one no matter what the value is, you can add limit 0,1 ad the end of your subquery.

If the value you need is a specific one, you need to find a way to update your query to isolate it but without having the full context, we cannot help you on that.

Body:
Update x1 a set a.dept_cd=(select distinct dept_cd from x2 b a.nm=b.nm)

It's my sql
Distinct make data unique, but  it result in an error message,

row subquery returns more than one row

My data is string
So i use name to return code(dept_cd)
Can you help me?


问:
converting array to object where array values are the object keys and object values are empty
I'm working on a reactjs web app I have an array like

```<code>let arr = ["name","message", etc...];
</code>```

I want to convert it to object but to look like

```<code>let desired = { name:'', message:'' };
</code>```

I tried a few things but none of them worked.

答:
If you just want to assign each value in the array the value of an empty string, use reduce:

let arr = ["name","message", "etc"];
let desired = arr.reduce((acc, curr) => (acc[curr] = "", acc), {});
console.log(desired);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

ES5 syntax:

var arr = ["name","message", "etc"];
var desired = arr.reduce(function(acc, curr) {
  acc[curr] = "";
  return acc;
}, {});
console.log(desired);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Body:
I'm working on a reactjs web app I have an array like

let arr = ["name","message", etc...];

I want to convert it to object but to look like

let desired = { name:'', message:'' };

I tried a few things but none of them worked.

Body:
If you just want to assign each value in the array the value of an empty string, use reduce:

let arr = ["name","message", "etc"];
let desired = arr.reduce((acc, curr) => (acc[curr] = "", acc), {});
console.log(desired);

.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5 syntax:

var arr = ["name","message", "etc"];
var desired = arr.reduce(function(acc, curr) {
  acc[curr] = "";
  return acc;
}, {});
console.log(desired);

.as-console-wrapper { max-height: 100% !important; top: auto; }


问:
How to check if all array values are blank in Javascript
I have an array like:

```<code>["", "", "", "1", "", ""]
</code>```

I want to alert when all the array values are blanks, i.e, when the array is like this:

```<code>["", "", "", "", "", ""]
</code>```

How can I achieve this.

答:
Here is also a more generic approach which would compact the array removing all falsey values and then check the remaining length:

let compact = a => a.reduce((r,c) => (!!c ? r.push(c) : null, r),[])

let isEmpty = array => compact(array).length == 0

console.log(isEmpty(["", false, 0, "", null, undefined])) // true
console.log(isEmpty(["", 1]))   // false
console.log(isEmpty(["", []]))  // false
console.log(isEmpty(["", {}]))  // false```
</div>
</div>
</p>

<p>But if this is the only use case you care about then you can also use  Array.some: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let isEmpty = a => !a.some(x => x !== '')

// OR let isEmpty = a => !a.some(x => x.toString().length > 0)

console.log(isEmpty(["", "", "", "", "", ""]))
console.log(isEmpty(["", "", "1", "", "", ""]))</code>```

You could also use Array.reduce:

let isEmpty = a => !a.reduce((r,c) => `${r}${c}`).length

console.log(isEmpty(["", "", "", "", "", ""]))
console.log(isEmpty(["", "", "1", "", "", ""]))```
</div>
</div>
</p>

<p>Array.filter:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let isEmpty = a => !a.filter(x => x.toString().length).length

console.log(isEmpty(["", "", "", "", "", ""]))
console.log(isEmpty(["", "", "1", "", "", ""]))</code>```

This will only be valid check against your current input however. Not against cases with arrays, object literals etc as part of your input array.

If you are using lodash this could be (via _.every and _.isEmpty):

let isArrayEmpty = a => _.every(a, _.isEmpty)

console.log(isArrayEmpty(["", "", "", "", "", ""]))
console.log(isArrayEmpty(["", "", "1", "", "", ""]))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

or also via _.compact which also removes falsey values:

let isArrayEmpty = a => !_.compact(a).length

console.log(isArrayEmpty(["", "", "", "", "", ""]))
console.log(isArrayEmpty(["", "", "1", "", "", ""]))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

Body:
I have an array like:

["", "", "", "1", "", ""]

I want to alert when all the array values are blanks, i.e, when the array is like this:

["", "", "", "", "", ""]

How can I achieve this.

Body:
Here is also a more generic approach which would compact the array removing all falsey values and then check the remaining length:

let compact = a => a.reduce((r,c) => (!!c ? r.push(c) : null, r),[])

let isEmpty = array => compact(array).length == 0

console.log(isEmpty(["", false, 0, "", null, undefined])) // true
console.log(isEmpty(["", 1]))   // false
console.log(isEmpty(["", []]))  // false
console.log(isEmpty(["", {}]))  // false

But if this is the only use case you care about then you can also use  Array.some:

let isEmpty = a => !a.some(x => x !== '')

// OR let isEmpty = a => !a.some(x => x.toString().length > 0)

console.log(isEmpty(["", "", "", "", "", ""]))
console.log(isEmpty(["", "", "1", "", "", ""]))

You could also use Array.reduce:

let isEmpty = a => !a.reduce((r,c) => `${r}${c}`).length

console.log(isEmpty(["", "", "", "", "", ""]))
console.log(isEmpty(["", "", "1", "", "", ""]))

Array.filter:

let isEmpty = a => !a.filter(x => x.toString().length).length

console.log(isEmpty(["", "", "", "", "", ""]))
console.log(isEmpty(["", "", "1", "", "", ""]))

This will only be valid check against your current input however. Not against cases with arrays, object literals etc as part of your input array.

If you are using lodash this could be (via _.every and _.isEmpty):

let isArrayEmpty = a => _.every(a, _.isEmpty)

console.log(isArrayEmpty(["", "", "", "", "", ""]))
console.log(isArrayEmpty(["", "", "1", "", "", ""]))

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

or also via _.compact which also removes falsey values:

let isArrayEmpty = a => !_.compact(a).length

console.log(isArrayEmpty(["", "", "", "", "", ""]))
console.log(isArrayEmpty(["", "", "1", "", "", ""]))

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>